diff --git a/Conf/task.yaml b/Conf/task.yaml index 8f8eaceb54..15b7581266 100644 --- a/Conf/task.yaml +++ b/Conf/task.yaml @@ -452,6 +452,7 @@ Problem of Apollonius: Program name: Program termination: Pythagorean triples: + QR decomposition: Quaternion type: Queue/Definition: @@ -498,6 +499,7 @@ Rot-13: Run-length encoding: Runtime evaluation: Runtime evaluation/In an environment: + S-Expressions: Safe addition: Same Fringe: @@ -515,3 +517,177 @@ Sequence of non-squares: Set: Set consolidation: Set of real numbers: +Set puzzle: +Seven-sided dice from five-sided dice: +SHA-1: +SHA-256: +Shell one-liner: +Short-circuit evaluation: +Show the epoch: +Sierpinski carpet: +Sierpinski triangle: +Sierpinski triangle/Graphical: +Sieve of Eratosthenes: +Simple database: +Simple windowed application: +Simulate input/Keyboard: +Simulate input/Mouse: +Singleton: +Singly-linked list/Element definition: +Singly-linked list/Element insertion: +Singly-linked list/Traversal: +Sleep: +SOAP: +Sockets: +Sokoban: +Solve a Hidato puzzle: +Sort an array of composite structures: +Sort an integer array: +Sort disjoint sublist: +Sort stability: +Sort using a custom comparator: +Sorting algorithms/Bead sort: +Sorting algorithms/Bogosort: +Sorting algorithms/Bubble sort: +Sorting algorithms/Cocktail sort: +Sorting algorithms/Comb sort: +Sorting algorithms/Counting sort: +Sorting algorithms/Gnome sort: +Sorting algorithms/Heapsort: +Sorting algorithms/Insertion sort: +Sorting algorithms/Merge sort: +Sorting algorithms/Pancake sort: +Sorting algorithms/Permutation sort: +Sorting algorithms/Quicksort: +Sorting algorithms/Radix sort: +Sorting algorithms/Selection sort: +Sorting algorithms/Shell sort: +Sorting algorithms/Sleep sort: +Sorting algorithms/Stooge sort: +Sorting algorithms/Strand sort: +Soundex: +Special characters: +Special variables: +Speech synthesis: +Spiral matrix: +SQL-based authentication: +Stable marriage problem: +Stack: +Stack traces: +Stair-climbing puzzle: +Standard deviation: +Start from a main routine: +Stem-and-leaf plot: +String case: +String comparison: +String concatenation: +String interpolation (included): +String length: +Strip a set of characters from a string: +Strip block comments: +Strip comments from a string: +Strip control codes and extended characters from a string: +Strip whitespace from a string/Top and tail: +Substring: +Substring/Top and tail: +Subtractive generator: +Sudoku: +Sum and product of an array: +Sum digits of an integer: +Sum of a series: +Sum of squares: +Sutherland-Hodgman polygon clipping: +Symmetric difference: +Synchronous concurrency: +System time: + +Table creation/Postal addresses: +Take notes on the command line: +Temperature conversion: +Terminal control/Clear the screen: +Terminal control/Coloured text: +Terminal control/Cursor movement: +Terminal control/Cursor positioning: +Terminal control/Dimensions: +Terminal control/Display an extended character: +Terminal control/Hiding the cursor: +Terminal control/Inverse video: +Terminal control/Positional read: +Terminal control/Preserve screen: +Terminal control/Ringing the terminal bell: +Terminal control/Unicode output: +Ternary logic: +Test a function: +Text processing/1: +Text processing/2: +Text processing/Max licenses in use: +Thiele's interpolation formula: #' +Tic-tac-toe: +Time a function: +Tokenize a string: +Top rank per group: +Topic variable: +Topological sort: +Topswops: +Towers of Hanoi: +Trabb Pardo–Knuth algorithm: +Tree traversal: +Trigonometric functions: +Truncatable primes: +Truncate a file: +Twelve statements: + +Unbias a random generator: +Undefined values: +Unicode strings: +Unicode variable names: +Universal Turing machine: +Update a configuration file: +URL decoding: +URL encoding: +Use another language to call a function: +User input/Graphical: +User input/Text: + +Vampire number: +Van der Corput sequence: +Variable size/Get: +Variable size/Set: +Variable-length quantity: +Variables: +Variadic function: +Vector products: +Verify distribution uniformity/Chi-squared test: +Verify distribution uniformity/Naive: +Video display modes: +Vigenère cipher: +Vigenère cipher/Cryptanalysis: +Visualize a tree: +Voronoi diagram: + +Walk a directory/Non-recursively: +Walk a directory/Recursively: +Web scraping: +Window creation: +Window creation/X11: +Window management: +Wireworld: +Word wrap: +Write float arrays to a text file: +Write language name in 3D ASCII: +Write to Windows event log: + +Xiaolin Wu's line algorithm: #' +XML/DOM serialization: +XML/Input: +XML/Output: +XML/XPath: + +Y combinator: +Yahoo! search interface: +Yin and yang: + +Zebra puzzle: +Zeckendorf arithmetic: +Zeckendorf number representation: +Zig-zag matrix: diff --git a/Lang/4D/Sort-an-integer-array b/Lang/4D/Sort-an-integer-array new file mode 120000 index 0000000000..ba4ddddd4e --- /dev/null +++ b/Lang/4D/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/4D \ No newline at end of file diff --git a/Lang/4D/String-case b/Lang/4D/String-case new file mode 120000 index 0000000000..4731ad4002 --- /dev/null +++ b/Lang/4D/String-case @@ -0,0 +1 @@ +../../Task/String-case/4D \ No newline at end of file diff --git a/Lang/4D/String-length b/Lang/4D/String-length new file mode 120000 index 0000000000..54f5064a37 --- /dev/null +++ b/Lang/4D/String-length @@ -0,0 +1 @@ +../../Task/String-length/4D \ No newline at end of file diff --git a/Lang/4D/Sum-and-product-of-an-array b/Lang/4D/Sum-and-product-of-an-array new file mode 120000 index 0000000000..52c6e2fabe --- /dev/null +++ b/Lang/4D/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/4D \ No newline at end of file diff --git a/Lang/6502-Assembly/String-case b/Lang/6502-Assembly/String-case new file mode 120000 index 0000000000..0b7e94c747 --- /dev/null +++ b/Lang/6502-Assembly/String-case @@ -0,0 +1 @@ +../../Task/String-case/6502-Assembly \ No newline at end of file diff --git a/Lang/6800-Assembly/Terminal-control-Ringing-the-terminal-bell b/Lang/6800-Assembly/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c2fd67e7ba --- /dev/null +++ b/Lang/6800-Assembly/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly \ No newline at end of file diff --git a/Lang/ACL2/Shell-one-liner b/Lang/ACL2/Shell-one-liner new file mode 120000 index 0000000000..a271ffdfab --- /dev/null +++ b/Lang/ACL2/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sierpinski-triangle b/Lang/ACL2/Sierpinski-triangle new file mode 120000 index 0000000000..81f2d269be --- /dev/null +++ b/Lang/ACL2/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sieve-of-Eratosthenes b/Lang/ACL2/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c1c74314d2 --- /dev/null +++ b/Lang/ACL2/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Singly-linked-list-Element-definition b/Lang/ACL2/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..e080a012c0 --- /dev/null +++ b/Lang/ACL2/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Singly-linked-list-Element-insertion b/Lang/ACL2/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..b4c00d61e0 --- /dev/null +++ b/Lang/ACL2/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Singly-linked-list-Traversal b/Lang/ACL2/Singly-linked-list-Traversal new file mode 120000 index 0000000000..46a80dee56 --- /dev/null +++ b/Lang/ACL2/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sort-an-array-of-composite-structures b/Lang/ACL2/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..69e0a8f6ba --- /dev/null +++ b/Lang/ACL2/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sorting-algorithms-Bubble-sort b/Lang/ACL2/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1c3c761989 --- /dev/null +++ b/Lang/ACL2/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sorting-algorithms-Insertion-sort b/Lang/ACL2/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..c12e6b2c24 --- /dev/null +++ b/Lang/ACL2/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sorting-algorithms-Merge-sort b/Lang/ACL2/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..eb06e2781a --- /dev/null +++ b/Lang/ACL2/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sorting-algorithms-Quicksort b/Lang/ACL2/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..107da487c3 --- /dev/null +++ b/Lang/ACL2/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Stem-and-leaf-plot b/Lang/ACL2/Stem-and-leaf-plot new file mode 120000 index 0000000000..cdfe9f9648 --- /dev/null +++ b/Lang/ACL2/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Substring-Top-and-tail b/Lang/ACL2/Substring-Top-and-tail new file mode 120000 index 0000000000..d9f94f4672 --- /dev/null +++ b/Lang/ACL2/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sum-and-product-of-an-array b/Lang/ACL2/Sum-and-product-of-an-array new file mode 120000 index 0000000000..1b903077c3 --- /dev/null +++ b/Lang/ACL2/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sum-of-a-series b/Lang/ACL2/Sum-of-a-series new file mode 120000 index 0000000000..4686439fdc --- /dev/null +++ b/Lang/ACL2/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Sum-of-squares b/Lang/ACL2/Sum-of-squares new file mode 120000 index 0000000000..88b97475b4 --- /dev/null +++ b/Lang/ACL2/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Terminal-control-Display-an-extended-character b/Lang/ACL2/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..fefd34990a --- /dev/null +++ b/Lang/ACL2/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Test-a-function b/Lang/ACL2/Test-a-function new file mode 120000 index 0000000000..6eeb99b9ff --- /dev/null +++ b/Lang/ACL2/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Time-a-function b/Lang/ACL2/Time-a-function new file mode 120000 index 0000000000..4c8d621d4c --- /dev/null +++ b/Lang/ACL2/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Tokenize-a-string b/Lang/ACL2/Tokenize-a-string new file mode 120000 index 0000000000..d9ee49dd31 --- /dev/null +++ b/Lang/ACL2/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Tree-traversal b/Lang/ACL2/Tree-traversal new file mode 120000 index 0000000000..c28f768bc1 --- /dev/null +++ b/Lang/ACL2/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Trigonometric-functions b/Lang/ACL2/Trigonometric-functions new file mode 120000 index 0000000000..681a40fbbc --- /dev/null +++ b/Lang/ACL2/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Unicode-variable-names b/Lang/ACL2/Unicode-variable-names new file mode 120000 index 0000000000..90c87c5f8a --- /dev/null +++ b/Lang/ACL2/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/ACL2 \ No newline at end of file diff --git a/Lang/ACL2/Variadic-function b/Lang/ACL2/Variadic-function new file mode 120000 index 0000000000..6640988225 --- /dev/null +++ b/Lang/ACL2/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/ACL2 \ No newline at end of file diff --git a/Lang/ALGOL-60/Trabb-Pardo-Knuth-algorithm b/Lang/ALGOL-60/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..08fa155cc1 --- /dev/null +++ b/Lang/ALGOL-60/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/Seven-sided-dice-from-five-sided-dice b/Lang/ALGOL-68/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..232715ad02 --- /dev/null +++ b/Lang/ALGOL-68/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Shell-one-liner b/Lang/ALGOL-68/Shell-one-liner new file mode 120000 index 0000000000..7327ad9ae0 --- /dev/null +++ b/Lang/ALGOL-68/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Short-circuit-evaluation b/Lang/ALGOL-68/Short-circuit-evaluation new file mode 120000 index 0000000000..230ed78917 --- /dev/null +++ b/Lang/ALGOL-68/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sierpinski-carpet b/Lang/ALGOL-68/Sierpinski-carpet new file mode 120000 index 0000000000..1b77803c6a --- /dev/null +++ b/Lang/ALGOL-68/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sierpinski-triangle b/Lang/ALGOL-68/Sierpinski-triangle new file mode 120000 index 0000000000..de48e2ed94 --- /dev/null +++ b/Lang/ALGOL-68/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sieve-of-Eratosthenes b/Lang/ALGOL-68/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..77bcdddc17 --- /dev/null +++ b/Lang/ALGOL-68/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Singly-linked-list-Element-definition b/Lang/ALGOL-68/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..5999142d69 --- /dev/null +++ b/Lang/ALGOL-68/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Singly-linked-list-Element-insertion b/Lang/ALGOL-68/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..c7518f13e2 --- /dev/null +++ b/Lang/ALGOL-68/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Singly-linked-list-Traversal b/Lang/ALGOL-68/Singly-linked-list-Traversal new file mode 120000 index 0000000000..0a8e9c57c3 --- /dev/null +++ b/Lang/ALGOL-68/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sort-an-array-of-composite-structures b/Lang/ALGOL-68/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..d6de044ce1 --- /dev/null +++ b/Lang/ALGOL-68/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sort-an-integer-array b/Lang/ALGOL-68/Sort-an-integer-array new file mode 120000 index 0000000000..c36531d05f --- /dev/null +++ b/Lang/ALGOL-68/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Bogosort b/Lang/ALGOL-68/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..de7bc9d3bd --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Bubble-sort b/Lang/ALGOL-68/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..a8ea7267b4 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Cocktail-sort b/Lang/ALGOL-68/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..194d749910 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Counting-sort b/Lang/ALGOL-68/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..ca124b3064 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Gnome-sort b/Lang/ALGOL-68/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..35272fc4b8 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Insertion-sort b/Lang/ALGOL-68/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..7195c80261 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Merge-sort b/Lang/ALGOL-68/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..191fc18415 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Quicksort b/Lang/ALGOL-68/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..076770ce3a --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Selection-sort b/Lang/ALGOL-68/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..3c1f0aabec --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Shell-sort b/Lang/ALGOL-68/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..be5dfe9c89 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Soundex b/Lang/ALGOL-68/Soundex new file mode 120000 index 0000000000..479925597d --- /dev/null +++ b/Lang/ALGOL-68/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Special-characters b/Lang/ALGOL-68/Special-characters new file mode 120000 index 0000000000..f7b80a444d --- /dev/null +++ b/Lang/ALGOL-68/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Special-variables b/Lang/ALGOL-68/Special-variables new file mode 120000 index 0000000000..dca2b8fb0c --- /dev/null +++ b/Lang/ALGOL-68/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Spiral-matrix b/Lang/ALGOL-68/Spiral-matrix new file mode 120000 index 0000000000..76c8bd662f --- /dev/null +++ b/Lang/ALGOL-68/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Stack b/Lang/ALGOL-68/Stack new file mode 120000 index 0000000000..02054eb280 --- /dev/null +++ b/Lang/ALGOL-68/Stack @@ -0,0 +1 @@ +../../Task/Stack/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Stair-climbing-puzzle b/Lang/ALGOL-68/Stair-climbing-puzzle new file mode 120000 index 0000000000..d84a0dc569 --- /dev/null +++ b/Lang/ALGOL-68/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Standard-deviation b/Lang/ALGOL-68/Standard-deviation new file mode 120000 index 0000000000..e1f4b79efc --- /dev/null +++ b/Lang/ALGOL-68/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-case b/Lang/ALGOL-68/String-case new file mode 120000 index 0000000000..3edaf3ecd1 --- /dev/null +++ b/Lang/ALGOL-68/String-case @@ -0,0 +1 @@ +../../Task/String-case/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-concatenation b/Lang/ALGOL-68/String-concatenation new file mode 120000 index 0000000000..6274660aaa --- /dev/null +++ b/Lang/ALGOL-68/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-interpolation--included- b/Lang/ALGOL-68/String-interpolation--included- new file mode 120000 index 0000000000..4b47fed295 --- /dev/null +++ b/Lang/ALGOL-68/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/String-length b/Lang/ALGOL-68/String-length new file mode 120000 index 0000000000..f7c17b86e2 --- /dev/null +++ b/Lang/ALGOL-68/String-length @@ -0,0 +1 @@ +../../Task/String-length/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Strip-a-set-of-characters-from-a-string b/Lang/ALGOL-68/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..aa8eeb8d3c --- /dev/null +++ b/Lang/ALGOL-68/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Strip-comments-from-a-string b/Lang/ALGOL-68/Strip-comments-from-a-string new file mode 120000 index 0000000000..7ef5e71fdc --- /dev/null +++ b/Lang/ALGOL-68/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Substring b/Lang/ALGOL-68/Substring new file mode 120000 index 0000000000..e1e88b8524 --- /dev/null +++ b/Lang/ALGOL-68/Substring @@ -0,0 +1 @@ +../../Task/Substring/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Substring-Top-and-tail b/Lang/ALGOL-68/Substring-Top-and-tail new file mode 120000 index 0000000000..32c49a0935 --- /dev/null +++ b/Lang/ALGOL-68/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sudoku b/Lang/ALGOL-68/Sudoku new file mode 120000 index 0000000000..0f32edc301 --- /dev/null +++ b/Lang/ALGOL-68/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sum-and-product-of-an-array b/Lang/ALGOL-68/Sum-and-product-of-an-array new file mode 120000 index 0000000000..3b052db623 --- /dev/null +++ b/Lang/ALGOL-68/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sum-of-a-series b/Lang/ALGOL-68/Sum-of-a-series new file mode 120000 index 0000000000..8de36e0091 --- /dev/null +++ b/Lang/ALGOL-68/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sum-of-squares b/Lang/ALGOL-68/Sum-of-squares new file mode 120000 index 0000000000..507e45dc64 --- /dev/null +++ b/Lang/ALGOL-68/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Synchronous-concurrency b/Lang/ALGOL-68/Synchronous-concurrency new file mode 120000 index 0000000000..a375a54774 --- /dev/null +++ b/Lang/ALGOL-68/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/System-time b/Lang/ALGOL-68/System-time new file mode 120000 index 0000000000..3250c399b9 --- /dev/null +++ b/Lang/ALGOL-68/System-time @@ -0,0 +1 @@ +../../Task/System-time/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Table-creation-Postal-addresses b/Lang/ALGOL-68/Table-creation-Postal-addresses new file mode 120000 index 0000000000..7b0f6b7159 --- /dev/null +++ b/Lang/ALGOL-68/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Ternary-logic b/Lang/ALGOL-68/Ternary-logic new file mode 120000 index 0000000000..9c5285a87a --- /dev/null +++ b/Lang/ALGOL-68/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Text-processing-1 b/Lang/ALGOL-68/Text-processing-1 new file mode 120000 index 0000000000..c7c7680e28 --- /dev/null +++ b/Lang/ALGOL-68/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Text-processing-Max-licenses-in-use b/Lang/ALGOL-68/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..29fd24b460 --- /dev/null +++ b/Lang/ALGOL-68/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Thieles-interpolation-formula b/Lang/ALGOL-68/Thieles-interpolation-formula new file mode 120000 index 0000000000..8c4c365a9b --- /dev/null +++ b/Lang/ALGOL-68/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Tokenize-a-string b/Lang/ALGOL-68/Tokenize-a-string new file mode 120000 index 0000000000..4369a5babe --- /dev/null +++ b/Lang/ALGOL-68/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Towers-of-Hanoi b/Lang/ALGOL-68/Towers-of-Hanoi new file mode 120000 index 0000000000..96462b8f6b --- /dev/null +++ b/Lang/ALGOL-68/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Tree-traversal b/Lang/ALGOL-68/Tree-traversal new file mode 120000 index 0000000000..fe34e5fd9a --- /dev/null +++ b/Lang/ALGOL-68/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Trigonometric-functions b/Lang/ALGOL-68/Trigonometric-functions new file mode 120000 index 0000000000..2d72b9eef2 --- /dev/null +++ b/Lang/ALGOL-68/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Truncatable-primes b/Lang/ALGOL-68/Truncatable-primes new file mode 120000 index 0000000000..6a1a28ef8c --- /dev/null +++ b/Lang/ALGOL-68/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Undefined-values b/Lang/ALGOL-68/Undefined-values new file mode 120000 index 0000000000..d6f7a5987f --- /dev/null +++ b/Lang/ALGOL-68/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Unicode-strings b/Lang/ALGOL-68/Unicode-strings new file mode 120000 index 0000000000..6b39931d5e --- /dev/null +++ b/Lang/ALGOL-68/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/User-input-Text b/Lang/ALGOL-68/User-input-Text new file mode 120000 index 0000000000..ec4dc31c2a --- /dev/null +++ b/Lang/ALGOL-68/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Variable-size-Get b/Lang/ALGOL-68/Variable-size-Get new file mode 120000 index 0000000000..dc36ceda47 --- /dev/null +++ b/Lang/ALGOL-68/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Variables b/Lang/ALGOL-68/Variables new file mode 120000 index 0000000000..bfbbf092f2 --- /dev/null +++ b/Lang/ALGOL-68/Variables @@ -0,0 +1 @@ +../../Task/Variables/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Variadic-function b/Lang/ALGOL-68/Variadic-function new file mode 120000 index 0000000000..71e6d219c2 --- /dev/null +++ b/Lang/ALGOL-68/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Vector-products b/Lang/ALGOL-68/Vector-products new file mode 120000 index 0000000000..c90b06972b --- /dev/null +++ b/Lang/ALGOL-68/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Vigen-re-cipher b/Lang/ALGOL-68/Vigen-re-cipher new file mode 120000 index 0000000000..83918b26eb --- /dev/null +++ b/Lang/ALGOL-68/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Walk-a-directory-Non-recursively b/Lang/ALGOL-68/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..dc231ac64f --- /dev/null +++ b/Lang/ALGOL-68/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Walk-a-directory-Recursively b/Lang/ALGOL-68/Walk-a-directory-Recursively new file mode 120000 index 0000000000..11c28f3e14 --- /dev/null +++ b/Lang/ALGOL-68/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Web-scraping b/Lang/ALGOL-68/Web-scraping new file mode 120000 index 0000000000..7af6ede66a --- /dev/null +++ b/Lang/ALGOL-68/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Window-creation b/Lang/ALGOL-68/Window-creation new file mode 120000 index 0000000000..fe501015dc --- /dev/null +++ b/Lang/ALGOL-68/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Window-creation-X11 b/Lang/ALGOL-68/Window-creation-X11 new file mode 120000 index 0000000000..e8720224ca --- /dev/null +++ b/Lang/ALGOL-68/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Wireworld b/Lang/ALGOL-68/Wireworld new file mode 120000 index 0000000000..758fb97391 --- /dev/null +++ b/Lang/ALGOL-68/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Write-float-arrays-to-a-text-file b/Lang/ALGOL-68/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..56d56c8423 --- /dev/null +++ b/Lang/ALGOL-68/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Y-combinator b/Lang/ALGOL-68/Y-combinator new file mode 120000 index 0000000000..4c36d55b8b --- /dev/null +++ b/Lang/ALGOL-68/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Yin-and-yang b/Lang/ALGOL-68/Yin-and-yang new file mode 120000 index 0000000000..ab2cace924 --- /dev/null +++ b/Lang/ALGOL-68/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Zig-zag-matrix b/Lang/ALGOL-68/Zig-zag-matrix new file mode 120000 index 0000000000..86827a117c --- /dev/null +++ b/Lang/ALGOL-68/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/ALGOL-68 \ No newline at end of file diff --git a/Lang/APL/Sort-an-integer-array b/Lang/APL/Sort-an-integer-array new file mode 120000 index 0000000000..446dea9571 --- /dev/null +++ b/Lang/APL/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/APL \ No newline at end of file diff --git a/Lang/APL/String-case b/Lang/APL/String-case new file mode 120000 index 0000000000..c41ba9a256 --- /dev/null +++ b/Lang/APL/String-case @@ -0,0 +1 @@ +../../Task/String-case/APL \ No newline at end of file diff --git a/Lang/APL/Sum-and-product-of-an-array b/Lang/APL/Sum-and-product-of-an-array new file mode 120000 index 0000000000..b4ddf99c80 --- /dev/null +++ b/Lang/APL/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/APL \ No newline at end of file diff --git a/Lang/APL/Text-processing-Max-licenses-in-use b/Lang/APL/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..1456025ce8 --- /dev/null +++ b/Lang/APL/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/APL \ No newline at end of file diff --git a/Lang/APL/Zig-zag-matrix b/Lang/APL/Zig-zag-matrix new file mode 120000 index 0000000000..741d14a4ac --- /dev/null +++ b/Lang/APL/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/APL \ No newline at end of file diff --git a/Lang/ATS/Tree-traversal b/Lang/ATS/Tree-traversal new file mode 120000 index 0000000000..dbae5492e1 --- /dev/null +++ b/Lang/ATS/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/ATS \ No newline at end of file diff --git a/Lang/AWK/Shell-one-liner b/Lang/AWK/Shell-one-liner new file mode 120000 index 0000000000..0ac1140554 --- /dev/null +++ b/Lang/AWK/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/AWK \ No newline at end of file diff --git a/Lang/AWK/Show-the-epoch b/Lang/AWK/Show-the-epoch new file mode 120000 index 0000000000..e69718afe6 --- /dev/null +++ b/Lang/AWK/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/AWK \ No newline at end of file diff --git a/Lang/AWK/Sierpinski-carpet b/Lang/AWK/Sierpinski-carpet new file mode 120000 index 0000000000..91a007e686 --- /dev/null +++ b/Lang/AWK/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/AWK \ No newline at end of file diff --git a/Lang/AWK/Sierpinski-triangle b/Lang/AWK/Sierpinski-triangle new file mode 120000 index 0000000000..e56aa2e19a --- /dev/null +++ b/Lang/AWK/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/AWK \ No newline at end of file diff --git a/Lang/AWK/Singly-linked-list-Element-definition b/Lang/AWK/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..d3070a6acf --- /dev/null +++ b/Lang/AWK/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/AWK \ No newline at end of file diff --git a/Lang/AWK/Sleep b/Lang/AWK/Sleep new file mode 120000 index 0000000000..9fd0044e22 --- /dev/null +++ b/Lang/AWK/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Bogosort b/Lang/AWK/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2e06613e45 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Bubble-sort b/Lang/AWK/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..45e87e9627 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Cocktail-sort b/Lang/AWK/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..19c7659cd1 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Comb-sort b/Lang/AWK/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..5f71842b0c --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Gnome-sort b/Lang/AWK/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..fc8033fb68 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Insertion-sort b/Lang/AWK/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..28f5b0fc37 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Quicksort b/Lang/AWK/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..89961b5697 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Selection-sort b/Lang/AWK/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..d54161fcd4 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Sorting-algorithms-Shell-sort b/Lang/AWK/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..060e9e5701 --- /dev/null +++ b/Lang/AWK/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/AWK \ No newline at end of file diff --git a/Lang/AWK/Soundex b/Lang/AWK/Soundex new file mode 120000 index 0000000000..ac97fec86d --- /dev/null +++ b/Lang/AWK/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/AWK \ No newline at end of file diff --git a/Lang/AWK/Spiral-matrix b/Lang/AWK/Spiral-matrix new file mode 120000 index 0000000000..e0a67b6f42 --- /dev/null +++ b/Lang/AWK/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/AWK \ No newline at end of file diff --git a/Lang/AWK/Start-from-a-main-routine b/Lang/AWK/Start-from-a-main-routine new file mode 120000 index 0000000000..26ad4acdf5 --- /dev/null +++ b/Lang/AWK/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/AWK \ No newline at end of file diff --git a/Lang/AWK/String-case b/Lang/AWK/String-case new file mode 120000 index 0000000000..0a6abcae04 --- /dev/null +++ b/Lang/AWK/String-case @@ -0,0 +1 @@ +../../Task/String-case/AWK \ No newline at end of file diff --git a/Lang/AWK/String-comparison b/Lang/AWK/String-comparison new file mode 120000 index 0000000000..5cd03e45f5 --- /dev/null +++ b/Lang/AWK/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/AWK \ No newline at end of file diff --git a/Lang/AWK/String-concatenation b/Lang/AWK/String-concatenation new file mode 120000 index 0000000000..e2962c0c4a --- /dev/null +++ b/Lang/AWK/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/AWK \ No newline at end of file diff --git a/Lang/AWK/String-length b/Lang/AWK/String-length new file mode 120000 index 0000000000..3e633fadcc --- /dev/null +++ b/Lang/AWK/String-length @@ -0,0 +1 @@ +../../Task/String-length/AWK \ No newline at end of file diff --git a/Lang/AWK/Strip-a-set-of-characters-from-a-string b/Lang/AWK/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a753c3be8a --- /dev/null +++ b/Lang/AWK/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Strip-comments-from-a-string b/Lang/AWK/Strip-comments-from-a-string new file mode 120000 index 0000000000..ee65f75cc4 --- /dev/null +++ b/Lang/AWK/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Strip-whitespace-from-a-string-Top-and-tail b/Lang/AWK/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ecbfeb1cbb --- /dev/null +++ b/Lang/AWK/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/AWK \ No newline at end of file diff --git a/Lang/AWK/Substring b/Lang/AWK/Substring new file mode 120000 index 0000000000..d1e8888608 --- /dev/null +++ b/Lang/AWK/Substring @@ -0,0 +1 @@ +../../Task/Substring/AWK \ No newline at end of file diff --git a/Lang/AWK/Substring-Top-and-tail b/Lang/AWK/Substring-Top-and-tail new file mode 120000 index 0000000000..39ace1247a --- /dev/null +++ b/Lang/AWK/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/AWK \ No newline at end of file diff --git a/Lang/AWK/Sum-and-product-of-an-array b/Lang/AWK/Sum-and-product-of-an-array new file mode 120000 index 0000000000..25f757496b --- /dev/null +++ b/Lang/AWK/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/AWK \ No newline at end of file diff --git a/Lang/AWK/Sum-digits-of-an-integer b/Lang/AWK/Sum-digits-of-an-integer new file mode 120000 index 0000000000..e8e64242b0 --- /dev/null +++ b/Lang/AWK/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/AWK \ No newline at end of file diff --git a/Lang/AWK/Sum-of-a-series b/Lang/AWK/Sum-of-a-series new file mode 120000 index 0000000000..a03ff3c9aa --- /dev/null +++ b/Lang/AWK/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/AWK \ No newline at end of file diff --git a/Lang/AWK/Sum-of-squares b/Lang/AWK/Sum-of-squares new file mode 120000 index 0000000000..bbff84fe5b --- /dev/null +++ b/Lang/AWK/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/AWK \ No newline at end of file diff --git a/Lang/AWK/System-time b/Lang/AWK/System-time new file mode 120000 index 0000000000..c21b8f320a --- /dev/null +++ b/Lang/AWK/System-time @@ -0,0 +1 @@ +../../Task/System-time/AWK \ No newline at end of file diff --git a/Lang/AWK/Table-creation-Postal-addresses b/Lang/AWK/Table-creation-Postal-addresses new file mode 120000 index 0000000000..81b1e8e78a --- /dev/null +++ b/Lang/AWK/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/AWK \ No newline at end of file diff --git a/Lang/AWK/Temperature-conversion b/Lang/AWK/Temperature-conversion new file mode 120000 index 0000000000..e60f6be167 --- /dev/null +++ b/Lang/AWK/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/AWK \ No newline at end of file diff --git a/Lang/AWK/Terminal-control-Clear-the-screen b/Lang/AWK/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..1d0ee72ed6 --- /dev/null +++ b/Lang/AWK/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/AWK \ No newline at end of file diff --git a/Lang/AWK/Terminal-control-Display-an-extended-character b/Lang/AWK/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..38e129b858 --- /dev/null +++ b/Lang/AWK/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/AWK \ No newline at end of file diff --git a/Lang/AWK/Terminal-control-Inverse-video b/Lang/AWK/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a663e67387 --- /dev/null +++ b/Lang/AWK/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/AWK \ No newline at end of file diff --git a/Lang/AWK/Terminal-control-Ringing-the-terminal-bell b/Lang/AWK/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..d92e619fb8 --- /dev/null +++ b/Lang/AWK/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/AWK \ No newline at end of file diff --git a/Lang/AWK/Terminal-control-Unicode-output b/Lang/AWK/Terminal-control-Unicode-output new file mode 120000 index 0000000000..ccf3596ac1 --- /dev/null +++ b/Lang/AWK/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/AWK \ No newline at end of file diff --git a/Lang/AWK/Text-processing-1 b/Lang/AWK/Text-processing-1 new file mode 120000 index 0000000000..c3ba51a4f7 --- /dev/null +++ b/Lang/AWK/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/AWK \ No newline at end of file diff --git a/Lang/AWK/Text-processing-2 b/Lang/AWK/Text-processing-2 new file mode 120000 index 0000000000..3308bdcc6e --- /dev/null +++ b/Lang/AWK/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/AWK \ No newline at end of file diff --git a/Lang/AWK/Text-processing-Max-licenses-in-use b/Lang/AWK/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8083e3bf8a --- /dev/null +++ b/Lang/AWK/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/AWK \ No newline at end of file diff --git a/Lang/AWK/Tokenize-a-string b/Lang/AWK/Tokenize-a-string new file mode 120000 index 0000000000..199e864e82 --- /dev/null +++ b/Lang/AWK/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Towers-of-Hanoi b/Lang/AWK/Towers-of-Hanoi new file mode 120000 index 0000000000..554cb4591b --- /dev/null +++ b/Lang/AWK/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/AWK \ No newline at end of file diff --git a/Lang/AWK/Trigonometric-functions b/Lang/AWK/Trigonometric-functions new file mode 120000 index 0000000000..c47b618a6d --- /dev/null +++ b/Lang/AWK/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/AWK \ No newline at end of file diff --git a/Lang/AWK/URL-decoding b/Lang/AWK/URL-decoding new file mode 120000 index 0000000000..d71abc3cb3 --- /dev/null +++ b/Lang/AWK/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/AWK \ No newline at end of file diff --git a/Lang/AWK/URL-encoding b/Lang/AWK/URL-encoding new file mode 120000 index 0000000000..22d2756049 --- /dev/null +++ b/Lang/AWK/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/AWK \ No newline at end of file diff --git a/Lang/AWK/User-input-Text b/Lang/AWK/User-input-Text new file mode 120000 index 0000000000..8629ba515b --- /dev/null +++ b/Lang/AWK/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/AWK \ No newline at end of file diff --git a/Lang/AWK/Variables b/Lang/AWK/Variables new file mode 120000 index 0000000000..59b332dee7 --- /dev/null +++ b/Lang/AWK/Variables @@ -0,0 +1 @@ +../../Task/Variables/AWK \ No newline at end of file diff --git a/Lang/AWK/Variadic-function b/Lang/AWK/Variadic-function new file mode 120000 index 0000000000..152e3028c1 --- /dev/null +++ b/Lang/AWK/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/AWK \ No newline at end of file diff --git a/Lang/AWK/Vector-products b/Lang/AWK/Vector-products new file mode 120000 index 0000000000..75f195719d --- /dev/null +++ b/Lang/AWK/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/AWK \ No newline at end of file diff --git a/Lang/AWK/Web-scraping b/Lang/AWK/Web-scraping new file mode 120000 index 0000000000..a56be8a1f9 --- /dev/null +++ b/Lang/AWK/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/AWK \ No newline at end of file diff --git a/Lang/AWK/Word-wrap b/Lang/AWK/Word-wrap new file mode 120000 index 0000000000..49a8785e71 --- /dev/null +++ b/Lang/AWK/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/AWK \ No newline at end of file diff --git a/Lang/AWK/Write-float-arrays-to-a-text-file b/Lang/AWK/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..9b6bd46d6b --- /dev/null +++ b/Lang/AWK/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/AWK \ No newline at end of file diff --git a/Lang/AWK/XML-Input b/Lang/AWK/XML-Input new file mode 120000 index 0000000000..3bf2eaa553 --- /dev/null +++ b/Lang/AWK/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/AWK \ No newline at end of file diff --git a/Lang/AWK/Zig-zag-matrix b/Lang/AWK/Zig-zag-matrix new file mode 120000 index 0000000000..d0a5eb3013 --- /dev/null +++ b/Lang/AWK/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/AWK \ No newline at end of file diff --git a/Lang/ActionScript/SOAP b/Lang/ActionScript/SOAP new file mode 120000 index 0000000000..949c1d1919 --- /dev/null +++ b/Lang/ActionScript/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Singleton b/Lang/ActionScript/Singleton new file mode 120000 index 0000000000..693032ac49 --- /dev/null +++ b/Lang/ActionScript/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Singly-linked-list-Element-definition b/Lang/ActionScript/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..929e135f15 --- /dev/null +++ b/Lang/ActionScript/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Singly-linked-list-Element-insertion b/Lang/ActionScript/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..4e7d81c1c8 --- /dev/null +++ b/Lang/ActionScript/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Singly-linked-list-Traversal b/Lang/ActionScript/Singly-linked-list-Traversal new file mode 120000 index 0000000000..0ec1cbcbc4 --- /dev/null +++ b/Lang/ActionScript/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sort-an-integer-array b/Lang/ActionScript/Sort-an-integer-array new file mode 120000 index 0000000000..ca710991bb --- /dev/null +++ b/Lang/ActionScript/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Bogosort b/Lang/ActionScript/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..a1c4a16bb5 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Bubble-sort b/Lang/ActionScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..cf9c28b087 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Cocktail-sort b/Lang/ActionScript/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..b4e1d347a4 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Comb-sort b/Lang/ActionScript/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..c48c71ddab --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Counting-sort b/Lang/ActionScript/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c301292553 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Gnome-sort b/Lang/ActionScript/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7430b34e88 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Heapsort b/Lang/ActionScript/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..ea737b6a3e --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Insertion-sort b/Lang/ActionScript/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..39a27d4c30 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Merge-sort b/Lang/ActionScript/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..29730e1827 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Permutation-sort b/Lang/ActionScript/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..92affe573c --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Quicksort b/Lang/ActionScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..1e83b1f81f --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Selection-sort b/Lang/ActionScript/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..0b37a246d0 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sorting-algorithms-Shell-sort b/Lang/ActionScript/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..e9b9bf1f28 --- /dev/null +++ b/Lang/ActionScript/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Stack b/Lang/ActionScript/Stack new file mode 120000 index 0000000000..35d04828c1 --- /dev/null +++ b/Lang/ActionScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Stair-climbing-puzzle b/Lang/ActionScript/Stair-climbing-puzzle new file mode 120000 index 0000000000..c04a1f8025 --- /dev/null +++ b/Lang/ActionScript/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/String-case b/Lang/ActionScript/String-case new file mode 120000 index 0000000000..1794785af0 --- /dev/null +++ b/Lang/ActionScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/String-concatenation b/Lang/ActionScript/String-concatenation new file mode 120000 index 0000000000..a481e1f95d --- /dev/null +++ b/Lang/ActionScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/String-length b/Lang/ActionScript/String-length new file mode 120000 index 0000000000..12467423f0 --- /dev/null +++ b/Lang/ActionScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sum-and-product-of-an-array b/Lang/ActionScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..dec2f546fe --- /dev/null +++ b/Lang/ActionScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sum-of-a-series b/Lang/ActionScript/Sum-of-a-series new file mode 120000 index 0000000000..7930ededf0 --- /dev/null +++ b/Lang/ActionScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Sum-of-squares b/Lang/ActionScript/Sum-of-squares new file mode 120000 index 0000000000..d97ce280bb --- /dev/null +++ b/Lang/ActionScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Tokenize-a-string b/Lang/ActionScript/Tokenize-a-string new file mode 120000 index 0000000000..d10f948fe8 --- /dev/null +++ b/Lang/ActionScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Towers-of-Hanoi b/Lang/ActionScript/Towers-of-Hanoi new file mode 120000 index 0000000000..d6cdaf7ba9 --- /dev/null +++ b/Lang/ActionScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Trigonometric-functions b/Lang/ActionScript/Trigonometric-functions new file mode 120000 index 0000000000..f210f652c6 --- /dev/null +++ b/Lang/ActionScript/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Undefined-values b/Lang/ActionScript/Undefined-values new file mode 120000 index 0000000000..7f76ad4415 --- /dev/null +++ b/Lang/ActionScript/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Variadic-function b/Lang/ActionScript/Variadic-function new file mode 120000 index 0000000000..dc7310d018 --- /dev/null +++ b/Lang/ActionScript/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/XML-Input b/Lang/ActionScript/XML-Input new file mode 120000 index 0000000000..7ef2ff94a2 --- /dev/null +++ b/Lang/ActionScript/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/ActionScript \ No newline at end of file diff --git a/Lang/ActionScript/Zig-zag-matrix b/Lang/ActionScript/Zig-zag-matrix new file mode 120000 index 0000000000..8ad3f2f89c --- /dev/null +++ b/Lang/ActionScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/ActionScript \ No newline at end of file diff --git a/Lang/Ada/SHA-1 b/Lang/Ada/SHA-1 new file mode 120000 index 0000000000..f3e042098a --- /dev/null +++ b/Lang/Ada/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Ada \ No newline at end of file diff --git a/Lang/Ada/Seven-sided-dice-from-five-sided-dice b/Lang/Ada/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..003c95db83 --- /dev/null +++ b/Lang/Ada/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Ada \ No newline at end of file diff --git a/Lang/Ada/Shell-one-liner b/Lang/Ada/Shell-one-liner new file mode 120000 index 0000000000..98eb3c6302 --- /dev/null +++ b/Lang/Ada/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Ada \ No newline at end of file diff --git a/Lang/Ada/Short-circuit-evaluation b/Lang/Ada/Short-circuit-evaluation new file mode 120000 index 0000000000..1ef29398fd --- /dev/null +++ b/Lang/Ada/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Ada \ No newline at end of file diff --git a/Lang/Ada/Show-the-epoch b/Lang/Ada/Show-the-epoch new file mode 120000 index 0000000000..e0319184a4 --- /dev/null +++ b/Lang/Ada/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-carpet b/Lang/Ada/Sierpinski-carpet new file mode 120000 index 0000000000..4690b92f08 --- /dev/null +++ b/Lang/Ada/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-triangle b/Lang/Ada/Sierpinski-triangle new file mode 120000 index 0000000000..e5367b8bb2 --- /dev/null +++ b/Lang/Ada/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Ada \ No newline at end of file diff --git a/Lang/Ada/Sieve-of-Eratosthenes b/Lang/Ada/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..4bae70ce89 --- /dev/null +++ b/Lang/Ada/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Ada \ No newline at end of file diff --git a/Lang/Ada/Simple-windowed-application b/Lang/Ada/Simple-windowed-application new file mode 120000 index 0000000000..87597db806 --- /dev/null +++ b/Lang/Ada/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Ada \ No newline at end of file diff --git a/Lang/Ada/Singleton b/Lang/Ada/Singleton new file mode 120000 index 0000000000..1fc0e94316 --- /dev/null +++ b/Lang/Ada/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Ada \ No newline at end of file diff --git a/Lang/Ada/Singly-linked-list-Element-definition b/Lang/Ada/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..abe7f91278 --- /dev/null +++ b/Lang/Ada/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Ada \ No newline at end of file diff --git a/Lang/Ada/Singly-linked-list-Element-insertion b/Lang/Ada/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..322203f531 --- /dev/null +++ b/Lang/Ada/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Ada \ No newline at end of file diff --git a/Lang/Ada/Singly-linked-list-Traversal b/Lang/Ada/Singly-linked-list-Traversal new file mode 120000 index 0000000000..c2af9dc510 --- /dev/null +++ b/Lang/Ada/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Ada \ No newline at end of file diff --git a/Lang/Ada/Sleep b/Lang/Ada/Sleep new file mode 120000 index 0000000000..149c392912 --- /dev/null +++ b/Lang/Ada/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Ada \ No newline at end of file diff --git a/Lang/Ada/Sockets b/Lang/Ada/Sockets new file mode 120000 index 0000000000..dc2937e1d5 --- /dev/null +++ b/Lang/Ada/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Ada \ No newline at end of file diff --git a/Lang/Ada/Sort-an-array-of-composite-structures b/Lang/Ada/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..989796a44c --- /dev/null +++ b/Lang/Ada/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Ada \ No newline at end of file diff --git a/Lang/Ada/Sort-an-integer-array b/Lang/Ada/Sort-an-integer-array new file mode 120000 index 0000000000..ee01e3c516 --- /dev/null +++ b/Lang/Ada/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Ada \ No newline at end of file diff --git a/Lang/Ada/Sort-disjoint-sublist b/Lang/Ada/Sort-disjoint-sublist new file mode 120000 index 0000000000..40adf0280a --- /dev/null +++ b/Lang/Ada/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Ada \ No newline at end of file diff --git a/Lang/Ada/Sort-using-a-custom-comparator b/Lang/Ada/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..47014b6e1d --- /dev/null +++ b/Lang/Ada/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Bogosort b/Lang/Ada/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..89de0b98a3 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Bubble-sort b/Lang/Ada/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8d2a4d22a8 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Cocktail-sort b/Lang/Ada/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..9c0468d72a --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Comb-sort b/Lang/Ada/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..789039c701 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Counting-sort b/Lang/Ada/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..118faf6e5f --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Gnome-sort b/Lang/Ada/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..4caedfe817 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Heapsort b/Lang/Ada/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..890638104b --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Insertion-sort b/Lang/Ada/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..61dcdc01f1 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Merge-sort b/Lang/Ada/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..cc08db022c --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Pancake-sort b/Lang/Ada/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..be36963931 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Quicksort b/Lang/Ada/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..6598727214 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Radix-sort b/Lang/Ada/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..b9dc935663 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Selection-sort b/Lang/Ada/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a295f3adbb --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Shell-sort b/Lang/Ada/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..bb0230adb6 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Sleep-sort b/Lang/Ada/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..775c74ddf4 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Stooge-sort b/Lang/Ada/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..1867a0fc57 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Soundex b/Lang/Ada/Soundex new file mode 120000 index 0000000000..e2c42789a5 --- /dev/null +++ b/Lang/Ada/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Ada \ No newline at end of file diff --git a/Lang/Ada/Special-characters b/Lang/Ada/Special-characters new file mode 120000 index 0000000000..d8715843d4 --- /dev/null +++ b/Lang/Ada/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Ada \ No newline at end of file diff --git a/Lang/Ada/Spiral-matrix b/Lang/Ada/Spiral-matrix new file mode 120000 index 0000000000..83592789dd --- /dev/null +++ b/Lang/Ada/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Ada \ No newline at end of file diff --git a/Lang/Ada/Stack b/Lang/Ada/Stack new file mode 120000 index 0000000000..39de142210 --- /dev/null +++ b/Lang/Ada/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ada \ No newline at end of file diff --git a/Lang/Ada/Stack-traces b/Lang/Ada/Stack-traces new file mode 120000 index 0000000000..58b318976b --- /dev/null +++ b/Lang/Ada/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Ada \ No newline at end of file diff --git a/Lang/Ada/Stair-climbing-puzzle b/Lang/Ada/Stair-climbing-puzzle new file mode 120000 index 0000000000..6a1ef94a65 --- /dev/null +++ b/Lang/Ada/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Ada \ No newline at end of file diff --git a/Lang/Ada/Standard-deviation b/Lang/Ada/Standard-deviation new file mode 120000 index 0000000000..b42c70390d --- /dev/null +++ b/Lang/Ada/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Ada \ No newline at end of file diff --git a/Lang/Ada/Start-from-a-main-routine b/Lang/Ada/Start-from-a-main-routine new file mode 120000 index 0000000000..e3f703b5ec --- /dev/null +++ b/Lang/Ada/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Ada \ No newline at end of file diff --git a/Lang/Ada/Stem-and-leaf-plot b/Lang/Ada/Stem-and-leaf-plot new file mode 120000 index 0000000000..01ceca7fe8 --- /dev/null +++ b/Lang/Ada/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Ada \ No newline at end of file diff --git a/Lang/Ada/String-case b/Lang/Ada/String-case new file mode 120000 index 0000000000..46a656b3f9 --- /dev/null +++ b/Lang/Ada/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ada \ No newline at end of file diff --git a/Lang/Ada/String-concatenation b/Lang/Ada/String-concatenation new file mode 120000 index 0000000000..b31c1d7ab9 --- /dev/null +++ b/Lang/Ada/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ada \ No newline at end of file diff --git a/Lang/Ada/String-interpolation--included- b/Lang/Ada/String-interpolation--included- new file mode 120000 index 0000000000..4e50aee612 --- /dev/null +++ b/Lang/Ada/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Ada \ No newline at end of file diff --git a/Lang/Ada/String-length b/Lang/Ada/String-length new file mode 120000 index 0000000000..f3aa0008b6 --- /dev/null +++ b/Lang/Ada/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ada \ No newline at end of file diff --git a/Lang/Ada/Strip-a-set-of-characters-from-a-string b/Lang/Ada/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..d20137ab32 --- /dev/null +++ b/Lang/Ada/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Strip-block-comments b/Lang/Ada/Strip-block-comments new file mode 120000 index 0000000000..a7c70d9f73 --- /dev/null +++ b/Lang/Ada/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Ada \ No newline at end of file diff --git a/Lang/Ada/Strip-comments-from-a-string b/Lang/Ada/Strip-comments-from-a-string new file mode 120000 index 0000000000..076affd245 --- /dev/null +++ b/Lang/Ada/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Ada/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..f6792facbc --- /dev/null +++ b/Lang/Ada/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Ada/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..75b42748e1 --- /dev/null +++ b/Lang/Ada/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Ada \ No newline at end of file diff --git a/Lang/Ada/Substring b/Lang/Ada/Substring new file mode 120000 index 0000000000..fab2257974 --- /dev/null +++ b/Lang/Ada/Substring @@ -0,0 +1 @@ +../../Task/Substring/Ada \ No newline at end of file diff --git a/Lang/Ada/Substring-Top-and-tail b/Lang/Ada/Substring-Top-and-tail new file mode 120000 index 0000000000..93b4ccc419 --- /dev/null +++ b/Lang/Ada/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Ada \ No newline at end of file diff --git a/Lang/Ada/Subtractive-generator b/Lang/Ada/Subtractive-generator new file mode 120000 index 0000000000..0b0deac716 --- /dev/null +++ b/Lang/Ada/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Ada \ No newline at end of file diff --git a/Lang/Ada/Sum-and-product-of-an-array b/Lang/Ada/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4c6068c6b7 --- /dev/null +++ b/Lang/Ada/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Ada \ No newline at end of file diff --git a/Lang/Ada/Sum-digits-of-an-integer b/Lang/Ada/Sum-digits-of-an-integer new file mode 120000 index 0000000000..3bb9f68107 --- /dev/null +++ b/Lang/Ada/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Ada \ No newline at end of file diff --git a/Lang/Ada/Sum-of-a-series b/Lang/Ada/Sum-of-a-series new file mode 120000 index 0000000000..5025b2646f --- /dev/null +++ b/Lang/Ada/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Ada \ No newline at end of file diff --git a/Lang/Ada/Sum-of-squares b/Lang/Ada/Sum-of-squares new file mode 120000 index 0000000000..225d83c705 --- /dev/null +++ b/Lang/Ada/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Ada \ No newline at end of file diff --git a/Lang/Ada/Sutherland-Hodgman-polygon-clipping b/Lang/Ada/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..6bb5479096 --- /dev/null +++ b/Lang/Ada/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Ada \ No newline at end of file diff --git a/Lang/Ada/Symmetric-difference b/Lang/Ada/Symmetric-difference new file mode 120000 index 0000000000..fb591753d3 --- /dev/null +++ b/Lang/Ada/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Ada \ No newline at end of file diff --git a/Lang/Ada/Synchronous-concurrency b/Lang/Ada/Synchronous-concurrency new file mode 120000 index 0000000000..04f4d389c6 --- /dev/null +++ b/Lang/Ada/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Ada \ No newline at end of file diff --git a/Lang/Ada/System-time b/Lang/Ada/System-time new file mode 120000 index 0000000000..246cf4b85d --- /dev/null +++ b/Lang/Ada/System-time @@ -0,0 +1 @@ +../../Task/System-time/Ada \ No newline at end of file diff --git a/Lang/Ada/Take-notes-on-the-command-line b/Lang/Ada/Take-notes-on-the-command-line new file mode 120000 index 0000000000..b3a87c35cd --- /dev/null +++ b/Lang/Ada/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Ada \ No newline at end of file diff --git a/Lang/Ada/Terminal-control-Clear-the-screen b/Lang/Ada/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..7b7fcf2c43 --- /dev/null +++ b/Lang/Ada/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Ada \ No newline at end of file diff --git a/Lang/Ada/Terminal-control-Cursor-positioning b/Lang/Ada/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..7354adc4f3 --- /dev/null +++ b/Lang/Ada/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Ada \ No newline at end of file diff --git a/Lang/Ada/Terminal-control-Display-an-extended-character b/Lang/Ada/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..91d798888b --- /dev/null +++ b/Lang/Ada/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Ada \ No newline at end of file diff --git a/Lang/Ada/Terminal-control-Ringing-the-terminal-bell b/Lang/Ada/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..d29ad8f27e --- /dev/null +++ b/Lang/Ada/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Ada \ No newline at end of file diff --git a/Lang/Ada/Ternary-logic b/Lang/Ada/Ternary-logic new file mode 120000 index 0000000000..bf900810b5 --- /dev/null +++ b/Lang/Ada/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Ada \ No newline at end of file diff --git a/Lang/Ada/Test-a-function b/Lang/Ada/Test-a-function new file mode 120000 index 0000000000..38030e6efd --- /dev/null +++ b/Lang/Ada/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Ada \ No newline at end of file diff --git a/Lang/Ada/Text-processing-1 b/Lang/Ada/Text-processing-1 new file mode 120000 index 0000000000..161ab58c30 --- /dev/null +++ b/Lang/Ada/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Ada \ No newline at end of file diff --git a/Lang/Ada/Text-processing-2 b/Lang/Ada/Text-processing-2 new file mode 120000 index 0000000000..7522da5719 --- /dev/null +++ b/Lang/Ada/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Ada \ No newline at end of file diff --git a/Lang/Ada/Text-processing-Max-licenses-in-use b/Lang/Ada/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..bbc39a8d6a --- /dev/null +++ b/Lang/Ada/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Ada \ No newline at end of file diff --git a/Lang/Ada/Thieles-interpolation-formula b/Lang/Ada/Thieles-interpolation-formula new file mode 120000 index 0000000000..241d61bc1c --- /dev/null +++ b/Lang/Ada/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Ada \ No newline at end of file diff --git a/Lang/Ada/Tic-tac-toe b/Lang/Ada/Tic-tac-toe new file mode 120000 index 0000000000..f7e60d61b6 --- /dev/null +++ b/Lang/Ada/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Ada \ No newline at end of file diff --git a/Lang/Ada/Time-a-function b/Lang/Ada/Time-a-function new file mode 120000 index 0000000000..5268c65e11 --- /dev/null +++ b/Lang/Ada/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Ada \ No newline at end of file diff --git a/Lang/Ada/Tokenize-a-string b/Lang/Ada/Tokenize-a-string new file mode 120000 index 0000000000..59bfc8e102 --- /dev/null +++ b/Lang/Ada/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Top-rank-per-group b/Lang/Ada/Top-rank-per-group new file mode 120000 index 0000000000..3a9e487d6a --- /dev/null +++ b/Lang/Ada/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Ada \ No newline at end of file diff --git a/Lang/Ada/Topological-sort b/Lang/Ada/Topological-sort new file mode 120000 index 0000000000..10cc4c454b --- /dev/null +++ b/Lang/Ada/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Towers-of-Hanoi b/Lang/Ada/Towers-of-Hanoi new file mode 120000 index 0000000000..fb7223d324 --- /dev/null +++ b/Lang/Ada/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ada \ No newline at end of file diff --git a/Lang/Ada/Trabb-Pardo-Knuth-algorithm b/Lang/Ada/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..a692e28f46 --- /dev/null +++ b/Lang/Ada/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Ada \ No newline at end of file diff --git a/Lang/Ada/Tree-traversal b/Lang/Ada/Tree-traversal new file mode 120000 index 0000000000..61d6e38e7e --- /dev/null +++ b/Lang/Ada/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Ada \ No newline at end of file diff --git a/Lang/Ada/Trigonometric-functions b/Lang/Ada/Trigonometric-functions new file mode 120000 index 0000000000..e4fac3cfa5 --- /dev/null +++ b/Lang/Ada/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Ada \ No newline at end of file diff --git a/Lang/Ada/Truncatable-primes b/Lang/Ada/Truncatable-primes new file mode 120000 index 0000000000..30dc8a035b --- /dev/null +++ b/Lang/Ada/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Truncate-a-file b/Lang/Ada/Truncate-a-file new file mode 120000 index 0000000000..557746c908 --- /dev/null +++ b/Lang/Ada/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Ada \ No newline at end of file diff --git a/Lang/Ada/Twelve-statements b/Lang/Ada/Twelve-statements new file mode 120000 index 0000000000..ff1b208d7f --- /dev/null +++ b/Lang/Ada/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Ada \ No newline at end of file diff --git a/Lang/Ada/URL-decoding b/Lang/Ada/URL-decoding new file mode 120000 index 0000000000..35104d6650 --- /dev/null +++ b/Lang/Ada/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Ada \ No newline at end of file diff --git a/Lang/Ada/URL-encoding b/Lang/Ada/URL-encoding new file mode 120000 index 0000000000..5f43e58904 --- /dev/null +++ b/Lang/Ada/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Ada \ No newline at end of file diff --git a/Lang/Ada/Unbias-a-random-generator b/Lang/Ada/Unbias-a-random-generator new file mode 120000 index 0000000000..6d82b2a682 --- /dev/null +++ b/Lang/Ada/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Ada \ No newline at end of file diff --git a/Lang/Ada/Undefined-values b/Lang/Ada/Undefined-values new file mode 120000 index 0000000000..af0aa28be3 --- /dev/null +++ b/Lang/Ada/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Ada \ No newline at end of file diff --git a/Lang/Ada/Unicode-variable-names b/Lang/Ada/Unicode-variable-names new file mode 120000 index 0000000000..d4e67d891b --- /dev/null +++ b/Lang/Ada/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ada \ No newline at end of file diff --git a/Lang/Ada/Universal-Turing-machine b/Lang/Ada/Universal-Turing-machine new file mode 120000 index 0000000000..1aecf5d51d --- /dev/null +++ b/Lang/Ada/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Ada \ No newline at end of file diff --git a/Lang/Ada/Use-another-language-to-call-a-function b/Lang/Ada/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..7b0070dfc1 --- /dev/null +++ b/Lang/Ada/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Ada \ No newline at end of file diff --git a/Lang/Ada/User-input-Graphical b/Lang/Ada/User-input-Graphical new file mode 120000 index 0000000000..c1f8f04eb0 --- /dev/null +++ b/Lang/Ada/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Ada \ No newline at end of file diff --git a/Lang/Ada/User-input-Text b/Lang/Ada/User-input-Text new file mode 120000 index 0000000000..ad860c25bf --- /dev/null +++ b/Lang/Ada/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Ada \ No newline at end of file diff --git a/Lang/Ada/Van-der-Corput-sequence b/Lang/Ada/Van-der-Corput-sequence new file mode 120000 index 0000000000..df8cad33b2 --- /dev/null +++ b/Lang/Ada/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Ada \ No newline at end of file diff --git a/Lang/Ada/Variable-length-quantity b/Lang/Ada/Variable-length-quantity new file mode 120000 index 0000000000..04fbaf364b --- /dev/null +++ b/Lang/Ada/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Ada \ No newline at end of file diff --git a/Lang/Ada/Variable-size-Get b/Lang/Ada/Variable-size-Get new file mode 120000 index 0000000000..e8ade651e8 --- /dev/null +++ b/Lang/Ada/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Ada \ No newline at end of file diff --git a/Lang/Ada/Variable-size-Set b/Lang/Ada/Variable-size-Set new file mode 120000 index 0000000000..f5653db999 --- /dev/null +++ b/Lang/Ada/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Ada \ No newline at end of file diff --git a/Lang/Ada/Variables b/Lang/Ada/Variables new file mode 120000 index 0000000000..b2ac890b96 --- /dev/null +++ b/Lang/Ada/Variables @@ -0,0 +1 @@ +../../Task/Variables/Ada \ No newline at end of file diff --git a/Lang/Ada/Variadic-function b/Lang/Ada/Variadic-function new file mode 120000 index 0000000000..fddcadb1ee --- /dev/null +++ b/Lang/Ada/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Ada \ No newline at end of file diff --git a/Lang/Ada/Vector-products b/Lang/Ada/Vector-products new file mode 120000 index 0000000000..4afafd00ff --- /dev/null +++ b/Lang/Ada/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Ada \ No newline at end of file diff --git a/Lang/Ada/Verify-distribution-uniformity-Naive b/Lang/Ada/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..a37a2b56d6 --- /dev/null +++ b/Lang/Ada/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Ada \ No newline at end of file diff --git a/Lang/Ada/Vigen-re-cipher b/Lang/Ada/Vigen-re-cipher new file mode 120000 index 0000000000..8f1869ce50 --- /dev/null +++ b/Lang/Ada/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Ada \ No newline at end of file diff --git a/Lang/Ada/Vigen-re-cipher-Cryptanalysis b/Lang/Ada/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..f65fab99c8 --- /dev/null +++ b/Lang/Ada/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Ada \ No newline at end of file diff --git a/Lang/Ada/Walk-a-directory-Non-recursively b/Lang/Ada/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..23f86d645b --- /dev/null +++ b/Lang/Ada/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Ada \ No newline at end of file diff --git a/Lang/Ada/Walk-a-directory-Recursively b/Lang/Ada/Walk-a-directory-Recursively new file mode 120000 index 0000000000..841f977cc1 --- /dev/null +++ b/Lang/Ada/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Ada \ No newline at end of file diff --git a/Lang/Ada/Web-scraping b/Lang/Ada/Web-scraping new file mode 120000 index 0000000000..0199f279af --- /dev/null +++ b/Lang/Ada/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Ada \ No newline at end of file diff --git a/Lang/Ada/Window-creation b/Lang/Ada/Window-creation new file mode 120000 index 0000000000..7382dac301 --- /dev/null +++ b/Lang/Ada/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Ada \ No newline at end of file diff --git a/Lang/Ada/Wireworld b/Lang/Ada/Wireworld new file mode 120000 index 0000000000..36f80f3710 --- /dev/null +++ b/Lang/Ada/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-wrap b/Lang/Ada/Word-wrap new file mode 120000 index 0000000000..827f9cda30 --- /dev/null +++ b/Lang/Ada/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Ada \ No newline at end of file diff --git a/Lang/Ada/Write-float-arrays-to-a-text-file b/Lang/Ada/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..99252b292a --- /dev/null +++ b/Lang/Ada/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Ada \ No newline at end of file diff --git a/Lang/Ada/Write-language-name-in-3D-ASCII b/Lang/Ada/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..04a859279e --- /dev/null +++ b/Lang/Ada/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Ada \ No newline at end of file diff --git a/Lang/Ada/XML-DOM-serialization b/Lang/Ada/XML-DOM-serialization new file mode 120000 index 0000000000..6eb2dc834f --- /dev/null +++ b/Lang/Ada/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Ada \ No newline at end of file diff --git a/Lang/Ada/XML-Input b/Lang/Ada/XML-Input new file mode 120000 index 0000000000..279ae60b28 --- /dev/null +++ b/Lang/Ada/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Ada \ No newline at end of file diff --git a/Lang/Ada/XML-Output b/Lang/Ada/XML-Output new file mode 120000 index 0000000000..9bce820900 --- /dev/null +++ b/Lang/Ada/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Ada \ No newline at end of file diff --git a/Lang/Ada/Yin-and-yang b/Lang/Ada/Yin-and-yang new file mode 120000 index 0000000000..5ca3dc24c4 --- /dev/null +++ b/Lang/Ada/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Ada \ No newline at end of file diff --git a/Lang/Ada/Zebra-puzzle b/Lang/Ada/Zebra-puzzle new file mode 120000 index 0000000000..ba34f998a0 --- /dev/null +++ b/Lang/Ada/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Ada \ No newline at end of file diff --git a/Lang/Ada/Zig-zag-matrix b/Lang/Ada/Zig-zag-matrix new file mode 120000 index 0000000000..3a1d35ad7d --- /dev/null +++ b/Lang/Ada/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Ada \ No newline at end of file diff --git a/Lang/Agena/Towers-of-Hanoi b/Lang/Agena/Towers-of-Hanoi new file mode 120000 index 0000000000..bed46b9187 --- /dev/null +++ b/Lang/Agena/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Agena \ No newline at end of file diff --git a/Lang/Aikido/Shell-one-liner b/Lang/Aikido/Shell-one-liner new file mode 120000 index 0000000000..30d7c1c34d --- /dev/null +++ b/Lang/Aikido/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Aikido \ No newline at end of file diff --git a/Lang/Aikido/String-interpolation--included- b/Lang/Aikido/String-interpolation--included- new file mode 120000 index 0000000000..5f74942fa2 --- /dev/null +++ b/Lang/Aikido/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Aikido \ No newline at end of file diff --git a/Lang/Aikido/Substring b/Lang/Aikido/Substring new file mode 120000 index 0000000000..f955c20074 --- /dev/null +++ b/Lang/Aikido/Substring @@ -0,0 +1 @@ +../../Task/Substring/Aikido \ No newline at end of file diff --git a/Lang/Aikido/Synchronous-concurrency b/Lang/Aikido/Synchronous-concurrency new file mode 120000 index 0000000000..662a3cf9cf --- /dev/null +++ b/Lang/Aikido/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Aikido \ No newline at end of file diff --git a/Lang/Aikido/XML-Input b/Lang/Aikido/XML-Input new file mode 120000 index 0000000000..2bc673e070 --- /dev/null +++ b/Lang/Aikido/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Aikido \ No newline at end of file diff --git a/Lang/Aime/Shell-one-liner b/Lang/Aime/Shell-one-liner new file mode 120000 index 0000000000..bbdb2282c5 --- /dev/null +++ b/Lang/Aime/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Aime \ No newline at end of file diff --git a/Lang/Aime/System-time b/Lang/Aime/System-time new file mode 120000 index 0000000000..38b000b094 --- /dev/null +++ b/Lang/Aime/System-time @@ -0,0 +1 @@ +../../Task/System-time/Aime \ No newline at end of file diff --git a/Lang/Aime/Text-processing-1 b/Lang/Aime/Text-processing-1 new file mode 120000 index 0000000000..17b732e1f3 --- /dev/null +++ b/Lang/Aime/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Aime \ No newline at end of file diff --git a/Lang/Aime/Time-a-function b/Lang/Aime/Time-a-function new file mode 120000 index 0000000000..d57f62fce0 --- /dev/null +++ b/Lang/Aime/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Aime \ No newline at end of file diff --git a/Lang/Alore/Sum-of-squares b/Lang/Alore/Sum-of-squares new file mode 120000 index 0000000000..381ab6ada9 --- /dev/null +++ b/Lang/Alore/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Alore \ No newline at end of file diff --git a/Lang/AmigaE/Towers-of-Hanoi b/Lang/AmigaE/Towers-of-Hanoi new file mode 120000 index 0000000000..a7823f1542 --- /dev/null +++ b/Lang/AmigaE/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/AmigaE \ No newline at end of file diff --git a/Lang/AppleScript/String-length b/Lang/AppleScript/String-length new file mode 120000 index 0000000000..cef3b0085e --- /dev/null +++ b/Lang/AppleScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Sum-and-product-of-an-array b/Lang/AppleScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e0bbd20107 --- /dev/null +++ b/Lang/AppleScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/System-time b/Lang/AppleScript/System-time new file mode 120000 index 0000000000..e4b7491036 --- /dev/null +++ b/Lang/AppleScript/System-time @@ -0,0 +1 @@ +../../Task/System-time/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Towers-of-Hanoi b/Lang/AppleScript/Towers-of-Hanoi new file mode 120000 index 0000000000..b7ae489e5d --- /dev/null +++ b/Lang/AppleScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/User-input-Graphical b/Lang/AppleScript/User-input-Graphical new file mode 120000 index 0000000000..6df6a82a96 --- /dev/null +++ b/Lang/AppleScript/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Variables b/Lang/AppleScript/Variables new file mode 120000 index 0000000000..a9f28dd70c --- /dev/null +++ b/Lang/AppleScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Walk-a-directory-Non-recursively b/Lang/AppleScript/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..fc2eb840d7 --- /dev/null +++ b/Lang/AppleScript/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/XML-XPath b/Lang/AppleScript/XML-XPath new file mode 120000 index 0000000000..1bf30cbfb2 --- /dev/null +++ b/Lang/AppleScript/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Y-combinator b/Lang/AppleScript/Y-combinator new file mode 120000 index 0000000000..9931a0a7f9 --- /dev/null +++ b/Lang/AppleScript/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Zig-zag-matrix b/Lang/AppleScript/Zig-zag-matrix new file mode 120000 index 0000000000..2d0c6ecdb3 --- /dev/null +++ b/Lang/AppleScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Stack b/Lang/Applesoft-BASIC/Stack new file mode 120000 index 0000000000..15bda7aeaa --- /dev/null +++ b/Lang/Applesoft-BASIC/Stack @@ -0,0 +1 @@ +../../Task/Stack/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Strip-a-set-of-characters-from-a-string b/Lang/Applesoft-BASIC/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..201e3a68e2 --- /dev/null +++ b/Lang/Applesoft-BASIC/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Arbre/String-case b/Lang/Arbre/String-case new file mode 120000 index 0000000000..93658a71db --- /dev/null +++ b/Lang/Arbre/String-case @@ -0,0 +1 @@ +../../Task/String-case/Arbre \ No newline at end of file diff --git a/Lang/Asymptote/Sierpinski-carpet b/Lang/Asymptote/Sierpinski-carpet new file mode 120000 index 0000000000..12b5d99399 --- /dev/null +++ b/Lang/Asymptote/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Sierpinski-triangle-Graphical b/Lang/Asymptote/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..ba56fba163 --- /dev/null +++ b/Lang/Asymptote/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Yin-and-yang b/Lang/Asymptote/Yin-and-yang new file mode 120000 index 0000000000..9f591aa06c --- /dev/null +++ b/Lang/Asymptote/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Asymptote \ No newline at end of file diff --git a/Lang/AutoHotkey/SOAP b/Lang/AutoHotkey/SOAP new file mode 120000 index 0000000000..7ddfbff0bd --- /dev/null +++ b/Lang/AutoHotkey/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Seven-sided-dice-from-five-sided-dice b/Lang/AutoHotkey/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..ea6764a75f --- /dev/null +++ b/Lang/AutoHotkey/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Short-circuit-evaluation b/Lang/AutoHotkey/Short-circuit-evaluation new file mode 120000 index 0000000000..7b042a93fd --- /dev/null +++ b/Lang/AutoHotkey/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sierpinski-carpet b/Lang/AutoHotkey/Sierpinski-carpet new file mode 120000 index 0000000000..6982df0ef7 --- /dev/null +++ b/Lang/AutoHotkey/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sierpinski-triangle b/Lang/AutoHotkey/Sierpinski-triangle new file mode 120000 index 0000000000..64583ad991 --- /dev/null +++ b/Lang/AutoHotkey/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sieve-of-Eratosthenes b/Lang/AutoHotkey/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..114d1fb2e0 --- /dev/null +++ b/Lang/AutoHotkey/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Simple-windowed-application b/Lang/AutoHotkey/Simple-windowed-application new file mode 120000 index 0000000000..2011972d44 --- /dev/null +++ b/Lang/AutoHotkey/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Simulate-input-Keyboard b/Lang/AutoHotkey/Simulate-input-Keyboard new file mode 120000 index 0000000000..a3f203b763 --- /dev/null +++ b/Lang/AutoHotkey/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Simulate-input-Mouse b/Lang/AutoHotkey/Simulate-input-Mouse new file mode 120000 index 0000000000..61deecb321 --- /dev/null +++ b/Lang/AutoHotkey/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Singleton b/Lang/AutoHotkey/Singleton new file mode 120000 index 0000000000..9a2c33eda9 --- /dev/null +++ b/Lang/AutoHotkey/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Singly-linked-list-Element-definition b/Lang/AutoHotkey/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..0ff5bc444d --- /dev/null +++ b/Lang/AutoHotkey/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Singly-linked-list-Element-insertion b/Lang/AutoHotkey/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..b139841b19 --- /dev/null +++ b/Lang/AutoHotkey/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Singly-linked-list-Traversal b/Lang/AutoHotkey/Singly-linked-list-Traversal new file mode 120000 index 0000000000..9aafe13695 --- /dev/null +++ b/Lang/AutoHotkey/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sleep b/Lang/AutoHotkey/Sleep new file mode 120000 index 0000000000..127bce1a7e --- /dev/null +++ b/Lang/AutoHotkey/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sockets b/Lang/AutoHotkey/Sockets new file mode 120000 index 0000000000..1c25b1767a --- /dev/null +++ b/Lang/AutoHotkey/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sort-an-array-of-composite-structures b/Lang/AutoHotkey/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..f954d3399f --- /dev/null +++ b/Lang/AutoHotkey/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sort-an-integer-array b/Lang/AutoHotkey/Sort-an-integer-array new file mode 120000 index 0000000000..15fd6454cd --- /dev/null +++ b/Lang/AutoHotkey/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sort-stability b/Lang/AutoHotkey/Sort-stability new file mode 120000 index 0000000000..7ce5ae4ef6 --- /dev/null +++ b/Lang/AutoHotkey/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sort-using-a-custom-comparator b/Lang/AutoHotkey/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..24d07fed48 --- /dev/null +++ b/Lang/AutoHotkey/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Bogosort b/Lang/AutoHotkey/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b0f15ad72e --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Bubble-sort b/Lang/AutoHotkey/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ab7eea6bf7 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Cocktail-sort b/Lang/AutoHotkey/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..5817ac8eae --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Comb-sort b/Lang/AutoHotkey/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..b267ce1151 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Counting-sort b/Lang/AutoHotkey/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..827c717441 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Gnome-sort b/Lang/AutoHotkey/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..e7cb058fc2 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Heapsort b/Lang/AutoHotkey/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..18eb72f627 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Insertion-sort b/Lang/AutoHotkey/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..9097075b77 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Merge-sort b/Lang/AutoHotkey/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..616b9301b1 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Pancake-sort b/Lang/AutoHotkey/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..7db5a24884 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Permutation-sort b/Lang/AutoHotkey/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..69987eb0bd --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Quicksort b/Lang/AutoHotkey/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..4876d2a7e2 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Selection-sort b/Lang/AutoHotkey/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ec8941f833 --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-algorithms-Shell-sort b/Lang/AutoHotkey/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..35250165ab --- /dev/null +++ b/Lang/AutoHotkey/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Soundex b/Lang/AutoHotkey/Soundex new file mode 120000 index 0000000000..76f7b04119 --- /dev/null +++ b/Lang/AutoHotkey/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Speech-synthesis b/Lang/AutoHotkey/Speech-synthesis new file mode 120000 index 0000000000..77974596e6 --- /dev/null +++ b/Lang/AutoHotkey/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Spiral-matrix b/Lang/AutoHotkey/Spiral-matrix new file mode 120000 index 0000000000..beb8bc1c2e --- /dev/null +++ b/Lang/AutoHotkey/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Stack b/Lang/AutoHotkey/Stack new file mode 120000 index 0000000000..751003f5c3 --- /dev/null +++ b/Lang/AutoHotkey/Stack @@ -0,0 +1 @@ +../../Task/Stack/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Stack-traces b/Lang/AutoHotkey/Stack-traces new file mode 120000 index 0000000000..36323d7198 --- /dev/null +++ b/Lang/AutoHotkey/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Stair-climbing-puzzle b/Lang/AutoHotkey/Stair-climbing-puzzle new file mode 120000 index 0000000000..041c17ce1c --- /dev/null +++ b/Lang/AutoHotkey/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Standard-deviation b/Lang/AutoHotkey/Standard-deviation new file mode 120000 index 0000000000..c5aaf10e72 --- /dev/null +++ b/Lang/AutoHotkey/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Stem-and-leaf-plot b/Lang/AutoHotkey/Stem-and-leaf-plot new file mode 120000 index 0000000000..32db785e30 --- /dev/null +++ b/Lang/AutoHotkey/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-case b/Lang/AutoHotkey/String-case new file mode 120000 index 0000000000..08c27edb33 --- /dev/null +++ b/Lang/AutoHotkey/String-case @@ -0,0 +1 @@ +../../Task/String-case/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-concatenation b/Lang/AutoHotkey/String-concatenation new file mode 120000 index 0000000000..7035d3045c --- /dev/null +++ b/Lang/AutoHotkey/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-interpolation--included- b/Lang/AutoHotkey/String-interpolation--included- new file mode 120000 index 0000000000..3eca320c69 --- /dev/null +++ b/Lang/AutoHotkey/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/String-length b/Lang/AutoHotkey/String-length new file mode 120000 index 0000000000..a5583b5cb5 --- /dev/null +++ b/Lang/AutoHotkey/String-length @@ -0,0 +1 @@ +../../Task/String-length/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Strip-a-set-of-characters-from-a-string b/Lang/AutoHotkey/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..9a7b541f93 --- /dev/null +++ b/Lang/AutoHotkey/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Strip-comments-from-a-string b/Lang/AutoHotkey/Strip-comments-from-a-string new file mode 120000 index 0000000000..c6b47433a1 --- /dev/null +++ b/Lang/AutoHotkey/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Strip-control-codes-and-extended-characters-from-a-string b/Lang/AutoHotkey/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..07df21c60d --- /dev/null +++ b/Lang/AutoHotkey/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Strip-whitespace-from-a-string-Top-and-tail b/Lang/AutoHotkey/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..971f302a3f --- /dev/null +++ b/Lang/AutoHotkey/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Substring b/Lang/AutoHotkey/Substring new file mode 120000 index 0000000000..37e796f96a --- /dev/null +++ b/Lang/AutoHotkey/Substring @@ -0,0 +1 @@ +../../Task/Substring/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Substring-Top-and-tail b/Lang/AutoHotkey/Substring-Top-and-tail new file mode 120000 index 0000000000..54734150c0 --- /dev/null +++ b/Lang/AutoHotkey/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sudoku b/Lang/AutoHotkey/Sudoku new file mode 120000 index 0000000000..d849f1945c --- /dev/null +++ b/Lang/AutoHotkey/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sum-and-product-of-an-array b/Lang/AutoHotkey/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5676dcf4d5 --- /dev/null +++ b/Lang/AutoHotkey/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sum-of-a-series b/Lang/AutoHotkey/Sum-of-a-series new file mode 120000 index 0000000000..70a663dca2 --- /dev/null +++ b/Lang/AutoHotkey/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sum-of-squares b/Lang/AutoHotkey/Sum-of-squares new file mode 120000 index 0000000000..ab1d9e894d --- /dev/null +++ b/Lang/AutoHotkey/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Symmetric-difference b/Lang/AutoHotkey/Symmetric-difference new file mode 120000 index 0000000000..09f9badf97 --- /dev/null +++ b/Lang/AutoHotkey/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/System-time b/Lang/AutoHotkey/System-time new file mode 120000 index 0000000000..c747baa76e --- /dev/null +++ b/Lang/AutoHotkey/System-time @@ -0,0 +1 @@ +../../Task/System-time/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Take-notes-on-the-command-line b/Lang/AutoHotkey/Take-notes-on-the-command-line new file mode 120000 index 0000000000..b9f903daec --- /dev/null +++ b/Lang/AutoHotkey/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Clear-the-screen b/Lang/AutoHotkey/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..7e1771d3e9 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Coloured-text b/Lang/AutoHotkey/Terminal-control-Coloured-text new file mode 120000 index 0000000000..40fd16d3ad --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Cursor-positioning b/Lang/AutoHotkey/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..85788e3af5 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Dimensions b/Lang/AutoHotkey/Terminal-control-Dimensions new file mode 120000 index 0000000000..ff2e6da519 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Hiding-the-cursor b/Lang/AutoHotkey/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..16fb5d2353 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Inverse-video b/Lang/AutoHotkey/Terminal-control-Inverse-video new file mode 120000 index 0000000000..e0c0680f99 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Positional-read b/Lang/AutoHotkey/Terminal-control-Positional-read new file mode 120000 index 0000000000..741af556c0 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Terminal-control-Ringing-the-terminal-bell b/Lang/AutoHotkey/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..2d5ec580c9 --- /dev/null +++ b/Lang/AutoHotkey/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Test-a-function b/Lang/AutoHotkey/Test-a-function new file mode 120000 index 0000000000..26229353b8 --- /dev/null +++ b/Lang/AutoHotkey/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Text-processing-1 b/Lang/AutoHotkey/Text-processing-1 new file mode 120000 index 0000000000..891d86b213 --- /dev/null +++ b/Lang/AutoHotkey/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Text-processing-2 b/Lang/AutoHotkey/Text-processing-2 new file mode 120000 index 0000000000..6513bfcec8 --- /dev/null +++ b/Lang/AutoHotkey/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Text-processing-Max-licenses-in-use b/Lang/AutoHotkey/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..e880e13fed --- /dev/null +++ b/Lang/AutoHotkey/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Tic-tac-toe b/Lang/AutoHotkey/Tic-tac-toe new file mode 120000 index 0000000000..a543e75d84 --- /dev/null +++ b/Lang/AutoHotkey/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Time-a-function b/Lang/AutoHotkey/Time-a-function new file mode 120000 index 0000000000..c9d1cb53f1 --- /dev/null +++ b/Lang/AutoHotkey/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Tokenize-a-string b/Lang/AutoHotkey/Tokenize-a-string new file mode 120000 index 0000000000..82114c7490 --- /dev/null +++ b/Lang/AutoHotkey/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Top-rank-per-group b/Lang/AutoHotkey/Top-rank-per-group new file mode 120000 index 0000000000..465b323618 --- /dev/null +++ b/Lang/AutoHotkey/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Towers-of-Hanoi b/Lang/AutoHotkey/Towers-of-Hanoi new file mode 120000 index 0000000000..0c4190b163 --- /dev/null +++ b/Lang/AutoHotkey/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Tree-traversal b/Lang/AutoHotkey/Tree-traversal new file mode 120000 index 0000000000..609fa5922e --- /dev/null +++ b/Lang/AutoHotkey/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Trigonometric-functions b/Lang/AutoHotkey/Trigonometric-functions new file mode 120000 index 0000000000..315dca4123 --- /dev/null +++ b/Lang/AutoHotkey/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/URL-decoding b/Lang/AutoHotkey/URL-decoding new file mode 120000 index 0000000000..5a7b216f6c --- /dev/null +++ b/Lang/AutoHotkey/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/URL-encoding b/Lang/AutoHotkey/URL-encoding new file mode 120000 index 0000000000..b6381aba3f --- /dev/null +++ b/Lang/AutoHotkey/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Unbias-a-random-generator b/Lang/AutoHotkey/Unbias-a-random-generator new file mode 120000 index 0000000000..2b5be42148 --- /dev/null +++ b/Lang/AutoHotkey/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Unicode-variable-names b/Lang/AutoHotkey/Unicode-variable-names new file mode 120000 index 0000000000..1cc050cd5e --- /dev/null +++ b/Lang/AutoHotkey/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Update-a-configuration-file b/Lang/AutoHotkey/Update-a-configuration-file new file mode 120000 index 0000000000..2b68dfa0d3 --- /dev/null +++ b/Lang/AutoHotkey/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Use-another-language-to-call-a-function b/Lang/AutoHotkey/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..d58edd77d8 --- /dev/null +++ b/Lang/AutoHotkey/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/User-input-Graphical b/Lang/AutoHotkey/User-input-Graphical new file mode 120000 index 0000000000..9b7ffef87a --- /dev/null +++ b/Lang/AutoHotkey/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/User-input-Text b/Lang/AutoHotkey/User-input-Text new file mode 120000 index 0000000000..0f861304a1 --- /dev/null +++ b/Lang/AutoHotkey/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Variable-size-Get b/Lang/AutoHotkey/Variable-size-Get new file mode 120000 index 0000000000..35fc64f085 --- /dev/null +++ b/Lang/AutoHotkey/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Variables b/Lang/AutoHotkey/Variables new file mode 120000 index 0000000000..965b488cd5 --- /dev/null +++ b/Lang/AutoHotkey/Variables @@ -0,0 +1 @@ +../../Task/Variables/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Variadic-function b/Lang/AutoHotkey/Variadic-function new file mode 120000 index 0000000000..1a9d2a8c98 --- /dev/null +++ b/Lang/AutoHotkey/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Verify-distribution-uniformity-Naive b/Lang/AutoHotkey/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..88f2a016fb --- /dev/null +++ b/Lang/AutoHotkey/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Vigen-re-cipher b/Lang/AutoHotkey/Vigen-re-cipher new file mode 120000 index 0000000000..f63ad50bcd --- /dev/null +++ b/Lang/AutoHotkey/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Walk-a-directory-Non-recursively b/Lang/AutoHotkey/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..7ad191102c --- /dev/null +++ b/Lang/AutoHotkey/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Walk-a-directory-Recursively b/Lang/AutoHotkey/Walk-a-directory-Recursively new file mode 120000 index 0000000000..776a8dee4c --- /dev/null +++ b/Lang/AutoHotkey/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Web-scraping b/Lang/AutoHotkey/Web-scraping new file mode 120000 index 0000000000..bf0fbf5fea --- /dev/null +++ b/Lang/AutoHotkey/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Window-creation b/Lang/AutoHotkey/Window-creation new file mode 120000 index 0000000000..511461d431 --- /dev/null +++ b/Lang/AutoHotkey/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Window-management b/Lang/AutoHotkey/Window-management new file mode 120000 index 0000000000..0efb87f6d2 --- /dev/null +++ b/Lang/AutoHotkey/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/XML-DOM-serialization b/Lang/AutoHotkey/XML-DOM-serialization new file mode 120000 index 0000000000..24ab9b1a46 --- /dev/null +++ b/Lang/AutoHotkey/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/XML-Input b/Lang/AutoHotkey/XML-Input new file mode 120000 index 0000000000..782f8fc6c3 --- /dev/null +++ b/Lang/AutoHotkey/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/XML-Output b/Lang/AutoHotkey/XML-Output new file mode 120000 index 0000000000..4174b234a2 --- /dev/null +++ b/Lang/AutoHotkey/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/XML-XPath b/Lang/AutoHotkey/XML-XPath new file mode 120000 index 0000000000..eb78c1732f --- /dev/null +++ b/Lang/AutoHotkey/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Yahoo--search-interface b/Lang/AutoHotkey/Yahoo--search-interface new file mode 120000 index 0000000000..551bba2852 --- /dev/null +++ b/Lang/AutoHotkey/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Yin-and-yang b/Lang/AutoHotkey/Yin-and-yang new file mode 120000 index 0000000000..b4df4beb91 --- /dev/null +++ b/Lang/AutoHotkey/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Zig-zag-matrix b/Lang/AutoHotkey/Zig-zag-matrix new file mode 120000 index 0000000000..2538318992 --- /dev/null +++ b/Lang/AutoHotkey/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/Sieve-of-Eratosthenes b/Lang/AutoIt/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..45e53c2e3f --- /dev/null +++ b/Lang/AutoIt/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Simulate-input-Keyboard b/Lang/AutoIt/Simulate-input-Keyboard new file mode 120000 index 0000000000..a7f4a91ad7 --- /dev/null +++ b/Lang/AutoIt/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Sleep b/Lang/AutoIt/Sleep new file mode 120000 index 0000000000..14cb933bf5 --- /dev/null +++ b/Lang/AutoIt/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/String-case b/Lang/AutoIt/String-case new file mode 120000 index 0000000000..df8d670176 --- /dev/null +++ b/Lang/AutoIt/String-case @@ -0,0 +1 @@ +../../Task/String-case/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Strip-comments-from-a-string b/Lang/AutoIt/Strip-comments-from-a-string new file mode 120000 index 0000000000..977d3d8d14 --- /dev/null +++ b/Lang/AutoIt/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/System-time b/Lang/AutoIt/System-time new file mode 120000 index 0000000000..87bca18681 --- /dev/null +++ b/Lang/AutoIt/System-time @@ -0,0 +1 @@ +../../Task/System-time/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Towers-of-Hanoi b/Lang/AutoIt/Towers-of-Hanoi new file mode 120000 index 0000000000..e06f29c657 --- /dev/null +++ b/Lang/AutoIt/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Trabb-Pardo-Knuth-algorithm b/Lang/AutoIt/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..4a741301b5 --- /dev/null +++ b/Lang/AutoIt/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Window-creation b/Lang/AutoIt/Window-creation new file mode 120000 index 0000000000..54c43d57f8 --- /dev/null +++ b/Lang/AutoIt/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Wireworld b/Lang/AutoIt/Wireworld new file mode 120000 index 0000000000..24b3bb4f4c --- /dev/null +++ b/Lang/AutoIt/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Zeckendorf-number-representation b/Lang/AutoIt/Zeckendorf-number-representation new file mode 120000 index 0000000000..b0e79d4ef9 --- /dev/null +++ b/Lang/AutoIt/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Zig-zag-matrix b/Lang/AutoIt/Zig-zag-matrix new file mode 120000 index 0000000000..b86f19a53d --- /dev/null +++ b/Lang/AutoIt/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/AutoIt \ No newline at end of file diff --git a/Lang/Axiom/Standard-deviation b/Lang/Axiom/Standard-deviation new file mode 120000 index 0000000000..c8209d2dc3 --- /dev/null +++ b/Lang/Axiom/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Axiom \ No newline at end of file diff --git a/Lang/BASIC/Shell-one-liner b/Lang/BASIC/Shell-one-liner new file mode 120000 index 0000000000..2f490286c5 --- /dev/null +++ b/Lang/BASIC/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sierpinski-triangle b/Lang/BASIC/Sierpinski-triangle new file mode 120000 index 0000000000..8f7251cf74 --- /dev/null +++ b/Lang/BASIC/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sieve-of-Eratosthenes b/Lang/BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9c44c5ad2c --- /dev/null +++ b/Lang/BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sleep b/Lang/BASIC/Sleep new file mode 120000 index 0000000000..37e5da9bd1 --- /dev/null +++ b/Lang/BASIC/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Bubble-sort b/Lang/BASIC/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ab0beeb396 --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Gnome-sort b/Lang/BASIC/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..ce27855f21 --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Insertion-sort b/Lang/BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..6a616f03ed --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Pancake-sort b/Lang/BASIC/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..b376f380f9 --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Quicksort b/Lang/BASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f7976ecb9f --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Stooge-sort b/Lang/BASIC/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..8bbb429644 --- /dev/null +++ b/Lang/BASIC/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Stair-climbing-puzzle b/Lang/BASIC/Stair-climbing-puzzle new file mode 120000 index 0000000000..67b9c2307c --- /dev/null +++ b/Lang/BASIC/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-case b/Lang/BASIC/String-case new file mode 120000 index 0000000000..d8339e2420 --- /dev/null +++ b/Lang/BASIC/String-case @@ -0,0 +1 @@ +../../Task/String-case/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-comparison b/Lang/BASIC/String-comparison new file mode 120000 index 0000000000..e2662fa496 --- /dev/null +++ b/Lang/BASIC/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-concatenation b/Lang/BASIC/String-concatenation new file mode 120000 index 0000000000..27a1d444ea --- /dev/null +++ b/Lang/BASIC/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/BASIC \ No newline at end of file diff --git a/Lang/BASIC/String-length b/Lang/BASIC/String-length new file mode 120000 index 0000000000..e5cf631fcf --- /dev/null +++ b/Lang/BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Strip-a-set-of-characters-from-a-string b/Lang/BASIC/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..0401cfc39d --- /dev/null +++ b/Lang/BASIC/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Strip-control-codes-and-extended-characters-from-a-string b/Lang/BASIC/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..47adb67270 --- /dev/null +++ b/Lang/BASIC/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..720620f08f --- /dev/null +++ b/Lang/BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Substring b/Lang/BASIC/Substring new file mode 120000 index 0000000000..1144234268 --- /dev/null +++ b/Lang/BASIC/Substring @@ -0,0 +1 @@ +../../Task/Substring/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Substring-Top-and-tail b/Lang/BASIC/Substring-Top-and-tail new file mode 120000 index 0000000000..feb32fbc58 --- /dev/null +++ b/Lang/BASIC/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sum-and-product-of-an-array b/Lang/BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..300e7cb142 --- /dev/null +++ b/Lang/BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sum-of-a-series b/Lang/BASIC/Sum-of-a-series new file mode 120000 index 0000000000..dad8960b87 --- /dev/null +++ b/Lang/BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sum-of-squares b/Lang/BASIC/Sum-of-squares new file mode 120000 index 0000000000..92fd5cac42 --- /dev/null +++ b/Lang/BASIC/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/BASIC \ No newline at end of file diff --git a/Lang/BASIC/System-time b/Lang/BASIC/System-time new file mode 120000 index 0000000000..74583c93c3 --- /dev/null +++ b/Lang/BASIC/System-time @@ -0,0 +1 @@ +../../Task/System-time/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Take-notes-on-the-command-line b/Lang/BASIC/Take-notes-on-the-command-line new file mode 120000 index 0000000000..6ead233623 --- /dev/null +++ b/Lang/BASIC/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Temperature-conversion b/Lang/BASIC/Temperature-conversion new file mode 120000 index 0000000000..21182b0539 --- /dev/null +++ b/Lang/BASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Clear-the-screen b/Lang/BASIC/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..edff259bed --- /dev/null +++ b/Lang/BASIC/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Coloured-text b/Lang/BASIC/Terminal-control-Coloured-text new file mode 120000 index 0000000000..0beaefc24c --- /dev/null +++ b/Lang/BASIC/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Cursor-movement b/Lang/BASIC/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..db00429aa9 --- /dev/null +++ b/Lang/BASIC/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Cursor-positioning b/Lang/BASIC/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..70b7850c39 --- /dev/null +++ b/Lang/BASIC/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Display-an-extended-character b/Lang/BASIC/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..4c2cd532be --- /dev/null +++ b/Lang/BASIC/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Hiding-the-cursor b/Lang/BASIC/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..54aaa7134b --- /dev/null +++ b/Lang/BASIC/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Inverse-video b/Lang/BASIC/Terminal-control-Inverse-video new file mode 120000 index 0000000000..45d4bdec33 --- /dev/null +++ b/Lang/BASIC/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Positional-read b/Lang/BASIC/Terminal-control-Positional-read new file mode 120000 index 0000000000..a8e641a048 --- /dev/null +++ b/Lang/BASIC/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Terminal-control-Ringing-the-terminal-bell b/Lang/BASIC/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..69ae2e7250 --- /dev/null +++ b/Lang/BASIC/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Time-a-function b/Lang/BASIC/Time-a-function new file mode 120000 index 0000000000..51915fd1a3 --- /dev/null +++ b/Lang/BASIC/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Tokenize-a-string b/Lang/BASIC/Tokenize-a-string new file mode 120000 index 0000000000..013825e398 --- /dev/null +++ b/Lang/BASIC/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Towers-of-Hanoi b/Lang/BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..68c4b20603 --- /dev/null +++ b/Lang/BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Trigonometric-functions b/Lang/BASIC/Trigonometric-functions new file mode 120000 index 0000000000..cd1b111724 --- /dev/null +++ b/Lang/BASIC/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Truncate-a-file b/Lang/BASIC/Truncate-a-file new file mode 120000 index 0000000000..dd5f3a64d4 --- /dev/null +++ b/Lang/BASIC/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/BASIC \ No newline at end of file diff --git a/Lang/BASIC/User-input-Text b/Lang/BASIC/User-input-Text new file mode 120000 index 0000000000..9d09c777c9 --- /dev/null +++ b/Lang/BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Variable-size-Get b/Lang/BASIC/Variable-size-Get new file mode 120000 index 0000000000..35600ae59c --- /dev/null +++ b/Lang/BASIC/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Variable-size-Set b/Lang/BASIC/Variable-size-Set new file mode 120000 index 0000000000..134658a68b --- /dev/null +++ b/Lang/BASIC/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Variables b/Lang/BASIC/Variables new file mode 120000 index 0000000000..2fb1cde3c7 --- /dev/null +++ b/Lang/BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Variadic-function b/Lang/BASIC/Variadic-function new file mode 120000 index 0000000000..605757d13a --- /dev/null +++ b/Lang/BASIC/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Walk-a-directory-Non-recursively b/Lang/BASIC/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..492afe81bc --- /dev/null +++ b/Lang/BASIC/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/BASIC \ No newline at end of file diff --git a/Lang/BASIC/XML-Output b/Lang/BASIC/XML-Output new file mode 120000 index 0000000000..86ab5d9c9f --- /dev/null +++ b/Lang/BASIC/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Sorting-algorithms-Bubble-sort b/Lang/BASIC256/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ae00ba7a43 --- /dev/null +++ b/Lang/BASIC256/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Speech-synthesis b/Lang/BASIC256/Speech-synthesis new file mode 120000 index 0000000000..11a4656157 --- /dev/null +++ b/Lang/BASIC256/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Towers-of-Hanoi b/Lang/BASIC256/Towers-of-Hanoi new file mode 120000 index 0000000000..96f476207e --- /dev/null +++ b/Lang/BASIC256/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Trabb-Pardo-Knuth-algorithm b/Lang/BASIC256/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..4cf8658399 --- /dev/null +++ b/Lang/BASIC256/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Vector-products b/Lang/BASIC256/Vector-products new file mode 120000 index 0000000000..05ba50269f --- /dev/null +++ b/Lang/BASIC256/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/SHA-1 b/Lang/BBC-BASIC/SHA-1 new file mode 120000 index 0000000000..5db36581b3 --- /dev/null +++ b/Lang/BBC-BASIC/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/SHA-256 b/Lang/BBC-BASIC/SHA-256 new file mode 120000 index 0000000000..0452a49bf5 --- /dev/null +++ b/Lang/BBC-BASIC/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Seven-sided-dice-from-five-sided-dice b/Lang/BBC-BASIC/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..c7c3c2585e --- /dev/null +++ b/Lang/BBC-BASIC/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Short-circuit-evaluation b/Lang/BBC-BASIC/Short-circuit-evaluation new file mode 120000 index 0000000000..63271c5af9 --- /dev/null +++ b/Lang/BBC-BASIC/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Show-the-epoch b/Lang/BBC-BASIC/Show-the-epoch new file mode 120000 index 0000000000..d61295c610 --- /dev/null +++ b/Lang/BBC-BASIC/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sierpinski-carpet b/Lang/BBC-BASIC/Sierpinski-carpet new file mode 120000 index 0000000000..b5302ae042 --- /dev/null +++ b/Lang/BBC-BASIC/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sierpinski-triangle b/Lang/BBC-BASIC/Sierpinski-triangle new file mode 120000 index 0000000000..bc0fc7864a --- /dev/null +++ b/Lang/BBC-BASIC/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sierpinski-triangle-Graphical b/Lang/BBC-BASIC/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..576bf5ebae --- /dev/null +++ b/Lang/BBC-BASIC/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sieve-of-Eratosthenes b/Lang/BBC-BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..6818c31bf6 --- /dev/null +++ b/Lang/BBC-BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Simple-windowed-application b/Lang/BBC-BASIC/Simple-windowed-application new file mode 120000 index 0000000000..185b07f252 --- /dev/null +++ b/Lang/BBC-BASIC/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Singly-linked-list-Element-definition b/Lang/BBC-BASIC/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..e0adffa07b --- /dev/null +++ b/Lang/BBC-BASIC/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Singly-linked-list-Element-insertion b/Lang/BBC-BASIC/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..fd31493752 --- /dev/null +++ b/Lang/BBC-BASIC/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Singly-linked-list-Traversal b/Lang/BBC-BASIC/Singly-linked-list-Traversal new file mode 120000 index 0000000000..876e716697 --- /dev/null +++ b/Lang/BBC-BASIC/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sleep b/Lang/BBC-BASIC/Sleep new file mode 120000 index 0000000000..3fe18b7c10 --- /dev/null +++ b/Lang/BBC-BASIC/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sockets b/Lang/BBC-BASIC/Sockets new file mode 120000 index 0000000000..413afe1074 --- /dev/null +++ b/Lang/BBC-BASIC/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sort-an-array-of-composite-structures b/Lang/BBC-BASIC/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..8d11e81de2 --- /dev/null +++ b/Lang/BBC-BASIC/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sort-an-integer-array b/Lang/BBC-BASIC/Sort-an-integer-array new file mode 120000 index 0000000000..288e03d1e9 --- /dev/null +++ b/Lang/BBC-BASIC/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sort-disjoint-sublist b/Lang/BBC-BASIC/Sort-disjoint-sublist new file mode 120000 index 0000000000..f8e95cc910 --- /dev/null +++ b/Lang/BBC-BASIC/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Bogosort b/Lang/BBC-BASIC/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b2b2609fcd --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Bubble-sort b/Lang/BBC-BASIC/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..43e03b6afb --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Cocktail-sort b/Lang/BBC-BASIC/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..c6f779bf28 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Comb-sort b/Lang/BBC-BASIC/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..8cb6cdaae2 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Counting-sort b/Lang/BBC-BASIC/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..574a1081fe --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Gnome-sort b/Lang/BBC-BASIC/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..34af0d93d1 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Heapsort b/Lang/BBC-BASIC/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..f555877650 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Insertion-sort b/Lang/BBC-BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..51b4989391 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Merge-sort b/Lang/BBC-BASIC/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..acd65cd773 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Pancake-sort b/Lang/BBC-BASIC/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..1d5abd9478 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Permutation-sort b/Lang/BBC-BASIC/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..b19c4def0d --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Quicksort b/Lang/BBC-BASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..25fe30627d --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Radix-sort b/Lang/BBC-BASIC/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..d9c74ac7cc --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Selection-sort b/Lang/BBC-BASIC/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..e148b84fd8 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Shell-sort b/Lang/BBC-BASIC/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..a520e39b8c --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Sleep-sort b/Lang/BBC-BASIC/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..43eb00ff2a --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sorting-algorithms-Stooge-sort b/Lang/BBC-BASIC/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..533c20db92 --- /dev/null +++ b/Lang/BBC-BASIC/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Soundex b/Lang/BBC-BASIC/Soundex new file mode 120000 index 0000000000..d49b233b8c --- /dev/null +++ b/Lang/BBC-BASIC/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Speech-synthesis b/Lang/BBC-BASIC/Speech-synthesis new file mode 120000 index 0000000000..0c49e691be --- /dev/null +++ b/Lang/BBC-BASIC/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Spiral-matrix b/Lang/BBC-BASIC/Spiral-matrix new file mode 120000 index 0000000000..297c3e087e --- /dev/null +++ b/Lang/BBC-BASIC/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Stable-marriage-problem b/Lang/BBC-BASIC/Stable-marriage-problem new file mode 120000 index 0000000000..2a75ddfc2a --- /dev/null +++ b/Lang/BBC-BASIC/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Stack b/Lang/BBC-BASIC/Stack new file mode 120000 index 0000000000..92871d4aba --- /dev/null +++ b/Lang/BBC-BASIC/Stack @@ -0,0 +1 @@ +../../Task/Stack/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Stair-climbing-puzzle b/Lang/BBC-BASIC/Stair-climbing-puzzle new file mode 120000 index 0000000000..6f6e7a1eee --- /dev/null +++ b/Lang/BBC-BASIC/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Standard-deviation b/Lang/BBC-BASIC/Standard-deviation new file mode 120000 index 0000000000..688d2647a5 --- /dev/null +++ b/Lang/BBC-BASIC/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Stem-and-leaf-plot b/Lang/BBC-BASIC/Stem-and-leaf-plot new file mode 120000 index 0000000000..140e83938e --- /dev/null +++ b/Lang/BBC-BASIC/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-case b/Lang/BBC-BASIC/String-case new file mode 120000 index 0000000000..20f92949a8 --- /dev/null +++ b/Lang/BBC-BASIC/String-case @@ -0,0 +1 @@ +../../Task/String-case/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-concatenation b/Lang/BBC-BASIC/String-concatenation new file mode 120000 index 0000000000..5378d96200 --- /dev/null +++ b/Lang/BBC-BASIC/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/String-length b/Lang/BBC-BASIC/String-length new file mode 120000 index 0000000000..24b2a840a7 --- /dev/null +++ b/Lang/BBC-BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Strip-a-set-of-characters-from-a-string b/Lang/BBC-BASIC/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..7679ba6435 --- /dev/null +++ b/Lang/BBC-BASIC/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Strip-block-comments b/Lang/BBC-BASIC/Strip-block-comments new file mode 120000 index 0000000000..89eff6f1e0 --- /dev/null +++ b/Lang/BBC-BASIC/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Strip-comments-from-a-string b/Lang/BBC-BASIC/Strip-comments-from-a-string new file mode 120000 index 0000000000..29d0b7ae06 --- /dev/null +++ b/Lang/BBC-BASIC/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Strip-control-codes-and-extended-characters-from-a-string b/Lang/BBC-BASIC/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..c2ab9bc118 --- /dev/null +++ b/Lang/BBC-BASIC/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/BBC-BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..9d7c39c962 --- /dev/null +++ b/Lang/BBC-BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Substring b/Lang/BBC-BASIC/Substring new file mode 120000 index 0000000000..c9859403f8 --- /dev/null +++ b/Lang/BBC-BASIC/Substring @@ -0,0 +1 @@ +../../Task/Substring/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Substring-Top-and-tail b/Lang/BBC-BASIC/Substring-Top-and-tail new file mode 120000 index 0000000000..dcd0b8738b --- /dev/null +++ b/Lang/BBC-BASIC/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Subtractive-generator b/Lang/BBC-BASIC/Subtractive-generator new file mode 120000 index 0000000000..ce21a95a9b --- /dev/null +++ b/Lang/BBC-BASIC/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sudoku b/Lang/BBC-BASIC/Sudoku new file mode 120000 index 0000000000..d2f752c2bc --- /dev/null +++ b/Lang/BBC-BASIC/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sum-and-product-of-an-array b/Lang/BBC-BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..8519b933fd --- /dev/null +++ b/Lang/BBC-BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sum-digits-of-an-integer b/Lang/BBC-BASIC/Sum-digits-of-an-integer new file mode 120000 index 0000000000..7cbe303b5e --- /dev/null +++ b/Lang/BBC-BASIC/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sum-of-a-series b/Lang/BBC-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..fdc5e0e306 --- /dev/null +++ b/Lang/BBC-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sum-of-squares b/Lang/BBC-BASIC/Sum-of-squares new file mode 120000 index 0000000000..0261516477 --- /dev/null +++ b/Lang/BBC-BASIC/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Sutherland-Hodgman-polygon-clipping b/Lang/BBC-BASIC/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..fe28871949 --- /dev/null +++ b/Lang/BBC-BASIC/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Symmetric-difference b/Lang/BBC-BASIC/Symmetric-difference new file mode 120000 index 0000000000..94ddd67a58 --- /dev/null +++ b/Lang/BBC-BASIC/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/System-time b/Lang/BBC-BASIC/System-time new file mode 120000 index 0000000000..ba47807ab1 --- /dev/null +++ b/Lang/BBC-BASIC/System-time @@ -0,0 +1 @@ +../../Task/System-time/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Take-notes-on-the-command-line b/Lang/BBC-BASIC/Take-notes-on-the-command-line new file mode 120000 index 0000000000..f10b030540 --- /dev/null +++ b/Lang/BBC-BASIC/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Clear-the-screen b/Lang/BBC-BASIC/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..b912b9f8ee --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Coloured-text b/Lang/BBC-BASIC/Terminal-control-Coloured-text new file mode 120000 index 0000000000..41053bc599 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Cursor-movement b/Lang/BBC-BASIC/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..5197c293c1 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Cursor-positioning b/Lang/BBC-BASIC/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..2c8b634b75 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Dimensions b/Lang/BBC-BASIC/Terminal-control-Dimensions new file mode 120000 index 0000000000..b9a1ccc61c --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Display-an-extended-character b/Lang/BBC-BASIC/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..8326bd1204 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Hiding-the-cursor b/Lang/BBC-BASIC/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..38f94971a2 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Inverse-video b/Lang/BBC-BASIC/Terminal-control-Inverse-video new file mode 120000 index 0000000000..88bc50404a --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Positional-read b/Lang/BBC-BASIC/Terminal-control-Positional-read new file mode 120000 index 0000000000..fca47c8c97 --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Preserve-screen b/Lang/BBC-BASIC/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..44a32a3b1d --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Ringing-the-terminal-bell b/Lang/BBC-BASIC/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..e86465c53e --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Terminal-control-Unicode-output b/Lang/BBC-BASIC/Terminal-control-Unicode-output new file mode 120000 index 0000000000..b46fbab6dc --- /dev/null +++ b/Lang/BBC-BASIC/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Ternary-logic b/Lang/BBC-BASIC/Ternary-logic new file mode 120000 index 0000000000..ef85d48977 --- /dev/null +++ b/Lang/BBC-BASIC/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Text-processing-1 b/Lang/BBC-BASIC/Text-processing-1 new file mode 120000 index 0000000000..ee2db3b2f6 --- /dev/null +++ b/Lang/BBC-BASIC/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Text-processing-Max-licenses-in-use b/Lang/BBC-BASIC/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..243e6b34a4 --- /dev/null +++ b/Lang/BBC-BASIC/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Time-a-function b/Lang/BBC-BASIC/Time-a-function new file mode 120000 index 0000000000..99187bd4f7 --- /dev/null +++ b/Lang/BBC-BASIC/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Tokenize-a-string b/Lang/BBC-BASIC/Tokenize-a-string new file mode 120000 index 0000000000..d5a8e0be54 --- /dev/null +++ b/Lang/BBC-BASIC/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Towers-of-Hanoi b/Lang/BBC-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..c468b2278c --- /dev/null +++ b/Lang/BBC-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Trigonometric-functions b/Lang/BBC-BASIC/Trigonometric-functions new file mode 120000 index 0000000000..6b554e17df --- /dev/null +++ b/Lang/BBC-BASIC/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Truncate-a-file b/Lang/BBC-BASIC/Truncate-a-file new file mode 120000 index 0000000000..6001e1ae79 --- /dev/null +++ b/Lang/BBC-BASIC/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Twelve-statements b/Lang/BBC-BASIC/Twelve-statements new file mode 120000 index 0000000000..c0fd288909 --- /dev/null +++ b/Lang/BBC-BASIC/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/URL-decoding b/Lang/BBC-BASIC/URL-decoding new file mode 120000 index 0000000000..4e0973984e --- /dev/null +++ b/Lang/BBC-BASIC/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/URL-encoding b/Lang/BBC-BASIC/URL-encoding new file mode 120000 index 0000000000..0dfee463dd --- /dev/null +++ b/Lang/BBC-BASIC/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Unbias-a-random-generator b/Lang/BBC-BASIC/Unbias-a-random-generator new file mode 120000 index 0000000000..360ad9f5de --- /dev/null +++ b/Lang/BBC-BASIC/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Undefined-values b/Lang/BBC-BASIC/Undefined-values new file mode 120000 index 0000000000..3f5b7a71bb --- /dev/null +++ b/Lang/BBC-BASIC/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Unicode-strings b/Lang/BBC-BASIC/Unicode-strings new file mode 120000 index 0000000000..f7748b54de --- /dev/null +++ b/Lang/BBC-BASIC/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/User-input-Graphical b/Lang/BBC-BASIC/User-input-Graphical new file mode 120000 index 0000000000..8037f04f11 --- /dev/null +++ b/Lang/BBC-BASIC/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/User-input-Text b/Lang/BBC-BASIC/User-input-Text new file mode 120000 index 0000000000..679b57098b --- /dev/null +++ b/Lang/BBC-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Van-der-Corput-sequence b/Lang/BBC-BASIC/Van-der-Corput-sequence new file mode 120000 index 0000000000..d5d9b36a87 --- /dev/null +++ b/Lang/BBC-BASIC/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Variable-size-Get b/Lang/BBC-BASIC/Variable-size-Get new file mode 120000 index 0000000000..5a9736fa9c --- /dev/null +++ b/Lang/BBC-BASIC/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Variable-size-Set b/Lang/BBC-BASIC/Variable-size-Set new file mode 120000 index 0000000000..98e1965630 --- /dev/null +++ b/Lang/BBC-BASIC/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Variables b/Lang/BBC-BASIC/Variables new file mode 120000 index 0000000000..32b935f998 --- /dev/null +++ b/Lang/BBC-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Vector-products b/Lang/BBC-BASIC/Vector-products new file mode 120000 index 0000000000..8545e4fb47 --- /dev/null +++ b/Lang/BBC-BASIC/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Verify-distribution-uniformity-Naive b/Lang/BBC-BASIC/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..e79a765a62 --- /dev/null +++ b/Lang/BBC-BASIC/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Video-display-modes b/Lang/BBC-BASIC/Video-display-modes new file mode 120000 index 0000000000..790575b1d3 --- /dev/null +++ b/Lang/BBC-BASIC/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Vigen-re-cipher b/Lang/BBC-BASIC/Vigen-re-cipher new file mode 120000 index 0000000000..8cf13d2738 --- /dev/null +++ b/Lang/BBC-BASIC/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Visualize-a-tree b/Lang/BBC-BASIC/Visualize-a-tree new file mode 120000 index 0000000000..b48412eaf9 --- /dev/null +++ b/Lang/BBC-BASIC/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Walk-a-directory-Non-recursively b/Lang/BBC-BASIC/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..7dce752b42 --- /dev/null +++ b/Lang/BBC-BASIC/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Walk-a-directory-Recursively b/Lang/BBC-BASIC/Walk-a-directory-Recursively new file mode 120000 index 0000000000..7eb1327065 --- /dev/null +++ b/Lang/BBC-BASIC/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Web-scraping b/Lang/BBC-BASIC/Web-scraping new file mode 120000 index 0000000000..58ac17c379 --- /dev/null +++ b/Lang/BBC-BASIC/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Window-creation b/Lang/BBC-BASIC/Window-creation new file mode 120000 index 0000000000..66db38f4ff --- /dev/null +++ b/Lang/BBC-BASIC/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Window-management b/Lang/BBC-BASIC/Window-management new file mode 120000 index 0000000000..9176991b86 --- /dev/null +++ b/Lang/BBC-BASIC/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Wireworld b/Lang/BBC-BASIC/Wireworld new file mode 120000 index 0000000000..ad774b0ab4 --- /dev/null +++ b/Lang/BBC-BASIC/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Write-float-arrays-to-a-text-file b/Lang/BBC-BASIC/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..ab7247b67f --- /dev/null +++ b/Lang/BBC-BASIC/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII b/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..1a033b1706 --- /dev/null +++ b/Lang/BBC-BASIC/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Write-to-Windows-event-log b/Lang/BBC-BASIC/Write-to-Windows-event-log new file mode 120000 index 0000000000..f730eb3857 --- /dev/null +++ b/Lang/BBC-BASIC/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/XML-Input b/Lang/BBC-BASIC/XML-Input new file mode 120000 index 0000000000..cc1373a08f --- /dev/null +++ b/Lang/BBC-BASIC/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Xiaolin-Wus-line-algorithm b/Lang/BBC-BASIC/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..6e70bdbe1e --- /dev/null +++ b/Lang/BBC-BASIC/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Yin-and-yang b/Lang/BBC-BASIC/Yin-and-yang new file mode 120000 index 0000000000..5a4e05d4a5 --- /dev/null +++ b/Lang/BBC-BASIC/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Zebra-puzzle b/Lang/BBC-BASIC/Zebra-puzzle new file mode 120000 index 0000000000..eafa1840a5 --- /dev/null +++ b/Lang/BBC-BASIC/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Zeckendorf-number-representation b/Lang/BBC-BASIC/Zeckendorf-number-representation new file mode 120000 index 0000000000..52c852a334 --- /dev/null +++ b/Lang/BBC-BASIC/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Zig-zag-matrix b/Lang/BBC-BASIC/Zig-zag-matrix new file mode 120000 index 0000000000..b465701034 --- /dev/null +++ b/Lang/BBC-BASIC/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/BBC-BASIC \ No newline at end of file diff --git a/Lang/BCPL/Sorting-algorithms-Heapsort b/Lang/BCPL/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..c210478ea1 --- /dev/null +++ b/Lang/BCPL/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Sorting-algorithms-Quicksort b/Lang/BCPL/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ae63747d63 --- /dev/null +++ b/Lang/BCPL/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Sorting-algorithms-Shell-sort b/Lang/BCPL/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..70667ebf44 --- /dev/null +++ b/Lang/BCPL/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Sudoku b/Lang/BCPL/Sudoku new file mode 120000 index 0000000000..6377337803 --- /dev/null +++ b/Lang/BCPL/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Synchronous-concurrency b/Lang/BCPL/Synchronous-concurrency new file mode 120000 index 0000000000..09a77f7898 --- /dev/null +++ b/Lang/BCPL/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/BCPL \ No newline at end of file diff --git a/Lang/Babel/Stack b/Lang/Babel/Stack new file mode 120000 index 0000000000..dd54b1815f --- /dev/null +++ b/Lang/Babel/Stack @@ -0,0 +1 @@ +../../Task/Stack/Babel \ No newline at end of file diff --git a/Lang/Babel/Sum-and-product-of-an-array b/Lang/Babel/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9d8c3ea0af --- /dev/null +++ b/Lang/Babel/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Babel \ No newline at end of file diff --git a/Lang/Babel/Variable-size-Get b/Lang/Babel/Variable-size-Get new file mode 120000 index 0000000000..51aaf747b4 --- /dev/null +++ b/Lang/Babel/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Babel \ No newline at end of file diff --git a/Lang/Batch-File/Sleep b/Lang/Batch-File/Sleep new file mode 120000 index 0000000000..d1639c91bd --- /dev/null +++ b/Lang/Batch-File/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Stack b/Lang/Batch-File/Stack new file mode 120000 index 0000000000..3423021bfc --- /dev/null +++ b/Lang/Batch-File/Stack @@ -0,0 +1 @@ +../../Task/Stack/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/String-concatenation b/Lang/Batch-File/String-concatenation new file mode 120000 index 0000000000..8773cd5bd6 --- /dev/null +++ b/Lang/Batch-File/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/String-interpolation--included- b/Lang/Batch-File/String-interpolation--included- new file mode 120000 index 0000000000..6efc4b2e5f --- /dev/null +++ b/Lang/Batch-File/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/String-length b/Lang/Batch-File/String-length new file mode 120000 index 0000000000..cb7d13c0f6 --- /dev/null +++ b/Lang/Batch-File/String-length @@ -0,0 +1 @@ +../../Task/String-length/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/System-time b/Lang/Batch-File/System-time new file mode 120000 index 0000000000..f418ab4858 --- /dev/null +++ b/Lang/Batch-File/System-time @@ -0,0 +1 @@ +../../Task/System-time/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Take-notes-on-the-command-line b/Lang/Batch-File/Take-notes-on-the-command-line new file mode 120000 index 0000000000..44f532eae3 --- /dev/null +++ b/Lang/Batch-File/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Clear-the-screen b/Lang/Batch-File/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..981aaf1b7e --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Text-processing-1 b/Lang/Batch-File/Text-processing-1 new file mode 120000 index 0000000000..bef55f62f4 --- /dev/null +++ b/Lang/Batch-File/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Tokenize-a-string b/Lang/Batch-File/Tokenize-a-string new file mode 120000 index 0000000000..0c1dac8a5e --- /dev/null +++ b/Lang/Batch-File/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/User-input-Text b/Lang/Batch-File/User-input-Text new file mode 120000 index 0000000000..9814922b7f --- /dev/null +++ b/Lang/Batch-File/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Walk-a-directory-Recursively b/Lang/Batch-File/Walk-a-directory-Recursively new file mode 120000 index 0000000000..8a338620e1 --- /dev/null +++ b/Lang/Batch-File/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Write-language-name-in-3D-ASCII b/Lang/Batch-File/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..7ba1fd7ed3 --- /dev/null +++ b/Lang/Batch-File/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/Sort-an-integer-array b/Lang/Befunge/Sort-an-integer-array new file mode 120000 index 0000000000..7ca6da69ec --- /dev/null +++ b/Lang/Befunge/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Befunge \ No newline at end of file diff --git a/Lang/Befunge/String-case b/Lang/Befunge/String-case new file mode 120000 index 0000000000..f3084bc77e --- /dev/null +++ b/Lang/Befunge/String-case @@ -0,0 +1 @@ +../../Task/String-case/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sum-and-product-of-an-array b/Lang/Befunge/Sum-and-product-of-an-array new file mode 120000 index 0000000000..512be15594 --- /dev/null +++ b/Lang/Befunge/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Ringing-the-terminal-bell b/Lang/Befunge/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b751d7a20d --- /dev/null +++ b/Lang/Befunge/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Befunge \ No newline at end of file diff --git a/Lang/Befunge/User-input-Text b/Lang/Befunge/User-input-Text new file mode 120000 index 0000000000..909cda6c54 --- /dev/null +++ b/Lang/Befunge/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Befunge \ No newline at end of file diff --git a/Lang/Blast/Terminal-control-Clear-the-screen b/Lang/Blast/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..c3590d49ec --- /dev/null +++ b/Lang/Blast/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Blast \ No newline at end of file diff --git a/Lang/Blast/Terminal-control-Cursor-positioning b/Lang/Blast/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..e1f05e7a42 --- /dev/null +++ b/Lang/Blast/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Blast \ No newline at end of file diff --git a/Lang/BlitzMax/Y-combinator b/Lang/BlitzMax/Y-combinator new file mode 120000 index 0000000000..0265609378 --- /dev/null +++ b/Lang/BlitzMax/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/BlitzMax \ No newline at end of file diff --git a/Lang/Bracmat/Sieve-of-Eratosthenes b/Lang/Bracmat/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..91078f2e80 --- /dev/null +++ b/Lang/Bracmat/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Singly-linked-list-Element-definition b/Lang/Bracmat/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1421987ea8 --- /dev/null +++ b/Lang/Bracmat/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sort-an-integer-array b/Lang/Bracmat/Sort-an-integer-array new file mode 120000 index 0000000000..cb001996f1 --- /dev/null +++ b/Lang/Bracmat/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Stable-marriage-problem b/Lang/Bracmat/Stable-marriage-problem new file mode 120000 index 0000000000..643835a2cd --- /dev/null +++ b/Lang/Bracmat/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Stack b/Lang/Bracmat/Stack new file mode 120000 index 0000000000..db5007753b --- /dev/null +++ b/Lang/Bracmat/Stack @@ -0,0 +1 @@ +../../Task/Stack/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-case b/Lang/Bracmat/String-case new file mode 120000 index 0000000000..d1c1f275ab --- /dev/null +++ b/Lang/Bracmat/String-case @@ -0,0 +1 @@ +../../Task/String-case/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-concatenation b/Lang/Bracmat/String-concatenation new file mode 120000 index 0000000000..b231baefc9 --- /dev/null +++ b/Lang/Bracmat/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-interpolation--included- b/Lang/Bracmat/String-interpolation--included- new file mode 120000 index 0000000000..fe281e485e --- /dev/null +++ b/Lang/Bracmat/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/String-length b/Lang/Bracmat/String-length new file mode 120000 index 0000000000..84435f4837 --- /dev/null +++ b/Lang/Bracmat/String-length @@ -0,0 +1 @@ +../../Task/String-length/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Strip-a-set-of-characters-from-a-string b/Lang/Bracmat/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..05616399fa --- /dev/null +++ b/Lang/Bracmat/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Bracmat/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..d744188a89 --- /dev/null +++ b/Lang/Bracmat/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Substring b/Lang/Bracmat/Substring new file mode 120000 index 0000000000..cf537a0a1c --- /dev/null +++ b/Lang/Bracmat/Substring @@ -0,0 +1 @@ +../../Task/Substring/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Substring-Top-and-tail b/Lang/Bracmat/Substring-Top-and-tail new file mode 120000 index 0000000000..be2e83c052 --- /dev/null +++ b/Lang/Bracmat/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Subtractive-generator b/Lang/Bracmat/Subtractive-generator new file mode 120000 index 0000000000..464e3ac55a --- /dev/null +++ b/Lang/Bracmat/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sudoku b/Lang/Bracmat/Sudoku new file mode 120000 index 0000000000..26e3361304 --- /dev/null +++ b/Lang/Bracmat/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Symmetric-difference b/Lang/Bracmat/Symmetric-difference new file mode 120000 index 0000000000..2b32e966d7 --- /dev/null +++ b/Lang/Bracmat/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Terminal-control-Clear-the-screen b/Lang/Bracmat/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..4cec56cb6a --- /dev/null +++ b/Lang/Bracmat/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Text-processing-Max-licenses-in-use b/Lang/Bracmat/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..1ef6226e43 --- /dev/null +++ b/Lang/Bracmat/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Tokenize-a-string b/Lang/Bracmat/Tokenize-a-string new file mode 120000 index 0000000000..63cf1d2e3e --- /dev/null +++ b/Lang/Bracmat/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Topological-sort b/Lang/Bracmat/Topological-sort new file mode 120000 index 0000000000..826838017f --- /dev/null +++ b/Lang/Bracmat/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Towers-of-Hanoi b/Lang/Bracmat/Towers-of-Hanoi new file mode 120000 index 0000000000..e818abf03e --- /dev/null +++ b/Lang/Bracmat/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Tree-traversal b/Lang/Bracmat/Tree-traversal new file mode 120000 index 0000000000..1a5cef0764 --- /dev/null +++ b/Lang/Bracmat/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/URL-decoding b/Lang/Bracmat/URL-decoding new file mode 120000 index 0000000000..a02d41a8da --- /dev/null +++ b/Lang/Bracmat/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/URL-encoding b/Lang/Bracmat/URL-encoding new file mode 120000 index 0000000000..8b841a60b8 --- /dev/null +++ b/Lang/Bracmat/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Y-combinator b/Lang/Bracmat/Y-combinator new file mode 120000 index 0000000000..f864abb8a5 --- /dev/null +++ b/Lang/Bracmat/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/Terminal-control-Ringing-the-terminal-bell b/Lang/Brainf---/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..6fca604544 --- /dev/null +++ b/Lang/Brainf---/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Brainf--- \ No newline at end of file diff --git a/Lang/Brat/Sorting-algorithms-Bogosort b/Lang/Brat/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..0089807ee9 --- /dev/null +++ b/Lang/Brat/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Brat \ No newline at end of file diff --git a/Lang/Brat/Stack b/Lang/Brat/Stack new file mode 120000 index 0000000000..f8c47026f3 --- /dev/null +++ b/Lang/Brat/Stack @@ -0,0 +1 @@ +../../Task/Stack/Brat \ No newline at end of file diff --git a/Lang/Brat/Sum-of-a-series b/Lang/Brat/Sum-of-a-series new file mode 120000 index 0000000000..41acd8cde7 --- /dev/null +++ b/Lang/Brat/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Brat \ No newline at end of file diff --git a/Lang/Brat/Sum-of-squares b/Lang/Brat/Sum-of-squares new file mode 120000 index 0000000000..e57d460434 --- /dev/null +++ b/Lang/Brat/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Brat \ No newline at end of file diff --git a/Lang/Brat/Test-a-function b/Lang/Brat/Test-a-function new file mode 120000 index 0000000000..d75a358904 --- /dev/null +++ b/Lang/Brat/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Brat \ No newline at end of file diff --git a/Lang/Burlesque/Shell-one-liner b/Lang/Burlesque/Shell-one-liner new file mode 120000 index 0000000000..be7d263cc6 --- /dev/null +++ b/Lang/Burlesque/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Sort-an-integer-array b/Lang/Burlesque/Sort-an-integer-array new file mode 120000 index 0000000000..bd12dbd0b1 --- /dev/null +++ b/Lang/Burlesque/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Sort-using-a-custom-comparator b/Lang/Burlesque/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..af7d5df465 --- /dev/null +++ b/Lang/Burlesque/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/String-case b/Lang/Burlesque/String-case new file mode 120000 index 0000000000..1762b035aa --- /dev/null +++ b/Lang/Burlesque/String-case @@ -0,0 +1 @@ +../../Task/String-case/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/String-comparison b/Lang/Burlesque/String-comparison new file mode 120000 index 0000000000..7a6de0dd12 --- /dev/null +++ b/Lang/Burlesque/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/String-concatenation b/Lang/Burlesque/String-concatenation new file mode 120000 index 0000000000..effa574a41 --- /dev/null +++ b/Lang/Burlesque/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Strip-a-set-of-characters-from-a-string b/Lang/Burlesque/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..07258a8bc4 --- /dev/null +++ b/Lang/Burlesque/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Burlesque/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..756f2f10af --- /dev/null +++ b/Lang/Burlesque/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Burlesque \ No newline at end of file diff --git a/Lang/C++/SHA-1 b/Lang/C++/SHA-1 new file mode 120000 index 0000000000..be1b5de6a1 --- /dev/null +++ b/Lang/C++/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/C++ \ No newline at end of file diff --git a/Lang/C++/Seven-sided-dice-from-five-sided-dice b/Lang/C++/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..c8dc890c4c --- /dev/null +++ b/Lang/C++/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/C++ \ No newline at end of file diff --git a/Lang/C++/Short-circuit-evaluation b/Lang/C++/Short-circuit-evaluation new file mode 120000 index 0000000000..893ddd2950 --- /dev/null +++ b/Lang/C++/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/C++ \ No newline at end of file diff --git a/Lang/C++/Show-the-epoch b/Lang/C++/Show-the-epoch new file mode 120000 index 0000000000..99edbaaa39 --- /dev/null +++ b/Lang/C++/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/C++ \ No newline at end of file diff --git a/Lang/C++/Sierpinski-triangle b/Lang/C++/Sierpinski-triangle new file mode 120000 index 0000000000..892666d10b --- /dev/null +++ b/Lang/C++/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/C++ \ No newline at end of file diff --git a/Lang/C++/Sieve-of-Eratosthenes b/Lang/C++/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2f6909c0af --- /dev/null +++ b/Lang/C++/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/C++ \ No newline at end of file diff --git a/Lang/C++/Simple-windowed-application b/Lang/C++/Simple-windowed-application new file mode 120000 index 0000000000..c62aa6419e --- /dev/null +++ b/Lang/C++/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/C++ \ No newline at end of file diff --git a/Lang/C++/Singleton b/Lang/C++/Singleton new file mode 120000 index 0000000000..3184fa57f2 --- /dev/null +++ b/Lang/C++/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/C++ \ No newline at end of file diff --git a/Lang/C++/Singly-linked-list-Element-definition b/Lang/C++/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..383fbc6338 --- /dev/null +++ b/Lang/C++/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/C++ \ No newline at end of file diff --git a/Lang/C++/Singly-linked-list-Element-insertion b/Lang/C++/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..c15de464dd --- /dev/null +++ b/Lang/C++/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/C++ \ No newline at end of file diff --git a/Lang/C++/Sleep b/Lang/C++/Sleep new file mode 120000 index 0000000000..2c42e8230a --- /dev/null +++ b/Lang/C++/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/C++ \ No newline at end of file diff --git a/Lang/C++/Sokoban b/Lang/C++/Sokoban new file mode 120000 index 0000000000..2230519219 --- /dev/null +++ b/Lang/C++/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/C++ \ No newline at end of file diff --git a/Lang/C++/Sort-an-array-of-composite-structures b/Lang/C++/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..d12155f0c4 --- /dev/null +++ b/Lang/C++/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/C++ \ No newline at end of file diff --git a/Lang/C++/Sort-an-integer-array b/Lang/C++/Sort-an-integer-array new file mode 120000 index 0000000000..3e0cf92ee9 --- /dev/null +++ b/Lang/C++/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/C++ \ No newline at end of file diff --git a/Lang/C++/Sort-disjoint-sublist b/Lang/C++/Sort-disjoint-sublist new file mode 120000 index 0000000000..66948be450 --- /dev/null +++ b/Lang/C++/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/C++ \ No newline at end of file diff --git a/Lang/C++/Sort-using-a-custom-comparator b/Lang/C++/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..104262d6c9 --- /dev/null +++ b/Lang/C++/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Bead-sort b/Lang/C++/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..a49d63d2ff --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Bogosort b/Lang/C++/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..ab739c2921 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Bubble-sort b/Lang/C++/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..961602eb1e --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Comb-sort b/Lang/C++/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..1b09cfc65b --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Gnome-sort b/Lang/C++/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..da2fa5f3de --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Heapsort b/Lang/C++/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..8dc632bcdb --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Insertion-sort b/Lang/C++/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..d20b259c79 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Merge-sort b/Lang/C++/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..41289468c3 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Pancake-sort b/Lang/C++/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..8dc37bb878 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Permutation-sort b/Lang/C++/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..854897f23c --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Quicksort b/Lang/C++/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f09ad38b10 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Radix-sort b/Lang/C++/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..54bbb80a97 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Selection-sort b/Lang/C++/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..61ee92688a --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Strand-sort b/Lang/C++/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..f259a88388 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Special-characters b/Lang/C++/Special-characters new file mode 120000 index 0000000000..de82b66f26 --- /dev/null +++ b/Lang/C++/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/C++ \ No newline at end of file diff --git a/Lang/C++/Spiral-matrix b/Lang/C++/Spiral-matrix new file mode 120000 index 0000000000..658173b9a3 --- /dev/null +++ b/Lang/C++/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/C++ \ No newline at end of file diff --git a/Lang/C++/Stable-marriage-problem b/Lang/C++/Stable-marriage-problem new file mode 120000 index 0000000000..37be01da15 --- /dev/null +++ b/Lang/C++/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Stack b/Lang/C++/Stack new file mode 120000 index 0000000000..3ffcca87ec --- /dev/null +++ b/Lang/C++/Stack @@ -0,0 +1 @@ +../../Task/Stack/C++ \ No newline at end of file diff --git a/Lang/C++/Stair-climbing-puzzle b/Lang/C++/Stair-climbing-puzzle new file mode 120000 index 0000000000..89918603cd --- /dev/null +++ b/Lang/C++/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/C++ \ No newline at end of file diff --git a/Lang/C++/Standard-deviation b/Lang/C++/Standard-deviation new file mode 120000 index 0000000000..ee435d2ebd --- /dev/null +++ b/Lang/C++/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/C++ \ No newline at end of file diff --git a/Lang/C++/Stem-and-leaf-plot b/Lang/C++/Stem-and-leaf-plot new file mode 120000 index 0000000000..2f484ae510 --- /dev/null +++ b/Lang/C++/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/C++ \ No newline at end of file diff --git a/Lang/C++/String-case b/Lang/C++/String-case new file mode 120000 index 0000000000..bcff54c822 --- /dev/null +++ b/Lang/C++/String-case @@ -0,0 +1 @@ +../../Task/String-case/C++ \ No newline at end of file diff --git a/Lang/C++/String-concatenation b/Lang/C++/String-concatenation new file mode 120000 index 0000000000..f945dbef4c --- /dev/null +++ b/Lang/C++/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/C++ \ No newline at end of file diff --git a/Lang/C++/String-interpolation--included- b/Lang/C++/String-interpolation--included- new file mode 120000 index 0000000000..c8718e26e5 --- /dev/null +++ b/Lang/C++/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/C++ \ No newline at end of file diff --git a/Lang/C++/String-length b/Lang/C++/String-length new file mode 120000 index 0000000000..3e1d45e5ed --- /dev/null +++ b/Lang/C++/String-length @@ -0,0 +1 @@ +../../Task/String-length/C++ \ No newline at end of file diff --git a/Lang/C++/Strip-a-set-of-characters-from-a-string b/Lang/C++/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a5d712e125 --- /dev/null +++ b/Lang/C++/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/C++ \ No newline at end of file diff --git a/Lang/C++/Strip-block-comments b/Lang/C++/Strip-block-comments new file mode 120000 index 0000000000..48982d0765 --- /dev/null +++ b/Lang/C++/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/C++ \ No newline at end of file diff --git a/Lang/C++/Strip-comments-from-a-string b/Lang/C++/Strip-comments-from-a-string new file mode 120000 index 0000000000..f3e681d874 --- /dev/null +++ b/Lang/C++/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/C++ \ No newline at end of file diff --git a/Lang/C++/Strip-control-codes-and-extended-characters-from-a-string b/Lang/C++/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..4a4fc78dda --- /dev/null +++ b/Lang/C++/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/C++ \ No newline at end of file diff --git a/Lang/C++/Strip-whitespace-from-a-string-Top-and-tail b/Lang/C++/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..88ef5492e8 --- /dev/null +++ b/Lang/C++/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/C++ \ No newline at end of file diff --git a/Lang/C++/Substring b/Lang/C++/Substring new file mode 120000 index 0000000000..63efc89874 --- /dev/null +++ b/Lang/C++/Substring @@ -0,0 +1 @@ +../../Task/Substring/C++ \ No newline at end of file diff --git a/Lang/C++/Substring-Top-and-tail b/Lang/C++/Substring-Top-and-tail new file mode 120000 index 0000000000..c9badde93c --- /dev/null +++ b/Lang/C++/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/C++ \ No newline at end of file diff --git a/Lang/C++/Subtractive-generator b/Lang/C++/Subtractive-generator new file mode 120000 index 0000000000..bd8fe94e9f --- /dev/null +++ b/Lang/C++/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/C++ \ No newline at end of file diff --git a/Lang/C++/Sudoku b/Lang/C++/Sudoku new file mode 120000 index 0000000000..1a90ff18ab --- /dev/null +++ b/Lang/C++/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/C++ \ No newline at end of file diff --git a/Lang/C++/Sum-and-product-of-an-array b/Lang/C++/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5f48162e99 --- /dev/null +++ b/Lang/C++/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/C++ \ No newline at end of file diff --git a/Lang/C++/Sum-digits-of-an-integer b/Lang/C++/Sum-digits-of-an-integer new file mode 120000 index 0000000000..ed9cd2a923 --- /dev/null +++ b/Lang/C++/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/C++ \ No newline at end of file diff --git a/Lang/C++/Sum-of-a-series b/Lang/C++/Sum-of-a-series new file mode 120000 index 0000000000..6dd6d5bd86 --- /dev/null +++ b/Lang/C++/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/C++ \ No newline at end of file diff --git a/Lang/C++/Sum-of-squares b/Lang/C++/Sum-of-squares new file mode 120000 index 0000000000..1acde37482 --- /dev/null +++ b/Lang/C++/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/C++ \ No newline at end of file diff --git a/Lang/C++/Symmetric-difference b/Lang/C++/Symmetric-difference new file mode 120000 index 0000000000..180a3c6dd2 --- /dev/null +++ b/Lang/C++/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/C++ \ No newline at end of file diff --git a/Lang/C++/System-time b/Lang/C++/System-time new file mode 120000 index 0000000000..9cb5579f57 --- /dev/null +++ b/Lang/C++/System-time @@ -0,0 +1 @@ +../../Task/System-time/C++ \ No newline at end of file diff --git a/Lang/C++/Take-notes-on-the-command-line b/Lang/C++/Take-notes-on-the-command-line new file mode 120000 index 0000000000..b84269a427 --- /dev/null +++ b/Lang/C++/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/C++ \ No newline at end of file diff --git a/Lang/C++/Terminal-control-Display-an-extended-character b/Lang/C++/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..51cf799eb2 --- /dev/null +++ b/Lang/C++/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/C++ \ No newline at end of file diff --git a/Lang/C++/Text-processing-1 b/Lang/C++/Text-processing-1 new file mode 120000 index 0000000000..99366deeea --- /dev/null +++ b/Lang/C++/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/C++ \ No newline at end of file diff --git a/Lang/C++/Text-processing-2 b/Lang/C++/Text-processing-2 new file mode 120000 index 0000000000..66ea6c36d2 --- /dev/null +++ b/Lang/C++/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/C++ \ No newline at end of file diff --git a/Lang/C++/Text-processing-Max-licenses-in-use b/Lang/C++/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..606da6b0b9 --- /dev/null +++ b/Lang/C++/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/C++ \ No newline at end of file diff --git a/Lang/C++/Time-a-function b/Lang/C++/Time-a-function new file mode 120000 index 0000000000..d92444af68 --- /dev/null +++ b/Lang/C++/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/C++ \ No newline at end of file diff --git a/Lang/C++/Tokenize-a-string b/Lang/C++/Tokenize-a-string new file mode 120000 index 0000000000..af4c203468 --- /dev/null +++ b/Lang/C++/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/C++ \ No newline at end of file diff --git a/Lang/C++/Top-rank-per-group b/Lang/C++/Top-rank-per-group new file mode 120000 index 0000000000..f3af2ee782 --- /dev/null +++ b/Lang/C++/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/C++ \ No newline at end of file diff --git a/Lang/C++/Towers-of-Hanoi b/Lang/C++/Towers-of-Hanoi new file mode 120000 index 0000000000..8e41edfa85 --- /dev/null +++ b/Lang/C++/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/C++ \ No newline at end of file diff --git a/Lang/C++/Trabb-Pardo-Knuth-algorithm b/Lang/C++/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..a23d3749d9 --- /dev/null +++ b/Lang/C++/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/C++ \ No newline at end of file diff --git a/Lang/C++/Tree-traversal b/Lang/C++/Tree-traversal new file mode 120000 index 0000000000..f6b7308119 --- /dev/null +++ b/Lang/C++/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/C++ \ No newline at end of file diff --git a/Lang/C++/Trigonometric-functions b/Lang/C++/Trigonometric-functions new file mode 120000 index 0000000000..dfe09f49b1 --- /dev/null +++ b/Lang/C++/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/C++ \ No newline at end of file diff --git a/Lang/C++/URL-decoding b/Lang/C++/URL-decoding new file mode 120000 index 0000000000..031b598b53 --- /dev/null +++ b/Lang/C++/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/C++ \ No newline at end of file diff --git a/Lang/C++/URL-encoding b/Lang/C++/URL-encoding new file mode 120000 index 0000000000..5ebd4aa375 --- /dev/null +++ b/Lang/C++/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/C++ \ No newline at end of file diff --git a/Lang/C++/User-input-Graphical b/Lang/C++/User-input-Graphical new file mode 120000 index 0000000000..ce72c42162 --- /dev/null +++ b/Lang/C++/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/C++ \ No newline at end of file diff --git a/Lang/C++/User-input-Text b/Lang/C++/User-input-Text new file mode 120000 index 0000000000..c167c35861 --- /dev/null +++ b/Lang/C++/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/C++ \ No newline at end of file diff --git a/Lang/C++/Vampire-number b/Lang/C++/Vampire-number new file mode 120000 index 0000000000..ac2e904317 --- /dev/null +++ b/Lang/C++/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/C++ \ No newline at end of file diff --git a/Lang/C++/Van-der-Corput-sequence b/Lang/C++/Van-der-Corput-sequence new file mode 120000 index 0000000000..50d5b5f573 --- /dev/null +++ b/Lang/C++/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/C++ \ No newline at end of file diff --git a/Lang/C++/Variable-size-Get b/Lang/C++/Variable-size-Get new file mode 120000 index 0000000000..d297d739bd --- /dev/null +++ b/Lang/C++/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/C++ \ No newline at end of file diff --git a/Lang/C++/Variable-size-Set b/Lang/C++/Variable-size-Set new file mode 120000 index 0000000000..5b19ad4163 --- /dev/null +++ b/Lang/C++/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/C++ \ No newline at end of file diff --git a/Lang/C++/Variables b/Lang/C++/Variables new file mode 120000 index 0000000000..7d4379138b --- /dev/null +++ b/Lang/C++/Variables @@ -0,0 +1 @@ +../../Task/Variables/C++ \ No newline at end of file diff --git a/Lang/C++/Variadic-function b/Lang/C++/Variadic-function new file mode 120000 index 0000000000..c1b9135629 --- /dev/null +++ b/Lang/C++/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/C++ \ No newline at end of file diff --git a/Lang/C++/Vector-products b/Lang/C++/Vector-products new file mode 120000 index 0000000000..633307037f --- /dev/null +++ b/Lang/C++/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/C++ \ No newline at end of file diff --git a/Lang/C++/Verify-distribution-uniformity-Naive b/Lang/C++/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..0183c8857c --- /dev/null +++ b/Lang/C++/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/C++ \ No newline at end of file diff --git a/Lang/C++/Vigen-re-cipher b/Lang/C++/Vigen-re-cipher new file mode 120000 index 0000000000..3fe2dbe6ea --- /dev/null +++ b/Lang/C++/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/C++ \ No newline at end of file diff --git a/Lang/C++/Vigen-re-cipher-Cryptanalysis b/Lang/C++/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..a60698d534 --- /dev/null +++ b/Lang/C++/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/C++ \ No newline at end of file diff --git a/Lang/C++/Walk-a-directory-Non-recursively b/Lang/C++/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..45c46c2c0a --- /dev/null +++ b/Lang/C++/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/C++ \ No newline at end of file diff --git a/Lang/C++/Walk-a-directory-Recursively b/Lang/C++/Walk-a-directory-Recursively new file mode 120000 index 0000000000..94893f8fba --- /dev/null +++ b/Lang/C++/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/C++ \ No newline at end of file diff --git a/Lang/C++/Web-scraping b/Lang/C++/Web-scraping new file mode 120000 index 0000000000..747074c721 --- /dev/null +++ b/Lang/C++/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/C++ \ No newline at end of file diff --git a/Lang/C++/Window-creation b/Lang/C++/Window-creation new file mode 120000 index 0000000000..af53fd6160 --- /dev/null +++ b/Lang/C++/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/C++ \ No newline at end of file diff --git a/Lang/C++/Wireworld b/Lang/C++/Wireworld new file mode 120000 index 0000000000..96badc824d --- /dev/null +++ b/Lang/C++/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/C++ \ No newline at end of file diff --git a/Lang/C++/Write-float-arrays-to-a-text-file b/Lang/C++/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..c7acd3c455 --- /dev/null +++ b/Lang/C++/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/C++ \ No newline at end of file diff --git a/Lang/C++/XML-Input b/Lang/C++/XML-Input new file mode 120000 index 0000000000..42e6c8aee8 --- /dev/null +++ b/Lang/C++/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/C++ \ No newline at end of file diff --git a/Lang/C++/XML-Output b/Lang/C++/XML-Output new file mode 120000 index 0000000000..0e16bcdd16 --- /dev/null +++ b/Lang/C++/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/C++ \ No newline at end of file diff --git a/Lang/C++/XML-XPath b/Lang/C++/XML-XPath new file mode 120000 index 0000000000..34fc630b1c --- /dev/null +++ b/Lang/C++/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/C++ \ No newline at end of file diff --git a/Lang/C++/Y-combinator b/Lang/C++/Y-combinator new file mode 120000 index 0000000000..05073e5cad --- /dev/null +++ b/Lang/C++/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/C++ \ No newline at end of file diff --git a/Lang/C++/Zeckendorf-arithmetic b/Lang/C++/Zeckendorf-arithmetic new file mode 120000 index 0000000000..19a4d00ac6 --- /dev/null +++ b/Lang/C++/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/C++ \ No newline at end of file diff --git a/Lang/C++/Zeckendorf-number-representation b/Lang/C++/Zeckendorf-number-representation new file mode 120000 index 0000000000..d7fd70e1fe --- /dev/null +++ b/Lang/C++/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/C++ \ No newline at end of file diff --git a/Lang/C++/Zig-zag-matrix b/Lang/C++/Zig-zag-matrix new file mode 120000 index 0000000000..5cc07a7645 --- /dev/null +++ b/Lang/C++/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/C++ \ No newline at end of file diff --git a/Lang/C-sharp/SHA-1 b/Lang/C-sharp/SHA-1 new file mode 120000 index 0000000000..4e236e6780 --- /dev/null +++ b/Lang/C-sharp/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/SHA-256 b/Lang/C-sharp/SHA-256 new file mode 120000 index 0000000000..2c1feb1c5b --- /dev/null +++ b/Lang/C-sharp/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Soundex b/Lang/C-sharp/Soundex new file mode 120000 index 0000000000..d1ebb9d966 --- /dev/null +++ b/Lang/C-sharp/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Strip-a-set-of-characters-from-a-string b/Lang/C-sharp/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..dd4534cde2 --- /dev/null +++ b/Lang/C-sharp/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Substring-Top-and-tail b/Lang/C-sharp/Substring-Top-and-tail new file mode 120000 index 0000000000..37fef94891 --- /dev/null +++ b/Lang/C-sharp/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Terminal-control-Display-an-extended-character b/Lang/C-sharp/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..c0a1541fcc --- /dev/null +++ b/Lang/C-sharp/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Test-a-function b/Lang/C-sharp/Test-a-function new file mode 120000 index 0000000000..39f186c1f4 --- /dev/null +++ b/Lang/C-sharp/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tic-tac-toe b/Lang/C-sharp/Tic-tac-toe new file mode 120000 index 0000000000..57b5b0ad23 --- /dev/null +++ b/Lang/C-sharp/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tree-traversal b/Lang/C-sharp/Tree-traversal new file mode 120000 index 0000000000..322b308445 --- /dev/null +++ b/Lang/C-sharp/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Truncate-a-file b/Lang/C-sharp/Truncate-a-file new file mode 120000 index 0000000000..e9877c6ec2 --- /dev/null +++ b/Lang/C-sharp/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/URL-decoding b/Lang/C-sharp/URL-decoding new file mode 120000 index 0000000000..307ff7228a --- /dev/null +++ b/Lang/C-sharp/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/URL-encoding b/Lang/C-sharp/URL-encoding new file mode 120000 index 0000000000..815121a452 --- /dev/null +++ b/Lang/C-sharp/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Unbias-a-random-generator b/Lang/C-sharp/Unbias-a-random-generator new file mode 120000 index 0000000000..a2d5f03fe0 --- /dev/null +++ b/Lang/C-sharp/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Word-wrap b/Lang/C-sharp/Word-wrap new file mode 120000 index 0000000000..12046279fc --- /dev/null +++ b/Lang/C-sharp/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Write-to-Windows-event-log b/Lang/C-sharp/Write-to-Windows-event-log new file mode 120000 index 0000000000..fede15eb59 --- /dev/null +++ b/Lang/C-sharp/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/XML-DOM-serialization b/Lang/C-sharp/XML-DOM-serialization new file mode 120000 index 0000000000..06f3c966b6 --- /dev/null +++ b/Lang/C-sharp/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/XML-Input b/Lang/C-sharp/XML-Input new file mode 120000 index 0000000000..b6a84cd79c --- /dev/null +++ b/Lang/C-sharp/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/XML-Output b/Lang/C-sharp/XML-Output new file mode 120000 index 0000000000..8b4b03af3e --- /dev/null +++ b/Lang/C-sharp/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/XML-XPath b/Lang/C-sharp/XML-XPath new file mode 120000 index 0000000000..b03e883ab4 --- /dev/null +++ b/Lang/C-sharp/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Yahoo--search-interface b/Lang/C-sharp/Yahoo--search-interface new file mode 120000 index 0000000000..2b2a13c482 --- /dev/null +++ b/Lang/C-sharp/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Zig-zag-matrix b/Lang/C-sharp/Zig-zag-matrix new file mode 120000 index 0000000000..6a47491969 --- /dev/null +++ b/Lang/C-sharp/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/C-sharp \ No newline at end of file diff --git a/Lang/C/SHA-1 b/Lang/C/SHA-1 new file mode 120000 index 0000000000..3cda719f83 --- /dev/null +++ b/Lang/C/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/C \ No newline at end of file diff --git a/Lang/C/SHA-256 b/Lang/C/SHA-256 new file mode 120000 index 0000000000..d3967dbb5f --- /dev/null +++ b/Lang/C/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/C \ No newline at end of file diff --git a/Lang/C/SQL-based-authentication b/Lang/C/SQL-based-authentication new file mode 120000 index 0000000000..e4806bee08 --- /dev/null +++ b/Lang/C/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/C \ No newline at end of file diff --git a/Lang/C/Set-puzzle b/Lang/C/Set-puzzle new file mode 120000 index 0000000000..994ddfb2f8 --- /dev/null +++ b/Lang/C/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/C \ No newline at end of file diff --git a/Lang/C/Seven-sided-dice-from-five-sided-dice b/Lang/C/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..fc400a1e47 --- /dev/null +++ b/Lang/C/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/C \ No newline at end of file diff --git a/Lang/C/Shell-one-liner b/Lang/C/Shell-one-liner new file mode 120000 index 0000000000..f101db57ff --- /dev/null +++ b/Lang/C/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/C \ No newline at end of file diff --git a/Lang/C/Short-circuit-evaluation b/Lang/C/Short-circuit-evaluation new file mode 120000 index 0000000000..d8383d82c0 --- /dev/null +++ b/Lang/C/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/C \ No newline at end of file diff --git a/Lang/C/Show-the-epoch b/Lang/C/Show-the-epoch new file mode 120000 index 0000000000..3086f81221 --- /dev/null +++ b/Lang/C/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/C \ No newline at end of file diff --git a/Lang/C/Sierpinski-carpet b/Lang/C/Sierpinski-carpet new file mode 120000 index 0000000000..f117bafdab --- /dev/null +++ b/Lang/C/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/C \ No newline at end of file diff --git a/Lang/C/Sierpinski-triangle b/Lang/C/Sierpinski-triangle new file mode 120000 index 0000000000..58603a07a7 --- /dev/null +++ b/Lang/C/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/C \ No newline at end of file diff --git a/Lang/C/Sierpinski-triangle-Graphical b/Lang/C/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..57e337d753 --- /dev/null +++ b/Lang/C/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/C \ No newline at end of file diff --git a/Lang/C/Sieve-of-Eratosthenes b/Lang/C/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..3cc8603afb --- /dev/null +++ b/Lang/C/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/C \ No newline at end of file diff --git a/Lang/C/Simple-database b/Lang/C/Simple-database new file mode 120000 index 0000000000..b047e2e79a --- /dev/null +++ b/Lang/C/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/C \ No newline at end of file diff --git a/Lang/C/Simple-windowed-application b/Lang/C/Simple-windowed-application new file mode 120000 index 0000000000..63516beb6c --- /dev/null +++ b/Lang/C/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/C \ No newline at end of file diff --git a/Lang/C/Simulate-input-Keyboard b/Lang/C/Simulate-input-Keyboard new file mode 120000 index 0000000000..6c38de056b --- /dev/null +++ b/Lang/C/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/C \ No newline at end of file diff --git a/Lang/C/Singleton b/Lang/C/Singleton new file mode 120000 index 0000000000..7cc0d437d5 --- /dev/null +++ b/Lang/C/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/C \ No newline at end of file diff --git a/Lang/C/Singly-linked-list-Element-definition b/Lang/C/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..b7ddf077ed --- /dev/null +++ b/Lang/C/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/C \ No newline at end of file diff --git a/Lang/C/Singly-linked-list-Element-insertion b/Lang/C/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..3a677f067e --- /dev/null +++ b/Lang/C/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/C \ No newline at end of file diff --git a/Lang/C/Singly-linked-list-Traversal b/Lang/C/Singly-linked-list-Traversal new file mode 120000 index 0000000000..46bbf99a1b --- /dev/null +++ b/Lang/C/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/C \ No newline at end of file diff --git a/Lang/C/Sleep b/Lang/C/Sleep new file mode 120000 index 0000000000..efdbd2429d --- /dev/null +++ b/Lang/C/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/C \ No newline at end of file diff --git a/Lang/C/Sockets b/Lang/C/Sockets new file mode 120000 index 0000000000..9e36a5e9b0 --- /dev/null +++ b/Lang/C/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/C \ No newline at end of file diff --git a/Lang/C/Sokoban b/Lang/C/Sokoban new file mode 120000 index 0000000000..d67941bb33 --- /dev/null +++ b/Lang/C/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/C \ No newline at end of file diff --git a/Lang/C/Solve-a-Hidato-puzzle b/Lang/C/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..f640a5ac20 --- /dev/null +++ b/Lang/C/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/C \ No newline at end of file diff --git a/Lang/C/Sort-an-array-of-composite-structures b/Lang/C/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..ac8a94e97e --- /dev/null +++ b/Lang/C/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/C \ No newline at end of file diff --git a/Lang/C/Sort-an-integer-array b/Lang/C/Sort-an-integer-array new file mode 120000 index 0000000000..f70c7986ad --- /dev/null +++ b/Lang/C/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/C \ No newline at end of file diff --git a/Lang/C/Sort-disjoint-sublist b/Lang/C/Sort-disjoint-sublist new file mode 120000 index 0000000000..e3c6d71f69 --- /dev/null +++ b/Lang/C/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/C \ No newline at end of file diff --git a/Lang/C/Sort-using-a-custom-comparator b/Lang/C/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..2ca9156ab0 --- /dev/null +++ b/Lang/C/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Bead-sort b/Lang/C/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..b7664af111 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Bogosort b/Lang/C/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..1d7c20325d --- /dev/null +++ b/Lang/C/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Bubble-sort b/Lang/C/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..da9bfcb2d4 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Cocktail-sort b/Lang/C/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..5f10931184 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Comb-sort b/Lang/C/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..bb4af215ea --- /dev/null +++ b/Lang/C/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Counting-sort b/Lang/C/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..fbc91ffc27 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Gnome-sort b/Lang/C/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..5cd889a1bb --- /dev/null +++ b/Lang/C/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Heapsort b/Lang/C/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..9f2bf37b43 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Insertion-sort b/Lang/C/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..ac892e5120 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Merge-sort b/Lang/C/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..617e2ecb11 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Pancake-sort b/Lang/C/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..a60743df9f --- /dev/null +++ b/Lang/C/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Permutation-sort b/Lang/C/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..62f25e7093 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Quicksort b/Lang/C/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..e0aa506d27 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Radix-sort b/Lang/C/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..6096888f85 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Selection-sort b/Lang/C/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..df00067ec4 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Shell-sort b/Lang/C/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..4dcef24c86 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Sleep-sort b/Lang/C/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..39898d66f0 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Stooge-sort b/Lang/C/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..e93946a3e1 --- /dev/null +++ b/Lang/C/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/C \ No newline at end of file diff --git a/Lang/C/Sorting-algorithms-Strand-sort b/Lang/C/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..60a6410b2d --- /dev/null +++ b/Lang/C/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/C \ No newline at end of file diff --git a/Lang/C/Soundex b/Lang/C/Soundex new file mode 120000 index 0000000000..155855e013 --- /dev/null +++ b/Lang/C/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/C \ No newline at end of file diff --git a/Lang/C/Special-variables b/Lang/C/Special-variables new file mode 120000 index 0000000000..ca3623a056 --- /dev/null +++ b/Lang/C/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/C \ No newline at end of file diff --git a/Lang/C/Speech-synthesis b/Lang/C/Speech-synthesis new file mode 120000 index 0000000000..e7bf0c4067 --- /dev/null +++ b/Lang/C/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/C \ No newline at end of file diff --git a/Lang/C/Spiral-matrix b/Lang/C/Spiral-matrix new file mode 120000 index 0000000000..d1baa39eda --- /dev/null +++ b/Lang/C/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/C \ No newline at end of file diff --git a/Lang/C/Stable-marriage-problem b/Lang/C/Stable-marriage-problem new file mode 120000 index 0000000000..ef8bdd465a --- /dev/null +++ b/Lang/C/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/C \ No newline at end of file diff --git a/Lang/C/Stack b/Lang/C/Stack new file mode 120000 index 0000000000..dd2241db69 --- /dev/null +++ b/Lang/C/Stack @@ -0,0 +1 @@ +../../Task/Stack/C \ No newline at end of file diff --git a/Lang/C/Stack-traces b/Lang/C/Stack-traces new file mode 120000 index 0000000000..522fc9be9f --- /dev/null +++ b/Lang/C/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/C \ No newline at end of file diff --git a/Lang/C/Stair-climbing-puzzle b/Lang/C/Stair-climbing-puzzle new file mode 120000 index 0000000000..8fcf869c0d --- /dev/null +++ b/Lang/C/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/C \ No newline at end of file diff --git a/Lang/C/Standard-deviation b/Lang/C/Standard-deviation new file mode 120000 index 0000000000..dacbf5a039 --- /dev/null +++ b/Lang/C/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/C \ No newline at end of file diff --git a/Lang/C/Stem-and-leaf-plot b/Lang/C/Stem-and-leaf-plot new file mode 120000 index 0000000000..4e3b630a2f --- /dev/null +++ b/Lang/C/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/C \ No newline at end of file diff --git a/Lang/C/String-case b/Lang/C/String-case new file mode 120000 index 0000000000..99042cdea0 --- /dev/null +++ b/Lang/C/String-case @@ -0,0 +1 @@ +../../Task/String-case/C \ No newline at end of file diff --git a/Lang/C/String-concatenation b/Lang/C/String-concatenation new file mode 120000 index 0000000000..f21a85ad56 --- /dev/null +++ b/Lang/C/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/C \ No newline at end of file diff --git a/Lang/C/String-interpolation--included- b/Lang/C/String-interpolation--included- new file mode 120000 index 0000000000..fb0dd0cc2a --- /dev/null +++ b/Lang/C/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/C \ No newline at end of file diff --git a/Lang/C/String-length b/Lang/C/String-length new file mode 120000 index 0000000000..8c30e7bcd0 --- /dev/null +++ b/Lang/C/String-length @@ -0,0 +1 @@ +../../Task/String-length/C \ No newline at end of file diff --git a/Lang/C/Strip-a-set-of-characters-from-a-string b/Lang/C/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..e44daca65b --- /dev/null +++ b/Lang/C/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/C \ No newline at end of file diff --git a/Lang/C/Strip-block-comments b/Lang/C/Strip-block-comments new file mode 120000 index 0000000000..9f1ba5feec --- /dev/null +++ b/Lang/C/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/C \ No newline at end of file diff --git a/Lang/C/Strip-comments-from-a-string b/Lang/C/Strip-comments-from-a-string new file mode 120000 index 0000000000..2b41e3c3de --- /dev/null +++ b/Lang/C/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/C \ No newline at end of file diff --git a/Lang/C/Strip-control-codes-and-extended-characters-from-a-string b/Lang/C/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..a4ae475c6c --- /dev/null +++ b/Lang/C/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/C \ No newline at end of file diff --git a/Lang/C/Strip-whitespace-from-a-string-Top-and-tail b/Lang/C/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..863d321f77 --- /dev/null +++ b/Lang/C/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/C \ No newline at end of file diff --git a/Lang/C/Substring b/Lang/C/Substring new file mode 120000 index 0000000000..196fc66e7d --- /dev/null +++ b/Lang/C/Substring @@ -0,0 +1 @@ +../../Task/Substring/C \ No newline at end of file diff --git a/Lang/C/Substring-Top-and-tail b/Lang/C/Substring-Top-and-tail new file mode 120000 index 0000000000..5100498858 --- /dev/null +++ b/Lang/C/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/C \ No newline at end of file diff --git a/Lang/C/Subtractive-generator b/Lang/C/Subtractive-generator new file mode 120000 index 0000000000..15b8c633ab --- /dev/null +++ b/Lang/C/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/C \ No newline at end of file diff --git a/Lang/C/Sudoku b/Lang/C/Sudoku new file mode 120000 index 0000000000..1ff5d9e03f --- /dev/null +++ b/Lang/C/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/C \ No newline at end of file diff --git a/Lang/C/Sum-and-product-of-an-array b/Lang/C/Sum-and-product-of-an-array new file mode 120000 index 0000000000..7d5f2af7fc --- /dev/null +++ b/Lang/C/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/C \ No newline at end of file diff --git a/Lang/C/Sum-digits-of-an-integer b/Lang/C/Sum-digits-of-an-integer new file mode 120000 index 0000000000..f08c62bbcf --- /dev/null +++ b/Lang/C/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/C \ No newline at end of file diff --git a/Lang/C/Sum-of-a-series b/Lang/C/Sum-of-a-series new file mode 120000 index 0000000000..fc03d5eb4b --- /dev/null +++ b/Lang/C/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/C \ No newline at end of file diff --git a/Lang/C/Sum-of-squares b/Lang/C/Sum-of-squares new file mode 120000 index 0000000000..d759be4fb2 --- /dev/null +++ b/Lang/C/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/C \ No newline at end of file diff --git a/Lang/C/Sutherland-Hodgman-polygon-clipping b/Lang/C/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..3a82638e39 --- /dev/null +++ b/Lang/C/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/C \ No newline at end of file diff --git a/Lang/C/Symmetric-difference b/Lang/C/Symmetric-difference new file mode 120000 index 0000000000..99b25155c2 --- /dev/null +++ b/Lang/C/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/C \ No newline at end of file diff --git a/Lang/C/Synchronous-concurrency b/Lang/C/Synchronous-concurrency new file mode 120000 index 0000000000..432b16c3f3 --- /dev/null +++ b/Lang/C/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/C \ No newline at end of file diff --git a/Lang/C/System-time b/Lang/C/System-time new file mode 120000 index 0000000000..5c5e72043a --- /dev/null +++ b/Lang/C/System-time @@ -0,0 +1 @@ +../../Task/System-time/C \ No newline at end of file diff --git a/Lang/C/Table-creation-Postal-addresses b/Lang/C/Table-creation-Postal-addresses new file mode 120000 index 0000000000..07ef83dbb3 --- /dev/null +++ b/Lang/C/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/C \ No newline at end of file diff --git a/Lang/C/Take-notes-on-the-command-line b/Lang/C/Take-notes-on-the-command-line new file mode 120000 index 0000000000..91393a144f --- /dev/null +++ b/Lang/C/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/C \ No newline at end of file diff --git a/Lang/C/Temperature-conversion b/Lang/C/Temperature-conversion new file mode 120000 index 0000000000..f54ef45fe1 --- /dev/null +++ b/Lang/C/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Clear-the-screen b/Lang/C/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..341f4cca60 --- /dev/null +++ b/Lang/C/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Coloured-text b/Lang/C/Terminal-control-Coloured-text new file mode 120000 index 0000000000..a1ea01bee4 --- /dev/null +++ b/Lang/C/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Cursor-positioning b/Lang/C/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..9ffe08de6f --- /dev/null +++ b/Lang/C/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Dimensions b/Lang/C/Terminal-control-Dimensions new file mode 120000 index 0000000000..b9b79501a1 --- /dev/null +++ b/Lang/C/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Display-an-extended-character b/Lang/C/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..ac4629b08c --- /dev/null +++ b/Lang/C/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Hiding-the-cursor b/Lang/C/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..6e296d27c4 --- /dev/null +++ b/Lang/C/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Inverse-video b/Lang/C/Terminal-control-Inverse-video new file mode 120000 index 0000000000..f8ce6c9c38 --- /dev/null +++ b/Lang/C/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Positional-read b/Lang/C/Terminal-control-Positional-read new file mode 120000 index 0000000000..a29dcd2189 --- /dev/null +++ b/Lang/C/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Preserve-screen b/Lang/C/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..54d3b48078 --- /dev/null +++ b/Lang/C/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Ringing-the-terminal-bell b/Lang/C/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..f56e77648d --- /dev/null +++ b/Lang/C/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/C \ No newline at end of file diff --git a/Lang/C/Terminal-control-Unicode-output b/Lang/C/Terminal-control-Unicode-output new file mode 120000 index 0000000000..7446810454 --- /dev/null +++ b/Lang/C/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/C \ No newline at end of file diff --git a/Lang/C/Ternary-logic b/Lang/C/Ternary-logic new file mode 120000 index 0000000000..8203cbc5c8 --- /dev/null +++ b/Lang/C/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/C \ No newline at end of file diff --git a/Lang/C/Test-a-function b/Lang/C/Test-a-function new file mode 120000 index 0000000000..8e0fbb37db --- /dev/null +++ b/Lang/C/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/C \ No newline at end of file diff --git a/Lang/C/Text-processing-1 b/Lang/C/Text-processing-1 new file mode 120000 index 0000000000..01b29a5138 --- /dev/null +++ b/Lang/C/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/C \ No newline at end of file diff --git a/Lang/C/Text-processing-2 b/Lang/C/Text-processing-2 new file mode 120000 index 0000000000..4011f9738f --- /dev/null +++ b/Lang/C/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/C \ No newline at end of file diff --git a/Lang/C/Text-processing-Max-licenses-in-use b/Lang/C/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8b234fd13a --- /dev/null +++ b/Lang/C/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/C \ No newline at end of file diff --git a/Lang/C/Thieles-interpolation-formula b/Lang/C/Thieles-interpolation-formula new file mode 120000 index 0000000000..dd7d812e7c --- /dev/null +++ b/Lang/C/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/C \ No newline at end of file diff --git a/Lang/C/Tic-tac-toe b/Lang/C/Tic-tac-toe new file mode 120000 index 0000000000..8bd367d7d5 --- /dev/null +++ b/Lang/C/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/C \ No newline at end of file diff --git a/Lang/C/Time-a-function b/Lang/C/Time-a-function new file mode 120000 index 0000000000..2ebd993bb6 --- /dev/null +++ b/Lang/C/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/C \ No newline at end of file diff --git a/Lang/C/Tokenize-a-string b/Lang/C/Tokenize-a-string new file mode 120000 index 0000000000..f1e430b5e4 --- /dev/null +++ b/Lang/C/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/C \ No newline at end of file diff --git a/Lang/C/Top-rank-per-group b/Lang/C/Top-rank-per-group new file mode 120000 index 0000000000..18b99e99b6 --- /dev/null +++ b/Lang/C/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/C \ No newline at end of file diff --git a/Lang/C/Topological-sort b/Lang/C/Topological-sort new file mode 120000 index 0000000000..f074942e44 --- /dev/null +++ b/Lang/C/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/C \ No newline at end of file diff --git a/Lang/C/Topswops b/Lang/C/Topswops new file mode 120000 index 0000000000..645fbc85fa --- /dev/null +++ b/Lang/C/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/C \ No newline at end of file diff --git a/Lang/C/Towers-of-Hanoi b/Lang/C/Towers-of-Hanoi new file mode 120000 index 0000000000..521c2e9f16 --- /dev/null +++ b/Lang/C/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/C \ No newline at end of file diff --git a/Lang/C/Trabb-Pardo-Knuth-algorithm b/Lang/C/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..b3f14bd8c5 --- /dev/null +++ b/Lang/C/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/C \ No newline at end of file diff --git a/Lang/C/Tree-traversal b/Lang/C/Tree-traversal new file mode 120000 index 0000000000..197cdedd48 --- /dev/null +++ b/Lang/C/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/C \ No newline at end of file diff --git a/Lang/C/Trigonometric-functions b/Lang/C/Trigonometric-functions new file mode 120000 index 0000000000..aeaa461b59 --- /dev/null +++ b/Lang/C/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/C \ No newline at end of file diff --git a/Lang/C/Truncatable-primes b/Lang/C/Truncatable-primes new file mode 120000 index 0000000000..f50fad6e1f --- /dev/null +++ b/Lang/C/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/C \ No newline at end of file diff --git a/Lang/C/Truncate-a-file b/Lang/C/Truncate-a-file new file mode 120000 index 0000000000..750e93a230 --- /dev/null +++ b/Lang/C/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/C \ No newline at end of file diff --git a/Lang/C/URL-decoding b/Lang/C/URL-decoding new file mode 120000 index 0000000000..2b79ee55b0 --- /dev/null +++ b/Lang/C/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/C \ No newline at end of file diff --git a/Lang/C/URL-encoding b/Lang/C/URL-encoding new file mode 120000 index 0000000000..9b4ed62bb3 --- /dev/null +++ b/Lang/C/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/C \ No newline at end of file diff --git a/Lang/C/Unbias-a-random-generator b/Lang/C/Unbias-a-random-generator new file mode 120000 index 0000000000..f71ff8c40e --- /dev/null +++ b/Lang/C/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/C \ No newline at end of file diff --git a/Lang/C/Undefined-values b/Lang/C/Undefined-values new file mode 120000 index 0000000000..5cdfeecb6c --- /dev/null +++ b/Lang/C/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/C \ No newline at end of file diff --git a/Lang/C/Unicode-strings b/Lang/C/Unicode-strings new file mode 120000 index 0000000000..a32b9908d8 --- /dev/null +++ b/Lang/C/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/C \ No newline at end of file diff --git a/Lang/C/Update-a-configuration-file b/Lang/C/Update-a-configuration-file new file mode 120000 index 0000000000..539fd17293 --- /dev/null +++ b/Lang/C/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/C \ No newline at end of file diff --git a/Lang/C/Use-another-language-to-call-a-function b/Lang/C/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..a04a2253dc --- /dev/null +++ b/Lang/C/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/C \ No newline at end of file diff --git a/Lang/C/User-input-Graphical b/Lang/C/User-input-Graphical new file mode 120000 index 0000000000..a0e83a6e2e --- /dev/null +++ b/Lang/C/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/C \ No newline at end of file diff --git a/Lang/C/User-input-Text b/Lang/C/User-input-Text new file mode 120000 index 0000000000..7b5e84bb92 --- /dev/null +++ b/Lang/C/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/C \ No newline at end of file diff --git a/Lang/C/Vampire-number b/Lang/C/Vampire-number new file mode 120000 index 0000000000..63c9f5c0cf --- /dev/null +++ b/Lang/C/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/C \ No newline at end of file diff --git a/Lang/C/Van-der-Corput-sequence b/Lang/C/Van-der-Corput-sequence new file mode 120000 index 0000000000..55f11278b6 --- /dev/null +++ b/Lang/C/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/C \ No newline at end of file diff --git a/Lang/C/Variable-length-quantity b/Lang/C/Variable-length-quantity new file mode 120000 index 0000000000..a7bb523ddc --- /dev/null +++ b/Lang/C/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/C \ No newline at end of file diff --git a/Lang/C/Variable-size-Get b/Lang/C/Variable-size-Get new file mode 120000 index 0000000000..a381221667 --- /dev/null +++ b/Lang/C/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/C \ No newline at end of file diff --git a/Lang/C/Variable-size-Set b/Lang/C/Variable-size-Set new file mode 120000 index 0000000000..7f247f3244 --- /dev/null +++ b/Lang/C/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/C \ No newline at end of file diff --git a/Lang/C/Variables b/Lang/C/Variables new file mode 120000 index 0000000000..ccba747937 --- /dev/null +++ b/Lang/C/Variables @@ -0,0 +1 @@ +../../Task/Variables/C \ No newline at end of file diff --git a/Lang/C/Variadic-function b/Lang/C/Variadic-function new file mode 120000 index 0000000000..5cf0d8482a --- /dev/null +++ b/Lang/C/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/C \ No newline at end of file diff --git a/Lang/C/Vector-products b/Lang/C/Vector-products new file mode 120000 index 0000000000..2b57f2ecc1 --- /dev/null +++ b/Lang/C/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/C \ No newline at end of file diff --git a/Lang/C/Verify-distribution-uniformity-Chi-squared-test b/Lang/C/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..f41e19d485 --- /dev/null +++ b/Lang/C/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/C \ No newline at end of file diff --git a/Lang/C/Verify-distribution-uniformity-Naive b/Lang/C/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..e29ac5c474 --- /dev/null +++ b/Lang/C/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/C \ No newline at end of file diff --git a/Lang/C/Vigen-re-cipher b/Lang/C/Vigen-re-cipher new file mode 120000 index 0000000000..d02d110a39 --- /dev/null +++ b/Lang/C/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/C \ No newline at end of file diff --git a/Lang/C/Vigen-re-cipher-Cryptanalysis b/Lang/C/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..24735c142a --- /dev/null +++ b/Lang/C/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/C \ No newline at end of file diff --git a/Lang/C/Visualize-a-tree b/Lang/C/Visualize-a-tree new file mode 120000 index 0000000000..856b87fbe6 --- /dev/null +++ b/Lang/C/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/C \ No newline at end of file diff --git a/Lang/C/Voronoi-diagram b/Lang/C/Voronoi-diagram new file mode 120000 index 0000000000..1112b9599a --- /dev/null +++ b/Lang/C/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/C \ No newline at end of file diff --git a/Lang/C/Walk-a-directory-Non-recursively b/Lang/C/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..ab14a1c7b2 --- /dev/null +++ b/Lang/C/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/C \ No newline at end of file diff --git a/Lang/C/Walk-a-directory-Recursively b/Lang/C/Walk-a-directory-Recursively new file mode 120000 index 0000000000..711f512338 --- /dev/null +++ b/Lang/C/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/C \ No newline at end of file diff --git a/Lang/C/Web-scraping b/Lang/C/Web-scraping new file mode 120000 index 0000000000..0f2adedf49 --- /dev/null +++ b/Lang/C/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/C \ No newline at end of file diff --git a/Lang/C/Window-creation b/Lang/C/Window-creation new file mode 120000 index 0000000000..743ae643c6 --- /dev/null +++ b/Lang/C/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/C \ No newline at end of file diff --git a/Lang/C/Window-creation-X11 b/Lang/C/Window-creation-X11 new file mode 120000 index 0000000000..1282a87e05 --- /dev/null +++ b/Lang/C/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/C \ No newline at end of file diff --git a/Lang/C/Wireworld b/Lang/C/Wireworld new file mode 120000 index 0000000000..5790a28f02 --- /dev/null +++ b/Lang/C/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/C \ No newline at end of file diff --git a/Lang/C/Word-wrap b/Lang/C/Word-wrap new file mode 120000 index 0000000000..d5a10684f5 --- /dev/null +++ b/Lang/C/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/C \ No newline at end of file diff --git a/Lang/C/Write-float-arrays-to-a-text-file b/Lang/C/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..b23aafe603 --- /dev/null +++ b/Lang/C/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/C \ No newline at end of file diff --git a/Lang/C/Write-language-name-in-3D-ASCII b/Lang/C/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..31b0a1f468 --- /dev/null +++ b/Lang/C/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/C \ No newline at end of file diff --git a/Lang/C/XML-DOM-serialization b/Lang/C/XML-DOM-serialization new file mode 120000 index 0000000000..8d7767ed61 --- /dev/null +++ b/Lang/C/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/C \ No newline at end of file diff --git a/Lang/C/XML-Input b/Lang/C/XML-Input new file mode 120000 index 0000000000..10b01b2c95 --- /dev/null +++ b/Lang/C/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/C \ No newline at end of file diff --git a/Lang/C/XML-Output b/Lang/C/XML-Output new file mode 120000 index 0000000000..2aaf19012b --- /dev/null +++ b/Lang/C/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/C \ No newline at end of file diff --git a/Lang/C/Xiaolin-Wus-line-algorithm b/Lang/C/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..fb381cef97 --- /dev/null +++ b/Lang/C/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/C \ No newline at end of file diff --git a/Lang/C/Y-combinator b/Lang/C/Y-combinator new file mode 120000 index 0000000000..b773734c8a --- /dev/null +++ b/Lang/C/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/C \ No newline at end of file diff --git a/Lang/C/Yin-and-yang b/Lang/C/Yin-and-yang new file mode 120000 index 0000000000..806dd5274d --- /dev/null +++ b/Lang/C/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/C \ No newline at end of file diff --git a/Lang/C/Zebra-puzzle b/Lang/C/Zebra-puzzle new file mode 120000 index 0000000000..3c82e02028 --- /dev/null +++ b/Lang/C/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/C \ No newline at end of file diff --git a/Lang/C/Zeckendorf-number-representation b/Lang/C/Zeckendorf-number-representation new file mode 120000 index 0000000000..4a94daf2ad --- /dev/null +++ b/Lang/C/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/C \ No newline at end of file diff --git a/Lang/C/Zig-zag-matrix b/Lang/C/Zig-zag-matrix new file mode 120000 index 0000000000..b55dc8ed4b --- /dev/null +++ b/Lang/C/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/C \ No newline at end of file diff --git a/Lang/CLIPS/Sum-of-a-series b/Lang/CLIPS/Sum-of-a-series new file mode 120000 index 0000000000..f0babe9b27 --- /dev/null +++ b/Lang/CLIPS/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/CLIPS \ No newline at end of file diff --git a/Lang/CMake/Shell-one-liner b/Lang/CMake/Shell-one-liner new file mode 120000 index 0000000000..8514c186bd --- /dev/null +++ b/Lang/CMake/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/CMake \ No newline at end of file diff --git a/Lang/CMake/Sieve-of-Eratosthenes b/Lang/CMake/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..87ad494736 --- /dev/null +++ b/Lang/CMake/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/CMake \ No newline at end of file diff --git a/Lang/CMake/Sorting-algorithms-Bubble-sort b/Lang/CMake/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..a9f7290e8b --- /dev/null +++ b/Lang/CMake/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/CMake \ No newline at end of file diff --git a/Lang/CMake/Sorting-algorithms-Insertion-sort b/Lang/CMake/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4a44d503b9 --- /dev/null +++ b/Lang/CMake/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/CMake \ No newline at end of file diff --git a/Lang/CMake/Sorting-algorithms-Strand-sort b/Lang/CMake/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..da51567eed --- /dev/null +++ b/Lang/CMake/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/CMake \ No newline at end of file diff --git a/Lang/CMake/String-case b/Lang/CMake/String-case new file mode 120000 index 0000000000..acdcc3b0a6 --- /dev/null +++ b/Lang/CMake/String-case @@ -0,0 +1 @@ +../../Task/String-case/CMake \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Bubble-sort b/Lang/COBOL/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..e21929bf4d --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Cocktail-sort b/Lang/COBOL/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..9806b3e2a4 --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Comb-sort b/Lang/COBOL/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..7ff80b58d0 --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Gnome-sort b/Lang/COBOL/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a815cd77db --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Insertion-sort b/Lang/COBOL/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..c9dfb1e33b --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Merge-sort b/Lang/COBOL/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..568df4ec36 --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Selection-sort b/Lang/COBOL/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..2a1223c94c --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Sorting-algorithms-Shell-sort b/Lang/COBOL/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..5e31982663 --- /dev/null +++ b/Lang/COBOL/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Soundex b/Lang/COBOL/Soundex new file mode 120000 index 0000000000..4e45440fa7 --- /dev/null +++ b/Lang/COBOL/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Stack b/Lang/COBOL/Stack new file mode 120000 index 0000000000..9969d90323 --- /dev/null +++ b/Lang/COBOL/Stack @@ -0,0 +1 @@ +../../Task/Stack/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Soundex b/Lang/Cache-ObjectScript/Soundex new file mode 120000 index 0000000000..a9cb185c16 --- /dev/null +++ b/Lang/Cache-ObjectScript/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Walk-a-directory-Recursively b/Lang/Cache-ObjectScript/Walk-a-directory-Recursively new file mode 120000 index 0000000000..cb5f6b42ac --- /dev/null +++ b/Lang/Cache-ObjectScript/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Web-scraping b/Lang/Cache-ObjectScript/Web-scraping new file mode 120000 index 0000000000..acf39cfe06 --- /dev/null +++ b/Lang/Cache-ObjectScript/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Chef/Sum-and-product-of-an-array b/Lang/Chef/Sum-and-product-of-an-array new file mode 120000 index 0000000000..669f805daf --- /dev/null +++ b/Lang/Chef/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Chef \ No newline at end of file diff --git a/Lang/Chef/Sum-of-squares b/Lang/Chef/Sum-of-squares new file mode 120000 index 0000000000..25df484541 --- /dev/null +++ b/Lang/Chef/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Chef \ No newline at end of file diff --git a/Lang/Clean/Singly-linked-list-Element-definition b/Lang/Clean/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..3de2a3b6c4 --- /dev/null +++ b/Lang/Clean/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Clean \ No newline at end of file diff --git a/Lang/Clean/Sort-an-integer-array b/Lang/Clean/Sort-an-integer-array new file mode 120000 index 0000000000..e2da90a248 --- /dev/null +++ b/Lang/Clean/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Clean \ No newline at end of file diff --git a/Lang/Clean/Sort-using-a-custom-comparator b/Lang/Clean/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..686d9de1ba --- /dev/null +++ b/Lang/Clean/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Clean \ No newline at end of file diff --git a/Lang/Clean/Sorting-algorithms-Bubble-sort b/Lang/Clean/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..4c0ff252fa --- /dev/null +++ b/Lang/Clean/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Clean \ No newline at end of file diff --git a/Lang/Clean/String-length b/Lang/Clean/String-length new file mode 120000 index 0000000000..8b819d3307 --- /dev/null +++ b/Lang/Clean/String-length @@ -0,0 +1 @@ +../../Task/String-length/Clean \ No newline at end of file diff --git a/Lang/Clean/Sum-and-product-of-an-array b/Lang/Clean/Sum-and-product-of-an-array new file mode 120000 index 0000000000..fde9bfdead --- /dev/null +++ b/Lang/Clean/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Clean \ No newline at end of file diff --git a/Lang/Clipper-XBase++/Soundex b/Lang/Clipper-XBase++/Soundex new file mode 120000 index 0000000000..94f25927c7 --- /dev/null +++ b/Lang/Clipper-XBase++/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Clipper-XBase++ \ No newline at end of file diff --git a/Lang/Clojure/Seven-sided-dice-from-five-sided-dice b/Lang/Clojure/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..0a503571f6 --- /dev/null +++ b/Lang/Clojure/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Shell-one-liner b/Lang/Clojure/Shell-one-liner new file mode 120000 index 0000000000..7e2889b282 --- /dev/null +++ b/Lang/Clojure/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Short-circuit-evaluation b/Lang/Clojure/Short-circuit-evaluation new file mode 120000 index 0000000000..f32d5a099b --- /dev/null +++ b/Lang/Clojure/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sierpinski-carpet b/Lang/Clojure/Sierpinski-carpet new file mode 120000 index 0000000000..439b15e80f --- /dev/null +++ b/Lang/Clojure/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sierpinski-triangle b/Lang/Clojure/Sierpinski-triangle new file mode 120000 index 0000000000..2db6e2c420 --- /dev/null +++ b/Lang/Clojure/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sieve-of-Eratosthenes b/Lang/Clojure/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..fac094e0fa --- /dev/null +++ b/Lang/Clojure/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Simple-windowed-application b/Lang/Clojure/Simple-windowed-application new file mode 120000 index 0000000000..ba6430c11a --- /dev/null +++ b/Lang/Clojure/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Simulate-input-Keyboard b/Lang/Clojure/Simulate-input-Keyboard new file mode 120000 index 0000000000..45519021de --- /dev/null +++ b/Lang/Clojure/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Singly-linked-list-Element-insertion b/Lang/Clojure/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..4a0d372b57 --- /dev/null +++ b/Lang/Clojure/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Singly-linked-list-Traversal b/Lang/Clojure/Singly-linked-list-Traversal new file mode 120000 index 0000000000..772a5ebfa0 --- /dev/null +++ b/Lang/Clojure/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sleep b/Lang/Clojure/Sleep new file mode 120000 index 0000000000..17c60b14d7 --- /dev/null +++ b/Lang/Clojure/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sockets b/Lang/Clojure/Sockets new file mode 120000 index 0000000000..7d1d3e63e4 --- /dev/null +++ b/Lang/Clojure/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sort-an-array-of-composite-structures b/Lang/Clojure/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..ccb1159975 --- /dev/null +++ b/Lang/Clojure/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sort-an-integer-array b/Lang/Clojure/Sort-an-integer-array new file mode 120000 index 0000000000..86b48a8492 --- /dev/null +++ b/Lang/Clojure/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sort-using-a-custom-comparator b/Lang/Clojure/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..dc836bbd53 --- /dev/null +++ b/Lang/Clojure/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Bead-sort b/Lang/Clojure/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..e3ccc5964f --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Bogosort b/Lang/Clojure/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..20d0ce7fda --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Bubble-sort b/Lang/Clojure/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..c5cd1e985a --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Gnome-sort b/Lang/Clojure/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..02e1ac0fa7 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Heapsort b/Lang/Clojure/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..7ad2687d42 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Insertion-sort b/Lang/Clojure/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..cf2c7c7f9d --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Merge-sort b/Lang/Clojure/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..a900e7684a --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Permutation-sort b/Lang/Clojure/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..98def9bf89 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Quicksort b/Lang/Clojure/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..cdc16c4e4e --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Selection-sort b/Lang/Clojure/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..09c1b2dfac --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Strand-sort b/Lang/Clojure/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..f0c66ba085 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Soundex b/Lang/Clojure/Soundex new file mode 120000 index 0000000000..6db49862e0 --- /dev/null +++ b/Lang/Clojure/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Spiral-matrix b/Lang/Clojure/Spiral-matrix new file mode 120000 index 0000000000..fcbf98baa4 --- /dev/null +++ b/Lang/Clojure/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Stair-climbing-puzzle b/Lang/Clojure/Stair-climbing-puzzle new file mode 120000 index 0000000000..452d57f27c --- /dev/null +++ b/Lang/Clojure/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Standard-deviation b/Lang/Clojure/Standard-deviation new file mode 120000 index 0000000000..b55f0b897e --- /dev/null +++ b/Lang/Clojure/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-case b/Lang/Clojure/String-case new file mode 120000 index 0000000000..ce5ce11698 --- /dev/null +++ b/Lang/Clojure/String-case @@ -0,0 +1 @@ +../../Task/String-case/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-concatenation b/Lang/Clojure/String-concatenation new file mode 120000 index 0000000000..2f8f6a6c27 --- /dev/null +++ b/Lang/Clojure/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-interpolation--included- b/Lang/Clojure/String-interpolation--included- new file mode 120000 index 0000000000..a62449de12 --- /dev/null +++ b/Lang/Clojure/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Clojure \ No newline at end of file diff --git a/Lang/Clojure/String-length b/Lang/Clojure/String-length new file mode 120000 index 0000000000..247d656135 --- /dev/null +++ b/Lang/Clojure/String-length @@ -0,0 +1 @@ +../../Task/String-length/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Strip-a-set-of-characters-from-a-string b/Lang/Clojure/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..e26a9d9771 --- /dev/null +++ b/Lang/Clojure/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Strip-block-comments b/Lang/Clojure/Strip-block-comments new file mode 120000 index 0000000000..534a6bfc1f --- /dev/null +++ b/Lang/Clojure/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Strip-comments-from-a-string b/Lang/Clojure/Strip-comments-from-a-string new file mode 120000 index 0000000000..b627f80c9f --- /dev/null +++ b/Lang/Clojure/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Substring b/Lang/Clojure/Substring new file mode 120000 index 0000000000..546c24769b --- /dev/null +++ b/Lang/Clojure/Substring @@ -0,0 +1 @@ +../../Task/Substring/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sudoku b/Lang/Clojure/Sudoku new file mode 120000 index 0000000000..fc5bc6e425 --- /dev/null +++ b/Lang/Clojure/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sum-and-product-of-an-array b/Lang/Clojure/Sum-and-product-of-an-array new file mode 120000 index 0000000000..536ebbec41 --- /dev/null +++ b/Lang/Clojure/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sum-of-a-series b/Lang/Clojure/Sum-of-a-series new file mode 120000 index 0000000000..18ab4f1c62 --- /dev/null +++ b/Lang/Clojure/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sum-of-squares b/Lang/Clojure/Sum-of-squares new file mode 120000 index 0000000000..765f1f4f8a --- /dev/null +++ b/Lang/Clojure/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Symmetric-difference b/Lang/Clojure/Symmetric-difference new file mode 120000 index 0000000000..629bb5cff5 --- /dev/null +++ b/Lang/Clojure/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Synchronous-concurrency b/Lang/Clojure/Synchronous-concurrency new file mode 120000 index 0000000000..33ae7a3d11 --- /dev/null +++ b/Lang/Clojure/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Clojure \ No newline at end of file diff --git a/Lang/Clojure/System-time b/Lang/Clojure/System-time new file mode 120000 index 0000000000..c401762c0b --- /dev/null +++ b/Lang/Clojure/System-time @@ -0,0 +1 @@ +../../Task/System-time/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Take-notes-on-the-command-line b/Lang/Clojure/Take-notes-on-the-command-line new file mode 120000 index 0000000000..d1ee1eb3de --- /dev/null +++ b/Lang/Clojure/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Test-a-function b/Lang/Clojure/Test-a-function new file mode 120000 index 0000000000..7fb120ec26 --- /dev/null +++ b/Lang/Clojure/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Time-a-function b/Lang/Clojure/Time-a-function new file mode 120000 index 0000000000..626ce3eeae --- /dev/null +++ b/Lang/Clojure/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Tokenize-a-string b/Lang/Clojure/Tokenize-a-string new file mode 120000 index 0000000000..54d415febc --- /dev/null +++ b/Lang/Clojure/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Top-rank-per-group b/Lang/Clojure/Top-rank-per-group new file mode 120000 index 0000000000..429f7622c3 --- /dev/null +++ b/Lang/Clojure/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Topological-sort b/Lang/Clojure/Topological-sort new file mode 120000 index 0000000000..c267e61a3b --- /dev/null +++ b/Lang/Clojure/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Towers-of-Hanoi b/Lang/Clojure/Towers-of-Hanoi new file mode 120000 index 0000000000..4ba9a7b4aa --- /dev/null +++ b/Lang/Clojure/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Tree-traversal b/Lang/Clojure/Tree-traversal new file mode 120000 index 0000000000..4a2dd8409a --- /dev/null +++ b/Lang/Clojure/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Trigonometric-functions b/Lang/Clojure/Trigonometric-functions new file mode 120000 index 0000000000..94441f0c68 --- /dev/null +++ b/Lang/Clojure/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Truncatable-primes b/Lang/Clojure/Truncatable-primes new file mode 120000 index 0000000000..83bdb26cde --- /dev/null +++ b/Lang/Clojure/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Clojure \ No newline at end of file diff --git a/Lang/Clojure/URL-decoding b/Lang/Clojure/URL-decoding new file mode 120000 index 0000000000..4865df85bd --- /dev/null +++ b/Lang/Clojure/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Unbias-a-random-generator b/Lang/Clojure/Unbias-a-random-generator new file mode 120000 index 0000000000..828f27587c --- /dev/null +++ b/Lang/Clojure/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Clojure \ No newline at end of file diff --git a/Lang/Clojure/User-input-Graphical b/Lang/Clojure/User-input-Graphical new file mode 120000 index 0000000000..ec61838bad --- /dev/null +++ b/Lang/Clojure/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Clojure \ No newline at end of file diff --git a/Lang/Clojure/User-input-Text b/Lang/Clojure/User-input-Text new file mode 120000 index 0000000000..cbdb9b5136 --- /dev/null +++ b/Lang/Clojure/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Vampire-number b/Lang/Clojure/Vampire-number new file mode 120000 index 0000000000..78e7e2a916 --- /dev/null +++ b/Lang/Clojure/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Variadic-function b/Lang/Clojure/Variadic-function new file mode 120000 index 0000000000..7deeff5bdc --- /dev/null +++ b/Lang/Clojure/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Vector-products b/Lang/Clojure/Vector-products new file mode 120000 index 0000000000..8ed5e432e5 --- /dev/null +++ b/Lang/Clojure/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Verify-distribution-uniformity-Naive b/Lang/Clojure/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..63c7292b05 --- /dev/null +++ b/Lang/Clojure/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Vigen-re-cipher b/Lang/Clojure/Vigen-re-cipher new file mode 120000 index 0000000000..35d501bc9f --- /dev/null +++ b/Lang/Clojure/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Walk-a-directory-Recursively b/Lang/Clojure/Walk-a-directory-Recursively new file mode 120000 index 0000000000..47440e3625 --- /dev/null +++ b/Lang/Clojure/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Web-scraping b/Lang/Clojure/Web-scraping new file mode 120000 index 0000000000..41b1919396 --- /dev/null +++ b/Lang/Clojure/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Window-creation b/Lang/Clojure/Window-creation new file mode 120000 index 0000000000..d8db4e16f5 --- /dev/null +++ b/Lang/Clojure/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Clojure \ No newline at end of file diff --git a/Lang/Clojure/XML-Input b/Lang/Clojure/XML-Input new file mode 120000 index 0000000000..cb986794d5 --- /dev/null +++ b/Lang/Clojure/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Clojure \ No newline at end of file diff --git a/Lang/Clojure/XML-Output b/Lang/Clojure/XML-Output new file mode 120000 index 0000000000..ec865c3be2 --- /dev/null +++ b/Lang/Clojure/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Y-combinator b/Lang/Clojure/Y-combinator new file mode 120000 index 0000000000..da94a7e166 --- /dev/null +++ b/Lang/Clojure/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Zig-zag-matrix b/Lang/Clojure/Zig-zag-matrix new file mode 120000 index 0000000000..53a8e63ef6 --- /dev/null +++ b/Lang/Clojure/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-algorithms-Heapsort b/Lang/CoffeeScript/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..6aa7480eeb --- /dev/null +++ b/Lang/CoffeeScript/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-algorithms-Merge-sort b/Lang/CoffeeScript/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e1c20fef03 --- /dev/null +++ b/Lang/CoffeeScript/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-algorithms-Permutation-sort b/Lang/CoffeeScript/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..40509059e0 --- /dev/null +++ b/Lang/CoffeeScript/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-algorithms-Quicksort b/Lang/CoffeeScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..30b88d6b8a --- /dev/null +++ b/Lang/CoffeeScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-algorithms-Sleep-sort b/Lang/CoffeeScript/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..20e65a14ac --- /dev/null +++ b/Lang/CoffeeScript/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Spiral-matrix b/Lang/CoffeeScript/Spiral-matrix new file mode 120000 index 0000000000..f728010949 --- /dev/null +++ b/Lang/CoffeeScript/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Stable-marriage-problem b/Lang/CoffeeScript/Stable-marriage-problem new file mode 120000 index 0000000000..e45058688a --- /dev/null +++ b/Lang/CoffeeScript/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Stack b/Lang/CoffeeScript/Stack new file mode 120000 index 0000000000..d8832584b6 --- /dev/null +++ b/Lang/CoffeeScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/String-interpolation--included- b/Lang/CoffeeScript/String-interpolation--included- new file mode 120000 index 0000000000..c6a6f5eb3d --- /dev/null +++ b/Lang/CoffeeScript/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sum-of-a-series b/Lang/CoffeeScript/Sum-of-a-series new file mode 120000 index 0000000000..a8e40a4370 --- /dev/null +++ b/Lang/CoffeeScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Tokenize-a-string b/Lang/CoffeeScript/Tokenize-a-string new file mode 120000 index 0000000000..df362aba2e --- /dev/null +++ b/Lang/CoffeeScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Topological-sort b/Lang/CoffeeScript/Topological-sort new file mode 120000 index 0000000000..f79f84331b --- /dev/null +++ b/Lang/CoffeeScript/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Towers-of-Hanoi b/Lang/CoffeeScript/Towers-of-Hanoi new file mode 120000 index 0000000000..44650279cf --- /dev/null +++ b/Lang/CoffeeScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Tree-traversal b/Lang/CoffeeScript/Tree-traversal new file mode 120000 index 0000000000..34e08a725e --- /dev/null +++ b/Lang/CoffeeScript/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Truncatable-primes b/Lang/CoffeeScript/Truncatable-primes new file mode 120000 index 0000000000..de17036c9e --- /dev/null +++ b/Lang/CoffeeScript/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/URL-decoding b/Lang/CoffeeScript/URL-decoding new file mode 120000 index 0000000000..0b6e5ef3a3 --- /dev/null +++ b/Lang/CoffeeScript/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Unbias-a-random-generator b/Lang/CoffeeScript/Unbias-a-random-generator new file mode 120000 index 0000000000..da299e2b88 --- /dev/null +++ b/Lang/CoffeeScript/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Vigen-re-cipher b/Lang/CoffeeScript/Vigen-re-cipher new file mode 120000 index 0000000000..50c27ff922 --- /dev/null +++ b/Lang/CoffeeScript/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Walk-a-directory-Recursively b/Lang/CoffeeScript/Walk-a-directory-Recursively new file mode 120000 index 0000000000..18b1e2dfe0 --- /dev/null +++ b/Lang/CoffeeScript/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Web-scraping b/Lang/CoffeeScript/Web-scraping new file mode 120000 index 0000000000..68e84f67f7 --- /dev/null +++ b/Lang/CoffeeScript/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Zig-zag-matrix b/Lang/CoffeeScript/Zig-zag-matrix new file mode 120000 index 0000000000..8c78f6240f --- /dev/null +++ b/Lang/CoffeeScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/SOAP b/Lang/ColdFusion/SOAP new file mode 120000 index 0000000000..d805159b77 --- /dev/null +++ b/Lang/ColdFusion/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/String-case b/Lang/ColdFusion/String-case new file mode 120000 index 0000000000..0127b5ee5e --- /dev/null +++ b/Lang/ColdFusion/String-case @@ -0,0 +1 @@ +../../Task/String-case/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/String-length b/Lang/ColdFusion/String-length new file mode 120000 index 0000000000..a093ee9535 --- /dev/null +++ b/Lang/ColdFusion/String-length @@ -0,0 +1 @@ +../../Task/String-length/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Sum-and-product-of-an-array b/Lang/ColdFusion/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c612e19ea8 --- /dev/null +++ b/Lang/ColdFusion/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Walk-a-directory-Non-recursively b/Lang/ColdFusion/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..07078792c9 --- /dev/null +++ b/Lang/ColdFusion/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/XML-XPath b/Lang/ColdFusion/XML-XPath new file mode 120000 index 0000000000..aab426cb79 --- /dev/null +++ b/Lang/ColdFusion/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/ColdFusion \ No newline at end of file diff --git a/Lang/Common-Lisp/SHA-1 b/Lang/Common-Lisp/SHA-1 new file mode 120000 index 0000000000..89f03a3045 --- /dev/null +++ b/Lang/Common-Lisp/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Seven-sided-dice-from-five-sided-dice b/Lang/Common-Lisp/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..3b245fba3d --- /dev/null +++ b/Lang/Common-Lisp/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Shell-one-liner b/Lang/Common-Lisp/Shell-one-liner new file mode 120000 index 0000000000..e59dcec376 --- /dev/null +++ b/Lang/Common-Lisp/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Short-circuit-evaluation b/Lang/Common-Lisp/Short-circuit-evaluation new file mode 120000 index 0000000000..4dab2ac72a --- /dev/null +++ b/Lang/Common-Lisp/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Show-the-epoch b/Lang/Common-Lisp/Show-the-epoch new file mode 120000 index 0000000000..d031179251 --- /dev/null +++ b/Lang/Common-Lisp/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sierpinski-carpet b/Lang/Common-Lisp/Sierpinski-carpet new file mode 120000 index 0000000000..9e63ebb5d0 --- /dev/null +++ b/Lang/Common-Lisp/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sierpinski-triangle b/Lang/Common-Lisp/Sierpinski-triangle new file mode 120000 index 0000000000..96479ea970 --- /dev/null +++ b/Lang/Common-Lisp/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sieve-of-Eratosthenes b/Lang/Common-Lisp/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..7abf9b8c1f --- /dev/null +++ b/Lang/Common-Lisp/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Simple-database b/Lang/Common-Lisp/Simple-database new file mode 120000 index 0000000000..63d146c851 --- /dev/null +++ b/Lang/Common-Lisp/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Simple-windowed-application b/Lang/Common-Lisp/Simple-windowed-application new file mode 120000 index 0000000000..2f1b222af5 --- /dev/null +++ b/Lang/Common-Lisp/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Singleton b/Lang/Common-Lisp/Singleton new file mode 120000 index 0000000000..c5a97dee89 --- /dev/null +++ b/Lang/Common-Lisp/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Singly-linked-list-Element-definition b/Lang/Common-Lisp/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..a70e2fd5d1 --- /dev/null +++ b/Lang/Common-Lisp/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Singly-linked-list-Element-insertion b/Lang/Common-Lisp/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..06c4be330d --- /dev/null +++ b/Lang/Common-Lisp/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Singly-linked-list-Traversal b/Lang/Common-Lisp/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8cdde57d94 --- /dev/null +++ b/Lang/Common-Lisp/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sleep b/Lang/Common-Lisp/Sleep new file mode 120000 index 0000000000..ee1e3afe51 --- /dev/null +++ b/Lang/Common-Lisp/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sockets b/Lang/Common-Lisp/Sockets new file mode 120000 index 0000000000..74bf8320aa --- /dev/null +++ b/Lang/Common-Lisp/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sort-an-array-of-composite-structures b/Lang/Common-Lisp/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..39c11351be --- /dev/null +++ b/Lang/Common-Lisp/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sort-an-integer-array b/Lang/Common-Lisp/Sort-an-integer-array new file mode 120000 index 0000000000..256da8c199 --- /dev/null +++ b/Lang/Common-Lisp/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sort-using-a-custom-comparator b/Lang/Common-Lisp/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..36ac70d0a2 --- /dev/null +++ b/Lang/Common-Lisp/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Bogosort b/Lang/Common-Lisp/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..917622f517 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Bubble-sort b/Lang/Common-Lisp/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..326257da01 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Cocktail-sort b/Lang/Common-Lisp/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..19685ea805 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Counting-sort b/Lang/Common-Lisp/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..5a756fb8dd --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Gnome-sort b/Lang/Common-Lisp/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..35438356d1 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Heapsort b/Lang/Common-Lisp/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..ff0dc50c26 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Insertion-sort b/Lang/Common-Lisp/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..ba43e5f39f --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Merge-sort b/Lang/Common-Lisp/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..32a487027b --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Pancake-sort b/Lang/Common-Lisp/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..0ec91f4e97 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Permutation-sort b/Lang/Common-Lisp/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..aaeeb132ea --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Quicksort b/Lang/Common-Lisp/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..9428c38d96 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Selection-sort b/Lang/Common-Lisp/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..95783c038b --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Shell-sort b/Lang/Common-Lisp/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..0754ab7a53 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Strand-sort b/Lang/Common-Lisp/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..ccb590a757 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Soundex b/Lang/Common-Lisp/Soundex new file mode 120000 index 0000000000..ef8bd34cb8 --- /dev/null +++ b/Lang/Common-Lisp/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Spiral-matrix b/Lang/Common-Lisp/Spiral-matrix new file mode 120000 index 0000000000..57344ab4d0 --- /dev/null +++ b/Lang/Common-Lisp/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Stack-traces b/Lang/Common-Lisp/Stack-traces new file mode 120000 index 0000000000..e0e17d178d --- /dev/null +++ b/Lang/Common-Lisp/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Stair-climbing-puzzle b/Lang/Common-Lisp/Stair-climbing-puzzle new file mode 120000 index 0000000000..2f293df972 --- /dev/null +++ b/Lang/Common-Lisp/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Standard-deviation b/Lang/Common-Lisp/Standard-deviation new file mode 120000 index 0000000000..d902bbccab --- /dev/null +++ b/Lang/Common-Lisp/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-case b/Lang/Common-Lisp/String-case new file mode 120000 index 0000000000..d9542fda0b --- /dev/null +++ b/Lang/Common-Lisp/String-case @@ -0,0 +1 @@ +../../Task/String-case/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-concatenation b/Lang/Common-Lisp/String-concatenation new file mode 120000 index 0000000000..988a1c4127 --- /dev/null +++ b/Lang/Common-Lisp/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-interpolation--included- b/Lang/Common-Lisp/String-interpolation--included- new file mode 120000 index 0000000000..bde01ed1b7 --- /dev/null +++ b/Lang/Common-Lisp/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-length b/Lang/Common-Lisp/String-length new file mode 120000 index 0000000000..676a193390 --- /dev/null +++ b/Lang/Common-Lisp/String-length @@ -0,0 +1 @@ +../../Task/String-length/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Strip-a-set-of-characters-from-a-string b/Lang/Common-Lisp/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..4f0788f034 --- /dev/null +++ b/Lang/Common-Lisp/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Substring b/Lang/Common-Lisp/Substring new file mode 120000 index 0000000000..204d0c4f14 --- /dev/null +++ b/Lang/Common-Lisp/Substring @@ -0,0 +1 @@ +../../Task/Substring/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Subtractive-generator b/Lang/Common-Lisp/Subtractive-generator new file mode 120000 index 0000000000..8d0a3ec1a8 --- /dev/null +++ b/Lang/Common-Lisp/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sudoku b/Lang/Common-Lisp/Sudoku new file mode 120000 index 0000000000..f5156dbd9b --- /dev/null +++ b/Lang/Common-Lisp/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sum-and-product-of-an-array b/Lang/Common-Lisp/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e5490726aa --- /dev/null +++ b/Lang/Common-Lisp/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sum-digits-of-an-integer b/Lang/Common-Lisp/Sum-digits-of-an-integer new file mode 120000 index 0000000000..e2a76e98c8 --- /dev/null +++ b/Lang/Common-Lisp/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sum-of-a-series b/Lang/Common-Lisp/Sum-of-a-series new file mode 120000 index 0000000000..81dd5b209f --- /dev/null +++ b/Lang/Common-Lisp/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sum-of-squares b/Lang/Common-Lisp/Sum-of-squares new file mode 120000 index 0000000000..9b7a67919c --- /dev/null +++ b/Lang/Common-Lisp/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Symmetric-difference b/Lang/Common-Lisp/Symmetric-difference new file mode 120000 index 0000000000..72bbc9a289 --- /dev/null +++ b/Lang/Common-Lisp/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Synchronous-concurrency b/Lang/Common-Lisp/Synchronous-concurrency new file mode 120000 index 0000000000..0f401280ab --- /dev/null +++ b/Lang/Common-Lisp/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/System-time b/Lang/Common-Lisp/System-time new file mode 120000 index 0000000000..95cfbde3d8 --- /dev/null +++ b/Lang/Common-Lisp/System-time @@ -0,0 +1 @@ +../../Task/System-time/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Ternary-logic b/Lang/Common-Lisp/Ternary-logic new file mode 120000 index 0000000000..345a02deb9 --- /dev/null +++ b/Lang/Common-Lisp/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Text-processing-1 b/Lang/Common-Lisp/Text-processing-1 new file mode 120000 index 0000000000..5740e6e38b --- /dev/null +++ b/Lang/Common-Lisp/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Text-processing-Max-licenses-in-use b/Lang/Common-Lisp/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..05cfc82991 --- /dev/null +++ b/Lang/Common-Lisp/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Thieles-interpolation-formula b/Lang/Common-Lisp/Thieles-interpolation-formula new file mode 120000 index 0000000000..8235291a89 --- /dev/null +++ b/Lang/Common-Lisp/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Time-a-function b/Lang/Common-Lisp/Time-a-function new file mode 120000 index 0000000000..b3d9001552 --- /dev/null +++ b/Lang/Common-Lisp/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Tokenize-a-string b/Lang/Common-Lisp/Tokenize-a-string new file mode 120000 index 0000000000..b3d8fe581c --- /dev/null +++ b/Lang/Common-Lisp/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Top-rank-per-group b/Lang/Common-Lisp/Top-rank-per-group new file mode 120000 index 0000000000..8850cbf2ae --- /dev/null +++ b/Lang/Common-Lisp/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Topological-sort b/Lang/Common-Lisp/Topological-sort new file mode 120000 index 0000000000..3c2ca72529 --- /dev/null +++ b/Lang/Common-Lisp/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Towers-of-Hanoi b/Lang/Common-Lisp/Towers-of-Hanoi new file mode 120000 index 0000000000..e881a016ce --- /dev/null +++ b/Lang/Common-Lisp/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Tree-traversal b/Lang/Common-Lisp/Tree-traversal new file mode 120000 index 0000000000..39691e6823 --- /dev/null +++ b/Lang/Common-Lisp/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Trigonometric-functions b/Lang/Common-Lisp/Trigonometric-functions new file mode 120000 index 0000000000..f41350e1db --- /dev/null +++ b/Lang/Common-Lisp/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Unbias-a-random-generator b/Lang/Common-Lisp/Unbias-a-random-generator new file mode 120000 index 0000000000..dba3efce18 --- /dev/null +++ b/Lang/Common-Lisp/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Undefined-values b/Lang/Common-Lisp/Undefined-values new file mode 120000 index 0000000000..995d927278 --- /dev/null +++ b/Lang/Common-Lisp/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Unicode-variable-names b/Lang/Common-Lisp/Unicode-variable-names new file mode 120000 index 0000000000..80eeeb6413 --- /dev/null +++ b/Lang/Common-Lisp/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/User-input-Graphical b/Lang/Common-Lisp/User-input-Graphical new file mode 120000 index 0000000000..101fe941c6 --- /dev/null +++ b/Lang/Common-Lisp/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/User-input-Text b/Lang/Common-Lisp/User-input-Text new file mode 120000 index 0000000000..ab3494e1b7 --- /dev/null +++ b/Lang/Common-Lisp/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Van-der-Corput-sequence b/Lang/Common-Lisp/Van-der-Corput-sequence new file mode 120000 index 0000000000..2e30708c8c --- /dev/null +++ b/Lang/Common-Lisp/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Variable-size-Get b/Lang/Common-Lisp/Variable-size-Get new file mode 120000 index 0000000000..1ef4c9aad4 --- /dev/null +++ b/Lang/Common-Lisp/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Variadic-function b/Lang/Common-Lisp/Variadic-function new file mode 120000 index 0000000000..4e7be7190e --- /dev/null +++ b/Lang/Common-Lisp/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Vector-products b/Lang/Common-Lisp/Vector-products new file mode 120000 index 0000000000..aac58752f2 --- /dev/null +++ b/Lang/Common-Lisp/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Verify-distribution-uniformity-Naive b/Lang/Common-Lisp/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..fc6f878bb9 --- /dev/null +++ b/Lang/Common-Lisp/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Vigen-re-cipher b/Lang/Common-Lisp/Vigen-re-cipher new file mode 120000 index 0000000000..e142c8a5c0 --- /dev/null +++ b/Lang/Common-Lisp/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Walk-a-directory-Non-recursively b/Lang/Common-Lisp/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..235606a69d --- /dev/null +++ b/Lang/Common-Lisp/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Walk-a-directory-Recursively b/Lang/Common-Lisp/Walk-a-directory-Recursively new file mode 120000 index 0000000000..1fa222c4c1 --- /dev/null +++ b/Lang/Common-Lisp/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Web-scraping b/Lang/Common-Lisp/Web-scraping new file mode 120000 index 0000000000..dd2f180691 --- /dev/null +++ b/Lang/Common-Lisp/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Window-creation b/Lang/Common-Lisp/Window-creation new file mode 120000 index 0000000000..5e21aaa888 --- /dev/null +++ b/Lang/Common-Lisp/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Window-creation-X11 b/Lang/Common-Lisp/Window-creation-X11 new file mode 120000 index 0000000000..e50e54d3ef --- /dev/null +++ b/Lang/Common-Lisp/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Wireworld b/Lang/Common-Lisp/Wireworld new file mode 120000 index 0000000000..82bcbfe242 --- /dev/null +++ b/Lang/Common-Lisp/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Write-float-arrays-to-a-text-file b/Lang/Common-Lisp/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d893e9b6bb --- /dev/null +++ b/Lang/Common-Lisp/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/XML-DOM-serialization b/Lang/Common-Lisp/XML-DOM-serialization new file mode 120000 index 0000000000..a6a8eabf26 --- /dev/null +++ b/Lang/Common-Lisp/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/XML-Input b/Lang/Common-Lisp/XML-Input new file mode 120000 index 0000000000..6fc3869feb --- /dev/null +++ b/Lang/Common-Lisp/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/XML-Output b/Lang/Common-Lisp/XML-Output new file mode 120000 index 0000000000..f955218bc5 --- /dev/null +++ b/Lang/Common-Lisp/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/XML-XPath b/Lang/Common-Lisp/XML-XPath new file mode 120000 index 0000000000..abfa7904c0 --- /dev/null +++ b/Lang/Common-Lisp/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Y-combinator b/Lang/Common-Lisp/Y-combinator new file mode 120000 index 0000000000..921569df62 --- /dev/null +++ b/Lang/Common-Lisp/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Zeckendorf-number-representation b/Lang/Common-Lisp/Zeckendorf-number-representation new file mode 120000 index 0000000000..5d518c85a5 --- /dev/null +++ b/Lang/Common-Lisp/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Zig-zag-matrix b/Lang/Common-Lisp/Zig-zag-matrix new file mode 120000 index 0000000000..97afd1aee7 --- /dev/null +++ b/Lang/Common-Lisp/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/String-length b/Lang/Component-Pascal/String-length new file mode 120000 index 0000000000..704913b16e --- /dev/null +++ b/Lang/Component-Pascal/String-length @@ -0,0 +1 @@ +../../Task/String-length/Component-Pascal \ No newline at end of file diff --git a/Lang/Curry/Sorting-algorithms-Merge-sort b/Lang/Curry/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..45e2896c7c --- /dev/null +++ b/Lang/Curry/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Curry \ No newline at end of file diff --git a/Lang/Curry/Sorting-algorithms-Quicksort b/Lang/Curry/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..bc601a9b7e --- /dev/null +++ b/Lang/Curry/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Curry \ No newline at end of file diff --git a/Lang/Curry/Sudoku b/Lang/Curry/Sudoku new file mode 120000 index 0000000000..108ca9b2dd --- /dev/null +++ b/Lang/Curry/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Curry \ No newline at end of file diff --git a/Lang/D/SHA-1 b/Lang/D/SHA-1 new file mode 120000 index 0000000000..0a141841ff --- /dev/null +++ b/Lang/D/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/D \ No newline at end of file diff --git a/Lang/D/Set-puzzle b/Lang/D/Set-puzzle new file mode 120000 index 0000000000..82844ef1c8 --- /dev/null +++ b/Lang/D/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/D \ No newline at end of file diff --git a/Lang/D/Seven-sided-dice-from-five-sided-dice b/Lang/D/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..4c06fdb774 --- /dev/null +++ b/Lang/D/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/D \ No newline at end of file diff --git a/Lang/D/Shell-one-liner b/Lang/D/Shell-one-liner new file mode 120000 index 0000000000..cc2996df08 --- /dev/null +++ b/Lang/D/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/D \ No newline at end of file diff --git a/Lang/D/Short-circuit-evaluation b/Lang/D/Short-circuit-evaluation new file mode 120000 index 0000000000..494af5758d --- /dev/null +++ b/Lang/D/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/D \ No newline at end of file diff --git a/Lang/D/Sierpinski-carpet b/Lang/D/Sierpinski-carpet new file mode 120000 index 0000000000..6ba9b8ae7a --- /dev/null +++ b/Lang/D/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/D \ No newline at end of file diff --git a/Lang/D/Sierpinski-triangle b/Lang/D/Sierpinski-triangle new file mode 120000 index 0000000000..a8373f893a --- /dev/null +++ b/Lang/D/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/D \ No newline at end of file diff --git a/Lang/D/Sierpinski-triangle-Graphical b/Lang/D/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..e123ae46bf --- /dev/null +++ b/Lang/D/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/D \ No newline at end of file diff --git a/Lang/D/Sieve-of-Eratosthenes b/Lang/D/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..a5ac789d71 --- /dev/null +++ b/Lang/D/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/D \ No newline at end of file diff --git a/Lang/D/Simple-database b/Lang/D/Simple-database new file mode 120000 index 0000000000..a921c64604 --- /dev/null +++ b/Lang/D/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/D \ No newline at end of file diff --git a/Lang/D/Simple-windowed-application b/Lang/D/Simple-windowed-application new file mode 120000 index 0000000000..1d07f2eb1d --- /dev/null +++ b/Lang/D/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/D \ No newline at end of file diff --git a/Lang/D/Singleton b/Lang/D/Singleton new file mode 120000 index 0000000000..c979b8016b --- /dev/null +++ b/Lang/D/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/D \ No newline at end of file diff --git a/Lang/D/Singly-linked-list-Element-definition b/Lang/D/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..53c269b948 --- /dev/null +++ b/Lang/D/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/D \ No newline at end of file diff --git a/Lang/D/Singly-linked-list-Element-insertion b/Lang/D/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..b7d26fff61 --- /dev/null +++ b/Lang/D/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/D \ No newline at end of file diff --git a/Lang/D/Singly-linked-list-Traversal b/Lang/D/Singly-linked-list-Traversal new file mode 120000 index 0000000000..9db033e04f --- /dev/null +++ b/Lang/D/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/D \ No newline at end of file diff --git a/Lang/D/Sleep b/Lang/D/Sleep new file mode 120000 index 0000000000..22bacab817 --- /dev/null +++ b/Lang/D/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/D \ No newline at end of file diff --git a/Lang/D/Sockets b/Lang/D/Sockets new file mode 120000 index 0000000000..739a2290f9 --- /dev/null +++ b/Lang/D/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/D \ No newline at end of file diff --git a/Lang/D/Sokoban b/Lang/D/Sokoban new file mode 120000 index 0000000000..9fe6d0901f --- /dev/null +++ b/Lang/D/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/D \ No newline at end of file diff --git a/Lang/D/Solve-a-Hidato-puzzle b/Lang/D/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..29a29869ae --- /dev/null +++ b/Lang/D/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/D \ No newline at end of file diff --git a/Lang/D/Sort-an-array-of-composite-structures b/Lang/D/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..e40949ff8b --- /dev/null +++ b/Lang/D/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/D \ No newline at end of file diff --git a/Lang/D/Sort-an-integer-array b/Lang/D/Sort-an-integer-array new file mode 120000 index 0000000000..97eec3dd5c --- /dev/null +++ b/Lang/D/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/D \ No newline at end of file diff --git a/Lang/D/Sort-disjoint-sublist b/Lang/D/Sort-disjoint-sublist new file mode 120000 index 0000000000..4a18cfd905 --- /dev/null +++ b/Lang/D/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/D \ No newline at end of file diff --git a/Lang/D/Sort-using-a-custom-comparator b/Lang/D/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..ff10de4061 --- /dev/null +++ b/Lang/D/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Bead-sort b/Lang/D/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..134ff852b0 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Bogosort b/Lang/D/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..01a1893910 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Bubble-sort b/Lang/D/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8b7e55509f --- /dev/null +++ b/Lang/D/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Cocktail-sort b/Lang/D/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..7a54dfd9e2 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Comb-sort b/Lang/D/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..af8db786f1 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Counting-sort b/Lang/D/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..998ab0d15c --- /dev/null +++ b/Lang/D/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Gnome-sort b/Lang/D/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..14c83a642c --- /dev/null +++ b/Lang/D/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Heapsort b/Lang/D/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..d6aab46f70 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Insertion-sort b/Lang/D/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..313c688ed4 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Merge-sort b/Lang/D/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..dfea5a88fd --- /dev/null +++ b/Lang/D/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Pancake-sort b/Lang/D/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..0117f15141 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Permutation-sort b/Lang/D/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..7985e93180 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Quicksort b/Lang/D/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..7444e7ff98 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Radix-sort b/Lang/D/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..dfaa7c5404 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Selection-sort b/Lang/D/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..34e08987d1 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Shell-sort b/Lang/D/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..da80f96895 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Sleep-sort b/Lang/D/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..89b64f9a44 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Stooge-sort b/Lang/D/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..64c6d012d7 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/D \ No newline at end of file diff --git a/Lang/D/Sorting-algorithms-Strand-sort b/Lang/D/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..5011a0afb9 --- /dev/null +++ b/Lang/D/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/D \ No newline at end of file diff --git a/Lang/D/Soundex b/Lang/D/Soundex new file mode 120000 index 0000000000..eccfc1f9c0 --- /dev/null +++ b/Lang/D/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/D \ No newline at end of file diff --git a/Lang/D/Spiral-matrix b/Lang/D/Spiral-matrix new file mode 120000 index 0000000000..3cfb0ddf62 --- /dev/null +++ b/Lang/D/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/D \ No newline at end of file diff --git a/Lang/D/Stable-marriage-problem b/Lang/D/Stable-marriage-problem new file mode 120000 index 0000000000..a9b39d605e --- /dev/null +++ b/Lang/D/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/D \ No newline at end of file diff --git a/Lang/D/Stack b/Lang/D/Stack new file mode 120000 index 0000000000..fa844e4db3 --- /dev/null +++ b/Lang/D/Stack @@ -0,0 +1 @@ +../../Task/Stack/D \ No newline at end of file diff --git a/Lang/D/Stack-traces b/Lang/D/Stack-traces new file mode 120000 index 0000000000..aef8f8f5b2 --- /dev/null +++ b/Lang/D/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/D \ No newline at end of file diff --git a/Lang/D/Stair-climbing-puzzle b/Lang/D/Stair-climbing-puzzle new file mode 120000 index 0000000000..5d95d6d757 --- /dev/null +++ b/Lang/D/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/D \ No newline at end of file diff --git a/Lang/D/Standard-deviation b/Lang/D/Standard-deviation new file mode 120000 index 0000000000..d3a2132ae9 --- /dev/null +++ b/Lang/D/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/D \ No newline at end of file diff --git a/Lang/D/Stem-and-leaf-plot b/Lang/D/Stem-and-leaf-plot new file mode 120000 index 0000000000..15880ccadc --- /dev/null +++ b/Lang/D/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/D \ No newline at end of file diff --git a/Lang/D/String-case b/Lang/D/String-case new file mode 120000 index 0000000000..92c77473ea --- /dev/null +++ b/Lang/D/String-case @@ -0,0 +1 @@ +../../Task/String-case/D \ No newline at end of file diff --git a/Lang/D/String-comparison b/Lang/D/String-comparison new file mode 120000 index 0000000000..b2c402ba25 --- /dev/null +++ b/Lang/D/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/D \ No newline at end of file diff --git a/Lang/D/String-concatenation b/Lang/D/String-concatenation new file mode 120000 index 0000000000..d7714babfd --- /dev/null +++ b/Lang/D/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/D \ No newline at end of file diff --git a/Lang/D/String-interpolation--included- b/Lang/D/String-interpolation--included- new file mode 120000 index 0000000000..becedf67ca --- /dev/null +++ b/Lang/D/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/D \ No newline at end of file diff --git a/Lang/D/String-length b/Lang/D/String-length new file mode 120000 index 0000000000..610516b555 --- /dev/null +++ b/Lang/D/String-length @@ -0,0 +1 @@ +../../Task/String-length/D \ No newline at end of file diff --git a/Lang/D/Strip-a-set-of-characters-from-a-string b/Lang/D/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..d947a74e82 --- /dev/null +++ b/Lang/D/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/D \ No newline at end of file diff --git a/Lang/D/Strip-block-comments b/Lang/D/Strip-block-comments new file mode 120000 index 0000000000..3a7851f1fc --- /dev/null +++ b/Lang/D/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/D \ No newline at end of file diff --git a/Lang/D/Strip-comments-from-a-string b/Lang/D/Strip-comments-from-a-string new file mode 120000 index 0000000000..877e12d4fe --- /dev/null +++ b/Lang/D/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/D \ No newline at end of file diff --git a/Lang/D/Strip-control-codes-and-extended-characters-from-a-string b/Lang/D/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..815dd04b50 --- /dev/null +++ b/Lang/D/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/D \ No newline at end of file diff --git a/Lang/D/Strip-whitespace-from-a-string-Top-and-tail b/Lang/D/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..1a9922579f --- /dev/null +++ b/Lang/D/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/D \ No newline at end of file diff --git a/Lang/D/Substring b/Lang/D/Substring new file mode 120000 index 0000000000..7cc28389ac --- /dev/null +++ b/Lang/D/Substring @@ -0,0 +1 @@ +../../Task/Substring/D \ No newline at end of file diff --git a/Lang/D/Substring-Top-and-tail b/Lang/D/Substring-Top-and-tail new file mode 120000 index 0000000000..090ba6cc51 --- /dev/null +++ b/Lang/D/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/D \ No newline at end of file diff --git a/Lang/D/Subtractive-generator b/Lang/D/Subtractive-generator new file mode 120000 index 0000000000..3a0918a47b --- /dev/null +++ b/Lang/D/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/D \ No newline at end of file diff --git a/Lang/D/Sudoku b/Lang/D/Sudoku new file mode 120000 index 0000000000..f40272fc76 --- /dev/null +++ b/Lang/D/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/D \ No newline at end of file diff --git a/Lang/D/Sum-and-product-of-an-array b/Lang/D/Sum-and-product-of-an-array new file mode 120000 index 0000000000..638fec07fa --- /dev/null +++ b/Lang/D/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/D \ No newline at end of file diff --git a/Lang/D/Sum-digits-of-an-integer b/Lang/D/Sum-digits-of-an-integer new file mode 120000 index 0000000000..deb81a8f48 --- /dev/null +++ b/Lang/D/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/D \ No newline at end of file diff --git a/Lang/D/Sum-of-a-series b/Lang/D/Sum-of-a-series new file mode 120000 index 0000000000..71e8c4eaeb --- /dev/null +++ b/Lang/D/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/D \ No newline at end of file diff --git a/Lang/D/Sum-of-squares b/Lang/D/Sum-of-squares new file mode 120000 index 0000000000..81d2cfaebd --- /dev/null +++ b/Lang/D/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/D \ No newline at end of file diff --git a/Lang/D/Sutherland-Hodgman-polygon-clipping b/Lang/D/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..d1e3f4d2f9 --- /dev/null +++ b/Lang/D/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/D \ No newline at end of file diff --git a/Lang/D/Symmetric-difference b/Lang/D/Symmetric-difference new file mode 120000 index 0000000000..85d72a6174 --- /dev/null +++ b/Lang/D/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/D \ No newline at end of file diff --git a/Lang/D/Synchronous-concurrency b/Lang/D/Synchronous-concurrency new file mode 120000 index 0000000000..263cbce60a --- /dev/null +++ b/Lang/D/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/D \ No newline at end of file diff --git a/Lang/D/System-time b/Lang/D/System-time new file mode 120000 index 0000000000..ad86563cfe --- /dev/null +++ b/Lang/D/System-time @@ -0,0 +1 @@ +../../Task/System-time/D \ No newline at end of file diff --git a/Lang/D/Take-notes-on-the-command-line b/Lang/D/Take-notes-on-the-command-line new file mode 120000 index 0000000000..61b9263035 --- /dev/null +++ b/Lang/D/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/D \ No newline at end of file diff --git a/Lang/D/Temperature-conversion b/Lang/D/Temperature-conversion new file mode 120000 index 0000000000..f9ce9c84c7 --- /dev/null +++ b/Lang/D/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/D \ No newline at end of file diff --git a/Lang/D/Terminal-control-Clear-the-screen b/Lang/D/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..aeb568e98f --- /dev/null +++ b/Lang/D/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/D \ No newline at end of file diff --git a/Lang/D/Terminal-control-Display-an-extended-character b/Lang/D/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..4e41a68c64 --- /dev/null +++ b/Lang/D/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/D \ No newline at end of file diff --git a/Lang/D/Ternary-logic b/Lang/D/Ternary-logic new file mode 120000 index 0000000000..903739801a --- /dev/null +++ b/Lang/D/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/D \ No newline at end of file diff --git a/Lang/D/Test-a-function b/Lang/D/Test-a-function new file mode 120000 index 0000000000..9bc09bb4d2 --- /dev/null +++ b/Lang/D/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/D \ No newline at end of file diff --git a/Lang/D/Text-processing-1 b/Lang/D/Text-processing-1 new file mode 120000 index 0000000000..d3f5b0b856 --- /dev/null +++ b/Lang/D/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/D \ No newline at end of file diff --git a/Lang/D/Text-processing-2 b/Lang/D/Text-processing-2 new file mode 120000 index 0000000000..c9f21bbf44 --- /dev/null +++ b/Lang/D/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/D \ No newline at end of file diff --git a/Lang/D/Text-processing-Max-licenses-in-use b/Lang/D/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..f1aa29f229 --- /dev/null +++ b/Lang/D/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/D \ No newline at end of file diff --git a/Lang/D/Thieles-interpolation-formula b/Lang/D/Thieles-interpolation-formula new file mode 120000 index 0000000000..3fca2c3f2f --- /dev/null +++ b/Lang/D/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/D \ No newline at end of file diff --git a/Lang/D/Tic-tac-toe b/Lang/D/Tic-tac-toe new file mode 120000 index 0000000000..15b1921eff --- /dev/null +++ b/Lang/D/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/D \ No newline at end of file diff --git a/Lang/D/Time-a-function b/Lang/D/Time-a-function new file mode 120000 index 0000000000..a0e7d8bff4 --- /dev/null +++ b/Lang/D/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/D \ No newline at end of file diff --git a/Lang/D/Tokenize-a-string b/Lang/D/Tokenize-a-string new file mode 120000 index 0000000000..bc6eba7f0c --- /dev/null +++ b/Lang/D/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/D \ No newline at end of file diff --git a/Lang/D/Top-rank-per-group b/Lang/D/Top-rank-per-group new file mode 120000 index 0000000000..f0a553b6ca --- /dev/null +++ b/Lang/D/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/D \ No newline at end of file diff --git a/Lang/D/Topological-sort b/Lang/D/Topological-sort new file mode 120000 index 0000000000..00a0486349 --- /dev/null +++ b/Lang/D/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/D \ No newline at end of file diff --git a/Lang/D/Topswops b/Lang/D/Topswops new file mode 120000 index 0000000000..569787d53c --- /dev/null +++ b/Lang/D/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/D \ No newline at end of file diff --git a/Lang/D/Towers-of-Hanoi b/Lang/D/Towers-of-Hanoi new file mode 120000 index 0000000000..739e502fb2 --- /dev/null +++ b/Lang/D/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/D \ No newline at end of file diff --git a/Lang/D/Trabb-Pardo-Knuth-algorithm b/Lang/D/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..0441b3aca2 --- /dev/null +++ b/Lang/D/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/D \ No newline at end of file diff --git a/Lang/D/Tree-traversal b/Lang/D/Tree-traversal new file mode 120000 index 0000000000..c340c4d13a --- /dev/null +++ b/Lang/D/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/D \ No newline at end of file diff --git a/Lang/D/Trigonometric-functions b/Lang/D/Trigonometric-functions new file mode 120000 index 0000000000..289cc05407 --- /dev/null +++ b/Lang/D/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/D \ No newline at end of file diff --git a/Lang/D/Truncatable-primes b/Lang/D/Truncatable-primes new file mode 120000 index 0000000000..9772b1fd67 --- /dev/null +++ b/Lang/D/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/D \ No newline at end of file diff --git a/Lang/D/Truncate-a-file b/Lang/D/Truncate-a-file new file mode 120000 index 0000000000..09042c4f76 --- /dev/null +++ b/Lang/D/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/D \ No newline at end of file diff --git a/Lang/D/Twelve-statements b/Lang/D/Twelve-statements new file mode 120000 index 0000000000..e272c21733 --- /dev/null +++ b/Lang/D/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/D \ No newline at end of file diff --git a/Lang/D/URL-decoding b/Lang/D/URL-decoding new file mode 120000 index 0000000000..b983a46f36 --- /dev/null +++ b/Lang/D/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/D \ No newline at end of file diff --git a/Lang/D/URL-encoding b/Lang/D/URL-encoding new file mode 120000 index 0000000000..89cd09224d --- /dev/null +++ b/Lang/D/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/D \ No newline at end of file diff --git a/Lang/D/Unbias-a-random-generator b/Lang/D/Unbias-a-random-generator new file mode 120000 index 0000000000..d1770cf8b7 --- /dev/null +++ b/Lang/D/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/D \ No newline at end of file diff --git a/Lang/D/Undefined-values b/Lang/D/Undefined-values new file mode 120000 index 0000000000..21f97adf0a --- /dev/null +++ b/Lang/D/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/D \ No newline at end of file diff --git a/Lang/D/Unicode-variable-names b/Lang/D/Unicode-variable-names new file mode 120000 index 0000000000..419ca70fda --- /dev/null +++ b/Lang/D/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/D \ No newline at end of file diff --git a/Lang/D/Universal-Turing-machine b/Lang/D/Universal-Turing-machine new file mode 120000 index 0000000000..5a1f3f1950 --- /dev/null +++ b/Lang/D/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/D \ No newline at end of file diff --git a/Lang/D/Update-a-configuration-file b/Lang/D/Update-a-configuration-file new file mode 120000 index 0000000000..4c2e144ed2 --- /dev/null +++ b/Lang/D/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/D \ No newline at end of file diff --git a/Lang/D/User-input-Text b/Lang/D/User-input-Text new file mode 120000 index 0000000000..4ae2ebb45a --- /dev/null +++ b/Lang/D/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/D \ No newline at end of file diff --git a/Lang/D/Vampire-number b/Lang/D/Vampire-number new file mode 120000 index 0000000000..77fb5f0955 --- /dev/null +++ b/Lang/D/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/D \ No newline at end of file diff --git a/Lang/D/Van-der-Corput-sequence b/Lang/D/Van-der-Corput-sequence new file mode 120000 index 0000000000..ee6c19bd7c --- /dev/null +++ b/Lang/D/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/D \ No newline at end of file diff --git a/Lang/D/Variable-length-quantity b/Lang/D/Variable-length-quantity new file mode 120000 index 0000000000..f8a1e79e21 --- /dev/null +++ b/Lang/D/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/D \ No newline at end of file diff --git a/Lang/D/Variable-size-Get b/Lang/D/Variable-size-Get new file mode 120000 index 0000000000..f4aec58139 --- /dev/null +++ b/Lang/D/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/D \ No newline at end of file diff --git a/Lang/D/Variable-size-Set b/Lang/D/Variable-size-Set new file mode 120000 index 0000000000..3037f50cce --- /dev/null +++ b/Lang/D/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/D \ No newline at end of file diff --git a/Lang/D/Variables b/Lang/D/Variables new file mode 120000 index 0000000000..c4fbcfd6a2 --- /dev/null +++ b/Lang/D/Variables @@ -0,0 +1 @@ +../../Task/Variables/D \ No newline at end of file diff --git a/Lang/D/Variadic-function b/Lang/D/Variadic-function new file mode 120000 index 0000000000..fea091a7f8 --- /dev/null +++ b/Lang/D/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/D \ No newline at end of file diff --git a/Lang/D/Vector-products b/Lang/D/Vector-products new file mode 120000 index 0000000000..281e1aaf29 --- /dev/null +++ b/Lang/D/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/D \ No newline at end of file diff --git a/Lang/D/Verify-distribution-uniformity-Chi-squared-test b/Lang/D/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..fd0a62e958 --- /dev/null +++ b/Lang/D/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/D \ No newline at end of file diff --git a/Lang/D/Verify-distribution-uniformity-Naive b/Lang/D/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..d2fdc90866 --- /dev/null +++ b/Lang/D/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/D \ No newline at end of file diff --git a/Lang/D/Vigen-re-cipher b/Lang/D/Vigen-re-cipher new file mode 120000 index 0000000000..ac5dc4def8 --- /dev/null +++ b/Lang/D/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/D \ No newline at end of file diff --git a/Lang/D/Vigen-re-cipher-Cryptanalysis b/Lang/D/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..4daa519504 --- /dev/null +++ b/Lang/D/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/D \ No newline at end of file diff --git a/Lang/D/Visualize-a-tree b/Lang/D/Visualize-a-tree new file mode 120000 index 0000000000..6e62a92650 --- /dev/null +++ b/Lang/D/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/D \ No newline at end of file diff --git a/Lang/D/Voronoi-diagram b/Lang/D/Voronoi-diagram new file mode 120000 index 0000000000..bbb1607919 --- /dev/null +++ b/Lang/D/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/D \ No newline at end of file diff --git a/Lang/D/Walk-a-directory-Non-recursively b/Lang/D/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b4837dfa33 --- /dev/null +++ b/Lang/D/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/D \ No newline at end of file diff --git a/Lang/D/Walk-a-directory-Recursively b/Lang/D/Walk-a-directory-Recursively new file mode 120000 index 0000000000..8528c5c3a3 --- /dev/null +++ b/Lang/D/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/D \ No newline at end of file diff --git a/Lang/D/Web-scraping b/Lang/D/Web-scraping new file mode 120000 index 0000000000..dd14db4158 --- /dev/null +++ b/Lang/D/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/D \ No newline at end of file diff --git a/Lang/D/Window-creation b/Lang/D/Window-creation new file mode 120000 index 0000000000..5e4f2ee2ae --- /dev/null +++ b/Lang/D/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/D \ No newline at end of file diff --git a/Lang/D/Wireworld b/Lang/D/Wireworld new file mode 120000 index 0000000000..908cd5b8ab --- /dev/null +++ b/Lang/D/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/D \ No newline at end of file diff --git a/Lang/D/Word-wrap b/Lang/D/Word-wrap new file mode 120000 index 0000000000..cce152fbc0 --- /dev/null +++ b/Lang/D/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/D \ No newline at end of file diff --git a/Lang/D/Write-float-arrays-to-a-text-file b/Lang/D/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..c999445674 --- /dev/null +++ b/Lang/D/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/D \ No newline at end of file diff --git a/Lang/D/Write-language-name-in-3D-ASCII b/Lang/D/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..dfe58341cf --- /dev/null +++ b/Lang/D/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/D \ No newline at end of file diff --git a/Lang/D/XML-DOM-serialization b/Lang/D/XML-DOM-serialization new file mode 120000 index 0000000000..3c9d878f70 --- /dev/null +++ b/Lang/D/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/D \ No newline at end of file diff --git a/Lang/D/XML-Input b/Lang/D/XML-Input new file mode 120000 index 0000000000..4226ff964a --- /dev/null +++ b/Lang/D/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/D \ No newline at end of file diff --git a/Lang/D/XML-Output b/Lang/D/XML-Output new file mode 120000 index 0000000000..b2deb1860e --- /dev/null +++ b/Lang/D/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/D \ No newline at end of file diff --git a/Lang/D/XML-XPath b/Lang/D/XML-XPath new file mode 120000 index 0000000000..00b5638f02 --- /dev/null +++ b/Lang/D/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/D \ No newline at end of file diff --git a/Lang/D/Xiaolin-Wus-line-algorithm b/Lang/D/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..07853cfe25 --- /dev/null +++ b/Lang/D/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/D \ No newline at end of file diff --git a/Lang/D/Y-combinator b/Lang/D/Y-combinator new file mode 120000 index 0000000000..26341364df --- /dev/null +++ b/Lang/D/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/D \ No newline at end of file diff --git a/Lang/D/Yin-and-yang b/Lang/D/Yin-and-yang new file mode 120000 index 0000000000..6feee311f8 --- /dev/null +++ b/Lang/D/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/D \ No newline at end of file diff --git a/Lang/D/Zebra-puzzle b/Lang/D/Zebra-puzzle new file mode 120000 index 0000000000..0901ca9739 --- /dev/null +++ b/Lang/D/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/D \ No newline at end of file diff --git a/Lang/D/Zeckendorf-number-representation b/Lang/D/Zeckendorf-number-representation new file mode 120000 index 0000000000..ef191ce9f3 --- /dev/null +++ b/Lang/D/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/D \ No newline at end of file diff --git a/Lang/D/Zig-zag-matrix b/Lang/D/Zig-zag-matrix new file mode 120000 index 0000000000..c58ec45cbb --- /dev/null +++ b/Lang/D/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/D \ No newline at end of file diff --git a/Lang/DWScript/Sierpinski-carpet b/Lang/DWScript/Sierpinski-carpet new file mode 120000 index 0000000000..663669022c --- /dev/null +++ b/Lang/DWScript/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Sierpinski-triangle b/Lang/DWScript/Sierpinski-triangle new file mode 120000 index 0000000000..b13cfba4a7 --- /dev/null +++ b/Lang/DWScript/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Sieve-of-Eratosthenes b/Lang/DWScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ee21fbeac8 --- /dev/null +++ b/Lang/DWScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Sorting-algorithms-Gnome-sort b/Lang/DWScript/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..3a87702f29 --- /dev/null +++ b/Lang/DWScript/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Stack b/Lang/DWScript/Stack new file mode 120000 index 0000000000..a64cf8f0c7 --- /dev/null +++ b/Lang/DWScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Stack-traces b/Lang/DWScript/Stack-traces new file mode 120000 index 0000000000..9577b4bd35 --- /dev/null +++ b/Lang/DWScript/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/DWScript \ No newline at end of file diff --git a/Lang/DWScript/String-case b/Lang/DWScript/String-case new file mode 120000 index 0000000000..2eb1d32eda --- /dev/null +++ b/Lang/DWScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/DWScript \ No newline at end of file diff --git a/Lang/DWScript/String-concatenation b/Lang/DWScript/String-concatenation new file mode 120000 index 0000000000..5f62fed258 --- /dev/null +++ b/Lang/DWScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/DWScript \ No newline at end of file diff --git a/Lang/DWScript/String-interpolation--included- b/Lang/DWScript/String-interpolation--included- new file mode 120000 index 0000000000..6cead47899 --- /dev/null +++ b/Lang/DWScript/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Strip-comments-from-a-string b/Lang/DWScript/Strip-comments-from-a-string new file mode 120000 index 0000000000..fc5a1a76c9 --- /dev/null +++ b/Lang/DWScript/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Strip-whitespace-from-a-string-Top-and-tail b/Lang/DWScript/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..5cbe52d72c --- /dev/null +++ b/Lang/DWScript/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Sum-of-a-series b/Lang/DWScript/Sum-of-a-series new file mode 120000 index 0000000000..80a0d9f649 --- /dev/null +++ b/Lang/DWScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/DWScript \ No newline at end of file diff --git a/Lang/DWScript/System-time b/Lang/DWScript/System-time new file mode 120000 index 0000000000..7b38dd9b78 --- /dev/null +++ b/Lang/DWScript/System-time @@ -0,0 +1 @@ +../../Task/System-time/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Unicode-variable-names b/Lang/DWScript/Unicode-variable-names new file mode 120000 index 0000000000..5f7de9f618 --- /dev/null +++ b/Lang/DWScript/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Variables b/Lang/DWScript/Variables new file mode 120000 index 0000000000..860a9236cf --- /dev/null +++ b/Lang/DWScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/DWScript \ No newline at end of file diff --git a/Lang/DWScript/Yin-and-yang b/Lang/DWScript/Yin-and-yang new file mode 120000 index 0000000000..b6c7c030b5 --- /dev/null +++ b/Lang/DWScript/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/DWScript \ No newline at end of file diff --git a/Lang/Dart/Show-the-epoch b/Lang/Dart/Show-the-epoch new file mode 120000 index 0000000000..35cb8be422 --- /dev/null +++ b/Lang/Dart/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Dart \ No newline at end of file diff --git a/Lang/Dart/Sieve-of-Eratosthenes b/Lang/Dart/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..cd000d6a57 --- /dev/null +++ b/Lang/Dart/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Dart \ No newline at end of file diff --git a/Lang/Dart/Sorting-algorithms-Heapsort b/Lang/Dart/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..b31c38d76e --- /dev/null +++ b/Lang/Dart/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Dart \ No newline at end of file diff --git a/Lang/Dart/Sorting-algorithms-Merge-sort b/Lang/Dart/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..b8a906d202 --- /dev/null +++ b/Lang/Dart/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Dart \ No newline at end of file diff --git a/Lang/Dart/Sorting-algorithms-Quicksort b/Lang/Dart/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..a39c74df61 --- /dev/null +++ b/Lang/Dart/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Dart \ No newline at end of file diff --git a/Lang/Dart/Sum-of-squares b/Lang/Dart/Sum-of-squares new file mode 120000 index 0000000000..3e0ee532ab --- /dev/null +++ b/Lang/Dart/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Dart \ No newline at end of file diff --git a/Lang/Dart/Towers-of-Hanoi b/Lang/Dart/Towers-of-Hanoi new file mode 120000 index 0000000000..7b8d0b5b59 --- /dev/null +++ b/Lang/Dart/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Dart \ No newline at end of file diff --git a/Lang/Dc/Shell-one-liner b/Lang/Dc/Shell-one-liner new file mode 120000 index 0000000000..ba0550ce13 --- /dev/null +++ b/Lang/Dc/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Dc \ No newline at end of file diff --git a/Lang/Dc/String-length b/Lang/Dc/String-length new file mode 120000 index 0000000000..330aab91c2 --- /dev/null +++ b/Lang/Dc/String-length @@ -0,0 +1 @@ +../../Task/String-length/Dc \ No newline at end of file diff --git a/Lang/Delphi/Short-circuit-evaluation b/Lang/Delphi/Short-circuit-evaluation new file mode 120000 index 0000000000..c0afc37d36 --- /dev/null +++ b/Lang/Delphi/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Show-the-epoch b/Lang/Delphi/Show-the-epoch new file mode 120000 index 0000000000..3dbd666644 --- /dev/null +++ b/Lang/Delphi/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sierpinski-triangle b/Lang/Delphi/Sierpinski-triangle new file mode 120000 index 0000000000..2290006f06 --- /dev/null +++ b/Lang/Delphi/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Simple-windowed-application b/Lang/Delphi/Simple-windowed-application new file mode 120000 index 0000000000..efa842f99c --- /dev/null +++ b/Lang/Delphi/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Singleton b/Lang/Delphi/Singleton new file mode 120000 index 0000000000..626c70efc7 --- /dev/null +++ b/Lang/Delphi/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Singly-linked-list-Element-definition b/Lang/Delphi/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..6d20f83450 --- /dev/null +++ b/Lang/Delphi/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Singly-linked-list-Element-insertion b/Lang/Delphi/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..2682c6fcd9 --- /dev/null +++ b/Lang/Delphi/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Singly-linked-list-Traversal b/Lang/Delphi/Singly-linked-list-Traversal new file mode 120000 index 0000000000..a2fdce6717 --- /dev/null +++ b/Lang/Delphi/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sleep b/Lang/Delphi/Sleep new file mode 120000 index 0000000000..cdc8c63d99 --- /dev/null +++ b/Lang/Delphi/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sockets b/Lang/Delphi/Sockets new file mode 120000 index 0000000000..2fd03fdffc --- /dev/null +++ b/Lang/Delphi/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sort-an-array-of-composite-structures b/Lang/Delphi/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..778bdf4137 --- /dev/null +++ b/Lang/Delphi/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sort-an-integer-array b/Lang/Delphi/Sort-an-integer-array new file mode 120000 index 0000000000..2ef1da81ac --- /dev/null +++ b/Lang/Delphi/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sort-using-a-custom-comparator b/Lang/Delphi/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..309bed5d5d --- /dev/null +++ b/Lang/Delphi/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Bead-sort b/Lang/Delphi/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..876a542ee5 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Bubble-sort b/Lang/Delphi/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..5e54b0b059 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Cocktail-sort b/Lang/Delphi/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..2a89ed77fd --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Gnome-sort b/Lang/Delphi/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..f49ad57212 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Insertion-sort b/Lang/Delphi/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..71c95f2374 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Selection-sort b/Lang/Delphi/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..f30f85c1c5 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-algorithms-Sleep-sort b/Lang/Delphi/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..7591284744 --- /dev/null +++ b/Lang/Delphi/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Soundex b/Lang/Delphi/Soundex new file mode 120000 index 0000000000..3f14771fe5 --- /dev/null +++ b/Lang/Delphi/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Stack b/Lang/Delphi/Stack new file mode 120000 index 0000000000..68d40cf7a0 --- /dev/null +++ b/Lang/Delphi/Stack @@ -0,0 +1 @@ +../../Task/Stack/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Standard-deviation b/Lang/Delphi/Standard-deviation new file mode 120000 index 0000000000..e4c6be14a1 --- /dev/null +++ b/Lang/Delphi/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Delphi \ No newline at end of file diff --git a/Lang/Delphi/String-case b/Lang/Delphi/String-case new file mode 120000 index 0000000000..2a01b14316 --- /dev/null +++ b/Lang/Delphi/String-case @@ -0,0 +1 @@ +../../Task/String-case/Delphi \ No newline at end of file diff --git a/Lang/Delphi/String-concatenation b/Lang/Delphi/String-concatenation new file mode 120000 index 0000000000..e669d47be6 --- /dev/null +++ b/Lang/Delphi/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Strip-a-set-of-characters-from-a-string b/Lang/Delphi/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..232efc5c6d --- /dev/null +++ b/Lang/Delphi/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Strip-comments-from-a-string b/Lang/Delphi/Strip-comments-from-a-string new file mode 120000 index 0000000000..d52689048c --- /dev/null +++ b/Lang/Delphi/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Delphi/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..1c2fe87006 --- /dev/null +++ b/Lang/Delphi/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Substring b/Lang/Delphi/Substring new file mode 120000 index 0000000000..48eca57d07 --- /dev/null +++ b/Lang/Delphi/Substring @@ -0,0 +1 @@ +../../Task/Substring/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Substring-Top-and-tail b/Lang/Delphi/Substring-Top-and-tail new file mode 120000 index 0000000000..7fef6321d5 --- /dev/null +++ b/Lang/Delphi/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sudoku b/Lang/Delphi/Sudoku new file mode 120000 index 0000000000..bc2f9e3c19 --- /dev/null +++ b/Lang/Delphi/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sum-and-product-of-an-array b/Lang/Delphi/Sum-and-product-of-an-array new file mode 120000 index 0000000000..26b6264bdf --- /dev/null +++ b/Lang/Delphi/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sum-of-a-series b/Lang/Delphi/Sum-of-a-series new file mode 120000 index 0000000000..1132c69685 --- /dev/null +++ b/Lang/Delphi/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sum-of-squares b/Lang/Delphi/Sum-of-squares new file mode 120000 index 0000000000..e52079355f --- /dev/null +++ b/Lang/Delphi/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Synchronous-concurrency b/Lang/Delphi/Synchronous-concurrency new file mode 120000 index 0000000000..234a41ad4f --- /dev/null +++ b/Lang/Delphi/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Delphi \ No newline at end of file diff --git a/Lang/Delphi/System-time b/Lang/Delphi/System-time new file mode 120000 index 0000000000..7c5122d267 --- /dev/null +++ b/Lang/Delphi/System-time @@ -0,0 +1 @@ +../../Task/System-time/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Terminal-control-Ringing-the-terminal-bell b/Lang/Delphi/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..107c394764 --- /dev/null +++ b/Lang/Delphi/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Ternary-logic b/Lang/Delphi/Ternary-logic new file mode 120000 index 0000000000..0940e008ed --- /dev/null +++ b/Lang/Delphi/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Test-a-function b/Lang/Delphi/Test-a-function new file mode 120000 index 0000000000..5d8f21851e --- /dev/null +++ b/Lang/Delphi/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Tokenize-a-string b/Lang/Delphi/Tokenize-a-string new file mode 120000 index 0000000000..70974d6e30 --- /dev/null +++ b/Lang/Delphi/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Delphi \ No newline at end of file diff --git a/Lang/Delphi/URL-decoding b/Lang/Delphi/URL-decoding new file mode 120000 index 0000000000..497afe582c --- /dev/null +++ b/Lang/Delphi/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Undefined-values b/Lang/Delphi/Undefined-values new file mode 120000 index 0000000000..f1e4d613aa --- /dev/null +++ b/Lang/Delphi/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Unicode-variable-names b/Lang/Delphi/Unicode-variable-names new file mode 120000 index 0000000000..e8fc2d9c35 --- /dev/null +++ b/Lang/Delphi/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Use-another-language-to-call-a-function b/Lang/Delphi/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..891e76b7e9 --- /dev/null +++ b/Lang/Delphi/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Delphi \ No newline at end of file diff --git a/Lang/Delphi/User-input-Graphical b/Lang/Delphi/User-input-Graphical new file mode 120000 index 0000000000..0c017eaf01 --- /dev/null +++ b/Lang/Delphi/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Delphi \ No newline at end of file diff --git a/Lang/Delphi/User-input-Text b/Lang/Delphi/User-input-Text new file mode 120000 index 0000000000..f97d0ddc47 --- /dev/null +++ b/Lang/Delphi/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Variable-size-Get b/Lang/Delphi/Variable-size-Get new file mode 120000 index 0000000000..5e5b825a45 --- /dev/null +++ b/Lang/Delphi/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Variables b/Lang/Delphi/Variables new file mode 120000 index 0000000000..fdf688fb2e --- /dev/null +++ b/Lang/Delphi/Variables @@ -0,0 +1 @@ +../../Task/Variables/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Web-scraping b/Lang/Delphi/Web-scraping new file mode 120000 index 0000000000..177dbf78ac --- /dev/null +++ b/Lang/Delphi/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Window-creation b/Lang/Delphi/Window-creation new file mode 120000 index 0000000000..d153ca6628 --- /dev/null +++ b/Lang/Delphi/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Write-to-Windows-event-log b/Lang/Delphi/Write-to-Windows-event-log new file mode 120000 index 0000000000..92321c5a59 --- /dev/null +++ b/Lang/Delphi/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Delphi \ No newline at end of file diff --git a/Lang/Delphi/XML-Input b/Lang/Delphi/XML-Input new file mode 120000 index 0000000000..a983ed8c88 --- /dev/null +++ b/Lang/Delphi/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Delphi \ No newline at end of file diff --git a/Lang/Delphi/XML-Output b/Lang/Delphi/XML-Output new file mode 120000 index 0000000000..5f6df0ad94 --- /dev/null +++ b/Lang/Delphi/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Delphi \ No newline at end of file diff --git a/Lang/Delphi/XML-XPath b/Lang/Delphi/XML-XPath new file mode 120000 index 0000000000..c2786955b0 --- /dev/null +++ b/Lang/Delphi/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Y-combinator b/Lang/Delphi/Y-combinator new file mode 120000 index 0000000000..8deaf9e853 --- /dev/null +++ b/Lang/Delphi/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Yin-and-yang b/Lang/Delphi/Yin-and-yang new file mode 120000 index 0000000000..ace3750045 --- /dev/null +++ b/Lang/Delphi/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Delphi \ No newline at end of file diff --git a/Lang/Dylan.NET/String-concatenation b/Lang/Dylan.NET/String-concatenation new file mode 120000 index 0000000000..c594822303 --- /dev/null +++ b/Lang/Dylan.NET/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Dylan.NET \ No newline at end of file diff --git a/Lang/Dylan/Sieve-of-Eratosthenes b/Lang/Dylan/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..e41e844e15 --- /dev/null +++ b/Lang/Dylan/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Dylan \ No newline at end of file diff --git a/Lang/E/Seven-sided-dice-from-five-sided-dice b/Lang/E/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..da6c981860 --- /dev/null +++ b/Lang/E/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/E \ No newline at end of file diff --git a/Lang/E/Shell-one-liner b/Lang/E/Shell-one-liner new file mode 120000 index 0000000000..7b737fb8f3 --- /dev/null +++ b/Lang/E/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/E \ No newline at end of file diff --git a/Lang/E/Short-circuit-evaluation b/Lang/E/Short-circuit-evaluation new file mode 120000 index 0000000000..e739a421ca --- /dev/null +++ b/Lang/E/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/E \ No newline at end of file diff --git a/Lang/E/Sierpinski-carpet b/Lang/E/Sierpinski-carpet new file mode 120000 index 0000000000..9dc0261622 --- /dev/null +++ b/Lang/E/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/E \ No newline at end of file diff --git a/Lang/E/Sierpinski-triangle b/Lang/E/Sierpinski-triangle new file mode 120000 index 0000000000..8d3308a79c --- /dev/null +++ b/Lang/E/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/E \ No newline at end of file diff --git a/Lang/E/Simple-windowed-application b/Lang/E/Simple-windowed-application new file mode 120000 index 0000000000..2df03bb6b9 --- /dev/null +++ b/Lang/E/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/E \ No newline at end of file diff --git a/Lang/E/Singleton b/Lang/E/Singleton new file mode 120000 index 0000000000..fb2bfbcece --- /dev/null +++ b/Lang/E/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/E \ No newline at end of file diff --git a/Lang/E/Singly-linked-list-Element-definition b/Lang/E/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..12057adccb --- /dev/null +++ b/Lang/E/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/E \ No newline at end of file diff --git a/Lang/E/Singly-linked-list-Element-insertion b/Lang/E/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..76ad350bc2 --- /dev/null +++ b/Lang/E/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/E \ No newline at end of file diff --git a/Lang/E/Singly-linked-list-Traversal b/Lang/E/Singly-linked-list-Traversal new file mode 120000 index 0000000000..c43a03556e --- /dev/null +++ b/Lang/E/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/E \ No newline at end of file diff --git a/Lang/E/Sleep b/Lang/E/Sleep new file mode 120000 index 0000000000..13feec131f --- /dev/null +++ b/Lang/E/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/E \ No newline at end of file diff --git a/Lang/E/Sort-an-array-of-composite-structures b/Lang/E/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..1ad8210673 --- /dev/null +++ b/Lang/E/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/E \ No newline at end of file diff --git a/Lang/E/Sort-an-integer-array b/Lang/E/Sort-an-integer-array new file mode 120000 index 0000000000..121ebb78e3 --- /dev/null +++ b/Lang/E/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/E \ No newline at end of file diff --git a/Lang/E/Sort-using-a-custom-comparator b/Lang/E/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..62930bea83 --- /dev/null +++ b/Lang/E/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Bogosort b/Lang/E/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..47abb9e1b3 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Bubble-sort b/Lang/E/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..3bf2fae70d --- /dev/null +++ b/Lang/E/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Cocktail-sort b/Lang/E/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..163ed128f4 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Counting-sort b/Lang/E/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..63ad00d5eb --- /dev/null +++ b/Lang/E/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Gnome-sort b/Lang/E/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..b06d98588b --- /dev/null +++ b/Lang/E/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Heapsort b/Lang/E/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..681c300ce9 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Insertion-sort b/Lang/E/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..1038988dae --- /dev/null +++ b/Lang/E/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Merge-sort b/Lang/E/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..2d61b4e130 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Permutation-sort b/Lang/E/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..7f25693103 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Quicksort b/Lang/E/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..0dad8f5cf3 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Selection-sort b/Lang/E/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ec0f2acc67 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/E \ No newline at end of file diff --git a/Lang/E/Sorting-algorithms-Shell-sort b/Lang/E/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..1c097d62a8 --- /dev/null +++ b/Lang/E/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/E \ No newline at end of file diff --git a/Lang/E/Special-characters b/Lang/E/Special-characters new file mode 120000 index 0000000000..bdec59f3f1 --- /dev/null +++ b/Lang/E/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/E \ No newline at end of file diff --git a/Lang/E/Spiral-matrix b/Lang/E/Spiral-matrix new file mode 120000 index 0000000000..2c8379d18e --- /dev/null +++ b/Lang/E/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/E \ No newline at end of file diff --git a/Lang/E/Stack b/Lang/E/Stack new file mode 120000 index 0000000000..73f8d706ae --- /dev/null +++ b/Lang/E/Stack @@ -0,0 +1 @@ +../../Task/Stack/E \ No newline at end of file diff --git a/Lang/E/Stair-climbing-puzzle b/Lang/E/Stair-climbing-puzzle new file mode 120000 index 0000000000..4c42106c1a --- /dev/null +++ b/Lang/E/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/E \ No newline at end of file diff --git a/Lang/E/Standard-deviation b/Lang/E/Standard-deviation new file mode 120000 index 0000000000..606d9f7d55 --- /dev/null +++ b/Lang/E/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/E \ No newline at end of file diff --git a/Lang/E/String-case b/Lang/E/String-case new file mode 120000 index 0000000000..8807c1d6c5 --- /dev/null +++ b/Lang/E/String-case @@ -0,0 +1 @@ +../../Task/String-case/E \ No newline at end of file diff --git a/Lang/E/String-interpolation--included- b/Lang/E/String-interpolation--included- new file mode 120000 index 0000000000..6b1e4451d6 --- /dev/null +++ b/Lang/E/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/E \ No newline at end of file diff --git a/Lang/E/String-length b/Lang/E/String-length new file mode 120000 index 0000000000..9fc83f3c1e --- /dev/null +++ b/Lang/E/String-length @@ -0,0 +1 @@ +../../Task/String-length/E \ No newline at end of file diff --git a/Lang/E/Substring b/Lang/E/Substring new file mode 120000 index 0000000000..279357d087 --- /dev/null +++ b/Lang/E/Substring @@ -0,0 +1 @@ +../../Task/Substring/E \ No newline at end of file diff --git a/Lang/E/Sum-and-product-of-an-array b/Lang/E/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f1e6020a17 --- /dev/null +++ b/Lang/E/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/E \ No newline at end of file diff --git a/Lang/E/Sum-of-a-series b/Lang/E/Sum-of-a-series new file mode 120000 index 0000000000..6fccbd93d6 --- /dev/null +++ b/Lang/E/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/E \ No newline at end of file diff --git a/Lang/E/Sum-of-squares b/Lang/E/Sum-of-squares new file mode 120000 index 0000000000..115bc0296b --- /dev/null +++ b/Lang/E/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/E \ No newline at end of file diff --git a/Lang/E/Symmetric-difference b/Lang/E/Symmetric-difference new file mode 120000 index 0000000000..35d42de6be --- /dev/null +++ b/Lang/E/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/E \ No newline at end of file diff --git a/Lang/E/Synchronous-concurrency b/Lang/E/Synchronous-concurrency new file mode 120000 index 0000000000..16bb9e441a --- /dev/null +++ b/Lang/E/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/E \ No newline at end of file diff --git a/Lang/E/System-time b/Lang/E/System-time new file mode 120000 index 0000000000..60f9431c05 --- /dev/null +++ b/Lang/E/System-time @@ -0,0 +1 @@ +../../Task/System-time/E \ No newline at end of file diff --git a/Lang/E/Take-notes-on-the-command-line b/Lang/E/Take-notes-on-the-command-line new file mode 120000 index 0000000000..38c559d9a4 --- /dev/null +++ b/Lang/E/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/E \ No newline at end of file diff --git a/Lang/E/Terminal-control-Ringing-the-terminal-bell b/Lang/E/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..8f5d8a50c0 --- /dev/null +++ b/Lang/E/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/E \ No newline at end of file diff --git a/Lang/E/Test-a-function b/Lang/E/Test-a-function new file mode 120000 index 0000000000..d55651c59c --- /dev/null +++ b/Lang/E/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/E \ No newline at end of file diff --git a/Lang/E/Text-processing-Max-licenses-in-use b/Lang/E/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8a6c26652e --- /dev/null +++ b/Lang/E/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/E \ No newline at end of file diff --git a/Lang/E/Time-a-function b/Lang/E/Time-a-function new file mode 120000 index 0000000000..e47e0c5579 --- /dev/null +++ b/Lang/E/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/E \ No newline at end of file diff --git a/Lang/E/Tokenize-a-string b/Lang/E/Tokenize-a-string new file mode 120000 index 0000000000..58b95710b2 --- /dev/null +++ b/Lang/E/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/E \ No newline at end of file diff --git a/Lang/E/Top-rank-per-group b/Lang/E/Top-rank-per-group new file mode 120000 index 0000000000..e1b7323587 --- /dev/null +++ b/Lang/E/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/E \ No newline at end of file diff --git a/Lang/E/Topological-sort b/Lang/E/Topological-sort new file mode 120000 index 0000000000..e3ad22e3d1 --- /dev/null +++ b/Lang/E/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/E \ No newline at end of file diff --git a/Lang/E/Towers-of-Hanoi b/Lang/E/Towers-of-Hanoi new file mode 120000 index 0000000000..0cb6199836 --- /dev/null +++ b/Lang/E/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/E \ No newline at end of file diff --git a/Lang/E/Tree-traversal b/Lang/E/Tree-traversal new file mode 120000 index 0000000000..453e8c9fe1 --- /dev/null +++ b/Lang/E/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/E \ No newline at end of file diff --git a/Lang/E/Trigonometric-functions b/Lang/E/Trigonometric-functions new file mode 120000 index 0000000000..c533606f34 --- /dev/null +++ b/Lang/E/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/E \ No newline at end of file diff --git a/Lang/E/Undefined-values b/Lang/E/Undefined-values new file mode 120000 index 0000000000..022f76b00b --- /dev/null +++ b/Lang/E/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/E \ No newline at end of file diff --git a/Lang/E/Variables b/Lang/E/Variables new file mode 120000 index 0000000000..e15af74ab9 --- /dev/null +++ b/Lang/E/Variables @@ -0,0 +1 @@ +../../Task/Variables/E \ No newline at end of file diff --git a/Lang/E/Variadic-function b/Lang/E/Variadic-function new file mode 120000 index 0000000000..238e9967d5 --- /dev/null +++ b/Lang/E/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/E \ No newline at end of file diff --git a/Lang/E/Walk-a-directory-Non-recursively b/Lang/E/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..efcef95e1c --- /dev/null +++ b/Lang/E/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/E \ No newline at end of file diff --git a/Lang/E/Walk-a-directory-Recursively b/Lang/E/Walk-a-directory-Recursively new file mode 120000 index 0000000000..d046a24958 --- /dev/null +++ b/Lang/E/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/E \ No newline at end of file diff --git a/Lang/E/Web-scraping b/Lang/E/Web-scraping new file mode 120000 index 0000000000..bcaf6b46f8 --- /dev/null +++ b/Lang/E/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/E \ No newline at end of file diff --git a/Lang/E/XML-DOM-serialization b/Lang/E/XML-DOM-serialization new file mode 120000 index 0000000000..ae64c4970c --- /dev/null +++ b/Lang/E/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/E \ No newline at end of file diff --git a/Lang/E/XML-XPath b/Lang/E/XML-XPath new file mode 120000 index 0000000000..0c830514c4 --- /dev/null +++ b/Lang/E/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/E \ No newline at end of file diff --git a/Lang/E/Y-combinator b/Lang/E/Y-combinator new file mode 120000 index 0000000000..0c0a059f58 --- /dev/null +++ b/Lang/E/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/E \ No newline at end of file diff --git a/Lang/E/Zig-zag-matrix b/Lang/E/Zig-zag-matrix new file mode 120000 index 0000000000..a6c2e9cb3e --- /dev/null +++ b/Lang/E/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/E \ No newline at end of file diff --git a/Lang/EGL/Sleep b/Lang/EGL/Sleep new file mode 120000 index 0000000000..a4d5783c88 --- /dev/null +++ b/Lang/EGL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/EGL \ No newline at end of file diff --git a/Lang/EGL/Sort-an-integer-array b/Lang/EGL/Sort-an-integer-array new file mode 120000 index 0000000000..90613b0afe --- /dev/null +++ b/Lang/EGL/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/EGL \ No newline at end of file diff --git a/Lang/EGL/Sort-using-a-custom-comparator b/Lang/EGL/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..5fd168e985 --- /dev/null +++ b/Lang/EGL/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/EGL \ No newline at end of file diff --git a/Lang/Eiffel/Sieve-of-Eratosthenes b/Lang/Eiffel/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..f8a9950f83 --- /dev/null +++ b/Lang/Eiffel/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sleep b/Lang/Eiffel/Sleep new file mode 120000 index 0000000000..768e6d3a34 --- /dev/null +++ b/Lang/Eiffel/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Bubble-sort b/Lang/Eiffel/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8bfdc6a6ef --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Insertion-sort b/Lang/Eiffel/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..02c396a456 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Shell-sort b/Lang/Eiffel/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..1bc16be49d --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sum-of-squares b/Lang/Eiffel/Sum-of-squares new file mode 120000 index 0000000000..e469d997b3 --- /dev/null +++ b/Lang/Eiffel/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Symmetric-difference b/Lang/Eiffel/Symmetric-difference new file mode 120000 index 0000000000..000f6360d4 --- /dev/null +++ b/Lang/Eiffel/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Window-creation b/Lang/Eiffel/Window-creation new file mode 120000 index 0000000000..4bf101f28f --- /dev/null +++ b/Lang/Eiffel/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Eiffel \ No newline at end of file diff --git a/Lang/Ela/Singly-linked-list-Traversal b/Lang/Ela/Singly-linked-list-Traversal new file mode 120000 index 0000000000..9ecef3f020 --- /dev/null +++ b/Lang/Ela/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Ela \ No newline at end of file diff --git a/Lang/Ela/Trabb-Pardo-Knuth-algorithm b/Lang/Ela/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..aa1436bc38 --- /dev/null +++ b/Lang/Ela/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Ela \ No newline at end of file diff --git a/Lang/Ela/Van-der-Corput-sequence b/Lang/Ela/Van-der-Corput-sequence new file mode 120000 index 0000000000..efedfd03f6 --- /dev/null +++ b/Lang/Ela/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Ela \ No newline at end of file diff --git a/Lang/Ela/Variables b/Lang/Ela/Variables new file mode 120000 index 0000000000..a3695a2118 --- /dev/null +++ b/Lang/Ela/Variables @@ -0,0 +1 @@ +../../Task/Variables/Ela \ No newline at end of file diff --git a/Lang/Ela/Y-combinator b/Lang/Ela/Y-combinator new file mode 120000 index 0000000000..330be09482 --- /dev/null +++ b/Lang/Ela/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Ela \ No newline at end of file diff --git a/Lang/Elisa/Stack b/Lang/Elisa/Stack new file mode 120000 index 0000000000..2c59b11822 --- /dev/null +++ b/Lang/Elisa/Stack @@ -0,0 +1 @@ +../../Task/Stack/Elisa \ No newline at end of file diff --git a/Lang/Elisa/Tree-traversal b/Lang/Elisa/Tree-traversal new file mode 120000 index 0000000000..7f890035e2 --- /dev/null +++ b/Lang/Elisa/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Elisa \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Shell-one-liner b/Lang/Emacs-Lisp/Shell-one-liner new file mode 120000 index 0000000000..3c23adb372 --- /dev/null +++ b/Lang/Emacs-Lisp/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sorting-algorithms-Insertion-sort b/Lang/Emacs-Lisp/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..03d48fb329 --- /dev/null +++ b/Lang/Emacs-Lisp/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sum-and-product-of-an-array b/Lang/Emacs-Lisp/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5bf8e36772 --- /dev/null +++ b/Lang/Emacs-Lisp/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Terminal-control-Ringing-the-terminal-bell b/Lang/Emacs-Lisp/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..472f0afa50 --- /dev/null +++ b/Lang/Emacs-Lisp/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Towers-of-Hanoi b/Lang/Emacs-Lisp/Towers-of-Hanoi new file mode 120000 index 0000000000..0101c649af --- /dev/null +++ b/Lang/Emacs-Lisp/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Walk-a-directory-Non-recursively b/Lang/Emacs-Lisp/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9610134f55 --- /dev/null +++ b/Lang/Emacs-Lisp/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Window-creation b/Lang/Emacs-Lisp/Window-creation new file mode 120000 index 0000000000..ab7f290eb5 --- /dev/null +++ b/Lang/Emacs-Lisp/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Shell-one-liner b/Lang/Erlang/Shell-one-liner new file mode 120000 index 0000000000..b4f66452b2 --- /dev/null +++ b/Lang/Erlang/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sierpinski-triangle b/Lang/Erlang/Sierpinski-triangle new file mode 120000 index 0000000000..89230dd5e4 --- /dev/null +++ b/Lang/Erlang/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sieve-of-Eratosthenes b/Lang/Erlang/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..09a7da5c6f --- /dev/null +++ b/Lang/Erlang/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Singleton b/Lang/Erlang/Singleton new file mode 120000 index 0000000000..76928f4f9e --- /dev/null +++ b/Lang/Erlang/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sleep b/Lang/Erlang/Sleep new file mode 120000 index 0000000000..e1aca3aac0 --- /dev/null +++ b/Lang/Erlang/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sockets b/Lang/Erlang/Sockets new file mode 120000 index 0000000000..2d9d2b7509 --- /dev/null +++ b/Lang/Erlang/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sort-an-array-of-composite-structures b/Lang/Erlang/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..6b5dd49aa9 --- /dev/null +++ b/Lang/Erlang/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sort-an-integer-array b/Lang/Erlang/Sort-an-integer-array new file mode 120000 index 0000000000..bcf7533b78 --- /dev/null +++ b/Lang/Erlang/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Gnome-sort b/Lang/Erlang/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..cf800715f8 --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Insertion-sort b/Lang/Erlang/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..2e24a4e225 --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Merge-sort b/Lang/Erlang/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..27f191d417 --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sorting-algorithms-Quicksort b/Lang/Erlang/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..2696e53357 --- /dev/null +++ b/Lang/Erlang/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Soundex b/Lang/Erlang/Soundex new file mode 120000 index 0000000000..f33f021c9a --- /dev/null +++ b/Lang/Erlang/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Stack b/Lang/Erlang/Stack new file mode 120000 index 0000000000..bd6fe7d4df --- /dev/null +++ b/Lang/Erlang/Stack @@ -0,0 +1 @@ +../../Task/Stack/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Stair-climbing-puzzle b/Lang/Erlang/Stair-climbing-puzzle new file mode 120000 index 0000000000..cff7141c30 --- /dev/null +++ b/Lang/Erlang/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Erlang \ No newline at end of file diff --git a/Lang/Erlang/String-case b/Lang/Erlang/String-case new file mode 120000 index 0000000000..07befaab20 --- /dev/null +++ b/Lang/Erlang/String-case @@ -0,0 +1 @@ +../../Task/String-case/Erlang \ No newline at end of file diff --git a/Lang/Erlang/String-concatenation b/Lang/Erlang/String-concatenation new file mode 120000 index 0000000000..afecc83da1 --- /dev/null +++ b/Lang/Erlang/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sum-and-product-of-an-array b/Lang/Erlang/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f2150dc40e --- /dev/null +++ b/Lang/Erlang/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sum-digits-of-an-integer b/Lang/Erlang/Sum-digits-of-an-integer new file mode 120000 index 0000000000..12a9671578 --- /dev/null +++ b/Lang/Erlang/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sum-of-a-series b/Lang/Erlang/Sum-of-a-series new file mode 120000 index 0000000000..745b21f99f --- /dev/null +++ b/Lang/Erlang/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sum-of-squares b/Lang/Erlang/Sum-of-squares new file mode 120000 index 0000000000..886b0b5109 --- /dev/null +++ b/Lang/Erlang/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Synchronous-concurrency b/Lang/Erlang/Synchronous-concurrency new file mode 120000 index 0000000000..c734a65452 --- /dev/null +++ b/Lang/Erlang/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Erlang \ No newline at end of file diff --git a/Lang/Erlang/System-time b/Lang/Erlang/System-time new file mode 120000 index 0000000000..d7d62ec484 --- /dev/null +++ b/Lang/Erlang/System-time @@ -0,0 +1 @@ +../../Task/System-time/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Time-a-function b/Lang/Erlang/Time-a-function new file mode 120000 index 0000000000..3b078d4e74 --- /dev/null +++ b/Lang/Erlang/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Tokenize-a-string b/Lang/Erlang/Tokenize-a-string new file mode 120000 index 0000000000..d407e93294 --- /dev/null +++ b/Lang/Erlang/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Topological-sort b/Lang/Erlang/Topological-sort new file mode 120000 index 0000000000..5c98604a0f --- /dev/null +++ b/Lang/Erlang/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Towers-of-Hanoi b/Lang/Erlang/Towers-of-Hanoi new file mode 120000 index 0000000000..848e8163e5 --- /dev/null +++ b/Lang/Erlang/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Tree-traversal b/Lang/Erlang/Tree-traversal new file mode 120000 index 0000000000..e520c3a4de --- /dev/null +++ b/Lang/Erlang/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Trigonometric-functions b/Lang/Erlang/Trigonometric-functions new file mode 120000 index 0000000000..8b447aec1d --- /dev/null +++ b/Lang/Erlang/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Universal-Turing-machine b/Lang/Erlang/Universal-Turing-machine new file mode 120000 index 0000000000..155f85bf2f --- /dev/null +++ b/Lang/Erlang/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Erlang \ No newline at end of file diff --git a/Lang/Erlang/User-input-Text b/Lang/Erlang/User-input-Text new file mode 120000 index 0000000000..1fc4e725d9 --- /dev/null +++ b/Lang/Erlang/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Vigen-re-cipher b/Lang/Erlang/Vigen-re-cipher new file mode 120000 index 0000000000..ed1208752a --- /dev/null +++ b/Lang/Erlang/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Web-scraping b/Lang/Erlang/Web-scraping new file mode 120000 index 0000000000..575c9a6c3d --- /dev/null +++ b/Lang/Erlang/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Y-combinator b/Lang/Erlang/Y-combinator new file mode 120000 index 0000000000..1d348fd70b --- /dev/null +++ b/Lang/Erlang/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Erlang \ No newline at end of file diff --git a/Lang/Euler-Math-Toolbox/Variadic-function b/Lang/Euler-Math-Toolbox/Variadic-function new file mode 120000 index 0000000000..eb93a80070 --- /dev/null +++ b/Lang/Euler-Math-Toolbox/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Euler-Math-Toolbox \ No newline at end of file diff --git a/Lang/Euler-Math-Toolbox/Verify-distribution-uniformity-Naive b/Lang/Euler-Math-Toolbox/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..d0b8bd6fde --- /dev/null +++ b/Lang/Euler-Math-Toolbox/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox \ No newline at end of file diff --git a/Lang/Euphoria/Sierpinski-triangle b/Lang/Euphoria/Sierpinski-triangle new file mode 120000 index 0000000000..ca76a0e472 --- /dev/null +++ b/Lang/Euphoria/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sieve-of-Eratosthenes b/Lang/Euphoria/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9791826db7 --- /dev/null +++ b/Lang/Euphoria/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Simple-windowed-application b/Lang/Euphoria/Simple-windowed-application new file mode 120000 index 0000000000..60a9bf16bf --- /dev/null +++ b/Lang/Euphoria/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sort-an-array-of-composite-structures b/Lang/Euphoria/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..4f66e17fb9 --- /dev/null +++ b/Lang/Euphoria/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sort-an-integer-array b/Lang/Euphoria/Sort-an-integer-array new file mode 120000 index 0000000000..82c700e8c2 --- /dev/null +++ b/Lang/Euphoria/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sort-disjoint-sublist b/Lang/Euphoria/Sort-disjoint-sublist new file mode 120000 index 0000000000..534714ed77 --- /dev/null +++ b/Lang/Euphoria/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sort-using-a-custom-comparator b/Lang/Euphoria/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..f99ba6651d --- /dev/null +++ b/Lang/Euphoria/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Bogosort b/Lang/Euphoria/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b70476659d --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Bubble-sort b/Lang/Euphoria/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..f8556eac71 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Cocktail-sort b/Lang/Euphoria/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..1ee0a30ee5 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Gnome-sort b/Lang/Euphoria/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..ba5d930f4e --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Insertion-sort b/Lang/Euphoria/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..951c1478f4 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Merge-sort b/Lang/Euphoria/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..70c19faa99 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Pancake-sort b/Lang/Euphoria/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..3055f89202 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Selection-sort b/Lang/Euphoria/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..24aebd2913 --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Shell-sort b/Lang/Euphoria/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..dd0fa8757b --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Sleep-sort b/Lang/Euphoria/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..07e4fdac0c --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Stooge-sort b/Lang/Euphoria/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..1714c1f1ad --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sorting-algorithms-Strand-sort b/Lang/Euphoria/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..52579c346e --- /dev/null +++ b/Lang/Euphoria/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Spiral-matrix b/Lang/Euphoria/Spiral-matrix new file mode 120000 index 0000000000..3ce9f126db --- /dev/null +++ b/Lang/Euphoria/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Stair-climbing-puzzle b/Lang/Euphoria/Stair-climbing-puzzle new file mode 120000 index 0000000000..a521a48e0a --- /dev/null +++ b/Lang/Euphoria/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Stem-and-leaf-plot b/Lang/Euphoria/Stem-and-leaf-plot new file mode 120000 index 0000000000..441a85c467 --- /dev/null +++ b/Lang/Euphoria/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/String-concatenation b/Lang/Euphoria/String-concatenation new file mode 120000 index 0000000000..467204e890 --- /dev/null +++ b/Lang/Euphoria/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/String-interpolation--included- b/Lang/Euphoria/String-interpolation--included- new file mode 120000 index 0000000000..e552a228f8 --- /dev/null +++ b/Lang/Euphoria/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/String-length b/Lang/Euphoria/String-length new file mode 120000 index 0000000000..e63274c1ad --- /dev/null +++ b/Lang/Euphoria/String-length @@ -0,0 +1 @@ +../../Task/String-length/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Strip-a-set-of-characters-from-a-string b/Lang/Euphoria/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..9051ffdd11 --- /dev/null +++ b/Lang/Euphoria/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Euphoria/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..6a9074e87c --- /dev/null +++ b/Lang/Euphoria/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Substring b/Lang/Euphoria/Substring new file mode 120000 index 0000000000..af530eb69a --- /dev/null +++ b/Lang/Euphoria/Substring @@ -0,0 +1 @@ +../../Task/Substring/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Substring-Top-and-tail b/Lang/Euphoria/Substring-Top-and-tail new file mode 120000 index 0000000000..dfaec3b2ee --- /dev/null +++ b/Lang/Euphoria/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sum-and-product-of-an-array b/Lang/Euphoria/Sum-and-product-of-an-array new file mode 120000 index 0000000000..0d293427a3 --- /dev/null +++ b/Lang/Euphoria/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sum-of-a-series b/Lang/Euphoria/Sum-of-a-series new file mode 120000 index 0000000000..1433dd32cc --- /dev/null +++ b/Lang/Euphoria/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sum-of-squares b/Lang/Euphoria/Sum-of-squares new file mode 120000 index 0000000000..4e4abd3657 --- /dev/null +++ b/Lang/Euphoria/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Synchronous-concurrency b/Lang/Euphoria/Synchronous-concurrency new file mode 120000 index 0000000000..5d708c02bb --- /dev/null +++ b/Lang/Euphoria/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Take-notes-on-the-command-line b/Lang/Euphoria/Take-notes-on-the-command-line new file mode 120000 index 0000000000..5a2d664415 --- /dev/null +++ b/Lang/Euphoria/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Terminal-control-Clear-the-screen b/Lang/Euphoria/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..7c47273379 --- /dev/null +++ b/Lang/Euphoria/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Terminal-control-Cursor-positioning b/Lang/Euphoria/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..4d4ff2448e --- /dev/null +++ b/Lang/Euphoria/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Terminal-control-Dimensions b/Lang/Euphoria/Terminal-control-Dimensions new file mode 120000 index 0000000000..2ece62e575 --- /dev/null +++ b/Lang/Euphoria/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Test-a-function b/Lang/Euphoria/Test-a-function new file mode 120000 index 0000000000..cb4e5ac5e2 --- /dev/null +++ b/Lang/Euphoria/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Text-processing-Max-licenses-in-use b/Lang/Euphoria/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..1d552bbf30 --- /dev/null +++ b/Lang/Euphoria/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Time-a-function b/Lang/Euphoria/Time-a-function new file mode 120000 index 0000000000..ade222f2bf --- /dev/null +++ b/Lang/Euphoria/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Tokenize-a-string b/Lang/Euphoria/Tokenize-a-string new file mode 120000 index 0000000000..d174a1988e --- /dev/null +++ b/Lang/Euphoria/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Towers-of-Hanoi b/Lang/Euphoria/Towers-of-Hanoi new file mode 120000 index 0000000000..52f6dc5a6d --- /dev/null +++ b/Lang/Euphoria/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Tree-traversal b/Lang/Euphoria/Tree-traversal new file mode 120000 index 0000000000..ebe2b989c8 --- /dev/null +++ b/Lang/Euphoria/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Unbias-a-random-generator b/Lang/Euphoria/Unbias-a-random-generator new file mode 120000 index 0000000000..a070d7ce04 --- /dev/null +++ b/Lang/Euphoria/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/User-input-Text b/Lang/Euphoria/User-input-Text new file mode 120000 index 0000000000..3d97710527 --- /dev/null +++ b/Lang/Euphoria/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Van-der-Corput-sequence b/Lang/Euphoria/Van-der-Corput-sequence new file mode 120000 index 0000000000..a1ea3f0b07 --- /dev/null +++ b/Lang/Euphoria/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Variable-length-quantity b/Lang/Euphoria/Variable-length-quantity new file mode 120000 index 0000000000..5f8e2e5f5f --- /dev/null +++ b/Lang/Euphoria/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Variadic-function b/Lang/Euphoria/Variadic-function new file mode 120000 index 0000000000..cb8116bb3b --- /dev/null +++ b/Lang/Euphoria/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Vector-products b/Lang/Euphoria/Vector-products new file mode 120000 index 0000000000..3b6ea95848 --- /dev/null +++ b/Lang/Euphoria/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Walk-a-directory-Non-recursively b/Lang/Euphoria/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..2b8ed677e5 --- /dev/null +++ b/Lang/Euphoria/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Window-creation b/Lang/Euphoria/Window-creation new file mode 120000 index 0000000000..25a4d56c5a --- /dev/null +++ b/Lang/Euphoria/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Write-float-arrays-to-a-text-file b/Lang/Euphoria/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..c41d70c8d9 --- /dev/null +++ b/Lang/Euphoria/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/XML-Output b/Lang/Euphoria/XML-Output new file mode 120000 index 0000000000..31fd44fe86 --- /dev/null +++ b/Lang/Euphoria/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Zig-zag-matrix b/Lang/Euphoria/Zig-zag-matrix new file mode 120000 index 0000000000..1db2bbcf74 --- /dev/null +++ b/Lang/Euphoria/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Euphoria \ No newline at end of file diff --git a/Lang/FALSE/Sierpinski-triangle b/Lang/FALSE/Sierpinski-triangle new file mode 120000 index 0000000000..40ec5b14f5 --- /dev/null +++ b/Lang/FALSE/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Sum-of-squares b/Lang/FALSE/Sum-of-squares new file mode 120000 index 0000000000..ce07d5fb7b --- /dev/null +++ b/Lang/FALSE/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Towers-of-Hanoi b/Lang/FALSE/Towers-of-Hanoi new file mode 120000 index 0000000000..68d8e40603 --- /dev/null +++ b/Lang/FALSE/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/FALSE \ No newline at end of file diff --git a/Lang/FALSE/User-input-Text b/Lang/FALSE/User-input-Text new file mode 120000 index 0000000000..4ad11ee908 --- /dev/null +++ b/Lang/FALSE/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/FALSE \ No newline at end of file diff --git a/Lang/Factor/Shell-one-liner b/Lang/Factor/Shell-one-liner new file mode 120000 index 0000000000..aeb238b86f --- /dev/null +++ b/Lang/Factor/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Factor \ No newline at end of file diff --git a/Lang/Factor/Sierpinski-triangle b/Lang/Factor/Sierpinski-triangle new file mode 120000 index 0000000000..d522f66694 --- /dev/null +++ b/Lang/Factor/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Factor \ No newline at end of file diff --git a/Lang/Factor/Singleton b/Lang/Factor/Singleton new file mode 120000 index 0000000000..f285393e14 --- /dev/null +++ b/Lang/Factor/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Factor \ No newline at end of file diff --git a/Lang/Factor/Singly-linked-list-Element-definition b/Lang/Factor/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..f829e7cc5d --- /dev/null +++ b/Lang/Factor/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Factor \ No newline at end of file diff --git a/Lang/Factor/Singly-linked-list-Element-insertion b/Lang/Factor/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..e878e2220a --- /dev/null +++ b/Lang/Factor/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Factor \ No newline at end of file diff --git a/Lang/Factor/Singly-linked-list-Traversal b/Lang/Factor/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8e530cf218 --- /dev/null +++ b/Lang/Factor/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Factor \ No newline at end of file diff --git a/Lang/Factor/Sleep b/Lang/Factor/Sleep new file mode 120000 index 0000000000..22acdc21ae --- /dev/null +++ b/Lang/Factor/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Factor \ No newline at end of file diff --git a/Lang/Factor/Sockets b/Lang/Factor/Sockets new file mode 120000 index 0000000000..33bd64fee0 --- /dev/null +++ b/Lang/Factor/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Factor \ No newline at end of file diff --git a/Lang/Factor/Sort-an-array-of-composite-structures b/Lang/Factor/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..0c06c8a8b5 --- /dev/null +++ b/Lang/Factor/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Factor \ No newline at end of file diff --git a/Lang/Factor/Sort-an-integer-array b/Lang/Factor/Sort-an-integer-array new file mode 120000 index 0000000000..428cefcf4c --- /dev/null +++ b/Lang/Factor/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Factor \ No newline at end of file diff --git a/Lang/Factor/Sort-using-a-custom-comparator b/Lang/Factor/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..d3b1a7a2fe --- /dev/null +++ b/Lang/Factor/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Bead-sort b/Lang/Factor/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..6a48c30a10 --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Bogosort b/Lang/Factor/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..d6149041f4 --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Bubble-sort b/Lang/Factor/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..9ba56d42bd --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Merge-sort b/Lang/Factor/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..531dd35ddd --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Quicksort b/Lang/Factor/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ead41f6405 --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Factor \ No newline at end of file diff --git a/Lang/Factor/Stack b/Lang/Factor/Stack new file mode 120000 index 0000000000..566d2f1329 --- /dev/null +++ b/Lang/Factor/Stack @@ -0,0 +1 @@ +../../Task/Stack/Factor \ No newline at end of file diff --git a/Lang/Factor/Standard-deviation b/Lang/Factor/Standard-deviation new file mode 120000 index 0000000000..0e8782d458 --- /dev/null +++ b/Lang/Factor/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Factor \ No newline at end of file diff --git a/Lang/Factor/String-case b/Lang/Factor/String-case new file mode 120000 index 0000000000..75bb0d9619 --- /dev/null +++ b/Lang/Factor/String-case @@ -0,0 +1 @@ +../../Task/String-case/Factor \ No newline at end of file diff --git a/Lang/Factor/String-concatenation b/Lang/Factor/String-concatenation new file mode 120000 index 0000000000..b6ffc0bf7a --- /dev/null +++ b/Lang/Factor/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Factor \ No newline at end of file diff --git a/Lang/Factor/String-interpolation--included- b/Lang/Factor/String-interpolation--included- new file mode 120000 index 0000000000..b85c5c28e5 --- /dev/null +++ b/Lang/Factor/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Factor \ No newline at end of file diff --git a/Lang/Factor/String-length b/Lang/Factor/String-length new file mode 120000 index 0000000000..ea49300fa2 --- /dev/null +++ b/Lang/Factor/String-length @@ -0,0 +1 @@ +../../Task/String-length/Factor \ No newline at end of file diff --git a/Lang/Factor/Substring b/Lang/Factor/Substring new file mode 120000 index 0000000000..3fc59b3ca9 --- /dev/null +++ b/Lang/Factor/Substring @@ -0,0 +1 @@ +../../Task/Substring/Factor \ No newline at end of file diff --git a/Lang/Factor/Sum-and-product-of-an-array b/Lang/Factor/Sum-and-product-of-an-array new file mode 120000 index 0000000000..0fb9428c3e --- /dev/null +++ b/Lang/Factor/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Factor \ No newline at end of file diff --git a/Lang/Factor/Sum-of-a-series b/Lang/Factor/Sum-of-a-series new file mode 120000 index 0000000000..32cb86cc42 --- /dev/null +++ b/Lang/Factor/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Factor \ No newline at end of file diff --git a/Lang/Factor/Sum-of-squares b/Lang/Factor/Sum-of-squares new file mode 120000 index 0000000000..317d9c1379 --- /dev/null +++ b/Lang/Factor/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Factor \ No newline at end of file diff --git a/Lang/Factor/Symmetric-difference b/Lang/Factor/Symmetric-difference new file mode 120000 index 0000000000..87bb1f3614 --- /dev/null +++ b/Lang/Factor/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Factor \ No newline at end of file diff --git a/Lang/Factor/System-time b/Lang/Factor/System-time new file mode 120000 index 0000000000..2a4d6050b6 --- /dev/null +++ b/Lang/Factor/System-time @@ -0,0 +1 @@ +../../Task/System-time/Factor \ No newline at end of file diff --git a/Lang/Factor/Take-notes-on-the-command-line b/Lang/Factor/Take-notes-on-the-command-line new file mode 120000 index 0000000000..c271ee3950 --- /dev/null +++ b/Lang/Factor/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Factor \ No newline at end of file diff --git a/Lang/Factor/Ternary-logic b/Lang/Factor/Ternary-logic new file mode 120000 index 0000000000..0624473721 --- /dev/null +++ b/Lang/Factor/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Factor \ No newline at end of file diff --git a/Lang/Factor/Test-a-function b/Lang/Factor/Test-a-function new file mode 120000 index 0000000000..b3c6235a85 --- /dev/null +++ b/Lang/Factor/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Factor \ No newline at end of file diff --git a/Lang/Factor/Text-processing-Max-licenses-in-use b/Lang/Factor/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..90a9cd1985 --- /dev/null +++ b/Lang/Factor/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Factor \ No newline at end of file diff --git a/Lang/Factor/Time-a-function b/Lang/Factor/Time-a-function new file mode 120000 index 0000000000..0f69cedfef --- /dev/null +++ b/Lang/Factor/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Factor \ No newline at end of file diff --git a/Lang/Factor/Tokenize-a-string b/Lang/Factor/Tokenize-a-string new file mode 120000 index 0000000000..4ee4e070e4 --- /dev/null +++ b/Lang/Factor/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Factor \ No newline at end of file diff --git a/Lang/Factor/Top-rank-per-group b/Lang/Factor/Top-rank-per-group new file mode 120000 index 0000000000..44db3db333 --- /dev/null +++ b/Lang/Factor/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Factor \ No newline at end of file diff --git a/Lang/Factor/Towers-of-Hanoi b/Lang/Factor/Towers-of-Hanoi new file mode 120000 index 0000000000..682a5b0285 --- /dev/null +++ b/Lang/Factor/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Factor \ No newline at end of file diff --git a/Lang/Factor/Tree-traversal b/Lang/Factor/Tree-traversal new file mode 120000 index 0000000000..907e5611ea --- /dev/null +++ b/Lang/Factor/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Factor \ No newline at end of file diff --git a/Lang/Factor/User-input-Text b/Lang/Factor/User-input-Text new file mode 120000 index 0000000000..b73e1831e0 --- /dev/null +++ b/Lang/Factor/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Factor \ No newline at end of file diff --git a/Lang/Factor/Variables b/Lang/Factor/Variables new file mode 120000 index 0000000000..c0b841911b --- /dev/null +++ b/Lang/Factor/Variables @@ -0,0 +1 @@ +../../Task/Variables/Factor \ No newline at end of file diff --git a/Lang/Factor/Walk-a-directory-Non-recursively b/Lang/Factor/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..508ae95516 --- /dev/null +++ b/Lang/Factor/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Factor \ No newline at end of file diff --git a/Lang/Factor/Walk-a-directory-Recursively b/Lang/Factor/Walk-a-directory-Recursively new file mode 120000 index 0000000000..dd3de31ee8 --- /dev/null +++ b/Lang/Factor/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Factor \ No newline at end of file diff --git a/Lang/Factor/Web-scraping b/Lang/Factor/Web-scraping new file mode 120000 index 0000000000..a79e09a909 --- /dev/null +++ b/Lang/Factor/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Factor \ No newline at end of file diff --git a/Lang/Factor/Window-creation b/Lang/Factor/Window-creation new file mode 120000 index 0000000000..df08b4b189 --- /dev/null +++ b/Lang/Factor/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Factor \ No newline at end of file diff --git a/Lang/Factor/XML-Input b/Lang/Factor/XML-Input new file mode 120000 index 0000000000..6157866c4a --- /dev/null +++ b/Lang/Factor/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Factor \ No newline at end of file diff --git a/Lang/Factor/XML-Output b/Lang/Factor/XML-Output new file mode 120000 index 0000000000..92162ab852 --- /dev/null +++ b/Lang/Factor/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Factor \ No newline at end of file diff --git a/Lang/Factor/Y-combinator b/Lang/Factor/Y-combinator new file mode 120000 index 0000000000..cfa61fead4 --- /dev/null +++ b/Lang/Factor/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Factor \ No newline at end of file diff --git a/Lang/Falcon/String-case b/Lang/Falcon/String-case new file mode 120000 index 0000000000..fd70ec046d --- /dev/null +++ b/Lang/Falcon/String-case @@ -0,0 +1 @@ +../../Task/String-case/Falcon \ No newline at end of file diff --git a/Lang/Falcon/User-input-Text b/Lang/Falcon/User-input-Text new file mode 120000 index 0000000000..cff79b58f9 --- /dev/null +++ b/Lang/Falcon/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Y-combinator b/Lang/Falcon/Y-combinator new file mode 120000 index 0000000000..c8960c7475 --- /dev/null +++ b/Lang/Falcon/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Falcon \ No newline at end of file diff --git a/Lang/Fan/Sierpinski-carpet b/Lang/Fan/Sierpinski-carpet new file mode 120000 index 0000000000..bbc9d27f56 --- /dev/null +++ b/Lang/Fan/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Fan \ No newline at end of file diff --git a/Lang/Fan/Zig-zag-matrix b/Lang/Fan/Zig-zag-matrix new file mode 120000 index 0000000000..7a1c725dd5 --- /dev/null +++ b/Lang/Fan/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Fan \ No newline at end of file diff --git a/Lang/Fantom/Short-circuit-evaluation b/Lang/Fantom/Short-circuit-evaluation new file mode 120000 index 0000000000..02ed69591b --- /dev/null +++ b/Lang/Fantom/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Simple-windowed-application b/Lang/Fantom/Simple-windowed-application new file mode 120000 index 0000000000..3f96132443 --- /dev/null +++ b/Lang/Fantom/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Simulate-input-Mouse b/Lang/Fantom/Simulate-input-Mouse new file mode 120000 index 0000000000..e65ef27650 --- /dev/null +++ b/Lang/Fantom/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Singly-linked-list-Element-definition b/Lang/Fantom/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..39374a6c3f --- /dev/null +++ b/Lang/Fantom/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Singly-linked-list-Element-insertion b/Lang/Fantom/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..86c32ca748 --- /dev/null +++ b/Lang/Fantom/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Singly-linked-list-Traversal b/Lang/Fantom/Singly-linked-list-Traversal new file mode 120000 index 0000000000..15e052e037 --- /dev/null +++ b/Lang/Fantom/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sleep b/Lang/Fantom/Sleep new file mode 120000 index 0000000000..b86cbb1e6f --- /dev/null +++ b/Lang/Fantom/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sockets b/Lang/Fantom/Sockets new file mode 120000 index 0000000000..dfd318202e --- /dev/null +++ b/Lang/Fantom/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sort-an-array-of-composite-structures b/Lang/Fantom/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..bf50a74cf4 --- /dev/null +++ b/Lang/Fantom/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sort-using-a-custom-comparator b/Lang/Fantom/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..0443304ad1 --- /dev/null +++ b/Lang/Fantom/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sorting-algorithms-Bogosort b/Lang/Fantom/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..deda22f83c --- /dev/null +++ b/Lang/Fantom/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sorting-algorithms-Gnome-sort b/Lang/Fantom/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..b39b4784f3 --- /dev/null +++ b/Lang/Fantom/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Fantom \ No newline at end of file diff --git a/Lang/Fantom/String-case b/Lang/Fantom/String-case new file mode 120000 index 0000000000..c593c3a1c2 --- /dev/null +++ b/Lang/Fantom/String-case @@ -0,0 +1 @@ +../../Task/String-case/Fantom \ No newline at end of file diff --git a/Lang/Fantom/String-concatenation b/Lang/Fantom/String-concatenation new file mode 120000 index 0000000000..9483437534 --- /dev/null +++ b/Lang/Fantom/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Fantom \ No newline at end of file diff --git a/Lang/Fantom/String-interpolation--included- b/Lang/Fantom/String-interpolation--included- new file mode 120000 index 0000000000..5cd5022a42 --- /dev/null +++ b/Lang/Fantom/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Fantom \ No newline at end of file diff --git a/Lang/Fantom/String-length b/Lang/Fantom/String-length new file mode 120000 index 0000000000..a5b254c20d --- /dev/null +++ b/Lang/Fantom/String-length @@ -0,0 +1 @@ +../../Task/String-length/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Strip-comments-from-a-string b/Lang/Fantom/Strip-comments-from-a-string new file mode 120000 index 0000000000..f2de19d711 --- /dev/null +++ b/Lang/Fantom/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sum-and-product-of-an-array b/Lang/Fantom/Sum-and-product-of-an-array new file mode 120000 index 0000000000..ab4033f5e7 --- /dev/null +++ b/Lang/Fantom/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sum-of-a-series b/Lang/Fantom/Sum-of-a-series new file mode 120000 index 0000000000..566d1f3cc3 --- /dev/null +++ b/Lang/Fantom/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Sum-of-squares b/Lang/Fantom/Sum-of-squares new file mode 120000 index 0000000000..8af32660c8 --- /dev/null +++ b/Lang/Fantom/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Fantom \ No newline at end of file diff --git a/Lang/Fantom/System-time b/Lang/Fantom/System-time new file mode 120000 index 0000000000..30981dc72e --- /dev/null +++ b/Lang/Fantom/System-time @@ -0,0 +1 @@ +../../Task/System-time/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Take-notes-on-the-command-line b/Lang/Fantom/Take-notes-on-the-command-line new file mode 120000 index 0000000000..deb4b60dde --- /dev/null +++ b/Lang/Fantom/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Test-a-function b/Lang/Fantom/Test-a-function new file mode 120000 index 0000000000..bac7ee3379 --- /dev/null +++ b/Lang/Fantom/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Tokenize-a-string b/Lang/Fantom/Tokenize-a-string new file mode 120000 index 0000000000..e216742081 --- /dev/null +++ b/Lang/Fantom/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Tree-traversal b/Lang/Fantom/Tree-traversal new file mode 120000 index 0000000000..ef485134e5 --- /dev/null +++ b/Lang/Fantom/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Trigonometric-functions b/Lang/Fantom/Trigonometric-functions new file mode 120000 index 0000000000..047b042fa4 --- /dev/null +++ b/Lang/Fantom/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Fantom \ No newline at end of file diff --git a/Lang/Fantom/User-input-Text b/Lang/Fantom/User-input-Text new file mode 120000 index 0000000000..1ae0f5dd87 --- /dev/null +++ b/Lang/Fantom/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Vector-products b/Lang/Fantom/Vector-products new file mode 120000 index 0000000000..37df51e3e9 --- /dev/null +++ b/Lang/Fantom/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Fantom \ No newline at end of file diff --git a/Lang/Fantom/Window-creation b/Lang/Fantom/Window-creation new file mode 120000 index 0000000000..22d9c41508 --- /dev/null +++ b/Lang/Fantom/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Fantom \ No newline at end of file diff --git a/Lang/Fantom/XML-DOM-serialization b/Lang/Fantom/XML-DOM-serialization new file mode 120000 index 0000000000..b0455e7318 --- /dev/null +++ b/Lang/Fantom/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Fantom \ No newline at end of file diff --git a/Lang/Fantom/XML-Input b/Lang/Fantom/XML-Input new file mode 120000 index 0000000000..4071e64637 --- /dev/null +++ b/Lang/Fantom/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Fantom \ No newline at end of file diff --git a/Lang/Fantom/XML-Output b/Lang/Fantom/XML-Output new file mode 120000 index 0000000000..c33bf497a3 --- /dev/null +++ b/Lang/Fantom/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Fantom \ No newline at end of file diff --git a/Lang/Fexl/Sorting-algorithms-Quicksort b/Lang/Fexl/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..a5cac6bcfd --- /dev/null +++ b/Lang/Fexl/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Fexl \ No newline at end of file diff --git a/Lang/Fish/Sum-of-squares b/Lang/Fish/Sum-of-squares new file mode 120000 index 0000000000..9a7d351f09 --- /dev/null +++ b/Lang/Fish/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Fish \ No newline at end of file diff --git a/Lang/Forth/Shell-one-liner b/Lang/Forth/Shell-one-liner new file mode 120000 index 0000000000..d8c66d138c --- /dev/null +++ b/Lang/Forth/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Forth \ No newline at end of file diff --git a/Lang/Forth/Short-circuit-evaluation b/Lang/Forth/Short-circuit-evaluation new file mode 120000 index 0000000000..8ef281ecea --- /dev/null +++ b/Lang/Forth/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Forth \ No newline at end of file diff --git a/Lang/Forth/Show-the-epoch b/Lang/Forth/Show-the-epoch new file mode 120000 index 0000000000..6d29af406e --- /dev/null +++ b/Lang/Forth/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Forth \ No newline at end of file diff --git a/Lang/Forth/Sierpinski-carpet b/Lang/Forth/Sierpinski-carpet new file mode 120000 index 0000000000..05397b18b3 --- /dev/null +++ b/Lang/Forth/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Forth \ No newline at end of file diff --git a/Lang/Forth/Sierpinski-triangle b/Lang/Forth/Sierpinski-triangle new file mode 120000 index 0000000000..1d1aabe42b --- /dev/null +++ b/Lang/Forth/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Forth \ No newline at end of file diff --git a/Lang/Forth/Simple-database b/Lang/Forth/Simple-database new file mode 120000 index 0000000000..0b0fff7a36 --- /dev/null +++ b/Lang/Forth/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Forth \ No newline at end of file diff --git a/Lang/Forth/Simple-windowed-application b/Lang/Forth/Simple-windowed-application new file mode 120000 index 0000000000..a4c1cc9388 --- /dev/null +++ b/Lang/Forth/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Forth \ No newline at end of file diff --git a/Lang/Forth/Singly-linked-list-Element-definition b/Lang/Forth/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..f350f83362 --- /dev/null +++ b/Lang/Forth/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Forth \ No newline at end of file diff --git a/Lang/Forth/Singly-linked-list-Element-insertion b/Lang/Forth/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..9f73aea887 --- /dev/null +++ b/Lang/Forth/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Forth \ No newline at end of file diff --git a/Lang/Forth/Singly-linked-list-Traversal b/Lang/Forth/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8d187ad00a --- /dev/null +++ b/Lang/Forth/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Forth \ No newline at end of file diff --git a/Lang/Forth/Sleep b/Lang/Forth/Sleep new file mode 120000 index 0000000000..545de3843f --- /dev/null +++ b/Lang/Forth/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Forth \ No newline at end of file diff --git a/Lang/Forth/Sockets b/Lang/Forth/Sockets new file mode 120000 index 0000000000..97860333a9 --- /dev/null +++ b/Lang/Forth/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Forth \ No newline at end of file diff --git a/Lang/Forth/Sort-an-integer-array b/Lang/Forth/Sort-an-integer-array new file mode 120000 index 0000000000..14a21ed934 --- /dev/null +++ b/Lang/Forth/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Bubble-sort b/Lang/Forth/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..57baa967ce --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Cocktail-sort b/Lang/Forth/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..85bc7d7960 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Comb-sort b/Lang/Forth/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..9648427cb0 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Gnome-sort b/Lang/Forth/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7580d7f857 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Heapsort b/Lang/Forth/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..8f9c9b9182 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Insertion-sort b/Lang/Forth/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..647aff3947 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Merge-sort b/Lang/Forth/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..86dc86343c --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Quicksort b/Lang/Forth/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..c03c53e36b --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Selection-sort b/Lang/Forth/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..2f29f8a7b5 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Shell-sort b/Lang/Forth/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..ac1f5ec0a5 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Soundex b/Lang/Forth/Soundex new file mode 120000 index 0000000000..a6f352e710 --- /dev/null +++ b/Lang/Forth/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Forth \ No newline at end of file diff --git a/Lang/Forth/Special-characters b/Lang/Forth/Special-characters new file mode 120000 index 0000000000..243996812e --- /dev/null +++ b/Lang/Forth/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Forth \ No newline at end of file diff --git a/Lang/Forth/Stack b/Lang/Forth/Stack new file mode 120000 index 0000000000..a76d131aad --- /dev/null +++ b/Lang/Forth/Stack @@ -0,0 +1 @@ +../../Task/Stack/Forth \ No newline at end of file diff --git a/Lang/Forth/Stack-traces b/Lang/Forth/Stack-traces new file mode 120000 index 0000000000..235b448bea --- /dev/null +++ b/Lang/Forth/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Forth \ No newline at end of file diff --git a/Lang/Forth/Stair-climbing-puzzle b/Lang/Forth/Stair-climbing-puzzle new file mode 120000 index 0000000000..6b10a5652d --- /dev/null +++ b/Lang/Forth/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Forth \ No newline at end of file diff --git a/Lang/Forth/Standard-deviation b/Lang/Forth/Standard-deviation new file mode 120000 index 0000000000..9dad1468f4 --- /dev/null +++ b/Lang/Forth/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Forth \ No newline at end of file diff --git a/Lang/Forth/Stem-and-leaf-plot b/Lang/Forth/Stem-and-leaf-plot new file mode 120000 index 0000000000..6dcf65f9bb --- /dev/null +++ b/Lang/Forth/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Forth \ No newline at end of file diff --git a/Lang/Forth/String-concatenation b/Lang/Forth/String-concatenation new file mode 120000 index 0000000000..3ddda92063 --- /dev/null +++ b/Lang/Forth/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Forth \ No newline at end of file diff --git a/Lang/Forth/String-length b/Lang/Forth/String-length new file mode 120000 index 0000000000..1fb40daec6 --- /dev/null +++ b/Lang/Forth/String-length @@ -0,0 +1 @@ +../../Task/String-length/Forth \ No newline at end of file diff --git a/Lang/Forth/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Forth/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..40868bd8fb --- /dev/null +++ b/Lang/Forth/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Forth \ No newline at end of file diff --git a/Lang/Forth/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Forth/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..4da8287fbc --- /dev/null +++ b/Lang/Forth/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Forth \ No newline at end of file diff --git a/Lang/Forth/Substring b/Lang/Forth/Substring new file mode 120000 index 0000000000..ab9665610d --- /dev/null +++ b/Lang/Forth/Substring @@ -0,0 +1 @@ +../../Task/Substring/Forth \ No newline at end of file diff --git a/Lang/Forth/Substring-Top-and-tail b/Lang/Forth/Substring-Top-and-tail new file mode 120000 index 0000000000..2c9d433369 --- /dev/null +++ b/Lang/Forth/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Forth \ No newline at end of file diff --git a/Lang/Forth/Sudoku b/Lang/Forth/Sudoku new file mode 120000 index 0000000000..aa984e92a7 --- /dev/null +++ b/Lang/Forth/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Forth \ No newline at end of file diff --git a/Lang/Forth/Sum-and-product-of-an-array b/Lang/Forth/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4f9560d138 --- /dev/null +++ b/Lang/Forth/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Forth \ No newline at end of file diff --git a/Lang/Forth/Sum-of-a-series b/Lang/Forth/Sum-of-a-series new file mode 120000 index 0000000000..9fa03aaeb6 --- /dev/null +++ b/Lang/Forth/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Forth \ No newline at end of file diff --git a/Lang/Forth/Sum-of-squares b/Lang/Forth/Sum-of-squares new file mode 120000 index 0000000000..395829012c --- /dev/null +++ b/Lang/Forth/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Forth \ No newline at end of file diff --git a/Lang/Forth/Symmetric-difference b/Lang/Forth/Symmetric-difference new file mode 120000 index 0000000000..f3a8633ad9 --- /dev/null +++ b/Lang/Forth/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Forth \ No newline at end of file diff --git a/Lang/Forth/System-time b/Lang/Forth/System-time new file mode 120000 index 0000000000..1389ea48de --- /dev/null +++ b/Lang/Forth/System-time @@ -0,0 +1 @@ +../../Task/System-time/Forth \ No newline at end of file diff --git a/Lang/Forth/Take-notes-on-the-command-line b/Lang/Forth/Take-notes-on-the-command-line new file mode 120000 index 0000000000..19f77089dc --- /dev/null +++ b/Lang/Forth/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Clear-the-screen b/Lang/Forth/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..c04564d715 --- /dev/null +++ b/Lang/Forth/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Cursor-positioning b/Lang/Forth/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..ac899fd951 --- /dev/null +++ b/Lang/Forth/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Dimensions b/Lang/Forth/Terminal-control-Dimensions new file mode 120000 index 0000000000..ecfa5ed1b6 --- /dev/null +++ b/Lang/Forth/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Display-an-extended-character b/Lang/Forth/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..acd5ac5879 --- /dev/null +++ b/Lang/Forth/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Forth \ No newline at end of file diff --git a/Lang/Forth/Terminal-control-Ringing-the-terminal-bell b/Lang/Forth/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b7cf634c2c --- /dev/null +++ b/Lang/Forth/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Forth \ No newline at end of file diff --git a/Lang/Forth/Text-processing-1 b/Lang/Forth/Text-processing-1 new file mode 120000 index 0000000000..eb6df3c6b4 --- /dev/null +++ b/Lang/Forth/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Forth \ No newline at end of file diff --git a/Lang/Forth/Text-processing-Max-licenses-in-use b/Lang/Forth/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..ba559b54ff --- /dev/null +++ b/Lang/Forth/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Forth \ No newline at end of file diff --git a/Lang/Forth/Time-a-function b/Lang/Forth/Time-a-function new file mode 120000 index 0000000000..4af88fc603 --- /dev/null +++ b/Lang/Forth/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Forth \ No newline at end of file diff --git a/Lang/Forth/Tokenize-a-string b/Lang/Forth/Tokenize-a-string new file mode 120000 index 0000000000..856ee71cd6 --- /dev/null +++ b/Lang/Forth/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Forth \ No newline at end of file diff --git a/Lang/Forth/Towers-of-Hanoi b/Lang/Forth/Towers-of-Hanoi new file mode 120000 index 0000000000..1b02f67b30 --- /dev/null +++ b/Lang/Forth/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Forth \ No newline at end of file diff --git a/Lang/Forth/Tree-traversal b/Lang/Forth/Tree-traversal new file mode 120000 index 0000000000..94d16cbaa4 --- /dev/null +++ b/Lang/Forth/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Forth \ No newline at end of file diff --git a/Lang/Forth/Trigonometric-functions b/Lang/Forth/Trigonometric-functions new file mode 120000 index 0000000000..78439f08b5 --- /dev/null +++ b/Lang/Forth/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Forth \ No newline at end of file diff --git a/Lang/Forth/Unicode-variable-names b/Lang/Forth/Unicode-variable-names new file mode 120000 index 0000000000..e759d47173 --- /dev/null +++ b/Lang/Forth/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Forth \ No newline at end of file diff --git a/Lang/Forth/User-input-Text b/Lang/Forth/User-input-Text new file mode 120000 index 0000000000..bc980887fe --- /dev/null +++ b/Lang/Forth/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Forth \ No newline at end of file diff --git a/Lang/Forth/Van-der-Corput-sequence b/Lang/Forth/Van-der-Corput-sequence new file mode 120000 index 0000000000..6e89667e89 --- /dev/null +++ b/Lang/Forth/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Forth \ No newline at end of file diff --git a/Lang/Forth/Variables b/Lang/Forth/Variables new file mode 120000 index 0000000000..ca61317e42 --- /dev/null +++ b/Lang/Forth/Variables @@ -0,0 +1 @@ +../../Task/Variables/Forth \ No newline at end of file diff --git a/Lang/Forth/Variadic-function b/Lang/Forth/Variadic-function new file mode 120000 index 0000000000..2ba5a8621e --- /dev/null +++ b/Lang/Forth/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Forth \ No newline at end of file diff --git a/Lang/Forth/Walk-a-directory-Non-recursively b/Lang/Forth/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..4c30b3cad8 --- /dev/null +++ b/Lang/Forth/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Forth \ No newline at end of file diff --git a/Lang/Forth/Walk-a-directory-Recursively b/Lang/Forth/Walk-a-directory-Recursively new file mode 120000 index 0000000000..e4a2d81dc0 --- /dev/null +++ b/Lang/Forth/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Forth \ No newline at end of file diff --git a/Lang/Forth/Web-scraping b/Lang/Forth/Web-scraping new file mode 120000 index 0000000000..2ee922b146 --- /dev/null +++ b/Lang/Forth/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Forth \ No newline at end of file diff --git a/Lang/Forth/Window-creation b/Lang/Forth/Window-creation new file mode 120000 index 0000000000..914ccec68e --- /dev/null +++ b/Lang/Forth/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Forth \ No newline at end of file diff --git a/Lang/Forth/Wireworld b/Lang/Forth/Wireworld new file mode 120000 index 0000000000..15223ed3c1 --- /dev/null +++ b/Lang/Forth/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Forth \ No newline at end of file diff --git a/Lang/Forth/Word-wrap b/Lang/Forth/Word-wrap new file mode 120000 index 0000000000..061baf0faf --- /dev/null +++ b/Lang/Forth/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Forth \ No newline at end of file diff --git a/Lang/Forth/Write-float-arrays-to-a-text-file b/Lang/Forth/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..e89246cbd3 --- /dev/null +++ b/Lang/Forth/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Forth \ No newline at end of file diff --git a/Lang/Forth/XML-DOM-serialization b/Lang/Forth/XML-DOM-serialization new file mode 120000 index 0000000000..d723c39632 --- /dev/null +++ b/Lang/Forth/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Forth \ No newline at end of file diff --git a/Lang/Forth/XML-Input b/Lang/Forth/XML-Input new file mode 120000 index 0000000000..af86dfd2ec --- /dev/null +++ b/Lang/Forth/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Forth \ No newline at end of file diff --git a/Lang/Forth/XML-Output b/Lang/Forth/XML-Output new file mode 120000 index 0000000000..757033c152 --- /dev/null +++ b/Lang/Forth/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Forth \ No newline at end of file diff --git a/Lang/Forth/Zig-zag-matrix b/Lang/Forth/Zig-zag-matrix new file mode 120000 index 0000000000..a5079e8c4f --- /dev/null +++ b/Lang/Forth/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Forth \ No newline at end of file diff --git a/Lang/Fortran/Seven-sided-dice-from-five-sided-dice b/Lang/Fortran/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..1218711296 --- /dev/null +++ b/Lang/Fortran/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Short-circuit-evaluation b/Lang/Fortran/Short-circuit-evaluation new file mode 120000 index 0000000000..4e4c6f2613 --- /dev/null +++ b/Lang/Fortran/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sierpinski-carpet b/Lang/Fortran/Sierpinski-carpet new file mode 120000 index 0000000000..9c9a19a1d7 --- /dev/null +++ b/Lang/Fortran/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sierpinski-triangle b/Lang/Fortran/Sierpinski-triangle new file mode 120000 index 0000000000..7278205d54 --- /dev/null +++ b/Lang/Fortran/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sieve-of-Eratosthenes b/Lang/Fortran/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..1f8c16bddb --- /dev/null +++ b/Lang/Fortran/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Singly-linked-list-Element-definition b/Lang/Fortran/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..5387da784a --- /dev/null +++ b/Lang/Fortran/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Singly-linked-list-Element-insertion b/Lang/Fortran/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..541db11eca --- /dev/null +++ b/Lang/Fortran/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Singly-linked-list-Traversal b/Lang/Fortran/Singly-linked-list-Traversal new file mode 120000 index 0000000000..20740b333c --- /dev/null +++ b/Lang/Fortran/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sleep b/Lang/Fortran/Sleep new file mode 120000 index 0000000000..a787f592b2 --- /dev/null +++ b/Lang/Fortran/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sort-an-array-of-composite-structures b/Lang/Fortran/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..a09189265f --- /dev/null +++ b/Lang/Fortran/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sort-an-integer-array b/Lang/Fortran/Sort-an-integer-array new file mode 120000 index 0000000000..589190876b --- /dev/null +++ b/Lang/Fortran/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sort-disjoint-sublist b/Lang/Fortran/Sort-disjoint-sublist new file mode 120000 index 0000000000..8d84820994 --- /dev/null +++ b/Lang/Fortran/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sort-using-a-custom-comparator b/Lang/Fortran/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..3f6a0b900b --- /dev/null +++ b/Lang/Fortran/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Bead-sort b/Lang/Fortran/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..2c1df25fb6 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Bogosort b/Lang/Fortran/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b857e2f2bc --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Bubble-sort b/Lang/Fortran/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..30ed107427 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Cocktail-sort b/Lang/Fortran/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..bd05effe9a --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Comb-sort b/Lang/Fortran/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..f14ef9d9b7 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Counting-sort b/Lang/Fortran/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..33179ea118 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Gnome-sort b/Lang/Fortran/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..1a4bf4b365 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Heapsort b/Lang/Fortran/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..bd5012fbc7 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Insertion-sort b/Lang/Fortran/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..65b6d44b9f --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Merge-sort b/Lang/Fortran/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..1de4681a73 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Pancake-sort b/Lang/Fortran/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..eaf19a8de6 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Quicksort b/Lang/Fortran/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..8ce86e51d1 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Selection-sort b/Lang/Fortran/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..c5ef8da3a9 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Shell-sort b/Lang/Fortran/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..d57b47cc89 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Stooge-sort b/Lang/Fortran/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..6629351b99 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Spiral-matrix b/Lang/Fortran/Spiral-matrix new file mode 120000 index 0000000000..49e48d7701 --- /dev/null +++ b/Lang/Fortran/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Stack b/Lang/Fortran/Stack new file mode 120000 index 0000000000..08d88c7188 --- /dev/null +++ b/Lang/Fortran/Stack @@ -0,0 +1 @@ +../../Task/Stack/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Stair-climbing-puzzle b/Lang/Fortran/Stair-climbing-puzzle new file mode 120000 index 0000000000..02c62f3c1d --- /dev/null +++ b/Lang/Fortran/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Standard-deviation b/Lang/Fortran/Standard-deviation new file mode 120000 index 0000000000..45df64cb97 --- /dev/null +++ b/Lang/Fortran/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/String-case b/Lang/Fortran/String-case new file mode 120000 index 0000000000..c208431a9a --- /dev/null +++ b/Lang/Fortran/String-case @@ -0,0 +1 @@ +../../Task/String-case/Fortran \ No newline at end of file diff --git a/Lang/Fortran/String-concatenation b/Lang/Fortran/String-concatenation new file mode 120000 index 0000000000..1ee3a06769 --- /dev/null +++ b/Lang/Fortran/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/String-interpolation--included- b/Lang/Fortran/String-interpolation--included- new file mode 120000 index 0000000000..9c0b68c96a --- /dev/null +++ b/Lang/Fortran/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Strip-a-set-of-characters-from-a-string b/Lang/Fortran/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..4d80142a60 --- /dev/null +++ b/Lang/Fortran/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Strip-comments-from-a-string b/Lang/Fortran/Strip-comments-from-a-string new file mode 120000 index 0000000000..5c0ae63257 --- /dev/null +++ b/Lang/Fortran/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Fortran/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..ffd049c83b --- /dev/null +++ b/Lang/Fortran/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Substring b/Lang/Fortran/Substring new file mode 120000 index 0000000000..fe5a3492bf --- /dev/null +++ b/Lang/Fortran/Substring @@ -0,0 +1 @@ +../../Task/Substring/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Substring-Top-and-tail b/Lang/Fortran/Substring-Top-and-tail new file mode 120000 index 0000000000..4c581c8dbc --- /dev/null +++ b/Lang/Fortran/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sudoku b/Lang/Fortran/Sudoku new file mode 120000 index 0000000000..e8a373dd76 --- /dev/null +++ b/Lang/Fortran/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-and-product-of-an-array b/Lang/Fortran/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e38a42ced4 --- /dev/null +++ b/Lang/Fortran/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-of-a-series b/Lang/Fortran/Sum-of-a-series new file mode 120000 index 0000000000..098f287fa8 --- /dev/null +++ b/Lang/Fortran/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-of-squares b/Lang/Fortran/Sum-of-squares new file mode 120000 index 0000000000..38dcfef26b --- /dev/null +++ b/Lang/Fortran/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Symmetric-difference b/Lang/Fortran/Symmetric-difference new file mode 120000 index 0000000000..e300f3dd42 --- /dev/null +++ b/Lang/Fortran/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Fortran \ No newline at end of file diff --git a/Lang/Fortran/System-time b/Lang/Fortran/System-time new file mode 120000 index 0000000000..2bbf2d62cb --- /dev/null +++ b/Lang/Fortran/System-time @@ -0,0 +1 @@ +../../Task/System-time/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Time-a-function b/Lang/Fortran/Time-a-function new file mode 120000 index 0000000000..b5a76eda02 --- /dev/null +++ b/Lang/Fortran/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Tokenize-a-string b/Lang/Fortran/Tokenize-a-string new file mode 120000 index 0000000000..376874285b --- /dev/null +++ b/Lang/Fortran/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Topological-sort b/Lang/Fortran/Topological-sort new file mode 120000 index 0000000000..48180444ff --- /dev/null +++ b/Lang/Fortran/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Towers-of-Hanoi b/Lang/Fortran/Towers-of-Hanoi new file mode 120000 index 0000000000..3d0828d804 --- /dev/null +++ b/Lang/Fortran/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Trigonometric-functions b/Lang/Fortran/Trigonometric-functions new file mode 120000 index 0000000000..35ac91860f --- /dev/null +++ b/Lang/Fortran/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Truncatable-primes b/Lang/Fortran/Truncatable-primes new file mode 120000 index 0000000000..746b018a5b --- /dev/null +++ b/Lang/Fortran/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Unbias-a-random-generator b/Lang/Fortran/Unbias-a-random-generator new file mode 120000 index 0000000000..5b5aea4f8d --- /dev/null +++ b/Lang/Fortran/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Fortran \ No newline at end of file diff --git a/Lang/Fortran/User-input-Text b/Lang/Fortran/User-input-Text new file mode 120000 index 0000000000..e9c39859c7 --- /dev/null +++ b/Lang/Fortran/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Variable-size-Get b/Lang/Fortran/Variable-size-Get new file mode 120000 index 0000000000..0980236b3a --- /dev/null +++ b/Lang/Fortran/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Variable-size-Set b/Lang/Fortran/Variable-size-Set new file mode 120000 index 0000000000..2bd893bb0b --- /dev/null +++ b/Lang/Fortran/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Variables b/Lang/Fortran/Variables new file mode 120000 index 0000000000..cd343e3921 --- /dev/null +++ b/Lang/Fortran/Variables @@ -0,0 +1 @@ +../../Task/Variables/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Variadic-function b/Lang/Fortran/Variadic-function new file mode 120000 index 0000000000..e0114738dd --- /dev/null +++ b/Lang/Fortran/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vector-products b/Lang/Fortran/Vector-products new file mode 120000 index 0000000000..b6b593579b --- /dev/null +++ b/Lang/Fortran/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Verify-distribution-uniformity-Chi-squared-test b/Lang/Fortran/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..c4918fa240 --- /dev/null +++ b/Lang/Fortran/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Verify-distribution-uniformity-Naive b/Lang/Fortran/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..bdf5779847 --- /dev/null +++ b/Lang/Fortran/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Wireworld b/Lang/Fortran/Wireworld new file mode 120000 index 0000000000..2b3d379549 --- /dev/null +++ b/Lang/Fortran/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Write-float-arrays-to-a-text-file b/Lang/Fortran/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..58afef4145 --- /dev/null +++ b/Lang/Fortran/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Zig-zag-matrix b/Lang/Fortran/Zig-zag-matrix new file mode 120000 index 0000000000..2374bfc06d --- /dev/null +++ b/Lang/Fortran/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Fortran \ No newline at end of file diff --git a/Lang/Frink/Sleep b/Lang/Frink/Sleep new file mode 120000 index 0000000000..e0823532e4 --- /dev/null +++ b/Lang/Frink/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Frink \ No newline at end of file diff --git a/Lang/Frink/User-input-Graphical b/Lang/Frink/User-input-Graphical new file mode 120000 index 0000000000..8d4f37e207 --- /dev/null +++ b/Lang/Frink/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Frink \ No newline at end of file diff --git a/Lang/Frink/User-input-Text b/Lang/Frink/User-input-Text new file mode 120000 index 0000000000..c75e647f35 --- /dev/null +++ b/Lang/Frink/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Frink \ No newline at end of file diff --git a/Lang/GAP/Sierpinski-triangle b/Lang/GAP/Sierpinski-triangle new file mode 120000 index 0000000000..548a698a81 --- /dev/null +++ b/Lang/GAP/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/GAP \ No newline at end of file diff --git a/Lang/GAP/Sieve-of-Eratosthenes b/Lang/GAP/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..0803ebc1df --- /dev/null +++ b/Lang/GAP/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/GAP \ No newline at end of file diff --git a/Lang/GAP/Sort-an-integer-array b/Lang/GAP/Sort-an-integer-array new file mode 120000 index 0000000000..be6b8429c6 --- /dev/null +++ b/Lang/GAP/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/GAP \ No newline at end of file diff --git a/Lang/GAP/Sort-stability b/Lang/GAP/Sort-stability new file mode 120000 index 0000000000..38f97e1b72 --- /dev/null +++ b/Lang/GAP/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/GAP \ No newline at end of file diff --git a/Lang/GAP/Sorting-algorithms-Insertion-sort b/Lang/GAP/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..57046a4d71 --- /dev/null +++ b/Lang/GAP/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/GAP \ No newline at end of file diff --git a/Lang/GAP/Sorting-algorithms-Selection-sort b/Lang/GAP/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..8e6ad54e6c --- /dev/null +++ b/Lang/GAP/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/GAP \ No newline at end of file diff --git a/Lang/GAP/Spiral-matrix b/Lang/GAP/Spiral-matrix new file mode 120000 index 0000000000..77fa3d30bd --- /dev/null +++ b/Lang/GAP/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/GAP \ No newline at end of file diff --git a/Lang/GAP/String-length b/Lang/GAP/String-length new file mode 120000 index 0000000000..c313e40e83 --- /dev/null +++ b/Lang/GAP/String-length @@ -0,0 +1 @@ +../../Task/String-length/GAP \ No newline at end of file diff --git a/Lang/GAP/Substring b/Lang/GAP/Substring new file mode 120000 index 0000000000..08f3353258 --- /dev/null +++ b/Lang/GAP/Substring @@ -0,0 +1 @@ +../../Task/Substring/GAP \ No newline at end of file diff --git a/Lang/GAP/Sum-and-product-of-an-array b/Lang/GAP/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5db68de04c --- /dev/null +++ b/Lang/GAP/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/GAP \ No newline at end of file diff --git a/Lang/GAP/Sum-of-a-series b/Lang/GAP/Sum-of-a-series new file mode 120000 index 0000000000..24dac25950 --- /dev/null +++ b/Lang/GAP/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/GAP \ No newline at end of file diff --git a/Lang/GAP/Sum-of-squares b/Lang/GAP/Sum-of-squares new file mode 120000 index 0000000000..5ccd16321f --- /dev/null +++ b/Lang/GAP/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/GAP \ No newline at end of file diff --git a/Lang/GAP/Symmetric-difference b/Lang/GAP/Symmetric-difference new file mode 120000 index 0000000000..320d810492 --- /dev/null +++ b/Lang/GAP/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/GAP \ No newline at end of file diff --git a/Lang/GAP/Time-a-function b/Lang/GAP/Time-a-function new file mode 120000 index 0000000000..b229175b50 --- /dev/null +++ b/Lang/GAP/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/GAP \ No newline at end of file diff --git a/Lang/GAP/Tokenize-a-string b/Lang/GAP/Tokenize-a-string new file mode 120000 index 0000000000..d4535000d3 --- /dev/null +++ b/Lang/GAP/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/GAP \ No newline at end of file diff --git a/Lang/GAP/Towers-of-Hanoi b/Lang/GAP/Towers-of-Hanoi new file mode 120000 index 0000000000..fd07d0131d --- /dev/null +++ b/Lang/GAP/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/GAP \ No newline at end of file diff --git a/Lang/GAP/Unbias-a-random-generator b/Lang/GAP/Unbias-a-random-generator new file mode 120000 index 0000000000..6a22b8eb94 --- /dev/null +++ b/Lang/GAP/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/GAP \ No newline at end of file diff --git a/Lang/GAP/Undefined-values b/Lang/GAP/Undefined-values new file mode 120000 index 0000000000..9fd1eec95c --- /dev/null +++ b/Lang/GAP/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/GAP \ No newline at end of file diff --git a/Lang/GAP/Variables b/Lang/GAP/Variables new file mode 120000 index 0000000000..b342af9681 --- /dev/null +++ b/Lang/GAP/Variables @@ -0,0 +1 @@ +../../Task/Variables/GAP \ No newline at end of file diff --git a/Lang/GAP/Vector-products b/Lang/GAP/Vector-products new file mode 120000 index 0000000000..020fbf6a36 --- /dev/null +++ b/Lang/GAP/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/GAP \ No newline at end of file diff --git a/Lang/GAP/Walk-a-directory-Recursively b/Lang/GAP/Walk-a-directory-Recursively new file mode 120000 index 0000000000..0bc5f4b558 --- /dev/null +++ b/Lang/GAP/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/GAP \ No newline at end of file diff --git a/Lang/GAP/Y-combinator b/Lang/GAP/Y-combinator new file mode 120000 index 0000000000..15fa3c9da3 --- /dev/null +++ b/Lang/GAP/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/GAP \ No newline at end of file diff --git a/Lang/GAP/Zig-zag-matrix b/Lang/GAP/Zig-zag-matrix new file mode 120000 index 0000000000..d854b35981 --- /dev/null +++ b/Lang/GAP/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/GAP \ No newline at end of file diff --git a/Lang/GLBasic/Sieve-of-Eratosthenes b/Lang/GLBasic/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..8f999e1870 --- /dev/null +++ b/Lang/GLBasic/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/GLBasic \ No newline at end of file diff --git a/Lang/GML/String-case b/Lang/GML/String-case new file mode 120000 index 0000000000..4a57d8edcf --- /dev/null +++ b/Lang/GML/String-case @@ -0,0 +1 @@ +../../Task/String-case/GML \ No newline at end of file diff --git a/Lang/GUISS/Simulate-input-Keyboard b/Lang/GUISS/Simulate-input-Keyboard new file mode 120000 index 0000000000..56f1511c29 --- /dev/null +++ b/Lang/GUISS/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Simulate-input-Mouse b/Lang/GUISS/Simulate-input-Mouse new file mode 120000 index 0000000000..f6e22c2a04 --- /dev/null +++ b/Lang/GUISS/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/GUISS \ No newline at end of file diff --git a/Lang/GUISS/System-time b/Lang/GUISS/System-time new file mode 120000 index 0000000000..fec1a73a63 --- /dev/null +++ b/Lang/GUISS/System-time @@ -0,0 +1 @@ +../../Task/System-time/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Terminal-control-Clear-the-screen b/Lang/GUISS/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..79f2b77b27 --- /dev/null +++ b/Lang/GUISS/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Walk-a-directory-Recursively b/Lang/GUISS/Walk-a-directory-Recursively new file mode 120000 index 0000000000..e5ba82e53c --- /dev/null +++ b/Lang/GUISS/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Window-creation b/Lang/GUISS/Window-creation new file mode 120000 index 0000000000..556e25ee97 --- /dev/null +++ b/Lang/GUISS/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Window-creation-X11 b/Lang/GUISS/Window-creation-X11 new file mode 120000 index 0000000000..1dbde2851f --- /dev/null +++ b/Lang/GUISS/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/GUISS \ No newline at end of file diff --git a/Lang/GUISS/Yahoo--search-interface b/Lang/GUISS/Yahoo--search-interface new file mode 120000 index 0000000000..e06583cdbc --- /dev/null +++ b/Lang/GUISS/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/GUISS \ No newline at end of file diff --git a/Lang/GW-BASIC/Sieve-of-Eratosthenes b/Lang/GW-BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..a54bde7693 --- /dev/null +++ b/Lang/GW-BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/String-length b/Lang/GW-BASIC/String-length new file mode 120000 index 0000000000..93273390ea --- /dev/null +++ b/Lang/GW-BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Substring-Top-and-tail b/Lang/GW-BASIC/Substring-Top-and-tail new file mode 120000 index 0000000000..e6b6406eaa --- /dev/null +++ b/Lang/GW-BASIC/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Sum-and-product-of-an-array b/Lang/GW-BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..ec452c7efe --- /dev/null +++ b/Lang/GW-BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Terminal-control-Clear-the-screen b/Lang/GW-BASIC/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..9061eea49a --- /dev/null +++ b/Lang/GW-BASIC/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Video-display-modes b/Lang/GW-BASIC/Video-display-modes new file mode 120000 index 0000000000..0f588e73b2 --- /dev/null +++ b/Lang/GW-BASIC/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Start-from-a-main-routine b/Lang/Gambas/Start-from-a-main-routine new file mode 120000 index 0000000000..b8aeb0d58e --- /dev/null +++ b/Lang/Gambas/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Gambas \ No newline at end of file diff --git a/Lang/Gambas/String-concatenation b/Lang/Gambas/String-concatenation new file mode 120000 index 0000000000..3e230fb892 --- /dev/null +++ b/Lang/Gambas/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Gambas \ No newline at end of file diff --git a/Lang/Gema/Shell-one-liner b/Lang/Gema/Shell-one-liner new file mode 120000 index 0000000000..c383bf96e4 --- /dev/null +++ b/Lang/Gema/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Gema \ No newline at end of file diff --git a/Lang/Gema/Text-processing-Max-licenses-in-use b/Lang/Gema/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..e37f7726d2 --- /dev/null +++ b/Lang/Gema/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Gema \ No newline at end of file diff --git a/Lang/Genyris/Y-combinator b/Lang/Genyris/Y-combinator new file mode 120000 index 0000000000..6a2ce4b652 --- /dev/null +++ b/Lang/Genyris/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Genyris \ No newline at end of file diff --git a/Lang/Go/SHA-1 b/Lang/Go/SHA-1 new file mode 120000 index 0000000000..09d9d1eb2b --- /dev/null +++ b/Lang/Go/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Go \ No newline at end of file diff --git a/Lang/Go/SHA-256 b/Lang/Go/SHA-256 new file mode 120000 index 0000000000..46445ade93 --- /dev/null +++ b/Lang/Go/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Go \ No newline at end of file diff --git a/Lang/Go/Seven-sided-dice-from-five-sided-dice b/Lang/Go/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..813490ca49 --- /dev/null +++ b/Lang/Go/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Go \ No newline at end of file diff --git a/Lang/Go/Shell-one-liner b/Lang/Go/Shell-one-liner new file mode 120000 index 0000000000..ebaa53b08f --- /dev/null +++ b/Lang/Go/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Go \ No newline at end of file diff --git a/Lang/Go/Short-circuit-evaluation b/Lang/Go/Short-circuit-evaluation new file mode 120000 index 0000000000..aeae01d04a --- /dev/null +++ b/Lang/Go/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Go \ No newline at end of file diff --git a/Lang/Go/Show-the-epoch b/Lang/Go/Show-the-epoch new file mode 120000 index 0000000000..2851f66401 --- /dev/null +++ b/Lang/Go/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Go \ No newline at end of file diff --git a/Lang/Go/Sierpinski-carpet b/Lang/Go/Sierpinski-carpet new file mode 120000 index 0000000000..350fe5a0a4 --- /dev/null +++ b/Lang/Go/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Go \ No newline at end of file diff --git a/Lang/Go/Sierpinski-triangle b/Lang/Go/Sierpinski-triangle new file mode 120000 index 0000000000..c5988108e7 --- /dev/null +++ b/Lang/Go/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Go \ No newline at end of file diff --git a/Lang/Go/Sierpinski-triangle-Graphical b/Lang/Go/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..e1d7c15d03 --- /dev/null +++ b/Lang/Go/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Go \ No newline at end of file diff --git a/Lang/Go/Sieve-of-Eratosthenes b/Lang/Go/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ae8a62d7b9 --- /dev/null +++ b/Lang/Go/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Go \ No newline at end of file diff --git a/Lang/Go/Simple-database b/Lang/Go/Simple-database new file mode 120000 index 0000000000..054e2b70f3 --- /dev/null +++ b/Lang/Go/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Go \ No newline at end of file diff --git a/Lang/Go/Simple-windowed-application b/Lang/Go/Simple-windowed-application new file mode 120000 index 0000000000..8b49dae907 --- /dev/null +++ b/Lang/Go/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Go \ No newline at end of file diff --git a/Lang/Go/Singleton b/Lang/Go/Singleton new file mode 120000 index 0000000000..6a090ffb6d --- /dev/null +++ b/Lang/Go/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Go \ No newline at end of file diff --git a/Lang/Go/Singly-linked-list-Element-definition b/Lang/Go/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..fa9d2dc330 --- /dev/null +++ b/Lang/Go/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Go \ No newline at end of file diff --git a/Lang/Go/Singly-linked-list-Element-insertion b/Lang/Go/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..09c8391981 --- /dev/null +++ b/Lang/Go/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Go \ No newline at end of file diff --git a/Lang/Go/Singly-linked-list-Traversal b/Lang/Go/Singly-linked-list-Traversal new file mode 120000 index 0000000000..77ba3af2cb --- /dev/null +++ b/Lang/Go/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Go \ No newline at end of file diff --git a/Lang/Go/Sleep b/Lang/Go/Sleep new file mode 120000 index 0000000000..b24d037ae1 --- /dev/null +++ b/Lang/Go/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Go \ No newline at end of file diff --git a/Lang/Go/Sockets b/Lang/Go/Sockets new file mode 120000 index 0000000000..79f098bf45 --- /dev/null +++ b/Lang/Go/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Go \ No newline at end of file diff --git a/Lang/Go/Sokoban b/Lang/Go/Sokoban new file mode 120000 index 0000000000..4e0fd6d11b --- /dev/null +++ b/Lang/Go/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Go \ No newline at end of file diff --git a/Lang/Go/Sort-an-array-of-composite-structures b/Lang/Go/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..4ba7e83bf7 --- /dev/null +++ b/Lang/Go/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Go \ No newline at end of file diff --git a/Lang/Go/Sort-an-integer-array b/Lang/Go/Sort-an-integer-array new file mode 120000 index 0000000000..245835ed56 --- /dev/null +++ b/Lang/Go/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Go \ No newline at end of file diff --git a/Lang/Go/Sort-disjoint-sublist b/Lang/Go/Sort-disjoint-sublist new file mode 120000 index 0000000000..e947fca290 --- /dev/null +++ b/Lang/Go/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Go \ No newline at end of file diff --git a/Lang/Go/Sort-using-a-custom-comparator b/Lang/Go/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..a6333762aa --- /dev/null +++ b/Lang/Go/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Bead-sort b/Lang/Go/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..475c265d97 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Bogosort b/Lang/Go/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..9f857d9070 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Bubble-sort b/Lang/Go/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..5b6105d85e --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Cocktail-sort b/Lang/Go/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..2053de4785 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Comb-sort b/Lang/Go/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..fc4ce0ca4e --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Counting-sort b/Lang/Go/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..dfe13fef57 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Gnome-sort b/Lang/Go/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7f2b1a24f9 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Heapsort b/Lang/Go/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..1b1bcef9d2 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Insertion-sort b/Lang/Go/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4c212ba184 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Merge-sort b/Lang/Go/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..3d0905bceb --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Pancake-sort b/Lang/Go/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..76e51e7cec --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Permutation-sort b/Lang/Go/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..f48007b22d --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Quicksort b/Lang/Go/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..438461f2c7 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Radix-sort b/Lang/Go/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..d51c954ebf --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Selection-sort b/Lang/Go/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ea37e80804 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Shell-sort b/Lang/Go/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..21b04ede79 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Sleep-sort b/Lang/Go/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..537fdbfb38 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Stooge-sort b/Lang/Go/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..b0a23ad347 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-algorithms-Strand-sort b/Lang/Go/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..00d99e1e85 --- /dev/null +++ b/Lang/Go/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Go \ No newline at end of file diff --git a/Lang/Go/Soundex b/Lang/Go/Soundex new file mode 120000 index 0000000000..d316f2e243 --- /dev/null +++ b/Lang/Go/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Go \ No newline at end of file diff --git a/Lang/Go/Spiral-matrix b/Lang/Go/Spiral-matrix new file mode 120000 index 0000000000..dd5824d035 --- /dev/null +++ b/Lang/Go/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Go \ No newline at end of file diff --git a/Lang/Go/Stable-marriage-problem b/Lang/Go/Stable-marriage-problem new file mode 120000 index 0000000000..5f11301711 --- /dev/null +++ b/Lang/Go/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Go \ No newline at end of file diff --git a/Lang/Go/Stack b/Lang/Go/Stack new file mode 120000 index 0000000000..26d1e7c4ea --- /dev/null +++ b/Lang/Go/Stack @@ -0,0 +1 @@ +../../Task/Stack/Go \ No newline at end of file diff --git a/Lang/Go/Stack-traces b/Lang/Go/Stack-traces new file mode 120000 index 0000000000..fac034b949 --- /dev/null +++ b/Lang/Go/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Go \ No newline at end of file diff --git a/Lang/Go/Stair-climbing-puzzle b/Lang/Go/Stair-climbing-puzzle new file mode 120000 index 0000000000..7b42402509 --- /dev/null +++ b/Lang/Go/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Go \ No newline at end of file diff --git a/Lang/Go/Standard-deviation b/Lang/Go/Standard-deviation new file mode 120000 index 0000000000..cbb11e110b --- /dev/null +++ b/Lang/Go/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Go \ No newline at end of file diff --git a/Lang/Go/Stem-and-leaf-plot b/Lang/Go/Stem-and-leaf-plot new file mode 120000 index 0000000000..403b082159 --- /dev/null +++ b/Lang/Go/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Go \ No newline at end of file diff --git a/Lang/Go/String-case b/Lang/Go/String-case new file mode 120000 index 0000000000..adde44d747 --- /dev/null +++ b/Lang/Go/String-case @@ -0,0 +1 @@ +../../Task/String-case/Go \ No newline at end of file diff --git a/Lang/Go/String-concatenation b/Lang/Go/String-concatenation new file mode 120000 index 0000000000..b00be52144 --- /dev/null +++ b/Lang/Go/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Go \ No newline at end of file diff --git a/Lang/Go/String-interpolation--included- b/Lang/Go/String-interpolation--included- new file mode 120000 index 0000000000..944b783dcf --- /dev/null +++ b/Lang/Go/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Go \ No newline at end of file diff --git a/Lang/Go/String-length b/Lang/Go/String-length new file mode 120000 index 0000000000..fb7a0a19a6 --- /dev/null +++ b/Lang/Go/String-length @@ -0,0 +1 @@ +../../Task/String-length/Go \ No newline at end of file diff --git a/Lang/Go/Strip-a-set-of-characters-from-a-string b/Lang/Go/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..5fde0fe3d0 --- /dev/null +++ b/Lang/Go/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Go \ No newline at end of file diff --git a/Lang/Go/Strip-block-comments b/Lang/Go/Strip-block-comments new file mode 120000 index 0000000000..fc544c4655 --- /dev/null +++ b/Lang/Go/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Go \ No newline at end of file diff --git a/Lang/Go/Strip-comments-from-a-string b/Lang/Go/Strip-comments-from-a-string new file mode 120000 index 0000000000..368df9bbfe --- /dev/null +++ b/Lang/Go/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Go \ No newline at end of file diff --git a/Lang/Go/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Go/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..d888ccc9cd --- /dev/null +++ b/Lang/Go/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Go \ No newline at end of file diff --git a/Lang/Go/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Go/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..d186061b5c --- /dev/null +++ b/Lang/Go/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Go \ No newline at end of file diff --git a/Lang/Go/Substring b/Lang/Go/Substring new file mode 120000 index 0000000000..d291178bbf --- /dev/null +++ b/Lang/Go/Substring @@ -0,0 +1 @@ +../../Task/Substring/Go \ No newline at end of file diff --git a/Lang/Go/Substring-Top-and-tail b/Lang/Go/Substring-Top-and-tail new file mode 120000 index 0000000000..b6f926cdfa --- /dev/null +++ b/Lang/Go/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Go \ No newline at end of file diff --git a/Lang/Go/Subtractive-generator b/Lang/Go/Subtractive-generator new file mode 120000 index 0000000000..7a3ce2116a --- /dev/null +++ b/Lang/Go/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Go \ No newline at end of file diff --git a/Lang/Go/Sudoku b/Lang/Go/Sudoku new file mode 120000 index 0000000000..4f6be575ae --- /dev/null +++ b/Lang/Go/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Go \ No newline at end of file diff --git a/Lang/Go/Sum-and-product-of-an-array b/Lang/Go/Sum-and-product-of-an-array new file mode 120000 index 0000000000..1e29072b01 --- /dev/null +++ b/Lang/Go/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Go \ No newline at end of file diff --git a/Lang/Go/Sum-digits-of-an-integer b/Lang/Go/Sum-digits-of-an-integer new file mode 120000 index 0000000000..562e66e1c5 --- /dev/null +++ b/Lang/Go/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Go \ No newline at end of file diff --git a/Lang/Go/Sum-of-a-series b/Lang/Go/Sum-of-a-series new file mode 120000 index 0000000000..3b04d0510c --- /dev/null +++ b/Lang/Go/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Go \ No newline at end of file diff --git a/Lang/Go/Sum-of-squares b/Lang/Go/Sum-of-squares new file mode 120000 index 0000000000..62868c869f --- /dev/null +++ b/Lang/Go/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Go \ No newline at end of file diff --git a/Lang/Go/Sutherland-Hodgman-polygon-clipping b/Lang/Go/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..e5e5a44f28 --- /dev/null +++ b/Lang/Go/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Go \ No newline at end of file diff --git a/Lang/Go/Symmetric-difference b/Lang/Go/Symmetric-difference new file mode 120000 index 0000000000..570269faad --- /dev/null +++ b/Lang/Go/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Go \ No newline at end of file diff --git a/Lang/Go/Synchronous-concurrency b/Lang/Go/Synchronous-concurrency new file mode 120000 index 0000000000..9f7049b5e0 --- /dev/null +++ b/Lang/Go/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Go \ No newline at end of file diff --git a/Lang/Go/System-time b/Lang/Go/System-time new file mode 120000 index 0000000000..22ec39dd2c --- /dev/null +++ b/Lang/Go/System-time @@ -0,0 +1 @@ +../../Task/System-time/Go \ No newline at end of file diff --git a/Lang/Go/Take-notes-on-the-command-line b/Lang/Go/Take-notes-on-the-command-line new file mode 120000 index 0000000000..91b249a55a --- /dev/null +++ b/Lang/Go/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Clear-the-screen b/Lang/Go/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..67a7103c13 --- /dev/null +++ b/Lang/Go/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Display-an-extended-character b/Lang/Go/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..e588e3bd3f --- /dev/null +++ b/Lang/Go/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Ringing-the-terminal-bell b/Lang/Go/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c94f3bc201 --- /dev/null +++ b/Lang/Go/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Go \ No newline at end of file diff --git a/Lang/Go/Ternary-logic b/Lang/Go/Ternary-logic new file mode 120000 index 0000000000..81b14fc062 --- /dev/null +++ b/Lang/Go/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Go \ No newline at end of file diff --git a/Lang/Go/Test-a-function b/Lang/Go/Test-a-function new file mode 120000 index 0000000000..c5e662bf73 --- /dev/null +++ b/Lang/Go/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Go \ No newline at end of file diff --git a/Lang/Go/Text-processing-1 b/Lang/Go/Text-processing-1 new file mode 120000 index 0000000000..d4714fe5ef --- /dev/null +++ b/Lang/Go/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Go \ No newline at end of file diff --git a/Lang/Go/Text-processing-2 b/Lang/Go/Text-processing-2 new file mode 120000 index 0000000000..76636ddfc4 --- /dev/null +++ b/Lang/Go/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Go \ No newline at end of file diff --git a/Lang/Go/Text-processing-Max-licenses-in-use b/Lang/Go/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..20c998ff54 --- /dev/null +++ b/Lang/Go/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Go \ No newline at end of file diff --git a/Lang/Go/Thieles-interpolation-formula b/Lang/Go/Thieles-interpolation-formula new file mode 120000 index 0000000000..b1a70b14b3 --- /dev/null +++ b/Lang/Go/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Go \ No newline at end of file diff --git a/Lang/Go/Tic-tac-toe b/Lang/Go/Tic-tac-toe new file mode 120000 index 0000000000..eadd0a968e --- /dev/null +++ b/Lang/Go/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Go \ No newline at end of file diff --git a/Lang/Go/Time-a-function b/Lang/Go/Time-a-function new file mode 120000 index 0000000000..f0593f9f65 --- /dev/null +++ b/Lang/Go/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Go \ No newline at end of file diff --git a/Lang/Go/Tokenize-a-string b/Lang/Go/Tokenize-a-string new file mode 120000 index 0000000000..0976dc8d1b --- /dev/null +++ b/Lang/Go/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Go \ No newline at end of file diff --git a/Lang/Go/Top-rank-per-group b/Lang/Go/Top-rank-per-group new file mode 120000 index 0000000000..2d754fe16d --- /dev/null +++ b/Lang/Go/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Go \ No newline at end of file diff --git a/Lang/Go/Topological-sort b/Lang/Go/Topological-sort new file mode 120000 index 0000000000..e7171d9d3a --- /dev/null +++ b/Lang/Go/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Go \ No newline at end of file diff --git a/Lang/Go/Topswops b/Lang/Go/Topswops new file mode 120000 index 0000000000..1e84aca2da --- /dev/null +++ b/Lang/Go/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Go \ No newline at end of file diff --git a/Lang/Go/Towers-of-Hanoi b/Lang/Go/Towers-of-Hanoi new file mode 120000 index 0000000000..4adedaf2f7 --- /dev/null +++ b/Lang/Go/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Go \ No newline at end of file diff --git a/Lang/Go/Trabb-Pardo-Knuth-algorithm b/Lang/Go/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..b78030530b --- /dev/null +++ b/Lang/Go/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Go \ No newline at end of file diff --git a/Lang/Go/Tree-traversal b/Lang/Go/Tree-traversal new file mode 120000 index 0000000000..5f45696a69 --- /dev/null +++ b/Lang/Go/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Go \ No newline at end of file diff --git a/Lang/Go/Trigonometric-functions b/Lang/Go/Trigonometric-functions new file mode 120000 index 0000000000..24658a73d2 --- /dev/null +++ b/Lang/Go/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Go \ No newline at end of file diff --git a/Lang/Go/Truncatable-primes b/Lang/Go/Truncatable-primes new file mode 120000 index 0000000000..658ecb04b1 --- /dev/null +++ b/Lang/Go/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Go \ No newline at end of file diff --git a/Lang/Go/Truncate-a-file b/Lang/Go/Truncate-a-file new file mode 120000 index 0000000000..0dcbb81efd --- /dev/null +++ b/Lang/Go/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Go \ No newline at end of file diff --git a/Lang/Go/Twelve-statements b/Lang/Go/Twelve-statements new file mode 120000 index 0000000000..5796abdc21 --- /dev/null +++ b/Lang/Go/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Go \ No newline at end of file diff --git a/Lang/Go/URL-decoding b/Lang/Go/URL-decoding new file mode 120000 index 0000000000..1a914f074e --- /dev/null +++ b/Lang/Go/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Go \ No newline at end of file diff --git a/Lang/Go/URL-encoding b/Lang/Go/URL-encoding new file mode 120000 index 0000000000..5452267a33 --- /dev/null +++ b/Lang/Go/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Go \ No newline at end of file diff --git a/Lang/Go/Unbias-a-random-generator b/Lang/Go/Unbias-a-random-generator new file mode 120000 index 0000000000..1275b7d922 --- /dev/null +++ b/Lang/Go/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Go \ No newline at end of file diff --git a/Lang/Go/Undefined-values b/Lang/Go/Undefined-values new file mode 120000 index 0000000000..87b7e3afcc --- /dev/null +++ b/Lang/Go/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Go \ No newline at end of file diff --git a/Lang/Go/Unicode-strings b/Lang/Go/Unicode-strings new file mode 120000 index 0000000000..2e4f42c37b --- /dev/null +++ b/Lang/Go/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Go \ No newline at end of file diff --git a/Lang/Go/Unicode-variable-names b/Lang/Go/Unicode-variable-names new file mode 120000 index 0000000000..26d49acdc7 --- /dev/null +++ b/Lang/Go/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Go \ No newline at end of file diff --git a/Lang/Go/Update-a-configuration-file b/Lang/Go/Update-a-configuration-file new file mode 120000 index 0000000000..c5e70c3d59 --- /dev/null +++ b/Lang/Go/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Go \ No newline at end of file diff --git a/Lang/Go/Use-another-language-to-call-a-function b/Lang/Go/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..10edde9da0 --- /dev/null +++ b/Lang/Go/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Go \ No newline at end of file diff --git a/Lang/Go/User-input-Text b/Lang/Go/User-input-Text new file mode 120000 index 0000000000..d5d4c18a0c --- /dev/null +++ b/Lang/Go/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Go \ No newline at end of file diff --git a/Lang/Go/Van-der-Corput-sequence b/Lang/Go/Van-der-Corput-sequence new file mode 120000 index 0000000000..b51ce00ece --- /dev/null +++ b/Lang/Go/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Go \ No newline at end of file diff --git a/Lang/Go/Variable-length-quantity b/Lang/Go/Variable-length-quantity new file mode 120000 index 0000000000..bb34aa7fe8 --- /dev/null +++ b/Lang/Go/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Go \ No newline at end of file diff --git a/Lang/Go/Variable-size-Get b/Lang/Go/Variable-size-Get new file mode 120000 index 0000000000..68a48fc887 --- /dev/null +++ b/Lang/Go/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Go \ No newline at end of file diff --git a/Lang/Go/Variable-size-Set b/Lang/Go/Variable-size-Set new file mode 120000 index 0000000000..904ce28851 --- /dev/null +++ b/Lang/Go/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Go \ No newline at end of file diff --git a/Lang/Go/Variables b/Lang/Go/Variables new file mode 120000 index 0000000000..a441b92c28 --- /dev/null +++ b/Lang/Go/Variables @@ -0,0 +1 @@ +../../Task/Variables/Go \ No newline at end of file diff --git a/Lang/Go/Variadic-function b/Lang/Go/Variadic-function new file mode 120000 index 0000000000..a524825a7d --- /dev/null +++ b/Lang/Go/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Go \ No newline at end of file diff --git a/Lang/Go/Vector-products b/Lang/Go/Vector-products new file mode 120000 index 0000000000..53032bcaf2 --- /dev/null +++ b/Lang/Go/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Go \ No newline at end of file diff --git a/Lang/Go/Verify-distribution-uniformity-Chi-squared-test b/Lang/Go/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..0b913f8807 --- /dev/null +++ b/Lang/Go/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Go \ No newline at end of file diff --git a/Lang/Go/Verify-distribution-uniformity-Naive b/Lang/Go/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..829b0167fb --- /dev/null +++ b/Lang/Go/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Go \ No newline at end of file diff --git a/Lang/Go/Vigen-re-cipher b/Lang/Go/Vigen-re-cipher new file mode 120000 index 0000000000..80980ff83b --- /dev/null +++ b/Lang/Go/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Go \ No newline at end of file diff --git a/Lang/Go/Visualize-a-tree b/Lang/Go/Visualize-a-tree new file mode 120000 index 0000000000..681b4ae561 --- /dev/null +++ b/Lang/Go/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Go \ No newline at end of file diff --git a/Lang/Go/Voronoi-diagram b/Lang/Go/Voronoi-diagram new file mode 120000 index 0000000000..b2853f94e4 --- /dev/null +++ b/Lang/Go/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Go \ No newline at end of file diff --git a/Lang/Go/Walk-a-directory-Non-recursively b/Lang/Go/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9e1c463f66 --- /dev/null +++ b/Lang/Go/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Go \ No newline at end of file diff --git a/Lang/Go/Walk-a-directory-Recursively b/Lang/Go/Walk-a-directory-Recursively new file mode 120000 index 0000000000..f3260151fb --- /dev/null +++ b/Lang/Go/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Go \ No newline at end of file diff --git a/Lang/Go/Web-scraping b/Lang/Go/Web-scraping new file mode 120000 index 0000000000..af0ea5eb2a --- /dev/null +++ b/Lang/Go/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Go \ No newline at end of file diff --git a/Lang/Go/Window-creation b/Lang/Go/Window-creation new file mode 120000 index 0000000000..f2583a52c3 --- /dev/null +++ b/Lang/Go/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Go \ No newline at end of file diff --git a/Lang/Go/Window-creation-X11 b/Lang/Go/Window-creation-X11 new file mode 120000 index 0000000000..b4b7968dc2 --- /dev/null +++ b/Lang/Go/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Go \ No newline at end of file diff --git a/Lang/Go/Wireworld b/Lang/Go/Wireworld new file mode 120000 index 0000000000..0464f1b57c --- /dev/null +++ b/Lang/Go/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Go \ No newline at end of file diff --git a/Lang/Go/Word-wrap b/Lang/Go/Word-wrap new file mode 120000 index 0000000000..2d54a4e5a2 --- /dev/null +++ b/Lang/Go/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Go \ No newline at end of file diff --git a/Lang/Go/Write-float-arrays-to-a-text-file b/Lang/Go/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..311d781661 --- /dev/null +++ b/Lang/Go/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Go \ No newline at end of file diff --git a/Lang/Go/Write-language-name-in-3D-ASCII b/Lang/Go/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..df57df7cdf --- /dev/null +++ b/Lang/Go/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Go \ No newline at end of file diff --git a/Lang/Go/XML-DOM-serialization b/Lang/Go/XML-DOM-serialization new file mode 120000 index 0000000000..d5e2bcd13f --- /dev/null +++ b/Lang/Go/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Go \ No newline at end of file diff --git a/Lang/Go/XML-Input b/Lang/Go/XML-Input new file mode 120000 index 0000000000..ef46b8998b --- /dev/null +++ b/Lang/Go/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Go \ No newline at end of file diff --git a/Lang/Go/XML-Output b/Lang/Go/XML-Output new file mode 120000 index 0000000000..2fa769cdbf --- /dev/null +++ b/Lang/Go/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Go \ No newline at end of file diff --git a/Lang/Go/Xiaolin-Wus-line-algorithm b/Lang/Go/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..1a5b4a70fe --- /dev/null +++ b/Lang/Go/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Go \ No newline at end of file diff --git a/Lang/Go/Y-combinator b/Lang/Go/Y-combinator new file mode 120000 index 0000000000..9e9cfe4aa8 --- /dev/null +++ b/Lang/Go/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Go \ No newline at end of file diff --git a/Lang/Go/Yin-and-yang b/Lang/Go/Yin-and-yang new file mode 120000 index 0000000000..b213178aec --- /dev/null +++ b/Lang/Go/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Go \ No newline at end of file diff --git a/Lang/Go/Zeckendorf-number-representation b/Lang/Go/Zeckendorf-number-representation new file mode 120000 index 0000000000..3ee5a9e635 --- /dev/null +++ b/Lang/Go/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Go \ No newline at end of file diff --git a/Lang/Go/Zig-zag-matrix b/Lang/Go/Zig-zag-matrix new file mode 120000 index 0000000000..c3d2aa64d6 --- /dev/null +++ b/Lang/Go/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Go \ No newline at end of file diff --git a/Lang/Golfscript/Sort-an-integer-array b/Lang/Golfscript/Sort-an-integer-array new file mode 120000 index 0000000000..cf68add6ca --- /dev/null +++ b/Lang/Golfscript/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Golfscript \ No newline at end of file diff --git a/Lang/Golfscript/String-concatenation b/Lang/Golfscript/String-concatenation new file mode 120000 index 0000000000..0442168388 --- /dev/null +++ b/Lang/Golfscript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Golfscript \ No newline at end of file diff --git a/Lang/Golfscript/Sum-of-squares b/Lang/Golfscript/Sum-of-squares new file mode 120000 index 0000000000..7906a26c89 --- /dev/null +++ b/Lang/Golfscript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Golfscript \ No newline at end of file diff --git a/Lang/Groovy/SHA-256 b/Lang/Groovy/SHA-256 new file mode 120000 index 0000000000..49e619856c --- /dev/null +++ b/Lang/Groovy/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Seven-sided-dice-from-five-sided-dice b/Lang/Groovy/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..d3fee1a782 --- /dev/null +++ b/Lang/Groovy/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Shell-one-liner b/Lang/Groovy/Shell-one-liner new file mode 120000 index 0000000000..308e0c708a --- /dev/null +++ b/Lang/Groovy/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Short-circuit-evaluation b/Lang/Groovy/Short-circuit-evaluation new file mode 120000 index 0000000000..5686fa177e --- /dev/null +++ b/Lang/Groovy/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Show-the-epoch b/Lang/Groovy/Show-the-epoch new file mode 120000 index 0000000000..361b2a5464 --- /dev/null +++ b/Lang/Groovy/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sierpinski-carpet b/Lang/Groovy/Sierpinski-carpet new file mode 120000 index 0000000000..49c86d58b3 --- /dev/null +++ b/Lang/Groovy/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sierpinski-triangle b/Lang/Groovy/Sierpinski-triangle new file mode 120000 index 0000000000..a7d376eeb3 --- /dev/null +++ b/Lang/Groovy/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sieve-of-Eratosthenes b/Lang/Groovy/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ed273965ac --- /dev/null +++ b/Lang/Groovy/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Simple-windowed-application b/Lang/Groovy/Simple-windowed-application new file mode 120000 index 0000000000..916e64f58f --- /dev/null +++ b/Lang/Groovy/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Singleton b/Lang/Groovy/Singleton new file mode 120000 index 0000000000..1b1fbb4386 --- /dev/null +++ b/Lang/Groovy/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Singly-linked-list-Element-definition b/Lang/Groovy/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..c5ad7228c7 --- /dev/null +++ b/Lang/Groovy/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Singly-linked-list-Element-insertion b/Lang/Groovy/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..30d5a4ad2e --- /dev/null +++ b/Lang/Groovy/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sleep b/Lang/Groovy/Sleep new file mode 120000 index 0000000000..e8e296c9a6 --- /dev/null +++ b/Lang/Groovy/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sockets b/Lang/Groovy/Sockets new file mode 120000 index 0000000000..01a0214dab --- /dev/null +++ b/Lang/Groovy/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sort-an-array-of-composite-structures b/Lang/Groovy/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..fc9d02aa45 --- /dev/null +++ b/Lang/Groovy/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sort-an-integer-array b/Lang/Groovy/Sort-an-integer-array new file mode 120000 index 0000000000..acb8b35424 --- /dev/null +++ b/Lang/Groovy/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sort-disjoint-sublist b/Lang/Groovy/Sort-disjoint-sublist new file mode 120000 index 0000000000..e53b86b362 --- /dev/null +++ b/Lang/Groovy/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sort-stability b/Lang/Groovy/Sort-stability new file mode 120000 index 0000000000..2bd90da573 --- /dev/null +++ b/Lang/Groovy/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sort-using-a-custom-comparator b/Lang/Groovy/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..0d804e3f9f --- /dev/null +++ b/Lang/Groovy/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Bead-sort b/Lang/Groovy/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..df7c0190bf --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Bogosort b/Lang/Groovy/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..973aa91559 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Bubble-sort b/Lang/Groovy/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..6b77c3e822 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Cocktail-sort b/Lang/Groovy/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..f4de773f4b --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Comb-sort b/Lang/Groovy/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..28f1282d9a --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Counting-sort b/Lang/Groovy/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..9bd30a349c --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Gnome-sort b/Lang/Groovy/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..069a036654 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Heapsort b/Lang/Groovy/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..e9144aa9fe --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Insertion-sort b/Lang/Groovy/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4529e40fbd --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Merge-sort b/Lang/Groovy/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..eb053bf787 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Pancake-sort b/Lang/Groovy/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..e5c40ba3f8 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Permutation-sort b/Lang/Groovy/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..0c0edd0e7f --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Radix-sort b/Lang/Groovy/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..8122bdf031 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Soundex b/Lang/Groovy/Soundex new file mode 120000 index 0000000000..2de103d41b --- /dev/null +++ b/Lang/Groovy/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Spiral-matrix b/Lang/Groovy/Spiral-matrix new file mode 120000 index 0000000000..ada8e1bbbc --- /dev/null +++ b/Lang/Groovy/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Stable-marriage-problem b/Lang/Groovy/Stable-marriage-problem new file mode 120000 index 0000000000..252e97d175 --- /dev/null +++ b/Lang/Groovy/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Stack b/Lang/Groovy/Stack new file mode 120000 index 0000000000..8e6c7815c0 --- /dev/null +++ b/Lang/Groovy/Stack @@ -0,0 +1 @@ +../../Task/Stack/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Stack-traces b/Lang/Groovy/Stack-traces new file mode 120000 index 0000000000..e62b254ca0 --- /dev/null +++ b/Lang/Groovy/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Standard-deviation b/Lang/Groovy/Standard-deviation new file mode 120000 index 0000000000..32c4cffe09 --- /dev/null +++ b/Lang/Groovy/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-case b/Lang/Groovy/String-case new file mode 120000 index 0000000000..9607983044 --- /dev/null +++ b/Lang/Groovy/String-case @@ -0,0 +1 @@ +../../Task/String-case/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-concatenation b/Lang/Groovy/String-concatenation new file mode 120000 index 0000000000..b4dc4d4074 --- /dev/null +++ b/Lang/Groovy/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-interpolation--included- b/Lang/Groovy/String-interpolation--included- new file mode 120000 index 0000000000..6914007547 --- /dev/null +++ b/Lang/Groovy/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Groovy \ No newline at end of file diff --git a/Lang/Groovy/String-length b/Lang/Groovy/String-length new file mode 120000 index 0000000000..4e27601d2b --- /dev/null +++ b/Lang/Groovy/String-length @@ -0,0 +1 @@ +../../Task/String-length/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Strip-a-set-of-characters-from-a-string b/Lang/Groovy/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..9dfc325020 --- /dev/null +++ b/Lang/Groovy/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Strip-block-comments b/Lang/Groovy/Strip-block-comments new file mode 120000 index 0000000000..39640d5136 --- /dev/null +++ b/Lang/Groovy/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Groovy/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..afdf1738a1 --- /dev/null +++ b/Lang/Groovy/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Substring b/Lang/Groovy/Substring new file mode 120000 index 0000000000..63f0e7c603 --- /dev/null +++ b/Lang/Groovy/Substring @@ -0,0 +1 @@ +../../Task/Substring/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Substring-Top-and-tail b/Lang/Groovy/Substring-Top-and-tail new file mode 120000 index 0000000000..1f4775b2fc --- /dev/null +++ b/Lang/Groovy/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sudoku b/Lang/Groovy/Sudoku new file mode 120000 index 0000000000..cf95afd96f --- /dev/null +++ b/Lang/Groovy/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sum-and-product-of-an-array b/Lang/Groovy/Sum-and-product-of-an-array new file mode 120000 index 0000000000..aa32ab606c --- /dev/null +++ b/Lang/Groovy/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sum-digits-of-an-integer b/Lang/Groovy/Sum-digits-of-an-integer new file mode 120000 index 0000000000..20916af6bb --- /dev/null +++ b/Lang/Groovy/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sum-of-a-series b/Lang/Groovy/Sum-of-a-series new file mode 120000 index 0000000000..a5fea26201 --- /dev/null +++ b/Lang/Groovy/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sum-of-squares b/Lang/Groovy/Sum-of-squares new file mode 120000 index 0000000000..b82900ce76 --- /dev/null +++ b/Lang/Groovy/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Symmetric-difference b/Lang/Groovy/Symmetric-difference new file mode 120000 index 0000000000..af6e1d4560 --- /dev/null +++ b/Lang/Groovy/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Groovy \ No newline at end of file diff --git a/Lang/Groovy/System-time b/Lang/Groovy/System-time new file mode 120000 index 0000000000..fb5f6d927a --- /dev/null +++ b/Lang/Groovy/System-time @@ -0,0 +1 @@ +../../Task/System-time/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Terminal-control-Ringing-the-terminal-bell b/Lang/Groovy/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b8b7fbe41f --- /dev/null +++ b/Lang/Groovy/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Ternary-logic b/Lang/Groovy/Ternary-logic new file mode 120000 index 0000000000..e9ef592a1f --- /dev/null +++ b/Lang/Groovy/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Text-processing-Max-licenses-in-use b/Lang/Groovy/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..9dd9b4b417 --- /dev/null +++ b/Lang/Groovy/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Tic-tac-toe b/Lang/Groovy/Tic-tac-toe new file mode 120000 index 0000000000..a538da9466 --- /dev/null +++ b/Lang/Groovy/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Time-a-function b/Lang/Groovy/Time-a-function new file mode 120000 index 0000000000..2417e2f45c --- /dev/null +++ b/Lang/Groovy/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Tokenize-a-string b/Lang/Groovy/Tokenize-a-string new file mode 120000 index 0000000000..c4cc91756a --- /dev/null +++ b/Lang/Groovy/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Top-rank-per-group b/Lang/Groovy/Top-rank-per-group new file mode 120000 index 0000000000..f128876561 --- /dev/null +++ b/Lang/Groovy/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Towers-of-Hanoi b/Lang/Groovy/Towers-of-Hanoi new file mode 120000 index 0000000000..050d379f9b --- /dev/null +++ b/Lang/Groovy/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Tree-traversal b/Lang/Groovy/Tree-traversal new file mode 120000 index 0000000000..91b6ad27f6 --- /dev/null +++ b/Lang/Groovy/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Trigonometric-functions b/Lang/Groovy/Trigonometric-functions new file mode 120000 index 0000000000..be4a847508 --- /dev/null +++ b/Lang/Groovy/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Twelve-statements b/Lang/Groovy/Twelve-statements new file mode 120000 index 0000000000..efb35857fe --- /dev/null +++ b/Lang/Groovy/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Groovy \ No newline at end of file diff --git a/Lang/Groovy/URL-decoding b/Lang/Groovy/URL-decoding new file mode 120000 index 0000000000..eac79d5a90 --- /dev/null +++ b/Lang/Groovy/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Groovy \ No newline at end of file diff --git a/Lang/Groovy/User-input-Text b/Lang/Groovy/User-input-Text new file mode 120000 index 0000000000..eac8cbf806 --- /dev/null +++ b/Lang/Groovy/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Variable-length-quantity b/Lang/Groovy/Variable-length-quantity new file mode 120000 index 0000000000..bbd82e57d6 --- /dev/null +++ b/Lang/Groovy/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Variadic-function b/Lang/Groovy/Variadic-function new file mode 120000 index 0000000000..6117f77fc6 --- /dev/null +++ b/Lang/Groovy/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Vector-products b/Lang/Groovy/Vector-products new file mode 120000 index 0000000000..b4764ec322 --- /dev/null +++ b/Lang/Groovy/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Walk-a-directory-Non-recursively b/Lang/Groovy/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..d47c209e84 --- /dev/null +++ b/Lang/Groovy/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Walk-a-directory-Recursively b/Lang/Groovy/Walk-a-directory-Recursively new file mode 120000 index 0000000000..8b6dab2d9e --- /dev/null +++ b/Lang/Groovy/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Web-scraping b/Lang/Groovy/Web-scraping new file mode 120000 index 0000000000..b187d88fa8 --- /dev/null +++ b/Lang/Groovy/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Groovy \ No newline at end of file diff --git a/Lang/Groovy/XML-DOM-serialization b/Lang/Groovy/XML-DOM-serialization new file mode 120000 index 0000000000..08891ad8ec --- /dev/null +++ b/Lang/Groovy/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Groovy \ No newline at end of file diff --git a/Lang/Groovy/XML-Input b/Lang/Groovy/XML-Input new file mode 120000 index 0000000000..85d4c891ff --- /dev/null +++ b/Lang/Groovy/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Groovy \ No newline at end of file diff --git a/Lang/Groovy/XML-Output b/Lang/Groovy/XML-Output new file mode 120000 index 0000000000..95a9cdd41c --- /dev/null +++ b/Lang/Groovy/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Groovy \ No newline at end of file diff --git a/Lang/Groovy/XML-XPath b/Lang/Groovy/XML-XPath new file mode 120000 index 0000000000..06d81b32e2 --- /dev/null +++ b/Lang/Groovy/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Y-combinator b/Lang/Groovy/Y-combinator new file mode 120000 index 0000000000..5540738180 --- /dev/null +++ b/Lang/Groovy/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Zig-zag-matrix b/Lang/Groovy/Zig-zag-matrix new file mode 120000 index 0000000000..9b84887cb5 --- /dev/null +++ b/Lang/Groovy/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Groovy \ No newline at end of file diff --git a/Lang/Haskell/Seven-sided-dice-from-five-sided-dice b/Lang/Haskell/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..12f985bda1 --- /dev/null +++ b/Lang/Haskell/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Shell-one-liner b/Lang/Haskell/Shell-one-liner new file mode 120000 index 0000000000..7f0146dffc --- /dev/null +++ b/Lang/Haskell/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Short-circuit-evaluation b/Lang/Haskell/Short-circuit-evaluation new file mode 120000 index 0000000000..fd30ac079a --- /dev/null +++ b/Lang/Haskell/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Show-the-epoch b/Lang/Haskell/Show-the-epoch new file mode 120000 index 0000000000..72cb146ba7 --- /dev/null +++ b/Lang/Haskell/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sierpinski-carpet b/Lang/Haskell/Sierpinski-carpet new file mode 120000 index 0000000000..f3ef027f21 --- /dev/null +++ b/Lang/Haskell/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sierpinski-triangle b/Lang/Haskell/Sierpinski-triangle new file mode 120000 index 0000000000..114a8742f6 --- /dev/null +++ b/Lang/Haskell/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sierpinski-triangle-Graphical b/Lang/Haskell/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..a636eb2a92 --- /dev/null +++ b/Lang/Haskell/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sieve-of-Eratosthenes b/Lang/Haskell/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..db7a03b362 --- /dev/null +++ b/Lang/Haskell/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Simple-database b/Lang/Haskell/Simple-database new file mode 120000 index 0000000000..004a5b935b --- /dev/null +++ b/Lang/Haskell/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Simple-windowed-application b/Lang/Haskell/Simple-windowed-application new file mode 120000 index 0000000000..fb5954c948 --- /dev/null +++ b/Lang/Haskell/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Singly-linked-list-Element-definition b/Lang/Haskell/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..40017932f0 --- /dev/null +++ b/Lang/Haskell/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Singly-linked-list-Element-insertion b/Lang/Haskell/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..948c5f8d95 --- /dev/null +++ b/Lang/Haskell/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Singly-linked-list-Traversal b/Lang/Haskell/Singly-linked-list-Traversal new file mode 120000 index 0000000000..0d7b6da279 --- /dev/null +++ b/Lang/Haskell/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sleep b/Lang/Haskell/Sleep new file mode 120000 index 0000000000..0fa245dfc5 --- /dev/null +++ b/Lang/Haskell/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sockets b/Lang/Haskell/Sockets new file mode 120000 index 0000000000..cdc6fe177a --- /dev/null +++ b/Lang/Haskell/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sort-an-array-of-composite-structures b/Lang/Haskell/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..d8a7a27b85 --- /dev/null +++ b/Lang/Haskell/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sort-an-integer-array b/Lang/Haskell/Sort-an-integer-array new file mode 120000 index 0000000000..f4532c93db --- /dev/null +++ b/Lang/Haskell/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sort-disjoint-sublist b/Lang/Haskell/Sort-disjoint-sublist new file mode 120000 index 0000000000..0efc1d05a3 --- /dev/null +++ b/Lang/Haskell/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sort-using-a-custom-comparator b/Lang/Haskell/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..9030d71316 --- /dev/null +++ b/Lang/Haskell/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Bead-sort b/Lang/Haskell/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..fe3d283466 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Bogosort b/Lang/Haskell/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..413de5c54e --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Bubble-sort b/Lang/Haskell/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..200be4db46 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Cocktail-sort b/Lang/Haskell/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..25894848e9 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Comb-sort b/Lang/Haskell/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..76e82f6970 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Counting-sort b/Lang/Haskell/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..32ad3074cb --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Gnome-sort b/Lang/Haskell/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..dcc26a82e7 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Heapsort b/Lang/Haskell/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..e33b81bf66 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Insertion-sort b/Lang/Haskell/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..488e5187c9 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Merge-sort b/Lang/Haskell/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..1d259a8755 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Pancake-sort b/Lang/Haskell/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..9b07f0b325 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Permutation-sort b/Lang/Haskell/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..5d9d6adc1a --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Quicksort b/Lang/Haskell/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..a5adbefbd3 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Radix-sort b/Lang/Haskell/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..47f0cacda5 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Selection-sort b/Lang/Haskell/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..8576564e70 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Shell-sort b/Lang/Haskell/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..c7db17551c --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Sleep-sort b/Lang/Haskell/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..6ab0c166ed --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Stooge-sort b/Lang/Haskell/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..8c2939c367 --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-algorithms-Strand-sort b/Lang/Haskell/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..77dec05efa --- /dev/null +++ b/Lang/Haskell/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Soundex b/Lang/Haskell/Soundex new file mode 120000 index 0000000000..d9dba90875 --- /dev/null +++ b/Lang/Haskell/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Special-characters b/Lang/Haskell/Special-characters new file mode 120000 index 0000000000..a4179a7907 --- /dev/null +++ b/Lang/Haskell/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Speech-synthesis b/Lang/Haskell/Speech-synthesis new file mode 120000 index 0000000000..c5cfb49b73 --- /dev/null +++ b/Lang/Haskell/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Spiral-matrix b/Lang/Haskell/Spiral-matrix new file mode 120000 index 0000000000..537e954f81 --- /dev/null +++ b/Lang/Haskell/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Stable-marriage-problem b/Lang/Haskell/Stable-marriage-problem new file mode 120000 index 0000000000..e1076efc18 --- /dev/null +++ b/Lang/Haskell/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Stack b/Lang/Haskell/Stack new file mode 120000 index 0000000000..cd444c1291 --- /dev/null +++ b/Lang/Haskell/Stack @@ -0,0 +1 @@ +../../Task/Stack/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Stair-climbing-puzzle b/Lang/Haskell/Stair-climbing-puzzle new file mode 120000 index 0000000000..f9e7954a13 --- /dev/null +++ b/Lang/Haskell/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Standard-deviation b/Lang/Haskell/Standard-deviation new file mode 120000 index 0000000000..e19450d67c --- /dev/null +++ b/Lang/Haskell/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Stem-and-leaf-plot b/Lang/Haskell/Stem-and-leaf-plot new file mode 120000 index 0000000000..72b02b15f9 --- /dev/null +++ b/Lang/Haskell/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-case b/Lang/Haskell/String-case new file mode 120000 index 0000000000..892f76fe0c --- /dev/null +++ b/Lang/Haskell/String-case @@ -0,0 +1 @@ +../../Task/String-case/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-concatenation b/Lang/Haskell/String-concatenation new file mode 120000 index 0000000000..6e709419dc --- /dev/null +++ b/Lang/Haskell/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-interpolation--included- b/Lang/Haskell/String-interpolation--included- new file mode 120000 index 0000000000..d8bd2c83a4 --- /dev/null +++ b/Lang/Haskell/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-length b/Lang/Haskell/String-length new file mode 120000 index 0000000000..4fa251ff63 --- /dev/null +++ b/Lang/Haskell/String-length @@ -0,0 +1 @@ +../../Task/String-length/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strip-a-set-of-characters-from-a-string b/Lang/Haskell/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..bff880c18e --- /dev/null +++ b/Lang/Haskell/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strip-block-comments b/Lang/Haskell/Strip-block-comments new file mode 120000 index 0000000000..c463031812 --- /dev/null +++ b/Lang/Haskell/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strip-comments-from-a-string b/Lang/Haskell/Strip-comments-from-a-string new file mode 120000 index 0000000000..3241b6d978 --- /dev/null +++ b/Lang/Haskell/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Haskell/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..9e22e62af3 --- /dev/null +++ b/Lang/Haskell/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Haskell/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..68c69d8582 --- /dev/null +++ b/Lang/Haskell/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Substring b/Lang/Haskell/Substring new file mode 120000 index 0000000000..8b6141fe4b --- /dev/null +++ b/Lang/Haskell/Substring @@ -0,0 +1 @@ +../../Task/Substring/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Substring-Top-and-tail b/Lang/Haskell/Substring-Top-and-tail new file mode 120000 index 0000000000..c11149d271 --- /dev/null +++ b/Lang/Haskell/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Subtractive-generator b/Lang/Haskell/Subtractive-generator new file mode 120000 index 0000000000..051c954873 --- /dev/null +++ b/Lang/Haskell/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sum-and-product-of-an-array b/Lang/Haskell/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4075b7aac3 --- /dev/null +++ b/Lang/Haskell/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sum-digits-of-an-integer b/Lang/Haskell/Sum-digits-of-an-integer new file mode 120000 index 0000000000..14af4fbffb --- /dev/null +++ b/Lang/Haskell/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sum-of-a-series b/Lang/Haskell/Sum-of-a-series new file mode 120000 index 0000000000..e094cbb394 --- /dev/null +++ b/Lang/Haskell/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sum-of-squares b/Lang/Haskell/Sum-of-squares new file mode 120000 index 0000000000..142724a38f --- /dev/null +++ b/Lang/Haskell/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sutherland-Hodgman-polygon-clipping b/Lang/Haskell/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..d27f103b3c --- /dev/null +++ b/Lang/Haskell/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Symmetric-difference b/Lang/Haskell/Symmetric-difference new file mode 120000 index 0000000000..1b9b288568 --- /dev/null +++ b/Lang/Haskell/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Synchronous-concurrency b/Lang/Haskell/Synchronous-concurrency new file mode 120000 index 0000000000..4a4d716883 --- /dev/null +++ b/Lang/Haskell/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Haskell \ No newline at end of file diff --git a/Lang/Haskell/System-time b/Lang/Haskell/System-time new file mode 120000 index 0000000000..8a3014f73b --- /dev/null +++ b/Lang/Haskell/System-time @@ -0,0 +1 @@ +../../Task/System-time/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Take-notes-on-the-command-line b/Lang/Haskell/Take-notes-on-the-command-line new file mode 120000 index 0000000000..5edc7f7dcc --- /dev/null +++ b/Lang/Haskell/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Terminal-control-Coloured-text b/Lang/Haskell/Terminal-control-Coloured-text new file mode 120000 index 0000000000..ebb9af3fff --- /dev/null +++ b/Lang/Haskell/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Terminal-control-Display-an-extended-character b/Lang/Haskell/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..de53947646 --- /dev/null +++ b/Lang/Haskell/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Terminal-control-Ringing-the-terminal-bell b/Lang/Haskell/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..52bd366c38 --- /dev/null +++ b/Lang/Haskell/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Ternary-logic b/Lang/Haskell/Ternary-logic new file mode 120000 index 0000000000..4fb051f232 --- /dev/null +++ b/Lang/Haskell/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Test-a-function b/Lang/Haskell/Test-a-function new file mode 120000 index 0000000000..c5744ee5bc --- /dev/null +++ b/Lang/Haskell/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Text-processing-1 b/Lang/Haskell/Text-processing-1 new file mode 120000 index 0000000000..62a9824432 --- /dev/null +++ b/Lang/Haskell/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Text-processing-2 b/Lang/Haskell/Text-processing-2 new file mode 120000 index 0000000000..ac23a62eb6 --- /dev/null +++ b/Lang/Haskell/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Thieles-interpolation-formula b/Lang/Haskell/Thieles-interpolation-formula new file mode 120000 index 0000000000..777b2633dc --- /dev/null +++ b/Lang/Haskell/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Tic-tac-toe b/Lang/Haskell/Tic-tac-toe new file mode 120000 index 0000000000..382825bfe2 --- /dev/null +++ b/Lang/Haskell/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Time-a-function b/Lang/Haskell/Time-a-function new file mode 120000 index 0000000000..5a778e67b5 --- /dev/null +++ b/Lang/Haskell/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Tokenize-a-string b/Lang/Haskell/Tokenize-a-string new file mode 120000 index 0000000000..029f353bdf --- /dev/null +++ b/Lang/Haskell/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Top-rank-per-group b/Lang/Haskell/Top-rank-per-group new file mode 120000 index 0000000000..1e7477a330 --- /dev/null +++ b/Lang/Haskell/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Topological-sort b/Lang/Haskell/Topological-sort new file mode 120000 index 0000000000..5c6e7ea4c0 --- /dev/null +++ b/Lang/Haskell/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Topswops b/Lang/Haskell/Topswops new file mode 120000 index 0000000000..340a1e76c5 --- /dev/null +++ b/Lang/Haskell/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Towers-of-Hanoi b/Lang/Haskell/Towers-of-Hanoi new file mode 120000 index 0000000000..a3a858e711 --- /dev/null +++ b/Lang/Haskell/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Trabb-Pardo-Knuth-algorithm b/Lang/Haskell/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..bbc44e774d --- /dev/null +++ b/Lang/Haskell/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Tree-traversal b/Lang/Haskell/Tree-traversal new file mode 120000 index 0000000000..cd31858d03 --- /dev/null +++ b/Lang/Haskell/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Trigonometric-functions b/Lang/Haskell/Trigonometric-functions new file mode 120000 index 0000000000..1134cb55ea --- /dev/null +++ b/Lang/Haskell/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Truncatable-primes b/Lang/Haskell/Truncatable-primes new file mode 120000 index 0000000000..5e414972c3 --- /dev/null +++ b/Lang/Haskell/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Truncate-a-file b/Lang/Haskell/Truncate-a-file new file mode 120000 index 0000000000..4cffa5de37 --- /dev/null +++ b/Lang/Haskell/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Twelve-statements b/Lang/Haskell/Twelve-statements new file mode 120000 index 0000000000..bdf1a49d84 --- /dev/null +++ b/Lang/Haskell/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Unbias-a-random-generator b/Lang/Haskell/Unbias-a-random-generator new file mode 120000 index 0000000000..4bbba50e84 --- /dev/null +++ b/Lang/Haskell/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Undefined-values b/Lang/Haskell/Undefined-values new file mode 120000 index 0000000000..87f7a151d4 --- /dev/null +++ b/Lang/Haskell/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Unicode-variable-names b/Lang/Haskell/Unicode-variable-names new file mode 120000 index 0000000000..85721f4fe3 --- /dev/null +++ b/Lang/Haskell/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Use-another-language-to-call-a-function b/Lang/Haskell/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..fbf8844a9c --- /dev/null +++ b/Lang/Haskell/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Haskell \ No newline at end of file diff --git a/Lang/Haskell/User-input-Graphical b/Lang/Haskell/User-input-Graphical new file mode 120000 index 0000000000..bed9917561 --- /dev/null +++ b/Lang/Haskell/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Haskell \ No newline at end of file diff --git a/Lang/Haskell/User-input-Text b/Lang/Haskell/User-input-Text new file mode 120000 index 0000000000..617ad223e2 --- /dev/null +++ b/Lang/Haskell/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Vampire-number b/Lang/Haskell/Vampire-number new file mode 120000 index 0000000000..07f3b9777d --- /dev/null +++ b/Lang/Haskell/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Van-der-Corput-sequence b/Lang/Haskell/Van-der-Corput-sequence new file mode 120000 index 0000000000..d3b5fc166b --- /dev/null +++ b/Lang/Haskell/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Variable-size-Get b/Lang/Haskell/Variable-size-Get new file mode 120000 index 0000000000..02aad08f83 --- /dev/null +++ b/Lang/Haskell/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Variables b/Lang/Haskell/Variables new file mode 120000 index 0000000000..0fd3ebf030 --- /dev/null +++ b/Lang/Haskell/Variables @@ -0,0 +1 @@ +../../Task/Variables/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Variadic-function b/Lang/Haskell/Variadic-function new file mode 120000 index 0000000000..5c8877611e --- /dev/null +++ b/Lang/Haskell/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Vector-products b/Lang/Haskell/Vector-products new file mode 120000 index 0000000000..8f26bfa023 --- /dev/null +++ b/Lang/Haskell/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Verify-distribution-uniformity-Naive b/Lang/Haskell/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..c161fe16d0 --- /dev/null +++ b/Lang/Haskell/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Vigen-re-cipher b/Lang/Haskell/Vigen-re-cipher new file mode 120000 index 0000000000..e53fe6b178 --- /dev/null +++ b/Lang/Haskell/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Visualize-a-tree b/Lang/Haskell/Visualize-a-tree new file mode 120000 index 0000000000..5dc33bf40a --- /dev/null +++ b/Lang/Haskell/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Walk-a-directory-Non-recursively b/Lang/Haskell/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..8f78c8edcc --- /dev/null +++ b/Lang/Haskell/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Walk-a-directory-Recursively b/Lang/Haskell/Walk-a-directory-Recursively new file mode 120000 index 0000000000..0037831d41 --- /dev/null +++ b/Lang/Haskell/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Web-scraping b/Lang/Haskell/Web-scraping new file mode 120000 index 0000000000..a1edaed4b2 --- /dev/null +++ b/Lang/Haskell/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Window-creation b/Lang/Haskell/Window-creation new file mode 120000 index 0000000000..6f013479eb --- /dev/null +++ b/Lang/Haskell/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Window-creation-X11 b/Lang/Haskell/Window-creation-X11 new file mode 120000 index 0000000000..dc2b06c081 --- /dev/null +++ b/Lang/Haskell/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Wireworld b/Lang/Haskell/Wireworld new file mode 120000 index 0000000000..785ef87942 --- /dev/null +++ b/Lang/Haskell/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Word-wrap b/Lang/Haskell/Word-wrap new file mode 120000 index 0000000000..aead8a28c7 --- /dev/null +++ b/Lang/Haskell/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Write-float-arrays-to-a-text-file b/Lang/Haskell/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..076c8b9640 --- /dev/null +++ b/Lang/Haskell/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Write-language-name-in-3D-ASCII b/Lang/Haskell/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..1b198b429a --- /dev/null +++ b/Lang/Haskell/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Haskell \ No newline at end of file diff --git a/Lang/Haskell/XML-DOM-serialization b/Lang/Haskell/XML-DOM-serialization new file mode 120000 index 0000000000..65fe6cfefe --- /dev/null +++ b/Lang/Haskell/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Haskell \ No newline at end of file diff --git a/Lang/Haskell/XML-Input b/Lang/Haskell/XML-Input new file mode 120000 index 0000000000..dc93fc532b --- /dev/null +++ b/Lang/Haskell/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Haskell \ No newline at end of file diff --git a/Lang/Haskell/XML-Output b/Lang/Haskell/XML-Output new file mode 120000 index 0000000000..c00d846f48 --- /dev/null +++ b/Lang/Haskell/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Haskell \ No newline at end of file diff --git a/Lang/Haskell/XML-XPath b/Lang/Haskell/XML-XPath new file mode 120000 index 0000000000..830323f554 --- /dev/null +++ b/Lang/Haskell/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Y-combinator b/Lang/Haskell/Y-combinator new file mode 120000 index 0000000000..0d726cd043 --- /dev/null +++ b/Lang/Haskell/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Yahoo--search-interface b/Lang/Haskell/Yahoo--search-interface new file mode 120000 index 0000000000..d03ea1239d --- /dev/null +++ b/Lang/Haskell/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Yin-and-yang b/Lang/Haskell/Yin-and-yang new file mode 120000 index 0000000000..6c061618f9 --- /dev/null +++ b/Lang/Haskell/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Zeckendorf-number-representation b/Lang/Haskell/Zeckendorf-number-representation new file mode 120000 index 0000000000..ffa9dc47ae --- /dev/null +++ b/Lang/Haskell/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Zig-zag-matrix b/Lang/Haskell/Zig-zag-matrix new file mode 120000 index 0000000000..a9fc070133 --- /dev/null +++ b/Lang/Haskell/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Haskell \ No newline at end of file diff --git a/Lang/Haxe/Sierpinski-triangle b/Lang/Haxe/Sierpinski-triangle new file mode 120000 index 0000000000..03e9fc788d --- /dev/null +++ b/Lang/Haxe/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Selection-sort b/Lang/Haxe/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..2b2a4210c0 --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Standard-deviation b/Lang/Haxe/Standard-deviation new file mode 120000 index 0000000000..01324a2bdc --- /dev/null +++ b/Lang/Haxe/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Use-another-language-to-call-a-function b/Lang/Haxe/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..c45220a7e2 --- /dev/null +++ b/Lang/Haxe/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Haxe \ No newline at end of file diff --git a/Lang/HicEst/Sieve-of-Eratosthenes b/Lang/HicEst/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..26aff7f5a8 --- /dev/null +++ b/Lang/HicEst/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Simple-windowed-application b/Lang/HicEst/Simple-windowed-application new file mode 120000 index 0000000000..6e8bf832d3 --- /dev/null +++ b/Lang/HicEst/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sleep b/Lang/HicEst/Sleep new file mode 120000 index 0000000000..fd7df25ec0 --- /dev/null +++ b/Lang/HicEst/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sort-an-integer-array b/Lang/HicEst/Sort-an-integer-array new file mode 120000 index 0000000000..bfd5f7fbd1 --- /dev/null +++ b/Lang/HicEst/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sorting-algorithms-Bubble-sort b/Lang/HicEst/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..dceb6ee46f --- /dev/null +++ b/Lang/HicEst/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sorting-algorithms-Insertion-sort b/Lang/HicEst/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..8ea6dbbd09 --- /dev/null +++ b/Lang/HicEst/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Standard-deviation b/Lang/HicEst/Standard-deviation new file mode 120000 index 0000000000..a8bfa138bf --- /dev/null +++ b/Lang/HicEst/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Stem-and-leaf-plot b/Lang/HicEst/Stem-and-leaf-plot new file mode 120000 index 0000000000..ceebb9e769 --- /dev/null +++ b/Lang/HicEst/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/HicEst \ No newline at end of file diff --git a/Lang/HicEst/String-case b/Lang/HicEst/String-case new file mode 120000 index 0000000000..3fa3d256a4 --- /dev/null +++ b/Lang/HicEst/String-case @@ -0,0 +1 @@ +../../Task/String-case/HicEst \ No newline at end of file diff --git a/Lang/HicEst/String-concatenation b/Lang/HicEst/String-concatenation new file mode 120000 index 0000000000..8608c9571d --- /dev/null +++ b/Lang/HicEst/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/HicEst \ No newline at end of file diff --git a/Lang/HicEst/String-interpolation--included- b/Lang/HicEst/String-interpolation--included- new file mode 120000 index 0000000000..2c7d7997dd --- /dev/null +++ b/Lang/HicEst/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/HicEst \ No newline at end of file diff --git a/Lang/HicEst/String-length b/Lang/HicEst/String-length new file mode 120000 index 0000000000..2f298fbb63 --- /dev/null +++ b/Lang/HicEst/String-length @@ -0,0 +1 @@ +../../Task/String-length/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Substring b/Lang/HicEst/Substring new file mode 120000 index 0000000000..79b6565fcb --- /dev/null +++ b/Lang/HicEst/Substring @@ -0,0 +1 @@ +../../Task/Substring/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sum-and-product-of-an-array b/Lang/HicEst/Sum-and-product-of-an-array new file mode 120000 index 0000000000..461b4ce04d --- /dev/null +++ b/Lang/HicEst/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Sum-of-a-series b/Lang/HicEst/Sum-of-a-series new file mode 120000 index 0000000000..f0679059fc --- /dev/null +++ b/Lang/HicEst/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Symmetric-difference b/Lang/HicEst/Symmetric-difference new file mode 120000 index 0000000000..aacb3eca44 --- /dev/null +++ b/Lang/HicEst/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/HicEst \ No newline at end of file diff --git a/Lang/HicEst/System-time b/Lang/HicEst/System-time new file mode 120000 index 0000000000..d6ad0349df --- /dev/null +++ b/Lang/HicEst/System-time @@ -0,0 +1 @@ +../../Task/System-time/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Take-notes-on-the-command-line b/Lang/HicEst/Take-notes-on-the-command-line new file mode 120000 index 0000000000..ff65f61270 --- /dev/null +++ b/Lang/HicEst/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Text-processing-Max-licenses-in-use b/Lang/HicEst/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..743d4fbbf4 --- /dev/null +++ b/Lang/HicEst/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Time-a-function b/Lang/HicEst/Time-a-function new file mode 120000 index 0000000000..6236967ddf --- /dev/null +++ b/Lang/HicEst/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Tokenize-a-string b/Lang/HicEst/Tokenize-a-string new file mode 120000 index 0000000000..707f0476bf --- /dev/null +++ b/Lang/HicEst/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Top-rank-per-group b/Lang/HicEst/Top-rank-per-group new file mode 120000 index 0000000000..b38b223b1c --- /dev/null +++ b/Lang/HicEst/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Trigonometric-functions b/Lang/HicEst/Trigonometric-functions new file mode 120000 index 0000000000..6e789cc4ef --- /dev/null +++ b/Lang/HicEst/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/HicEst \ No newline at end of file diff --git a/Lang/HicEst/User-input-Graphical b/Lang/HicEst/User-input-Graphical new file mode 120000 index 0000000000..2bb04587d5 --- /dev/null +++ b/Lang/HicEst/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Variables b/Lang/HicEst/Variables new file mode 120000 index 0000000000..1883d09e9d --- /dev/null +++ b/Lang/HicEst/Variables @@ -0,0 +1 @@ +../../Task/Variables/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Walk-a-directory-Non-recursively b/Lang/HicEst/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..712f290ea6 --- /dev/null +++ b/Lang/HicEst/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Window-creation b/Lang/HicEst/Window-creation new file mode 120000 index 0000000000..d518c0e7c8 --- /dev/null +++ b/Lang/HicEst/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Window-management b/Lang/HicEst/Window-management new file mode 120000 index 0000000000..39c5adea1a --- /dev/null +++ b/Lang/HicEst/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/HicEst \ No newline at end of file diff --git a/Lang/HicEst/Write-float-arrays-to-a-text-file b/Lang/HicEst/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..044c7b80d2 --- /dev/null +++ b/Lang/HicEst/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/HicEst \ No newline at end of file diff --git a/Lang/HicEst/XML-Input b/Lang/HicEst/XML-Input new file mode 120000 index 0000000000..10331f2967 --- /dev/null +++ b/Lang/HicEst/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/HicEst \ No newline at end of file diff --git a/Lang/HicEst/XML-Output b/Lang/HicEst/XML-Output new file mode 120000 index 0000000000..2b51ac4bfd --- /dev/null +++ b/Lang/HicEst/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/HicEst \ No newline at end of file diff --git a/Lang/HicEst/XML-XPath b/Lang/HicEst/XML-XPath new file mode 120000 index 0000000000..add1d1a5c6 --- /dev/null +++ b/Lang/HicEst/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/HicEst \ No newline at end of file diff --git a/Lang/IDL/Sierpinski-triangle b/Lang/IDL/Sierpinski-triangle new file mode 120000 index 0000000000..06708082af --- /dev/null +++ b/Lang/IDL/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/IDL \ No newline at end of file diff --git a/Lang/IDL/Simple-windowed-application b/Lang/IDL/Simple-windowed-application new file mode 120000 index 0000000000..135f781fdb --- /dev/null +++ b/Lang/IDL/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/IDL \ No newline at end of file diff --git a/Lang/IDL/Sleep b/Lang/IDL/Sleep new file mode 120000 index 0000000000..0489c54b63 --- /dev/null +++ b/Lang/IDL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/IDL \ No newline at end of file diff --git a/Lang/IDL/Sockets b/Lang/IDL/Sockets new file mode 120000 index 0000000000..1a5c204888 --- /dev/null +++ b/Lang/IDL/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/IDL \ No newline at end of file diff --git a/Lang/IDL/Sort-an-integer-array b/Lang/IDL/Sort-an-integer-array new file mode 120000 index 0000000000..f53bd40ad5 --- /dev/null +++ b/Lang/IDL/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/IDL \ No newline at end of file diff --git a/Lang/IDL/Sorting-algorithms-Quicksort b/Lang/IDL/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..78cd0334dc --- /dev/null +++ b/Lang/IDL/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/IDL \ No newline at end of file diff --git a/Lang/IDL/String-concatenation b/Lang/IDL/String-concatenation new file mode 120000 index 0000000000..dd338bbd50 --- /dev/null +++ b/Lang/IDL/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/IDL \ No newline at end of file diff --git a/Lang/IDL/String-length b/Lang/IDL/String-length new file mode 120000 index 0000000000..b9ad16a5f7 --- /dev/null +++ b/Lang/IDL/String-length @@ -0,0 +1 @@ +../../Task/String-length/IDL \ No newline at end of file diff --git a/Lang/IDL/Sum-and-product-of-an-array b/Lang/IDL/Sum-and-product-of-an-array new file mode 120000 index 0000000000..ca4606ba31 --- /dev/null +++ b/Lang/IDL/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/IDL \ No newline at end of file diff --git a/Lang/IDL/Sum-of-a-series b/Lang/IDL/Sum-of-a-series new file mode 120000 index 0000000000..70dadcbed2 --- /dev/null +++ b/Lang/IDL/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/IDL \ No newline at end of file diff --git a/Lang/IDL/Sum-of-squares b/Lang/IDL/Sum-of-squares new file mode 120000 index 0000000000..41c37bd0c6 --- /dev/null +++ b/Lang/IDL/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/IDL \ No newline at end of file diff --git a/Lang/IDL/Trigonometric-functions b/Lang/IDL/Trigonometric-functions new file mode 120000 index 0000000000..59d0c9428a --- /dev/null +++ b/Lang/IDL/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/IDL \ No newline at end of file diff --git a/Lang/IDL/Variable-size-Get b/Lang/IDL/Variable-size-Get new file mode 120000 index 0000000000..6688e732c8 --- /dev/null +++ b/Lang/IDL/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/IDL \ No newline at end of file diff --git a/Lang/IDL/Walk-a-directory-Non-recursively b/Lang/IDL/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..67157828be --- /dev/null +++ b/Lang/IDL/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/IDL \ No newline at end of file diff --git a/Lang/IDL/Walk-a-directory-Recursively b/Lang/IDL/Walk-a-directory-Recursively new file mode 120000 index 0000000000..67ed512ab7 --- /dev/null +++ b/Lang/IDL/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/IDL \ No newline at end of file diff --git a/Lang/IDL/Window-creation b/Lang/IDL/Window-creation new file mode 120000 index 0000000000..8c36d75ea4 --- /dev/null +++ b/Lang/IDL/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/IDL \ No newline at end of file diff --git a/Lang/IDL/Write-float-arrays-to-a-text-file b/Lang/IDL/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..6260c219ef --- /dev/null +++ b/Lang/IDL/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/IDL \ No newline at end of file diff --git a/Lang/Icon/Seven-sided-dice-from-five-sided-dice b/Lang/Icon/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..cf1624fdb2 --- /dev/null +++ b/Lang/Icon/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Icon \ No newline at end of file diff --git a/Lang/Icon/Short-circuit-evaluation b/Lang/Icon/Short-circuit-evaluation new file mode 120000 index 0000000000..f80cbd0cd5 --- /dev/null +++ b/Lang/Icon/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Icon \ No newline at end of file diff --git a/Lang/Icon/Show-the-epoch b/Lang/Icon/Show-the-epoch new file mode 120000 index 0000000000..914b4ba595 --- /dev/null +++ b/Lang/Icon/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Icon \ No newline at end of file diff --git a/Lang/Icon/Sierpinski-carpet b/Lang/Icon/Sierpinski-carpet new file mode 120000 index 0000000000..27fa87223d --- /dev/null +++ b/Lang/Icon/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Icon \ No newline at end of file diff --git a/Lang/Icon/Sierpinski-triangle b/Lang/Icon/Sierpinski-triangle new file mode 120000 index 0000000000..1d3152739d --- /dev/null +++ b/Lang/Icon/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Icon \ No newline at end of file diff --git a/Lang/Icon/Sierpinski-triangle-Graphical b/Lang/Icon/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..8e2a4dba42 --- /dev/null +++ b/Lang/Icon/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Icon \ No newline at end of file diff --git a/Lang/Icon/Sieve-of-Eratosthenes b/Lang/Icon/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d9f427f102 --- /dev/null +++ b/Lang/Icon/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Icon \ No newline at end of file diff --git a/Lang/Icon/Singly-linked-list-Traversal b/Lang/Icon/Singly-linked-list-Traversal new file mode 120000 index 0000000000..6e0aa3fb3e --- /dev/null +++ b/Lang/Icon/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Icon \ No newline at end of file diff --git a/Lang/Icon/Sleep b/Lang/Icon/Sleep new file mode 120000 index 0000000000..ce4620cc62 --- /dev/null +++ b/Lang/Icon/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-an-array-of-composite-structures b/Lang/Icon/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..5c000f4068 --- /dev/null +++ b/Lang/Icon/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-an-integer-array b/Lang/Icon/Sort-an-integer-array new file mode 120000 index 0000000000..a0c771c3d6 --- /dev/null +++ b/Lang/Icon/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-disjoint-sublist b/Lang/Icon/Sort-disjoint-sublist new file mode 120000 index 0000000000..b09d7407a9 --- /dev/null +++ b/Lang/Icon/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-using-a-custom-comparator b/Lang/Icon/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..c3eff434bd --- /dev/null +++ b/Lang/Icon/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Bead-sort b/Lang/Icon/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..d9d42fff82 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Bogosort b/Lang/Icon/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..622a1fd73a --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Bubble-sort b/Lang/Icon/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..3a05c0c3b5 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Cocktail-sort b/Lang/Icon/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..3d4dfc594e --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Comb-sort b/Lang/Icon/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..bf8feef803 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Counting-sort b/Lang/Icon/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..893d309a99 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Gnome-sort b/Lang/Icon/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..f0530e80be --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Heapsort b/Lang/Icon/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..5ca37964da --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Insertion-sort b/Lang/Icon/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..414c6ebd90 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Merge-sort b/Lang/Icon/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..24d75e9865 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Pancake-sort b/Lang/Icon/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..cccedd16e9 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Permutation-sort b/Lang/Icon/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..f468a6faa6 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Quicksort b/Lang/Icon/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..44bf9b4592 --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Selection-sort b/Lang/Icon/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..94e82fe7cc --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Shell-sort b/Lang/Icon/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..01207212db --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Sorting-algorithms-Stooge-sort b/Lang/Icon/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..eb7ecb15fe --- /dev/null +++ b/Lang/Icon/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Icon \ No newline at end of file diff --git a/Lang/Icon/Soundex b/Lang/Icon/Soundex new file mode 120000 index 0000000000..d79a47cf76 --- /dev/null +++ b/Lang/Icon/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Icon \ No newline at end of file diff --git a/Lang/Icon/Special-variables b/Lang/Icon/Special-variables new file mode 120000 index 0000000000..8ecee224a7 --- /dev/null +++ b/Lang/Icon/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Icon \ No newline at end of file diff --git a/Lang/Icon/Spiral-matrix b/Lang/Icon/Spiral-matrix new file mode 120000 index 0000000000..4af202c86d --- /dev/null +++ b/Lang/Icon/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Icon \ No newline at end of file diff --git a/Lang/Icon/Stable-marriage-problem b/Lang/Icon/Stable-marriage-problem new file mode 120000 index 0000000000..e9982b09d7 --- /dev/null +++ b/Lang/Icon/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Stack b/Lang/Icon/Stack new file mode 120000 index 0000000000..3049ec866f --- /dev/null +++ b/Lang/Icon/Stack @@ -0,0 +1 @@ +../../Task/Stack/Icon \ No newline at end of file diff --git a/Lang/Icon/Stair-climbing-puzzle b/Lang/Icon/Stair-climbing-puzzle new file mode 120000 index 0000000000..1bdb994884 --- /dev/null +++ b/Lang/Icon/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Icon \ No newline at end of file diff --git a/Lang/Icon/Standard-deviation b/Lang/Icon/Standard-deviation new file mode 120000 index 0000000000..ca6327a6d5 --- /dev/null +++ b/Lang/Icon/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Icon \ No newline at end of file diff --git a/Lang/Icon/Stem-and-leaf-plot b/Lang/Icon/Stem-and-leaf-plot new file mode 120000 index 0000000000..168a5383d7 --- /dev/null +++ b/Lang/Icon/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Icon \ No newline at end of file diff --git a/Lang/Icon/String-case b/Lang/Icon/String-case new file mode 120000 index 0000000000..3b191646c6 --- /dev/null +++ b/Lang/Icon/String-case @@ -0,0 +1 @@ +../../Task/String-case/Icon \ No newline at end of file diff --git a/Lang/Icon/String-concatenation b/Lang/Icon/String-concatenation new file mode 120000 index 0000000000..b1994e5056 --- /dev/null +++ b/Lang/Icon/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Icon \ No newline at end of file diff --git a/Lang/Icon/String-interpolation--included- b/Lang/Icon/String-interpolation--included- new file mode 120000 index 0000000000..6f0cb91ea6 --- /dev/null +++ b/Lang/Icon/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Icon \ No newline at end of file diff --git a/Lang/Icon/String-length b/Lang/Icon/String-length new file mode 120000 index 0000000000..19eca4b079 --- /dev/null +++ b/Lang/Icon/String-length @@ -0,0 +1 @@ +../../Task/String-length/Icon \ No newline at end of file diff --git a/Lang/Icon/Strip-a-set-of-characters-from-a-string b/Lang/Icon/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..ec1aae7c9a --- /dev/null +++ b/Lang/Icon/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Strip-block-comments b/Lang/Icon/Strip-block-comments new file mode 120000 index 0000000000..3eb6a5ce99 --- /dev/null +++ b/Lang/Icon/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Icon \ No newline at end of file diff --git a/Lang/Icon/Strip-comments-from-a-string b/Lang/Icon/Strip-comments-from-a-string new file mode 120000 index 0000000000..dcf73221db --- /dev/null +++ b/Lang/Icon/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Icon/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..18fc9675ab --- /dev/null +++ b/Lang/Icon/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Icon/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ae8906a402 --- /dev/null +++ b/Lang/Icon/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Icon \ No newline at end of file diff --git a/Lang/Icon/Substring b/Lang/Icon/Substring new file mode 120000 index 0000000000..3c8f939885 --- /dev/null +++ b/Lang/Icon/Substring @@ -0,0 +1 @@ +../../Task/Substring/Icon \ No newline at end of file diff --git a/Lang/Icon/Substring-Top-and-tail b/Lang/Icon/Substring-Top-and-tail new file mode 120000 index 0000000000..26edf47e51 --- /dev/null +++ b/Lang/Icon/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Icon \ No newline at end of file diff --git a/Lang/Icon/Subtractive-generator b/Lang/Icon/Subtractive-generator new file mode 120000 index 0000000000..b2b52aaa38 --- /dev/null +++ b/Lang/Icon/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Icon \ No newline at end of file diff --git a/Lang/Icon/Sum-and-product-of-an-array b/Lang/Icon/Sum-and-product-of-an-array new file mode 120000 index 0000000000..eea88eb8d8 --- /dev/null +++ b/Lang/Icon/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Icon \ No newline at end of file diff --git a/Lang/Icon/Sum-of-a-series b/Lang/Icon/Sum-of-a-series new file mode 120000 index 0000000000..1de8dba912 --- /dev/null +++ b/Lang/Icon/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Icon \ No newline at end of file diff --git a/Lang/Icon/Sum-of-squares b/Lang/Icon/Sum-of-squares new file mode 120000 index 0000000000..952c0c74cd --- /dev/null +++ b/Lang/Icon/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Icon \ No newline at end of file diff --git a/Lang/Icon/Symmetric-difference b/Lang/Icon/Symmetric-difference new file mode 120000 index 0000000000..1847ec9c61 --- /dev/null +++ b/Lang/Icon/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Icon \ No newline at end of file diff --git a/Lang/Icon/Synchronous-concurrency b/Lang/Icon/Synchronous-concurrency new file mode 120000 index 0000000000..8f56e9912a --- /dev/null +++ b/Lang/Icon/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Icon \ No newline at end of file diff --git a/Lang/Icon/System-time b/Lang/Icon/System-time new file mode 120000 index 0000000000..f05d9632a1 --- /dev/null +++ b/Lang/Icon/System-time @@ -0,0 +1 @@ +../../Task/System-time/Icon \ No newline at end of file diff --git a/Lang/Icon/Take-notes-on-the-command-line b/Lang/Icon/Take-notes-on-the-command-line new file mode 120000 index 0000000000..43afed7564 --- /dev/null +++ b/Lang/Icon/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Icon \ No newline at end of file diff --git a/Lang/Icon/Terminal-control-Clear-the-screen b/Lang/Icon/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..53a47922da --- /dev/null +++ b/Lang/Icon/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Icon \ No newline at end of file diff --git a/Lang/Icon/Terminal-control-Display-an-extended-character b/Lang/Icon/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..378098ae90 --- /dev/null +++ b/Lang/Icon/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Icon \ No newline at end of file diff --git a/Lang/Icon/Terminal-control-Ringing-the-terminal-bell b/Lang/Icon/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..4e4eaf2044 --- /dev/null +++ b/Lang/Icon/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Icon \ No newline at end of file diff --git a/Lang/Icon/Ternary-logic b/Lang/Icon/Ternary-logic new file mode 120000 index 0000000000..ec00bf6767 --- /dev/null +++ b/Lang/Icon/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Icon \ No newline at end of file diff --git a/Lang/Icon/Text-processing-1 b/Lang/Icon/Text-processing-1 new file mode 120000 index 0000000000..be1d28db8f --- /dev/null +++ b/Lang/Icon/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Icon \ No newline at end of file diff --git a/Lang/Icon/Text-processing-Max-licenses-in-use b/Lang/Icon/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..24aadbcd38 --- /dev/null +++ b/Lang/Icon/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Icon \ No newline at end of file diff --git a/Lang/Icon/Tic-tac-toe b/Lang/Icon/Tic-tac-toe new file mode 120000 index 0000000000..88e9b2d10b --- /dev/null +++ b/Lang/Icon/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Icon \ No newline at end of file diff --git a/Lang/Icon/Time-a-function b/Lang/Icon/Time-a-function new file mode 120000 index 0000000000..f73194a74b --- /dev/null +++ b/Lang/Icon/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Tokenize-a-string b/Lang/Icon/Tokenize-a-string new file mode 120000 index 0000000000..d7aa38fc0e --- /dev/null +++ b/Lang/Icon/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Icon \ No newline at end of file diff --git a/Lang/Icon/Top-rank-per-group b/Lang/Icon/Top-rank-per-group new file mode 120000 index 0000000000..bffb672291 --- /dev/null +++ b/Lang/Icon/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Icon \ No newline at end of file diff --git a/Lang/Icon/Towers-of-Hanoi b/Lang/Icon/Towers-of-Hanoi new file mode 120000 index 0000000000..41f87e7e93 --- /dev/null +++ b/Lang/Icon/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Icon \ No newline at end of file diff --git a/Lang/Icon/Tree-traversal b/Lang/Icon/Tree-traversal new file mode 120000 index 0000000000..912c169909 --- /dev/null +++ b/Lang/Icon/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Icon \ No newline at end of file diff --git a/Lang/Icon/Truncate-a-file b/Lang/Icon/Truncate-a-file new file mode 120000 index 0000000000..734475b0c8 --- /dev/null +++ b/Lang/Icon/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Icon \ No newline at end of file diff --git a/Lang/Icon/URL-decoding b/Lang/Icon/URL-decoding new file mode 120000 index 0000000000..33d84c2b31 --- /dev/null +++ b/Lang/Icon/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Icon \ No newline at end of file diff --git a/Lang/Icon/URL-encoding b/Lang/Icon/URL-encoding new file mode 120000 index 0000000000..bbf827f8d0 --- /dev/null +++ b/Lang/Icon/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Icon \ No newline at end of file diff --git a/Lang/Icon/Unbias-a-random-generator b/Lang/Icon/Unbias-a-random-generator new file mode 120000 index 0000000000..4f7f07b8e2 --- /dev/null +++ b/Lang/Icon/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Icon \ No newline at end of file diff --git a/Lang/Icon/User-input-Graphical b/Lang/Icon/User-input-Graphical new file mode 120000 index 0000000000..8e60f8fc2b --- /dev/null +++ b/Lang/Icon/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Icon \ No newline at end of file diff --git a/Lang/Icon/User-input-Text b/Lang/Icon/User-input-Text new file mode 120000 index 0000000000..a9ccdc4468 --- /dev/null +++ b/Lang/Icon/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Icon \ No newline at end of file diff --git a/Lang/Icon/Van-der-Corput-sequence b/Lang/Icon/Van-der-Corput-sequence new file mode 120000 index 0000000000..431302f4b5 --- /dev/null +++ b/Lang/Icon/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Icon \ No newline at end of file diff --git a/Lang/Icon/Variable-length-quantity b/Lang/Icon/Variable-length-quantity new file mode 120000 index 0000000000..bd9b62872f --- /dev/null +++ b/Lang/Icon/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Icon \ No newline at end of file diff --git a/Lang/Icon/Variable-size-Get b/Lang/Icon/Variable-size-Get new file mode 120000 index 0000000000..97f68ec739 --- /dev/null +++ b/Lang/Icon/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Icon \ No newline at end of file diff --git a/Lang/Icon/Variable-size-Set b/Lang/Icon/Variable-size-Set new file mode 120000 index 0000000000..a052c51b08 --- /dev/null +++ b/Lang/Icon/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Icon \ No newline at end of file diff --git a/Lang/Icon/Variadic-function b/Lang/Icon/Variadic-function new file mode 120000 index 0000000000..4614991a53 --- /dev/null +++ b/Lang/Icon/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Vector-products b/Lang/Icon/Vector-products new file mode 120000 index 0000000000..003c000abe --- /dev/null +++ b/Lang/Icon/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Icon \ No newline at end of file diff --git a/Lang/Icon/Verify-distribution-uniformity-Naive b/Lang/Icon/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..b46d497ca0 --- /dev/null +++ b/Lang/Icon/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Icon \ No newline at end of file diff --git a/Lang/Icon/Vigen-re-cipher b/Lang/Icon/Vigen-re-cipher new file mode 120000 index 0000000000..65bdfc5fa2 --- /dev/null +++ b/Lang/Icon/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Icon \ No newline at end of file diff --git a/Lang/Icon/Voronoi-diagram b/Lang/Icon/Voronoi-diagram new file mode 120000 index 0000000000..5f3f75922c --- /dev/null +++ b/Lang/Icon/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Icon \ No newline at end of file diff --git a/Lang/Icon/Walk-a-directory-Non-recursively b/Lang/Icon/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..324faff970 --- /dev/null +++ b/Lang/Icon/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Icon \ No newline at end of file diff --git a/Lang/Icon/Window-creation-X11 b/Lang/Icon/Window-creation-X11 new file mode 120000 index 0000000000..d6c9585ddf --- /dev/null +++ b/Lang/Icon/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Icon \ No newline at end of file diff --git a/Lang/Icon/Window-management b/Lang/Icon/Window-management new file mode 120000 index 0000000000..e4b5705b22 --- /dev/null +++ b/Lang/Icon/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Icon \ No newline at end of file diff --git a/Lang/Icon/Wireworld b/Lang/Icon/Wireworld new file mode 120000 index 0000000000..b4b4473d06 --- /dev/null +++ b/Lang/Icon/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Icon \ No newline at end of file diff --git a/Lang/Icon/Write-language-name-in-3D-ASCII b/Lang/Icon/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..ed2223f4e8 --- /dev/null +++ b/Lang/Icon/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Icon \ No newline at end of file diff --git a/Lang/Icon/Yin-and-yang b/Lang/Icon/Yin-and-yang new file mode 120000 index 0000000000..2927a08227 --- /dev/null +++ b/Lang/Icon/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Icon \ No newline at end of file diff --git a/Lang/Icon/Zig-zag-matrix b/Lang/Icon/Zig-zag-matrix new file mode 120000 index 0000000000..5554260424 --- /dev/null +++ b/Lang/Icon/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Icon \ No newline at end of file diff --git a/Lang/Inform-6/Sorting-algorithms-Bogosort b/Lang/Inform-6/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..5ee60f1fbb --- /dev/null +++ b/Lang/Inform-6/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Inform-6 \ No newline at end of file diff --git a/Lang/Inform-7/Sort-an-integer-array b/Lang/Inform-7/Sort-an-integer-array new file mode 120000 index 0000000000..7206fe33f0 --- /dev/null +++ b/Lang/Inform-7/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Inform-7 \ No newline at end of file diff --git a/Lang/Inform-7/Strip-comments-from-a-string b/Lang/Inform-7/Strip-comments-from-a-string new file mode 120000 index 0000000000..b4b0b6c62c --- /dev/null +++ b/Lang/Inform-7/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Inform-7 \ No newline at end of file diff --git a/Lang/Inform-7/Sum-and-product-of-an-array b/Lang/Inform-7/Sum-and-product-of-an-array new file mode 120000 index 0000000000..76d5390192 --- /dev/null +++ b/Lang/Inform-7/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Inform-7 \ No newline at end of file diff --git a/Lang/Inform-7/Sum-of-squares b/Lang/Inform-7/Sum-of-squares new file mode 120000 index 0000000000..3021ae42e9 --- /dev/null +++ b/Lang/Inform-7/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Inform-7 \ No newline at end of file diff --git a/Lang/Inform-7/Towers-of-Hanoi b/Lang/Inform-7/Towers-of-Hanoi new file mode 120000 index 0000000000..674a753ef4 --- /dev/null +++ b/Lang/Inform-7/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Inform-7 \ No newline at end of file diff --git a/Lang/Io/Singleton b/Lang/Io/Singleton new file mode 120000 index 0000000000..79e4b70de7 --- /dev/null +++ b/Lang/Io/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Io \ No newline at end of file diff --git a/Lang/Io/Sort-an-integer-array b/Lang/Io/Sort-an-integer-array new file mode 120000 index 0000000000..642e0a6a5a --- /dev/null +++ b/Lang/Io/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Bogosort b/Lang/Io/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..cddef05bcd --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Bubble-sort b/Lang/Io/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1dc40014bd --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Cocktail-sort b/Lang/Io/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..8a247f15a6 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Comb-sort b/Lang/Io/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..99ca0f8ae9 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Counting-sort b/Lang/Io/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..059c858a16 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Gnome-sort b/Lang/Io/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..bc9ef5709e --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Insertion-sort b/Lang/Io/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..0eedc221bf --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Merge-sort b/Lang/Io/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..39bfd9cd02 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Quicksort b/Lang/Io/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..78c95d9036 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Selection-sort b/Lang/Io/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..9093694aa1 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Io \ No newline at end of file diff --git a/Lang/Io/Sorting-algorithms-Shell-sort b/Lang/Io/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..613b3623a5 --- /dev/null +++ b/Lang/Io/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Io \ No newline at end of file diff --git a/Lang/Io/Stack b/Lang/Io/Stack new file mode 120000 index 0000000000..60ef7d350b --- /dev/null +++ b/Lang/Io/Stack @@ -0,0 +1 @@ +../../Task/Stack/Io \ No newline at end of file diff --git a/Lang/Io/String-length b/Lang/Io/String-length new file mode 120000 index 0000000000..bb3fe3e9ec --- /dev/null +++ b/Lang/Io/String-length @@ -0,0 +1 @@ +../../Task/String-length/Io \ No newline at end of file diff --git a/Lang/Io/Sum-of-squares b/Lang/Io/Sum-of-squares new file mode 120000 index 0000000000..dae58650ea --- /dev/null +++ b/Lang/Io/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Io \ No newline at end of file diff --git a/Lang/Io/System-time b/Lang/Io/System-time new file mode 120000 index 0000000000..f92fe9dfe1 --- /dev/null +++ b/Lang/Io/System-time @@ -0,0 +1 @@ +../../Task/System-time/Io \ No newline at end of file diff --git a/Lang/Io/Tokenize-a-string b/Lang/Io/Tokenize-a-string new file mode 120000 index 0000000000..b0f90115b7 --- /dev/null +++ b/Lang/Io/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Io \ No newline at end of file diff --git a/Lang/Io/Towers-of-Hanoi b/Lang/Io/Towers-of-Hanoi new file mode 120000 index 0000000000..0246ade1dd --- /dev/null +++ b/Lang/Io/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Io \ No newline at end of file diff --git a/Lang/Io/Trabb-Pardo-Knuth-algorithm b/Lang/Io/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..aaec77bf17 --- /dev/null +++ b/Lang/Io/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Io \ No newline at end of file diff --git a/Lang/Io/User-input-Text b/Lang/Io/User-input-Text new file mode 120000 index 0000000000..47ba05b009 --- /dev/null +++ b/Lang/Io/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Io \ No newline at end of file diff --git a/Lang/Io/Variadic-function b/Lang/Io/Variadic-function new file mode 120000 index 0000000000..fe39b6c421 --- /dev/null +++ b/Lang/Io/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Io \ No newline at end of file diff --git a/Lang/Ioke/Stack b/Lang/Ioke/Stack new file mode 120000 index 0000000000..25839e9897 --- /dev/null +++ b/Lang/Ioke/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ioke \ No newline at end of file diff --git a/Lang/Ioke/Time-a-function b/Lang/Ioke/Time-a-function new file mode 120000 index 0000000000..84e0add7ec --- /dev/null +++ b/Lang/Ioke/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Ioke \ No newline at end of file diff --git a/Lang/Ioke/Towers-of-Hanoi b/Lang/Ioke/Towers-of-Hanoi new file mode 120000 index 0000000000..5e0605c9ca --- /dev/null +++ b/Lang/Ioke/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ioke \ No newline at end of file diff --git a/Lang/J/Set-puzzle b/Lang/J/Set-puzzle new file mode 120000 index 0000000000..499896574d --- /dev/null +++ b/Lang/J/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/J \ No newline at end of file diff --git a/Lang/J/Seven-sided-dice-from-five-sided-dice b/Lang/J/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..bd864b7c12 --- /dev/null +++ b/Lang/J/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/J \ No newline at end of file diff --git a/Lang/J/Shell-one-liner b/Lang/J/Shell-one-liner new file mode 120000 index 0000000000..c4736aa1f1 --- /dev/null +++ b/Lang/J/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/J \ No newline at end of file diff --git a/Lang/J/Short-circuit-evaluation b/Lang/J/Short-circuit-evaluation new file mode 120000 index 0000000000..be215b2790 --- /dev/null +++ b/Lang/J/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/J \ No newline at end of file diff --git a/Lang/J/Show-the-epoch b/Lang/J/Show-the-epoch new file mode 120000 index 0000000000..94eed511aa --- /dev/null +++ b/Lang/J/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/J \ No newline at end of file diff --git a/Lang/J/Sierpinski-carpet b/Lang/J/Sierpinski-carpet new file mode 120000 index 0000000000..e8fb1988cc --- /dev/null +++ b/Lang/J/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/J \ No newline at end of file diff --git a/Lang/J/Sierpinski-triangle b/Lang/J/Sierpinski-triangle new file mode 120000 index 0000000000..8dff6f47c3 --- /dev/null +++ b/Lang/J/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/J \ No newline at end of file diff --git a/Lang/J/Sierpinski-triangle-Graphical b/Lang/J/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..63542d4ff3 --- /dev/null +++ b/Lang/J/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/J \ No newline at end of file diff --git a/Lang/J/Simple-database b/Lang/J/Simple-database new file mode 120000 index 0000000000..82ebcb44fe --- /dev/null +++ b/Lang/J/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/J \ No newline at end of file diff --git a/Lang/J/Simple-windowed-application b/Lang/J/Simple-windowed-application new file mode 120000 index 0000000000..5470728af9 --- /dev/null +++ b/Lang/J/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/J \ No newline at end of file diff --git a/Lang/J/Singly-linked-list-Element-definition b/Lang/J/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..32f0683b7d --- /dev/null +++ b/Lang/J/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/J \ No newline at end of file diff --git a/Lang/J/Singly-linked-list-Element-insertion b/Lang/J/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..d6fcd6facc --- /dev/null +++ b/Lang/J/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/J \ No newline at end of file diff --git a/Lang/J/Singly-linked-list-Traversal b/Lang/J/Singly-linked-list-Traversal new file mode 120000 index 0000000000..f0e3d4e095 --- /dev/null +++ b/Lang/J/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/J \ No newline at end of file diff --git a/Lang/J/Sleep b/Lang/J/Sleep new file mode 120000 index 0000000000..fefb84f85f --- /dev/null +++ b/Lang/J/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/J \ No newline at end of file diff --git a/Lang/J/Sockets b/Lang/J/Sockets new file mode 120000 index 0000000000..b7b768743f --- /dev/null +++ b/Lang/J/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/J \ No newline at end of file diff --git a/Lang/J/Sort-an-array-of-composite-structures b/Lang/J/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..6c6fa46975 --- /dev/null +++ b/Lang/J/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/J \ No newline at end of file diff --git a/Lang/J/Sort-an-integer-array b/Lang/J/Sort-an-integer-array new file mode 120000 index 0000000000..0071945729 --- /dev/null +++ b/Lang/J/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/J \ No newline at end of file diff --git a/Lang/J/Sort-disjoint-sublist b/Lang/J/Sort-disjoint-sublist new file mode 120000 index 0000000000..f15b73cfaa --- /dev/null +++ b/Lang/J/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/J \ No newline at end of file diff --git a/Lang/J/Sort-using-a-custom-comparator b/Lang/J/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..bf5b8c0777 --- /dev/null +++ b/Lang/J/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Bead-sort b/Lang/J/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..c4508a954b --- /dev/null +++ b/Lang/J/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Bogosort b/Lang/J/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..fa54be5f05 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Bubble-sort b/Lang/J/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..d54c1a18c9 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Cocktail-sort b/Lang/J/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..bcb14784af --- /dev/null +++ b/Lang/J/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Comb-sort b/Lang/J/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..7579f6abb3 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Counting-sort b/Lang/J/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..81a0813b4b --- /dev/null +++ b/Lang/J/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Gnome-sort b/Lang/J/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..028207f80c --- /dev/null +++ b/Lang/J/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Heapsort b/Lang/J/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..0accd71b4b --- /dev/null +++ b/Lang/J/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Insertion-sort b/Lang/J/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..20b53c5850 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Merge-sort b/Lang/J/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..37dc027821 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Pancake-sort b/Lang/J/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..03e4a192ef --- /dev/null +++ b/Lang/J/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Permutation-sort b/Lang/J/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..629a19cb34 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Quicksort b/Lang/J/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..2be83f046b --- /dev/null +++ b/Lang/J/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Radix-sort b/Lang/J/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..62661d93f9 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Selection-sort b/Lang/J/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..4d03f08356 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Shell-sort b/Lang/J/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..b07434134d --- /dev/null +++ b/Lang/J/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Stooge-sort b/Lang/J/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..8a30094ebe --- /dev/null +++ b/Lang/J/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/J \ No newline at end of file diff --git a/Lang/J/Sorting-algorithms-Strand-sort b/Lang/J/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..024b6e8a68 --- /dev/null +++ b/Lang/J/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/J \ No newline at end of file diff --git a/Lang/J/Soundex b/Lang/J/Soundex new file mode 120000 index 0000000000..6af575bd82 --- /dev/null +++ b/Lang/J/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/J \ No newline at end of file diff --git a/Lang/J/Special-characters b/Lang/J/Special-characters new file mode 120000 index 0000000000..537313e0ef --- /dev/null +++ b/Lang/J/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/J \ No newline at end of file diff --git a/Lang/J/Spiral-matrix b/Lang/J/Spiral-matrix new file mode 120000 index 0000000000..4701d5290f --- /dev/null +++ b/Lang/J/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/J \ No newline at end of file diff --git a/Lang/J/Stable-marriage-problem b/Lang/J/Stable-marriage-problem new file mode 120000 index 0000000000..622525f5f7 --- /dev/null +++ b/Lang/J/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/J \ No newline at end of file diff --git a/Lang/J/Stack b/Lang/J/Stack new file mode 120000 index 0000000000..dacb46e3f4 --- /dev/null +++ b/Lang/J/Stack @@ -0,0 +1 @@ +../../Task/Stack/J \ No newline at end of file diff --git a/Lang/J/Stack-traces b/Lang/J/Stack-traces new file mode 120000 index 0000000000..5af07e67e8 --- /dev/null +++ b/Lang/J/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/J \ No newline at end of file diff --git a/Lang/J/Stair-climbing-puzzle b/Lang/J/Stair-climbing-puzzle new file mode 120000 index 0000000000..e6b19c5b29 --- /dev/null +++ b/Lang/J/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/J \ No newline at end of file diff --git a/Lang/J/Standard-deviation b/Lang/J/Standard-deviation new file mode 120000 index 0000000000..49ea3ab5d4 --- /dev/null +++ b/Lang/J/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/J \ No newline at end of file diff --git a/Lang/J/Stem-and-leaf-plot b/Lang/J/Stem-and-leaf-plot new file mode 120000 index 0000000000..3ba045ffca --- /dev/null +++ b/Lang/J/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/J \ No newline at end of file diff --git a/Lang/J/String-case b/Lang/J/String-case new file mode 120000 index 0000000000..106d230612 --- /dev/null +++ b/Lang/J/String-case @@ -0,0 +1 @@ +../../Task/String-case/J \ No newline at end of file diff --git a/Lang/J/String-comparison b/Lang/J/String-comparison new file mode 120000 index 0000000000..57d12d83d7 --- /dev/null +++ b/Lang/J/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/J \ No newline at end of file diff --git a/Lang/J/String-concatenation b/Lang/J/String-concatenation new file mode 120000 index 0000000000..9f8d635064 --- /dev/null +++ b/Lang/J/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/J \ No newline at end of file diff --git a/Lang/J/String-interpolation--included- b/Lang/J/String-interpolation--included- new file mode 120000 index 0000000000..483e11f61f --- /dev/null +++ b/Lang/J/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/J \ No newline at end of file diff --git a/Lang/J/String-length b/Lang/J/String-length new file mode 120000 index 0000000000..eae6b4eb3f --- /dev/null +++ b/Lang/J/String-length @@ -0,0 +1 @@ +../../Task/String-length/J \ No newline at end of file diff --git a/Lang/J/Strip-a-set-of-characters-from-a-string b/Lang/J/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..3fa2c5e62a --- /dev/null +++ b/Lang/J/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/J \ No newline at end of file diff --git a/Lang/J/Strip-block-comments b/Lang/J/Strip-block-comments new file mode 120000 index 0000000000..e09cac6870 --- /dev/null +++ b/Lang/J/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/J \ No newline at end of file diff --git a/Lang/J/Strip-comments-from-a-string b/Lang/J/Strip-comments-from-a-string new file mode 120000 index 0000000000..67414cbccd --- /dev/null +++ b/Lang/J/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/J \ No newline at end of file diff --git a/Lang/J/Strip-control-codes-and-extended-characters-from-a-string b/Lang/J/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..8a116edf15 --- /dev/null +++ b/Lang/J/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/J \ No newline at end of file diff --git a/Lang/J/Strip-whitespace-from-a-string-Top-and-tail b/Lang/J/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..4762a4ef1c --- /dev/null +++ b/Lang/J/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/J \ No newline at end of file diff --git a/Lang/J/Substring b/Lang/J/Substring new file mode 120000 index 0000000000..7ba8ac212b --- /dev/null +++ b/Lang/J/Substring @@ -0,0 +1 @@ +../../Task/Substring/J \ No newline at end of file diff --git a/Lang/J/Substring-Top-and-tail b/Lang/J/Substring-Top-and-tail new file mode 120000 index 0000000000..374634d0fe --- /dev/null +++ b/Lang/J/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/J \ No newline at end of file diff --git a/Lang/J/Subtractive-generator b/Lang/J/Subtractive-generator new file mode 120000 index 0000000000..fc17ff784d --- /dev/null +++ b/Lang/J/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/J \ No newline at end of file diff --git a/Lang/J/Sum-and-product-of-an-array b/Lang/J/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9990f0dd7c --- /dev/null +++ b/Lang/J/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/J \ No newline at end of file diff --git a/Lang/J/Sum-digits-of-an-integer b/Lang/J/Sum-digits-of-an-integer new file mode 120000 index 0000000000..a26ce2e428 --- /dev/null +++ b/Lang/J/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/J \ No newline at end of file diff --git a/Lang/J/Sum-of-a-series b/Lang/J/Sum-of-a-series new file mode 120000 index 0000000000..f2fbdf79e2 --- /dev/null +++ b/Lang/J/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/J \ No newline at end of file diff --git a/Lang/J/Sum-of-squares b/Lang/J/Sum-of-squares new file mode 120000 index 0000000000..9acc20031a --- /dev/null +++ b/Lang/J/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/J \ No newline at end of file diff --git a/Lang/J/Sutherland-Hodgman-polygon-clipping b/Lang/J/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..240e778adc --- /dev/null +++ b/Lang/J/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/J \ No newline at end of file diff --git a/Lang/J/Symmetric-difference b/Lang/J/Symmetric-difference new file mode 120000 index 0000000000..4a6eb06dc1 --- /dev/null +++ b/Lang/J/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/J \ No newline at end of file diff --git a/Lang/J/System-time b/Lang/J/System-time new file mode 120000 index 0000000000..636af92485 --- /dev/null +++ b/Lang/J/System-time @@ -0,0 +1 @@ +../../Task/System-time/J \ No newline at end of file diff --git a/Lang/J/Table-creation-Postal-addresses b/Lang/J/Table-creation-Postal-addresses new file mode 120000 index 0000000000..c6322a5434 --- /dev/null +++ b/Lang/J/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/J \ No newline at end of file diff --git a/Lang/J/Take-notes-on-the-command-line b/Lang/J/Take-notes-on-the-command-line new file mode 120000 index 0000000000..795936a2d9 --- /dev/null +++ b/Lang/J/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/J \ No newline at end of file diff --git a/Lang/J/Temperature-conversion b/Lang/J/Temperature-conversion new file mode 120000 index 0000000000..3d723ae5fc --- /dev/null +++ b/Lang/J/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Clear-the-screen b/Lang/J/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..751f55894b --- /dev/null +++ b/Lang/J/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Coloured-text b/Lang/J/Terminal-control-Coloured-text new file mode 120000 index 0000000000..f5b142cd6a --- /dev/null +++ b/Lang/J/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Cursor-positioning b/Lang/J/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..a6680de929 --- /dev/null +++ b/Lang/J/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Dimensions b/Lang/J/Terminal-control-Dimensions new file mode 120000 index 0000000000..3d08cd3f58 --- /dev/null +++ b/Lang/J/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Display-an-extended-character b/Lang/J/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..e0a133be22 --- /dev/null +++ b/Lang/J/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Hiding-the-cursor b/Lang/J/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..9907f810ef --- /dev/null +++ b/Lang/J/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Inverse-video b/Lang/J/Terminal-control-Inverse-video new file mode 120000 index 0000000000..89fd29d413 --- /dev/null +++ b/Lang/J/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/J \ No newline at end of file diff --git a/Lang/J/Terminal-control-Ringing-the-terminal-bell b/Lang/J/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..d5de77930a --- /dev/null +++ b/Lang/J/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/J \ No newline at end of file diff --git a/Lang/J/Ternary-logic b/Lang/J/Ternary-logic new file mode 120000 index 0000000000..cc2510b939 --- /dev/null +++ b/Lang/J/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/J \ No newline at end of file diff --git a/Lang/J/Test-a-function b/Lang/J/Test-a-function new file mode 120000 index 0000000000..87ac72de5b --- /dev/null +++ b/Lang/J/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/J \ No newline at end of file diff --git a/Lang/J/Text-processing-1 b/Lang/J/Text-processing-1 new file mode 120000 index 0000000000..7b54b541d8 --- /dev/null +++ b/Lang/J/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/J \ No newline at end of file diff --git a/Lang/J/Text-processing-2 b/Lang/J/Text-processing-2 new file mode 120000 index 0000000000..fe87e61cd0 --- /dev/null +++ b/Lang/J/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/J \ No newline at end of file diff --git a/Lang/J/Thieles-interpolation-formula b/Lang/J/Thieles-interpolation-formula new file mode 120000 index 0000000000..007850d942 --- /dev/null +++ b/Lang/J/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/J \ No newline at end of file diff --git a/Lang/J/Tic-tac-toe b/Lang/J/Tic-tac-toe new file mode 120000 index 0000000000..3e0097ccb4 --- /dev/null +++ b/Lang/J/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/J \ No newline at end of file diff --git a/Lang/J/Time-a-function b/Lang/J/Time-a-function new file mode 120000 index 0000000000..628782c2e3 --- /dev/null +++ b/Lang/J/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/J \ No newline at end of file diff --git a/Lang/J/Tokenize-a-string b/Lang/J/Tokenize-a-string new file mode 120000 index 0000000000..ebf060ab76 --- /dev/null +++ b/Lang/J/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/J \ No newline at end of file diff --git a/Lang/J/Top-rank-per-group b/Lang/J/Top-rank-per-group new file mode 120000 index 0000000000..26322a4ce4 --- /dev/null +++ b/Lang/J/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/J \ No newline at end of file diff --git a/Lang/J/Topic-variable b/Lang/J/Topic-variable new file mode 120000 index 0000000000..27d08f6592 --- /dev/null +++ b/Lang/J/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/J \ No newline at end of file diff --git a/Lang/J/Topological-sort b/Lang/J/Topological-sort new file mode 120000 index 0000000000..746c15fb3d --- /dev/null +++ b/Lang/J/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/J \ No newline at end of file diff --git a/Lang/J/Topswops b/Lang/J/Topswops new file mode 120000 index 0000000000..ca87e281d6 --- /dev/null +++ b/Lang/J/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/J \ No newline at end of file diff --git a/Lang/J/Towers-of-Hanoi b/Lang/J/Towers-of-Hanoi new file mode 120000 index 0000000000..7207b92b1b --- /dev/null +++ b/Lang/J/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/J \ No newline at end of file diff --git a/Lang/J/Trabb-Pardo-Knuth-algorithm b/Lang/J/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..0deb7394c0 --- /dev/null +++ b/Lang/J/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/J \ No newline at end of file diff --git a/Lang/J/Tree-traversal b/Lang/J/Tree-traversal new file mode 120000 index 0000000000..fff4911563 --- /dev/null +++ b/Lang/J/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/J \ No newline at end of file diff --git a/Lang/J/Trigonometric-functions b/Lang/J/Trigonometric-functions new file mode 120000 index 0000000000..c2fd3f2f18 --- /dev/null +++ b/Lang/J/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/J \ No newline at end of file diff --git a/Lang/J/Truncate-a-file b/Lang/J/Truncate-a-file new file mode 120000 index 0000000000..d224e4a240 --- /dev/null +++ b/Lang/J/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/J \ No newline at end of file diff --git a/Lang/J/Twelve-statements b/Lang/J/Twelve-statements new file mode 120000 index 0000000000..ccadb1e59d --- /dev/null +++ b/Lang/J/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/J \ No newline at end of file diff --git a/Lang/J/URL-decoding b/Lang/J/URL-decoding new file mode 120000 index 0000000000..f38a2f0f13 --- /dev/null +++ b/Lang/J/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/J \ No newline at end of file diff --git a/Lang/J/URL-encoding b/Lang/J/URL-encoding new file mode 120000 index 0000000000..e61150a934 --- /dev/null +++ b/Lang/J/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/J \ No newline at end of file diff --git a/Lang/J/Unbias-a-random-generator b/Lang/J/Unbias-a-random-generator new file mode 120000 index 0000000000..afd20099d8 --- /dev/null +++ b/Lang/J/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/J \ No newline at end of file diff --git a/Lang/J/Undefined-values b/Lang/J/Undefined-values new file mode 120000 index 0000000000..c44e5e9734 --- /dev/null +++ b/Lang/J/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/J \ No newline at end of file diff --git a/Lang/J/Unicode-strings b/Lang/J/Unicode-strings new file mode 120000 index 0000000000..4521bea447 --- /dev/null +++ b/Lang/J/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/J \ No newline at end of file diff --git a/Lang/J/Update-a-configuration-file b/Lang/J/Update-a-configuration-file new file mode 120000 index 0000000000..fa29cbb205 --- /dev/null +++ b/Lang/J/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/J \ No newline at end of file diff --git a/Lang/J/Use-another-language-to-call-a-function b/Lang/J/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..d17ec84c30 --- /dev/null +++ b/Lang/J/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/J \ No newline at end of file diff --git a/Lang/J/User-input-Graphical b/Lang/J/User-input-Graphical new file mode 120000 index 0000000000..cb68df7d47 --- /dev/null +++ b/Lang/J/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/J \ No newline at end of file diff --git a/Lang/J/User-input-Text b/Lang/J/User-input-Text new file mode 120000 index 0000000000..c1e054fc8e --- /dev/null +++ b/Lang/J/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/J \ No newline at end of file diff --git a/Lang/J/Van-der-Corput-sequence b/Lang/J/Van-der-Corput-sequence new file mode 120000 index 0000000000..14896e695b --- /dev/null +++ b/Lang/J/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/J \ No newline at end of file diff --git a/Lang/J/Variable-length-quantity b/Lang/J/Variable-length-quantity new file mode 120000 index 0000000000..1aca551138 --- /dev/null +++ b/Lang/J/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/J \ No newline at end of file diff --git a/Lang/J/Variable-size-Get b/Lang/J/Variable-size-Get new file mode 120000 index 0000000000..4cad4ac773 --- /dev/null +++ b/Lang/J/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/J \ No newline at end of file diff --git a/Lang/J/Variable-size-Set b/Lang/J/Variable-size-Set new file mode 120000 index 0000000000..c40a6e9106 --- /dev/null +++ b/Lang/J/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/J \ No newline at end of file diff --git a/Lang/J/Variables b/Lang/J/Variables new file mode 120000 index 0000000000..2497aa34d7 --- /dev/null +++ b/Lang/J/Variables @@ -0,0 +1 @@ +../../Task/Variables/J \ No newline at end of file diff --git a/Lang/J/Variadic-function b/Lang/J/Variadic-function new file mode 120000 index 0000000000..32eeaad052 --- /dev/null +++ b/Lang/J/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/J \ No newline at end of file diff --git a/Lang/J/Vector-products b/Lang/J/Vector-products new file mode 120000 index 0000000000..69ddcf5afb --- /dev/null +++ b/Lang/J/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/J \ No newline at end of file diff --git a/Lang/J/Verify-distribution-uniformity-Chi-squared-test b/Lang/J/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..365c3e8ecd --- /dev/null +++ b/Lang/J/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/J \ No newline at end of file diff --git a/Lang/J/Verify-distribution-uniformity-Naive b/Lang/J/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..d1bad7dcc0 --- /dev/null +++ b/Lang/J/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/J \ No newline at end of file diff --git a/Lang/J/Vigen-re-cipher b/Lang/J/Vigen-re-cipher new file mode 120000 index 0000000000..2d13a4aab8 --- /dev/null +++ b/Lang/J/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/J \ No newline at end of file diff --git a/Lang/J/Voronoi-diagram b/Lang/J/Voronoi-diagram new file mode 120000 index 0000000000..3eb3404ca4 --- /dev/null +++ b/Lang/J/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/J \ No newline at end of file diff --git a/Lang/J/Walk-a-directory-Non-recursively b/Lang/J/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..3467978b99 --- /dev/null +++ b/Lang/J/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/J \ No newline at end of file diff --git a/Lang/J/Walk-a-directory-Recursively b/Lang/J/Walk-a-directory-Recursively new file mode 120000 index 0000000000..9b32485cd1 --- /dev/null +++ b/Lang/J/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/J \ No newline at end of file diff --git a/Lang/J/Web-scraping b/Lang/J/Web-scraping new file mode 120000 index 0000000000..4d73cebd90 --- /dev/null +++ b/Lang/J/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/J \ No newline at end of file diff --git a/Lang/J/Window-creation b/Lang/J/Window-creation new file mode 120000 index 0000000000..c908704c48 --- /dev/null +++ b/Lang/J/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/J \ No newline at end of file diff --git a/Lang/J/Wireworld b/Lang/J/Wireworld new file mode 120000 index 0000000000..67136e6577 --- /dev/null +++ b/Lang/J/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/J \ No newline at end of file diff --git a/Lang/J/Word-wrap b/Lang/J/Word-wrap new file mode 120000 index 0000000000..caddaf220d --- /dev/null +++ b/Lang/J/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/J \ No newline at end of file diff --git a/Lang/J/Write-float-arrays-to-a-text-file b/Lang/J/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..17896f2d0b --- /dev/null +++ b/Lang/J/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/J \ No newline at end of file diff --git a/Lang/J/Write-language-name-in-3D-ASCII b/Lang/J/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..402f2aa241 --- /dev/null +++ b/Lang/J/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/J \ No newline at end of file diff --git a/Lang/J/XML-DOM-serialization b/Lang/J/XML-DOM-serialization new file mode 120000 index 0000000000..991fd5eae3 --- /dev/null +++ b/Lang/J/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/J \ No newline at end of file diff --git a/Lang/J/XML-Input b/Lang/J/XML-Input new file mode 120000 index 0000000000..10ceec4acb --- /dev/null +++ b/Lang/J/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/J \ No newline at end of file diff --git a/Lang/J/XML-Output b/Lang/J/XML-Output new file mode 120000 index 0000000000..d9cb70b65e --- /dev/null +++ b/Lang/J/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/J \ No newline at end of file diff --git a/Lang/J/Xiaolin-Wus-line-algorithm b/Lang/J/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..f87f5db857 --- /dev/null +++ b/Lang/J/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/J \ No newline at end of file diff --git a/Lang/J/Y-combinator b/Lang/J/Y-combinator new file mode 120000 index 0000000000..d4f8c98b26 --- /dev/null +++ b/Lang/J/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/J \ No newline at end of file diff --git a/Lang/J/Yin-and-yang b/Lang/J/Yin-and-yang new file mode 120000 index 0000000000..148f4c199b --- /dev/null +++ b/Lang/J/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/J \ No newline at end of file diff --git a/Lang/J/Zebra-puzzle b/Lang/J/Zebra-puzzle new file mode 120000 index 0000000000..c44a412593 --- /dev/null +++ b/Lang/J/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/J \ No newline at end of file diff --git a/Lang/J/Zeckendorf-number-representation b/Lang/J/Zeckendorf-number-representation new file mode 120000 index 0000000000..08dd0de1ce --- /dev/null +++ b/Lang/J/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/J \ No newline at end of file diff --git a/Lang/J/Zig-zag-matrix b/Lang/J/Zig-zag-matrix new file mode 120000 index 0000000000..437c51791f --- /dev/null +++ b/Lang/J/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/J \ No newline at end of file diff --git a/Lang/Java/SQL-based-authentication b/Lang/Java/SQL-based-authentication new file mode 120000 index 0000000000..b0d426e12f --- /dev/null +++ b/Lang/Java/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Java \ No newline at end of file diff --git a/Lang/Java/Set-puzzle b/Lang/Java/Set-puzzle new file mode 120000 index 0000000000..d9fb8d4f10 --- /dev/null +++ b/Lang/Java/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Java \ No newline at end of file diff --git a/Lang/Java/Shell-one-liner b/Lang/Java/Shell-one-liner new file mode 120000 index 0000000000..c592eaa399 --- /dev/null +++ b/Lang/Java/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Java \ No newline at end of file diff --git a/Lang/Java/Short-circuit-evaluation b/Lang/Java/Short-circuit-evaluation new file mode 120000 index 0000000000..dc8599f733 --- /dev/null +++ b/Lang/Java/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Java \ No newline at end of file diff --git a/Lang/Java/Show-the-epoch b/Lang/Java/Show-the-epoch new file mode 120000 index 0000000000..0d10aa7174 --- /dev/null +++ b/Lang/Java/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Java \ No newline at end of file diff --git a/Lang/Java/Sierpinski-carpet b/Lang/Java/Sierpinski-carpet new file mode 120000 index 0000000000..4319b00852 --- /dev/null +++ b/Lang/Java/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Java \ No newline at end of file diff --git a/Lang/Java/Sierpinski-triangle b/Lang/Java/Sierpinski-triangle new file mode 120000 index 0000000000..3d1eb2d109 --- /dev/null +++ b/Lang/Java/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Java \ No newline at end of file diff --git a/Lang/Java/Sieve-of-Eratosthenes b/Lang/Java/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..1cc79c7aed --- /dev/null +++ b/Lang/Java/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Java \ No newline at end of file diff --git a/Lang/Java/Simple-windowed-application b/Lang/Java/Simple-windowed-application new file mode 120000 index 0000000000..11d3057e00 --- /dev/null +++ b/Lang/Java/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Java \ No newline at end of file diff --git a/Lang/Java/Simulate-input-Keyboard b/Lang/Java/Simulate-input-Keyboard new file mode 120000 index 0000000000..c302bd5d41 --- /dev/null +++ b/Lang/Java/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Java \ No newline at end of file diff --git a/Lang/Java/Simulate-input-Mouse b/Lang/Java/Simulate-input-Mouse new file mode 120000 index 0000000000..731737f3cc --- /dev/null +++ b/Lang/Java/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Java \ No newline at end of file diff --git a/Lang/Java/Singleton b/Lang/Java/Singleton new file mode 120000 index 0000000000..0c59f45d73 --- /dev/null +++ b/Lang/Java/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Java \ No newline at end of file diff --git a/Lang/Java/Singly-linked-list-Element-definition b/Lang/Java/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..d8c6a16cbc --- /dev/null +++ b/Lang/Java/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Java \ No newline at end of file diff --git a/Lang/Java/Singly-linked-list-Element-insertion b/Lang/Java/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..1c117d59b4 --- /dev/null +++ b/Lang/Java/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Java \ No newline at end of file diff --git a/Lang/Java/Singly-linked-list-Traversal b/Lang/Java/Singly-linked-list-Traversal new file mode 120000 index 0000000000..2edbd1a9b1 --- /dev/null +++ b/Lang/Java/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Java \ No newline at end of file diff --git a/Lang/Java/Sleep b/Lang/Java/Sleep new file mode 120000 index 0000000000..7c7faeaac9 --- /dev/null +++ b/Lang/Java/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Java \ No newline at end of file diff --git a/Lang/Java/Sockets b/Lang/Java/Sockets new file mode 120000 index 0000000000..6231121c48 --- /dev/null +++ b/Lang/Java/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Java \ No newline at end of file diff --git a/Lang/Java/Sort-an-array-of-composite-structures b/Lang/Java/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..8a03ae19ee --- /dev/null +++ b/Lang/Java/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Java \ No newline at end of file diff --git a/Lang/Java/Sort-an-integer-array b/Lang/Java/Sort-an-integer-array new file mode 120000 index 0000000000..b19cbebbf6 --- /dev/null +++ b/Lang/Java/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Java \ No newline at end of file diff --git a/Lang/Java/Sort-disjoint-sublist b/Lang/Java/Sort-disjoint-sublist new file mode 120000 index 0000000000..a5a23551db --- /dev/null +++ b/Lang/Java/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Java \ No newline at end of file diff --git a/Lang/Java/Sort-stability b/Lang/Java/Sort-stability new file mode 120000 index 0000000000..6f078bfc68 --- /dev/null +++ b/Lang/Java/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Java \ No newline at end of file diff --git a/Lang/Java/Sort-using-a-custom-comparator b/Lang/Java/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..f06d937431 --- /dev/null +++ b/Lang/Java/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Bogosort b/Lang/Java/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..be16167d28 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Bubble-sort b/Lang/Java/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..7b45f55857 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Cocktail-sort b/Lang/Java/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..83e4b0fea7 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Comb-sort b/Lang/Java/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..e0c62d326a --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Counting-sort b/Lang/Java/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..5a4ec5413a --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Gnome-sort b/Lang/Java/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7293ccdaf3 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Heapsort b/Lang/Java/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..e043f92ce6 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Insertion-sort b/Lang/Java/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..1562d9e1e7 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Merge-sort b/Lang/Java/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..5a250218ea --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Pancake-sort b/Lang/Java/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..3014b1273b --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Quicksort b/Lang/Java/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..243242d953 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Selection-sort b/Lang/Java/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ac07a35065 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Shell-sort b/Lang/Java/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..8199821725 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Sleep-sort b/Lang/Java/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..b221715685 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Stooge-sort b/Lang/Java/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..91adbef7cc --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-algorithms-Strand-sort b/Lang/Java/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..42169f7723 --- /dev/null +++ b/Lang/Java/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Java \ No newline at end of file diff --git a/Lang/Java/Soundex b/Lang/Java/Soundex new file mode 120000 index 0000000000..de85df85de --- /dev/null +++ b/Lang/Java/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Java \ No newline at end of file diff --git a/Lang/Java/Special-characters b/Lang/Java/Special-characters new file mode 120000 index 0000000000..3b35d0222d --- /dev/null +++ b/Lang/Java/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Java \ No newline at end of file diff --git a/Lang/Java/Spiral-matrix b/Lang/Java/Spiral-matrix new file mode 120000 index 0000000000..4a661bb4b5 --- /dev/null +++ b/Lang/Java/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Java \ No newline at end of file diff --git a/Lang/Java/Stable-marriage-problem b/Lang/Java/Stable-marriage-problem new file mode 120000 index 0000000000..776bc5175d --- /dev/null +++ b/Lang/Java/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Java \ No newline at end of file diff --git a/Lang/Java/Stack b/Lang/Java/Stack new file mode 120000 index 0000000000..d95518e74e --- /dev/null +++ b/Lang/Java/Stack @@ -0,0 +1 @@ +../../Task/Stack/Java \ No newline at end of file diff --git a/Lang/Java/Stack-traces b/Lang/Java/Stack-traces new file mode 120000 index 0000000000..59a3f25b70 --- /dev/null +++ b/Lang/Java/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Java \ No newline at end of file diff --git a/Lang/Java/Stair-climbing-puzzle b/Lang/Java/Stair-climbing-puzzle new file mode 120000 index 0000000000..d15d0b3f9a --- /dev/null +++ b/Lang/Java/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Java \ No newline at end of file diff --git a/Lang/Java/Standard-deviation b/Lang/Java/Standard-deviation new file mode 120000 index 0000000000..7e52652d25 --- /dev/null +++ b/Lang/Java/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Java \ No newline at end of file diff --git a/Lang/Java/Stem-and-leaf-plot b/Lang/Java/Stem-and-leaf-plot new file mode 120000 index 0000000000..26ce8cfdb5 --- /dev/null +++ b/Lang/Java/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Java \ No newline at end of file diff --git a/Lang/Java/String-case b/Lang/Java/String-case new file mode 120000 index 0000000000..faf1ea5cbb --- /dev/null +++ b/Lang/Java/String-case @@ -0,0 +1 @@ +../../Task/String-case/Java \ No newline at end of file diff --git a/Lang/Java/String-concatenation b/Lang/Java/String-concatenation new file mode 120000 index 0000000000..5516e7e23b --- /dev/null +++ b/Lang/Java/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Java \ No newline at end of file diff --git a/Lang/Java/String-interpolation--included- b/Lang/Java/String-interpolation--included- new file mode 120000 index 0000000000..5534e272b7 --- /dev/null +++ b/Lang/Java/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Java \ No newline at end of file diff --git a/Lang/Java/String-length b/Lang/Java/String-length new file mode 120000 index 0000000000..1aa658913c --- /dev/null +++ b/Lang/Java/String-length @@ -0,0 +1 @@ +../../Task/String-length/Java \ No newline at end of file diff --git a/Lang/Java/Strip-a-set-of-characters-from-a-string b/Lang/Java/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..7803040264 --- /dev/null +++ b/Lang/Java/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Java \ No newline at end of file diff --git a/Lang/Java/Strip-block-comments b/Lang/Java/Strip-block-comments new file mode 120000 index 0000000000..0187e7930f --- /dev/null +++ b/Lang/Java/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Java \ No newline at end of file diff --git a/Lang/Java/Strip-comments-from-a-string b/Lang/Java/Strip-comments-from-a-string new file mode 120000 index 0000000000..b32f007097 --- /dev/null +++ b/Lang/Java/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Java \ No newline at end of file diff --git a/Lang/Java/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Java/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..0c45cdec6b --- /dev/null +++ b/Lang/Java/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Java \ No newline at end of file diff --git a/Lang/Java/Substring b/Lang/Java/Substring new file mode 120000 index 0000000000..aa79bcdb7f --- /dev/null +++ b/Lang/Java/Substring @@ -0,0 +1 @@ +../../Task/Substring/Java \ No newline at end of file diff --git a/Lang/Java/Substring-Top-and-tail b/Lang/Java/Substring-Top-and-tail new file mode 120000 index 0000000000..e9ce865b25 --- /dev/null +++ b/Lang/Java/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Java \ No newline at end of file diff --git a/Lang/Java/Sudoku b/Lang/Java/Sudoku new file mode 120000 index 0000000000..e2b2c1415e --- /dev/null +++ b/Lang/Java/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Java \ No newline at end of file diff --git a/Lang/Java/Sum-and-product-of-an-array b/Lang/Java/Sum-and-product-of-an-array new file mode 120000 index 0000000000..dcbe55746c --- /dev/null +++ b/Lang/Java/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Java \ No newline at end of file diff --git a/Lang/Java/Sum-digits-of-an-integer b/Lang/Java/Sum-digits-of-an-integer new file mode 120000 index 0000000000..c5463bc2c3 --- /dev/null +++ b/Lang/Java/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Java \ No newline at end of file diff --git a/Lang/Java/Sum-of-a-series b/Lang/Java/Sum-of-a-series new file mode 120000 index 0000000000..f7d88196ad --- /dev/null +++ b/Lang/Java/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Java \ No newline at end of file diff --git a/Lang/Java/Sum-of-squares b/Lang/Java/Sum-of-squares new file mode 120000 index 0000000000..bdda025252 --- /dev/null +++ b/Lang/Java/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Java \ No newline at end of file diff --git a/Lang/Java/Symmetric-difference b/Lang/Java/Symmetric-difference new file mode 120000 index 0000000000..16294a66d3 --- /dev/null +++ b/Lang/Java/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Java \ No newline at end of file diff --git a/Lang/Java/Synchronous-concurrency b/Lang/Java/Synchronous-concurrency new file mode 120000 index 0000000000..316aab9aeb --- /dev/null +++ b/Lang/Java/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Java \ No newline at end of file diff --git a/Lang/Java/System-time b/Lang/Java/System-time new file mode 120000 index 0000000000..109e85d702 --- /dev/null +++ b/Lang/Java/System-time @@ -0,0 +1 @@ +../../Task/System-time/Java \ No newline at end of file diff --git a/Lang/Java/Take-notes-on-the-command-line b/Lang/Java/Take-notes-on-the-command-line new file mode 120000 index 0000000000..560c9acb9f --- /dev/null +++ b/Lang/Java/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Java \ No newline at end of file diff --git a/Lang/Java/Temperature-conversion b/Lang/Java/Temperature-conversion new file mode 120000 index 0000000000..5903a098c1 --- /dev/null +++ b/Lang/Java/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Java \ No newline at end of file diff --git a/Lang/Java/Terminal-control-Display-an-extended-character b/Lang/Java/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..4e88c8a9fa --- /dev/null +++ b/Lang/Java/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Java \ No newline at end of file diff --git a/Lang/Java/Terminal-control-Ringing-the-terminal-bell b/Lang/Java/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..4f3bad371b --- /dev/null +++ b/Lang/Java/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Java \ No newline at end of file diff --git a/Lang/Java/Ternary-logic b/Lang/Java/Ternary-logic new file mode 120000 index 0000000000..b43f90c606 --- /dev/null +++ b/Lang/Java/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Java \ No newline at end of file diff --git a/Lang/Java/Test-a-function b/Lang/Java/Test-a-function new file mode 120000 index 0000000000..8f7efde316 --- /dev/null +++ b/Lang/Java/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Java \ No newline at end of file diff --git a/Lang/Java/Text-processing-2 b/Lang/Java/Text-processing-2 new file mode 120000 index 0000000000..227cf748df --- /dev/null +++ b/Lang/Java/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Java \ No newline at end of file diff --git a/Lang/Java/Text-processing-Max-licenses-in-use b/Lang/Java/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..52404b0548 --- /dev/null +++ b/Lang/Java/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Java \ No newline at end of file diff --git a/Lang/Java/Tic-tac-toe b/Lang/Java/Tic-tac-toe new file mode 120000 index 0000000000..f320c95126 --- /dev/null +++ b/Lang/Java/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Java \ No newline at end of file diff --git a/Lang/Java/Time-a-function b/Lang/Java/Time-a-function new file mode 120000 index 0000000000..52c56f9088 --- /dev/null +++ b/Lang/Java/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Java \ No newline at end of file diff --git a/Lang/Java/Tokenize-a-string b/Lang/Java/Tokenize-a-string new file mode 120000 index 0000000000..cc171bafac --- /dev/null +++ b/Lang/Java/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Java \ No newline at end of file diff --git a/Lang/Java/Topological-sort b/Lang/Java/Topological-sort new file mode 120000 index 0000000000..34071ee270 --- /dev/null +++ b/Lang/Java/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Java \ No newline at end of file diff --git a/Lang/Java/Topswops b/Lang/Java/Topswops new file mode 120000 index 0000000000..610b090f66 --- /dev/null +++ b/Lang/Java/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Java \ No newline at end of file diff --git a/Lang/Java/Towers-of-Hanoi b/Lang/Java/Towers-of-Hanoi new file mode 120000 index 0000000000..277d363dc6 --- /dev/null +++ b/Lang/Java/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Java \ No newline at end of file diff --git a/Lang/Java/Trabb-Pardo-Knuth-algorithm b/Lang/Java/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..eca360b4dd --- /dev/null +++ b/Lang/Java/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Tree-traversal b/Lang/Java/Tree-traversal new file mode 120000 index 0000000000..3ff92b9943 --- /dev/null +++ b/Lang/Java/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Java \ No newline at end of file diff --git a/Lang/Java/Trigonometric-functions b/Lang/Java/Trigonometric-functions new file mode 120000 index 0000000000..f4561c2889 --- /dev/null +++ b/Lang/Java/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Java \ No newline at end of file diff --git a/Lang/Java/Truncatable-primes b/Lang/Java/Truncatable-primes new file mode 120000 index 0000000000..d8a542fc4d --- /dev/null +++ b/Lang/Java/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Java \ No newline at end of file diff --git a/Lang/Java/Truncate-a-file b/Lang/Java/Truncate-a-file new file mode 120000 index 0000000000..3646b0c1d3 --- /dev/null +++ b/Lang/Java/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Java \ No newline at end of file diff --git a/Lang/Java/Twelve-statements b/Lang/Java/Twelve-statements new file mode 120000 index 0000000000..8f6fcafe7f --- /dev/null +++ b/Lang/Java/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Java \ No newline at end of file diff --git a/Lang/Java/URL-decoding b/Lang/Java/URL-decoding new file mode 120000 index 0000000000..81235067c3 --- /dev/null +++ b/Lang/Java/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Java \ No newline at end of file diff --git a/Lang/Java/URL-encoding b/Lang/Java/URL-encoding new file mode 120000 index 0000000000..061d85146f --- /dev/null +++ b/Lang/Java/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Java \ No newline at end of file diff --git a/Lang/Java/Unbias-a-random-generator b/Lang/Java/Unbias-a-random-generator new file mode 120000 index 0000000000..fddc962221 --- /dev/null +++ b/Lang/Java/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Java \ No newline at end of file diff --git a/Lang/Java/Undefined-values b/Lang/Java/Undefined-values new file mode 120000 index 0000000000..e234ac5cd1 --- /dev/null +++ b/Lang/Java/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Java \ No newline at end of file diff --git a/Lang/Java/Unicode-variable-names b/Lang/Java/Unicode-variable-names new file mode 120000 index 0000000000..01a1055fb3 --- /dev/null +++ b/Lang/Java/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Java \ No newline at end of file diff --git a/Lang/Java/Universal-Turing-machine b/Lang/Java/Universal-Turing-machine new file mode 120000 index 0000000000..6dbc72d1a8 --- /dev/null +++ b/Lang/Java/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Java \ No newline at end of file diff --git a/Lang/Java/User-input-Graphical b/Lang/Java/User-input-Graphical new file mode 120000 index 0000000000..a534203a59 --- /dev/null +++ b/Lang/Java/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Java \ No newline at end of file diff --git a/Lang/Java/User-input-Text b/Lang/Java/User-input-Text new file mode 120000 index 0000000000..8173f7320f --- /dev/null +++ b/Lang/Java/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Java \ No newline at end of file diff --git a/Lang/Java/Vampire-number b/Lang/Java/Vampire-number new file mode 120000 index 0000000000..1947c01d33 --- /dev/null +++ b/Lang/Java/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Java \ No newline at end of file diff --git a/Lang/Java/Van-der-Corput-sequence b/Lang/Java/Van-der-Corput-sequence new file mode 120000 index 0000000000..8cf78b70cb --- /dev/null +++ b/Lang/Java/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Java \ No newline at end of file diff --git a/Lang/Java/Variable-length-quantity b/Lang/Java/Variable-length-quantity new file mode 120000 index 0000000000..bc62f38640 --- /dev/null +++ b/Lang/Java/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Java \ No newline at end of file diff --git a/Lang/Java/Variables b/Lang/Java/Variables new file mode 120000 index 0000000000..1556792c77 --- /dev/null +++ b/Lang/Java/Variables @@ -0,0 +1 @@ +../../Task/Variables/Java \ No newline at end of file diff --git a/Lang/Java/Variadic-function b/Lang/Java/Variadic-function new file mode 120000 index 0000000000..685ffe9116 --- /dev/null +++ b/Lang/Java/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Java \ No newline at end of file diff --git a/Lang/Java/Vector-products b/Lang/Java/Vector-products new file mode 120000 index 0000000000..3a23014200 --- /dev/null +++ b/Lang/Java/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Java \ No newline at end of file diff --git a/Lang/Java/Vigen-re-cipher b/Lang/Java/Vigen-re-cipher new file mode 120000 index 0000000000..b9c803ab1a --- /dev/null +++ b/Lang/Java/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Java \ No newline at end of file diff --git a/Lang/Java/Walk-a-directory-Non-recursively b/Lang/Java/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..bfef741b82 --- /dev/null +++ b/Lang/Java/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Java \ No newline at end of file diff --git a/Lang/Java/Walk-a-directory-Recursively b/Lang/Java/Walk-a-directory-Recursively new file mode 120000 index 0000000000..ab95cff99b --- /dev/null +++ b/Lang/Java/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Java \ No newline at end of file diff --git a/Lang/Java/Web-scraping b/Lang/Java/Web-scraping new file mode 120000 index 0000000000..0eaa818a94 --- /dev/null +++ b/Lang/Java/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Java \ No newline at end of file diff --git a/Lang/Java/Window-creation b/Lang/Java/Window-creation new file mode 120000 index 0000000000..6f3e71db49 --- /dev/null +++ b/Lang/Java/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Java \ No newline at end of file diff --git a/Lang/Java/Window-creation-X11 b/Lang/Java/Window-creation-X11 new file mode 120000 index 0000000000..0c2a5320b7 --- /dev/null +++ b/Lang/Java/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Java \ No newline at end of file diff --git a/Lang/Java/Write-float-arrays-to-a-text-file b/Lang/Java/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..c098b05129 --- /dev/null +++ b/Lang/Java/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Java \ No newline at end of file diff --git a/Lang/Java/XML-DOM-serialization b/Lang/Java/XML-DOM-serialization new file mode 120000 index 0000000000..27d3635085 --- /dev/null +++ b/Lang/Java/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Java \ No newline at end of file diff --git a/Lang/Java/XML-Input b/Lang/Java/XML-Input new file mode 120000 index 0000000000..23e45a2557 --- /dev/null +++ b/Lang/Java/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Java \ No newline at end of file diff --git a/Lang/Java/XML-Output b/Lang/Java/XML-Output new file mode 120000 index 0000000000..29ce8defee --- /dev/null +++ b/Lang/Java/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Java \ No newline at end of file diff --git a/Lang/Java/XML-XPath b/Lang/Java/XML-XPath new file mode 120000 index 0000000000..04d572036f --- /dev/null +++ b/Lang/Java/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Java \ No newline at end of file diff --git a/Lang/Java/Y-combinator b/Lang/Java/Y-combinator new file mode 120000 index 0000000000..dc2f419941 --- /dev/null +++ b/Lang/Java/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Java \ No newline at end of file diff --git a/Lang/Java/Yahoo--search-interface b/Lang/Java/Yahoo--search-interface new file mode 120000 index 0000000000..4f806a7648 --- /dev/null +++ b/Lang/Java/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Java \ No newline at end of file diff --git a/Lang/Java/Yin-and-yang b/Lang/Java/Yin-and-yang new file mode 120000 index 0000000000..f36d8c12ec --- /dev/null +++ b/Lang/Java/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Java \ No newline at end of file diff --git a/Lang/Java/Zeckendorf-number-representation b/Lang/Java/Zeckendorf-number-representation new file mode 120000 index 0000000000..c01be82a5d --- /dev/null +++ b/Lang/Java/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Java \ No newline at end of file diff --git a/Lang/Java/Zig-zag-matrix b/Lang/Java/Zig-zag-matrix new file mode 120000 index 0000000000..e37edb9538 --- /dev/null +++ b/Lang/Java/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Java \ No newline at end of file diff --git a/Lang/JavaFX-Script/Sierpinski-triangle b/Lang/JavaFX-Script/Sierpinski-triangle new file mode 120000 index 0000000000..1e156647aa --- /dev/null +++ b/Lang/JavaFX-Script/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/JavaFX-Script \ No newline at end of file diff --git a/Lang/JavaFX-Script/Simple-windowed-application b/Lang/JavaFX-Script/Simple-windowed-application new file mode 120000 index 0000000000..c14b4aeaab --- /dev/null +++ b/Lang/JavaFX-Script/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/JavaFX-Script \ No newline at end of file diff --git a/Lang/JavaScript/Seven-sided-dice-from-five-sided-dice b/Lang/JavaScript/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..5835c808e5 --- /dev/null +++ b/Lang/JavaScript/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Shell-one-liner b/Lang/JavaScript/Shell-one-liner new file mode 120000 index 0000000000..22a0adc722 --- /dev/null +++ b/Lang/JavaScript/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Show-the-epoch b/Lang/JavaScript/Show-the-epoch new file mode 120000 index 0000000000..2b0e4387c7 --- /dev/null +++ b/Lang/JavaScript/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sierpinski-carpet b/Lang/JavaScript/Sierpinski-carpet new file mode 120000 index 0000000000..75854360dc --- /dev/null +++ b/Lang/JavaScript/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sierpinski-triangle b/Lang/JavaScript/Sierpinski-triangle new file mode 120000 index 0000000000..25a1a13d85 --- /dev/null +++ b/Lang/JavaScript/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sieve-of-Eratosthenes b/Lang/JavaScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..641bb72eed --- /dev/null +++ b/Lang/JavaScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Singleton b/Lang/JavaScript/Singleton new file mode 120000 index 0000000000..a2abd0df17 --- /dev/null +++ b/Lang/JavaScript/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Singly-linked-list-Element-definition b/Lang/JavaScript/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..101f77ed1f --- /dev/null +++ b/Lang/JavaScript/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Singly-linked-list-Element-insertion b/Lang/JavaScript/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..336312e435 --- /dev/null +++ b/Lang/JavaScript/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Singly-linked-list-Traversal b/Lang/JavaScript/Singly-linked-list-Traversal new file mode 120000 index 0000000000..d394c3b381 --- /dev/null +++ b/Lang/JavaScript/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sleep b/Lang/JavaScript/Sleep new file mode 120000 index 0000000000..e4b5ad07d9 --- /dev/null +++ b/Lang/JavaScript/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-an-array-of-composite-structures b/Lang/JavaScript/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..d7b953ba1b --- /dev/null +++ b/Lang/JavaScript/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-an-integer-array b/Lang/JavaScript/Sort-an-integer-array new file mode 120000 index 0000000000..f3d0226f51 --- /dev/null +++ b/Lang/JavaScript/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-disjoint-sublist b/Lang/JavaScript/Sort-disjoint-sublist new file mode 120000 index 0000000000..2b9128cb77 --- /dev/null +++ b/Lang/JavaScript/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-stability b/Lang/JavaScript/Sort-stability new file mode 120000 index 0000000000..bc38b9439d --- /dev/null +++ b/Lang/JavaScript/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-using-a-custom-comparator b/Lang/JavaScript/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..c572c5f3bf --- /dev/null +++ b/Lang/JavaScript/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Bogosort b/Lang/JavaScript/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..d042ce8bd5 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Bubble-sort b/Lang/JavaScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..075ca9c836 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Counting-sort b/Lang/JavaScript/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..6d7896552d --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Gnome-sort b/Lang/JavaScript/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..333dcf54da --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Insertion-sort b/Lang/JavaScript/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..b1c6729385 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Merge-sort b/Lang/JavaScript/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..16bf3905ef --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Pancake-sort b/Lang/JavaScript/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..f5e2c54eaa --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Quicksort b/Lang/JavaScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..b80dee8750 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Shell-sort b/Lang/JavaScript/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..79810bd92b --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Sleep-sort b/Lang/JavaScript/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..ef1e13e953 --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Soundex b/Lang/JavaScript/Soundex new file mode 120000 index 0000000000..b04e122d90 --- /dev/null +++ b/Lang/JavaScript/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Special-variables b/Lang/JavaScript/Special-variables new file mode 120000 index 0000000000..55f1fac895 --- /dev/null +++ b/Lang/JavaScript/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Spiral-matrix b/Lang/JavaScript/Spiral-matrix new file mode 120000 index 0000000000..4ab2e18b1b --- /dev/null +++ b/Lang/JavaScript/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Stable-marriage-problem b/Lang/JavaScript/Stable-marriage-problem new file mode 120000 index 0000000000..39e109466d --- /dev/null +++ b/Lang/JavaScript/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Stack b/Lang/JavaScript/Stack new file mode 120000 index 0000000000..c999475300 --- /dev/null +++ b/Lang/JavaScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Stack-traces b/Lang/JavaScript/Stack-traces new file mode 120000 index 0000000000..a0c37675bc --- /dev/null +++ b/Lang/JavaScript/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Standard-deviation b/Lang/JavaScript/Standard-deviation new file mode 120000 index 0000000000..6c2653a133 --- /dev/null +++ b/Lang/JavaScript/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Stem-and-leaf-plot b/Lang/JavaScript/Stem-and-leaf-plot new file mode 120000 index 0000000000..439537f880 --- /dev/null +++ b/Lang/JavaScript/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-case b/Lang/JavaScript/String-case new file mode 120000 index 0000000000..db46fdd9f2 --- /dev/null +++ b/Lang/JavaScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-concatenation b/Lang/JavaScript/String-concatenation new file mode 120000 index 0000000000..7a8c1d1c24 --- /dev/null +++ b/Lang/JavaScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-interpolation--included- b/Lang/JavaScript/String-interpolation--included- new file mode 120000 index 0000000000..e0496a5e18 --- /dev/null +++ b/Lang/JavaScript/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/String-length b/Lang/JavaScript/String-length new file mode 120000 index 0000000000..e2a398313e --- /dev/null +++ b/Lang/JavaScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Strip-a-set-of-characters-from-a-string b/Lang/JavaScript/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..0b3b7f0e93 --- /dev/null +++ b/Lang/JavaScript/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Strip-comments-from-a-string b/Lang/JavaScript/Strip-comments-from-a-string new file mode 120000 index 0000000000..fa52fe1a78 --- /dev/null +++ b/Lang/JavaScript/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Substring b/Lang/JavaScript/Substring new file mode 120000 index 0000000000..cea95caddb --- /dev/null +++ b/Lang/JavaScript/Substring @@ -0,0 +1 @@ +../../Task/Substring/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Substring-Top-and-tail b/Lang/JavaScript/Substring-Top-and-tail new file mode 120000 index 0000000000..945d4d09df --- /dev/null +++ b/Lang/JavaScript/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sum-and-product-of-an-array b/Lang/JavaScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..0f49e22e37 --- /dev/null +++ b/Lang/JavaScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sum-of-a-series b/Lang/JavaScript/Sum-of-a-series new file mode 120000 index 0000000000..ebaa68002a --- /dev/null +++ b/Lang/JavaScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sum-of-squares b/Lang/JavaScript/Sum-of-squares new file mode 120000 index 0000000000..bc3736af95 --- /dev/null +++ b/Lang/JavaScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sutherland-Hodgman-polygon-clipping b/Lang/JavaScript/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..fd30641c8e --- /dev/null +++ b/Lang/JavaScript/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Symmetric-difference b/Lang/JavaScript/Symmetric-difference new file mode 120000 index 0000000000..a7eca6ca58 --- /dev/null +++ b/Lang/JavaScript/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/System-time b/Lang/JavaScript/System-time new file mode 120000 index 0000000000..dd702b6cf6 --- /dev/null +++ b/Lang/JavaScript/System-time @@ -0,0 +1 @@ +../../Task/System-time/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Take-notes-on-the-command-line b/Lang/JavaScript/Take-notes-on-the-command-line new file mode 120000 index 0000000000..e6c2dd73d3 --- /dev/null +++ b/Lang/JavaScript/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Terminal-control-Preserve-screen b/Lang/JavaScript/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..b2955a6485 --- /dev/null +++ b/Lang/JavaScript/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Text-processing-1 b/Lang/JavaScript/Text-processing-1 new file mode 120000 index 0000000000..55ce9e9d51 --- /dev/null +++ b/Lang/JavaScript/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Text-processing-2 b/Lang/JavaScript/Text-processing-2 new file mode 120000 index 0000000000..ba105521c5 --- /dev/null +++ b/Lang/JavaScript/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Text-processing-Max-licenses-in-use b/Lang/JavaScript/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..9d59ac584c --- /dev/null +++ b/Lang/JavaScript/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tokenize-a-string b/Lang/JavaScript/Tokenize-a-string new file mode 120000 index 0000000000..a1dc614a8d --- /dev/null +++ b/Lang/JavaScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Top-rank-per-group b/Lang/JavaScript/Top-rank-per-group new file mode 120000 index 0000000000..a644db0258 --- /dev/null +++ b/Lang/JavaScript/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Towers-of-Hanoi b/Lang/JavaScript/Towers-of-Hanoi new file mode 120000 index 0000000000..746d072b78 --- /dev/null +++ b/Lang/JavaScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Trabb-Pardo-Knuth-algorithm b/Lang/JavaScript/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..310efb2e4a --- /dev/null +++ b/Lang/JavaScript/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tree-traversal b/Lang/JavaScript/Tree-traversal new file mode 120000 index 0000000000..75108b2ae1 --- /dev/null +++ b/Lang/JavaScript/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Trigonometric-functions b/Lang/JavaScript/Trigonometric-functions new file mode 120000 index 0000000000..af773fa456 --- /dev/null +++ b/Lang/JavaScript/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/URL-decoding b/Lang/JavaScript/URL-decoding new file mode 120000 index 0000000000..f45c2dafba --- /dev/null +++ b/Lang/JavaScript/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/URL-encoding b/Lang/JavaScript/URL-encoding new file mode 120000 index 0000000000..4b18ecd25a --- /dev/null +++ b/Lang/JavaScript/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Undefined-values b/Lang/JavaScript/Undefined-values new file mode 120000 index 0000000000..0c0d9b0193 --- /dev/null +++ b/Lang/JavaScript/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/User-input-Graphical b/Lang/JavaScript/User-input-Graphical new file mode 120000 index 0000000000..40f9eba7e8 --- /dev/null +++ b/Lang/JavaScript/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/User-input-Text b/Lang/JavaScript/User-input-Text new file mode 120000 index 0000000000..0dfd4919ba --- /dev/null +++ b/Lang/JavaScript/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Variables b/Lang/JavaScript/Variables new file mode 120000 index 0000000000..64f74829b8 --- /dev/null +++ b/Lang/JavaScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Variadic-function b/Lang/JavaScript/Variadic-function new file mode 120000 index 0000000000..034ce4a749 --- /dev/null +++ b/Lang/JavaScript/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vector-products b/Lang/JavaScript/Vector-products new file mode 120000 index 0000000000..aeb94e01ac --- /dev/null +++ b/Lang/JavaScript/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Verify-distribution-uniformity-Naive b/Lang/JavaScript/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..477fb94683 --- /dev/null +++ b/Lang/JavaScript/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vigen-re-cipher b/Lang/JavaScript/Vigen-re-cipher new file mode 120000 index 0000000000..9ca4bcb1e8 --- /dev/null +++ b/Lang/JavaScript/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Visualize-a-tree b/Lang/JavaScript/Visualize-a-tree new file mode 120000 index 0000000000..47dc64ebea --- /dev/null +++ b/Lang/JavaScript/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Walk-a-directory-Non-recursively b/Lang/JavaScript/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..afbee601e5 --- /dev/null +++ b/Lang/JavaScript/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Walk-a-directory-Recursively b/Lang/JavaScript/Walk-a-directory-Recursively new file mode 120000 index 0000000000..65fea85ba8 --- /dev/null +++ b/Lang/JavaScript/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/XML-DOM-serialization b/Lang/JavaScript/XML-DOM-serialization new file mode 120000 index 0000000000..b30305213d --- /dev/null +++ b/Lang/JavaScript/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/XML-Input b/Lang/JavaScript/XML-Input new file mode 120000 index 0000000000..f0c6d569b2 --- /dev/null +++ b/Lang/JavaScript/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/XML-XPath b/Lang/JavaScript/XML-XPath new file mode 120000 index 0000000000..61e7395f92 --- /dev/null +++ b/Lang/JavaScript/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Y-combinator b/Lang/JavaScript/Y-combinator new file mode 120000 index 0000000000..aa57addced --- /dev/null +++ b/Lang/JavaScript/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Zig-zag-matrix b/Lang/JavaScript/Zig-zag-matrix new file mode 120000 index 0000000000..4824bbde32 --- /dev/null +++ b/Lang/JavaScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/JavaScript \ No newline at end of file diff --git a/Lang/Joy/Sorting-algorithms-Quicksort b/Lang/Joy/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..100da9cd6a --- /dev/null +++ b/Lang/Joy/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Joy \ No newline at end of file diff --git a/Lang/Joy/Towers-of-Hanoi b/Lang/Joy/Towers-of-Hanoi new file mode 120000 index 0000000000..c7498926ed --- /dev/null +++ b/Lang/Joy/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Joy \ No newline at end of file diff --git a/Lang/Joy/User-input-Text b/Lang/Joy/User-input-Text new file mode 120000 index 0000000000..24a8416d6c --- /dev/null +++ b/Lang/Joy/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Joy \ No newline at end of file diff --git a/Lang/Joy/Variables b/Lang/Joy/Variables new file mode 120000 index 0000000000..7ef5693a0f --- /dev/null +++ b/Lang/Joy/Variables @@ -0,0 +1 @@ +../../Task/Variables/Joy \ No newline at end of file diff --git a/Lang/Joy/Write-float-arrays-to-a-text-file b/Lang/Joy/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d10022c97e --- /dev/null +++ b/Lang/Joy/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Joy \ No newline at end of file diff --git a/Lang/Joy/XML-Output b/Lang/Joy/XML-Output new file mode 120000 index 0000000000..778efa1941 --- /dev/null +++ b/Lang/Joy/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Joy \ No newline at end of file diff --git a/Lang/Joy/Y-combinator b/Lang/Joy/Y-combinator new file mode 120000 index 0000000000..39554581c7 --- /dev/null +++ b/Lang/Joy/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Joy \ No newline at end of file diff --git a/Lang/Joy/Zig-zag-matrix b/Lang/Joy/Zig-zag-matrix new file mode 120000 index 0000000000..bff1e645ea --- /dev/null +++ b/Lang/Joy/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Joy \ No newline at end of file diff --git a/Lang/JudoScript/String-length b/Lang/JudoScript/String-length new file mode 120000 index 0000000000..dde47503e3 --- /dev/null +++ b/Lang/JudoScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/JudoScript \ No newline at end of file diff --git a/Lang/Julia/Shell-one-liner b/Lang/Julia/Shell-one-liner new file mode 120000 index 0000000000..ff82f6f82a --- /dev/null +++ b/Lang/Julia/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Julia \ No newline at end of file diff --git a/Lang/Julia/Short-circuit-evaluation b/Lang/Julia/Short-circuit-evaluation new file mode 120000 index 0000000000..e4709b92f0 --- /dev/null +++ b/Lang/Julia/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Julia \ No newline at end of file diff --git a/Lang/Julia/Sort-an-integer-array b/Lang/Julia/Sort-an-integer-array new file mode 120000 index 0000000000..a13a873eb6 --- /dev/null +++ b/Lang/Julia/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Julia \ No newline at end of file diff --git a/Lang/Julia/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Julia/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..9c2976de3d --- /dev/null +++ b/Lang/Julia/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Julia \ No newline at end of file diff --git a/Lang/Julia/Substring b/Lang/Julia/Substring new file mode 120000 index 0000000000..64c5978984 --- /dev/null +++ b/Lang/Julia/Substring @@ -0,0 +1 @@ +../../Task/Substring/Julia \ No newline at end of file diff --git a/Lang/Julia/Substring-Top-and-tail b/Lang/Julia/Substring-Top-and-tail new file mode 120000 index 0000000000..aa94ae4f18 --- /dev/null +++ b/Lang/Julia/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Julia \ No newline at end of file diff --git a/Lang/Julia/Sum-and-product-of-an-array b/Lang/Julia/Sum-and-product-of-an-array new file mode 120000 index 0000000000..964cc1ed0d --- /dev/null +++ b/Lang/Julia/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Julia \ No newline at end of file diff --git a/Lang/Julia/Sum-of-a-series b/Lang/Julia/Sum-of-a-series new file mode 120000 index 0000000000..616b586edd --- /dev/null +++ b/Lang/Julia/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Julia \ No newline at end of file diff --git a/Lang/Julia/Sum-of-squares b/Lang/Julia/Sum-of-squares new file mode 120000 index 0000000000..74f9ca6c63 --- /dev/null +++ b/Lang/Julia/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Julia \ No newline at end of file diff --git a/Lang/Julia/Temperature-conversion b/Lang/Julia/Temperature-conversion new file mode 120000 index 0000000000..138d5d8b8f --- /dev/null +++ b/Lang/Julia/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Julia \ No newline at end of file diff --git a/Lang/Julia/Topswops b/Lang/Julia/Topswops new file mode 120000 index 0000000000..ca9447ad51 --- /dev/null +++ b/Lang/Julia/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Julia \ No newline at end of file diff --git a/Lang/Julia/Trabb-Pardo-Knuth-algorithm b/Lang/Julia/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..f9e0b232c8 --- /dev/null +++ b/Lang/Julia/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Variable-size-Get b/Lang/Julia/Variable-size-Get new file mode 120000 index 0000000000..780b67172e --- /dev/null +++ b/Lang/Julia/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Julia \ No newline at end of file diff --git a/Lang/Julia/Variables b/Lang/Julia/Variables new file mode 120000 index 0000000000..976277291a --- /dev/null +++ b/Lang/Julia/Variables @@ -0,0 +1 @@ +../../Task/Variables/Julia \ No newline at end of file diff --git a/Lang/Julia/Variadic-function b/Lang/Julia/Variadic-function new file mode 120000 index 0000000000..a3b44ba9a4 --- /dev/null +++ b/Lang/Julia/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Write-float-arrays-to-a-text-file b/Lang/Julia/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..4bf5fb9527 --- /dev/null +++ b/Lang/Julia/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Zeckendorf-number-representation b/Lang/Julia/Zeckendorf-number-representation new file mode 120000 index 0000000000..86bfd15062 --- /dev/null +++ b/Lang/Julia/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Julia \ No newline at end of file diff --git a/Lang/K/Shell-one-liner b/Lang/K/Shell-one-liner new file mode 120000 index 0000000000..4e6919aa71 --- /dev/null +++ b/Lang/K/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/K \ No newline at end of file diff --git a/Lang/K/Sort-an-integer-array b/Lang/K/Sort-an-integer-array new file mode 120000 index 0000000000..0f64e0f685 --- /dev/null +++ b/Lang/K/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/K \ No newline at end of file diff --git a/Lang/K/Sort-disjoint-sublist b/Lang/K/Sort-disjoint-sublist new file mode 120000 index 0000000000..b67f254d80 --- /dev/null +++ b/Lang/K/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/K \ No newline at end of file diff --git a/Lang/K/Sorting-algorithms-Quicksort b/Lang/K/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..87fb6f5455 --- /dev/null +++ b/Lang/K/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/K \ No newline at end of file diff --git a/Lang/K/Sum-of-a-series b/Lang/K/Sum-of-a-series new file mode 120000 index 0000000000..63f31b616f --- /dev/null +++ b/Lang/K/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/K \ No newline at end of file diff --git a/Lang/K/Sum-of-squares b/Lang/K/Sum-of-squares new file mode 120000 index 0000000000..59c2114bff --- /dev/null +++ b/Lang/K/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/K \ No newline at end of file diff --git a/Lang/K/Symmetric-difference b/Lang/K/Symmetric-difference new file mode 120000 index 0000000000..141da190f3 --- /dev/null +++ b/Lang/K/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/K \ No newline at end of file diff --git a/Lang/K/Text-processing-Max-licenses-in-use b/Lang/K/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..b183cf64de --- /dev/null +++ b/Lang/K/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/K \ No newline at end of file diff --git a/Lang/K/Towers-of-Hanoi b/Lang/K/Towers-of-Hanoi new file mode 120000 index 0000000000..6c17ee9886 --- /dev/null +++ b/Lang/K/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/K \ No newline at end of file diff --git a/Lang/Kite/User-input-Text b/Lang/Kite/User-input-Text new file mode 120000 index 0000000000..41b2f01e24 --- /dev/null +++ b/Lang/Kite/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Kite \ No newline at end of file diff --git a/Lang/LOLCODE/Undefined-values b/Lang/LOLCODE/Undefined-values new file mode 120000 index 0000000000..07d4b7b5b4 --- /dev/null +++ b/Lang/LOLCODE/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Unicode-variable-names b/Lang/LOLCODE/Unicode-variable-names new file mode 120000 index 0000000000..78f52bc13a --- /dev/null +++ b/Lang/LOLCODE/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/LOLCODE \ No newline at end of file diff --git a/Lang/LSE64/String-length b/Lang/LSE64/String-length new file mode 120000 index 0000000000..115fabc437 --- /dev/null +++ b/Lang/LSE64/String-length @@ -0,0 +1 @@ +../../Task/String-length/LSE64 \ No newline at end of file diff --git a/Lang/LaTeX/Special-characters b/Lang/LaTeX/Special-characters new file mode 120000 index 0000000000..b791e12855 --- /dev/null +++ b/Lang/LaTeX/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/LaTeX \ No newline at end of file diff --git a/Lang/Lang5/String-concatenation b/Lang/Lang5/String-concatenation new file mode 120000 index 0000000000..b137f74e24 --- /dev/null +++ b/Lang/Lang5/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Substring b/Lang/Lang5/Substring new file mode 120000 index 0000000000..096f926146 --- /dev/null +++ b/Lang/Lang5/Substring @@ -0,0 +1 @@ +../../Task/Substring/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Sum-and-product-of-an-array b/Lang/Lang5/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9af0f9e12e --- /dev/null +++ b/Lang/Lang5/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Sum-of-a-series b/Lang/Lang5/Sum-of-a-series new file mode 120000 index 0000000000..34b75b99c7 --- /dev/null +++ b/Lang/Lang5/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Sum-of-squares b/Lang/Lang5/Sum-of-squares new file mode 120000 index 0000000000..8daec1ddc5 --- /dev/null +++ b/Lang/Lang5/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Lang5 \ No newline at end of file diff --git a/Lang/Lang5/Tokenize-a-string b/Lang/Lang5/Tokenize-a-string new file mode 120000 index 0000000000..719ccd586b --- /dev/null +++ b/Lang/Lang5/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Lang5 \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Shell-one-liner b/Lang/Liberty-BASIC/Shell-one-liner new file mode 120000 index 0000000000..4a43a15790 --- /dev/null +++ b/Lang/Liberty-BASIC/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Short-circuit-evaluation b/Lang/Liberty-BASIC/Short-circuit-evaluation new file mode 120000 index 0000000000..27b604d03a --- /dev/null +++ b/Lang/Liberty-BASIC/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sierpinski-carpet b/Lang/Liberty-BASIC/Sierpinski-carpet new file mode 120000 index 0000000000..fb8d572445 --- /dev/null +++ b/Lang/Liberty-BASIC/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sierpinski-triangle b/Lang/Liberty-BASIC/Sierpinski-triangle new file mode 120000 index 0000000000..483406d468 --- /dev/null +++ b/Lang/Liberty-BASIC/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sierpinski-triangle-Graphical b/Lang/Liberty-BASIC/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..6a673a3f5e --- /dev/null +++ b/Lang/Liberty-BASIC/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sieve-of-Eratosthenes b/Lang/Liberty-BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2557b418e9 --- /dev/null +++ b/Lang/Liberty-BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Simple-windowed-application b/Lang/Liberty-BASIC/Simple-windowed-application new file mode 120000 index 0000000000..9eae54bb0b --- /dev/null +++ b/Lang/Liberty-BASIC/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sleep b/Lang/Liberty-BASIC/Sleep new file mode 120000 index 0000000000..d10f586d93 --- /dev/null +++ b/Lang/Liberty-BASIC/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sort-an-array-of-composite-structures b/Lang/Liberty-BASIC/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..350d2e9f19 --- /dev/null +++ b/Lang/Liberty-BASIC/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sort-an-integer-array b/Lang/Liberty-BASIC/Sort-an-integer-array new file mode 120000 index 0000000000..12f86cd87e --- /dev/null +++ b/Lang/Liberty-BASIC/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Bubble-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b00aaa7ec0 --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Heapsort b/Lang/Liberty-BASIC/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..1d74aa3824 --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Insertion-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..abc9fb6c5b --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Merge-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..1dc0b03d4f --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Selection-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..9adde347bd --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Speech-synthesis b/Lang/Liberty-BASIC/Speech-synthesis new file mode 120000 index 0000000000..4a21356fee --- /dev/null +++ b/Lang/Liberty-BASIC/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Spiral-matrix b/Lang/Liberty-BASIC/Spiral-matrix new file mode 120000 index 0000000000..b19ab57685 --- /dev/null +++ b/Lang/Liberty-BASIC/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Stack b/Lang/Liberty-BASIC/Stack new file mode 120000 index 0000000000..5f22ee7fde --- /dev/null +++ b/Lang/Liberty-BASIC/Stack @@ -0,0 +1 @@ +../../Task/Stack/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Stair-climbing-puzzle b/Lang/Liberty-BASIC/Stair-climbing-puzzle new file mode 120000 index 0000000000..e4e8e4bfb4 --- /dev/null +++ b/Lang/Liberty-BASIC/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Standard-deviation b/Lang/Liberty-BASIC/Standard-deviation new file mode 120000 index 0000000000..b06b9cf188 --- /dev/null +++ b/Lang/Liberty-BASIC/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/String-case b/Lang/Liberty-BASIC/String-case new file mode 120000 index 0000000000..597afb5d79 --- /dev/null +++ b/Lang/Liberty-BASIC/String-case @@ -0,0 +1 @@ +../../Task/String-case/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Strip-a-set-of-characters-from-a-string b/Lang/Liberty-BASIC/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a82a61cc2f --- /dev/null +++ b/Lang/Liberty-BASIC/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Strip-block-comments b/Lang/Liberty-BASIC/Strip-block-comments new file mode 120000 index 0000000000..258367f18c --- /dev/null +++ b/Lang/Liberty-BASIC/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Strip-comments-from-a-string b/Lang/Liberty-BASIC/Strip-comments-from-a-string new file mode 120000 index 0000000000..34c9ede1b8 --- /dev/null +++ b/Lang/Liberty-BASIC/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Liberty-BASIC/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..94204e631a --- /dev/null +++ b/Lang/Liberty-BASIC/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Liberty-BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..337e688ef5 --- /dev/null +++ b/Lang/Liberty-BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Substring b/Lang/Liberty-BASIC/Substring new file mode 120000 index 0000000000..918007d2b6 --- /dev/null +++ b/Lang/Liberty-BASIC/Substring @@ -0,0 +1 @@ +../../Task/Substring/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Substring-Top-and-tail b/Lang/Liberty-BASIC/Substring-Top-and-tail new file mode 120000 index 0000000000..9f61d08d25 --- /dev/null +++ b/Lang/Liberty-BASIC/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sum-and-product-of-an-array b/Lang/Liberty-BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..80c160ba03 --- /dev/null +++ b/Lang/Liberty-BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sum-of-a-series b/Lang/Liberty-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..b99f455075 --- /dev/null +++ b/Lang/Liberty-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sum-of-squares b/Lang/Liberty-BASIC/Sum-of-squares new file mode 120000 index 0000000000..ccf75f98c2 --- /dev/null +++ b/Lang/Liberty-BASIC/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/System-time b/Lang/Liberty-BASIC/System-time new file mode 120000 index 0000000000..31395e276c --- /dev/null +++ b/Lang/Liberty-BASIC/System-time @@ -0,0 +1 @@ +../../Task/System-time/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Terminal-control-Cursor-positioning b/Lang/Liberty-BASIC/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..682a4832ab --- /dev/null +++ b/Lang/Liberty-BASIC/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Ternary-logic b/Lang/Liberty-BASIC/Ternary-logic new file mode 120000 index 0000000000..fb9384f5bc --- /dev/null +++ b/Lang/Liberty-BASIC/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Tokenize-a-string b/Lang/Liberty-BASIC/Tokenize-a-string new file mode 120000 index 0000000000..59a66cdddd --- /dev/null +++ b/Lang/Liberty-BASIC/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Towers-of-Hanoi b/Lang/Liberty-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..91a13767b1 --- /dev/null +++ b/Lang/Liberty-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Trigonometric-functions b/Lang/Liberty-BASIC/Trigonometric-functions new file mode 120000 index 0000000000..a47b191104 --- /dev/null +++ b/Lang/Liberty-BASIC/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Truncate-a-file b/Lang/Liberty-BASIC/Truncate-a-file new file mode 120000 index 0000000000..498b3d0a44 --- /dev/null +++ b/Lang/Liberty-BASIC/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/URL-decoding b/Lang/Liberty-BASIC/URL-decoding new file mode 120000 index 0000000000..eb94c28d2f --- /dev/null +++ b/Lang/Liberty-BASIC/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/URL-encoding b/Lang/Liberty-BASIC/URL-encoding new file mode 120000 index 0000000000..8ee7621dc9 --- /dev/null +++ b/Lang/Liberty-BASIC/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Unbias-a-random-generator b/Lang/Liberty-BASIC/Unbias-a-random-generator new file mode 120000 index 0000000000..8d58a30fe3 --- /dev/null +++ b/Lang/Liberty-BASIC/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/User-input-Graphical b/Lang/Liberty-BASIC/User-input-Graphical new file mode 120000 index 0000000000..c2c6880437 --- /dev/null +++ b/Lang/Liberty-BASIC/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/User-input-Text b/Lang/Liberty-BASIC/User-input-Text new file mode 120000 index 0000000000..2a1226f41d --- /dev/null +++ b/Lang/Liberty-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Variables b/Lang/Liberty-BASIC/Variables new file mode 120000 index 0000000000..9a9c7969fe --- /dev/null +++ b/Lang/Liberty-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Vector-products b/Lang/Liberty-BASIC/Vector-products new file mode 120000 index 0000000000..2e6105a0ee --- /dev/null +++ b/Lang/Liberty-BASIC/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Vigen-re-cipher b/Lang/Liberty-BASIC/Vigen-re-cipher new file mode 120000 index 0000000000..bf9fabf5e0 --- /dev/null +++ b/Lang/Liberty-BASIC/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Voronoi-diagram b/Lang/Liberty-BASIC/Voronoi-diagram new file mode 120000 index 0000000000..b4251bb506 --- /dev/null +++ b/Lang/Liberty-BASIC/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Web-scraping b/Lang/Liberty-BASIC/Web-scraping new file mode 120000 index 0000000000..39001d2705 --- /dev/null +++ b/Lang/Liberty-BASIC/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Window-creation b/Lang/Liberty-BASIC/Window-creation new file mode 120000 index 0000000000..7ae07ab7d1 --- /dev/null +++ b/Lang/Liberty-BASIC/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Wireworld b/Lang/Liberty-BASIC/Wireworld new file mode 120000 index 0000000000..92e3bd1c8c --- /dev/null +++ b/Lang/Liberty-BASIC/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Xiaolin-Wus-line-algorithm b/Lang/Liberty-BASIC/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..9a18e2da6c --- /dev/null +++ b/Lang/Liberty-BASIC/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Yin-and-yang b/Lang/Liberty-BASIC/Yin-and-yang new file mode 120000 index 0000000000..f84b3ed075 --- /dev/null +++ b/Lang/Liberty-BASIC/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Lisaac/Sorting-algorithms-Bubble-sort b/Lang/Lisaac/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..d96af04a39 --- /dev/null +++ b/Lang/Lisaac/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Lisaac \ No newline at end of file diff --git a/Lang/Lisaac/Sorting-algorithms-Shell-sort b/Lang/Lisaac/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..0e75c660d4 --- /dev/null +++ b/Lang/Lisaac/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Lisaac \ No newline at end of file diff --git a/Lang/Lisaac/String-concatenation b/Lang/Lisaac/String-concatenation new file mode 120000 index 0000000000..b588d87b26 --- /dev/null +++ b/Lang/Lisaac/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Lisaac \ No newline at end of file diff --git a/Lang/Lisaac/Use-another-language-to-call-a-function b/Lang/Lisaac/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..b030b12094 --- /dev/null +++ b/Lang/Lisaac/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Lisaac \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Speech-synthesis b/Lang/Locomotive-Basic/Speech-synthesis new file mode 120000 index 0000000000..568d383787 --- /dev/null +++ b/Lang/Locomotive-Basic/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Substring-Top-and-tail b/Lang/Locomotive-Basic/Substring-Top-and-tail new file mode 120000 index 0000000000..4418f409f3 --- /dev/null +++ b/Lang/Locomotive-Basic/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/System-time b/Lang/Locomotive-Basic/System-time new file mode 120000 index 0000000000..71b074beeb --- /dev/null +++ b/Lang/Locomotive-Basic/System-time @@ -0,0 +1 @@ +../../Task/System-time/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Terminal-control-Dimensions b/Lang/Locomotive-Basic/Terminal-control-Dimensions new file mode 120000 index 0000000000..00e65ce76e --- /dev/null +++ b/Lang/Locomotive-Basic/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Terminal-control-Display-an-extended-character b/Lang/Locomotive-Basic/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..1f7eb76fdc --- /dev/null +++ b/Lang/Locomotive-Basic/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Terminal-control-Hiding-the-cursor b/Lang/Locomotive-Basic/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..41f77b666f --- /dev/null +++ b/Lang/Locomotive-Basic/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Unicode-strings b/Lang/Locomotive-Basic/Unicode-strings new file mode 120000 index 0000000000..8747515dbb --- /dev/null +++ b/Lang/Locomotive-Basic/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Video-display-modes b/Lang/Locomotive-Basic/Video-display-modes new file mode 120000 index 0000000000..779d0deb55 --- /dev/null +++ b/Lang/Locomotive-Basic/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Logo/Short-circuit-evaluation b/Lang/Logo/Short-circuit-evaluation new file mode 120000 index 0000000000..53d65471ac --- /dev/null +++ b/Lang/Logo/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Logo \ No newline at end of file diff --git a/Lang/Logo/Sierpinski-triangle b/Lang/Logo/Sierpinski-triangle new file mode 120000 index 0000000000..e2624b0b02 --- /dev/null +++ b/Lang/Logo/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Logo \ No newline at end of file diff --git a/Lang/Logo/Sierpinski-triangle-Graphical b/Lang/Logo/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..f3f66bec1a --- /dev/null +++ b/Lang/Logo/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Logo \ No newline at end of file diff --git a/Lang/Logo/Simple-windowed-application b/Lang/Logo/Simple-windowed-application new file mode 120000 index 0000000000..435e197ba5 --- /dev/null +++ b/Lang/Logo/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Logo \ No newline at end of file diff --git a/Lang/Logo/Singly-linked-list-Element-definition b/Lang/Logo/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..af8ce107eb --- /dev/null +++ b/Lang/Logo/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Logo \ No newline at end of file diff --git a/Lang/Logo/Singly-linked-list-Element-insertion b/Lang/Logo/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..baff8a260e --- /dev/null +++ b/Lang/Logo/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Logo \ No newline at end of file diff --git a/Lang/Logo/Singly-linked-list-Traversal b/Lang/Logo/Singly-linked-list-Traversal new file mode 120000 index 0000000000..b26d5109ce --- /dev/null +++ b/Lang/Logo/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Logo \ No newline at end of file diff --git a/Lang/Logo/Sleep b/Lang/Logo/Sleep new file mode 120000 index 0000000000..2e6306741c --- /dev/null +++ b/Lang/Logo/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Logo \ No newline at end of file diff --git a/Lang/Logo/Sorting-algorithms-Merge-sort b/Lang/Logo/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..b60bbcacf5 --- /dev/null +++ b/Lang/Logo/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Logo \ No newline at end of file diff --git a/Lang/Logo/Sorting-algorithms-Quicksort b/Lang/Logo/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..6007b6b011 --- /dev/null +++ b/Lang/Logo/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Logo \ No newline at end of file diff --git a/Lang/Logo/Stack b/Lang/Logo/Stack new file mode 120000 index 0000000000..64d533768a --- /dev/null +++ b/Lang/Logo/Stack @@ -0,0 +1 @@ +../../Task/Stack/Logo \ No newline at end of file diff --git a/Lang/Logo/Stair-climbing-puzzle b/Lang/Logo/Stair-climbing-puzzle new file mode 120000 index 0000000000..97bd78c71b --- /dev/null +++ b/Lang/Logo/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Logo \ No newline at end of file diff --git a/Lang/Logo/String-concatenation b/Lang/Logo/String-concatenation new file mode 120000 index 0000000000..105e932c3e --- /dev/null +++ b/Lang/Logo/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Logo \ No newline at end of file diff --git a/Lang/Logo/String-length b/Lang/Logo/String-length new file mode 120000 index 0000000000..1abe155267 --- /dev/null +++ b/Lang/Logo/String-length @@ -0,0 +1 @@ +../../Task/String-length/Logo \ No newline at end of file diff --git a/Lang/Logo/Strip-a-set-of-characters-from-a-string b/Lang/Logo/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..0aa8fbc421 --- /dev/null +++ b/Lang/Logo/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Logo \ No newline at end of file diff --git a/Lang/Logo/Substring b/Lang/Logo/Substring new file mode 120000 index 0000000000..59dd7707f7 --- /dev/null +++ b/Lang/Logo/Substring @@ -0,0 +1 @@ +../../Task/Substring/Logo \ No newline at end of file diff --git a/Lang/Logo/Sum-and-product-of-an-array b/Lang/Logo/Sum-and-product-of-an-array new file mode 120000 index 0000000000..91f8050d89 --- /dev/null +++ b/Lang/Logo/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Logo \ No newline at end of file diff --git a/Lang/Logo/Sum-of-a-series b/Lang/Logo/Sum-of-a-series new file mode 120000 index 0000000000..7c7dcabd3d --- /dev/null +++ b/Lang/Logo/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Logo \ No newline at end of file diff --git a/Lang/Logo/Sum-of-squares b/Lang/Logo/Sum-of-squares new file mode 120000 index 0000000000..869401c3f8 --- /dev/null +++ b/Lang/Logo/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Logo \ No newline at end of file diff --git a/Lang/Logo/Symmetric-difference b/Lang/Logo/Symmetric-difference new file mode 120000 index 0000000000..5cc44460c5 --- /dev/null +++ b/Lang/Logo/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Logo \ No newline at end of file diff --git a/Lang/Logo/System-time b/Lang/Logo/System-time new file mode 120000 index 0000000000..8dca0ac88c --- /dev/null +++ b/Lang/Logo/System-time @@ -0,0 +1 @@ +../../Task/System-time/Logo \ No newline at end of file diff --git a/Lang/Logo/Terminal-control-Clear-the-screen b/Lang/Logo/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..1ae0978dc4 --- /dev/null +++ b/Lang/Logo/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Logo \ No newline at end of file diff --git a/Lang/Logo/Terminal-control-Cursor-positioning b/Lang/Logo/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..a861aca292 --- /dev/null +++ b/Lang/Logo/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Logo \ No newline at end of file diff --git a/Lang/Logo/Terminal-control-Ringing-the-terminal-bell b/Lang/Logo/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..dddc8e9518 --- /dev/null +++ b/Lang/Logo/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Logo \ No newline at end of file diff --git a/Lang/Logo/Time-a-function b/Lang/Logo/Time-a-function new file mode 120000 index 0000000000..482e0c5c4d --- /dev/null +++ b/Lang/Logo/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Logo \ No newline at end of file diff --git a/Lang/Logo/Tokenize-a-string b/Lang/Logo/Tokenize-a-string new file mode 120000 index 0000000000..f50eb1a58d --- /dev/null +++ b/Lang/Logo/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Logo \ No newline at end of file diff --git a/Lang/Logo/Towers-of-Hanoi b/Lang/Logo/Towers-of-Hanoi new file mode 120000 index 0000000000..29ff91fcc9 --- /dev/null +++ b/Lang/Logo/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Logo \ No newline at end of file diff --git a/Lang/Logo/Tree-traversal b/Lang/Logo/Tree-traversal new file mode 120000 index 0000000000..7ac692328d --- /dev/null +++ b/Lang/Logo/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Logo \ No newline at end of file diff --git a/Lang/Logo/Trigonometric-functions b/Lang/Logo/Trigonometric-functions new file mode 120000 index 0000000000..9c87c88054 --- /dev/null +++ b/Lang/Logo/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Logo \ No newline at end of file diff --git a/Lang/Logo/Undefined-values b/Lang/Logo/Undefined-values new file mode 120000 index 0000000000..eda0f5ff1d --- /dev/null +++ b/Lang/Logo/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Logo \ No newline at end of file diff --git a/Lang/Logo/User-input-Text b/Lang/Logo/User-input-Text new file mode 120000 index 0000000000..fbcca9d278 --- /dev/null +++ b/Lang/Logo/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Logo \ No newline at end of file diff --git a/Lang/Logo/Variables b/Lang/Logo/Variables new file mode 120000 index 0000000000..66fde947e5 --- /dev/null +++ b/Lang/Logo/Variables @@ -0,0 +1 @@ +../../Task/Variables/Logo \ No newline at end of file diff --git a/Lang/Logo/Variadic-function b/Lang/Logo/Variadic-function new file mode 120000 index 0000000000..8fa4fdc024 --- /dev/null +++ b/Lang/Logo/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Logo \ No newline at end of file diff --git a/Lang/Logo/Wireworld b/Lang/Logo/Wireworld new file mode 120000 index 0000000000..a7c44c1101 --- /dev/null +++ b/Lang/Logo/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Logo \ No newline at end of file diff --git a/Lang/Logo/Yin-and-yang b/Lang/Logo/Yin-and-yang new file mode 120000 index 0000000000..96edfc18e5 --- /dev/null +++ b/Lang/Logo/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Logo \ No newline at end of file diff --git a/Lang/Logtalk/Singleton b/Lang/Logtalk/Singleton new file mode 120000 index 0000000000..df2d285cac --- /dev/null +++ b/Lang/Logtalk/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Sorting-algorithms-Merge-sort b/Lang/Logtalk/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..b809766c74 --- /dev/null +++ b/Lang/Logtalk/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Sorting-algorithms-Quicksort b/Lang/Logtalk/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..73117e805a --- /dev/null +++ b/Lang/Logtalk/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Sum-of-squares b/Lang/Logtalk/Sum-of-squares new file mode 120000 index 0000000000..89bb282b0b --- /dev/null +++ b/Lang/Logtalk/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Towers-of-Hanoi b/Lang/Logtalk/Towers-of-Hanoi new file mode 120000 index 0000000000..239396508f --- /dev/null +++ b/Lang/Logtalk/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Logtalk \ No newline at end of file diff --git a/Lang/LotusScript/Sorting-algorithms-Heapsort b/Lang/LotusScript/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..d31d098e4a --- /dev/null +++ b/Lang/LotusScript/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/LotusScript \ No newline at end of file diff --git a/Lang/LotusScript/Variables b/Lang/LotusScript/Variables new file mode 120000 index 0000000000..96ac1074f7 --- /dev/null +++ b/Lang/LotusScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/LotusScript \ No newline at end of file diff --git a/Lang/Lua/Seven-sided-dice-from-five-sided-dice b/Lang/Lua/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..4e999fab42 --- /dev/null +++ b/Lang/Lua/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Lua \ No newline at end of file diff --git a/Lang/Lua/Shell-one-liner b/Lang/Lua/Shell-one-liner new file mode 120000 index 0000000000..abe984a60f --- /dev/null +++ b/Lang/Lua/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Lua \ No newline at end of file diff --git a/Lang/Lua/Short-circuit-evaluation b/Lang/Lua/Short-circuit-evaluation new file mode 120000 index 0000000000..d9f7fdd89e --- /dev/null +++ b/Lang/Lua/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Lua \ No newline at end of file diff --git a/Lang/Lua/Sieve-of-Eratosthenes b/Lang/Lua/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..4a85f8f632 --- /dev/null +++ b/Lang/Lua/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Lua \ No newline at end of file diff --git a/Lang/Lua/Simple-windowed-application b/Lang/Lua/Simple-windowed-application new file mode 120000 index 0000000000..c4915a7d35 --- /dev/null +++ b/Lang/Lua/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Lua \ No newline at end of file diff --git a/Lang/Lua/Sockets b/Lang/Lua/Sockets new file mode 120000 index 0000000000..0441a3c1cb --- /dev/null +++ b/Lang/Lua/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Lua \ No newline at end of file diff --git a/Lang/Lua/Sort-an-array-of-composite-structures b/Lang/Lua/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..014e97cb2e --- /dev/null +++ b/Lang/Lua/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Lua \ No newline at end of file diff --git a/Lang/Lua/Sort-an-integer-array b/Lang/Lua/Sort-an-integer-array new file mode 120000 index 0000000000..17c06af410 --- /dev/null +++ b/Lang/Lua/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Lua \ No newline at end of file diff --git a/Lang/Lua/Sort-disjoint-sublist b/Lang/Lua/Sort-disjoint-sublist new file mode 120000 index 0000000000..d1f04f2182 --- /dev/null +++ b/Lang/Lua/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Lua \ No newline at end of file diff --git a/Lang/Lua/Sort-using-a-custom-comparator b/Lang/Lua/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..e7d7ca2885 --- /dev/null +++ b/Lang/Lua/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Bogosort b/Lang/Lua/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..44f2bff8e3 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Bubble-sort b/Lang/Lua/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b5803402aa --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Cocktail-sort b/Lang/Lua/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..0e6da419e1 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Comb-sort b/Lang/Lua/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..2cde94542e --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Counting-sort b/Lang/Lua/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..352d511f62 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Gnome-sort b/Lang/Lua/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..c8624f4a36 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Insertion-sort b/Lang/Lua/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..92e5737ade --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Quicksort b/Lang/Lua/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..3a8a231c62 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Selection-sort b/Lang/Lua/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..6f66e33174 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Shell-sort b/Lang/Lua/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..e36ec41ed8 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Stooge-sort b/Lang/Lua/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..63ed28e7ca --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Spiral-matrix b/Lang/Lua/Spiral-matrix new file mode 120000 index 0000000000..ee2c603ead --- /dev/null +++ b/Lang/Lua/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Lua \ No newline at end of file diff --git a/Lang/Lua/Stable-marriage-problem b/Lang/Lua/Stable-marriage-problem new file mode 120000 index 0000000000..7d2f2da64b --- /dev/null +++ b/Lang/Lua/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Lua \ No newline at end of file diff --git a/Lang/Lua/Stack b/Lang/Lua/Stack new file mode 120000 index 0000000000..9e50788047 --- /dev/null +++ b/Lang/Lua/Stack @@ -0,0 +1 @@ +../../Task/Stack/Lua \ No newline at end of file diff --git a/Lang/Lua/Stack-traces b/Lang/Lua/Stack-traces new file mode 120000 index 0000000000..3f6c7a2229 --- /dev/null +++ b/Lang/Lua/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Lua \ No newline at end of file diff --git a/Lang/Lua/Stair-climbing-puzzle b/Lang/Lua/Stair-climbing-puzzle new file mode 120000 index 0000000000..a69f808449 --- /dev/null +++ b/Lang/Lua/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Lua \ No newline at end of file diff --git a/Lang/Lua/Stem-and-leaf-plot b/Lang/Lua/Stem-and-leaf-plot new file mode 120000 index 0000000000..34d70aa97d --- /dev/null +++ b/Lang/Lua/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Lua \ No newline at end of file diff --git a/Lang/Lua/String-case b/Lang/Lua/String-case new file mode 120000 index 0000000000..cba0f6b495 --- /dev/null +++ b/Lang/Lua/String-case @@ -0,0 +1 @@ +../../Task/String-case/Lua \ No newline at end of file diff --git a/Lang/Lua/String-interpolation--included- b/Lang/Lua/String-interpolation--included- new file mode 120000 index 0000000000..1b77ad3c00 --- /dev/null +++ b/Lang/Lua/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Lua \ No newline at end of file diff --git a/Lang/Lua/String-length b/Lang/Lua/String-length new file mode 120000 index 0000000000..77e43b96bb --- /dev/null +++ b/Lang/Lua/String-length @@ -0,0 +1 @@ +../../Task/String-length/Lua \ No newline at end of file diff --git a/Lang/Lua/Strip-a-set-of-characters-from-a-string b/Lang/Lua/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..015b9a468d --- /dev/null +++ b/Lang/Lua/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Lua \ No newline at end of file diff --git a/Lang/Lua/Strip-block-comments b/Lang/Lua/Strip-block-comments new file mode 120000 index 0000000000..62b2f49fe0 --- /dev/null +++ b/Lang/Lua/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Lua \ No newline at end of file diff --git a/Lang/Lua/Strip-comments-from-a-string b/Lang/Lua/Strip-comments-from-a-string new file mode 120000 index 0000000000..d4e0d34a7b --- /dev/null +++ b/Lang/Lua/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Lua \ No newline at end of file diff --git a/Lang/Lua/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Lua/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..3c1e6c04aa --- /dev/null +++ b/Lang/Lua/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Lua \ No newline at end of file diff --git a/Lang/Lua/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Lua/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..c39ab0f18c --- /dev/null +++ b/Lang/Lua/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Lua \ No newline at end of file diff --git a/Lang/Lua/Substring b/Lang/Lua/Substring new file mode 120000 index 0000000000..f8ba0bcd2f --- /dev/null +++ b/Lang/Lua/Substring @@ -0,0 +1 @@ +../../Task/Substring/Lua \ No newline at end of file diff --git a/Lang/Lua/Substring-Top-and-tail b/Lang/Lua/Substring-Top-and-tail new file mode 120000 index 0000000000..ca91af06dc --- /dev/null +++ b/Lang/Lua/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-and-product-of-an-array b/Lang/Lua/Sum-and-product-of-an-array new file mode 120000 index 0000000000..89bd3e984f --- /dev/null +++ b/Lang/Lua/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-of-a-series b/Lang/Lua/Sum-of-a-series new file mode 120000 index 0000000000..4db87dc0bf --- /dev/null +++ b/Lang/Lua/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-of-squares b/Lang/Lua/Sum-of-squares new file mode 120000 index 0000000000..cca0d9e7b3 --- /dev/null +++ b/Lang/Lua/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Lua \ No newline at end of file diff --git a/Lang/Lua/Sutherland-Hodgman-polygon-clipping b/Lang/Lua/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..782367a5d8 --- /dev/null +++ b/Lang/Lua/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Lua \ No newline at end of file diff --git a/Lang/Lua/Symmetric-difference b/Lang/Lua/Symmetric-difference new file mode 120000 index 0000000000..d4f0a82f76 --- /dev/null +++ b/Lang/Lua/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Lua \ No newline at end of file diff --git a/Lang/Lua/Synchronous-concurrency b/Lang/Lua/Synchronous-concurrency new file mode 120000 index 0000000000..4cd5596c64 --- /dev/null +++ b/Lang/Lua/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Lua \ No newline at end of file diff --git a/Lang/Lua/System-time b/Lang/Lua/System-time new file mode 120000 index 0000000000..5d6a66f02b --- /dev/null +++ b/Lang/Lua/System-time @@ -0,0 +1 @@ +../../Task/System-time/Lua \ No newline at end of file diff --git a/Lang/Lua/Take-notes-on-the-command-line b/Lang/Lua/Take-notes-on-the-command-line new file mode 120000 index 0000000000..56b5ac0d73 --- /dev/null +++ b/Lang/Lua/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Lua \ No newline at end of file diff --git a/Lang/Lua/Terminal-control-Clear-the-screen b/Lang/Lua/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..e9f29a70aa --- /dev/null +++ b/Lang/Lua/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Lua \ No newline at end of file diff --git a/Lang/Lua/Test-a-function b/Lang/Lua/Test-a-function new file mode 120000 index 0000000000..555098b6ce --- /dev/null +++ b/Lang/Lua/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Text-processing-1 b/Lang/Lua/Text-processing-1 new file mode 120000 index 0000000000..096a8e1fce --- /dev/null +++ b/Lang/Lua/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Lua \ No newline at end of file diff --git a/Lang/Lua/Text-processing-2 b/Lang/Lua/Text-processing-2 new file mode 120000 index 0000000000..404aeeeb87 --- /dev/null +++ b/Lang/Lua/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Lua \ No newline at end of file diff --git a/Lang/Lua/Text-processing-Max-licenses-in-use b/Lang/Lua/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8c312ea011 --- /dev/null +++ b/Lang/Lua/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Lua \ No newline at end of file diff --git a/Lang/Lua/Time-a-function b/Lang/Lua/Time-a-function new file mode 120000 index 0000000000..20ccc38078 --- /dev/null +++ b/Lang/Lua/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Tokenize-a-string b/Lang/Lua/Tokenize-a-string new file mode 120000 index 0000000000..535c271262 --- /dev/null +++ b/Lang/Lua/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Lua \ No newline at end of file diff --git a/Lang/Lua/Top-rank-per-group b/Lang/Lua/Top-rank-per-group new file mode 120000 index 0000000000..9be40d902d --- /dev/null +++ b/Lang/Lua/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Lua \ No newline at end of file diff --git a/Lang/Lua/Towers-of-Hanoi b/Lang/Lua/Towers-of-Hanoi new file mode 120000 index 0000000000..219fca0290 --- /dev/null +++ b/Lang/Lua/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Lua \ No newline at end of file diff --git a/Lang/Lua/Trigonometric-functions b/Lang/Lua/Trigonometric-functions new file mode 120000 index 0000000000..1290d60c45 --- /dev/null +++ b/Lang/Lua/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Lua \ No newline at end of file diff --git a/Lang/Lua/Truncatable-primes b/Lang/Lua/Truncatable-primes new file mode 120000 index 0000000000..b8c7b652d8 --- /dev/null +++ b/Lang/Lua/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Unbias-a-random-generator b/Lang/Lua/Unbias-a-random-generator new file mode 120000 index 0000000000..ff83c06e9e --- /dev/null +++ b/Lang/Lua/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Lua \ No newline at end of file diff --git a/Lang/Lua/Undefined-values b/Lang/Lua/Undefined-values new file mode 120000 index 0000000000..cfd5bee6e5 --- /dev/null +++ b/Lang/Lua/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Lua \ No newline at end of file diff --git a/Lang/Lua/Unicode-variable-names b/Lang/Lua/Unicode-variable-names new file mode 120000 index 0000000000..92bda9b1c8 --- /dev/null +++ b/Lang/Lua/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Lua \ No newline at end of file diff --git a/Lang/Lua/User-input-Text b/Lang/Lua/User-input-Text new file mode 120000 index 0000000000..862205fed5 --- /dev/null +++ b/Lang/Lua/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Lua \ No newline at end of file diff --git a/Lang/Lua/Variables b/Lang/Lua/Variables new file mode 120000 index 0000000000..4f78c5d638 --- /dev/null +++ b/Lang/Lua/Variables @@ -0,0 +1 @@ +../../Task/Variables/Lua \ No newline at end of file diff --git a/Lang/Lua/Variadic-function b/Lang/Lua/Variadic-function new file mode 120000 index 0000000000..3315027285 --- /dev/null +++ b/Lang/Lua/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Vector-products b/Lang/Lua/Vector-products new file mode 120000 index 0000000000..ebc5b76b3c --- /dev/null +++ b/Lang/Lua/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Lua \ No newline at end of file diff --git a/Lang/Lua/Vigen-re-cipher b/Lang/Lua/Vigen-re-cipher new file mode 120000 index 0000000000..2e524ebbc6 --- /dev/null +++ b/Lang/Lua/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Lua \ No newline at end of file diff --git a/Lang/Lua/Walk-a-directory-Non-recursively b/Lang/Lua/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9ccca7f3be --- /dev/null +++ b/Lang/Lua/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Lua \ No newline at end of file diff --git a/Lang/Lua/Window-creation b/Lang/Lua/Window-creation new file mode 120000 index 0000000000..cd16247110 --- /dev/null +++ b/Lang/Lua/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Lua \ No newline at end of file diff --git a/Lang/Lua/Write-float-arrays-to-a-text-file b/Lang/Lua/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..97f5bdf829 --- /dev/null +++ b/Lang/Lua/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Lua \ No newline at end of file diff --git a/Lang/Lua/XML-Input b/Lang/Lua/XML-Input new file mode 120000 index 0000000000..844116e002 --- /dev/null +++ b/Lang/Lua/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Lua \ No newline at end of file diff --git a/Lang/Lua/XML-XPath b/Lang/Lua/XML-XPath new file mode 120000 index 0000000000..61924463e1 --- /dev/null +++ b/Lang/Lua/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Lua \ No newline at end of file diff --git a/Lang/Lua/Y-combinator b/Lang/Lua/Y-combinator new file mode 120000 index 0000000000..3823155799 --- /dev/null +++ b/Lang/Lua/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Lua \ No newline at end of file diff --git a/Lang/Lua/Zig-zag-matrix b/Lang/Lua/Zig-zag-matrix new file mode 120000 index 0000000000..04e19ef68d --- /dev/null +++ b/Lang/Lua/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Lua \ No newline at end of file diff --git a/Lang/Lucid/Sorting-algorithms-Bubble-sort b/Lang/Lucid/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..01fe9fbc2f --- /dev/null +++ b/Lang/Lucid/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Lucid \ No newline at end of file diff --git a/Lang/Lucid/Sorting-algorithms-Merge-sort b/Lang/Lucid/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..c7eb03640b --- /dev/null +++ b/Lang/Lucid/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Lucid \ No newline at end of file diff --git a/Lang/Lucid/Sorting-algorithms-Quicksort b/Lang/Lucid/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..677c635084 --- /dev/null +++ b/Lang/Lucid/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Lucid \ No newline at end of file diff --git a/Lang/Lucid/Sum-and-product-of-an-array b/Lang/Lucid/Sum-and-product-of-an-array new file mode 120000 index 0000000000..44efead16b --- /dev/null +++ b/Lang/Lucid/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Lucid \ No newline at end of file diff --git a/Lang/Lucid/Sum-of-a-series b/Lang/Lucid/Sum-of-a-series new file mode 120000 index 0000000000..50b1035854 --- /dev/null +++ b/Lang/Lucid/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Lucid \ No newline at end of file diff --git a/Lang/M4/Sieve-of-Eratosthenes b/Lang/M4/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..09044ee2c4 --- /dev/null +++ b/Lang/M4/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/M4 \ No newline at end of file diff --git a/Lang/M4/Sorting-algorithms-Bogosort b/Lang/M4/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..00026ba83f --- /dev/null +++ b/Lang/M4/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/M4 \ No newline at end of file diff --git a/Lang/M4/Sorting-algorithms-Bubble-sort b/Lang/M4/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ec7ad16793 --- /dev/null +++ b/Lang/M4/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/M4 \ No newline at end of file diff --git a/Lang/M4/Sorting-algorithms-Counting-sort b/Lang/M4/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..0ba811bf32 --- /dev/null +++ b/Lang/M4/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/M4 \ No newline at end of file diff --git a/Lang/M4/Sorting-algorithms-Heapsort b/Lang/M4/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..990f8662f7 --- /dev/null +++ b/Lang/M4/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/M4 \ No newline at end of file diff --git a/Lang/M4/Sorting-algorithms-Quicksort b/Lang/M4/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..8fc9077db6 --- /dev/null +++ b/Lang/M4/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/M4 \ No newline at end of file diff --git a/Lang/M4/String-case b/Lang/M4/String-case new file mode 120000 index 0000000000..66967344a7 --- /dev/null +++ b/Lang/M4/String-case @@ -0,0 +1 @@ +../../Task/String-case/M4 \ No newline at end of file diff --git a/Lang/M4/String-concatenation b/Lang/M4/String-concatenation new file mode 120000 index 0000000000..db7f7cee41 --- /dev/null +++ b/Lang/M4/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/M4 \ No newline at end of file diff --git a/Lang/M4/Text-processing-Max-licenses-in-use b/Lang/M4/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..9bb6f8ba92 --- /dev/null +++ b/Lang/M4/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/M4 \ No newline at end of file diff --git a/Lang/M4/Tokenize-a-string b/Lang/M4/Tokenize-a-string new file mode 120000 index 0000000000..6e158a9c77 --- /dev/null +++ b/Lang/M4/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/M4 \ No newline at end of file diff --git a/Lang/M4/Variadic-function b/Lang/M4/Variadic-function new file mode 120000 index 0000000000..d434e183f8 --- /dev/null +++ b/Lang/M4/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/M4 \ No newline at end of file diff --git a/Lang/M4/Zig-zag-matrix b/Lang/M4/Zig-zag-matrix new file mode 120000 index 0000000000..d139c38e9c --- /dev/null +++ b/Lang/M4/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/M4 \ No newline at end of file diff --git a/Lang/MATLAB/Short-circuit-evaluation b/Lang/MATLAB/Short-circuit-evaluation new file mode 120000 index 0000000000..2311bfd702 --- /dev/null +++ b/Lang/MATLAB/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Show-the-epoch b/Lang/MATLAB/Show-the-epoch new file mode 120000 index 0000000000..63b4b309dd --- /dev/null +++ b/Lang/MATLAB/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sieve-of-Eratosthenes b/Lang/MATLAB/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..1b2d0da420 --- /dev/null +++ b/Lang/MATLAB/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Singly-linked-list-Traversal b/Lang/MATLAB/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8aa0968e8c --- /dev/null +++ b/Lang/MATLAB/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sleep b/Lang/MATLAB/Sleep new file mode 120000 index 0000000000..2768ff4039 --- /dev/null +++ b/Lang/MATLAB/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sort-an-integer-array b/Lang/MATLAB/Sort-an-integer-array new file mode 120000 index 0000000000..48a6403c14 --- /dev/null +++ b/Lang/MATLAB/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Bogosort b/Lang/MATLAB/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..c09afc7a7a --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Bubble-sort b/Lang/MATLAB/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..e557e182bc --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Cocktail-sort b/Lang/MATLAB/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..141c646533 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Comb-sort b/Lang/MATLAB/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..1af971b13e --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Counting-sort b/Lang/MATLAB/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..1c188e3ffe --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Gnome-sort b/Lang/MATLAB/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..46e56eb171 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Heapsort b/Lang/MATLAB/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..dc9cbe75f9 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Insertion-sort b/Lang/MATLAB/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..a1e60d8835 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Merge-sort b/Lang/MATLAB/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..d472655f0a --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Pancake-sort b/Lang/MATLAB/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..47cb24cb73 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Permutation-sort b/Lang/MATLAB/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..a542f4e128 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Quicksort b/Lang/MATLAB/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f00bb004d1 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Selection-sort b/Lang/MATLAB/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..3e53bcfa55 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Shell-sort b/Lang/MATLAB/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..254d11ce81 --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sorting-algorithms-Stooge-sort b/Lang/MATLAB/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..502ad673ff --- /dev/null +++ b/Lang/MATLAB/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Spiral-matrix b/Lang/MATLAB/Spiral-matrix new file mode 120000 index 0000000000..2f00f01deb --- /dev/null +++ b/Lang/MATLAB/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Stack b/Lang/MATLAB/Stack new file mode 120000 index 0000000000..7ff507337d --- /dev/null +++ b/Lang/MATLAB/Stack @@ -0,0 +1 @@ +../../Task/Stack/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Stair-climbing-puzzle b/Lang/MATLAB/Stair-climbing-puzzle new file mode 120000 index 0000000000..018ea51958 --- /dev/null +++ b/Lang/MATLAB/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Stem-and-leaf-plot b/Lang/MATLAB/Stem-and-leaf-plot new file mode 120000 index 0000000000..1d90c77a65 --- /dev/null +++ b/Lang/MATLAB/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/String-case b/Lang/MATLAB/String-case new file mode 120000 index 0000000000..6eb0045514 --- /dev/null +++ b/Lang/MATLAB/String-case @@ -0,0 +1 @@ +../../Task/String-case/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/String-concatenation b/Lang/MATLAB/String-concatenation new file mode 120000 index 0000000000..9251558a67 --- /dev/null +++ b/Lang/MATLAB/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/String-length b/Lang/MATLAB/String-length new file mode 120000 index 0000000000..8856433c91 --- /dev/null +++ b/Lang/MATLAB/String-length @@ -0,0 +1 @@ +../../Task/String-length/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strip-a-set-of-characters-from-a-string b/Lang/MATLAB/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a984f12aae --- /dev/null +++ b/Lang/MATLAB/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strip-block-comments b/Lang/MATLAB/Strip-block-comments new file mode 120000 index 0000000000..5698f97c25 --- /dev/null +++ b/Lang/MATLAB/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strip-comments-from-a-string b/Lang/MATLAB/Strip-comments-from-a-string new file mode 120000 index 0000000000..4191bf0962 --- /dev/null +++ b/Lang/MATLAB/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strip-control-codes-and-extended-characters-from-a-string b/Lang/MATLAB/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..26d078d2df --- /dev/null +++ b/Lang/MATLAB/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strip-whitespace-from-a-string-Top-and-tail b/Lang/MATLAB/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..f57ccaca1b --- /dev/null +++ b/Lang/MATLAB/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Substring b/Lang/MATLAB/Substring new file mode 120000 index 0000000000..8a18df1e55 --- /dev/null +++ b/Lang/MATLAB/Substring @@ -0,0 +1 @@ +../../Task/Substring/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Substring-Top-and-tail b/Lang/MATLAB/Substring-Top-and-tail new file mode 120000 index 0000000000..4dfc7c8a36 --- /dev/null +++ b/Lang/MATLAB/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sudoku b/Lang/MATLAB/Sudoku new file mode 120000 index 0000000000..261e0c9de0 --- /dev/null +++ b/Lang/MATLAB/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sum-and-product-of-an-array b/Lang/MATLAB/Sum-and-product-of-an-array new file mode 120000 index 0000000000..37e66056ba --- /dev/null +++ b/Lang/MATLAB/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sum-of-a-series b/Lang/MATLAB/Sum-of-a-series new file mode 120000 index 0000000000..8c40a98582 --- /dev/null +++ b/Lang/MATLAB/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sum-of-squares b/Lang/MATLAB/Sum-of-squares new file mode 120000 index 0000000000..6f7b94c448 --- /dev/null +++ b/Lang/MATLAB/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sutherland-Hodgman-polygon-clipping b/Lang/MATLAB/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..531f45812a --- /dev/null +++ b/Lang/MATLAB/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Symmetric-difference b/Lang/MATLAB/Symmetric-difference new file mode 120000 index 0000000000..fa1b97f381 --- /dev/null +++ b/Lang/MATLAB/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/System-time b/Lang/MATLAB/System-time new file mode 120000 index 0000000000..c997e72474 --- /dev/null +++ b/Lang/MATLAB/System-time @@ -0,0 +1 @@ +../../Task/System-time/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Take-notes-on-the-command-line b/Lang/MATLAB/Take-notes-on-the-command-line new file mode 120000 index 0000000000..c360d1fc3f --- /dev/null +++ b/Lang/MATLAB/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Text-processing-2 b/Lang/MATLAB/Text-processing-2 new file mode 120000 index 0000000000..d6ffd22e2f --- /dev/null +++ b/Lang/MATLAB/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Tokenize-a-string b/Lang/MATLAB/Tokenize-a-string new file mode 120000 index 0000000000..3eaf670a3d --- /dev/null +++ b/Lang/MATLAB/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Towers-of-Hanoi b/Lang/MATLAB/Towers-of-Hanoi new file mode 120000 index 0000000000..906f647a6a --- /dev/null +++ b/Lang/MATLAB/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Trigonometric-functions b/Lang/MATLAB/Trigonometric-functions new file mode 120000 index 0000000000..df61093d28 --- /dev/null +++ b/Lang/MATLAB/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Truncatable-primes b/Lang/MATLAB/Truncatable-primes new file mode 120000 index 0000000000..9cd6a0d6ff --- /dev/null +++ b/Lang/MATLAB/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Undefined-values b/Lang/MATLAB/Undefined-values new file mode 120000 index 0000000000..55a60b1dfb --- /dev/null +++ b/Lang/MATLAB/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/User-input-Text b/Lang/MATLAB/User-input-Text new file mode 120000 index 0000000000..5ea8289ec7 --- /dev/null +++ b/Lang/MATLAB/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Van-der-Corput-sequence b/Lang/MATLAB/Van-der-Corput-sequence new file mode 120000 index 0000000000..a33cb28470 --- /dev/null +++ b/Lang/MATLAB/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Variables b/Lang/MATLAB/Variables new file mode 120000 index 0000000000..df76240596 --- /dev/null +++ b/Lang/MATLAB/Variables @@ -0,0 +1 @@ +../../Task/Variables/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Variadic-function b/Lang/MATLAB/Variadic-function new file mode 120000 index 0000000000..6a6cbbc694 --- /dev/null +++ b/Lang/MATLAB/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Vector-products b/Lang/MATLAB/Vector-products new file mode 120000 index 0000000000..d0e655c7c1 --- /dev/null +++ b/Lang/MATLAB/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Write-float-arrays-to-a-text-file b/Lang/MATLAB/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..3939fc3325 --- /dev/null +++ b/Lang/MATLAB/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Zig-zag-matrix b/Lang/MATLAB/Zig-zag-matrix new file mode 120000 index 0000000000..d3335ee381 --- /dev/null +++ b/Lang/MATLAB/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/MATLAB \ No newline at end of file diff --git a/Lang/MAXScript/Simple-windowed-application b/Lang/MAXScript/Simple-windowed-application new file mode 120000 index 0000000000..631765d834 --- /dev/null +++ b/Lang/MAXScript/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sort-an-array-of-composite-structures b/Lang/MAXScript/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..08f6e46de3 --- /dev/null +++ b/Lang/MAXScript/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sort-an-integer-array b/Lang/MAXScript/Sort-an-integer-array new file mode 120000 index 0000000000..0ce1a83f3a --- /dev/null +++ b/Lang/MAXScript/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sort-using-a-custom-comparator b/Lang/MAXScript/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..e49b2b20b9 --- /dev/null +++ b/Lang/MAXScript/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Bogosort b/Lang/MAXScript/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2e044bf906 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Bubble-sort b/Lang/MAXScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..d58b54ad1b --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Cocktail-sort b/Lang/MAXScript/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..0701c0bd54 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Quicksort b/Lang/MAXScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..79fb45554c --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Selection-sort b/Lang/MAXScript/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..705a69922a --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/String-case b/Lang/MAXScript/String-case new file mode 120000 index 0000000000..d31dc5e1e0 --- /dev/null +++ b/Lang/MAXScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/String-concatenation b/Lang/MAXScript/String-concatenation new file mode 120000 index 0000000000..79499fe033 --- /dev/null +++ b/Lang/MAXScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/String-length b/Lang/MAXScript/String-length new file mode 120000 index 0000000000..c22b9ef558 --- /dev/null +++ b/Lang/MAXScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sum-and-product-of-an-array b/Lang/MAXScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c029f515ef --- /dev/null +++ b/Lang/MAXScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sum-of-a-series b/Lang/MAXScript/Sum-of-a-series new file mode 120000 index 0000000000..4d26f2e3d4 --- /dev/null +++ b/Lang/MAXScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Text-processing-Max-licenses-in-use b/Lang/MAXScript/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..2d75118a3d --- /dev/null +++ b/Lang/MAXScript/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Tokenize-a-string b/Lang/MAXScript/Tokenize-a-string new file mode 120000 index 0000000000..5164a704c5 --- /dev/null +++ b/Lang/MAXScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Trigonometric-functions b/Lang/MAXScript/Trigonometric-functions new file mode 120000 index 0000000000..efd549728a --- /dev/null +++ b/Lang/MAXScript/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Walk-a-directory-Non-recursively b/Lang/MAXScript/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..6d798aa29b --- /dev/null +++ b/Lang/MAXScript/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Walk-a-directory-Recursively b/Lang/MAXScript/Walk-a-directory-Recursively new file mode 120000 index 0000000000..0c673b4661 --- /dev/null +++ b/Lang/MAXScript/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/MAXScript \ No newline at end of file diff --git a/Lang/ML-I/Special-variables b/Lang/ML-I/Special-variables new file mode 120000 index 0000000000..9cdaa0a658 --- /dev/null +++ b/Lang/ML-I/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/ML-I \ No newline at end of file diff --git a/Lang/MMIX/Sorting-algorithms-Bubble-sort b/Lang/MMIX/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..275a6d7ce4 --- /dev/null +++ b/Lang/MMIX/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/MMIX \ No newline at end of file diff --git a/Lang/MMIX/Sum-of-a-series b/Lang/MMIX/Sum-of-a-series new file mode 120000 index 0000000000..191b3fc656 --- /dev/null +++ b/Lang/MMIX/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/MMIX \ No newline at end of file diff --git a/Lang/MMIX/Tokenize-a-string b/Lang/MMIX/Tokenize-a-string new file mode 120000 index 0000000000..7340ba3b74 --- /dev/null +++ b/Lang/MMIX/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/MMIX \ No newline at end of file diff --git a/Lang/MOO/Sum-of-squares b/Lang/MOO/Sum-of-squares new file mode 120000 index 0000000000..1e889df4ad --- /dev/null +++ b/Lang/MOO/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/MOO \ No newline at end of file diff --git a/Lang/MUMPS/Short-circuit-evaluation b/Lang/MUMPS/Short-circuit-evaluation new file mode 120000 index 0000000000..2c67ee6777 --- /dev/null +++ b/Lang/MUMPS/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Sieve-of-Eratosthenes b/Lang/MUMPS/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d4053b5541 --- /dev/null +++ b/Lang/MUMPS/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Sort-an-integer-array b/Lang/MUMPS/Sort-an-integer-array new file mode 120000 index 0000000000..85f2bec64e --- /dev/null +++ b/Lang/MUMPS/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Soundex b/Lang/MUMPS/Soundex new file mode 120000 index 0000000000..8484f12d17 --- /dev/null +++ b/Lang/MUMPS/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/String-case b/Lang/MUMPS/String-case new file mode 120000 index 0000000000..9c489495f4 --- /dev/null +++ b/Lang/MUMPS/String-case @@ -0,0 +1 @@ +../../Task/String-case/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/String-concatenation b/Lang/MUMPS/String-concatenation new file mode 120000 index 0000000000..e20b6728d9 --- /dev/null +++ b/Lang/MUMPS/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Substring b/Lang/MUMPS/Substring new file mode 120000 index 0000000000..3ac06f1e08 --- /dev/null +++ b/Lang/MUMPS/Substring @@ -0,0 +1 @@ +../../Task/Substring/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Sum-and-product-of-an-array b/Lang/MUMPS/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c64f8cf0cd --- /dev/null +++ b/Lang/MUMPS/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Sum-of-a-series b/Lang/MUMPS/Sum-of-a-series new file mode 120000 index 0000000000..f72b4432a0 --- /dev/null +++ b/Lang/MUMPS/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Sum-of-squares b/Lang/MUMPS/Sum-of-squares new file mode 120000 index 0000000000..c568d8454d --- /dev/null +++ b/Lang/MUMPS/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/System-time b/Lang/MUMPS/System-time new file mode 120000 index 0000000000..fda74c2b21 --- /dev/null +++ b/Lang/MUMPS/System-time @@ -0,0 +1 @@ +../../Task/System-time/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Tokenize-a-string b/Lang/MUMPS/Tokenize-a-string new file mode 120000 index 0000000000..e37c108398 --- /dev/null +++ b/Lang/MUMPS/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/Undefined-values b/Lang/MUMPS/Undefined-values new file mode 120000 index 0000000000..250f1bb2de --- /dev/null +++ b/Lang/MUMPS/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/MUMPS \ No newline at end of file diff --git a/Lang/MUMPS/User-input-Text b/Lang/MUMPS/User-input-Text new file mode 120000 index 0000000000..ddfc5c7934 --- /dev/null +++ b/Lang/MUMPS/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/MUMPS \ No newline at end of file diff --git a/Lang/Maple/Substring-Top-and-tail b/Lang/Maple/Substring-Top-and-tail new file mode 120000 index 0000000000..a4a309187f --- /dev/null +++ b/Lang/Maple/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Maple \ No newline at end of file diff --git a/Lang/Maple/Y-combinator b/Lang/Maple/Y-combinator new file mode 120000 index 0000000000..d60d5f0837 --- /dev/null +++ b/Lang/Maple/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Maple \ No newline at end of file diff --git a/Lang/Mathematica/SHA-1 b/Lang/Mathematica/SHA-1 new file mode 120000 index 0000000000..4961d12248 --- /dev/null +++ b/Lang/Mathematica/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/SHA-256 b/Lang/Mathematica/SHA-256 new file mode 120000 index 0000000000..a35ae56c7d --- /dev/null +++ b/Lang/Mathematica/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/SOAP b/Lang/Mathematica/SOAP new file mode 120000 index 0000000000..40c7ef2216 --- /dev/null +++ b/Lang/Mathematica/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Seven-sided-dice-from-five-sided-dice b/Lang/Mathematica/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..9888fa43b8 --- /dev/null +++ b/Lang/Mathematica/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Shell-one-liner b/Lang/Mathematica/Shell-one-liner new file mode 120000 index 0000000000..f2d17f3da8 --- /dev/null +++ b/Lang/Mathematica/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Short-circuit-evaluation b/Lang/Mathematica/Short-circuit-evaluation new file mode 120000 index 0000000000..2ae2cd103e --- /dev/null +++ b/Lang/Mathematica/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Show-the-epoch b/Lang/Mathematica/Show-the-epoch new file mode 120000 index 0000000000..1b477ecbcb --- /dev/null +++ b/Lang/Mathematica/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sierpinski-carpet b/Lang/Mathematica/Sierpinski-carpet new file mode 120000 index 0000000000..89376683de --- /dev/null +++ b/Lang/Mathematica/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sierpinski-triangle b/Lang/Mathematica/Sierpinski-triangle new file mode 120000 index 0000000000..71e363b7f2 --- /dev/null +++ b/Lang/Mathematica/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sierpinski-triangle-Graphical b/Lang/Mathematica/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..5a601efbdc --- /dev/null +++ b/Lang/Mathematica/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sieve-of-Eratosthenes b/Lang/Mathematica/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..6e175e99a8 --- /dev/null +++ b/Lang/Mathematica/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Simple-windowed-application b/Lang/Mathematica/Simple-windowed-application new file mode 120000 index 0000000000..94f735fcfe --- /dev/null +++ b/Lang/Mathematica/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Singly-linked-list-Element-definition b/Lang/Mathematica/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..c97ddc7a7f --- /dev/null +++ b/Lang/Mathematica/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Singly-linked-list-Element-insertion b/Lang/Mathematica/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..58e4ffaede --- /dev/null +++ b/Lang/Mathematica/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Singly-linked-list-Traversal b/Lang/Mathematica/Singly-linked-list-Traversal new file mode 120000 index 0000000000..aea8bcf3f6 --- /dev/null +++ b/Lang/Mathematica/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sleep b/Lang/Mathematica/Sleep new file mode 120000 index 0000000000..d8125f87f3 --- /dev/null +++ b/Lang/Mathematica/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sort-an-array-of-composite-structures b/Lang/Mathematica/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..a540c68455 --- /dev/null +++ b/Lang/Mathematica/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sort-an-integer-array b/Lang/Mathematica/Sort-an-integer-array new file mode 120000 index 0000000000..e556836547 --- /dev/null +++ b/Lang/Mathematica/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sort-disjoint-sublist b/Lang/Mathematica/Sort-disjoint-sublist new file mode 120000 index 0000000000..afd4dcb29d --- /dev/null +++ b/Lang/Mathematica/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sort-stability b/Lang/Mathematica/Sort-stability new file mode 120000 index 0000000000..2a51a7d0f2 --- /dev/null +++ b/Lang/Mathematica/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sort-using-a-custom-comparator b/Lang/Mathematica/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..b2012426d8 --- /dev/null +++ b/Lang/Mathematica/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Bead-sort b/Lang/Mathematica/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5c01ca3e92 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Bogosort b/Lang/Mathematica/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b9f9714258 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Bubble-sort b/Lang/Mathematica/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..3f84200271 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Cocktail-sort b/Lang/Mathematica/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..b01a0715e6 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Comb-sort b/Lang/Mathematica/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..28b8f57495 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Counting-sort b/Lang/Mathematica/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..de97cf2fcb --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Gnome-sort b/Lang/Mathematica/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..fc34c21f78 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Heapsort b/Lang/Mathematica/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..78aa232e2f --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Insertion-sort b/Lang/Mathematica/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..f73e764c62 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Merge-sort b/Lang/Mathematica/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..7f6d640cb7 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Pancake-sort b/Lang/Mathematica/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..338b9f0ec3 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Permutation-sort b/Lang/Mathematica/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..c38072bf65 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Quicksort b/Lang/Mathematica/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f8966bfd04 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Selection-sort b/Lang/Mathematica/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..b17d6f823b --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Shell-sort b/Lang/Mathematica/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..945d97283b --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Sleep-sort b/Lang/Mathematica/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..8d383af55a --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Stooge-sort b/Lang/Mathematica/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..0e617bbf69 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Strand-sort b/Lang/Mathematica/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..eace040828 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Soundex b/Lang/Mathematica/Soundex new file mode 120000 index 0000000000..e901ab71eb --- /dev/null +++ b/Lang/Mathematica/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Special-characters b/Lang/Mathematica/Special-characters new file mode 120000 index 0000000000..ebb362974c --- /dev/null +++ b/Lang/Mathematica/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Special-variables b/Lang/Mathematica/Special-variables new file mode 120000 index 0000000000..3fe4b53369 --- /dev/null +++ b/Lang/Mathematica/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Speech-synthesis b/Lang/Mathematica/Speech-synthesis new file mode 120000 index 0000000000..a1f304c9a0 --- /dev/null +++ b/Lang/Mathematica/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Spiral-matrix b/Lang/Mathematica/Spiral-matrix new file mode 120000 index 0000000000..6f3221980c --- /dev/null +++ b/Lang/Mathematica/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Stack b/Lang/Mathematica/Stack new file mode 120000 index 0000000000..a8855c4ee5 --- /dev/null +++ b/Lang/Mathematica/Stack @@ -0,0 +1 @@ +../../Task/Stack/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Stack-traces b/Lang/Mathematica/Stack-traces new file mode 120000 index 0000000000..a5032dcb84 --- /dev/null +++ b/Lang/Mathematica/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Stair-climbing-puzzle b/Lang/Mathematica/Stair-climbing-puzzle new file mode 120000 index 0000000000..c35becfc6c --- /dev/null +++ b/Lang/Mathematica/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Standard-deviation b/Lang/Mathematica/Standard-deviation new file mode 120000 index 0000000000..cfa5a9d5a1 --- /dev/null +++ b/Lang/Mathematica/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Stem-and-leaf-plot b/Lang/Mathematica/Stem-and-leaf-plot new file mode 120000 index 0000000000..352bf6b1fa --- /dev/null +++ b/Lang/Mathematica/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-case b/Lang/Mathematica/String-case new file mode 120000 index 0000000000..48dea361b4 --- /dev/null +++ b/Lang/Mathematica/String-case @@ -0,0 +1 @@ +../../Task/String-case/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-concatenation b/Lang/Mathematica/String-concatenation new file mode 120000 index 0000000000..84674ced4b --- /dev/null +++ b/Lang/Mathematica/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-interpolation--included- b/Lang/Mathematica/String-interpolation--included- new file mode 120000 index 0000000000..a0b59d771e --- /dev/null +++ b/Lang/Mathematica/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-length b/Lang/Mathematica/String-length new file mode 120000 index 0000000000..07af8317dc --- /dev/null +++ b/Lang/Mathematica/String-length @@ -0,0 +1 @@ +../../Task/String-length/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strip-a-set-of-characters-from-a-string b/Lang/Mathematica/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..0d01aacb62 --- /dev/null +++ b/Lang/Mathematica/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strip-block-comments b/Lang/Mathematica/Strip-block-comments new file mode 120000 index 0000000000..29bb5c2155 --- /dev/null +++ b/Lang/Mathematica/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strip-comments-from-a-string b/Lang/Mathematica/Strip-comments-from-a-string new file mode 120000 index 0000000000..2e923861b8 --- /dev/null +++ b/Lang/Mathematica/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Mathematica/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..98e51932bf --- /dev/null +++ b/Lang/Mathematica/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Mathematica/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..aa769df12c --- /dev/null +++ b/Lang/Mathematica/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Substring b/Lang/Mathematica/Substring new file mode 120000 index 0000000000..9f7efb3e93 --- /dev/null +++ b/Lang/Mathematica/Substring @@ -0,0 +1 @@ +../../Task/Substring/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Substring-Top-and-tail b/Lang/Mathematica/Substring-Top-and-tail new file mode 120000 index 0000000000..e3bce65b4e --- /dev/null +++ b/Lang/Mathematica/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Subtractive-generator b/Lang/Mathematica/Subtractive-generator new file mode 120000 index 0000000000..1db755053b --- /dev/null +++ b/Lang/Mathematica/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sudoku b/Lang/Mathematica/Sudoku new file mode 120000 index 0000000000..ce28ddf388 --- /dev/null +++ b/Lang/Mathematica/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sum-and-product-of-an-array b/Lang/Mathematica/Sum-and-product-of-an-array new file mode 120000 index 0000000000..2d37be6c0d --- /dev/null +++ b/Lang/Mathematica/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sum-digits-of-an-integer b/Lang/Mathematica/Sum-digits-of-an-integer new file mode 120000 index 0000000000..fcbce82bd3 --- /dev/null +++ b/Lang/Mathematica/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sum-of-a-series b/Lang/Mathematica/Sum-of-a-series new file mode 120000 index 0000000000..c3391055ab --- /dev/null +++ b/Lang/Mathematica/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sum-of-squares b/Lang/Mathematica/Sum-of-squares new file mode 120000 index 0000000000..bb1fa4f5db --- /dev/null +++ b/Lang/Mathematica/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Symmetric-difference b/Lang/Mathematica/Symmetric-difference new file mode 120000 index 0000000000..afa698c9ad --- /dev/null +++ b/Lang/Mathematica/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/System-time b/Lang/Mathematica/System-time new file mode 120000 index 0000000000..79ac3b80fe --- /dev/null +++ b/Lang/Mathematica/System-time @@ -0,0 +1 @@ +../../Task/System-time/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Table-creation-Postal-addresses b/Lang/Mathematica/Table-creation-Postal-addresses new file mode 120000 index 0000000000..562183ded2 --- /dev/null +++ b/Lang/Mathematica/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Temperature-conversion b/Lang/Mathematica/Temperature-conversion new file mode 120000 index 0000000000..c9516f782e --- /dev/null +++ b/Lang/Mathematica/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Clear-the-screen b/Lang/Mathematica/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..5f9437d328 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Coloured-text b/Lang/Mathematica/Terminal-control-Coloured-text new file mode 120000 index 0000000000..e327aa7c84 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Cursor-movement b/Lang/Mathematica/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..6cb69fbfbf --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Cursor-positioning b/Lang/Mathematica/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..7b17ae0be3 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Dimensions b/Lang/Mathematica/Terminal-control-Dimensions new file mode 120000 index 0000000000..ae8c3ece8c --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Display-an-extended-character b/Lang/Mathematica/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..ddd5b7d970 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Hiding-the-cursor b/Lang/Mathematica/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..ef8ceef693 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Inverse-video b/Lang/Mathematica/Terminal-control-Inverse-video new file mode 120000 index 0000000000..0caa2165b6 --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Preserve-screen b/Lang/Mathematica/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..bc3048cccd --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Ringing-the-terminal-bell b/Lang/Mathematica/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..0944792c3b --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Terminal-control-Unicode-output b/Lang/Mathematica/Terminal-control-Unicode-output new file mode 120000 index 0000000000..de4c33308f --- /dev/null +++ b/Lang/Mathematica/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Ternary-logic b/Lang/Mathematica/Ternary-logic new file mode 120000 index 0000000000..a9ed67483b --- /dev/null +++ b/Lang/Mathematica/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Test-a-function b/Lang/Mathematica/Test-a-function new file mode 120000 index 0000000000..125958b4b3 --- /dev/null +++ b/Lang/Mathematica/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Text-processing-1 b/Lang/Mathematica/Text-processing-1 new file mode 120000 index 0000000000..e1f99d6881 --- /dev/null +++ b/Lang/Mathematica/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Text-processing-2 b/Lang/Mathematica/Text-processing-2 new file mode 120000 index 0000000000..89bb2be5b2 --- /dev/null +++ b/Lang/Mathematica/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Text-processing-Max-licenses-in-use b/Lang/Mathematica/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..1acc6081ed --- /dev/null +++ b/Lang/Mathematica/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tic-tac-toe b/Lang/Mathematica/Tic-tac-toe new file mode 120000 index 0000000000..59d8699427 --- /dev/null +++ b/Lang/Mathematica/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Time-a-function b/Lang/Mathematica/Time-a-function new file mode 120000 index 0000000000..85298861b2 --- /dev/null +++ b/Lang/Mathematica/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tokenize-a-string b/Lang/Mathematica/Tokenize-a-string new file mode 120000 index 0000000000..f17af66cbd --- /dev/null +++ b/Lang/Mathematica/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Top-rank-per-group b/Lang/Mathematica/Top-rank-per-group new file mode 120000 index 0000000000..373cb06976 --- /dev/null +++ b/Lang/Mathematica/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Topological-sort b/Lang/Mathematica/Topological-sort new file mode 120000 index 0000000000..fbc06037d1 --- /dev/null +++ b/Lang/Mathematica/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Topswops b/Lang/Mathematica/Topswops new file mode 120000 index 0000000000..5c9ff4acf3 --- /dev/null +++ b/Lang/Mathematica/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Towers-of-Hanoi b/Lang/Mathematica/Towers-of-Hanoi new file mode 120000 index 0000000000..39877cb588 --- /dev/null +++ b/Lang/Mathematica/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tree-traversal b/Lang/Mathematica/Tree-traversal new file mode 120000 index 0000000000..6e9632150d --- /dev/null +++ b/Lang/Mathematica/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Trigonometric-functions b/Lang/Mathematica/Trigonometric-functions new file mode 120000 index 0000000000..3e033c38be --- /dev/null +++ b/Lang/Mathematica/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Truncatable-primes b/Lang/Mathematica/Truncatable-primes new file mode 120000 index 0000000000..426620e623 --- /dev/null +++ b/Lang/Mathematica/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Truncate-a-file b/Lang/Mathematica/Truncate-a-file new file mode 120000 index 0000000000..ab3f9fddc7 --- /dev/null +++ b/Lang/Mathematica/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Twelve-statements b/Lang/Mathematica/Twelve-statements new file mode 120000 index 0000000000..cbe193b8e1 --- /dev/null +++ b/Lang/Mathematica/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/URL-decoding b/Lang/Mathematica/URL-decoding new file mode 120000 index 0000000000..f68bae2fc2 --- /dev/null +++ b/Lang/Mathematica/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/URL-encoding b/Lang/Mathematica/URL-encoding new file mode 120000 index 0000000000..e5a63ceced --- /dev/null +++ b/Lang/Mathematica/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Unbias-a-random-generator b/Lang/Mathematica/Unbias-a-random-generator new file mode 120000 index 0000000000..b8944fd387 --- /dev/null +++ b/Lang/Mathematica/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Undefined-values b/Lang/Mathematica/Undefined-values new file mode 120000 index 0000000000..42de1d0667 --- /dev/null +++ b/Lang/Mathematica/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Unicode-variable-names b/Lang/Mathematica/Unicode-variable-names new file mode 120000 index 0000000000..8da089f148 --- /dev/null +++ b/Lang/Mathematica/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/User-input-Graphical b/Lang/Mathematica/User-input-Graphical new file mode 120000 index 0000000000..ff62c8d19e --- /dev/null +++ b/Lang/Mathematica/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/User-input-Text b/Lang/Mathematica/User-input-Text new file mode 120000 index 0000000000..c38cc5e6e0 --- /dev/null +++ b/Lang/Mathematica/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Van-der-Corput-sequence b/Lang/Mathematica/Van-der-Corput-sequence new file mode 120000 index 0000000000..ee45528a91 --- /dev/null +++ b/Lang/Mathematica/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Variable-length-quantity b/Lang/Mathematica/Variable-length-quantity new file mode 120000 index 0000000000..cf831749f2 --- /dev/null +++ b/Lang/Mathematica/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Variable-size-Get b/Lang/Mathematica/Variable-size-Get new file mode 120000 index 0000000000..a0d0efc934 --- /dev/null +++ b/Lang/Mathematica/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Variadic-function b/Lang/Mathematica/Variadic-function new file mode 120000 index 0000000000..5733e0c618 --- /dev/null +++ b/Lang/Mathematica/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Vector-products b/Lang/Mathematica/Vector-products new file mode 120000 index 0000000000..9031d78d2a --- /dev/null +++ b/Lang/Mathematica/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Verify-distribution-uniformity-Chi-squared-test b/Lang/Mathematica/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..7fe92b8112 --- /dev/null +++ b/Lang/Mathematica/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Verify-distribution-uniformity-Naive b/Lang/Mathematica/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..6aa03784f2 --- /dev/null +++ b/Lang/Mathematica/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Vigen-re-cipher b/Lang/Mathematica/Vigen-re-cipher new file mode 120000 index 0000000000..733b19048e --- /dev/null +++ b/Lang/Mathematica/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Visualize-a-tree b/Lang/Mathematica/Visualize-a-tree new file mode 120000 index 0000000000..4b9eff7306 --- /dev/null +++ b/Lang/Mathematica/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Voronoi-diagram b/Lang/Mathematica/Voronoi-diagram new file mode 120000 index 0000000000..94bbc7803c --- /dev/null +++ b/Lang/Mathematica/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Walk-a-directory-Non-recursively b/Lang/Mathematica/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b47d428b53 --- /dev/null +++ b/Lang/Mathematica/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Walk-a-directory-Recursively b/Lang/Mathematica/Walk-a-directory-Recursively new file mode 120000 index 0000000000..609fbf591e --- /dev/null +++ b/Lang/Mathematica/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Web-scraping b/Lang/Mathematica/Web-scraping new file mode 120000 index 0000000000..7512d6d468 --- /dev/null +++ b/Lang/Mathematica/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Window-creation b/Lang/Mathematica/Window-creation new file mode 120000 index 0000000000..972360bb8b --- /dev/null +++ b/Lang/Mathematica/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Wireworld b/Lang/Mathematica/Wireworld new file mode 120000 index 0000000000..9e5ebedb78 --- /dev/null +++ b/Lang/Mathematica/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Write-float-arrays-to-a-text-file b/Lang/Mathematica/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..789363ddec --- /dev/null +++ b/Lang/Mathematica/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/XML-DOM-serialization b/Lang/Mathematica/XML-DOM-serialization new file mode 120000 index 0000000000..018d1cd43a --- /dev/null +++ b/Lang/Mathematica/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/XML-Input b/Lang/Mathematica/XML-Input new file mode 120000 index 0000000000..6bab4308cc --- /dev/null +++ b/Lang/Mathematica/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/XML-Output b/Lang/Mathematica/XML-Output new file mode 120000 index 0000000000..090d185b9c --- /dev/null +++ b/Lang/Mathematica/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/XML-XPath b/Lang/Mathematica/XML-XPath new file mode 120000 index 0000000000..22ea275ae3 --- /dev/null +++ b/Lang/Mathematica/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Y-combinator b/Lang/Mathematica/Y-combinator new file mode 120000 index 0000000000..ec537c9374 --- /dev/null +++ b/Lang/Mathematica/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Yahoo--search-interface b/Lang/Mathematica/Yahoo--search-interface new file mode 120000 index 0000000000..074d25435f --- /dev/null +++ b/Lang/Mathematica/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Yin-and-yang b/Lang/Mathematica/Yin-and-yang new file mode 120000 index 0000000000..43e4b39825 --- /dev/null +++ b/Lang/Mathematica/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Zeckendorf-number-representation b/Lang/Mathematica/Zeckendorf-number-representation new file mode 120000 index 0000000000..6dde6a1131 --- /dev/null +++ b/Lang/Mathematica/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Zig-zag-matrix b/Lang/Mathematica/Zig-zag-matrix new file mode 120000 index 0000000000..47a58f80eb --- /dev/null +++ b/Lang/Mathematica/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Mathematica \ No newline at end of file diff --git a/Lang/Mathprog/Solve-a-Hidato-puzzle b/Lang/Mathprog/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..72917f126a --- /dev/null +++ b/Lang/Mathprog/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Mathprog \ No newline at end of file diff --git a/Lang/Maxima/Show-the-epoch b/Lang/Maxima/Show-the-epoch new file mode 120000 index 0000000000..3935697461 --- /dev/null +++ b/Lang/Maxima/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sieve-of-Eratosthenes b/Lang/Maxima/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..cf6b24e325 --- /dev/null +++ b/Lang/Maxima/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sort-an-integer-array b/Lang/Maxima/Sort-an-integer-array new file mode 120000 index 0000000000..6f7ee9a8d9 --- /dev/null +++ b/Lang/Maxima/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sort-using-a-custom-comparator b/Lang/Maxima/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..6de3de3ce1 --- /dev/null +++ b/Lang/Maxima/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Insertion-sort b/Lang/Maxima/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..3df672aa96 --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Merge-sort b/Lang/Maxima/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..01df0ac126 --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Selection-sort b/Lang/Maxima/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..eaa1fbeb3c --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Special-variables b/Lang/Maxima/Special-variables new file mode 120000 index 0000000000..5c651f05af --- /dev/null +++ b/Lang/Maxima/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Spiral-matrix b/Lang/Maxima/Spiral-matrix new file mode 120000 index 0000000000..a6bd57d0c6 --- /dev/null +++ b/Lang/Maxima/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Stack b/Lang/Maxima/Stack new file mode 120000 index 0000000000..911f77b563 --- /dev/null +++ b/Lang/Maxima/Stack @@ -0,0 +1 @@ +../../Task/Stack/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Stem-and-leaf-plot b/Lang/Maxima/Stem-and-leaf-plot new file mode 120000 index 0000000000..9c238f9cb2 --- /dev/null +++ b/Lang/Maxima/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Maxima \ No newline at end of file diff --git a/Lang/Maxima/String-concatenation b/Lang/Maxima/String-concatenation new file mode 120000 index 0000000000..ae8d0fa0ed --- /dev/null +++ b/Lang/Maxima/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Maxima \ No newline at end of file diff --git a/Lang/Maxima/String-interpolation--included- b/Lang/Maxima/String-interpolation--included- new file mode 120000 index 0000000000..39184947ab --- /dev/null +++ b/Lang/Maxima/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Maxima \ No newline at end of file diff --git a/Lang/Maxima/String-length b/Lang/Maxima/String-length new file mode 120000 index 0000000000..8acdc9d7e2 --- /dev/null +++ b/Lang/Maxima/String-length @@ -0,0 +1 @@ +../../Task/String-length/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Substring b/Lang/Maxima/Substring new file mode 120000 index 0000000000..cf9ca68c45 --- /dev/null +++ b/Lang/Maxima/Substring @@ -0,0 +1 @@ +../../Task/Substring/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sum-and-product-of-an-array b/Lang/Maxima/Sum-and-product-of-an-array new file mode 120000 index 0000000000..8672494ad6 --- /dev/null +++ b/Lang/Maxima/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sum-of-a-series b/Lang/Maxima/Sum-of-a-series new file mode 120000 index 0000000000..468d9f342b --- /dev/null +++ b/Lang/Maxima/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sum-of-squares b/Lang/Maxima/Sum-of-squares new file mode 120000 index 0000000000..db23ee12a3 --- /dev/null +++ b/Lang/Maxima/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Symmetric-difference b/Lang/Maxima/Symmetric-difference new file mode 120000 index 0000000000..066c266d27 --- /dev/null +++ b/Lang/Maxima/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Maxima \ No newline at end of file diff --git a/Lang/Maxima/System-time b/Lang/Maxima/System-time new file mode 120000 index 0000000000..1d3c989a82 --- /dev/null +++ b/Lang/Maxima/System-time @@ -0,0 +1 @@ +../../Task/System-time/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Time-a-function b/Lang/Maxima/Time-a-function new file mode 120000 index 0000000000..7b4ef14dd0 --- /dev/null +++ b/Lang/Maxima/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Trigonometric-functions b/Lang/Maxima/Trigonometric-functions new file mode 120000 index 0000000000..c65a7db82f --- /dev/null +++ b/Lang/Maxima/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Variadic-function b/Lang/Maxima/Variadic-function new file mode 120000 index 0000000000..fb3f73f9aa --- /dev/null +++ b/Lang/Maxima/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Visualize-a-tree b/Lang/Maxima/Visualize-a-tree new file mode 120000 index 0000000000..6e6a097e49 --- /dev/null +++ b/Lang/Maxima/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Zig-zag-matrix b/Lang/Maxima/Zig-zag-matrix new file mode 120000 index 0000000000..08216027a4 --- /dev/null +++ b/Lang/Maxima/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Maxima \ No newline at end of file diff --git a/Lang/Mercury/Sort-an-integer-array b/Lang/Mercury/Sort-an-integer-array new file mode 120000 index 0000000000..2a35aa3f73 --- /dev/null +++ b/Lang/Mercury/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Sorting-algorithms-Merge-sort b/Lang/Mercury/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..c7a22d54c6 --- /dev/null +++ b/Lang/Mercury/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Mercury \ No newline at end of file diff --git a/Lang/Mercury/String-case b/Lang/Mercury/String-case new file mode 120000 index 0000000000..3678a113f4 --- /dev/null +++ b/Lang/Mercury/String-case @@ -0,0 +1 @@ +../../Task/String-case/Mercury \ No newline at end of file diff --git a/Lang/Mercury/String-concatenation b/Lang/Mercury/String-concatenation new file mode 120000 index 0000000000..cae19d1621 --- /dev/null +++ b/Lang/Mercury/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Mercury/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..c36a3d59b1 --- /dev/null +++ b/Lang/Mercury/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Sum-of-squares b/Lang/Mercury/Sum-of-squares new file mode 120000 index 0000000000..1e2808f37c --- /dev/null +++ b/Lang/Mercury/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Symmetric-difference b/Lang/Mercury/Symmetric-difference new file mode 120000 index 0000000000..a2fcc73a63 --- /dev/null +++ b/Lang/Mercury/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Tokenize-a-string b/Lang/Mercury/Tokenize-a-string new file mode 120000 index 0000000000..0f03b9e4ff --- /dev/null +++ b/Lang/Mercury/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Universal-Turing-machine b/Lang/Mercury/Universal-Turing-machine new file mode 120000 index 0000000000..77e21c551e --- /dev/null +++ b/Lang/Mercury/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Vector-products b/Lang/Mercury/Vector-products new file mode 120000 index 0000000000..92f05c8974 --- /dev/null +++ b/Lang/Mercury/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Mercury \ No newline at end of file diff --git a/Lang/Metafont/Sorting-algorithms-Gnome-sort b/Lang/Metafont/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..6846815f8b --- /dev/null +++ b/Lang/Metafont/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Metafont \ No newline at end of file diff --git a/Lang/Metafont/String-case b/Lang/Metafont/String-case new file mode 120000 index 0000000000..f040655645 --- /dev/null +++ b/Lang/Metafont/String-case @@ -0,0 +1 @@ +../../Task/String-case/Metafont \ No newline at end of file diff --git a/Lang/Metafont/String-concatenation b/Lang/Metafont/String-concatenation new file mode 120000 index 0000000000..466881e0aa --- /dev/null +++ b/Lang/Metafont/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Metafont \ No newline at end of file diff --git a/Lang/Metafont/String-length b/Lang/Metafont/String-length new file mode 120000 index 0000000000..1e31176b9e --- /dev/null +++ b/Lang/Metafont/String-length @@ -0,0 +1 @@ +../../Task/String-length/Metafont \ No newline at end of file diff --git a/Lang/Metafont/Trigonometric-functions b/Lang/Metafont/Trigonometric-functions new file mode 120000 index 0000000000..168a39b60c --- /dev/null +++ b/Lang/Metafont/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Metafont \ No newline at end of file diff --git a/Lang/Metafont/User-input-Text b/Lang/Metafont/User-input-Text new file mode 120000 index 0000000000..4be15dc286 --- /dev/null +++ b/Lang/Metafont/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Metafont \ No newline at end of file diff --git a/Lang/Metafont/Variadic-function b/Lang/Metafont/Variadic-function new file mode 120000 index 0000000000..2e9450557a --- /dev/null +++ b/Lang/Metafont/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Metafont \ No newline at end of file diff --git a/Lang/Metapost/Yin-and-yang b/Lang/Metapost/Yin-and-yang new file mode 120000 index 0000000000..46bd5aefe4 --- /dev/null +++ b/Lang/Metapost/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Metapost \ No newline at end of file diff --git a/Lang/Mirah/User-input-Text b/Lang/Mirah/User-input-Text new file mode 120000 index 0000000000..ef07441d92 --- /dev/null +++ b/Lang/Mirah/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Mirah \ No newline at end of file diff --git a/Lang/Modula-2/Singly-linked-list-Element-definition b/Lang/Modula-2/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..ac50d62ddd --- /dev/null +++ b/Lang/Modula-2/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Sorting-algorithms-Bubble-sort b/Lang/Modula-2/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..e73e524b3f --- /dev/null +++ b/Lang/Modula-2/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Sorting-algorithms-Quicksort b/Lang/Modula-2/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..0d6e0303a6 --- /dev/null +++ b/Lang/Modula-2/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-3/Sieve-of-Eratosthenes b/Lang/Modula-3/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..cebd3ffebb --- /dev/null +++ b/Lang/Modula-3/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Simple-windowed-application b/Lang/Modula-3/Simple-windowed-application new file mode 120000 index 0000000000..c8cd0a3589 --- /dev/null +++ b/Lang/Modula-3/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sort-an-integer-array b/Lang/Modula-3/Sort-an-integer-array new file mode 120000 index 0000000000..ae69c705b9 --- /dev/null +++ b/Lang/Modula-3/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sorting-algorithms-Bogosort b/Lang/Modula-3/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..daf2c4a48c --- /dev/null +++ b/Lang/Modula-3/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sorting-algorithms-Bubble-sort b/Lang/Modula-3/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..0eb640ca25 --- /dev/null +++ b/Lang/Modula-3/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sorting-algorithms-Counting-sort b/Lang/Modula-3/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..8552236777 --- /dev/null +++ b/Lang/Modula-3/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sorting-algorithms-Insertion-sort b/Lang/Modula-3/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..9eb2732965 --- /dev/null +++ b/Lang/Modula-3/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sorting-algorithms-Quicksort b/Lang/Modula-3/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..50c64c7a4c --- /dev/null +++ b/Lang/Modula-3/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/String-case b/Lang/Modula-3/String-case new file mode 120000 index 0000000000..6b5de9fbef --- /dev/null +++ b/Lang/Modula-3/String-case @@ -0,0 +1 @@ +../../Task/String-case/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/String-concatenation b/Lang/Modula-3/String-concatenation new file mode 120000 index 0000000000..33963277cb --- /dev/null +++ b/Lang/Modula-3/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/String-length b/Lang/Modula-3/String-length new file mode 120000 index 0000000000..efde24049a --- /dev/null +++ b/Lang/Modula-3/String-length @@ -0,0 +1 @@ +../../Task/String-length/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sum-and-product-of-an-array b/Lang/Modula-3/Sum-and-product-of-an-array new file mode 120000 index 0000000000..23ff878857 --- /dev/null +++ b/Lang/Modula-3/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sum-of-a-series b/Lang/Modula-3/Sum-of-a-series new file mode 120000 index 0000000000..ce89dfafd7 --- /dev/null +++ b/Lang/Modula-3/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Sum-of-squares b/Lang/Modula-3/Sum-of-squares new file mode 120000 index 0000000000..ca7390fa63 --- /dev/null +++ b/Lang/Modula-3/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/System-time b/Lang/Modula-3/System-time new file mode 120000 index 0000000000..63931dd943 --- /dev/null +++ b/Lang/Modula-3/System-time @@ -0,0 +1 @@ +../../Task/System-time/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Tokenize-a-string b/Lang/Modula-3/Tokenize-a-string new file mode 120000 index 0000000000..5f61ea1069 --- /dev/null +++ b/Lang/Modula-3/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Towers-of-Hanoi b/Lang/Modula-3/Towers-of-Hanoi new file mode 120000 index 0000000000..290d0066d4 --- /dev/null +++ b/Lang/Modula-3/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/User-input-Text b/Lang/Modula-3/User-input-Text new file mode 120000 index 0000000000..61205f18ae --- /dev/null +++ b/Lang/Modula-3/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Variable-size-Get b/Lang/Modula-3/Variable-size-Get new file mode 120000 index 0000000000..4626c17440 --- /dev/null +++ b/Lang/Modula-3/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Variable-size-Set b/Lang/Modula-3/Variable-size-Set new file mode 120000 index 0000000000..c72c6239d9 --- /dev/null +++ b/Lang/Modula-3/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Variables b/Lang/Modula-3/Variables new file mode 120000 index 0000000000..f8b076d648 --- /dev/null +++ b/Lang/Modula-3/Variables @@ -0,0 +1 @@ +../../Task/Variables/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Variadic-function b/Lang/Modula-3/Variadic-function new file mode 120000 index 0000000000..a8cd14f504 --- /dev/null +++ b/Lang/Modula-3/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Zig-zag-matrix b/Lang/Modula-3/Zig-zag-matrix new file mode 120000 index 0000000000..b311ac35e5 --- /dev/null +++ b/Lang/Modula-3/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Modula-3 \ No newline at end of file diff --git a/Lang/MySQL/Table-creation-Postal-addresses b/Lang/MySQL/Table-creation-Postal-addresses new file mode 120000 index 0000000000..6c408006b0 --- /dev/null +++ b/Lang/MySQL/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/MySQL \ No newline at end of file diff --git a/Lang/Nemerle/Short-circuit-evaluation b/Lang/Nemerle/Short-circuit-evaluation new file mode 120000 index 0000000000..f853d1ef3d --- /dev/null +++ b/Lang/Nemerle/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sockets b/Lang/Nemerle/Sockets new file mode 120000 index 0000000000..05480c449a --- /dev/null +++ b/Lang/Nemerle/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Bogosort b/Lang/Nemerle/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..4d820df438 --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Bubble-sort b/Lang/Nemerle/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..15e86b7a52 --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Insertion-sort b/Lang/Nemerle/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..f4a2f97669 --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Quicksort b/Lang/Nemerle/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..8598dbbc43 --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sorting-algorithms-Selection-sort b/Lang/Nemerle/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ac2342f60e --- /dev/null +++ b/Lang/Nemerle/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/String-case b/Lang/Nemerle/String-case new file mode 120000 index 0000000000..dc93edfa08 --- /dev/null +++ b/Lang/Nemerle/String-case @@ -0,0 +1 @@ +../../Task/String-case/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/String-concatenation b/Lang/Nemerle/String-concatenation new file mode 120000 index 0000000000..0c95a9e774 --- /dev/null +++ b/Lang/Nemerle/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/String-interpolation--included- b/Lang/Nemerle/String-interpolation--included- new file mode 120000 index 0000000000..ccf828c297 --- /dev/null +++ b/Lang/Nemerle/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/String-length b/Lang/Nemerle/String-length new file mode 120000 index 0000000000..b3a37c9054 --- /dev/null +++ b/Lang/Nemerle/String-length @@ -0,0 +1 @@ +../../Task/String-length/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Strip-a-set-of-characters-from-a-string b/Lang/Nemerle/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..f24af488bb --- /dev/null +++ b/Lang/Nemerle/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Nemerle/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..0157d5c9a3 --- /dev/null +++ b/Lang/Nemerle/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Substring b/Lang/Nemerle/Substring new file mode 120000 index 0000000000..9a71330800 --- /dev/null +++ b/Lang/Nemerle/Substring @@ -0,0 +1 @@ +../../Task/Substring/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Substring-Top-and-tail b/Lang/Nemerle/Substring-Top-and-tail new file mode 120000 index 0000000000..ce06eab82a --- /dev/null +++ b/Lang/Nemerle/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sum-and-product-of-an-array b/Lang/Nemerle/Sum-and-product-of-an-array new file mode 120000 index 0000000000..0ae872e9aa --- /dev/null +++ b/Lang/Nemerle/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Sum-of-squares b/Lang/Nemerle/Sum-of-squares new file mode 120000 index 0000000000..9379bbf50f --- /dev/null +++ b/Lang/Nemerle/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Tokenize-a-string b/Lang/Nemerle/Tokenize-a-string new file mode 120000 index 0000000000..0c8d6c980d --- /dev/null +++ b/Lang/Nemerle/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Towers-of-Hanoi b/Lang/Nemerle/Towers-of-Hanoi new file mode 120000 index 0000000000..0bd007ee26 --- /dev/null +++ b/Lang/Nemerle/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/User-input-Text b/Lang/Nemerle/User-input-Text new file mode 120000 index 0000000000..d8c929e28e --- /dev/null +++ b/Lang/Nemerle/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Nemerle \ No newline at end of file diff --git a/Lang/Nemerle/Vector-products b/Lang/Nemerle/Vector-products new file mode 120000 index 0000000000..3bf3c8379d --- /dev/null +++ b/Lang/Nemerle/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Nemerle \ No newline at end of file diff --git a/Lang/NetRexx/SHA-1 b/Lang/NetRexx/SHA-1 new file mode 120000 index 0000000000..ac836818ba --- /dev/null +++ b/Lang/NetRexx/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/SHA-256 b/Lang/NetRexx/SHA-256 new file mode 120000 index 0000000000..79cdc14526 --- /dev/null +++ b/Lang/NetRexx/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Shell-one-liner b/Lang/NetRexx/Shell-one-liner new file mode 120000 index 0000000000..6675c862fb --- /dev/null +++ b/Lang/NetRexx/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Show-the-epoch b/Lang/NetRexx/Show-the-epoch new file mode 120000 index 0000000000..56c542c851 --- /dev/null +++ b/Lang/NetRexx/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sieve-of-Eratosthenes b/Lang/NetRexx/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..6bdbf287da --- /dev/null +++ b/Lang/NetRexx/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Singleton b/Lang/NetRexx/Singleton new file mode 120000 index 0000000000..531333d1b4 --- /dev/null +++ b/Lang/NetRexx/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sleep b/Lang/NetRexx/Sleep new file mode 120000 index 0000000000..24991c9491 --- /dev/null +++ b/Lang/NetRexx/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sockets b/Lang/NetRexx/Sockets new file mode 120000 index 0000000000..21047a3533 --- /dev/null +++ b/Lang/NetRexx/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sort-an-array-of-composite-structures b/Lang/NetRexx/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..76d18ee7a3 --- /dev/null +++ b/Lang/NetRexx/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sort-an-integer-array b/Lang/NetRexx/Sort-an-integer-array new file mode 120000 index 0000000000..3bcd65766f --- /dev/null +++ b/Lang/NetRexx/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sort-stability b/Lang/NetRexx/Sort-stability new file mode 120000 index 0000000000..fef43a24ab --- /dev/null +++ b/Lang/NetRexx/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sort-using-a-custom-comparator b/Lang/NetRexx/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..fc856fb72b --- /dev/null +++ b/Lang/NetRexx/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Bead-sort b/Lang/NetRexx/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..304c52f780 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Bogosort b/Lang/NetRexx/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..826d6376e3 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Bubble-sort b/Lang/NetRexx/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..490decbc3d --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Cocktail-sort b/Lang/NetRexx/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..2531b73633 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Comb-sort b/Lang/NetRexx/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..8a85055aef --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Counting-sort b/Lang/NetRexx/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..b33d6dbe73 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Gnome-sort b/Lang/NetRexx/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..cf1b170d7a --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Heapsort b/Lang/NetRexx/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..40c3dabca9 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Insertion-sort b/Lang/NetRexx/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..d51c2d196c --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Merge-sort b/Lang/NetRexx/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..8a0510f917 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Quicksort b/Lang/NetRexx/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..3b1a3faaa7 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Selection-sort b/Lang/NetRexx/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a8236bbf67 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Shell-sort b/Lang/NetRexx/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..41aa05de1c --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Sleep-sort b/Lang/NetRexx/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..a785db41b8 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Stooge-sort b/Lang/NetRexx/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..172ffc9744 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sorting-algorithms-Strand-sort b/Lang/NetRexx/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..aa6eb55a78 --- /dev/null +++ b/Lang/NetRexx/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Special-variables b/Lang/NetRexx/Special-variables new file mode 120000 index 0000000000..30de55e2bb --- /dev/null +++ b/Lang/NetRexx/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Spiral-matrix b/Lang/NetRexx/Spiral-matrix new file mode 120000 index 0000000000..5e91d22a5e --- /dev/null +++ b/Lang/NetRexx/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Stack-traces b/Lang/NetRexx/Stack-traces new file mode 120000 index 0000000000..fb221a1044 --- /dev/null +++ b/Lang/NetRexx/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-case b/Lang/NetRexx/String-case new file mode 120000 index 0000000000..1c63681612 --- /dev/null +++ b/Lang/NetRexx/String-case @@ -0,0 +1 @@ +../../Task/String-case/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-comparison b/Lang/NetRexx/String-comparison new file mode 120000 index 0000000000..450871cb4b --- /dev/null +++ b/Lang/NetRexx/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-concatenation b/Lang/NetRexx/String-concatenation new file mode 120000 index 0000000000..ca91c47b87 --- /dev/null +++ b/Lang/NetRexx/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/String-interpolation--included- b/Lang/NetRexx/String-interpolation--included- new file mode 120000 index 0000000000..f783fc8c04 --- /dev/null +++ b/Lang/NetRexx/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Strip-a-set-of-characters-from-a-string b/Lang/NetRexx/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..91dcc65a28 --- /dev/null +++ b/Lang/NetRexx/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Strip-whitespace-from-a-string-Top-and-tail b/Lang/NetRexx/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..77c823c493 --- /dev/null +++ b/Lang/NetRexx/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Substring b/Lang/NetRexx/Substring new file mode 120000 index 0000000000..b384a34e0b --- /dev/null +++ b/Lang/NetRexx/Substring @@ -0,0 +1 @@ +../../Task/Substring/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sum-and-product-of-an-array b/Lang/NetRexx/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f8d41a91ce --- /dev/null +++ b/Lang/NetRexx/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Sum-digits-of-an-integer b/Lang/NetRexx/Sum-digits-of-an-integer new file mode 120000 index 0000000000..ef0b18fdb2 --- /dev/null +++ b/Lang/NetRexx/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/System-time b/Lang/NetRexx/System-time new file mode 120000 index 0000000000..cb979483dd --- /dev/null +++ b/Lang/NetRexx/System-time @@ -0,0 +1 @@ +../../Task/System-time/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Table-creation-Postal-addresses b/Lang/NetRexx/Table-creation-Postal-addresses new file mode 120000 index 0000000000..3dcaa73a26 --- /dev/null +++ b/Lang/NetRexx/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Test-a-function b/Lang/NetRexx/Test-a-function new file mode 120000 index 0000000000..7f2f53091e --- /dev/null +++ b/Lang/NetRexx/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Tokenize-a-string b/Lang/NetRexx/Tokenize-a-string new file mode 120000 index 0000000000..9ad6de3fac --- /dev/null +++ b/Lang/NetRexx/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Towers-of-Hanoi b/Lang/NetRexx/Towers-of-Hanoi new file mode 120000 index 0000000000..2c0f7f9537 --- /dev/null +++ b/Lang/NetRexx/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Trigonometric-functions b/Lang/NetRexx/Trigonometric-functions new file mode 120000 index 0000000000..6f3c558555 --- /dev/null +++ b/Lang/NetRexx/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/URL-decoding b/Lang/NetRexx/URL-decoding new file mode 120000 index 0000000000..30fe745917 --- /dev/null +++ b/Lang/NetRexx/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/URL-encoding b/Lang/NetRexx/URL-encoding new file mode 120000 index 0000000000..e03a88db4b --- /dev/null +++ b/Lang/NetRexx/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Unbias-a-random-generator b/Lang/NetRexx/Unbias-a-random-generator new file mode 120000 index 0000000000..4e4b4374ab --- /dev/null +++ b/Lang/NetRexx/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Unicode-variable-names b/Lang/NetRexx/Unicode-variable-names new file mode 120000 index 0000000000..47e3bc4cc8 --- /dev/null +++ b/Lang/NetRexx/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/User-input-Graphical b/Lang/NetRexx/User-input-Graphical new file mode 120000 index 0000000000..f900eb1071 --- /dev/null +++ b/Lang/NetRexx/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/User-input-Text b/Lang/NetRexx/User-input-Text new file mode 120000 index 0000000000..174a1ba18c --- /dev/null +++ b/Lang/NetRexx/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Vigen-re-cipher b/Lang/NetRexx/Vigen-re-cipher new file mode 120000 index 0000000000..087933c315 --- /dev/null +++ b/Lang/NetRexx/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Web-scraping b/Lang/NetRexx/Web-scraping new file mode 120000 index 0000000000..dc32d13c18 --- /dev/null +++ b/Lang/NetRexx/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Window-creation b/Lang/NetRexx/Window-creation new file mode 120000 index 0000000000..de9d85d9b6 --- /dev/null +++ b/Lang/NetRexx/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Write-float-arrays-to-a-text-file b/Lang/NetRexx/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..6b5ac26627 --- /dev/null +++ b/Lang/NetRexx/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Write-language-name-in-3D-ASCII b/Lang/NetRexx/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..0044ac615c --- /dev/null +++ b/Lang/NetRexx/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/XML-DOM-serialization b/Lang/NetRexx/XML-DOM-serialization new file mode 120000 index 0000000000..c3ff85092b --- /dev/null +++ b/Lang/NetRexx/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/XML-Output b/Lang/NetRexx/XML-Output new file mode 120000 index 0000000000..47c3540ca1 --- /dev/null +++ b/Lang/NetRexx/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/XML-XPath b/Lang/NetRexx/XML-XPath new file mode 120000 index 0000000000..1829178e80 --- /dev/null +++ b/Lang/NetRexx/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Yin-and-yang b/Lang/NetRexx/Yin-and-yang new file mode 120000 index 0000000000..bfbae24afa --- /dev/null +++ b/Lang/NetRexx/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/NetRexx \ No newline at end of file diff --git a/Lang/NetRexx/Zig-zag-matrix b/Lang/NetRexx/Zig-zag-matrix new file mode 120000 index 0000000000..e3cc2ff4aa --- /dev/null +++ b/Lang/NetRexx/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/Shell-one-liner b/Lang/NewLISP/Shell-one-liner new file mode 120000 index 0000000000..f5662881d3 --- /dev/null +++ b/Lang/NewLISP/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Show-the-epoch b/Lang/NewLISP/Show-the-epoch new file mode 120000 index 0000000000..962e80f82c --- /dev/null +++ b/Lang/NewLISP/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Sleep b/Lang/NewLISP/Sleep new file mode 120000 index 0000000000..51b4c3f9a2 --- /dev/null +++ b/Lang/NewLISP/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/String-case b/Lang/NewLISP/String-case new file mode 120000 index 0000000000..57471249da --- /dev/null +++ b/Lang/NewLISP/String-case @@ -0,0 +1 @@ +../../Task/String-case/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/String-length b/Lang/NewLISP/String-length new file mode 120000 index 0000000000..0bf92b7469 --- /dev/null +++ b/Lang/NewLISP/String-length @@ -0,0 +1 @@ +../../Task/String-length/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Sum-of-squares b/Lang/NewLISP/Sum-of-squares new file mode 120000 index 0000000000..adcc7ddef1 --- /dev/null +++ b/Lang/NewLISP/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Towers-of-Hanoi b/Lang/NewLISP/Towers-of-Hanoi new file mode 120000 index 0000000000..9952f2b0b4 --- /dev/null +++ b/Lang/NewLISP/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/User-input-Graphical b/Lang/NewLISP/User-input-Graphical new file mode 120000 index 0000000000..a1f1278e8f --- /dev/null +++ b/Lang/NewLISP/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Write-float-arrays-to-a-text-file b/Lang/NewLISP/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..3b7629ff1e --- /dev/null +++ b/Lang/NewLISP/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/NewLISP \ No newline at end of file diff --git a/Lang/Nial/Sort-an-integer-array b/Lang/Nial/Sort-an-integer-array new file mode 120000 index 0000000000..407e29bc9f --- /dev/null +++ b/Lang/Nial/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Nial \ No newline at end of file diff --git a/Lang/Nial/Sort-using-a-custom-comparator b/Lang/Nial/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..d8489e0659 --- /dev/null +++ b/Lang/Nial/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Nial \ No newline at end of file diff --git a/Lang/Nial/Sorting-algorithms-Quicksort b/Lang/Nial/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..0e86fb1747 --- /dev/null +++ b/Lang/Nial/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Nial \ No newline at end of file diff --git a/Lang/Nial/String-case b/Lang/Nial/String-case new file mode 120000 index 0000000000..fb71526899 --- /dev/null +++ b/Lang/Nial/String-case @@ -0,0 +1 @@ +../../Task/String-case/Nial \ No newline at end of file diff --git a/Lang/Nial/Sum-and-product-of-an-array b/Lang/Nial/Sum-and-product-of-an-array new file mode 120000 index 0000000000..172ddd8c9d --- /dev/null +++ b/Lang/Nial/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Nial \ No newline at end of file diff --git a/Lang/Nial/Sum-of-a-series b/Lang/Nial/Sum-of-a-series new file mode 120000 index 0000000000..432405cd41 --- /dev/null +++ b/Lang/Nial/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Nial \ No newline at end of file diff --git a/Lang/Nimrod/Sleep b/Lang/Nimrod/Sleep new file mode 120000 index 0000000000..66956689ed --- /dev/null +++ b/Lang/Nimrod/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Sorting-algorithms-Quicksort b/Lang/Nimrod/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..abe9c784fe --- /dev/null +++ b/Lang/Nimrod/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/String-concatenation b/Lang/Nimrod/String-concatenation new file mode 120000 index 0000000000..228a56b383 --- /dev/null +++ b/Lang/Nimrod/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Towers-of-Hanoi b/Lang/Nimrod/Towers-of-Hanoi new file mode 120000 index 0000000000..8bbb6dc0ee --- /dev/null +++ b/Lang/Nimrod/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Nimrod \ No newline at end of file diff --git a/Lang/Nimrod/Unicode-variable-names b/Lang/Nimrod/Unicode-variable-names new file mode 120000 index 0000000000..ba8d276e84 --- /dev/null +++ b/Lang/Nimrod/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Nimrod \ No newline at end of file diff --git a/Lang/Niue/Sieve-of-Eratosthenes b/Lang/Niue/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2cd10c4dba --- /dev/null +++ b/Lang/Niue/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Niue \ No newline at end of file diff --git a/Lang/Niue/Sort-an-integer-array b/Lang/Niue/Sort-an-integer-array new file mode 120000 index 0000000000..5df0dc632d --- /dev/null +++ b/Lang/Niue/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Niue \ No newline at end of file diff --git a/Lang/Niue/Substring b/Lang/Niue/Substring new file mode 120000 index 0000000000..2e1dbb8908 --- /dev/null +++ b/Lang/Niue/Substring @@ -0,0 +1 @@ +../../Task/Substring/Niue \ No newline at end of file diff --git a/Lang/OCaml/SHA-1 b/Lang/OCaml/SHA-1 new file mode 120000 index 0000000000..d07d388c74 --- /dev/null +++ b/Lang/OCaml/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/OCaml \ No newline at end of file diff --git a/Lang/OCaml/SHA-256 b/Lang/OCaml/SHA-256 new file mode 120000 index 0000000000..39443d622e --- /dev/null +++ b/Lang/OCaml/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Seven-sided-dice-from-five-sided-dice b/Lang/OCaml/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..d6b7944c2b --- /dev/null +++ b/Lang/OCaml/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Shell-one-liner b/Lang/OCaml/Shell-one-liner new file mode 120000 index 0000000000..ddea85f601 --- /dev/null +++ b/Lang/OCaml/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Short-circuit-evaluation b/Lang/OCaml/Short-circuit-evaluation new file mode 120000 index 0000000000..e8035c70c0 --- /dev/null +++ b/Lang/OCaml/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Show-the-epoch b/Lang/OCaml/Show-the-epoch new file mode 120000 index 0000000000..933de04536 --- /dev/null +++ b/Lang/OCaml/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sierpinski-carpet b/Lang/OCaml/Sierpinski-carpet new file mode 120000 index 0000000000..bedc800afa --- /dev/null +++ b/Lang/OCaml/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sierpinski-triangle b/Lang/OCaml/Sierpinski-triangle new file mode 120000 index 0000000000..77dc19cbcd --- /dev/null +++ b/Lang/OCaml/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sierpinski-triangle-Graphical b/Lang/OCaml/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..9996318313 --- /dev/null +++ b/Lang/OCaml/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sieve-of-Eratosthenes b/Lang/OCaml/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..16ccab3c66 --- /dev/null +++ b/Lang/OCaml/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Simple-windowed-application b/Lang/OCaml/Simple-windowed-application new file mode 120000 index 0000000000..448cb6edd6 --- /dev/null +++ b/Lang/OCaml/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Simulate-input-Keyboard b/Lang/OCaml/Simulate-input-Keyboard new file mode 120000 index 0000000000..45efbe1118 --- /dev/null +++ b/Lang/OCaml/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Singly-linked-list-Element-definition b/Lang/OCaml/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1d150fe2dd --- /dev/null +++ b/Lang/OCaml/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Singly-linked-list-Element-insertion b/Lang/OCaml/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..c1b700d1fe --- /dev/null +++ b/Lang/OCaml/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Singly-linked-list-Traversal b/Lang/OCaml/Singly-linked-list-Traversal new file mode 120000 index 0000000000..3e0ce6b70e --- /dev/null +++ b/Lang/OCaml/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sleep b/Lang/OCaml/Sleep new file mode 120000 index 0000000000..ae187f7d63 --- /dev/null +++ b/Lang/OCaml/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sockets b/Lang/OCaml/Sockets new file mode 120000 index 0000000000..c7b0944f65 --- /dev/null +++ b/Lang/OCaml/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sokoban b/Lang/OCaml/Sokoban new file mode 120000 index 0000000000..b1a2d9005c --- /dev/null +++ b/Lang/OCaml/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sort-an-array-of-composite-structures b/Lang/OCaml/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..41876bf47a --- /dev/null +++ b/Lang/OCaml/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sort-an-integer-array b/Lang/OCaml/Sort-an-integer-array new file mode 120000 index 0000000000..297d4f3d57 --- /dev/null +++ b/Lang/OCaml/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sort-disjoint-sublist b/Lang/OCaml/Sort-disjoint-sublist new file mode 120000 index 0000000000..05dd15c63f --- /dev/null +++ b/Lang/OCaml/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sort-using-a-custom-comparator b/Lang/OCaml/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..7e9a766a7a --- /dev/null +++ b/Lang/OCaml/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Bead-sort b/Lang/OCaml/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..298c7d1ff6 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Bogosort b/Lang/OCaml/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..511faa9d9f --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Bubble-sort b/Lang/OCaml/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..4009ed359e --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Cocktail-sort b/Lang/OCaml/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..9f836c06a0 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Comb-sort b/Lang/OCaml/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..0312b01dd8 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Counting-sort b/Lang/OCaml/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..47ede65aea --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Gnome-sort b/Lang/OCaml/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..e52d62d3e0 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Heapsort b/Lang/OCaml/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..f38229a5f5 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Insertion-sort b/Lang/OCaml/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..28b4c090d9 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Merge-sort b/Lang/OCaml/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..c7bdf65c7c --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Pancake-sort b/Lang/OCaml/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..7fd9cef524 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Permutation-sort b/Lang/OCaml/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..24f7d7356c --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Quicksort b/Lang/OCaml/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f669ddace5 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Selection-sort b/Lang/OCaml/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a44a4ce821 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Shell-sort b/Lang/OCaml/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..1aaa5d1c5f --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Stooge-sort b/Lang/OCaml/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..03785bef22 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Strand-sort b/Lang/OCaml/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..496d996047 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Soundex b/Lang/OCaml/Soundex new file mode 120000 index 0000000000..0f41c35283 --- /dev/null +++ b/Lang/OCaml/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Special-characters b/Lang/OCaml/Special-characters new file mode 120000 index 0000000000..8c79458838 --- /dev/null +++ b/Lang/OCaml/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Special-variables b/Lang/OCaml/Special-variables new file mode 120000 index 0000000000..abef0d3f68 --- /dev/null +++ b/Lang/OCaml/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Spiral-matrix b/Lang/OCaml/Spiral-matrix new file mode 120000 index 0000000000..92e8aaf623 --- /dev/null +++ b/Lang/OCaml/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Stable-marriage-problem b/Lang/OCaml/Stable-marriage-problem new file mode 120000 index 0000000000..82ba5cfc90 --- /dev/null +++ b/Lang/OCaml/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Stack b/Lang/OCaml/Stack new file mode 120000 index 0000000000..6e0d9ddf77 --- /dev/null +++ b/Lang/OCaml/Stack @@ -0,0 +1 @@ +../../Task/Stack/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Stack-traces b/Lang/OCaml/Stack-traces new file mode 120000 index 0000000000..98d2ec12cf --- /dev/null +++ b/Lang/OCaml/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Stair-climbing-puzzle b/Lang/OCaml/Stair-climbing-puzzle new file mode 120000 index 0000000000..26da3fdbdb --- /dev/null +++ b/Lang/OCaml/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Standard-deviation b/Lang/OCaml/Standard-deviation new file mode 120000 index 0000000000..bc81d222ec --- /dev/null +++ b/Lang/OCaml/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Stem-and-leaf-plot b/Lang/OCaml/Stem-and-leaf-plot new file mode 120000 index 0000000000..e710b5d0d9 --- /dev/null +++ b/Lang/OCaml/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-case b/Lang/OCaml/String-case new file mode 120000 index 0000000000..b96bf9bd82 --- /dev/null +++ b/Lang/OCaml/String-case @@ -0,0 +1 @@ +../../Task/String-case/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-concatenation b/Lang/OCaml/String-concatenation new file mode 120000 index 0000000000..35819fc10b --- /dev/null +++ b/Lang/OCaml/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-interpolation--included- b/Lang/OCaml/String-interpolation--included- new file mode 120000 index 0000000000..cb731b7f6d --- /dev/null +++ b/Lang/OCaml/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/OCaml \ No newline at end of file diff --git a/Lang/OCaml/String-length b/Lang/OCaml/String-length new file mode 120000 index 0000000000..b2dedc2f0d --- /dev/null +++ b/Lang/OCaml/String-length @@ -0,0 +1 @@ +../../Task/String-length/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Strip-a-set-of-characters-from-a-string b/Lang/OCaml/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..288618b172 --- /dev/null +++ b/Lang/OCaml/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Strip-comments-from-a-string b/Lang/OCaml/Strip-comments-from-a-string new file mode 120000 index 0000000000..1640c54a0a --- /dev/null +++ b/Lang/OCaml/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Strip-control-codes-and-extended-characters-from-a-string b/Lang/OCaml/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..fb57ce000c --- /dev/null +++ b/Lang/OCaml/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Strip-whitespace-from-a-string-Top-and-tail b/Lang/OCaml/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..8fa93c3cff --- /dev/null +++ b/Lang/OCaml/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Substring b/Lang/OCaml/Substring new file mode 120000 index 0000000000..da5b437bad --- /dev/null +++ b/Lang/OCaml/Substring @@ -0,0 +1 @@ +../../Task/Substring/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Substring-Top-and-tail b/Lang/OCaml/Substring-Top-and-tail new file mode 120000 index 0000000000..42fa3f37c4 --- /dev/null +++ b/Lang/OCaml/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Subtractive-generator b/Lang/OCaml/Subtractive-generator new file mode 120000 index 0000000000..f4a6719273 --- /dev/null +++ b/Lang/OCaml/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sudoku b/Lang/OCaml/Sudoku new file mode 120000 index 0000000000..fb2439f502 --- /dev/null +++ b/Lang/OCaml/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sum-and-product-of-an-array b/Lang/OCaml/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a6d098968c --- /dev/null +++ b/Lang/OCaml/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sum-digits-of-an-integer b/Lang/OCaml/Sum-digits-of-an-integer new file mode 120000 index 0000000000..749b8103dd --- /dev/null +++ b/Lang/OCaml/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sum-of-a-series b/Lang/OCaml/Sum-of-a-series new file mode 120000 index 0000000000..4020343da1 --- /dev/null +++ b/Lang/OCaml/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sum-of-squares b/Lang/OCaml/Sum-of-squares new file mode 120000 index 0000000000..c72e80762e --- /dev/null +++ b/Lang/OCaml/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sutherland-Hodgman-polygon-clipping b/Lang/OCaml/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..146cf214f4 --- /dev/null +++ b/Lang/OCaml/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Symmetric-difference b/Lang/OCaml/Symmetric-difference new file mode 120000 index 0000000000..ad590f9709 --- /dev/null +++ b/Lang/OCaml/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Synchronous-concurrency b/Lang/OCaml/Synchronous-concurrency new file mode 120000 index 0000000000..354a9e900a --- /dev/null +++ b/Lang/OCaml/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/OCaml \ No newline at end of file diff --git a/Lang/OCaml/System-time b/Lang/OCaml/System-time new file mode 120000 index 0000000000..96435ca1cf --- /dev/null +++ b/Lang/OCaml/System-time @@ -0,0 +1 @@ +../../Task/System-time/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Take-notes-on-the-command-line b/Lang/OCaml/Take-notes-on-the-command-line new file mode 120000 index 0000000000..1467c8067f --- /dev/null +++ b/Lang/OCaml/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Terminal-control-Clear-the-screen b/Lang/OCaml/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..a86bba8b3b --- /dev/null +++ b/Lang/OCaml/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Terminal-control-Coloured-text b/Lang/OCaml/Terminal-control-Coloured-text new file mode 120000 index 0000000000..edb62ab288 --- /dev/null +++ b/Lang/OCaml/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Terminal-control-Cursor-positioning b/Lang/OCaml/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..c4c715a39e --- /dev/null +++ b/Lang/OCaml/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Terminal-control-Dimensions b/Lang/OCaml/Terminal-control-Dimensions new file mode 120000 index 0000000000..3f35b166ed --- /dev/null +++ b/Lang/OCaml/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Terminal-control-Inverse-video b/Lang/OCaml/Terminal-control-Inverse-video new file mode 120000 index 0000000000..3b777ec026 --- /dev/null +++ b/Lang/OCaml/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Ternary-logic b/Lang/OCaml/Ternary-logic new file mode 120000 index 0000000000..0d87614e91 --- /dev/null +++ b/Lang/OCaml/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Test-a-function b/Lang/OCaml/Test-a-function new file mode 120000 index 0000000000..c6e86073e6 --- /dev/null +++ b/Lang/OCaml/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Text-processing-1 b/Lang/OCaml/Text-processing-1 new file mode 120000 index 0000000000..a986b0d4ec --- /dev/null +++ b/Lang/OCaml/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Text-processing-2 b/Lang/OCaml/Text-processing-2 new file mode 120000 index 0000000000..bbf7fe1bfb --- /dev/null +++ b/Lang/OCaml/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Text-processing-Max-licenses-in-use b/Lang/OCaml/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..f3330dc0a9 --- /dev/null +++ b/Lang/OCaml/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Thieles-interpolation-formula b/Lang/OCaml/Thieles-interpolation-formula new file mode 120000 index 0000000000..d3590c71f1 --- /dev/null +++ b/Lang/OCaml/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Time-a-function b/Lang/OCaml/Time-a-function new file mode 120000 index 0000000000..1ffcfe4c61 --- /dev/null +++ b/Lang/OCaml/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Tokenize-a-string b/Lang/OCaml/Tokenize-a-string new file mode 120000 index 0000000000..aa937e1edb --- /dev/null +++ b/Lang/OCaml/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Top-rank-per-group b/Lang/OCaml/Top-rank-per-group new file mode 120000 index 0000000000..f73de1cbbe --- /dev/null +++ b/Lang/OCaml/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Topological-sort b/Lang/OCaml/Topological-sort new file mode 120000 index 0000000000..2cac5c3678 --- /dev/null +++ b/Lang/OCaml/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Towers-of-Hanoi b/Lang/OCaml/Towers-of-Hanoi new file mode 120000 index 0000000000..99d0f0cfcb --- /dev/null +++ b/Lang/OCaml/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Trabb-Pardo-Knuth-algorithm b/Lang/OCaml/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..8a64e0035e --- /dev/null +++ b/Lang/OCaml/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Tree-traversal b/Lang/OCaml/Tree-traversal new file mode 120000 index 0000000000..fb742597f5 --- /dev/null +++ b/Lang/OCaml/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Trigonometric-functions b/Lang/OCaml/Trigonometric-functions new file mode 120000 index 0000000000..aebf244546 --- /dev/null +++ b/Lang/OCaml/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Truncate-a-file b/Lang/OCaml/Truncate-a-file new file mode 120000 index 0000000000..6c1b614c44 --- /dev/null +++ b/Lang/OCaml/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/OCaml \ No newline at end of file diff --git a/Lang/OCaml/URL-decoding b/Lang/OCaml/URL-decoding new file mode 120000 index 0000000000..152973e152 --- /dev/null +++ b/Lang/OCaml/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/OCaml \ No newline at end of file diff --git a/Lang/OCaml/URL-encoding b/Lang/OCaml/URL-encoding new file mode 120000 index 0000000000..5ce33a5320 --- /dev/null +++ b/Lang/OCaml/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Unbias-a-random-generator b/Lang/OCaml/Unbias-a-random-generator new file mode 120000 index 0000000000..9850f4c9d8 --- /dev/null +++ b/Lang/OCaml/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Undefined-values b/Lang/OCaml/Undefined-values new file mode 120000 index 0000000000..74a832dd07 --- /dev/null +++ b/Lang/OCaml/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Use-another-language-to-call-a-function b/Lang/OCaml/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..34a8d23218 --- /dev/null +++ b/Lang/OCaml/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/OCaml \ No newline at end of file diff --git a/Lang/OCaml/User-input-Text b/Lang/OCaml/User-input-Text new file mode 120000 index 0000000000..0a347de7a8 --- /dev/null +++ b/Lang/OCaml/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Variable-length-quantity b/Lang/OCaml/Variable-length-quantity new file mode 120000 index 0000000000..4eeba734ca --- /dev/null +++ b/Lang/OCaml/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Variable-size-Get b/Lang/OCaml/Variable-size-Get new file mode 120000 index 0000000000..e562f98830 --- /dev/null +++ b/Lang/OCaml/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Variables b/Lang/OCaml/Variables new file mode 120000 index 0000000000..5577782526 --- /dev/null +++ b/Lang/OCaml/Variables @@ -0,0 +1 @@ +../../Task/Variables/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Vector-products b/Lang/OCaml/Vector-products new file mode 120000 index 0000000000..e73ec0fb3e --- /dev/null +++ b/Lang/OCaml/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Verify-distribution-uniformity-Chi-squared-test b/Lang/OCaml/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..f45adc726a --- /dev/null +++ b/Lang/OCaml/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Verify-distribution-uniformity-Naive b/Lang/OCaml/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..29a462b97f --- /dev/null +++ b/Lang/OCaml/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Vigen-re-cipher b/Lang/OCaml/Vigen-re-cipher new file mode 120000 index 0000000000..3d489314fe --- /dev/null +++ b/Lang/OCaml/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Walk-a-directory-Non-recursively b/Lang/OCaml/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..d1a311a00a --- /dev/null +++ b/Lang/OCaml/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Walk-a-directory-Recursively b/Lang/OCaml/Walk-a-directory-Recursively new file mode 120000 index 0000000000..c2b728ba94 --- /dev/null +++ b/Lang/OCaml/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Web-scraping b/Lang/OCaml/Web-scraping new file mode 120000 index 0000000000..3cdddc67cc --- /dev/null +++ b/Lang/OCaml/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Window-creation b/Lang/OCaml/Window-creation new file mode 120000 index 0000000000..7ba1f1ba09 --- /dev/null +++ b/Lang/OCaml/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Window-creation-X11 b/Lang/OCaml/Window-creation-X11 new file mode 120000 index 0000000000..8cc6a9a780 --- /dev/null +++ b/Lang/OCaml/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Wireworld b/Lang/OCaml/Wireworld new file mode 120000 index 0000000000..a36e07fc16 --- /dev/null +++ b/Lang/OCaml/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Word-wrap b/Lang/OCaml/Word-wrap new file mode 120000 index 0000000000..06cb5ed8cc --- /dev/null +++ b/Lang/OCaml/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Write-float-arrays-to-a-text-file b/Lang/OCaml/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..e02a857c9e --- /dev/null +++ b/Lang/OCaml/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/OCaml \ No newline at end of file diff --git a/Lang/OCaml/XML-Input b/Lang/OCaml/XML-Input new file mode 120000 index 0000000000..709f3fc275 --- /dev/null +++ b/Lang/OCaml/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/OCaml \ No newline at end of file diff --git a/Lang/OCaml/XML-Output b/Lang/OCaml/XML-Output new file mode 120000 index 0000000000..ea99d627b9 --- /dev/null +++ b/Lang/OCaml/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Y-combinator b/Lang/OCaml/Y-combinator new file mode 120000 index 0000000000..4bd5f6ddfd --- /dev/null +++ b/Lang/OCaml/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Yin-and-yang b/Lang/OCaml/Yin-and-yang new file mode 120000 index 0000000000..0fa4669b82 --- /dev/null +++ b/Lang/OCaml/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Zig-zag-matrix b/Lang/OCaml/Zig-zag-matrix new file mode 120000 index 0000000000..fd39e63944 --- /dev/null +++ b/Lang/OCaml/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/Sieve-of-Eratosthenes b/Lang/Oberon-2/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..7f816a3d7c --- /dev/null +++ b/Lang/Oberon-2/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Sorting-algorithms-Bogosort b/Lang/Oberon-2/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2ac01e445e --- /dev/null +++ b/Lang/Oberon-2/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/String-length b/Lang/Oberon-2/String-length new file mode 120000 index 0000000000..683df7cbad --- /dev/null +++ b/Lang/Oberon-2/String-length @@ -0,0 +1 @@ +../../Task/String-length/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Oberon-2/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..18339b5773 --- /dev/null +++ b/Lang/Oberon-2/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Sum-digits-of-an-integer b/Lang/Oberon-2/Sum-digits-of-an-integer new file mode 120000 index 0000000000..99f159ab5a --- /dev/null +++ b/Lang/Oberon-2/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/SHA-256 b/Lang/Objeck/SHA-256 new file mode 120000 index 0000000000..f205ea95ef --- /dev/null +++ b/Lang/Objeck/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Shell-one-liner b/Lang/Objeck/Shell-one-liner new file mode 120000 index 0000000000..318d772b5c --- /dev/null +++ b/Lang/Objeck/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Short-circuit-evaluation b/Lang/Objeck/Short-circuit-evaluation new file mode 120000 index 0000000000..1611edd51a --- /dev/null +++ b/Lang/Objeck/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Singleton b/Lang/Objeck/Singleton new file mode 120000 index 0000000000..0b69f58f25 --- /dev/null +++ b/Lang/Objeck/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Singly-linked-list-Traversal b/Lang/Objeck/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8c6fa1e017 --- /dev/null +++ b/Lang/Objeck/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sleep b/Lang/Objeck/Sleep new file mode 120000 index 0000000000..99c8ae8104 --- /dev/null +++ b/Lang/Objeck/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sockets b/Lang/Objeck/Sockets new file mode 120000 index 0000000000..55d2e9e61d --- /dev/null +++ b/Lang/Objeck/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sort-an-array-of-composite-structures b/Lang/Objeck/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..6bda78c32b --- /dev/null +++ b/Lang/Objeck/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sort-an-integer-array b/Lang/Objeck/Sort-an-integer-array new file mode 120000 index 0000000000..7b4b70a9b3 --- /dev/null +++ b/Lang/Objeck/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Bubble-sort b/Lang/Objeck/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..2cbadc3b12 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Cocktail-sort b/Lang/Objeck/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..54a1114abd --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Comb-sort b/Lang/Objeck/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..afea9b199e --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Counting-sort b/Lang/Objeck/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..9c58ed4276 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Gnome-sort b/Lang/Objeck/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7a78285edd --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Heapsort b/Lang/Objeck/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..d6e86fdab2 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Insertion-sort b/Lang/Objeck/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4e83a78fb8 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Quicksort b/Lang/Objeck/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..2804037782 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Shell-sort b/Lang/Objeck/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..409297e9c4 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Sleep-sort b/Lang/Objeck/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..ffe097c04d --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-algorithms-Stooge-sort b/Lang/Objeck/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..7449e635e1 --- /dev/null +++ b/Lang/Objeck/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Special-characters b/Lang/Objeck/Special-characters new file mode 120000 index 0000000000..3166f09710 --- /dev/null +++ b/Lang/Objeck/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Stack b/Lang/Objeck/Stack new file mode 120000 index 0000000000..1d26c3c31f --- /dev/null +++ b/Lang/Objeck/Stack @@ -0,0 +1 @@ +../../Task/Stack/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Standard-deviation b/Lang/Objeck/Standard-deviation new file mode 120000 index 0000000000..edfd5e9636 --- /dev/null +++ b/Lang/Objeck/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-case b/Lang/Objeck/String-case new file mode 120000 index 0000000000..caef5a886b --- /dev/null +++ b/Lang/Objeck/String-case @@ -0,0 +1 @@ +../../Task/String-case/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-concatenation b/Lang/Objeck/String-concatenation new file mode 120000 index 0000000000..87df379eaa --- /dev/null +++ b/Lang/Objeck/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Objeck \ No newline at end of file diff --git a/Lang/Objeck/String-length b/Lang/Objeck/String-length new file mode 120000 index 0000000000..1c3640c2b3 --- /dev/null +++ b/Lang/Objeck/String-length @@ -0,0 +1 @@ +../../Task/String-length/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Substring b/Lang/Objeck/Substring new file mode 120000 index 0000000000..4a4fa4aac8 --- /dev/null +++ b/Lang/Objeck/Substring @@ -0,0 +1 @@ +../../Task/Substring/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Substring-Top-and-tail b/Lang/Objeck/Substring-Top-and-tail new file mode 120000 index 0000000000..d55b8fda10 --- /dev/null +++ b/Lang/Objeck/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sum-and-product-of-an-array b/Lang/Objeck/Sum-and-product-of-an-array new file mode 120000 index 0000000000..32fab85dbe --- /dev/null +++ b/Lang/Objeck/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sum-of-a-series b/Lang/Objeck/Sum-of-a-series new file mode 120000 index 0000000000..f8700c0821 --- /dev/null +++ b/Lang/Objeck/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sum-of-squares b/Lang/Objeck/Sum-of-squares new file mode 120000 index 0000000000..7f21987ed0 --- /dev/null +++ b/Lang/Objeck/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Objeck \ No newline at end of file diff --git a/Lang/Objeck/System-time b/Lang/Objeck/System-time new file mode 120000 index 0000000000..37bdc3d20c --- /dev/null +++ b/Lang/Objeck/System-time @@ -0,0 +1 @@ +../../Task/System-time/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Temperature-conversion b/Lang/Objeck/Temperature-conversion new file mode 120000 index 0000000000..6541fb3a16 --- /dev/null +++ b/Lang/Objeck/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Terminal-control-Ringing-the-terminal-bell b/Lang/Objeck/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..a69841f542 --- /dev/null +++ b/Lang/Objeck/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Tokenize-a-string b/Lang/Objeck/Tokenize-a-string new file mode 120000 index 0000000000..5a3da1303b --- /dev/null +++ b/Lang/Objeck/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Objeck \ No newline at end of file diff --git a/Lang/Objeck/URL-decoding b/Lang/Objeck/URL-decoding new file mode 120000 index 0000000000..6573dd83fd --- /dev/null +++ b/Lang/Objeck/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Objeck \ No newline at end of file diff --git a/Lang/Objeck/URL-encoding b/Lang/Objeck/URL-encoding new file mode 120000 index 0000000000..2bf35f9972 --- /dev/null +++ b/Lang/Objeck/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Objeck \ No newline at end of file diff --git a/Lang/Objeck/User-input-Text b/Lang/Objeck/User-input-Text new file mode 120000 index 0000000000..acd24c8a42 --- /dev/null +++ b/Lang/Objeck/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Variables b/Lang/Objeck/Variables new file mode 120000 index 0000000000..c48e5913fb --- /dev/null +++ b/Lang/Objeck/Variables @@ -0,0 +1 @@ +../../Task/Variables/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Vector-products b/Lang/Objeck/Vector-products new file mode 120000 index 0000000000..dc5bf20c21 --- /dev/null +++ b/Lang/Objeck/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Vigen-re-cipher b/Lang/Objeck/Vigen-re-cipher new file mode 120000 index 0000000000..91da2695ef --- /dev/null +++ b/Lang/Objeck/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Walk-a-directory-Non-recursively b/Lang/Objeck/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b79593ed67 --- /dev/null +++ b/Lang/Objeck/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Web-scraping b/Lang/Objeck/Web-scraping new file mode 120000 index 0000000000..b7c1dd3279 --- /dev/null +++ b/Lang/Objeck/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Window-creation b/Lang/Objeck/Window-creation new file mode 120000 index 0000000000..6ba16d72d5 --- /dev/null +++ b/Lang/Objeck/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Objeck \ No newline at end of file diff --git a/Lang/Objeck/XML-DOM-serialization b/Lang/Objeck/XML-DOM-serialization new file mode 120000 index 0000000000..7bc7a00b84 --- /dev/null +++ b/Lang/Objeck/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Objeck \ No newline at end of file diff --git a/Lang/Objeck/XML-Input b/Lang/Objeck/XML-Input new file mode 120000 index 0000000000..dd5673cb51 --- /dev/null +++ b/Lang/Objeck/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Objeck \ No newline at end of file diff --git a/Lang/Objeck/XML-Output b/Lang/Objeck/XML-Output new file mode 120000 index 0000000000..24e76296ca --- /dev/null +++ b/Lang/Objeck/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Objeck \ No newline at end of file diff --git a/Lang/Objeck/XML-XPath b/Lang/Objeck/XML-XPath new file mode 120000 index 0000000000..66f4cfcee5 --- /dev/null +++ b/Lang/Objeck/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Zig-zag-matrix b/Lang/Objeck/Zig-zag-matrix new file mode 120000 index 0000000000..2e6972429e --- /dev/null +++ b/Lang/Objeck/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal/Topological-sort b/Lang/Object-Pascal/Topological-sort new file mode 120000 index 0000000000..f73d327ce2 --- /dev/null +++ b/Lang/Object-Pascal/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Object-Pascal \ No newline at end of file diff --git a/Lang/Objective-C/Show-the-epoch b/Lang/Objective-C/Show-the-epoch new file mode 120000 index 0000000000..ac27fe990d --- /dev/null +++ b/Lang/Objective-C/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Simple-windowed-application b/Lang/Objective-C/Simple-windowed-application new file mode 120000 index 0000000000..8c3d6ef4fa --- /dev/null +++ b/Lang/Objective-C/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Singleton b/Lang/Objective-C/Singleton new file mode 120000 index 0000000000..9f3b1cd562 --- /dev/null +++ b/Lang/Objective-C/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Singly-linked-list-Element-definition b/Lang/Objective-C/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..824caa519a --- /dev/null +++ b/Lang/Objective-C/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Singly-linked-list-Traversal b/Lang/Objective-C/Singly-linked-list-Traversal new file mode 120000 index 0000000000..b80df2a521 --- /dev/null +++ b/Lang/Objective-C/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sleep b/Lang/Objective-C/Sleep new file mode 120000 index 0000000000..7c43abb7d5 --- /dev/null +++ b/Lang/Objective-C/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sockets b/Lang/Objective-C/Sockets new file mode 120000 index 0000000000..fd5a357f7a --- /dev/null +++ b/Lang/Objective-C/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sort-an-array-of-composite-structures b/Lang/Objective-C/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..844348d672 --- /dev/null +++ b/Lang/Objective-C/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sort-an-integer-array b/Lang/Objective-C/Sort-an-integer-array new file mode 120000 index 0000000000..16d7c55859 --- /dev/null +++ b/Lang/Objective-C/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sort-disjoint-sublist b/Lang/Objective-C/Sort-disjoint-sublist new file mode 120000 index 0000000000..3653da6b8e --- /dev/null +++ b/Lang/Objective-C/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sort-using-a-custom-comparator b/Lang/Objective-C/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..8cc31cb707 --- /dev/null +++ b/Lang/Objective-C/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sorting-algorithms-Sleep-sort b/Lang/Objective-C/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..fc86be03e4 --- /dev/null +++ b/Lang/Objective-C/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Stable-marriage-problem b/Lang/Objective-C/Stable-marriage-problem new file mode 120000 index 0000000000..b7ce9aa311 --- /dev/null +++ b/Lang/Objective-C/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Stack b/Lang/Objective-C/Stack new file mode 120000 index 0000000000..1b538cd9b2 --- /dev/null +++ b/Lang/Objective-C/Stack @@ -0,0 +1 @@ +../../Task/Stack/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Stack-traces b/Lang/Objective-C/Stack-traces new file mode 120000 index 0000000000..3aad07c6ec --- /dev/null +++ b/Lang/Objective-C/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Standard-deviation b/Lang/Objective-C/Standard-deviation new file mode 120000 index 0000000000..6c35bd9b48 --- /dev/null +++ b/Lang/Objective-C/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/String-case b/Lang/Objective-C/String-case new file mode 120000 index 0000000000..b58e6fa193 --- /dev/null +++ b/Lang/Objective-C/String-case @@ -0,0 +1 @@ +../../Task/String-case/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/String-concatenation b/Lang/Objective-C/String-concatenation new file mode 120000 index 0000000000..11e2df247b --- /dev/null +++ b/Lang/Objective-C/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/String-length b/Lang/Objective-C/String-length new file mode 120000 index 0000000000..9510fc9185 --- /dev/null +++ b/Lang/Objective-C/String-length @@ -0,0 +1 @@ +../../Task/String-length/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Strip-a-set-of-characters-from-a-string b/Lang/Objective-C/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..fc28cffd46 --- /dev/null +++ b/Lang/Objective-C/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Objective-C/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ee44ff6b39 --- /dev/null +++ b/Lang/Objective-C/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sum-and-product-of-an-array b/Lang/Objective-C/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5d58797963 --- /dev/null +++ b/Lang/Objective-C/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Symmetric-difference b/Lang/Objective-C/Symmetric-difference new file mode 120000 index 0000000000..9bf502dd98 --- /dev/null +++ b/Lang/Objective-C/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/System-time b/Lang/Objective-C/System-time new file mode 120000 index 0000000000..25560099b3 --- /dev/null +++ b/Lang/Objective-C/System-time @@ -0,0 +1 @@ +../../Task/System-time/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Temperature-conversion b/Lang/Objective-C/Temperature-conversion new file mode 120000 index 0000000000..3c2b760a33 --- /dev/null +++ b/Lang/Objective-C/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Tokenize-a-string b/Lang/Objective-C/Tokenize-a-string new file mode 120000 index 0000000000..311059b6c5 --- /dev/null +++ b/Lang/Objective-C/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Towers-of-Hanoi b/Lang/Objective-C/Towers-of-Hanoi new file mode 120000 index 0000000000..7a1265f6ce --- /dev/null +++ b/Lang/Objective-C/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Trabb-Pardo-Knuth-algorithm b/Lang/Objective-C/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..f4be2bc5f8 --- /dev/null +++ b/Lang/Objective-C/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/URL-decoding b/Lang/Objective-C/URL-decoding new file mode 120000 index 0000000000..6a82d6bb5c --- /dev/null +++ b/Lang/Objective-C/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/URL-encoding b/Lang/Objective-C/URL-encoding new file mode 120000 index 0000000000..24b9929bd1 --- /dev/null +++ b/Lang/Objective-C/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Variadic-function b/Lang/Objective-C/Variadic-function new file mode 120000 index 0000000000..6f6bea942e --- /dev/null +++ b/Lang/Objective-C/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Walk-a-directory-Non-recursively b/Lang/Objective-C/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..84ea6ad99e --- /dev/null +++ b/Lang/Objective-C/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Walk-a-directory-Recursively b/Lang/Objective-C/Walk-a-directory-Recursively new file mode 120000 index 0000000000..72334e55d6 --- /dev/null +++ b/Lang/Objective-C/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Window-creation b/Lang/Objective-C/Window-creation new file mode 120000 index 0000000000..7527a73f0b --- /dev/null +++ b/Lang/Objective-C/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Y-combinator b/Lang/Objective-C/Y-combinator new file mode 120000 index 0000000000..0fa78d617f --- /dev/null +++ b/Lang/Objective-C/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Objective-C \ No newline at end of file diff --git a/Lang/Octave/Sort-an-integer-array b/Lang/Octave/Sort-an-integer-array new file mode 120000 index 0000000000..1d80082bfd --- /dev/null +++ b/Lang/Octave/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Bead-sort b/Lang/Octave/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..837abf9f4d --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Bubble-sort b/Lang/Octave/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..68e7351d93 --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Cocktail-sort b/Lang/Octave/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..5edb9f6e21 --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Counting-sort b/Lang/Octave/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c18c76a075 --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Gnome-sort b/Lang/Octave/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..48da61449a --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Octave \ No newline at end of file diff --git a/Lang/Octave/Sorting-algorithms-Quicksort b/Lang/Octave/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..5b3823c217 --- /dev/null +++ b/Lang/Octave/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Octave \ No newline at end of file diff --git a/Lang/Octave/Spiral-matrix b/Lang/Octave/Spiral-matrix new file mode 120000 index 0000000000..d37009b2b4 --- /dev/null +++ b/Lang/Octave/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Octave \ No newline at end of file diff --git a/Lang/Octave/String-case b/Lang/Octave/String-case new file mode 120000 index 0000000000..b44d780d12 --- /dev/null +++ b/Lang/Octave/String-case @@ -0,0 +1 @@ +../../Task/String-case/Octave \ No newline at end of file diff --git a/Lang/Octave/String-length b/Lang/Octave/String-length new file mode 120000 index 0000000000..c66ee04eeb --- /dev/null +++ b/Lang/Octave/String-length @@ -0,0 +1 @@ +../../Task/String-length/Octave \ No newline at end of file diff --git a/Lang/Octave/Sum-and-product-of-an-array b/Lang/Octave/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e09e459771 --- /dev/null +++ b/Lang/Octave/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Octave \ No newline at end of file diff --git a/Lang/Octave/Sum-of-a-series b/Lang/Octave/Sum-of-a-series new file mode 120000 index 0000000000..a7aeaaad6d --- /dev/null +++ b/Lang/Octave/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Octave \ No newline at end of file diff --git a/Lang/Octave/Sum-of-squares b/Lang/Octave/Sum-of-squares new file mode 120000 index 0000000000..37e0b59438 --- /dev/null +++ b/Lang/Octave/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Octave \ No newline at end of file diff --git a/Lang/Octave/Terminal-control-Clear-the-screen b/Lang/Octave/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..afff4c53a1 --- /dev/null +++ b/Lang/Octave/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Octave \ No newline at end of file diff --git a/Lang/Octave/Towers-of-Hanoi b/Lang/Octave/Towers-of-Hanoi new file mode 120000 index 0000000000..cc678df19e --- /dev/null +++ b/Lang/Octave/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Octave \ No newline at end of file diff --git a/Lang/Octave/Trigonometric-functions b/Lang/Octave/Trigonometric-functions new file mode 120000 index 0000000000..b4b2d83e81 --- /dev/null +++ b/Lang/Octave/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Octave \ No newline at end of file diff --git a/Lang/Octave/User-input-Text b/Lang/Octave/User-input-Text new file mode 120000 index 0000000000..7bd57cd399 --- /dev/null +++ b/Lang/Octave/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Octave \ No newline at end of file diff --git a/Lang/Octave/Vector-products b/Lang/Octave/Vector-products new file mode 120000 index 0000000000..b2ddfeeab8 --- /dev/null +++ b/Lang/Octave/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Octave \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Sort-stability b/Lang/OpenEdge-Progress/Sort-stability new file mode 120000 index 0000000000..e9970735c6 --- /dev/null +++ b/Lang/OpenEdge-Progress/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Sorting-algorithms-Bead-sort b/Lang/OpenEdge-Progress/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..797bd7767a --- /dev/null +++ b/Lang/OpenEdge-Progress/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/String-case b/Lang/OpenEdge-Progress/String-case new file mode 120000 index 0000000000..93851f9e83 --- /dev/null +++ b/Lang/OpenEdge-Progress/String-case @@ -0,0 +1 @@ +../../Task/String-case/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/String-length b/Lang/OpenEdge-Progress/String-length new file mode 120000 index 0000000000..828eee89fa --- /dev/null +++ b/Lang/OpenEdge-Progress/String-length @@ -0,0 +1 @@ +../../Task/String-length/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Strip-whitespace-from-a-string-Top-and-tail b/Lang/OpenEdge-Progress/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..6a3ceb1df6 --- /dev/null +++ b/Lang/OpenEdge-Progress/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Sum-of-a-series b/Lang/OpenEdge-Progress/Sum-of-a-series new file mode 120000 index 0000000000..388eaca92f --- /dev/null +++ b/Lang/OpenEdge-Progress/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Tokenize-a-string b/Lang/OpenEdge-Progress/Tokenize-a-string new file mode 120000 index 0000000000..20337ac57b --- /dev/null +++ b/Lang/OpenEdge-Progress/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Truncatable-primes b/Lang/OpenEdge-Progress/Truncatable-primes new file mode 120000 index 0000000000..22f6605a71 --- /dev/null +++ b/Lang/OpenEdge-Progress/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/XML-DOM-serialization b/Lang/OpenEdge-Progress/XML-DOM-serialization new file mode 120000 index 0000000000..6dcd092691 --- /dev/null +++ b/Lang/OpenEdge-Progress/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/XML-Input b/Lang/OpenEdge-Progress/XML-Input new file mode 120000 index 0000000000..755ccb22b5 --- /dev/null +++ b/Lang/OpenEdge-Progress/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/Openscad/String-concatenation b/Lang/Openscad/String-concatenation new file mode 120000 index 0000000000..642b1ceb6c --- /dev/null +++ b/Lang/Openscad/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Openscad \ No newline at end of file diff --git a/Lang/Openscad/Variables b/Lang/Openscad/Variables new file mode 120000 index 0000000000..05e5efdbb0 --- /dev/null +++ b/Lang/Openscad/Variables @@ -0,0 +1 @@ +../../Task/Variables/Openscad \ No newline at end of file diff --git a/Lang/Order/Sierpinski-carpet b/Lang/Order/Sierpinski-carpet new file mode 120000 index 0000000000..d25aaec6e2 --- /dev/null +++ b/Lang/Order/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Order \ No newline at end of file diff --git a/Lang/Order/Sort-an-integer-array b/Lang/Order/Sort-an-integer-array new file mode 120000 index 0000000000..61494d696b --- /dev/null +++ b/Lang/Order/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Order \ No newline at end of file diff --git a/Lang/Order/Sort-disjoint-sublist b/Lang/Order/Sort-disjoint-sublist new file mode 120000 index 0000000000..b8a2064a20 --- /dev/null +++ b/Lang/Order/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Order \ No newline at end of file diff --git a/Lang/Order/Sum-of-squares b/Lang/Order/Sum-of-squares new file mode 120000 index 0000000000..1b187a115d --- /dev/null +++ b/Lang/Order/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Order \ No newline at end of file diff --git a/Lang/Order/Y-combinator b/Lang/Order/Y-combinator new file mode 120000 index 0000000000..81e8c5bdc6 --- /dev/null +++ b/Lang/Order/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Order \ No newline at end of file diff --git a/Lang/OxygenBasic/Singleton b/Lang/OxygenBasic/Singleton new file mode 120000 index 0000000000..2ee5d31d49 --- /dev/null +++ b/Lang/OxygenBasic/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Stack b/Lang/OxygenBasic/Stack new file mode 120000 index 0000000000..52356dc417 --- /dev/null +++ b/Lang/OxygenBasic/Stack @@ -0,0 +1 @@ +../../Task/Stack/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Stack-traces b/Lang/OxygenBasic/Stack-traces new file mode 120000 index 0000000000..8a9f00e65b --- /dev/null +++ b/Lang/OxygenBasic/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/String-case b/Lang/OxygenBasic/String-case new file mode 120000 index 0000000000..9cf48e027a --- /dev/null +++ b/Lang/OxygenBasic/String-case @@ -0,0 +1 @@ +../../Task/String-case/OxygenBasic \ No newline at end of file diff --git a/Lang/Oz/Shell-one-liner b/Lang/Oz/Shell-one-liner new file mode 120000 index 0000000000..c1681fb677 --- /dev/null +++ b/Lang/Oz/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Oz \ No newline at end of file diff --git a/Lang/Oz/Short-circuit-evaluation b/Lang/Oz/Short-circuit-evaluation new file mode 120000 index 0000000000..503da6b43c --- /dev/null +++ b/Lang/Oz/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Oz \ No newline at end of file diff --git a/Lang/Oz/Sierpinski-carpet b/Lang/Oz/Sierpinski-carpet new file mode 120000 index 0000000000..00405ff919 --- /dev/null +++ b/Lang/Oz/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Oz \ No newline at end of file diff --git a/Lang/Oz/Sierpinski-triangle b/Lang/Oz/Sierpinski-triangle new file mode 120000 index 0000000000..33d5fe1ed5 --- /dev/null +++ b/Lang/Oz/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Oz \ No newline at end of file diff --git a/Lang/Oz/Sieve-of-Eratosthenes b/Lang/Oz/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..eb094adece --- /dev/null +++ b/Lang/Oz/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Oz \ No newline at end of file diff --git a/Lang/Oz/Simple-windowed-application b/Lang/Oz/Simple-windowed-application new file mode 120000 index 0000000000..5d109849f6 --- /dev/null +++ b/Lang/Oz/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Oz \ No newline at end of file diff --git a/Lang/Oz/Simulate-input-Keyboard b/Lang/Oz/Simulate-input-Keyboard new file mode 120000 index 0000000000..2726d9689f --- /dev/null +++ b/Lang/Oz/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Oz \ No newline at end of file diff --git a/Lang/Oz/Simulate-input-Mouse b/Lang/Oz/Simulate-input-Mouse new file mode 120000 index 0000000000..81a51ba68c --- /dev/null +++ b/Lang/Oz/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Oz \ No newline at end of file diff --git a/Lang/Oz/Singleton b/Lang/Oz/Singleton new file mode 120000 index 0000000000..46101165b3 --- /dev/null +++ b/Lang/Oz/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Oz \ No newline at end of file diff --git a/Lang/Oz/Sleep b/Lang/Oz/Sleep new file mode 120000 index 0000000000..ac0ac4c508 --- /dev/null +++ b/Lang/Oz/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Oz \ No newline at end of file diff --git a/Lang/Oz/Sockets b/Lang/Oz/Sockets new file mode 120000 index 0000000000..0e225b3b8a --- /dev/null +++ b/Lang/Oz/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Oz \ No newline at end of file diff --git a/Lang/Oz/Sort-an-array-of-composite-structures b/Lang/Oz/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..18aedb0883 --- /dev/null +++ b/Lang/Oz/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Oz \ No newline at end of file diff --git a/Lang/Oz/Sort-an-integer-array b/Lang/Oz/Sort-an-integer-array new file mode 120000 index 0000000000..a83a79e766 --- /dev/null +++ b/Lang/Oz/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Oz \ No newline at end of file diff --git a/Lang/Oz/Sort-stability b/Lang/Oz/Sort-stability new file mode 120000 index 0000000000..0948f0c2a4 --- /dev/null +++ b/Lang/Oz/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Oz \ No newline at end of file diff --git a/Lang/Oz/Sort-using-a-custom-comparator b/Lang/Oz/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..f7ec6938fe --- /dev/null +++ b/Lang/Oz/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Bogosort b/Lang/Oz/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..409a9ee005 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Bubble-sort b/Lang/Oz/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..903eeae9ab --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Cocktail-sort b/Lang/Oz/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..ff008d2c87 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Comb-sort b/Lang/Oz/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..dd7e932e43 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Counting-sort b/Lang/Oz/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..a1f5460908 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Gnome-sort b/Lang/Oz/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..0c41cf416d --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Heapsort b/Lang/Oz/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..4cc364915d --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Insertion-sort b/Lang/Oz/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..e84fbf066a --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Merge-sort b/Lang/Oz/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..62d9823d93 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Quicksort b/Lang/Oz/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ca157ead23 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Selection-sort b/Lang/Oz/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..6a4c509d15 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Sorting-algorithms-Stooge-sort b/Lang/Oz/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..727e1992b4 --- /dev/null +++ b/Lang/Oz/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Spiral-matrix b/Lang/Oz/Spiral-matrix new file mode 120000 index 0000000000..42b5565ec4 --- /dev/null +++ b/Lang/Oz/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Oz \ No newline at end of file diff --git a/Lang/Oz/Stack b/Lang/Oz/Stack new file mode 120000 index 0000000000..bc67c915a8 --- /dev/null +++ b/Lang/Oz/Stack @@ -0,0 +1 @@ +../../Task/Stack/Oz \ No newline at end of file diff --git a/Lang/Oz/Stack-traces b/Lang/Oz/Stack-traces new file mode 120000 index 0000000000..5018461efd --- /dev/null +++ b/Lang/Oz/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Oz \ No newline at end of file diff --git a/Lang/Oz/Stair-climbing-puzzle b/Lang/Oz/Stair-climbing-puzzle new file mode 120000 index 0000000000..940bb483e7 --- /dev/null +++ b/Lang/Oz/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Oz \ No newline at end of file diff --git a/Lang/Oz/String-case b/Lang/Oz/String-case new file mode 120000 index 0000000000..9231170c97 --- /dev/null +++ b/Lang/Oz/String-case @@ -0,0 +1 @@ +../../Task/String-case/Oz \ No newline at end of file diff --git a/Lang/Oz/String-concatenation b/Lang/Oz/String-concatenation new file mode 120000 index 0000000000..b98b496c80 --- /dev/null +++ b/Lang/Oz/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Oz \ No newline at end of file diff --git a/Lang/Oz/String-interpolation--included- b/Lang/Oz/String-interpolation--included- new file mode 120000 index 0000000000..b6a11bed1f --- /dev/null +++ b/Lang/Oz/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Oz \ No newline at end of file diff --git a/Lang/Oz/String-length b/Lang/Oz/String-length new file mode 120000 index 0000000000..9b6e13e878 --- /dev/null +++ b/Lang/Oz/String-length @@ -0,0 +1 @@ +../../Task/String-length/Oz \ No newline at end of file diff --git a/Lang/Oz/Substring b/Lang/Oz/Substring new file mode 120000 index 0000000000..ea76f995d4 --- /dev/null +++ b/Lang/Oz/Substring @@ -0,0 +1 @@ +../../Task/Substring/Oz \ No newline at end of file diff --git a/Lang/Oz/Sudoku b/Lang/Oz/Sudoku new file mode 120000 index 0000000000..e068a2aa03 --- /dev/null +++ b/Lang/Oz/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Oz \ No newline at end of file diff --git a/Lang/Oz/Sum-and-product-of-an-array b/Lang/Oz/Sum-and-product-of-an-array new file mode 120000 index 0000000000..d5167ca9c5 --- /dev/null +++ b/Lang/Oz/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Oz \ No newline at end of file diff --git a/Lang/Oz/Sum-of-a-series b/Lang/Oz/Sum-of-a-series new file mode 120000 index 0000000000..da678b71ee --- /dev/null +++ b/Lang/Oz/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Oz \ No newline at end of file diff --git a/Lang/Oz/Sum-of-squares b/Lang/Oz/Sum-of-squares new file mode 120000 index 0000000000..10e8bd94c0 --- /dev/null +++ b/Lang/Oz/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Oz \ No newline at end of file diff --git a/Lang/Oz/Symmetric-difference b/Lang/Oz/Symmetric-difference new file mode 120000 index 0000000000..76a9dae6f8 --- /dev/null +++ b/Lang/Oz/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Oz \ No newline at end of file diff --git a/Lang/Oz/Synchronous-concurrency b/Lang/Oz/Synchronous-concurrency new file mode 120000 index 0000000000..62effc9b14 --- /dev/null +++ b/Lang/Oz/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Oz \ No newline at end of file diff --git a/Lang/Oz/System-time b/Lang/Oz/System-time new file mode 120000 index 0000000000..7a917d2862 --- /dev/null +++ b/Lang/Oz/System-time @@ -0,0 +1 @@ +../../Task/System-time/Oz \ No newline at end of file diff --git a/Lang/Oz/Table-creation-Postal-addresses b/Lang/Oz/Table-creation-Postal-addresses new file mode 120000 index 0000000000..d5282b9427 --- /dev/null +++ b/Lang/Oz/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Oz \ No newline at end of file diff --git a/Lang/Oz/Take-notes-on-the-command-line b/Lang/Oz/Take-notes-on-the-command-line new file mode 120000 index 0000000000..ec54665af3 --- /dev/null +++ b/Lang/Oz/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Oz \ No newline at end of file diff --git a/Lang/Oz/Text-processing-Max-licenses-in-use b/Lang/Oz/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..a74e916805 --- /dev/null +++ b/Lang/Oz/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Oz \ No newline at end of file diff --git a/Lang/Oz/Time-a-function b/Lang/Oz/Time-a-function new file mode 120000 index 0000000000..959a3b952f --- /dev/null +++ b/Lang/Oz/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Oz \ No newline at end of file diff --git a/Lang/Oz/Tokenize-a-string b/Lang/Oz/Tokenize-a-string new file mode 120000 index 0000000000..ce82520a00 --- /dev/null +++ b/Lang/Oz/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Oz \ No newline at end of file diff --git a/Lang/Oz/Top-rank-per-group b/Lang/Oz/Top-rank-per-group new file mode 120000 index 0000000000..b00902e1a7 --- /dev/null +++ b/Lang/Oz/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Oz \ No newline at end of file diff --git a/Lang/Oz/Topological-sort b/Lang/Oz/Topological-sort new file mode 120000 index 0000000000..e3ac38030b --- /dev/null +++ b/Lang/Oz/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Oz \ No newline at end of file diff --git a/Lang/Oz/Towers-of-Hanoi b/Lang/Oz/Towers-of-Hanoi new file mode 120000 index 0000000000..b49d8b7d8a --- /dev/null +++ b/Lang/Oz/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Oz \ No newline at end of file diff --git a/Lang/Oz/Tree-traversal b/Lang/Oz/Tree-traversal new file mode 120000 index 0000000000..9c45952222 --- /dev/null +++ b/Lang/Oz/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Oz \ No newline at end of file diff --git a/Lang/Oz/Trigonometric-functions b/Lang/Oz/Trigonometric-functions new file mode 120000 index 0000000000..6c4997f240 --- /dev/null +++ b/Lang/Oz/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Oz \ No newline at end of file diff --git a/Lang/Oz/Undefined-values b/Lang/Oz/Undefined-values new file mode 120000 index 0000000000..0e864549e7 --- /dev/null +++ b/Lang/Oz/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Oz \ No newline at end of file diff --git a/Lang/Oz/User-input-Graphical b/Lang/Oz/User-input-Graphical new file mode 120000 index 0000000000..061e321f08 --- /dev/null +++ b/Lang/Oz/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Oz \ No newline at end of file diff --git a/Lang/Oz/User-input-Text b/Lang/Oz/User-input-Text new file mode 120000 index 0000000000..dd0dc5f26b --- /dev/null +++ b/Lang/Oz/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Oz \ No newline at end of file diff --git a/Lang/Oz/Variables b/Lang/Oz/Variables new file mode 120000 index 0000000000..e647db95c7 --- /dev/null +++ b/Lang/Oz/Variables @@ -0,0 +1 @@ +../../Task/Variables/Oz \ No newline at end of file diff --git a/Lang/Oz/Variadic-function b/Lang/Oz/Variadic-function new file mode 120000 index 0000000000..bf53568a3b --- /dev/null +++ b/Lang/Oz/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Oz \ No newline at end of file diff --git a/Lang/Oz/Walk-a-directory-Non-recursively b/Lang/Oz/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b735b8c349 --- /dev/null +++ b/Lang/Oz/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Oz \ No newline at end of file diff --git a/Lang/Oz/Walk-a-directory-Recursively b/Lang/Oz/Walk-a-directory-Recursively new file mode 120000 index 0000000000..3b6a0b0d7c --- /dev/null +++ b/Lang/Oz/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Oz \ No newline at end of file diff --git a/Lang/Oz/Web-scraping b/Lang/Oz/Web-scraping new file mode 120000 index 0000000000..e47ba383a2 --- /dev/null +++ b/Lang/Oz/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Oz \ No newline at end of file diff --git a/Lang/Oz/Window-creation b/Lang/Oz/Window-creation new file mode 120000 index 0000000000..1453cf86a6 --- /dev/null +++ b/Lang/Oz/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Oz \ No newline at end of file diff --git a/Lang/Oz/Window-management b/Lang/Oz/Window-management new file mode 120000 index 0000000000..dab38c9930 --- /dev/null +++ b/Lang/Oz/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Oz \ No newline at end of file diff --git a/Lang/Oz/Wireworld b/Lang/Oz/Wireworld new file mode 120000 index 0000000000..4d82ff88df --- /dev/null +++ b/Lang/Oz/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Oz \ No newline at end of file diff --git a/Lang/Oz/XML-DOM-serialization b/Lang/Oz/XML-DOM-serialization new file mode 120000 index 0000000000..856e06c0ab --- /dev/null +++ b/Lang/Oz/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Oz \ No newline at end of file diff --git a/Lang/Oz/XML-Input b/Lang/Oz/XML-Input new file mode 120000 index 0000000000..a8326841ac --- /dev/null +++ b/Lang/Oz/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Oz \ No newline at end of file diff --git a/Lang/Oz/XML-Output b/Lang/Oz/XML-Output new file mode 120000 index 0000000000..f26a94f9a1 --- /dev/null +++ b/Lang/Oz/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Oz \ No newline at end of file diff --git a/Lang/Oz/XML-XPath b/Lang/Oz/XML-XPath new file mode 120000 index 0000000000..088890592c --- /dev/null +++ b/Lang/Oz/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Oz \ No newline at end of file diff --git a/Lang/Oz/Y-combinator b/Lang/Oz/Y-combinator new file mode 120000 index 0000000000..48b9a6b974 --- /dev/null +++ b/Lang/Oz/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Oz \ No newline at end of file diff --git a/Lang/Oz/Yahoo--search-interface b/Lang/Oz/Yahoo--search-interface new file mode 120000 index 0000000000..3038770512 --- /dev/null +++ b/Lang/Oz/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Oz \ No newline at end of file diff --git a/Lang/Oz/Zig-zag-matrix b/Lang/Oz/Zig-zag-matrix new file mode 120000 index 0000000000..2824e411a2 --- /dev/null +++ b/Lang/Oz/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/Seven-sided-dice-from-five-sided-dice b/Lang/PARI-GP/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..14f4937c57 --- /dev/null +++ b/Lang/PARI-GP/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Shell-one-liner b/Lang/PARI-GP/Shell-one-liner new file mode 120000 index 0000000000..679da38e6e --- /dev/null +++ b/Lang/PARI-GP/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Short-circuit-evaluation b/Lang/PARI-GP/Short-circuit-evaluation new file mode 120000 index 0000000000..7b55935182 --- /dev/null +++ b/Lang/PARI-GP/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sieve-of-Eratosthenes b/Lang/PARI-GP/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..49f0d5056a --- /dev/null +++ b/Lang/PARI-GP/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sleep b/Lang/PARI-GP/Sleep new file mode 120000 index 0000000000..682d0d52a7 --- /dev/null +++ b/Lang/PARI-GP/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sort-an-array-of-composite-structures b/Lang/PARI-GP/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..bdabbb65c4 --- /dev/null +++ b/Lang/PARI-GP/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sort-an-integer-array b/Lang/PARI-GP/Sort-an-integer-array new file mode 120000 index 0000000000..5d0c9d58f6 --- /dev/null +++ b/Lang/PARI-GP/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sort-disjoint-sublist b/Lang/PARI-GP/Sort-disjoint-sublist new file mode 120000 index 0000000000..280ea069d7 --- /dev/null +++ b/Lang/PARI-GP/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sort-using-a-custom-comparator b/Lang/PARI-GP/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..61ee9a2834 --- /dev/null +++ b/Lang/PARI-GP/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Bead-sort b/Lang/PARI-GP/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..3cea87c8e2 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Bogosort b/Lang/PARI-GP/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..70f8f83a63 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Bubble-sort b/Lang/PARI-GP/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..925adef0ee --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Cocktail-sort b/Lang/PARI-GP/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..72feacb253 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Comb-sort b/Lang/PARI-GP/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..c2a4f0c8ae --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Counting-sort b/Lang/PARI-GP/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..16aef3baea --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Gnome-sort b/Lang/PARI-GP/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7b457d205d --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Insertion-sort b/Lang/PARI-GP/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..a41b696020 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Merge-sort b/Lang/PARI-GP/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..88d545802b --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Pancake-sort b/Lang/PARI-GP/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..6df58959f7 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Permutation-sort b/Lang/PARI-GP/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..67c09321fd --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Quicksort b/Lang/PARI-GP/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..60299f8f01 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Selection-sort b/Lang/PARI-GP/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..6f80bfd942 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Shell-sort b/Lang/PARI-GP/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..25ce3fa65e --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Stooge-sort b/Lang/PARI-GP/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..60b6d2d557 --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-algorithms-Strand-sort b/Lang/PARI-GP/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..9946c6577d --- /dev/null +++ b/Lang/PARI-GP/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Special-characters b/Lang/PARI-GP/Special-characters new file mode 120000 index 0000000000..5370c280a6 --- /dev/null +++ b/Lang/PARI-GP/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Stack b/Lang/PARI-GP/Stack new file mode 120000 index 0000000000..dbc769f6ad --- /dev/null +++ b/Lang/PARI-GP/Stack @@ -0,0 +1 @@ +../../Task/Stack/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Stair-climbing-puzzle b/Lang/PARI-GP/Stair-climbing-puzzle new file mode 120000 index 0000000000..162fcc71f0 --- /dev/null +++ b/Lang/PARI-GP/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Standard-deviation b/Lang/PARI-GP/Standard-deviation new file mode 120000 index 0000000000..4369e11be2 --- /dev/null +++ b/Lang/PARI-GP/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-concatenation b/Lang/PARI-GP/String-concatenation new file mode 120000 index 0000000000..01c8cc2dfb --- /dev/null +++ b/Lang/PARI-GP/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-interpolation--included- b/Lang/PARI-GP/String-interpolation--included- new file mode 120000 index 0000000000..bd05766ffd --- /dev/null +++ b/Lang/PARI-GP/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/String-length b/Lang/PARI-GP/String-length new file mode 120000 index 0000000000..0e3bb04b64 --- /dev/null +++ b/Lang/PARI-GP/String-length @@ -0,0 +1 @@ +../../Task/String-length/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Strip-a-set-of-characters-from-a-string b/Lang/PARI-GP/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..1bb3f07b50 --- /dev/null +++ b/Lang/PARI-GP/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Substring-Top-and-tail b/Lang/PARI-GP/Substring-Top-and-tail new file mode 120000 index 0000000000..9455daa046 --- /dev/null +++ b/Lang/PARI-GP/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Subtractive-generator b/Lang/PARI-GP/Subtractive-generator new file mode 120000 index 0000000000..6ef5c03e72 --- /dev/null +++ b/Lang/PARI-GP/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sum-and-product-of-an-array b/Lang/PARI-GP/Sum-and-product-of-an-array new file mode 120000 index 0000000000..7ae9b34eb8 --- /dev/null +++ b/Lang/PARI-GP/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sum-digits-of-an-integer b/Lang/PARI-GP/Sum-digits-of-an-integer new file mode 120000 index 0000000000..b55108a703 --- /dev/null +++ b/Lang/PARI-GP/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sum-of-a-series b/Lang/PARI-GP/Sum-of-a-series new file mode 120000 index 0000000000..e8a07eb4fb --- /dev/null +++ b/Lang/PARI-GP/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sum-of-squares b/Lang/PARI-GP/Sum-of-squares new file mode 120000 index 0000000000..363d871182 --- /dev/null +++ b/Lang/PARI-GP/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Symmetric-difference b/Lang/PARI-GP/Symmetric-difference new file mode 120000 index 0000000000..6c95772b36 --- /dev/null +++ b/Lang/PARI-GP/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/System-time b/Lang/PARI-GP/System-time new file mode 120000 index 0000000000..99c80572d7 --- /dev/null +++ b/Lang/PARI-GP/System-time @@ -0,0 +1 @@ +../../Task/System-time/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Temperature-conversion b/Lang/PARI-GP/Temperature-conversion new file mode 120000 index 0000000000..ee467aa287 --- /dev/null +++ b/Lang/PARI-GP/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Text-processing-Max-licenses-in-use b/Lang/PARI-GP/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..b6afa5ac5d --- /dev/null +++ b/Lang/PARI-GP/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Time-a-function b/Lang/PARI-GP/Time-a-function new file mode 120000 index 0000000000..dbd81060d6 --- /dev/null +++ b/Lang/PARI-GP/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Top-rank-per-group b/Lang/PARI-GP/Top-rank-per-group new file mode 120000 index 0000000000..4cb79f0ee4 --- /dev/null +++ b/Lang/PARI-GP/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Trabb-Pardo-Knuth-algorithm b/Lang/PARI-GP/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..0bc3e478c5 --- /dev/null +++ b/Lang/PARI-GP/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Trigonometric-functions b/Lang/PARI-GP/Trigonometric-functions new file mode 120000 index 0000000000..80511536a6 --- /dev/null +++ b/Lang/PARI-GP/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Truncatable-primes b/Lang/PARI-GP/Truncatable-primes new file mode 120000 index 0000000000..50a3cbb6c8 --- /dev/null +++ b/Lang/PARI-GP/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Unbias-a-random-generator b/Lang/PARI-GP/Unbias-a-random-generator new file mode 120000 index 0000000000..1923daf466 --- /dev/null +++ b/Lang/PARI-GP/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Undefined-values b/Lang/PARI-GP/Undefined-values new file mode 120000 index 0000000000..c8211bbf0c --- /dev/null +++ b/Lang/PARI-GP/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/User-input-Text b/Lang/PARI-GP/User-input-Text new file mode 120000 index 0000000000..bb38008703 --- /dev/null +++ b/Lang/PARI-GP/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Van-der-Corput-sequence b/Lang/PARI-GP/Van-der-Corput-sequence new file mode 120000 index 0000000000..3629618cb1 --- /dev/null +++ b/Lang/PARI-GP/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Variable-size-Get b/Lang/PARI-GP/Variable-size-Get new file mode 120000 index 0000000000..62c2603da9 --- /dev/null +++ b/Lang/PARI-GP/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Variable-size-Set b/Lang/PARI-GP/Variable-size-Set new file mode 120000 index 0000000000..640089b03e --- /dev/null +++ b/Lang/PARI-GP/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Variables b/Lang/PARI-GP/Variables new file mode 120000 index 0000000000..1438ab6e0d --- /dev/null +++ b/Lang/PARI-GP/Variables @@ -0,0 +1 @@ +../../Task/Variables/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Vector-products b/Lang/PARI-GP/Vector-products new file mode 120000 index 0000000000..32f62a9f94 --- /dev/null +++ b/Lang/PARI-GP/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Verify-distribution-uniformity-Chi-squared-test b/Lang/PARI-GP/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..4cc9bbb286 --- /dev/null +++ b/Lang/PARI-GP/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Verify-distribution-uniformity-Naive b/Lang/PARI-GP/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..af48fbeda0 --- /dev/null +++ b/Lang/PARI-GP/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Wireworld b/Lang/PARI-GP/Wireworld new file mode 120000 index 0000000000..7096b6bec5 --- /dev/null +++ b/Lang/PARI-GP/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Word-wrap b/Lang/PARI-GP/Word-wrap new file mode 120000 index 0000000000..f393c6fcf0 --- /dev/null +++ b/Lang/PARI-GP/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Write-float-arrays-to-a-text-file b/Lang/PARI-GP/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..23c9f92382 --- /dev/null +++ b/Lang/PARI-GP/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Zeckendorf-number-representation b/Lang/PARI-GP/Zeckendorf-number-representation new file mode 120000 index 0000000000..36cd7a508d --- /dev/null +++ b/Lang/PARI-GP/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Zig-zag-matrix b/Lang/PARI-GP/Zig-zag-matrix new file mode 120000 index 0000000000..64afe3cf95 --- /dev/null +++ b/Lang/PARI-GP/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/SHA-1 b/Lang/PHP/SHA-1 new file mode 120000 index 0000000000..6dfde3be90 --- /dev/null +++ b/Lang/PHP/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/PHP \ No newline at end of file diff --git a/Lang/PHP/SHA-256 b/Lang/PHP/SHA-256 new file mode 120000 index 0000000000..98425fe764 --- /dev/null +++ b/Lang/PHP/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/PHP \ No newline at end of file diff --git a/Lang/PHP/SOAP b/Lang/PHP/SOAP new file mode 120000 index 0000000000..45334c4289 --- /dev/null +++ b/Lang/PHP/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/PHP \ No newline at end of file diff --git a/Lang/PHP/SQL-based-authentication b/Lang/PHP/SQL-based-authentication new file mode 120000 index 0000000000..d97dfdff07 --- /dev/null +++ b/Lang/PHP/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/PHP \ No newline at end of file diff --git a/Lang/PHP/Shell-one-liner b/Lang/PHP/Shell-one-liner new file mode 120000 index 0000000000..a28702f20f --- /dev/null +++ b/Lang/PHP/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/PHP \ No newline at end of file diff --git a/Lang/PHP/Show-the-epoch b/Lang/PHP/Show-the-epoch new file mode 120000 index 0000000000..084a2c94e5 --- /dev/null +++ b/Lang/PHP/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PHP \ No newline at end of file diff --git a/Lang/PHP/Sieve-of-Eratosthenes b/Lang/PHP/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..8565cfce2c --- /dev/null +++ b/Lang/PHP/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PHP \ No newline at end of file diff --git a/Lang/PHP/Singleton b/Lang/PHP/Singleton new file mode 120000 index 0000000000..b6c2ee39fc --- /dev/null +++ b/Lang/PHP/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/PHP \ No newline at end of file diff --git a/Lang/PHP/Sleep b/Lang/PHP/Sleep new file mode 120000 index 0000000000..11ac96f39b --- /dev/null +++ b/Lang/PHP/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PHP \ No newline at end of file diff --git a/Lang/PHP/Sockets b/Lang/PHP/Sockets new file mode 120000 index 0000000000..fc42322e8d --- /dev/null +++ b/Lang/PHP/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/PHP \ No newline at end of file diff --git a/Lang/PHP/Sort-an-integer-array b/Lang/PHP/Sort-an-integer-array new file mode 120000 index 0000000000..ae006443e5 --- /dev/null +++ b/Lang/PHP/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PHP \ No newline at end of file diff --git a/Lang/PHP/Sort-using-a-custom-comparator b/Lang/PHP/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..c9d146c7be --- /dev/null +++ b/Lang/PHP/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Bead-sort b/Lang/PHP/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..cfc2e2b895 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Bogosort b/Lang/PHP/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..1ea8c7ea34 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Bubble-sort b/Lang/PHP/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..9f0b70c502 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Cocktail-sort b/Lang/PHP/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..2bceff4ea6 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Comb-sort b/Lang/PHP/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..f33545229a --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Counting-sort b/Lang/PHP/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c6093cba04 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Gnome-sort b/Lang/PHP/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..17dd97c9f6 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Insertion-sort b/Lang/PHP/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..71d98d4c24 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Merge-sort b/Lang/PHP/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..8795b9a3f9 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Permutation-sort b/Lang/PHP/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..aecdf34861 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Quicksort b/Lang/PHP/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..c347c3dec5 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Selection-sort b/Lang/PHP/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ee1c7c482c --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Shell-sort b/Lang/PHP/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..2f327553df --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Stooge-sort b/Lang/PHP/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..f1ed61fd79 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Sorting-algorithms-Strand-sort b/Lang/PHP/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..6511a59939 --- /dev/null +++ b/Lang/PHP/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/PHP \ No newline at end of file diff --git a/Lang/PHP/Soundex b/Lang/PHP/Soundex new file mode 120000 index 0000000000..509ac1988e --- /dev/null +++ b/Lang/PHP/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/PHP \ No newline at end of file diff --git a/Lang/PHP/Stack b/Lang/PHP/Stack new file mode 120000 index 0000000000..a7c8fb06e9 --- /dev/null +++ b/Lang/PHP/Stack @@ -0,0 +1 @@ +../../Task/Stack/PHP \ No newline at end of file diff --git a/Lang/PHP/Stack-traces b/Lang/PHP/Stack-traces new file mode 120000 index 0000000000..8d347a8f89 --- /dev/null +++ b/Lang/PHP/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PHP \ No newline at end of file diff --git a/Lang/PHP/String-case b/Lang/PHP/String-case new file mode 120000 index 0000000000..d683109166 --- /dev/null +++ b/Lang/PHP/String-case @@ -0,0 +1 @@ +../../Task/String-case/PHP \ No newline at end of file diff --git a/Lang/PHP/String-concatenation b/Lang/PHP/String-concatenation new file mode 120000 index 0000000000..e896369dbc --- /dev/null +++ b/Lang/PHP/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PHP \ No newline at end of file diff --git a/Lang/PHP/String-interpolation--included- b/Lang/PHP/String-interpolation--included- new file mode 120000 index 0000000000..c814abb4d6 --- /dev/null +++ b/Lang/PHP/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PHP \ No newline at end of file diff --git a/Lang/PHP/String-length b/Lang/PHP/String-length new file mode 120000 index 0000000000..6d4fa6b53b --- /dev/null +++ b/Lang/PHP/String-length @@ -0,0 +1 @@ +../../Task/String-length/PHP \ No newline at end of file diff --git a/Lang/PHP/Strip-a-set-of-characters-from-a-string b/Lang/PHP/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..d25bfd1610 --- /dev/null +++ b/Lang/PHP/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PHP \ No newline at end of file diff --git a/Lang/PHP/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PHP/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..b7e666d003 --- /dev/null +++ b/Lang/PHP/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PHP \ No newline at end of file diff --git a/Lang/PHP/Substring b/Lang/PHP/Substring new file mode 120000 index 0000000000..9c73bc162f --- /dev/null +++ b/Lang/PHP/Substring @@ -0,0 +1 @@ +../../Task/Substring/PHP \ No newline at end of file diff --git a/Lang/PHP/Substring-Top-and-tail b/Lang/PHP/Substring-Top-and-tail new file mode 120000 index 0000000000..1ac5c6206f --- /dev/null +++ b/Lang/PHP/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PHP \ No newline at end of file diff --git a/Lang/PHP/Sum-and-product-of-an-array b/Lang/PHP/Sum-and-product-of-an-array new file mode 120000 index 0000000000..121b53e336 --- /dev/null +++ b/Lang/PHP/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PHP \ No newline at end of file diff --git a/Lang/PHP/Sum-digits-of-an-integer b/Lang/PHP/Sum-digits-of-an-integer new file mode 120000 index 0000000000..3d575fc14f --- /dev/null +++ b/Lang/PHP/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PHP \ No newline at end of file diff --git a/Lang/PHP/Sum-of-a-series b/Lang/PHP/Sum-of-a-series new file mode 120000 index 0000000000..584fa576c4 --- /dev/null +++ b/Lang/PHP/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PHP \ No newline at end of file diff --git a/Lang/PHP/Sum-of-squares b/Lang/PHP/Sum-of-squares new file mode 120000 index 0000000000..33433f3d5e --- /dev/null +++ b/Lang/PHP/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PHP \ No newline at end of file diff --git a/Lang/PHP/Symmetric-difference b/Lang/PHP/Symmetric-difference new file mode 120000 index 0000000000..bf24acbe0a --- /dev/null +++ b/Lang/PHP/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PHP \ No newline at end of file diff --git a/Lang/PHP/System-time b/Lang/PHP/System-time new file mode 120000 index 0000000000..403c1ffe8b --- /dev/null +++ b/Lang/PHP/System-time @@ -0,0 +1 @@ +../../Task/System-time/PHP \ No newline at end of file diff --git a/Lang/PHP/Table-creation-Postal-addresses b/Lang/PHP/Table-creation-Postal-addresses new file mode 120000 index 0000000000..605b6329f3 --- /dev/null +++ b/Lang/PHP/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/PHP \ No newline at end of file diff --git a/Lang/PHP/Take-notes-on-the-command-line b/Lang/PHP/Take-notes-on-the-command-line new file mode 120000 index 0000000000..a2cecaf39e --- /dev/null +++ b/Lang/PHP/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PHP \ No newline at end of file diff --git a/Lang/PHP/Temperature-conversion b/Lang/PHP/Temperature-conversion new file mode 120000 index 0000000000..ae82befc02 --- /dev/null +++ b/Lang/PHP/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PHP \ No newline at end of file diff --git a/Lang/PHP/Text-processing-2 b/Lang/PHP/Text-processing-2 new file mode 120000 index 0000000000..1e2381faff --- /dev/null +++ b/Lang/PHP/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/PHP \ No newline at end of file diff --git a/Lang/PHP/Text-processing-Max-licenses-in-use b/Lang/PHP/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..ec4ea63405 --- /dev/null +++ b/Lang/PHP/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/PHP \ No newline at end of file diff --git a/Lang/PHP/Tokenize-a-string b/Lang/PHP/Tokenize-a-string new file mode 120000 index 0000000000..72deb2aa7e --- /dev/null +++ b/Lang/PHP/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PHP \ No newline at end of file diff --git a/Lang/PHP/Top-rank-per-group b/Lang/PHP/Top-rank-per-group new file mode 120000 index 0000000000..6a85103806 --- /dev/null +++ b/Lang/PHP/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PHP \ No newline at end of file diff --git a/Lang/PHP/Towers-of-Hanoi b/Lang/PHP/Towers-of-Hanoi new file mode 120000 index 0000000000..fdd065f0a3 --- /dev/null +++ b/Lang/PHP/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PHP \ No newline at end of file diff --git a/Lang/PHP/Trigonometric-functions b/Lang/PHP/Trigonometric-functions new file mode 120000 index 0000000000..f73df03bde --- /dev/null +++ b/Lang/PHP/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PHP \ No newline at end of file diff --git a/Lang/PHP/URL-decoding b/Lang/PHP/URL-decoding new file mode 120000 index 0000000000..0ffeda6384 --- /dev/null +++ b/Lang/PHP/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/PHP \ No newline at end of file diff --git a/Lang/PHP/URL-encoding b/Lang/PHP/URL-encoding new file mode 120000 index 0000000000..0f8704d535 --- /dev/null +++ b/Lang/PHP/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PHP \ No newline at end of file diff --git a/Lang/PHP/Undefined-values b/Lang/PHP/Undefined-values new file mode 120000 index 0000000000..a563741bb1 --- /dev/null +++ b/Lang/PHP/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PHP \ No newline at end of file diff --git a/Lang/PHP/Unicode-variable-names b/Lang/PHP/Unicode-variable-names new file mode 120000 index 0000000000..e745dd4b8e --- /dev/null +++ b/Lang/PHP/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/PHP \ No newline at end of file diff --git a/Lang/PHP/User-input-Text b/Lang/PHP/User-input-Text new file mode 120000 index 0000000000..2b6da32093 --- /dev/null +++ b/Lang/PHP/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PHP \ No newline at end of file diff --git a/Lang/PHP/Variables b/Lang/PHP/Variables new file mode 120000 index 0000000000..52e6610e88 --- /dev/null +++ b/Lang/PHP/Variables @@ -0,0 +1 @@ +../../Task/Variables/PHP \ No newline at end of file diff --git a/Lang/PHP/Variadic-function b/Lang/PHP/Variadic-function new file mode 120000 index 0000000000..2d9f9def82 --- /dev/null +++ b/Lang/PHP/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PHP \ No newline at end of file diff --git a/Lang/PHP/Walk-a-directory-Non-recursively b/Lang/PHP/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..d4fc13b620 --- /dev/null +++ b/Lang/PHP/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PHP \ No newline at end of file diff --git a/Lang/PHP/Walk-a-directory-Recursively b/Lang/PHP/Walk-a-directory-Recursively new file mode 120000 index 0000000000..ac5ae2a131 --- /dev/null +++ b/Lang/PHP/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PHP \ No newline at end of file diff --git a/Lang/PHP/Web-scraping b/Lang/PHP/Web-scraping new file mode 120000 index 0000000000..acd9e3e285 --- /dev/null +++ b/Lang/PHP/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/PHP \ No newline at end of file diff --git a/Lang/PHP/Wireworld b/Lang/PHP/Wireworld new file mode 120000 index 0000000000..c36d65dbbf --- /dev/null +++ b/Lang/PHP/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/PHP \ No newline at end of file diff --git a/Lang/PHP/XML-DOM-serialization b/Lang/PHP/XML-DOM-serialization new file mode 120000 index 0000000000..e414101e92 --- /dev/null +++ b/Lang/PHP/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/PHP \ No newline at end of file diff --git a/Lang/PHP/XML-Input b/Lang/PHP/XML-Input new file mode 120000 index 0000000000..2046521695 --- /dev/null +++ b/Lang/PHP/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PHP \ No newline at end of file diff --git a/Lang/PHP/XML-XPath b/Lang/PHP/XML-XPath new file mode 120000 index 0000000000..97ba05ff37 --- /dev/null +++ b/Lang/PHP/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/PHP \ No newline at end of file diff --git a/Lang/PHP/Y-combinator b/Lang/PHP/Y-combinator new file mode 120000 index 0000000000..4f54cd51f4 --- /dev/null +++ b/Lang/PHP/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/PHP \ No newline at end of file diff --git a/Lang/PHP/Zig-zag-matrix b/Lang/PHP/Zig-zag-matrix new file mode 120000 index 0000000000..c4e33a9eea --- /dev/null +++ b/Lang/PHP/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PHP \ No newline at end of file diff --git a/Lang/PL-I/Short-circuit-evaluation b/Lang/PL-I/Short-circuit-evaluation new file mode 120000 index 0000000000..3c0a7c246a --- /dev/null +++ b/Lang/PL-I/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Show-the-epoch b/Lang/PL-I/Show-the-epoch new file mode 120000 index 0000000000..b82b1d0ea5 --- /dev/null +++ b/Lang/PL-I/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sierpinski-triangle b/Lang/PL-I/Sierpinski-triangle new file mode 120000 index 0000000000..d15f57b683 --- /dev/null +++ b/Lang/PL-I/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sieve-of-Eratosthenes b/Lang/PL-I/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..fcbb4b64ae --- /dev/null +++ b/Lang/PL-I/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sleep b/Lang/PL-I/Sleep new file mode 120000 index 0000000000..dc4a066bc9 --- /dev/null +++ b/Lang/PL-I/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sort-an-integer-array b/Lang/PL-I/Sort-an-integer-array new file mode 120000 index 0000000000..a93805e47f --- /dev/null +++ b/Lang/PL-I/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sort-using-a-custom-comparator b/Lang/PL-I/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..79cc33a2f5 --- /dev/null +++ b/Lang/PL-I/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Bead-sort b/Lang/PL-I/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..00e0ddd7cc --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Bubble-sort b/Lang/PL-I/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..87f775cf14 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Cocktail-sort b/Lang/PL-I/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..692f2f1b0f --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Comb-sort b/Lang/PL-I/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..ef5e4b43c7 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Counting-sort b/Lang/PL-I/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..5111994f03 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Insertion-sort b/Lang/PL-I/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..90b6ba4df3 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Merge-sort b/Lang/PL-I/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..07b69e9f9f --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Pancake-sort b/Lang/PL-I/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..d99fc897d5 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Quicksort b/Lang/PL-I/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..342d3f8a0b --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Shell-sort b/Lang/PL-I/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..59d3960343 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Stooge-sort b/Lang/PL-I/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..3627383524 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Strand-sort b/Lang/PL-I/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..425fb79aae --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Soundex b/Lang/PL-I/Soundex new file mode 120000 index 0000000000..fcd707f0ad --- /dev/null +++ b/Lang/PL-I/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Special-characters b/Lang/PL-I/Special-characters new file mode 120000 index 0000000000..18c06c2e15 --- /dev/null +++ b/Lang/PL-I/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Spiral-matrix b/Lang/PL-I/Spiral-matrix new file mode 120000 index 0000000000..86185ba3c0 --- /dev/null +++ b/Lang/PL-I/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Stack b/Lang/PL-I/Stack new file mode 120000 index 0000000000..520ab207f4 --- /dev/null +++ b/Lang/PL-I/Stack @@ -0,0 +1 @@ +../../Task/Stack/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Stack-traces b/Lang/PL-I/Stack-traces new file mode 120000 index 0000000000..bd5cab283a --- /dev/null +++ b/Lang/PL-I/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Standard-deviation b/Lang/PL-I/Standard-deviation new file mode 120000 index 0000000000..a7ef1c963b --- /dev/null +++ b/Lang/PL-I/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-case b/Lang/PL-I/String-case new file mode 120000 index 0000000000..1fd6b76c02 --- /dev/null +++ b/Lang/PL-I/String-case @@ -0,0 +1 @@ +../../Task/String-case/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-concatenation b/Lang/PL-I/String-concatenation new file mode 120000 index 0000000000..65340516a0 --- /dev/null +++ b/Lang/PL-I/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/String-length b/Lang/PL-I/String-length new file mode 120000 index 0000000000..45398a17f1 --- /dev/null +++ b/Lang/PL-I/String-length @@ -0,0 +1 @@ +../../Task/String-length/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Strip-a-set-of-characters-from-a-string b/Lang/PL-I/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..fd071f94de --- /dev/null +++ b/Lang/PL-I/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Strip-block-comments b/Lang/PL-I/Strip-block-comments new file mode 120000 index 0000000000..c8064cb6e6 --- /dev/null +++ b/Lang/PL-I/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Strip-comments-from-a-string b/Lang/PL-I/Strip-comments-from-a-string new file mode 120000 index 0000000000..aba045ad19 --- /dev/null +++ b/Lang/PL-I/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PL-I/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..f2a926297d --- /dev/null +++ b/Lang/PL-I/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PL-I/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..b3c860ba6e --- /dev/null +++ b/Lang/PL-I/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Substring b/Lang/PL-I/Substring new file mode 120000 index 0000000000..1a2d3cd276 --- /dev/null +++ b/Lang/PL-I/Substring @@ -0,0 +1 @@ +../../Task/Substring/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Substring-Top-and-tail b/Lang/PL-I/Substring-Top-and-tail new file mode 120000 index 0000000000..3b1fb40c70 --- /dev/null +++ b/Lang/PL-I/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Subtractive-generator b/Lang/PL-I/Subtractive-generator new file mode 120000 index 0000000000..c89950fd1f --- /dev/null +++ b/Lang/PL-I/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sum-and-product-of-an-array b/Lang/PL-I/Sum-and-product-of-an-array new file mode 120000 index 0000000000..118335327e --- /dev/null +++ b/Lang/PL-I/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sum-digits-of-an-integer b/Lang/PL-I/Sum-digits-of-an-integer new file mode 120000 index 0000000000..b75adac2c8 --- /dev/null +++ b/Lang/PL-I/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sum-of-a-series b/Lang/PL-I/Sum-of-a-series new file mode 120000 index 0000000000..e408517255 --- /dev/null +++ b/Lang/PL-I/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sum-of-squares b/Lang/PL-I/Sum-of-squares new file mode 120000 index 0000000000..54dd5c976f --- /dev/null +++ b/Lang/PL-I/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PL-I \ No newline at end of file diff --git a/Lang/PL-I/System-time b/Lang/PL-I/System-time new file mode 120000 index 0000000000..460fe617cd --- /dev/null +++ b/Lang/PL-I/System-time @@ -0,0 +1 @@ +../../Task/System-time/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Terminal-control-Display-an-extended-character b/Lang/PL-I/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..0825b5c503 --- /dev/null +++ b/Lang/PL-I/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Terminal-control-Ringing-the-terminal-bell b/Lang/PL-I/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..99a9118463 --- /dev/null +++ b/Lang/PL-I/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Text-processing-1 b/Lang/PL-I/Text-processing-1 new file mode 120000 index 0000000000..3fe3368d6a --- /dev/null +++ b/Lang/PL-I/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Text-processing-2 b/Lang/PL-I/Text-processing-2 new file mode 120000 index 0000000000..79e8122c74 --- /dev/null +++ b/Lang/PL-I/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Text-processing-Max-licenses-in-use b/Lang/PL-I/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..c2cf2fb10b --- /dev/null +++ b/Lang/PL-I/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Time-a-function b/Lang/PL-I/Time-a-function new file mode 120000 index 0000000000..c6c1b700e7 --- /dev/null +++ b/Lang/PL-I/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Tokenize-a-string b/Lang/PL-I/Tokenize-a-string new file mode 120000 index 0000000000..20a3124893 --- /dev/null +++ b/Lang/PL-I/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Towers-of-Hanoi b/Lang/PL-I/Towers-of-Hanoi new file mode 120000 index 0000000000..2164f5cbb3 --- /dev/null +++ b/Lang/PL-I/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Trigonometric-functions b/Lang/PL-I/Trigonometric-functions new file mode 120000 index 0000000000..9329f84787 --- /dev/null +++ b/Lang/PL-I/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Truncatable-primes b/Lang/PL-I/Truncatable-primes new file mode 120000 index 0000000000..8de789e6a1 --- /dev/null +++ b/Lang/PL-I/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Truncate-a-file b/Lang/PL-I/Truncate-a-file new file mode 120000 index 0000000000..38e49dba6e --- /dev/null +++ b/Lang/PL-I/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Unbias-a-random-generator b/Lang/PL-I/Unbias-a-random-generator new file mode 120000 index 0000000000..c543550685 --- /dev/null +++ b/Lang/PL-I/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/PL-I \ No newline at end of file diff --git a/Lang/PL-I/User-input-Text b/Lang/PL-I/User-input-Text new file mode 120000 index 0000000000..eacd790d45 --- /dev/null +++ b/Lang/PL-I/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Van-der-Corput-sequence b/Lang/PL-I/Van-der-Corput-sequence new file mode 120000 index 0000000000..97070ec9d0 --- /dev/null +++ b/Lang/PL-I/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Variable-length-quantity b/Lang/PL-I/Variable-length-quantity new file mode 120000 index 0000000000..567e315cfa --- /dev/null +++ b/Lang/PL-I/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Variable-size-Get b/Lang/PL-I/Variable-size-Get new file mode 120000 index 0000000000..e190abb6b0 --- /dev/null +++ b/Lang/PL-I/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Variable-size-Set b/Lang/PL-I/Variable-size-Set new file mode 120000 index 0000000000..819d5c3d95 --- /dev/null +++ b/Lang/PL-I/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Variables b/Lang/PL-I/Variables new file mode 120000 index 0000000000..2c70f29010 --- /dev/null +++ b/Lang/PL-I/Variables @@ -0,0 +1 @@ +../../Task/Variables/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Variadic-function b/Lang/PL-I/Variadic-function new file mode 120000 index 0000000000..fc4c48b58d --- /dev/null +++ b/Lang/PL-I/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Vector-products b/Lang/PL-I/Vector-products new file mode 120000 index 0000000000..ecf7e5e44c --- /dev/null +++ b/Lang/PL-I/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Vigen-re-cipher b/Lang/PL-I/Vigen-re-cipher new file mode 120000 index 0000000000..e590119b11 --- /dev/null +++ b/Lang/PL-I/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Write-float-arrays-to-a-text-file b/Lang/PL-I/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..1f944e870d --- /dev/null +++ b/Lang/PL-I/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Zig-zag-matrix b/Lang/PL-I/Zig-zag-matrix new file mode 120000 index 0000000000..0891f45e98 --- /dev/null +++ b/Lang/PL-I/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PL-I \ No newline at end of file diff --git a/Lang/PL-SQL/String-case b/Lang/PL-SQL/String-case new file mode 120000 index 0000000000..20d01a15d0 --- /dev/null +++ b/Lang/PL-SQL/String-case @@ -0,0 +1 @@ +../../Task/String-case/PL-SQL \ No newline at end of file diff --git a/Lang/PL-SQL/String-length b/Lang/PL-SQL/String-length new file mode 120000 index 0000000000..233f3db39a --- /dev/null +++ b/Lang/PL-SQL/String-length @@ -0,0 +1 @@ +../../Task/String-length/PL-SQL \ No newline at end of file diff --git a/Lang/PL-SQL/Trigonometric-functions b/Lang/PL-SQL/Trigonometric-functions new file mode 120000 index 0000000000..5cfe9fc78a --- /dev/null +++ b/Lang/PL-SQL/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PL-SQL \ No newline at end of file diff --git a/Lang/POV-Ray/Yin-and-yang b/Lang/POV-Ray/Yin-and-yang new file mode 120000 index 0000000000..bb655e842a --- /dev/null +++ b/Lang/POV-Ray/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/POV-Ray \ No newline at end of file diff --git a/Lang/Pascal/Shell-one-liner b/Lang/Pascal/Shell-one-liner new file mode 120000 index 0000000000..cb930ca346 --- /dev/null +++ b/Lang/Pascal/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Short-circuit-evaluation b/Lang/Pascal/Short-circuit-evaluation new file mode 120000 index 0000000000..61a188295d --- /dev/null +++ b/Lang/Pascal/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Show-the-epoch b/Lang/Pascal/Show-the-epoch new file mode 120000 index 0000000000..e1ac025be4 --- /dev/null +++ b/Lang/Pascal/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sierpinski-carpet b/Lang/Pascal/Sierpinski-carpet new file mode 120000 index 0000000000..d9941d8434 --- /dev/null +++ b/Lang/Pascal/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sierpinski-triangle b/Lang/Pascal/Sierpinski-triangle new file mode 120000 index 0000000000..4f317731d4 --- /dev/null +++ b/Lang/Pascal/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sieve-of-Eratosthenes b/Lang/Pascal/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..f4254dd892 --- /dev/null +++ b/Lang/Pascal/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Simple-windowed-application b/Lang/Pascal/Simple-windowed-application new file mode 120000 index 0000000000..bd15819d21 --- /dev/null +++ b/Lang/Pascal/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Singly-linked-list-Element-definition b/Lang/Pascal/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..3dda578515 --- /dev/null +++ b/Lang/Pascal/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Singly-linked-list-Element-insertion b/Lang/Pascal/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..6202cc2822 --- /dev/null +++ b/Lang/Pascal/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Bogosort b/Lang/Pascal/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..401773780a --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Bubble-sort b/Lang/Pascal/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..0ad44d147e --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Comb-sort b/Lang/Pascal/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..237a146a9a --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Counting-sort b/Lang/Pascal/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..fcad6bc4e1 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Gnome-sort b/Lang/Pascal/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a26771c385 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Heapsort b/Lang/Pascal/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..f1e4da6754 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Merge-sort b/Lang/Pascal/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..ab72e86c73 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Pancake-sort b/Lang/Pascal/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..a21665639c --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Quicksort b/Lang/Pascal/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f81d3b6286 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Shell-sort b/Lang/Pascal/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..f087b1c113 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Stooge-sort b/Lang/Pascal/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..08d0cc68e4 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-algorithms-Strand-sort b/Lang/Pascal/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..3bea2b6459 --- /dev/null +++ b/Lang/Pascal/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Stack b/Lang/Pascal/Stack new file mode 120000 index 0000000000..213719d8e8 --- /dev/null +++ b/Lang/Pascal/Stack @@ -0,0 +1 @@ +../../Task/Stack/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Stair-climbing-puzzle b/Lang/Pascal/Stair-climbing-puzzle new file mode 120000 index 0000000000..9a3c198367 --- /dev/null +++ b/Lang/Pascal/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Pascal \ No newline at end of file diff --git a/Lang/Pascal/String-concatenation b/Lang/Pascal/String-concatenation new file mode 120000 index 0000000000..b95a9531dc --- /dev/null +++ b/Lang/Pascal/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/String-length b/Lang/Pascal/String-length new file mode 120000 index 0000000000..ae3f409ac6 --- /dev/null +++ b/Lang/Pascal/String-length @@ -0,0 +1 @@ +../../Task/String-length/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Pascal/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..99efe608fd --- /dev/null +++ b/Lang/Pascal/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sum-of-a-series b/Lang/Pascal/Sum-of-a-series new file mode 120000 index 0000000000..6b5da3668b --- /dev/null +++ b/Lang/Pascal/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sum-of-squares b/Lang/Pascal/Sum-of-squares new file mode 120000 index 0000000000..7f8dcdb664 --- /dev/null +++ b/Lang/Pascal/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Pascal \ No newline at end of file diff --git a/Lang/Pascal/System-time b/Lang/Pascal/System-time new file mode 120000 index 0000000000..cfad99e55e --- /dev/null +++ b/Lang/Pascal/System-time @@ -0,0 +1 @@ +../../Task/System-time/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Terminal-control-Clear-the-screen b/Lang/Pascal/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..e3c68785e2 --- /dev/null +++ b/Lang/Pascal/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Terminal-control-Cursor-positioning b/Lang/Pascal/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..cb9530a7f0 --- /dev/null +++ b/Lang/Pascal/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Terminal-control-Display-an-extended-character b/Lang/Pascal/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..a020935a11 --- /dev/null +++ b/Lang/Pascal/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Ternary-logic b/Lang/Pascal/Ternary-logic new file mode 120000 index 0000000000..c67d2f5d1b --- /dev/null +++ b/Lang/Pascal/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Tokenize-a-string b/Lang/Pascal/Tokenize-a-string new file mode 120000 index 0000000000..a01bfad091 --- /dev/null +++ b/Lang/Pascal/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Top-rank-per-group b/Lang/Pascal/Top-rank-per-group new file mode 120000 index 0000000000..47938ab205 --- /dev/null +++ b/Lang/Pascal/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Towers-of-Hanoi b/Lang/Pascal/Towers-of-Hanoi new file mode 120000 index 0000000000..7058e9b86b --- /dev/null +++ b/Lang/Pascal/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Trigonometric-functions b/Lang/Pascal/Trigonometric-functions new file mode 120000 index 0000000000..0abe6b9ad2 --- /dev/null +++ b/Lang/Pascal/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Truncate-a-file b/Lang/Pascal/Truncate-a-file new file mode 120000 index 0000000000..b930ccf95e --- /dev/null +++ b/Lang/Pascal/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Pascal \ No newline at end of file diff --git a/Lang/Pascal/User-input-Text b/Lang/Pascal/User-input-Text new file mode 120000 index 0000000000..b4c87c2336 --- /dev/null +++ b/Lang/Pascal/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Variable-size-Get b/Lang/Pascal/Variable-size-Get new file mode 120000 index 0000000000..33c6f369a7 --- /dev/null +++ b/Lang/Pascal/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Variable-size-Set b/Lang/Pascal/Variable-size-Set new file mode 120000 index 0000000000..006bf2cf39 --- /dev/null +++ b/Lang/Pascal/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Vector-products b/Lang/Pascal/Vector-products new file mode 120000 index 0000000000..8af90dc904 --- /dev/null +++ b/Lang/Pascal/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Walk-a-directory-Non-recursively b/Lang/Pascal/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..bdd4f51e29 --- /dev/null +++ b/Lang/Pascal/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Window-creation b/Lang/Pascal/Window-creation new file mode 120000 index 0000000000..ed0d1a3f59 --- /dev/null +++ b/Lang/Pascal/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Write-float-arrays-to-a-text-file b/Lang/Pascal/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..6dd390a63c --- /dev/null +++ b/Lang/Pascal/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Pascal \ No newline at end of file diff --git a/Lang/Pascal/XML-DOM-serialization b/Lang/Pascal/XML-DOM-serialization new file mode 120000 index 0000000000..4a112bc878 --- /dev/null +++ b/Lang/Pascal/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Zig-zag-matrix b/Lang/Pascal/Zig-zag-matrix new file mode 120000 index 0000000000..85fdc4d3a1 --- /dev/null +++ b/Lang/Pascal/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/SHA-1 b/Lang/Perl-6/SHA-1 new file mode 120000 index 0000000000..6335b4b00c --- /dev/null +++ b/Lang/Perl-6/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/SHA-256 b/Lang/Perl-6/SHA-256 new file mode 120000 index 0000000000..fae4b5c5ab --- /dev/null +++ b/Lang/Perl-6/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Set-puzzle b/Lang/Perl-6/Set-puzzle new file mode 120000 index 0000000000..6aed515635 --- /dev/null +++ b/Lang/Perl-6/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Seven-sided-dice-from-five-sided-dice b/Lang/Perl-6/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..0c759d6930 --- /dev/null +++ b/Lang/Perl-6/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Shell-one-liner b/Lang/Perl-6/Shell-one-liner new file mode 120000 index 0000000000..5e3b9ac121 --- /dev/null +++ b/Lang/Perl-6/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Short-circuit-evaluation b/Lang/Perl-6/Short-circuit-evaluation new file mode 120000 index 0000000000..dbde16355b --- /dev/null +++ b/Lang/Perl-6/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Show-the-epoch b/Lang/Perl-6/Show-the-epoch new file mode 120000 index 0000000000..34eb82580d --- /dev/null +++ b/Lang/Perl-6/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sierpinski-carpet b/Lang/Perl-6/Sierpinski-carpet new file mode 120000 index 0000000000..983123e51f --- /dev/null +++ b/Lang/Perl-6/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sierpinski-triangle b/Lang/Perl-6/Sierpinski-triangle new file mode 120000 index 0000000000..2f31f57b01 --- /dev/null +++ b/Lang/Perl-6/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sierpinski-triangle-Graphical b/Lang/Perl-6/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..1a9dbc2ff0 --- /dev/null +++ b/Lang/Perl-6/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sieve-of-Eratosthenes b/Lang/Perl-6/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..103fe06dac --- /dev/null +++ b/Lang/Perl-6/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Singleton b/Lang/Perl-6/Singleton new file mode 120000 index 0000000000..c969d43a38 --- /dev/null +++ b/Lang/Perl-6/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Singly-linked-list-Element-definition b/Lang/Perl-6/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..2a78b5463b --- /dev/null +++ b/Lang/Perl-6/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Singly-linked-list-Element-insertion b/Lang/Perl-6/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..db0fd0012d --- /dev/null +++ b/Lang/Perl-6/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Singly-linked-list-Traversal b/Lang/Perl-6/Singly-linked-list-Traversal new file mode 120000 index 0000000000..eb7775b78b --- /dev/null +++ b/Lang/Perl-6/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sleep b/Lang/Perl-6/Sleep new file mode 120000 index 0000000000..9d8760cca1 --- /dev/null +++ b/Lang/Perl-6/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sockets b/Lang/Perl-6/Sockets new file mode 120000 index 0000000000..e45a231b24 --- /dev/null +++ b/Lang/Perl-6/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Solve-a-Hidato-puzzle b/Lang/Perl-6/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..06028d5f2b --- /dev/null +++ b/Lang/Perl-6/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sort-an-array-of-composite-structures b/Lang/Perl-6/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..142d8e393f --- /dev/null +++ b/Lang/Perl-6/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sort-an-integer-array b/Lang/Perl-6/Sort-an-integer-array new file mode 120000 index 0000000000..38c5666193 --- /dev/null +++ b/Lang/Perl-6/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sort-disjoint-sublist b/Lang/Perl-6/Sort-disjoint-sublist new file mode 120000 index 0000000000..d602749211 --- /dev/null +++ b/Lang/Perl-6/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sort-stability b/Lang/Perl-6/Sort-stability new file mode 120000 index 0000000000..035f775bf7 --- /dev/null +++ b/Lang/Perl-6/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sort-using-a-custom-comparator b/Lang/Perl-6/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..b042d97f06 --- /dev/null +++ b/Lang/Perl-6/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Bead-sort b/Lang/Perl-6/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..84db3547a1 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Bogosort b/Lang/Perl-6/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..d7b128ee83 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Bubble-sort b/Lang/Perl-6/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ef10bcb624 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Cocktail-sort b/Lang/Perl-6/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..8b63a6f669 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Comb-sort b/Lang/Perl-6/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..65a9b6a823 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Counting-sort b/Lang/Perl-6/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..ed3c96712e --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Gnome-sort b/Lang/Perl-6/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..1bf0149837 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Heapsort b/Lang/Perl-6/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..a772c08a40 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Insertion-sort b/Lang/Perl-6/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4148e5ed4e --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Merge-sort b/Lang/Perl-6/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..60dbd37d4e --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Pancake-sort b/Lang/Perl-6/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..4f842cacc6 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Permutation-sort b/Lang/Perl-6/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..53755ebeca --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Quicksort b/Lang/Perl-6/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..d8dda2921c --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Radix-sort b/Lang/Perl-6/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..fe1821d09f --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Selection-sort b/Lang/Perl-6/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a887d3beb3 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Shell-sort b/Lang/Perl-6/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..ac8f33e6b2 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Sleep-sort b/Lang/Perl-6/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..6a0d625c44 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Stooge-sort b/Lang/Perl-6/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..4e510ff776 --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sorting-algorithms-Strand-sort b/Lang/Perl-6/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..141885c64a --- /dev/null +++ b/Lang/Perl-6/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Soundex b/Lang/Perl-6/Soundex new file mode 120000 index 0000000000..bd13f5f2e5 --- /dev/null +++ b/Lang/Perl-6/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Special-variables b/Lang/Perl-6/Special-variables new file mode 120000 index 0000000000..301de76a29 --- /dev/null +++ b/Lang/Perl-6/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Spiral-matrix b/Lang/Perl-6/Spiral-matrix new file mode 120000 index 0000000000..4e3f478d19 --- /dev/null +++ b/Lang/Perl-6/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stack b/Lang/Perl-6/Stack new file mode 120000 index 0000000000..9649652fea --- /dev/null +++ b/Lang/Perl-6/Stack @@ -0,0 +1 @@ +../../Task/Stack/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stack-traces b/Lang/Perl-6/Stack-traces new file mode 120000 index 0000000000..86ae5262f4 --- /dev/null +++ b/Lang/Perl-6/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stair-climbing-puzzle b/Lang/Perl-6/Stair-climbing-puzzle new file mode 120000 index 0000000000..72c8eec876 --- /dev/null +++ b/Lang/Perl-6/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Standard-deviation b/Lang/Perl-6/Standard-deviation new file mode 120000 index 0000000000..fd7b9fde9f --- /dev/null +++ b/Lang/Perl-6/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Start-from-a-main-routine b/Lang/Perl-6/Start-from-a-main-routine new file mode 120000 index 0000000000..2e480a655e --- /dev/null +++ b/Lang/Perl-6/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stem-and-leaf-plot b/Lang/Perl-6/Stem-and-leaf-plot new file mode 120000 index 0000000000..9c09de46f3 --- /dev/null +++ b/Lang/Perl-6/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-case b/Lang/Perl-6/String-case new file mode 120000 index 0000000000..0ee0fd71b3 --- /dev/null +++ b/Lang/Perl-6/String-case @@ -0,0 +1 @@ +../../Task/String-case/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-comparison b/Lang/Perl-6/String-comparison new file mode 120000 index 0000000000..5d878ffcfd --- /dev/null +++ b/Lang/Perl-6/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-concatenation b/Lang/Perl-6/String-concatenation new file mode 120000 index 0000000000..210a6be449 --- /dev/null +++ b/Lang/Perl-6/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-interpolation--included- b/Lang/Perl-6/String-interpolation--included- new file mode 120000 index 0000000000..83067153e9 --- /dev/null +++ b/Lang/Perl-6/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/String-length b/Lang/Perl-6/String-length new file mode 120000 index 0000000000..5fc2b868a6 --- /dev/null +++ b/Lang/Perl-6/String-length @@ -0,0 +1 @@ +../../Task/String-length/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Strip-a-set-of-characters-from-a-string b/Lang/Perl-6/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..ae51e31625 --- /dev/null +++ b/Lang/Perl-6/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Strip-block-comments b/Lang/Perl-6/Strip-block-comments new file mode 120000 index 0000000000..e6c19958bf --- /dev/null +++ b/Lang/Perl-6/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Strip-comments-from-a-string b/Lang/Perl-6/Strip-comments-from-a-string new file mode 120000 index 0000000000..24a49f2ba2 --- /dev/null +++ b/Lang/Perl-6/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Perl-6/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..13f920f739 --- /dev/null +++ b/Lang/Perl-6/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Perl-6/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..d05c510a18 --- /dev/null +++ b/Lang/Perl-6/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Substring b/Lang/Perl-6/Substring new file mode 120000 index 0000000000..de3217eaf7 --- /dev/null +++ b/Lang/Perl-6/Substring @@ -0,0 +1 @@ +../../Task/Substring/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Substring-Top-and-tail b/Lang/Perl-6/Substring-Top-and-tail new file mode 120000 index 0000000000..58c46930b9 --- /dev/null +++ b/Lang/Perl-6/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Subtractive-generator b/Lang/Perl-6/Subtractive-generator new file mode 120000 index 0000000000..f7e518e857 --- /dev/null +++ b/Lang/Perl-6/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sudoku b/Lang/Perl-6/Sudoku new file mode 120000 index 0000000000..8cf04aa3f3 --- /dev/null +++ b/Lang/Perl-6/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sum-and-product-of-an-array b/Lang/Perl-6/Sum-and-product-of-an-array new file mode 120000 index 0000000000..6c716bdafd --- /dev/null +++ b/Lang/Perl-6/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sum-digits-of-an-integer b/Lang/Perl-6/Sum-digits-of-an-integer new file mode 120000 index 0000000000..9265b2a268 --- /dev/null +++ b/Lang/Perl-6/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sum-of-a-series b/Lang/Perl-6/Sum-of-a-series new file mode 120000 index 0000000000..867ed181bf --- /dev/null +++ b/Lang/Perl-6/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sum-of-squares b/Lang/Perl-6/Sum-of-squares new file mode 120000 index 0000000000..3864233845 --- /dev/null +++ b/Lang/Perl-6/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Symmetric-difference b/Lang/Perl-6/Symmetric-difference new file mode 120000 index 0000000000..85a9355b86 --- /dev/null +++ b/Lang/Perl-6/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Synchronous-concurrency b/Lang/Perl-6/Synchronous-concurrency new file mode 120000 index 0000000000..4417568e36 --- /dev/null +++ b/Lang/Perl-6/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/System-time b/Lang/Perl-6/System-time new file mode 120000 index 0000000000..5e0a9f6a62 --- /dev/null +++ b/Lang/Perl-6/System-time @@ -0,0 +1 @@ +../../Task/System-time/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Take-notes-on-the-command-line b/Lang/Perl-6/Take-notes-on-the-command-line new file mode 120000 index 0000000000..9a7bd666b5 --- /dev/null +++ b/Lang/Perl-6/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Temperature-conversion b/Lang/Perl-6/Temperature-conversion new file mode 120000 index 0000000000..b53faee74a --- /dev/null +++ b/Lang/Perl-6/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Clear-the-screen b/Lang/Perl-6/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..2c7e067268 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Cursor-positioning b/Lang/Perl-6/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..ebd45004d4 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Dimensions b/Lang/Perl-6/Terminal-control-Dimensions new file mode 120000 index 0000000000..962a61f429 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Display-an-extended-character b/Lang/Perl-6/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..e924c5b067 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Hiding-the-cursor b/Lang/Perl-6/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..7d8f944727 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Inverse-video b/Lang/Perl-6/Terminal-control-Inverse-video new file mode 120000 index 0000000000..ea321f757e --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Ringing-the-terminal-bell b/Lang/Perl-6/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..57a01a6d36 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Terminal-control-Unicode-output b/Lang/Perl-6/Terminal-control-Unicode-output new file mode 120000 index 0000000000..5ec2dbadc4 --- /dev/null +++ b/Lang/Perl-6/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Ternary-logic b/Lang/Perl-6/Ternary-logic new file mode 120000 index 0000000000..cd4621b55f --- /dev/null +++ b/Lang/Perl-6/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Test-a-function b/Lang/Perl-6/Test-a-function new file mode 120000 index 0000000000..86660409d4 --- /dev/null +++ b/Lang/Perl-6/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Text-processing-1 b/Lang/Perl-6/Text-processing-1 new file mode 120000 index 0000000000..f5ae971151 --- /dev/null +++ b/Lang/Perl-6/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Text-processing-2 b/Lang/Perl-6/Text-processing-2 new file mode 120000 index 0000000000..919afad8dc --- /dev/null +++ b/Lang/Perl-6/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Text-processing-Max-licenses-in-use b/Lang/Perl-6/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..34c5ff1e66 --- /dev/null +++ b/Lang/Perl-6/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Thieles-interpolation-formula b/Lang/Perl-6/Thieles-interpolation-formula new file mode 120000 index 0000000000..659d9a6110 --- /dev/null +++ b/Lang/Perl-6/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Tic-tac-toe b/Lang/Perl-6/Tic-tac-toe new file mode 120000 index 0000000000..2430a5f4b1 --- /dev/null +++ b/Lang/Perl-6/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Time-a-function b/Lang/Perl-6/Time-a-function new file mode 120000 index 0000000000..0f69c53078 --- /dev/null +++ b/Lang/Perl-6/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Tokenize-a-string b/Lang/Perl-6/Tokenize-a-string new file mode 120000 index 0000000000..7de5b5fa40 --- /dev/null +++ b/Lang/Perl-6/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Top-rank-per-group b/Lang/Perl-6/Top-rank-per-group new file mode 120000 index 0000000000..cd7f336994 --- /dev/null +++ b/Lang/Perl-6/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Topic-variable b/Lang/Perl-6/Topic-variable new file mode 120000 index 0000000000..4d77ad4e57 --- /dev/null +++ b/Lang/Perl-6/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Topological-sort b/Lang/Perl-6/Topological-sort new file mode 120000 index 0000000000..09f2564034 --- /dev/null +++ b/Lang/Perl-6/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Topswops b/Lang/Perl-6/Topswops new file mode 120000 index 0000000000..362ade11bb --- /dev/null +++ b/Lang/Perl-6/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Towers-of-Hanoi b/Lang/Perl-6/Towers-of-Hanoi new file mode 120000 index 0000000000..8d8ec004b0 --- /dev/null +++ b/Lang/Perl-6/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Trabb-Pardo-Knuth-algorithm b/Lang/Perl-6/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..98ac348a7d --- /dev/null +++ b/Lang/Perl-6/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Tree-traversal b/Lang/Perl-6/Tree-traversal new file mode 120000 index 0000000000..0c70162761 --- /dev/null +++ b/Lang/Perl-6/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Trigonometric-functions b/Lang/Perl-6/Trigonometric-functions new file mode 120000 index 0000000000..c6256239e0 --- /dev/null +++ b/Lang/Perl-6/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Truncatable-primes b/Lang/Perl-6/Truncatable-primes new file mode 120000 index 0000000000..29248ba050 --- /dev/null +++ b/Lang/Perl-6/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Truncate-a-file b/Lang/Perl-6/Truncate-a-file new file mode 120000 index 0000000000..c168cd81bf --- /dev/null +++ b/Lang/Perl-6/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Twelve-statements b/Lang/Perl-6/Twelve-statements new file mode 120000 index 0000000000..77c642fb24 --- /dev/null +++ b/Lang/Perl-6/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/URL-decoding b/Lang/Perl-6/URL-decoding new file mode 120000 index 0000000000..e8ce7a617b --- /dev/null +++ b/Lang/Perl-6/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/URL-encoding b/Lang/Perl-6/URL-encoding new file mode 120000 index 0000000000..e247fd08d2 --- /dev/null +++ b/Lang/Perl-6/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Unbias-a-random-generator b/Lang/Perl-6/Unbias-a-random-generator new file mode 120000 index 0000000000..55f50bbf0c --- /dev/null +++ b/Lang/Perl-6/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Undefined-values b/Lang/Perl-6/Undefined-values new file mode 120000 index 0000000000..e97738bd1d --- /dev/null +++ b/Lang/Perl-6/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Unicode-strings b/Lang/Perl-6/Unicode-strings new file mode 120000 index 0000000000..1fe37c45ad --- /dev/null +++ b/Lang/Perl-6/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Unicode-variable-names b/Lang/Perl-6/Unicode-variable-names new file mode 120000 index 0000000000..05d951796b --- /dev/null +++ b/Lang/Perl-6/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Universal-Turing-machine b/Lang/Perl-6/Universal-Turing-machine new file mode 120000 index 0000000000..3d88f707ac --- /dev/null +++ b/Lang/Perl-6/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/User-input-Text b/Lang/Perl-6/User-input-Text new file mode 120000 index 0000000000..223e728d92 --- /dev/null +++ b/Lang/Perl-6/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Vampire-number b/Lang/Perl-6/Vampire-number new file mode 120000 index 0000000000..908c053ad9 --- /dev/null +++ b/Lang/Perl-6/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Van-der-Corput-sequence b/Lang/Perl-6/Van-der-Corput-sequence new file mode 120000 index 0000000000..5c51b49ae3 --- /dev/null +++ b/Lang/Perl-6/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Variable-length-quantity b/Lang/Perl-6/Variable-length-quantity new file mode 120000 index 0000000000..055473b193 --- /dev/null +++ b/Lang/Perl-6/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Variables b/Lang/Perl-6/Variables new file mode 120000 index 0000000000..872e3f7ba2 --- /dev/null +++ b/Lang/Perl-6/Variables @@ -0,0 +1 @@ +../../Task/Variables/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Variadic-function b/Lang/Perl-6/Variadic-function new file mode 120000 index 0000000000..b730025abd --- /dev/null +++ b/Lang/Perl-6/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Vector-products b/Lang/Perl-6/Vector-products new file mode 120000 index 0000000000..0e3489f309 --- /dev/null +++ b/Lang/Perl-6/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Verify-distribution-uniformity-Chi-squared-test b/Lang/Perl-6/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..1e02270b6f --- /dev/null +++ b/Lang/Perl-6/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Verify-distribution-uniformity-Naive b/Lang/Perl-6/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..f0b6d65745 --- /dev/null +++ b/Lang/Perl-6/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Vigen-re-cipher b/Lang/Perl-6/Vigen-re-cipher new file mode 120000 index 0000000000..df887b495d --- /dev/null +++ b/Lang/Perl-6/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Visualize-a-tree b/Lang/Perl-6/Visualize-a-tree new file mode 120000 index 0000000000..1d871999d7 --- /dev/null +++ b/Lang/Perl-6/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Walk-a-directory-Non-recursively b/Lang/Perl-6/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..db5c2a57ca --- /dev/null +++ b/Lang/Perl-6/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Walk-a-directory-Recursively b/Lang/Perl-6/Walk-a-directory-Recursively new file mode 120000 index 0000000000..be2c4863f4 --- /dev/null +++ b/Lang/Perl-6/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Web-scraping b/Lang/Perl-6/Web-scraping new file mode 120000 index 0000000000..6c3e3b872c --- /dev/null +++ b/Lang/Perl-6/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Wireworld b/Lang/Perl-6/Wireworld new file mode 120000 index 0000000000..cd5a01c2e6 --- /dev/null +++ b/Lang/Perl-6/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Word-wrap b/Lang/Perl-6/Word-wrap new file mode 120000 index 0000000000..420b855934 --- /dev/null +++ b/Lang/Perl-6/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Write-float-arrays-to-a-text-file b/Lang/Perl-6/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..3eaf984b27 --- /dev/null +++ b/Lang/Perl-6/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Write-language-name-in-3D-ASCII b/Lang/Perl-6/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..b3840e47bc --- /dev/null +++ b/Lang/Perl-6/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Xiaolin-Wus-line-algorithm b/Lang/Perl-6/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..1e937becd9 --- /dev/null +++ b/Lang/Perl-6/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Y-combinator b/Lang/Perl-6/Y-combinator new file mode 120000 index 0000000000..4f311730ee --- /dev/null +++ b/Lang/Perl-6/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Yin-and-yang b/Lang/Perl-6/Yin-and-yang new file mode 120000 index 0000000000..5c9a974959 --- /dev/null +++ b/Lang/Perl-6/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Zeckendorf-arithmetic b/Lang/Perl-6/Zeckendorf-arithmetic new file mode 120000 index 0000000000..672b08c89f --- /dev/null +++ b/Lang/Perl-6/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Zeckendorf-number-representation b/Lang/Perl-6/Zeckendorf-number-representation new file mode 120000 index 0000000000..a9caa00e3f --- /dev/null +++ b/Lang/Perl-6/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Zig-zag-matrix b/Lang/Perl-6/Zig-zag-matrix new file mode 120000 index 0000000000..f892ed8905 --- /dev/null +++ b/Lang/Perl-6/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/SHA-1 b/Lang/Perl/SHA-1 new file mode 120000 index 0000000000..fbfd2b3b31 --- /dev/null +++ b/Lang/Perl/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Perl \ No newline at end of file diff --git a/Lang/Perl/SHA-256 b/Lang/Perl/SHA-256 new file mode 120000 index 0000000000..832dea6cfe --- /dev/null +++ b/Lang/Perl/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Perl \ No newline at end of file diff --git a/Lang/Perl/SOAP b/Lang/Perl/SOAP new file mode 120000 index 0000000000..34e2d32f00 --- /dev/null +++ b/Lang/Perl/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Perl \ No newline at end of file diff --git a/Lang/Perl/SQL-based-authentication b/Lang/Perl/SQL-based-authentication new file mode 120000 index 0000000000..ef9eab14b4 --- /dev/null +++ b/Lang/Perl/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Perl \ No newline at end of file diff --git a/Lang/Perl/Shell-one-liner b/Lang/Perl/Shell-one-liner new file mode 120000 index 0000000000..3b06e91c61 --- /dev/null +++ b/Lang/Perl/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Perl \ No newline at end of file diff --git a/Lang/Perl/Short-circuit-evaluation b/Lang/Perl/Short-circuit-evaluation new file mode 120000 index 0000000000..40c00c5d34 --- /dev/null +++ b/Lang/Perl/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Perl \ No newline at end of file diff --git a/Lang/Perl/Show-the-epoch b/Lang/Perl/Show-the-epoch new file mode 120000 index 0000000000..8cd52a80e8 --- /dev/null +++ b/Lang/Perl/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Perl \ No newline at end of file diff --git a/Lang/Perl/Sierpinski-carpet b/Lang/Perl/Sierpinski-carpet new file mode 120000 index 0000000000..b72b66b3d6 --- /dev/null +++ b/Lang/Perl/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Perl \ No newline at end of file diff --git a/Lang/Perl/Sierpinski-triangle b/Lang/Perl/Sierpinski-triangle new file mode 120000 index 0000000000..acfc639cf3 --- /dev/null +++ b/Lang/Perl/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Perl \ No newline at end of file diff --git a/Lang/Perl/Sierpinski-triangle-Graphical b/Lang/Perl/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..ffb6cbdbbe --- /dev/null +++ b/Lang/Perl/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Perl \ No newline at end of file diff --git a/Lang/Perl/Sieve-of-Eratosthenes b/Lang/Perl/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..6a3b580959 --- /dev/null +++ b/Lang/Perl/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Perl \ No newline at end of file diff --git a/Lang/Perl/Simple-windowed-application b/Lang/Perl/Simple-windowed-application new file mode 120000 index 0000000000..6b6522b7a4 --- /dev/null +++ b/Lang/Perl/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Perl \ No newline at end of file diff --git a/Lang/Perl/Simulate-input-Keyboard b/Lang/Perl/Simulate-input-Keyboard new file mode 120000 index 0000000000..161f05c563 --- /dev/null +++ b/Lang/Perl/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Perl \ No newline at end of file diff --git a/Lang/Perl/Singleton b/Lang/Perl/Singleton new file mode 120000 index 0000000000..c183ef4968 --- /dev/null +++ b/Lang/Perl/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Perl \ No newline at end of file diff --git a/Lang/Perl/Singly-linked-list-Element-definition b/Lang/Perl/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..7553e97296 --- /dev/null +++ b/Lang/Perl/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Perl \ No newline at end of file diff --git a/Lang/Perl/Singly-linked-list-Element-insertion b/Lang/Perl/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..55ad311815 --- /dev/null +++ b/Lang/Perl/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Perl \ No newline at end of file diff --git a/Lang/Perl/Sleep b/Lang/Perl/Sleep new file mode 120000 index 0000000000..571b4c2a99 --- /dev/null +++ b/Lang/Perl/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Perl \ No newline at end of file diff --git a/Lang/Perl/Sockets b/Lang/Perl/Sockets new file mode 120000 index 0000000000..08f4ce48a3 --- /dev/null +++ b/Lang/Perl/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Perl \ No newline at end of file diff --git a/Lang/Perl/Solve-a-Hidato-puzzle b/Lang/Perl/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..805e4b9f9b --- /dev/null +++ b/Lang/Perl/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Sort-an-array-of-composite-structures b/Lang/Perl/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..f60a882d1c --- /dev/null +++ b/Lang/Perl/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Perl \ No newline at end of file diff --git a/Lang/Perl/Sort-an-integer-array b/Lang/Perl/Sort-an-integer-array new file mode 120000 index 0000000000..f6f317a47c --- /dev/null +++ b/Lang/Perl/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Perl \ No newline at end of file diff --git a/Lang/Perl/Sort-disjoint-sublist b/Lang/Perl/Sort-disjoint-sublist new file mode 120000 index 0000000000..e6e24eecac --- /dev/null +++ b/Lang/Perl/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Perl \ No newline at end of file diff --git a/Lang/Perl/Sort-stability b/Lang/Perl/Sort-stability new file mode 120000 index 0000000000..f45d4720c4 --- /dev/null +++ b/Lang/Perl/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Perl \ No newline at end of file diff --git a/Lang/Perl/Sort-using-a-custom-comparator b/Lang/Perl/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..b22b8ac22d --- /dev/null +++ b/Lang/Perl/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Bead-sort b/Lang/Perl/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..c2a4452515 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Bogosort b/Lang/Perl/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..93baa9af97 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Bubble-sort b/Lang/Perl/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..00fb5ece88 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Cocktail-sort b/Lang/Perl/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..c997d073ca --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Comb-sort b/Lang/Perl/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..cac29976d1 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Counting-sort b/Lang/Perl/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..0431036141 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Gnome-sort b/Lang/Perl/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..64792fa982 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Heapsort b/Lang/Perl/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..286a1cbb17 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Insertion-sort b/Lang/Perl/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..486f1ea298 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Merge-sort b/Lang/Perl/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..206828449e --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Pancake-sort b/Lang/Perl/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..3da2384d0f --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Permutation-sort b/Lang/Perl/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..2e5d01be74 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Quicksort b/Lang/Perl/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..4a7bf65777 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Selection-sort b/Lang/Perl/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..bcb6249a3f --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Shell-sort b/Lang/Perl/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..513eeb28a6 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Sleep-sort b/Lang/Perl/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..4afa767f02 --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Stooge-sort b/Lang/Perl/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..22ec19a8aa --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-algorithms-Strand-sort b/Lang/Perl/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..962342eb9c --- /dev/null +++ b/Lang/Perl/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Soundex b/Lang/Perl/Soundex new file mode 120000 index 0000000000..744fb3335c --- /dev/null +++ b/Lang/Perl/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Perl \ No newline at end of file diff --git a/Lang/Perl/Spiral-matrix b/Lang/Perl/Spiral-matrix new file mode 120000 index 0000000000..536e45016d --- /dev/null +++ b/Lang/Perl/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Perl \ No newline at end of file diff --git a/Lang/Perl/Stable-marriage-problem b/Lang/Perl/Stable-marriage-problem new file mode 120000 index 0000000000..cea5d2eb8a --- /dev/null +++ b/Lang/Perl/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Perl \ No newline at end of file diff --git a/Lang/Perl/Stack b/Lang/Perl/Stack new file mode 120000 index 0000000000..adebc3eb9c --- /dev/null +++ b/Lang/Perl/Stack @@ -0,0 +1 @@ +../../Task/Stack/Perl \ No newline at end of file diff --git a/Lang/Perl/Stack-traces b/Lang/Perl/Stack-traces new file mode 120000 index 0000000000..f3dc82253a --- /dev/null +++ b/Lang/Perl/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Perl \ No newline at end of file diff --git a/Lang/Perl/Stair-climbing-puzzle b/Lang/Perl/Stair-climbing-puzzle new file mode 120000 index 0000000000..faf4dd50a7 --- /dev/null +++ b/Lang/Perl/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Standard-deviation b/Lang/Perl/Standard-deviation new file mode 120000 index 0000000000..1cc6321764 --- /dev/null +++ b/Lang/Perl/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Perl \ No newline at end of file diff --git a/Lang/Perl/Start-from-a-main-routine b/Lang/Perl/Start-from-a-main-routine new file mode 120000 index 0000000000..436e926cb0 --- /dev/null +++ b/Lang/Perl/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Perl \ No newline at end of file diff --git a/Lang/Perl/Stem-and-leaf-plot b/Lang/Perl/Stem-and-leaf-plot new file mode 120000 index 0000000000..13dd54e399 --- /dev/null +++ b/Lang/Perl/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Perl \ No newline at end of file diff --git a/Lang/Perl/String-case b/Lang/Perl/String-case new file mode 120000 index 0000000000..54b305a785 --- /dev/null +++ b/Lang/Perl/String-case @@ -0,0 +1 @@ +../../Task/String-case/Perl \ No newline at end of file diff --git a/Lang/Perl/String-concatenation b/Lang/Perl/String-concatenation new file mode 120000 index 0000000000..e22ca89e3a --- /dev/null +++ b/Lang/Perl/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Perl \ No newline at end of file diff --git a/Lang/Perl/String-interpolation--included- b/Lang/Perl/String-interpolation--included- new file mode 120000 index 0000000000..88eb602f63 --- /dev/null +++ b/Lang/Perl/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Perl \ No newline at end of file diff --git a/Lang/Perl/String-length b/Lang/Perl/String-length new file mode 120000 index 0000000000..d0a4d26746 --- /dev/null +++ b/Lang/Perl/String-length @@ -0,0 +1 @@ +../../Task/String-length/Perl \ No newline at end of file diff --git a/Lang/Perl/Strip-a-set-of-characters-from-a-string b/Lang/Perl/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a7ce4ac1b9 --- /dev/null +++ b/Lang/Perl/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Strip-block-comments b/Lang/Perl/Strip-block-comments new file mode 120000 index 0000000000..e828aad6f5 --- /dev/null +++ b/Lang/Perl/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Perl \ No newline at end of file diff --git a/Lang/Perl/Strip-comments-from-a-string b/Lang/Perl/Strip-comments-from-a-string new file mode 120000 index 0000000000..157bf96d90 --- /dev/null +++ b/Lang/Perl/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Perl/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..2f5d662704 --- /dev/null +++ b/Lang/Perl/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Perl/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..f2c207dcbf --- /dev/null +++ b/Lang/Perl/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Perl \ No newline at end of file diff --git a/Lang/Perl/Substring b/Lang/Perl/Substring new file mode 120000 index 0000000000..a56c1d9b88 --- /dev/null +++ b/Lang/Perl/Substring @@ -0,0 +1 @@ +../../Task/Substring/Perl \ No newline at end of file diff --git a/Lang/Perl/Substring-Top-and-tail b/Lang/Perl/Substring-Top-and-tail new file mode 120000 index 0000000000..a5c1f5cdc0 --- /dev/null +++ b/Lang/Perl/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Perl \ No newline at end of file diff --git a/Lang/Perl/Subtractive-generator b/Lang/Perl/Subtractive-generator new file mode 120000 index 0000000000..be40a86530 --- /dev/null +++ b/Lang/Perl/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Perl \ No newline at end of file diff --git a/Lang/Perl/Sudoku b/Lang/Perl/Sudoku new file mode 120000 index 0000000000..19203a9745 --- /dev/null +++ b/Lang/Perl/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Perl \ No newline at end of file diff --git a/Lang/Perl/Sum-and-product-of-an-array b/Lang/Perl/Sum-and-product-of-an-array new file mode 120000 index 0000000000..90d672e45a --- /dev/null +++ b/Lang/Perl/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Perl \ No newline at end of file diff --git a/Lang/Perl/Sum-digits-of-an-integer b/Lang/Perl/Sum-digits-of-an-integer new file mode 120000 index 0000000000..79122a9a87 --- /dev/null +++ b/Lang/Perl/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Perl \ No newline at end of file diff --git a/Lang/Perl/Sum-of-a-series b/Lang/Perl/Sum-of-a-series new file mode 120000 index 0000000000..4ffc774f4c --- /dev/null +++ b/Lang/Perl/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Perl \ No newline at end of file diff --git a/Lang/Perl/Sum-of-squares b/Lang/Perl/Sum-of-squares new file mode 120000 index 0000000000..44862413b8 --- /dev/null +++ b/Lang/Perl/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Perl \ No newline at end of file diff --git a/Lang/Perl/Symmetric-difference b/Lang/Perl/Symmetric-difference new file mode 120000 index 0000000000..dbc7349b2e --- /dev/null +++ b/Lang/Perl/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Perl \ No newline at end of file diff --git a/Lang/Perl/Synchronous-concurrency b/Lang/Perl/Synchronous-concurrency new file mode 120000 index 0000000000..78676007fa --- /dev/null +++ b/Lang/Perl/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Perl \ No newline at end of file diff --git a/Lang/Perl/System-time b/Lang/Perl/System-time new file mode 120000 index 0000000000..76dbb6b1a8 --- /dev/null +++ b/Lang/Perl/System-time @@ -0,0 +1 @@ +../../Task/System-time/Perl \ No newline at end of file diff --git a/Lang/Perl/Table-creation-Postal-addresses b/Lang/Perl/Table-creation-Postal-addresses new file mode 120000 index 0000000000..035b833c8a --- /dev/null +++ b/Lang/Perl/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Perl \ No newline at end of file diff --git a/Lang/Perl/Take-notes-on-the-command-line b/Lang/Perl/Take-notes-on-the-command-line new file mode 120000 index 0000000000..1280017d93 --- /dev/null +++ b/Lang/Perl/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Perl \ No newline at end of file diff --git a/Lang/Perl/Terminal-control-Clear-the-screen b/Lang/Perl/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..509eb38e1a --- /dev/null +++ b/Lang/Perl/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Perl \ No newline at end of file diff --git a/Lang/Perl/Terminal-control-Dimensions b/Lang/Perl/Terminal-control-Dimensions new file mode 120000 index 0000000000..5554f9e2cd --- /dev/null +++ b/Lang/Perl/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Perl \ No newline at end of file diff --git a/Lang/Perl/Terminal-control-Ringing-the-terminal-bell b/Lang/Perl/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..87babf87a0 --- /dev/null +++ b/Lang/Perl/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Perl \ No newline at end of file diff --git a/Lang/Perl/Ternary-logic b/Lang/Perl/Ternary-logic new file mode 120000 index 0000000000..9ba2f6ef39 --- /dev/null +++ b/Lang/Perl/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Perl \ No newline at end of file diff --git a/Lang/Perl/Test-a-function b/Lang/Perl/Test-a-function new file mode 120000 index 0000000000..4b9fefa728 --- /dev/null +++ b/Lang/Perl/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Perl \ No newline at end of file diff --git a/Lang/Perl/Text-processing-1 b/Lang/Perl/Text-processing-1 new file mode 120000 index 0000000000..7507bce921 --- /dev/null +++ b/Lang/Perl/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Perl \ No newline at end of file diff --git a/Lang/Perl/Text-processing-2 b/Lang/Perl/Text-processing-2 new file mode 120000 index 0000000000..998fc8076a --- /dev/null +++ b/Lang/Perl/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Perl \ No newline at end of file diff --git a/Lang/Perl/Text-processing-Max-licenses-in-use b/Lang/Perl/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..554d6dc850 --- /dev/null +++ b/Lang/Perl/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Perl \ No newline at end of file diff --git a/Lang/Perl/Time-a-function b/Lang/Perl/Time-a-function new file mode 120000 index 0000000000..ec9f338812 --- /dev/null +++ b/Lang/Perl/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Perl \ No newline at end of file diff --git a/Lang/Perl/Tokenize-a-string b/Lang/Perl/Tokenize-a-string new file mode 120000 index 0000000000..25fe867bd0 --- /dev/null +++ b/Lang/Perl/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Perl \ No newline at end of file diff --git a/Lang/Perl/Top-rank-per-group b/Lang/Perl/Top-rank-per-group new file mode 120000 index 0000000000..c4dbc8dffd --- /dev/null +++ b/Lang/Perl/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Perl \ No newline at end of file diff --git a/Lang/Perl/Topic-variable b/Lang/Perl/Topic-variable new file mode 120000 index 0000000000..45d2f13ed3 --- /dev/null +++ b/Lang/Perl/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Perl \ No newline at end of file diff --git a/Lang/Perl/Topological-sort b/Lang/Perl/Topological-sort new file mode 120000 index 0000000000..fffc10be0d --- /dev/null +++ b/Lang/Perl/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Towers-of-Hanoi b/Lang/Perl/Towers-of-Hanoi new file mode 120000 index 0000000000..d3f22a40b8 --- /dev/null +++ b/Lang/Perl/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Perl \ No newline at end of file diff --git a/Lang/Perl/Trabb-Pardo-Knuth-algorithm b/Lang/Perl/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..158597ca1a --- /dev/null +++ b/Lang/Perl/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/Tree-traversal b/Lang/Perl/Tree-traversal new file mode 120000 index 0000000000..7ae48c1ace --- /dev/null +++ b/Lang/Perl/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Perl \ No newline at end of file diff --git a/Lang/Perl/Trigonometric-functions b/Lang/Perl/Trigonometric-functions new file mode 120000 index 0000000000..2c5a8c85a0 --- /dev/null +++ b/Lang/Perl/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Perl \ No newline at end of file diff --git a/Lang/Perl/Truncate-a-file b/Lang/Perl/Truncate-a-file new file mode 120000 index 0000000000..b3781b7270 --- /dev/null +++ b/Lang/Perl/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Perl \ No newline at end of file diff --git a/Lang/Perl/URL-decoding b/Lang/Perl/URL-decoding new file mode 120000 index 0000000000..adf98610f0 --- /dev/null +++ b/Lang/Perl/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Perl \ No newline at end of file diff --git a/Lang/Perl/URL-encoding b/Lang/Perl/URL-encoding new file mode 120000 index 0000000000..c434e78b35 --- /dev/null +++ b/Lang/Perl/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Perl \ No newline at end of file diff --git a/Lang/Perl/Unbias-a-random-generator b/Lang/Perl/Unbias-a-random-generator new file mode 120000 index 0000000000..10e04bb8ef --- /dev/null +++ b/Lang/Perl/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Perl \ No newline at end of file diff --git a/Lang/Perl/Undefined-values b/Lang/Perl/Undefined-values new file mode 120000 index 0000000000..b304a2024a --- /dev/null +++ b/Lang/Perl/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Perl \ No newline at end of file diff --git a/Lang/Perl/Unicode-strings b/Lang/Perl/Unicode-strings new file mode 120000 index 0000000000..bcea2bd80b --- /dev/null +++ b/Lang/Perl/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Perl \ No newline at end of file diff --git a/Lang/Perl/Unicode-variable-names b/Lang/Perl/Unicode-variable-names new file mode 120000 index 0000000000..6ec80fc5db --- /dev/null +++ b/Lang/Perl/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Perl \ No newline at end of file diff --git a/Lang/Perl/Universal-Turing-machine b/Lang/Perl/Universal-Turing-machine new file mode 120000 index 0000000000..c258ada35b --- /dev/null +++ b/Lang/Perl/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Perl \ No newline at end of file diff --git a/Lang/Perl/Update-a-configuration-file b/Lang/Perl/Update-a-configuration-file new file mode 120000 index 0000000000..8347b0d1c5 --- /dev/null +++ b/Lang/Perl/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Perl \ No newline at end of file diff --git a/Lang/Perl/User-input-Graphical b/Lang/Perl/User-input-Graphical new file mode 120000 index 0000000000..2afa2225f5 --- /dev/null +++ b/Lang/Perl/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Perl \ No newline at end of file diff --git a/Lang/Perl/User-input-Text b/Lang/Perl/User-input-Text new file mode 120000 index 0000000000..1987d2a6b4 --- /dev/null +++ b/Lang/Perl/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Perl \ No newline at end of file diff --git a/Lang/Perl/Variable-length-quantity b/Lang/Perl/Variable-length-quantity new file mode 120000 index 0000000000..27e9a011f2 --- /dev/null +++ b/Lang/Perl/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Perl \ No newline at end of file diff --git a/Lang/Perl/Variable-size-Get b/Lang/Perl/Variable-size-Get new file mode 120000 index 0000000000..33bbfb0642 --- /dev/null +++ b/Lang/Perl/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Perl \ No newline at end of file diff --git a/Lang/Perl/Variables b/Lang/Perl/Variables new file mode 120000 index 0000000000..1b5f4c76a0 --- /dev/null +++ b/Lang/Perl/Variables @@ -0,0 +1 @@ +../../Task/Variables/Perl \ No newline at end of file diff --git a/Lang/Perl/Variadic-function b/Lang/Perl/Variadic-function new file mode 120000 index 0000000000..a3350fb48d --- /dev/null +++ b/Lang/Perl/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Perl \ No newline at end of file diff --git a/Lang/Perl/Vector-products b/Lang/Perl/Vector-products new file mode 120000 index 0000000000..fe6e794d66 --- /dev/null +++ b/Lang/Perl/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Perl \ No newline at end of file diff --git a/Lang/Perl/Vigen-re-cipher b/Lang/Perl/Vigen-re-cipher new file mode 120000 index 0000000000..313eda15d6 --- /dev/null +++ b/Lang/Perl/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Perl \ No newline at end of file diff --git a/Lang/Perl/Walk-a-directory-Non-recursively b/Lang/Perl/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..8da69715fe --- /dev/null +++ b/Lang/Perl/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Perl \ No newline at end of file diff --git a/Lang/Perl/Walk-a-directory-Recursively b/Lang/Perl/Walk-a-directory-Recursively new file mode 120000 index 0000000000..3ec274f311 --- /dev/null +++ b/Lang/Perl/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Perl \ No newline at end of file diff --git a/Lang/Perl/Web-scraping b/Lang/Perl/Web-scraping new file mode 120000 index 0000000000..5fccbfeef5 --- /dev/null +++ b/Lang/Perl/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Perl \ No newline at end of file diff --git a/Lang/Perl/Window-creation b/Lang/Perl/Window-creation new file mode 120000 index 0000000000..fb2d53515d --- /dev/null +++ b/Lang/Perl/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Perl \ No newline at end of file diff --git a/Lang/Perl/Window-creation-X11 b/Lang/Perl/Window-creation-X11 new file mode 120000 index 0000000000..76ef55560f --- /dev/null +++ b/Lang/Perl/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Perl \ No newline at end of file diff --git a/Lang/Perl/Wireworld b/Lang/Perl/Wireworld new file mode 120000 index 0000000000..029ce33152 --- /dev/null +++ b/Lang/Perl/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Perl \ No newline at end of file diff --git a/Lang/Perl/Word-wrap b/Lang/Perl/Word-wrap new file mode 120000 index 0000000000..e35a65e54d --- /dev/null +++ b/Lang/Perl/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Perl \ No newline at end of file diff --git a/Lang/Perl/Write-float-arrays-to-a-text-file b/Lang/Perl/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..19e9779464 --- /dev/null +++ b/Lang/Perl/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Perl \ No newline at end of file diff --git a/Lang/Perl/XML-DOM-serialization b/Lang/Perl/XML-DOM-serialization new file mode 120000 index 0000000000..d6cec8e825 --- /dev/null +++ b/Lang/Perl/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Perl \ No newline at end of file diff --git a/Lang/Perl/XML-Input b/Lang/Perl/XML-Input new file mode 120000 index 0000000000..c148e0985d --- /dev/null +++ b/Lang/Perl/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Perl \ No newline at end of file diff --git a/Lang/Perl/XML-Output b/Lang/Perl/XML-Output new file mode 120000 index 0000000000..e1e1d98acf --- /dev/null +++ b/Lang/Perl/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Perl \ No newline at end of file diff --git a/Lang/Perl/XML-XPath b/Lang/Perl/XML-XPath new file mode 120000 index 0000000000..a9782e2c91 --- /dev/null +++ b/Lang/Perl/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Perl \ No newline at end of file diff --git a/Lang/Perl/Y-combinator b/Lang/Perl/Y-combinator new file mode 120000 index 0000000000..2e23d73a8c --- /dev/null +++ b/Lang/Perl/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Perl \ No newline at end of file diff --git a/Lang/Perl/Yahoo--search-interface b/Lang/Perl/Yahoo--search-interface new file mode 120000 index 0000000000..b2fdb63f8d --- /dev/null +++ b/Lang/Perl/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Perl \ No newline at end of file diff --git a/Lang/Perl/Yin-and-yang b/Lang/Perl/Yin-and-yang new file mode 120000 index 0000000000..5a9a67474f --- /dev/null +++ b/Lang/Perl/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Perl \ No newline at end of file diff --git a/Lang/Perl/Zebra-puzzle b/Lang/Perl/Zebra-puzzle new file mode 120000 index 0000000000..4f2cf83778 --- /dev/null +++ b/Lang/Perl/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Zig-zag-matrix b/Lang/Perl/Zig-zag-matrix new file mode 120000 index 0000000000..a11ba20a2d --- /dev/null +++ b/Lang/Perl/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/SHA-1 b/Lang/PicoLisp/SHA-1 new file mode 120000 index 0000000000..6337fdf1d1 --- /dev/null +++ b/Lang/PicoLisp/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Seven-sided-dice-from-five-sided-dice b/Lang/PicoLisp/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..30166264c4 --- /dev/null +++ b/Lang/PicoLisp/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Shell-one-liner b/Lang/PicoLisp/Shell-one-liner new file mode 120000 index 0000000000..d9e9aed6db --- /dev/null +++ b/Lang/PicoLisp/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Short-circuit-evaluation b/Lang/PicoLisp/Short-circuit-evaluation new file mode 120000 index 0000000000..89c3fe222e --- /dev/null +++ b/Lang/PicoLisp/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Show-the-epoch b/Lang/PicoLisp/Show-the-epoch new file mode 120000 index 0000000000..e18f7f1f80 --- /dev/null +++ b/Lang/PicoLisp/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sierpinski-carpet b/Lang/PicoLisp/Sierpinski-carpet new file mode 120000 index 0000000000..ef33f1a328 --- /dev/null +++ b/Lang/PicoLisp/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sierpinski-triangle b/Lang/PicoLisp/Sierpinski-triangle new file mode 120000 index 0000000000..007256c9e4 --- /dev/null +++ b/Lang/PicoLisp/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sierpinski-triangle-Graphical b/Lang/PicoLisp/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..e604938d01 --- /dev/null +++ b/Lang/PicoLisp/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sieve-of-Eratosthenes b/Lang/PicoLisp/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d8f11122be --- /dev/null +++ b/Lang/PicoLisp/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Simple-database b/Lang/PicoLisp/Simple-database new file mode 120000 index 0000000000..1895eff0e5 --- /dev/null +++ b/Lang/PicoLisp/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Simple-windowed-application b/Lang/PicoLisp/Simple-windowed-application new file mode 120000 index 0000000000..1de7df346a --- /dev/null +++ b/Lang/PicoLisp/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Simulate-input-Keyboard b/Lang/PicoLisp/Simulate-input-Keyboard new file mode 120000 index 0000000000..ea0412403e --- /dev/null +++ b/Lang/PicoLisp/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Simulate-input-Mouse b/Lang/PicoLisp/Simulate-input-Mouse new file mode 120000 index 0000000000..1368cd1173 --- /dev/null +++ b/Lang/PicoLisp/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Singleton b/Lang/PicoLisp/Singleton new file mode 120000 index 0000000000..f1e6e3f1bc --- /dev/null +++ b/Lang/PicoLisp/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Singly-linked-list-Element-insertion b/Lang/PicoLisp/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..66f066015c --- /dev/null +++ b/Lang/PicoLisp/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Singly-linked-list-Traversal b/Lang/PicoLisp/Singly-linked-list-Traversal new file mode 120000 index 0000000000..1ab816ddfd --- /dev/null +++ b/Lang/PicoLisp/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sleep b/Lang/PicoLisp/Sleep new file mode 120000 index 0000000000..9557440fb4 --- /dev/null +++ b/Lang/PicoLisp/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sockets b/Lang/PicoLisp/Sockets new file mode 120000 index 0000000000..780230badd --- /dev/null +++ b/Lang/PicoLisp/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sokoban b/Lang/PicoLisp/Sokoban new file mode 120000 index 0000000000..7dfd8edf5c --- /dev/null +++ b/Lang/PicoLisp/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Solve-a-Hidato-puzzle b/Lang/PicoLisp/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..e36bef862b --- /dev/null +++ b/Lang/PicoLisp/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sort-an-array-of-composite-structures b/Lang/PicoLisp/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..94bb243100 --- /dev/null +++ b/Lang/PicoLisp/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sort-an-integer-array b/Lang/PicoLisp/Sort-an-integer-array new file mode 120000 index 0000000000..d89b6dd7e5 --- /dev/null +++ b/Lang/PicoLisp/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sort-disjoint-sublist b/Lang/PicoLisp/Sort-disjoint-sublist new file mode 120000 index 0000000000..8c998d19db --- /dev/null +++ b/Lang/PicoLisp/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sort-using-a-custom-comparator b/Lang/PicoLisp/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..474cd918c4 --- /dev/null +++ b/Lang/PicoLisp/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Bead-sort b/Lang/PicoLisp/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..dbffb8c7c2 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Bogosort b/Lang/PicoLisp/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..6c19604aa7 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Bubble-sort b/Lang/PicoLisp/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..82126ba330 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Cocktail-sort b/Lang/PicoLisp/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..0ceb00f56f --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Comb-sort b/Lang/PicoLisp/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..89f02a75fc --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Counting-sort b/Lang/PicoLisp/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..90d2548267 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Gnome-sort b/Lang/PicoLisp/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..de8801794f --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Heapsort b/Lang/PicoLisp/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..add4d27c1b --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Insertion-sort b/Lang/PicoLisp/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..34f4a880b4 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Merge-sort b/Lang/PicoLisp/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..59159a48ea --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Pancake-sort b/Lang/PicoLisp/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..dfc85c7270 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Permutation-sort b/Lang/PicoLisp/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..658542d777 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Quicksort b/Lang/PicoLisp/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..e8fbf5c1e2 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Radix-sort b/Lang/PicoLisp/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..f6a7154896 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Selection-sort b/Lang/PicoLisp/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..8ba1b4b42b --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Shell-sort b/Lang/PicoLisp/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..89a68d5d4d --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Sleep-sort b/Lang/PicoLisp/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..f85b56a5c6 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Stooge-sort b/Lang/PicoLisp/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..9258bead56 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sorting-algorithms-Strand-sort b/Lang/PicoLisp/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..77f6c48612 --- /dev/null +++ b/Lang/PicoLisp/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Soundex b/Lang/PicoLisp/Soundex new file mode 120000 index 0000000000..2fe2de78d3 --- /dev/null +++ b/Lang/PicoLisp/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Speech-synthesis b/Lang/PicoLisp/Speech-synthesis new file mode 120000 index 0000000000..a1cca056a6 --- /dev/null +++ b/Lang/PicoLisp/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Spiral-matrix b/Lang/PicoLisp/Spiral-matrix new file mode 120000 index 0000000000..52e9f66e97 --- /dev/null +++ b/Lang/PicoLisp/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stable-marriage-problem b/Lang/PicoLisp/Stable-marriage-problem new file mode 120000 index 0000000000..7c68b9ebc3 --- /dev/null +++ b/Lang/PicoLisp/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stack b/Lang/PicoLisp/Stack new file mode 120000 index 0000000000..a28281fd9b --- /dev/null +++ b/Lang/PicoLisp/Stack @@ -0,0 +1 @@ +../../Task/Stack/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stack-traces b/Lang/PicoLisp/Stack-traces new file mode 120000 index 0000000000..a09221461d --- /dev/null +++ b/Lang/PicoLisp/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stair-climbing-puzzle b/Lang/PicoLisp/Stair-climbing-puzzle new file mode 120000 index 0000000000..e125fdff58 --- /dev/null +++ b/Lang/PicoLisp/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Standard-deviation b/Lang/PicoLisp/Standard-deviation new file mode 120000 index 0000000000..fd6c328ad7 --- /dev/null +++ b/Lang/PicoLisp/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stem-and-leaf-plot b/Lang/PicoLisp/Stem-and-leaf-plot new file mode 120000 index 0000000000..be0141d8af --- /dev/null +++ b/Lang/PicoLisp/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-case b/Lang/PicoLisp/String-case new file mode 120000 index 0000000000..df5605b332 --- /dev/null +++ b/Lang/PicoLisp/String-case @@ -0,0 +1 @@ +../../Task/String-case/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-concatenation b/Lang/PicoLisp/String-concatenation new file mode 120000 index 0000000000..ae34e35e7a --- /dev/null +++ b/Lang/PicoLisp/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-interpolation--included- b/Lang/PicoLisp/String-interpolation--included- new file mode 120000 index 0000000000..752309c589 --- /dev/null +++ b/Lang/PicoLisp/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-length b/Lang/PicoLisp/String-length new file mode 120000 index 0000000000..a06d289a8b --- /dev/null +++ b/Lang/PicoLisp/String-length @@ -0,0 +1 @@ +../../Task/String-length/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Strip-a-set-of-characters-from-a-string b/Lang/PicoLisp/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..72ff21c40e --- /dev/null +++ b/Lang/PicoLisp/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Strip-block-comments b/Lang/PicoLisp/Strip-block-comments new file mode 120000 index 0000000000..2b35892ad1 --- /dev/null +++ b/Lang/PicoLisp/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Strip-comments-from-a-string b/Lang/PicoLisp/Strip-comments-from-a-string new file mode 120000 index 0000000000..808b3981eb --- /dev/null +++ b/Lang/PicoLisp/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PicoLisp/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..e75139eeac --- /dev/null +++ b/Lang/PicoLisp/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PicoLisp/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..b61dbea461 --- /dev/null +++ b/Lang/PicoLisp/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Substring b/Lang/PicoLisp/Substring new file mode 120000 index 0000000000..0bf1a727e7 --- /dev/null +++ b/Lang/PicoLisp/Substring @@ -0,0 +1 @@ +../../Task/Substring/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Substring-Top-and-tail b/Lang/PicoLisp/Substring-Top-and-tail new file mode 120000 index 0000000000..613e965440 --- /dev/null +++ b/Lang/PicoLisp/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Subtractive-generator b/Lang/PicoLisp/Subtractive-generator new file mode 120000 index 0000000000..37c119a1b4 --- /dev/null +++ b/Lang/PicoLisp/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sudoku b/Lang/PicoLisp/Sudoku new file mode 120000 index 0000000000..eff097e84b --- /dev/null +++ b/Lang/PicoLisp/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sum-and-product-of-an-array b/Lang/PicoLisp/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4cdae32d08 --- /dev/null +++ b/Lang/PicoLisp/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sum-digits-of-an-integer b/Lang/PicoLisp/Sum-digits-of-an-integer new file mode 120000 index 0000000000..6e5fd6e81a --- /dev/null +++ b/Lang/PicoLisp/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sum-of-a-series b/Lang/PicoLisp/Sum-of-a-series new file mode 120000 index 0000000000..f6224732e0 --- /dev/null +++ b/Lang/PicoLisp/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Sum-of-squares b/Lang/PicoLisp/Sum-of-squares new file mode 120000 index 0000000000..4596fc3061 --- /dev/null +++ b/Lang/PicoLisp/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Symmetric-difference b/Lang/PicoLisp/Symmetric-difference new file mode 120000 index 0000000000..43de9f8b88 --- /dev/null +++ b/Lang/PicoLisp/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Synchronous-concurrency b/Lang/PicoLisp/Synchronous-concurrency new file mode 120000 index 0000000000..b349b31e12 --- /dev/null +++ b/Lang/PicoLisp/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/System-time b/Lang/PicoLisp/System-time new file mode 120000 index 0000000000..4c8e2d83f4 --- /dev/null +++ b/Lang/PicoLisp/System-time @@ -0,0 +1 @@ +../../Task/System-time/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Table-creation-Postal-addresses b/Lang/PicoLisp/Table-creation-Postal-addresses new file mode 120000 index 0000000000..a3bbd642fb --- /dev/null +++ b/Lang/PicoLisp/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Take-notes-on-the-command-line b/Lang/PicoLisp/Take-notes-on-the-command-line new file mode 120000 index 0000000000..3ca3850c2e --- /dev/null +++ b/Lang/PicoLisp/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Clear-the-screen b/Lang/PicoLisp/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..f7a296f141 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Coloured-text b/Lang/PicoLisp/Terminal-control-Coloured-text new file mode 120000 index 0000000000..e5bc71f4bc --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Cursor-movement b/Lang/PicoLisp/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..b60aac8487 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Cursor-positioning b/Lang/PicoLisp/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..c9e82cecd8 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Dimensions b/Lang/PicoLisp/Terminal-control-Dimensions new file mode 120000 index 0000000000..e71066546a --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Display-an-extended-character b/Lang/PicoLisp/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..df0b4390f3 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Hiding-the-cursor b/Lang/PicoLisp/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..39bc69379b --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Inverse-video b/Lang/PicoLisp/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a7c73847d9 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Preserve-screen b/Lang/PicoLisp/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..45cf45e477 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Ringing-the-terminal-bell b/Lang/PicoLisp/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b7c3224ef9 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Terminal-control-Unicode-output b/Lang/PicoLisp/Terminal-control-Unicode-output new file mode 120000 index 0000000000..33dcb9bbd1 --- /dev/null +++ b/Lang/PicoLisp/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Ternary-logic b/Lang/PicoLisp/Ternary-logic new file mode 120000 index 0000000000..e0376e24eb --- /dev/null +++ b/Lang/PicoLisp/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Test-a-function b/Lang/PicoLisp/Test-a-function new file mode 120000 index 0000000000..3dde52ba4d --- /dev/null +++ b/Lang/PicoLisp/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Text-processing-1 b/Lang/PicoLisp/Text-processing-1 new file mode 120000 index 0000000000..6ee696c211 --- /dev/null +++ b/Lang/PicoLisp/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Text-processing-2 b/Lang/PicoLisp/Text-processing-2 new file mode 120000 index 0000000000..5ce194ae38 --- /dev/null +++ b/Lang/PicoLisp/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Text-processing-Max-licenses-in-use b/Lang/PicoLisp/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..87c2295ee8 --- /dev/null +++ b/Lang/PicoLisp/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Thieles-interpolation-formula b/Lang/PicoLisp/Thieles-interpolation-formula new file mode 120000 index 0000000000..253731665e --- /dev/null +++ b/Lang/PicoLisp/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Tic-tac-toe b/Lang/PicoLisp/Tic-tac-toe new file mode 120000 index 0000000000..5fbce4e7e9 --- /dev/null +++ b/Lang/PicoLisp/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Time-a-function b/Lang/PicoLisp/Time-a-function new file mode 120000 index 0000000000..cacf1e887e --- /dev/null +++ b/Lang/PicoLisp/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Tokenize-a-string b/Lang/PicoLisp/Tokenize-a-string new file mode 120000 index 0000000000..fa13581fea --- /dev/null +++ b/Lang/PicoLisp/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Top-rank-per-group b/Lang/PicoLisp/Top-rank-per-group new file mode 120000 index 0000000000..6e88044f6d --- /dev/null +++ b/Lang/PicoLisp/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Topological-sort b/Lang/PicoLisp/Topological-sort new file mode 120000 index 0000000000..479cff6e20 --- /dev/null +++ b/Lang/PicoLisp/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Towers-of-Hanoi b/Lang/PicoLisp/Towers-of-Hanoi new file mode 120000 index 0000000000..e614a99f91 --- /dev/null +++ b/Lang/PicoLisp/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Trabb-Pardo-Knuth-algorithm b/Lang/PicoLisp/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..2546ca7750 --- /dev/null +++ b/Lang/PicoLisp/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Tree-traversal b/Lang/PicoLisp/Tree-traversal new file mode 120000 index 0000000000..c9cad9a463 --- /dev/null +++ b/Lang/PicoLisp/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Trigonometric-functions b/Lang/PicoLisp/Trigonometric-functions new file mode 120000 index 0000000000..5882329713 --- /dev/null +++ b/Lang/PicoLisp/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Truncatable-primes b/Lang/PicoLisp/Truncatable-primes new file mode 120000 index 0000000000..a02539e971 --- /dev/null +++ b/Lang/PicoLisp/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Truncate-a-file b/Lang/PicoLisp/Truncate-a-file new file mode 120000 index 0000000000..a4416da19c --- /dev/null +++ b/Lang/PicoLisp/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/URL-encoding b/Lang/PicoLisp/URL-encoding new file mode 120000 index 0000000000..3527b60bb1 --- /dev/null +++ b/Lang/PicoLisp/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Unbias-a-random-generator b/Lang/PicoLisp/Unbias-a-random-generator new file mode 120000 index 0000000000..daef176510 --- /dev/null +++ b/Lang/PicoLisp/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Undefined-values b/Lang/PicoLisp/Undefined-values new file mode 120000 index 0000000000..06e1a29b8d --- /dev/null +++ b/Lang/PicoLisp/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Unicode-strings b/Lang/PicoLisp/Unicode-strings new file mode 120000 index 0000000000..b168b96e8a --- /dev/null +++ b/Lang/PicoLisp/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Unicode-variable-names b/Lang/PicoLisp/Unicode-variable-names new file mode 120000 index 0000000000..082a9758e7 --- /dev/null +++ b/Lang/PicoLisp/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Update-a-configuration-file b/Lang/PicoLisp/Update-a-configuration-file new file mode 120000 index 0000000000..7a48a3ce70 --- /dev/null +++ b/Lang/PicoLisp/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Use-another-language-to-call-a-function b/Lang/PicoLisp/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..09df18a26c --- /dev/null +++ b/Lang/PicoLisp/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/User-input-Graphical b/Lang/PicoLisp/User-input-Graphical new file mode 120000 index 0000000000..f99219a490 --- /dev/null +++ b/Lang/PicoLisp/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/User-input-Text b/Lang/PicoLisp/User-input-Text new file mode 120000 index 0000000000..135d597d09 --- /dev/null +++ b/Lang/PicoLisp/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Van-der-Corput-sequence b/Lang/PicoLisp/Van-der-Corput-sequence new file mode 120000 index 0000000000..1fbb7bbab7 --- /dev/null +++ b/Lang/PicoLisp/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Variable-length-quantity b/Lang/PicoLisp/Variable-length-quantity new file mode 120000 index 0000000000..5394e38ae5 --- /dev/null +++ b/Lang/PicoLisp/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Variables b/Lang/PicoLisp/Variables new file mode 120000 index 0000000000..f061b6a020 --- /dev/null +++ b/Lang/PicoLisp/Variables @@ -0,0 +1 @@ +../../Task/Variables/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Variadic-function b/Lang/PicoLisp/Variadic-function new file mode 120000 index 0000000000..c6a1880f89 --- /dev/null +++ b/Lang/PicoLisp/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Vector-products b/Lang/PicoLisp/Vector-products new file mode 120000 index 0000000000..d265175aae --- /dev/null +++ b/Lang/PicoLisp/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Verify-distribution-uniformity-Naive b/Lang/PicoLisp/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..4386504822 --- /dev/null +++ b/Lang/PicoLisp/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Vigen-re-cipher b/Lang/PicoLisp/Vigen-re-cipher new file mode 120000 index 0000000000..79ad8e3ade --- /dev/null +++ b/Lang/PicoLisp/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Walk-a-directory-Non-recursively b/Lang/PicoLisp/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..0f3666570d --- /dev/null +++ b/Lang/PicoLisp/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Walk-a-directory-Recursively b/Lang/PicoLisp/Walk-a-directory-Recursively new file mode 120000 index 0000000000..d136a41008 --- /dev/null +++ b/Lang/PicoLisp/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Web-scraping b/Lang/PicoLisp/Web-scraping new file mode 120000 index 0000000000..cf623fbb0a --- /dev/null +++ b/Lang/PicoLisp/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Window-creation b/Lang/PicoLisp/Window-creation new file mode 120000 index 0000000000..6245b97daa --- /dev/null +++ b/Lang/PicoLisp/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Window-creation-X11 b/Lang/PicoLisp/Window-creation-X11 new file mode 120000 index 0000000000..1bcf225e39 --- /dev/null +++ b/Lang/PicoLisp/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Window-management b/Lang/PicoLisp/Window-management new file mode 120000 index 0000000000..d8f4d237e0 --- /dev/null +++ b/Lang/PicoLisp/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Wireworld b/Lang/PicoLisp/Wireworld new file mode 120000 index 0000000000..16689547b0 --- /dev/null +++ b/Lang/PicoLisp/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Word-wrap b/Lang/PicoLisp/Word-wrap new file mode 120000 index 0000000000..ff27a35ecc --- /dev/null +++ b/Lang/PicoLisp/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Write-float-arrays-to-a-text-file b/Lang/PicoLisp/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..20e7e4ab61 --- /dev/null +++ b/Lang/PicoLisp/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Write-to-Windows-event-log b/Lang/PicoLisp/Write-to-Windows-event-log new file mode 120000 index 0000000000..e6418a1bb6 --- /dev/null +++ b/Lang/PicoLisp/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/XML-DOM-serialization b/Lang/PicoLisp/XML-DOM-serialization new file mode 120000 index 0000000000..baba317757 --- /dev/null +++ b/Lang/PicoLisp/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/XML-Input b/Lang/PicoLisp/XML-Input new file mode 120000 index 0000000000..e9f9229cf6 --- /dev/null +++ b/Lang/PicoLisp/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/XML-Output b/Lang/PicoLisp/XML-Output new file mode 120000 index 0000000000..cdc1a9a4be --- /dev/null +++ b/Lang/PicoLisp/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/XML-XPath b/Lang/PicoLisp/XML-XPath new file mode 120000 index 0000000000..d889e5009f --- /dev/null +++ b/Lang/PicoLisp/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Xiaolin-Wus-line-algorithm b/Lang/PicoLisp/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..2572d2545d --- /dev/null +++ b/Lang/PicoLisp/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Y-combinator b/Lang/PicoLisp/Y-combinator new file mode 120000 index 0000000000..5eda54bda6 --- /dev/null +++ b/Lang/PicoLisp/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Yahoo--search-interface b/Lang/PicoLisp/Yahoo--search-interface new file mode 120000 index 0000000000..f8e4f8114c --- /dev/null +++ b/Lang/PicoLisp/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Yin-and-yang b/Lang/PicoLisp/Yin-and-yang new file mode 120000 index 0000000000..98bde966e2 --- /dev/null +++ b/Lang/PicoLisp/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Zebra-puzzle b/Lang/PicoLisp/Zebra-puzzle new file mode 120000 index 0000000000..c30ff7a2c3 --- /dev/null +++ b/Lang/PicoLisp/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Zig-zag-matrix b/Lang/PicoLisp/Zig-zag-matrix new file mode 120000 index 0000000000..e9bf6ea061 --- /dev/null +++ b/Lang/PicoLisp/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PicoLisp \ No newline at end of file diff --git a/Lang/Pike/Shell-one-liner b/Lang/Pike/Shell-one-liner new file mode 120000 index 0000000000..aecf952b17 --- /dev/null +++ b/Lang/Pike/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Pike \ No newline at end of file diff --git a/Lang/Pike/Short-circuit-evaluation b/Lang/Pike/Short-circuit-evaluation new file mode 120000 index 0000000000..e1ae787397 --- /dev/null +++ b/Lang/Pike/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Pike \ No newline at end of file diff --git a/Lang/Pike/Simple-database b/Lang/Pike/Simple-database new file mode 120000 index 0000000000..68545ef702 --- /dev/null +++ b/Lang/Pike/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Pike \ No newline at end of file diff --git a/Lang/Pike/Simple-windowed-application b/Lang/Pike/Simple-windowed-application new file mode 120000 index 0000000000..5b69b5b55f --- /dev/null +++ b/Lang/Pike/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Pike \ No newline at end of file diff --git a/Lang/Pike/Sockets b/Lang/Pike/Sockets new file mode 120000 index 0000000000..c33c3ff081 --- /dev/null +++ b/Lang/Pike/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Pike \ No newline at end of file diff --git a/Lang/Pike/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Pike/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..0b4b4821a1 --- /dev/null +++ b/Lang/Pike/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Pike \ No newline at end of file diff --git a/Lang/Pike/Sum-of-a-series b/Lang/Pike/Sum-of-a-series new file mode 120000 index 0000000000..e4539a9b42 --- /dev/null +++ b/Lang/Pike/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Pike \ No newline at end of file diff --git a/Lang/Pike/Symmetric-difference b/Lang/Pike/Symmetric-difference new file mode 120000 index 0000000000..e84e231d55 --- /dev/null +++ b/Lang/Pike/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Pike \ No newline at end of file diff --git a/Lang/Pike/Tokenize-a-string b/Lang/Pike/Tokenize-a-string new file mode 120000 index 0000000000..bdfb2cf264 --- /dev/null +++ b/Lang/Pike/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Pike \ No newline at end of file diff --git a/Lang/Pike/Undefined-values b/Lang/Pike/Undefined-values new file mode 120000 index 0000000000..8eb3b0eea1 --- /dev/null +++ b/Lang/Pike/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Pike \ No newline at end of file diff --git a/Lang/Pike/User-input-Text b/Lang/Pike/User-input-Text new file mode 120000 index 0000000000..a13cb47928 --- /dev/null +++ b/Lang/Pike/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Pike \ No newline at end of file diff --git a/Lang/Pike/Walk-a-directory-Non-recursively b/Lang/Pike/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9b3db6a072 --- /dev/null +++ b/Lang/Pike/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Pike \ No newline at end of file diff --git a/Lang/Pike/XML-DOM-serialization b/Lang/Pike/XML-DOM-serialization new file mode 120000 index 0000000000..a52af1bd29 --- /dev/null +++ b/Lang/Pike/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Pike \ No newline at end of file diff --git a/Lang/Pike/XML-Input b/Lang/Pike/XML-Input new file mode 120000 index 0000000000..4f50c8b5a7 --- /dev/null +++ b/Lang/Pike/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Pike \ No newline at end of file diff --git a/Lang/Pop11/Sierpinski-triangle b/Lang/Pop11/Sierpinski-triangle new file mode 120000 index 0000000000..35aa94e9f1 --- /dev/null +++ b/Lang/Pop11/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Singly-linked-list-Element-definition b/Lang/Pop11/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..0305ed3805 --- /dev/null +++ b/Lang/Pop11/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Singly-linked-list-Element-insertion b/Lang/Pop11/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..56ee3a08c3 --- /dev/null +++ b/Lang/Pop11/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sort-an-integer-array b/Lang/Pop11/Sort-an-integer-array new file mode 120000 index 0000000000..2831f5100c --- /dev/null +++ b/Lang/Pop11/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sort-using-a-custom-comparator b/Lang/Pop11/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..11ca88e96a --- /dev/null +++ b/Lang/Pop11/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sorting-algorithms-Bubble-sort b/Lang/Pop11/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..a318d41fcf --- /dev/null +++ b/Lang/Pop11/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/String-case b/Lang/Pop11/String-case new file mode 120000 index 0000000000..3470d0dd85 --- /dev/null +++ b/Lang/Pop11/String-case @@ -0,0 +1 @@ +../../Task/String-case/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/String-length b/Lang/Pop11/String-length new file mode 120000 index 0000000000..e0e492c59e --- /dev/null +++ b/Lang/Pop11/String-length @@ -0,0 +1 @@ +../../Task/String-length/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sum-and-product-of-an-array b/Lang/Pop11/Sum-and-product-of-an-array new file mode 120000 index 0000000000..861b9ec088 --- /dev/null +++ b/Lang/Pop11/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sum-of-a-series b/Lang/Pop11/Sum-of-a-series new file mode 120000 index 0000000000..effa5d96d3 --- /dev/null +++ b/Lang/Pop11/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Sum-of-squares b/Lang/Pop11/Sum-of-squares new file mode 120000 index 0000000000..1099c3bdbf --- /dev/null +++ b/Lang/Pop11/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Tokenize-a-string b/Lang/Pop11/Tokenize-a-string new file mode 120000 index 0000000000..c08b159993 --- /dev/null +++ b/Lang/Pop11/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Towers-of-Hanoi b/Lang/Pop11/Towers-of-Hanoi new file mode 120000 index 0000000000..ff9c90e57e --- /dev/null +++ b/Lang/Pop11/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Trigonometric-functions b/Lang/Pop11/Trigonometric-functions new file mode 120000 index 0000000000..8270da05c8 --- /dev/null +++ b/Lang/Pop11/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/User-input-Text b/Lang/Pop11/User-input-Text new file mode 120000 index 0000000000..d2acfab382 --- /dev/null +++ b/Lang/Pop11/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Variable-size-Get b/Lang/Pop11/Variable-size-Get new file mode 120000 index 0000000000..2500a49722 --- /dev/null +++ b/Lang/Pop11/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Walk-a-directory-Non-recursively b/Lang/Pop11/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..9b21800997 --- /dev/null +++ b/Lang/Pop11/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Walk-a-directory-Recursively b/Lang/Pop11/Walk-a-directory-Recursively new file mode 120000 index 0000000000..efd84feeac --- /dev/null +++ b/Lang/Pop11/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Pop11 \ No newline at end of file diff --git a/Lang/Pop11/Y-combinator b/Lang/Pop11/Y-combinator new file mode 120000 index 0000000000..67c5fcdbfe --- /dev/null +++ b/Lang/Pop11/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Pop11 \ No newline at end of file diff --git a/Lang/PostScript/Sierpinski-carpet b/Lang/PostScript/Sierpinski-carpet new file mode 120000 index 0000000000..7bb28b4545 --- /dev/null +++ b/Lang/PostScript/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sierpinski-triangle b/Lang/PostScript/Sierpinski-triangle new file mode 120000 index 0000000000..8e26733b48 --- /dev/null +++ b/Lang/PostScript/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sierpinski-triangle-Graphical b/Lang/PostScript/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..cdcf0235cb --- /dev/null +++ b/Lang/PostScript/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sorting-algorithms-Bubble-sort b/Lang/PostScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..d5fae1d685 --- /dev/null +++ b/Lang/PostScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Stack b/Lang/PostScript/Stack new file mode 120000 index 0000000000..9c5c8d6a4a --- /dev/null +++ b/Lang/PostScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/PostScript \ No newline at end of file diff --git a/Lang/PostScript/String-length b/Lang/PostScript/String-length new file mode 120000 index 0000000000..b058d8e2ac --- /dev/null +++ b/Lang/PostScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sum-and-product-of-an-array b/Lang/PostScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..b0be523a87 --- /dev/null +++ b/Lang/PostScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sum-of-a-series b/Lang/PostScript/Sum-of-a-series new file mode 120000 index 0000000000..63fe3ee3d1 --- /dev/null +++ b/Lang/PostScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Sum-of-squares b/Lang/PostScript/Sum-of-squares new file mode 120000 index 0000000000..0e51c2ee14 --- /dev/null +++ b/Lang/PostScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Terminal-control-Ringing-the-terminal-bell b/Lang/PostScript/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..a26c5f4599 --- /dev/null +++ b/Lang/PostScript/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Towers-of-Hanoi b/Lang/PostScript/Towers-of-Hanoi new file mode 120000 index 0000000000..6fd42ab951 --- /dev/null +++ b/Lang/PostScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Trigonometric-functions b/Lang/PostScript/Trigonometric-functions new file mode 120000 index 0000000000..4904dcb2f5 --- /dev/null +++ b/Lang/PostScript/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PostScript \ No newline at end of file diff --git a/Lang/PostScript/User-input-Text b/Lang/PostScript/User-input-Text new file mode 120000 index 0000000000..8976eee865 --- /dev/null +++ b/Lang/PostScript/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Y-combinator b/Lang/PostScript/Y-combinator new file mode 120000 index 0000000000..cb806d4c92 --- /dev/null +++ b/Lang/PostScript/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Yin-and-yang b/Lang/PostScript/Yin-and-yang new file mode 120000 index 0000000000..755bc4137d --- /dev/null +++ b/Lang/PostScript/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/PostScript \ No newline at end of file diff --git a/Lang/PostScript/Zig-zag-matrix b/Lang/PostScript/Zig-zag-matrix new file mode 120000 index 0000000000..9e693d07d2 --- /dev/null +++ b/Lang/PostScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PostScript \ No newline at end of file diff --git a/Lang/PowerBASIC/Sort-an-integer-array b/Lang/PowerBASIC/Sort-an-integer-array new file mode 120000 index 0000000000..f9cb13f464 --- /dev/null +++ b/Lang/PowerBASIC/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Sort-using-a-custom-comparator b/Lang/PowerBASIC/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..d93ea60ad0 --- /dev/null +++ b/Lang/PowerBASIC/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Sorting-algorithms-Gnome-sort b/Lang/PowerBASIC/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..7418f69731 --- /dev/null +++ b/Lang/PowerBASIC/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Sorting-algorithms-Stooge-sort b/Lang/PowerBASIC/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..45e49f18ea --- /dev/null +++ b/Lang/PowerBASIC/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Tokenize-a-string b/Lang/PowerBASIC/Tokenize-a-string new file mode 120000 index 0000000000..c877112582 --- /dev/null +++ b/Lang/PowerBASIC/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Truncate-a-file b/Lang/PowerBASIC/Truncate-a-file new file mode 120000 index 0000000000..a275f8cffd --- /dev/null +++ b/Lang/PowerBASIC/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/User-input-Graphical b/Lang/PowerBASIC/User-input-Graphical new file mode 120000 index 0000000000..851529c310 --- /dev/null +++ b/Lang/PowerBASIC/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerShell/Shell-one-liner b/Lang/PowerShell/Shell-one-liner new file mode 120000 index 0000000000..6ed31747d9 --- /dev/null +++ b/Lang/PowerShell/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Show-the-epoch b/Lang/PowerShell/Show-the-epoch new file mode 120000 index 0000000000..ce139eb2c7 --- /dev/null +++ b/Lang/PowerShell/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sierpinski-carpet b/Lang/PowerShell/Sierpinski-carpet new file mode 120000 index 0000000000..809429794d --- /dev/null +++ b/Lang/PowerShell/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sierpinski-triangle b/Lang/PowerShell/Sierpinski-triangle new file mode 120000 index 0000000000..c02bcd7d45 --- /dev/null +++ b/Lang/PowerShell/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sieve-of-Eratosthenes b/Lang/PowerShell/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..a28c1f8eb5 --- /dev/null +++ b/Lang/PowerShell/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Simple-windowed-application b/Lang/PowerShell/Simple-windowed-application new file mode 120000 index 0000000000..3fc0fdc796 --- /dev/null +++ b/Lang/PowerShell/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sleep b/Lang/PowerShell/Sleep new file mode 120000 index 0000000000..a7d97b0479 --- /dev/null +++ b/Lang/PowerShell/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sort-an-integer-array b/Lang/PowerShell/Sort-an-integer-array new file mode 120000 index 0000000000..4b172c8f51 --- /dev/null +++ b/Lang/PowerShell/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sort-using-a-custom-comparator b/Lang/PowerShell/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..768cf8b8fe --- /dev/null +++ b/Lang/PowerShell/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Bead-sort b/Lang/PowerShell/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5ef6c74a0b --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Bogosort b/Lang/PowerShell/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..7759857a7e --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Bubble-sort b/Lang/PowerShell/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..c9e1830883 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Cocktail-sort b/Lang/PowerShell/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..e36e0e6586 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Comb-sort b/Lang/PowerShell/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..4657cc94fb --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Merge-sort b/Lang/PowerShell/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..f384045c54 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Pancake-sort b/Lang/PowerShell/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..4d8d96508f --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Permutation-sort b/Lang/PowerShell/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..600cf260bd --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Quicksort b/Lang/PowerShell/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..1153a5208f --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Selection-sort b/Lang/PowerShell/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..b81abcfb41 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Shell-sort b/Lang/PowerShell/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..fdc36b4c1a --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Stooge-sort b/Lang/PowerShell/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..0c87bb9236 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Standard-deviation b/Lang/PowerShell/Standard-deviation new file mode 120000 index 0000000000..dd2b2e384d --- /dev/null +++ b/Lang/PowerShell/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-case b/Lang/PowerShell/String-case new file mode 120000 index 0000000000..ad259b0deb --- /dev/null +++ b/Lang/PowerShell/String-case @@ -0,0 +1 @@ +../../Task/String-case/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-concatenation b/Lang/PowerShell/String-concatenation new file mode 120000 index 0000000000..9d4679f872 --- /dev/null +++ b/Lang/PowerShell/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-length b/Lang/PowerShell/String-length new file mode 120000 index 0000000000..647bd3e541 --- /dev/null +++ b/Lang/PowerShell/String-length @@ -0,0 +1 @@ +../../Task/String-length/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Substring b/Lang/PowerShell/Substring new file mode 120000 index 0000000000..cfb8f99bbd --- /dev/null +++ b/Lang/PowerShell/Substring @@ -0,0 +1 @@ +../../Task/Substring/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sum-and-product-of-an-array b/Lang/PowerShell/Sum-and-product-of-an-array new file mode 120000 index 0000000000..8d19d6e29f --- /dev/null +++ b/Lang/PowerShell/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sum-of-a-series b/Lang/PowerShell/Sum-of-a-series new file mode 120000 index 0000000000..89dc07714d --- /dev/null +++ b/Lang/PowerShell/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sum-of-squares b/Lang/PowerShell/Sum-of-squares new file mode 120000 index 0000000000..654dedcf5e --- /dev/null +++ b/Lang/PowerShell/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/System-time b/Lang/PowerShell/System-time new file mode 120000 index 0000000000..2ebdb6faf1 --- /dev/null +++ b/Lang/PowerShell/System-time @@ -0,0 +1 @@ +../../Task/System-time/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Take-notes-on-the-command-line b/Lang/PowerShell/Take-notes-on-the-command-line new file mode 120000 index 0000000000..a13b80c849 --- /dev/null +++ b/Lang/PowerShell/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Terminal-control-Clear-the-screen b/Lang/PowerShell/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..288792fdc0 --- /dev/null +++ b/Lang/PowerShell/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Terminal-control-Cursor-positioning b/Lang/PowerShell/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..06dbb8bd28 --- /dev/null +++ b/Lang/PowerShell/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Terminal-control-Ringing-the-terminal-bell b/Lang/PowerShell/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..19971d782a --- /dev/null +++ b/Lang/PowerShell/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Text-processing-2 b/Lang/PowerShell/Text-processing-2 new file mode 120000 index 0000000000..6e4d996ba4 --- /dev/null +++ b/Lang/PowerShell/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Thieles-interpolation-formula b/Lang/PowerShell/Thieles-interpolation-formula new file mode 120000 index 0000000000..a1cf36ec6d --- /dev/null +++ b/Lang/PowerShell/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Tokenize-a-string b/Lang/PowerShell/Tokenize-a-string new file mode 120000 index 0000000000..cc790649ea --- /dev/null +++ b/Lang/PowerShell/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Top-rank-per-group b/Lang/PowerShell/Top-rank-per-group new file mode 120000 index 0000000000..305457e60b --- /dev/null +++ b/Lang/PowerShell/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Topological-sort b/Lang/PowerShell/Topological-sort new file mode 120000 index 0000000000..ee8cd4663e --- /dev/null +++ b/Lang/PowerShell/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Trigonometric-functions b/Lang/PowerShell/Trigonometric-functions new file mode 120000 index 0000000000..4fa484a91c --- /dev/null +++ b/Lang/PowerShell/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Truncatable-primes b/Lang/PowerShell/Truncatable-primes new file mode 120000 index 0000000000..3c5d8ba5fe --- /dev/null +++ b/Lang/PowerShell/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/User-input-Graphical b/Lang/PowerShell/User-input-Graphical new file mode 120000 index 0000000000..72efebdb14 --- /dev/null +++ b/Lang/PowerShell/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/User-input-Text b/Lang/PowerShell/User-input-Text new file mode 120000 index 0000000000..182948db42 --- /dev/null +++ b/Lang/PowerShell/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Variables b/Lang/PowerShell/Variables new file mode 120000 index 0000000000..a8428fa69d --- /dev/null +++ b/Lang/PowerShell/Variables @@ -0,0 +1 @@ +../../Task/Variables/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Variadic-function b/Lang/PowerShell/Variadic-function new file mode 120000 index 0000000000..7ff63fc9a4 --- /dev/null +++ b/Lang/PowerShell/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Walk-a-directory-Non-recursively b/Lang/PowerShell/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..278a8ff718 --- /dev/null +++ b/Lang/PowerShell/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Walk-a-directory-Recursively b/Lang/PowerShell/Walk-a-directory-Recursively new file mode 120000 index 0000000000..56813a10cf --- /dev/null +++ b/Lang/PowerShell/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Web-scraping b/Lang/PowerShell/Web-scraping new file mode 120000 index 0000000000..9a8e71fc5e --- /dev/null +++ b/Lang/PowerShell/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Window-creation b/Lang/PowerShell/Window-creation new file mode 120000 index 0000000000..165a4097da --- /dev/null +++ b/Lang/PowerShell/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Write-to-Windows-event-log b/Lang/PowerShell/Write-to-Windows-event-log new file mode 120000 index 0000000000..6842822373 --- /dev/null +++ b/Lang/PowerShell/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/XML-Input b/Lang/PowerShell/XML-Input new file mode 120000 index 0000000000..0208bfbb91 --- /dev/null +++ b/Lang/PowerShell/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Y-combinator b/Lang/PowerShell/Y-combinator new file mode 120000 index 0000000000..3f63751f8b --- /dev/null +++ b/Lang/PowerShell/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Zig-zag-matrix b/Lang/PowerShell/Zig-zag-matrix new file mode 120000 index 0000000000..acaba8645a --- /dev/null +++ b/Lang/PowerShell/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PowerShell \ No newline at end of file diff --git a/Lang/ProDOS/Terminal-control-Clear-the-screen b/Lang/ProDOS/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..374105de04 --- /dev/null +++ b/Lang/ProDOS/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/ProDOS \ No newline at end of file diff --git a/Lang/Processing/Sieve-of-Eratosthenes b/Lang/Processing/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..98c735101e --- /dev/null +++ b/Lang/Processing/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Processing \ No newline at end of file diff --git a/Lang/Prolog/Short-circuit-evaluation b/Lang/Prolog/Short-circuit-evaluation new file mode 120000 index 0000000000..0cb0936965 --- /dev/null +++ b/Lang/Prolog/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sierpinski-triangle b/Lang/Prolog/Sierpinski-triangle new file mode 120000 index 0000000000..321dee0b9c --- /dev/null +++ b/Lang/Prolog/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sierpinski-triangle-Graphical b/Lang/Prolog/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..0a5f900e5a --- /dev/null +++ b/Lang/Prolog/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sieve-of-Eratosthenes b/Lang/Prolog/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..5ca45a201e --- /dev/null +++ b/Lang/Prolog/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Simple-windowed-application b/Lang/Prolog/Simple-windowed-application new file mode 120000 index 0000000000..b7efd34315 --- /dev/null +++ b/Lang/Prolog/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sleep b/Lang/Prolog/Sleep new file mode 120000 index 0000000000..7c492319d4 --- /dev/null +++ b/Lang/Prolog/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Solve-a-Hidato-puzzle b/Lang/Prolog/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..50bea4ccbb --- /dev/null +++ b/Lang/Prolog/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sort-using-a-custom-comparator b/Lang/Prolog/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..ddb8a109e8 --- /dev/null +++ b/Lang/Prolog/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Insertion-sort b/Lang/Prolog/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..83f42bf472 --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Merge-sort b/Lang/Prolog/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..5bb30d0923 --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Permutation-sort b/Lang/Prolog/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..016c9d3cbb --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Quicksort b/Lang/Prolog/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..0015c48c91 --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sorting-algorithms-Sleep-sort b/Lang/Prolog/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..6286fad2ae --- /dev/null +++ b/Lang/Prolog/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Stable-marriage-problem b/Lang/Prolog/Stable-marriage-problem new file mode 120000 index 0000000000..3c0b9d68ad --- /dev/null +++ b/Lang/Prolog/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Stack b/Lang/Prolog/Stack new file mode 120000 index 0000000000..5f30c4c419 --- /dev/null +++ b/Lang/Prolog/Stack @@ -0,0 +1 @@ +../../Task/Stack/Prolog \ No newline at end of file diff --git a/Lang/Prolog/String-interpolation--included- b/Lang/Prolog/String-interpolation--included- new file mode 120000 index 0000000000..622663037a --- /dev/null +++ b/Lang/Prolog/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Strip-a-set-of-characters-from-a-string b/Lang/Prolog/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..d07eb2bb2d --- /dev/null +++ b/Lang/Prolog/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Strip-comments-from-a-string b/Lang/Prolog/Strip-comments-from-a-string new file mode 120000 index 0000000000..86c718af04 --- /dev/null +++ b/Lang/Prolog/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Prolog/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..3baa81f8af --- /dev/null +++ b/Lang/Prolog/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Substring-Top-and-tail b/Lang/Prolog/Substring-Top-and-tail new file mode 120000 index 0000000000..225e42e1ac --- /dev/null +++ b/Lang/Prolog/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sudoku b/Lang/Prolog/Sudoku new file mode 120000 index 0000000000..20955f67b4 --- /dev/null +++ b/Lang/Prolog/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sum-and-product-of-an-array b/Lang/Prolog/Sum-and-product-of-an-array new file mode 120000 index 0000000000..08b44798d4 --- /dev/null +++ b/Lang/Prolog/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sum-of-a-series b/Lang/Prolog/Sum-of-a-series new file mode 120000 index 0000000000..f53e82ee59 --- /dev/null +++ b/Lang/Prolog/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Symmetric-difference b/Lang/Prolog/Symmetric-difference new file mode 120000 index 0000000000..8076d4c110 --- /dev/null +++ b/Lang/Prolog/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Tic-tac-toe b/Lang/Prolog/Tic-tac-toe new file mode 120000 index 0000000000..532c486cf2 --- /dev/null +++ b/Lang/Prolog/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Tokenize-a-string b/Lang/Prolog/Tokenize-a-string new file mode 120000 index 0000000000..094b763ea6 --- /dev/null +++ b/Lang/Prolog/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Towers-of-Hanoi b/Lang/Prolog/Towers-of-Hanoi new file mode 120000 index 0000000000..e855eacaeb --- /dev/null +++ b/Lang/Prolog/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Tree-traversal b/Lang/Prolog/Tree-traversal new file mode 120000 index 0000000000..3e0c481298 --- /dev/null +++ b/Lang/Prolog/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Twelve-statements b/Lang/Prolog/Twelve-statements new file mode 120000 index 0000000000..757210cdc8 --- /dev/null +++ b/Lang/Prolog/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Universal-Turing-machine b/Lang/Prolog/Universal-Turing-machine new file mode 120000 index 0000000000..57608b7654 --- /dev/null +++ b/Lang/Prolog/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Van-der-Corput-sequence b/Lang/Prolog/Van-der-Corput-sequence new file mode 120000 index 0000000000..db1e97df95 --- /dev/null +++ b/Lang/Prolog/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Visualize-a-tree b/Lang/Prolog/Visualize-a-tree new file mode 120000 index 0000000000..8c22d70dbc --- /dev/null +++ b/Lang/Prolog/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Voronoi-diagram b/Lang/Prolog/Voronoi-diagram new file mode 120000 index 0000000000..2189c7db01 --- /dev/null +++ b/Lang/Prolog/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Window-creation b/Lang/Prolog/Window-creation new file mode 120000 index 0000000000..323205dbe8 --- /dev/null +++ b/Lang/Prolog/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Y-combinator b/Lang/Prolog/Y-combinator new file mode 120000 index 0000000000..30918d4941 --- /dev/null +++ b/Lang/Prolog/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Yin-and-yang b/Lang/Prolog/Yin-and-yang new file mode 120000 index 0000000000..8bd58af9cc --- /dev/null +++ b/Lang/Prolog/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Zebra-puzzle b/Lang/Prolog/Zebra-puzzle new file mode 120000 index 0000000000..433f4452eb --- /dev/null +++ b/Lang/Prolog/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Zig-zag-matrix b/Lang/Prolog/Zig-zag-matrix new file mode 120000 index 0000000000..4ac8187bfa --- /dev/null +++ b/Lang/Prolog/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Prolog \ No newline at end of file diff --git a/Lang/Protium/Singly-linked-list-Traversal b/Lang/Protium/Singly-linked-list-Traversal new file mode 120000 index 0000000000..9a9187cee8 --- /dev/null +++ b/Lang/Protium/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Protium \ No newline at end of file diff --git a/Lang/Protium/Sleep b/Lang/Protium/Sleep new file mode 120000 index 0000000000..87cc3d33b8 --- /dev/null +++ b/Lang/Protium/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Protium \ No newline at end of file diff --git a/Lang/Protium/Sort-an-integer-array b/Lang/Protium/Sort-an-integer-array new file mode 120000 index 0000000000..5712474a41 --- /dev/null +++ b/Lang/Protium/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Protium \ No newline at end of file diff --git a/Lang/Protium/String-case b/Lang/Protium/String-case new file mode 120000 index 0000000000..9d5ea1e0e4 --- /dev/null +++ b/Lang/Protium/String-case @@ -0,0 +1 @@ +../../Task/String-case/Protium \ No newline at end of file diff --git a/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..96aefd6590 --- /dev/null +++ b/Lang/Protium/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Protium \ No newline at end of file diff --git a/Lang/Protium/Unicode-variable-names b/Lang/Protium/Unicode-variable-names new file mode 120000 index 0000000000..67d1b95832 --- /dev/null +++ b/Lang/Protium/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Protium \ No newline at end of file diff --git a/Lang/Protium/Web-scraping b/Lang/Protium/Web-scraping new file mode 120000 index 0000000000..6613ad1328 --- /dev/null +++ b/Lang/Protium/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Protium \ No newline at end of file diff --git a/Lang/PureBasic/SOAP b/Lang/PureBasic/SOAP new file mode 120000 index 0000000000..d64d35e630 --- /dev/null +++ b/Lang/PureBasic/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Seven-sided-dice-from-five-sided-dice b/Lang/PureBasic/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..e311bd4274 --- /dev/null +++ b/Lang/PureBasic/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Shell-one-liner b/Lang/PureBasic/Shell-one-liner new file mode 120000 index 0000000000..2980b45fd7 --- /dev/null +++ b/Lang/PureBasic/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Short-circuit-evaluation b/Lang/PureBasic/Short-circuit-evaluation new file mode 120000 index 0000000000..d6ee0aaf92 --- /dev/null +++ b/Lang/PureBasic/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Show-the-epoch b/Lang/PureBasic/Show-the-epoch new file mode 120000 index 0000000000..8bf4b90f64 --- /dev/null +++ b/Lang/PureBasic/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sierpinski-carpet b/Lang/PureBasic/Sierpinski-carpet new file mode 120000 index 0000000000..b7e8a25fae --- /dev/null +++ b/Lang/PureBasic/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sierpinski-triangle b/Lang/PureBasic/Sierpinski-triangle new file mode 120000 index 0000000000..6779d4c197 --- /dev/null +++ b/Lang/PureBasic/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sieve-of-Eratosthenes b/Lang/PureBasic/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..511699df63 --- /dev/null +++ b/Lang/PureBasic/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Simple-windowed-application b/Lang/PureBasic/Simple-windowed-application new file mode 120000 index 0000000000..d2ad7a7b78 --- /dev/null +++ b/Lang/PureBasic/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Simulate-input-Keyboard b/Lang/PureBasic/Simulate-input-Keyboard new file mode 120000 index 0000000000..a5f6b48e60 --- /dev/null +++ b/Lang/PureBasic/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Simulate-input-Mouse b/Lang/PureBasic/Simulate-input-Mouse new file mode 120000 index 0000000000..d64237f111 --- /dev/null +++ b/Lang/PureBasic/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Singleton b/Lang/PureBasic/Singleton new file mode 120000 index 0000000000..a23c75b544 --- /dev/null +++ b/Lang/PureBasic/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Singly-linked-list-Element-definition b/Lang/PureBasic/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..b465908def --- /dev/null +++ b/Lang/PureBasic/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Singly-linked-list-Element-insertion b/Lang/PureBasic/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..4925803661 --- /dev/null +++ b/Lang/PureBasic/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Singly-linked-list-Traversal b/Lang/PureBasic/Singly-linked-list-Traversal new file mode 120000 index 0000000000..19a5a2971b --- /dev/null +++ b/Lang/PureBasic/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sleep b/Lang/PureBasic/Sleep new file mode 120000 index 0000000000..0a801ce93d --- /dev/null +++ b/Lang/PureBasic/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sockets b/Lang/PureBasic/Sockets new file mode 120000 index 0000000000..c0492daaf8 --- /dev/null +++ b/Lang/PureBasic/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sort-an-array-of-composite-structures b/Lang/PureBasic/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..82beeb27ae --- /dev/null +++ b/Lang/PureBasic/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sort-an-integer-array b/Lang/PureBasic/Sort-an-integer-array new file mode 120000 index 0000000000..6c0f903258 --- /dev/null +++ b/Lang/PureBasic/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sort-disjoint-sublist b/Lang/PureBasic/Sort-disjoint-sublist new file mode 120000 index 0000000000..23469a88ce --- /dev/null +++ b/Lang/PureBasic/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Bead-sort b/Lang/PureBasic/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..c2b44cba75 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Bogosort b/Lang/PureBasic/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..4251c4f1bd --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Bubble-sort b/Lang/PureBasic/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..4215d232b5 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Cocktail-sort b/Lang/PureBasic/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..37791c590a --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Comb-sort b/Lang/PureBasic/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..3071a81b83 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Counting-sort b/Lang/PureBasic/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..5a1bf8324f --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Gnome-sort b/Lang/PureBasic/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..3858c4ca72 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Heapsort b/Lang/PureBasic/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..7849dcb4ac --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Insertion-sort b/Lang/PureBasic/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..540967bb40 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Merge-sort b/Lang/PureBasic/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..b5e03e2837 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Pancake-sort b/Lang/PureBasic/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..93658ae2b4 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Permutation-sort b/Lang/PureBasic/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..7331df5153 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Quicksort b/Lang/PureBasic/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..78e70e78b1 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Radix-sort b/Lang/PureBasic/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..a7e28099d1 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Selection-sort b/Lang/PureBasic/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..648d003013 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Shell-sort b/Lang/PureBasic/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..b8bd61d9b5 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Sleep-sort b/Lang/PureBasic/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..14d9ebd472 --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Stooge-sort b/Lang/PureBasic/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..1813ab648b --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sorting-algorithms-Strand-sort b/Lang/PureBasic/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..c09e1712dd --- /dev/null +++ b/Lang/PureBasic/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Soundex b/Lang/PureBasic/Soundex new file mode 120000 index 0000000000..3a1ee1592d --- /dev/null +++ b/Lang/PureBasic/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Special-characters b/Lang/PureBasic/Special-characters new file mode 120000 index 0000000000..5f247f68ce --- /dev/null +++ b/Lang/PureBasic/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Spiral-matrix b/Lang/PureBasic/Spiral-matrix new file mode 120000 index 0000000000..16f317f036 --- /dev/null +++ b/Lang/PureBasic/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Stable-marriage-problem b/Lang/PureBasic/Stable-marriage-problem new file mode 120000 index 0000000000..2b29f5ef7e --- /dev/null +++ b/Lang/PureBasic/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Stack b/Lang/PureBasic/Stack new file mode 120000 index 0000000000..97d493b7d7 --- /dev/null +++ b/Lang/PureBasic/Stack @@ -0,0 +1 @@ +../../Task/Stack/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Stack-traces b/Lang/PureBasic/Stack-traces new file mode 120000 index 0000000000..e95d27b384 --- /dev/null +++ b/Lang/PureBasic/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Stair-climbing-puzzle b/Lang/PureBasic/Stair-climbing-puzzle new file mode 120000 index 0000000000..b3eb757d3f --- /dev/null +++ b/Lang/PureBasic/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Standard-deviation b/Lang/PureBasic/Standard-deviation new file mode 120000 index 0000000000..12936a6821 --- /dev/null +++ b/Lang/PureBasic/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Stem-and-leaf-plot b/Lang/PureBasic/Stem-and-leaf-plot new file mode 120000 index 0000000000..e4d9ddcc7d --- /dev/null +++ b/Lang/PureBasic/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-case b/Lang/PureBasic/String-case new file mode 120000 index 0000000000..3d3675da1e --- /dev/null +++ b/Lang/PureBasic/String-case @@ -0,0 +1 @@ +../../Task/String-case/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-concatenation b/Lang/PureBasic/String-concatenation new file mode 120000 index 0000000000..242bfe93bc --- /dev/null +++ b/Lang/PureBasic/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-interpolation--included- b/Lang/PureBasic/String-interpolation--included- new file mode 120000 index 0000000000..94c0759cb8 --- /dev/null +++ b/Lang/PureBasic/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/String-length b/Lang/PureBasic/String-length new file mode 120000 index 0000000000..de220bb244 --- /dev/null +++ b/Lang/PureBasic/String-length @@ -0,0 +1 @@ +../../Task/String-length/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Strip-a-set-of-characters-from-a-string b/Lang/PureBasic/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..93eb50c51a --- /dev/null +++ b/Lang/PureBasic/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Strip-block-comments b/Lang/PureBasic/Strip-block-comments new file mode 120000 index 0000000000..efd5fbaf5f --- /dev/null +++ b/Lang/PureBasic/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Strip-comments-from-a-string b/Lang/PureBasic/Strip-comments-from-a-string new file mode 120000 index 0000000000..c7f1fc48c7 --- /dev/null +++ b/Lang/PureBasic/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PureBasic/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..77df3827a0 --- /dev/null +++ b/Lang/PureBasic/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PureBasic/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..91ee3b652c --- /dev/null +++ b/Lang/PureBasic/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Substring b/Lang/PureBasic/Substring new file mode 120000 index 0000000000..ff4037b4e4 --- /dev/null +++ b/Lang/PureBasic/Substring @@ -0,0 +1 @@ +../../Task/Substring/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Substring-Top-and-tail b/Lang/PureBasic/Substring-Top-and-tail new file mode 120000 index 0000000000..ae635dc911 --- /dev/null +++ b/Lang/PureBasic/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sudoku b/Lang/PureBasic/Sudoku new file mode 120000 index 0000000000..bf35697f47 --- /dev/null +++ b/Lang/PureBasic/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sum-and-product-of-an-array b/Lang/PureBasic/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a05a8e2d30 --- /dev/null +++ b/Lang/PureBasic/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sum-of-a-series b/Lang/PureBasic/Sum-of-a-series new file mode 120000 index 0000000000..b22b6d5583 --- /dev/null +++ b/Lang/PureBasic/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sum-of-squares b/Lang/PureBasic/Sum-of-squares new file mode 120000 index 0000000000..8285d60961 --- /dev/null +++ b/Lang/PureBasic/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Sutherland-Hodgman-polygon-clipping b/Lang/PureBasic/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..b02c399900 --- /dev/null +++ b/Lang/PureBasic/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Symmetric-difference b/Lang/PureBasic/Symmetric-difference new file mode 120000 index 0000000000..f26504afca --- /dev/null +++ b/Lang/PureBasic/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Synchronous-concurrency b/Lang/PureBasic/Synchronous-concurrency new file mode 120000 index 0000000000..d7ddeb70a5 --- /dev/null +++ b/Lang/PureBasic/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/System-time b/Lang/PureBasic/System-time new file mode 120000 index 0000000000..2b3147637a --- /dev/null +++ b/Lang/PureBasic/System-time @@ -0,0 +1 @@ +../../Task/System-time/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Table-creation-Postal-addresses b/Lang/PureBasic/Table-creation-Postal-addresses new file mode 120000 index 0000000000..70546a0226 --- /dev/null +++ b/Lang/PureBasic/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Take-notes-on-the-command-line b/Lang/PureBasic/Take-notes-on-the-command-line new file mode 120000 index 0000000000..cd269146f7 --- /dev/null +++ b/Lang/PureBasic/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Clear-the-screen b/Lang/PureBasic/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..8a716535d2 --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Coloured-text b/Lang/PureBasic/Terminal-control-Coloured-text new file mode 120000 index 0000000000..46232bdc98 --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Cursor-positioning b/Lang/PureBasic/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..7ba42f0d57 --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Dimensions b/Lang/PureBasic/Terminal-control-Dimensions new file mode 120000 index 0000000000..f005b2b03b --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Display-an-extended-character b/Lang/PureBasic/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..2837f9dedd --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Hiding-the-cursor b/Lang/PureBasic/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..c1d6fc15e5 --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Inverse-video b/Lang/PureBasic/Terminal-control-Inverse-video new file mode 120000 index 0000000000..474d2fc099 --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Terminal-control-Ringing-the-terminal-bell b/Lang/PureBasic/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..986660144d --- /dev/null +++ b/Lang/PureBasic/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Test-a-function b/Lang/PureBasic/Test-a-function new file mode 120000 index 0000000000..4c71f5858e --- /dev/null +++ b/Lang/PureBasic/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Text-processing-1 b/Lang/PureBasic/Text-processing-1 new file mode 120000 index 0000000000..c2b34f88bc --- /dev/null +++ b/Lang/PureBasic/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Text-processing-2 b/Lang/PureBasic/Text-processing-2 new file mode 120000 index 0000000000..6469e60bf2 --- /dev/null +++ b/Lang/PureBasic/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Text-processing-Max-licenses-in-use b/Lang/PureBasic/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..bd3edeb63f --- /dev/null +++ b/Lang/PureBasic/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Time-a-function b/Lang/PureBasic/Time-a-function new file mode 120000 index 0000000000..3ab739a298 --- /dev/null +++ b/Lang/PureBasic/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Tokenize-a-string b/Lang/PureBasic/Tokenize-a-string new file mode 120000 index 0000000000..fe3ee4378e --- /dev/null +++ b/Lang/PureBasic/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Top-rank-per-group b/Lang/PureBasic/Top-rank-per-group new file mode 120000 index 0000000000..6800162fe7 --- /dev/null +++ b/Lang/PureBasic/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Topological-sort b/Lang/PureBasic/Topological-sort new file mode 120000 index 0000000000..660796d446 --- /dev/null +++ b/Lang/PureBasic/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Towers-of-Hanoi b/Lang/PureBasic/Towers-of-Hanoi new file mode 120000 index 0000000000..74e7b0c8b1 --- /dev/null +++ b/Lang/PureBasic/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Trabb-Pardo-Knuth-algorithm b/Lang/PureBasic/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..910ff88e79 --- /dev/null +++ b/Lang/PureBasic/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Tree-traversal b/Lang/PureBasic/Tree-traversal new file mode 120000 index 0000000000..d218b1040a --- /dev/null +++ b/Lang/PureBasic/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Trigonometric-functions b/Lang/PureBasic/Trigonometric-functions new file mode 120000 index 0000000000..96d695a2c8 --- /dev/null +++ b/Lang/PureBasic/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Truncatable-primes b/Lang/PureBasic/Truncatable-primes new file mode 120000 index 0000000000..0561572316 --- /dev/null +++ b/Lang/PureBasic/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Truncate-a-file b/Lang/PureBasic/Truncate-a-file new file mode 120000 index 0000000000..2ccb6fa693 --- /dev/null +++ b/Lang/PureBasic/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/URL-decoding b/Lang/PureBasic/URL-decoding new file mode 120000 index 0000000000..e70784489f --- /dev/null +++ b/Lang/PureBasic/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/URL-encoding b/Lang/PureBasic/URL-encoding new file mode 120000 index 0000000000..934369e800 --- /dev/null +++ b/Lang/PureBasic/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Unbias-a-random-generator b/Lang/PureBasic/Unbias-a-random-generator new file mode 120000 index 0000000000..a8e7c39e3d --- /dev/null +++ b/Lang/PureBasic/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Undefined-values b/Lang/PureBasic/Undefined-values new file mode 120000 index 0000000000..d287bf97a2 --- /dev/null +++ b/Lang/PureBasic/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/User-input-Graphical b/Lang/PureBasic/User-input-Graphical new file mode 120000 index 0000000000..a2e8a6411c --- /dev/null +++ b/Lang/PureBasic/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/User-input-Text b/Lang/PureBasic/User-input-Text new file mode 120000 index 0000000000..c4edbdcf74 --- /dev/null +++ b/Lang/PureBasic/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Variable-size-Get b/Lang/PureBasic/Variable-size-Get new file mode 120000 index 0000000000..ca958e1b12 --- /dev/null +++ b/Lang/PureBasic/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Variables b/Lang/PureBasic/Variables new file mode 120000 index 0000000000..387c54158a --- /dev/null +++ b/Lang/PureBasic/Variables @@ -0,0 +1 @@ +../../Task/Variables/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Vector-products b/Lang/PureBasic/Vector-products new file mode 120000 index 0000000000..b10a6dec45 --- /dev/null +++ b/Lang/PureBasic/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Verify-distribution-uniformity-Naive b/Lang/PureBasic/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..c1f5991a0f --- /dev/null +++ b/Lang/PureBasic/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Vigen-re-cipher b/Lang/PureBasic/Vigen-re-cipher new file mode 120000 index 0000000000..e5e312cf9a --- /dev/null +++ b/Lang/PureBasic/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Voronoi-diagram b/Lang/PureBasic/Voronoi-diagram new file mode 120000 index 0000000000..bd61bfc1cd --- /dev/null +++ b/Lang/PureBasic/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Walk-a-directory-Non-recursively b/Lang/PureBasic/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..e73f515da6 --- /dev/null +++ b/Lang/PureBasic/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Walk-a-directory-Recursively b/Lang/PureBasic/Walk-a-directory-Recursively new file mode 120000 index 0000000000..30eb1dcbfd --- /dev/null +++ b/Lang/PureBasic/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Web-scraping b/Lang/PureBasic/Web-scraping new file mode 120000 index 0000000000..56dff6528c --- /dev/null +++ b/Lang/PureBasic/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Window-creation b/Lang/PureBasic/Window-creation new file mode 120000 index 0000000000..bf73b111d9 --- /dev/null +++ b/Lang/PureBasic/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Window-management b/Lang/PureBasic/Window-management new file mode 120000 index 0000000000..5c5cc280da --- /dev/null +++ b/Lang/PureBasic/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Wireworld b/Lang/PureBasic/Wireworld new file mode 120000 index 0000000000..822dc834cf --- /dev/null +++ b/Lang/PureBasic/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Write-float-arrays-to-a-text-file b/Lang/PureBasic/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..9cb7494b2b --- /dev/null +++ b/Lang/PureBasic/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Write-to-Windows-event-log b/Lang/PureBasic/Write-to-Windows-event-log new file mode 120000 index 0000000000..9f0363b31e --- /dev/null +++ b/Lang/PureBasic/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/XML-Input b/Lang/PureBasic/XML-Input new file mode 120000 index 0000000000..72c0f1b62d --- /dev/null +++ b/Lang/PureBasic/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/XML-Output b/Lang/PureBasic/XML-Output new file mode 120000 index 0000000000..759dccedbf --- /dev/null +++ b/Lang/PureBasic/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Xiaolin-Wus-line-algorithm b/Lang/PureBasic/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..9b40313026 --- /dev/null +++ b/Lang/PureBasic/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Yin-and-yang b/Lang/PureBasic/Yin-and-yang new file mode 120000 index 0000000000..711dccd352 --- /dev/null +++ b/Lang/PureBasic/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Zig-zag-matrix b/Lang/PureBasic/Zig-zag-matrix new file mode 120000 index 0000000000..e30767960e --- /dev/null +++ b/Lang/PureBasic/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/PureBasic \ No newline at end of file diff --git a/Lang/Python/SHA-1 b/Lang/Python/SHA-1 new file mode 120000 index 0000000000..b56d81f299 --- /dev/null +++ b/Lang/Python/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Python \ No newline at end of file diff --git a/Lang/Python/SHA-256 b/Lang/Python/SHA-256 new file mode 120000 index 0000000000..b1c3fa637b --- /dev/null +++ b/Lang/Python/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Python \ No newline at end of file diff --git a/Lang/Python/SOAP b/Lang/Python/SOAP new file mode 120000 index 0000000000..cc17ed050c --- /dev/null +++ b/Lang/Python/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Python \ No newline at end of file diff --git a/Lang/Python/SQL-based-authentication b/Lang/Python/SQL-based-authentication new file mode 120000 index 0000000000..82d9a85f55 --- /dev/null +++ b/Lang/Python/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Python \ No newline at end of file diff --git a/Lang/Python/Set-puzzle b/Lang/Python/Set-puzzle new file mode 120000 index 0000000000..57748e07a7 --- /dev/null +++ b/Lang/Python/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Seven-sided-dice-from-five-sided-dice b/Lang/Python/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..6cc3215974 --- /dev/null +++ b/Lang/Python/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Python \ No newline at end of file diff --git a/Lang/Python/Shell-one-liner b/Lang/Python/Shell-one-liner new file mode 120000 index 0000000000..0388fdcccf --- /dev/null +++ b/Lang/Python/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Python \ No newline at end of file diff --git a/Lang/Python/Short-circuit-evaluation b/Lang/Python/Short-circuit-evaluation new file mode 120000 index 0000000000..90a41da45b --- /dev/null +++ b/Lang/Python/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Python \ No newline at end of file diff --git a/Lang/Python/Show-the-epoch b/Lang/Python/Show-the-epoch new file mode 120000 index 0000000000..8652f13027 --- /dev/null +++ b/Lang/Python/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Python \ No newline at end of file diff --git a/Lang/Python/Sierpinski-carpet b/Lang/Python/Sierpinski-carpet new file mode 120000 index 0000000000..60850c79a4 --- /dev/null +++ b/Lang/Python/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Python \ No newline at end of file diff --git a/Lang/Python/Sierpinski-triangle b/Lang/Python/Sierpinski-triangle new file mode 120000 index 0000000000..f072ae227e --- /dev/null +++ b/Lang/Python/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Python \ No newline at end of file diff --git a/Lang/Python/Sierpinski-triangle-Graphical b/Lang/Python/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..93ccabfb85 --- /dev/null +++ b/Lang/Python/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Python \ No newline at end of file diff --git a/Lang/Python/Sieve-of-Eratosthenes b/Lang/Python/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9255ffa620 --- /dev/null +++ b/Lang/Python/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Python \ No newline at end of file diff --git a/Lang/Python/Simple-database b/Lang/Python/Simple-database new file mode 120000 index 0000000000..9f93a029b2 --- /dev/null +++ b/Lang/Python/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Python \ No newline at end of file diff --git a/Lang/Python/Simple-windowed-application b/Lang/Python/Simple-windowed-application new file mode 120000 index 0000000000..35b779b90c --- /dev/null +++ b/Lang/Python/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Python \ No newline at end of file diff --git a/Lang/Python/Singleton b/Lang/Python/Singleton new file mode 120000 index 0000000000..6be15a99c7 --- /dev/null +++ b/Lang/Python/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Python \ No newline at end of file diff --git a/Lang/Python/Singly-linked-list-Element-definition b/Lang/Python/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..5f49c4382a --- /dev/null +++ b/Lang/Python/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Python \ No newline at end of file diff --git a/Lang/Python/Singly-linked-list-Element-insertion b/Lang/Python/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..75b4a645ae --- /dev/null +++ b/Lang/Python/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Python \ No newline at end of file diff --git a/Lang/Python/Singly-linked-list-Traversal b/Lang/Python/Singly-linked-list-Traversal new file mode 120000 index 0000000000..32eeafb980 --- /dev/null +++ b/Lang/Python/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Python \ No newline at end of file diff --git a/Lang/Python/Sleep b/Lang/Python/Sleep new file mode 120000 index 0000000000..aa17a36817 --- /dev/null +++ b/Lang/Python/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Python \ No newline at end of file diff --git a/Lang/Python/Sockets b/Lang/Python/Sockets new file mode 120000 index 0000000000..6cc264f09e --- /dev/null +++ b/Lang/Python/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Python \ No newline at end of file diff --git a/Lang/Python/Sokoban b/Lang/Python/Sokoban new file mode 120000 index 0000000000..b2c4fe2637 --- /dev/null +++ b/Lang/Python/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Python \ No newline at end of file diff --git a/Lang/Python/Solve-a-Hidato-puzzle b/Lang/Python/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..c11536eb46 --- /dev/null +++ b/Lang/Python/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Sort-an-array-of-composite-structures b/Lang/Python/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..856b7122c8 --- /dev/null +++ b/Lang/Python/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Python \ No newline at end of file diff --git a/Lang/Python/Sort-an-integer-array b/Lang/Python/Sort-an-integer-array new file mode 120000 index 0000000000..4941fbd755 --- /dev/null +++ b/Lang/Python/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Python \ No newline at end of file diff --git a/Lang/Python/Sort-disjoint-sublist b/Lang/Python/Sort-disjoint-sublist new file mode 120000 index 0000000000..f4c4309e0c --- /dev/null +++ b/Lang/Python/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Python \ No newline at end of file diff --git a/Lang/Python/Sort-using-a-custom-comparator b/Lang/Python/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..27415ea798 --- /dev/null +++ b/Lang/Python/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Bead-sort b/Lang/Python/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..63aa5b241a --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Bogosort b/Lang/Python/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..6d9fe37f1c --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Bubble-sort b/Lang/Python/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ed0eff8c0d --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Cocktail-sort b/Lang/Python/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..72b49ed5d6 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Comb-sort b/Lang/Python/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..5fb060d9f1 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Counting-sort b/Lang/Python/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..f0da2bb0e8 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Gnome-sort b/Lang/Python/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..6b1dc8af6a --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Heapsort b/Lang/Python/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..98a8a3bb6d --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Insertion-sort b/Lang/Python/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..8ad2e757e6 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Merge-sort b/Lang/Python/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..74101bccf0 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Pancake-sort b/Lang/Python/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..d89d7c300f --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Permutation-sort b/Lang/Python/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..1b7b529392 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Quicksort b/Lang/Python/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..22eb04f20d --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Radix-sort b/Lang/Python/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..930ab0344d --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Selection-sort b/Lang/Python/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..879682bbbf --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Shell-sort b/Lang/Python/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..33bd38f085 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Sleep-sort b/Lang/Python/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..145aee52c2 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Stooge-sort b/Lang/Python/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..cadf3928af --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-algorithms-Strand-sort b/Lang/Python/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..fae3eddb80 --- /dev/null +++ b/Lang/Python/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Python \ No newline at end of file diff --git a/Lang/Python/Soundex b/Lang/Python/Soundex new file mode 120000 index 0000000000..7c2a6446b8 --- /dev/null +++ b/Lang/Python/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Python \ No newline at end of file diff --git a/Lang/Python/Special-variables b/Lang/Python/Special-variables new file mode 120000 index 0000000000..a526e9653d --- /dev/null +++ b/Lang/Python/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Python \ No newline at end of file diff --git a/Lang/Python/Spiral-matrix b/Lang/Python/Spiral-matrix new file mode 120000 index 0000000000..3b0c53aa0b --- /dev/null +++ b/Lang/Python/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Python \ No newline at end of file diff --git a/Lang/Python/Stable-marriage-problem b/Lang/Python/Stable-marriage-problem new file mode 120000 index 0000000000..b3f9aed047 --- /dev/null +++ b/Lang/Python/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Python \ No newline at end of file diff --git a/Lang/Python/Stack b/Lang/Python/Stack new file mode 120000 index 0000000000..716be05e79 --- /dev/null +++ b/Lang/Python/Stack @@ -0,0 +1 @@ +../../Task/Stack/Python \ No newline at end of file diff --git a/Lang/Python/Stack-traces b/Lang/Python/Stack-traces new file mode 120000 index 0000000000..be3f4bd33f --- /dev/null +++ b/Lang/Python/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Python \ No newline at end of file diff --git a/Lang/Python/Stair-climbing-puzzle b/Lang/Python/Stair-climbing-puzzle new file mode 120000 index 0000000000..5613496ec0 --- /dev/null +++ b/Lang/Python/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Standard-deviation b/Lang/Python/Standard-deviation new file mode 120000 index 0000000000..468a855a6b --- /dev/null +++ b/Lang/Python/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Python \ No newline at end of file diff --git a/Lang/Python/Stem-and-leaf-plot b/Lang/Python/Stem-and-leaf-plot new file mode 120000 index 0000000000..73008451f0 --- /dev/null +++ b/Lang/Python/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Python \ No newline at end of file diff --git a/Lang/Python/String-case b/Lang/Python/String-case new file mode 120000 index 0000000000..2c3e1e09f1 --- /dev/null +++ b/Lang/Python/String-case @@ -0,0 +1 @@ +../../Task/String-case/Python \ No newline at end of file diff --git a/Lang/Python/String-comparison b/Lang/Python/String-comparison new file mode 120000 index 0000000000..1f0b00ccaa --- /dev/null +++ b/Lang/Python/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Python \ No newline at end of file diff --git a/Lang/Python/String-concatenation b/Lang/Python/String-concatenation new file mode 120000 index 0000000000..a6e300e93c --- /dev/null +++ b/Lang/Python/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Python \ No newline at end of file diff --git a/Lang/Python/String-interpolation--included- b/Lang/Python/String-interpolation--included- new file mode 120000 index 0000000000..d3ee1df42f --- /dev/null +++ b/Lang/Python/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Python \ No newline at end of file diff --git a/Lang/Python/String-length b/Lang/Python/String-length new file mode 120000 index 0000000000..cdea4ae8fc --- /dev/null +++ b/Lang/Python/String-length @@ -0,0 +1 @@ +../../Task/String-length/Python \ No newline at end of file diff --git a/Lang/Python/Strip-a-set-of-characters-from-a-string b/Lang/Python/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..9bec799946 --- /dev/null +++ b/Lang/Python/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Python \ No newline at end of file diff --git a/Lang/Python/Strip-block-comments b/Lang/Python/Strip-block-comments new file mode 120000 index 0000000000..24bd266674 --- /dev/null +++ b/Lang/Python/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Python \ No newline at end of file diff --git a/Lang/Python/Strip-comments-from-a-string b/Lang/Python/Strip-comments-from-a-string new file mode 120000 index 0000000000..e88894c183 --- /dev/null +++ b/Lang/Python/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Python \ No newline at end of file diff --git a/Lang/Python/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Python/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..eab712596d --- /dev/null +++ b/Lang/Python/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Python \ No newline at end of file diff --git a/Lang/Python/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Python/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..06d9d0fefb --- /dev/null +++ b/Lang/Python/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Python \ No newline at end of file diff --git a/Lang/Python/Substring b/Lang/Python/Substring new file mode 120000 index 0000000000..447a209232 --- /dev/null +++ b/Lang/Python/Substring @@ -0,0 +1 @@ +../../Task/Substring/Python \ No newline at end of file diff --git a/Lang/Python/Substring-Top-and-tail b/Lang/Python/Substring-Top-and-tail new file mode 120000 index 0000000000..4fee6d7d0b --- /dev/null +++ b/Lang/Python/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Python \ No newline at end of file diff --git a/Lang/Python/Subtractive-generator b/Lang/Python/Subtractive-generator new file mode 120000 index 0000000000..75a038bdda --- /dev/null +++ b/Lang/Python/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Python \ No newline at end of file diff --git a/Lang/Python/Sudoku b/Lang/Python/Sudoku new file mode 120000 index 0000000000..b0976416c0 --- /dev/null +++ b/Lang/Python/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Python \ No newline at end of file diff --git a/Lang/Python/Sum-and-product-of-an-array b/Lang/Python/Sum-and-product-of-an-array new file mode 120000 index 0000000000..ec6a8c211c --- /dev/null +++ b/Lang/Python/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Python \ No newline at end of file diff --git a/Lang/Python/Sum-digits-of-an-integer b/Lang/Python/Sum-digits-of-an-integer new file mode 120000 index 0000000000..afd8eeb964 --- /dev/null +++ b/Lang/Python/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Python \ No newline at end of file diff --git a/Lang/Python/Sum-of-a-series b/Lang/Python/Sum-of-a-series new file mode 120000 index 0000000000..86afcca32c --- /dev/null +++ b/Lang/Python/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Python \ No newline at end of file diff --git a/Lang/Python/Sum-of-squares b/Lang/Python/Sum-of-squares new file mode 120000 index 0000000000..99b08c9a8a --- /dev/null +++ b/Lang/Python/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Python \ No newline at end of file diff --git a/Lang/Python/Sutherland-Hodgman-polygon-clipping b/Lang/Python/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..08efed2a68 --- /dev/null +++ b/Lang/Python/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Python \ No newline at end of file diff --git a/Lang/Python/Symmetric-difference b/Lang/Python/Symmetric-difference new file mode 120000 index 0000000000..ce2a2dee27 --- /dev/null +++ b/Lang/Python/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Python \ No newline at end of file diff --git a/Lang/Python/Synchronous-concurrency b/Lang/Python/Synchronous-concurrency new file mode 120000 index 0000000000..b995ce3a77 --- /dev/null +++ b/Lang/Python/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Python \ No newline at end of file diff --git a/Lang/Python/System-time b/Lang/Python/System-time new file mode 120000 index 0000000000..a5fa10e420 --- /dev/null +++ b/Lang/Python/System-time @@ -0,0 +1 @@ +../../Task/System-time/Python \ No newline at end of file diff --git a/Lang/Python/Table-creation-Postal-addresses b/Lang/Python/Table-creation-Postal-addresses new file mode 120000 index 0000000000..53651211e8 --- /dev/null +++ b/Lang/Python/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Python \ No newline at end of file diff --git a/Lang/Python/Take-notes-on-the-command-line b/Lang/Python/Take-notes-on-the-command-line new file mode 120000 index 0000000000..1b93e0c80b --- /dev/null +++ b/Lang/Python/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Python \ No newline at end of file diff --git a/Lang/Python/Temperature-conversion b/Lang/Python/Temperature-conversion new file mode 120000 index 0000000000..41229e33fe --- /dev/null +++ b/Lang/Python/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Clear-the-screen b/Lang/Python/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..646fd26673 --- /dev/null +++ b/Lang/Python/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Coloured-text b/Lang/Python/Terminal-control-Coloured-text new file mode 120000 index 0000000000..a5972ae5a1 --- /dev/null +++ b/Lang/Python/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Cursor-positioning b/Lang/Python/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..38590f49b7 --- /dev/null +++ b/Lang/Python/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Dimensions b/Lang/Python/Terminal-control-Dimensions new file mode 120000 index 0000000000..5bef670420 --- /dev/null +++ b/Lang/Python/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Display-an-extended-character b/Lang/Python/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..7ff7d8ce84 --- /dev/null +++ b/Lang/Python/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Inverse-video b/Lang/Python/Terminal-control-Inverse-video new file mode 120000 index 0000000000..131b6d00c1 --- /dev/null +++ b/Lang/Python/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Preserve-screen b/Lang/Python/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..4cdb2f5375 --- /dev/null +++ b/Lang/Python/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Ringing-the-terminal-bell b/Lang/Python/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b95becf507 --- /dev/null +++ b/Lang/Python/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Python \ No newline at end of file diff --git a/Lang/Python/Ternary-logic b/Lang/Python/Ternary-logic new file mode 120000 index 0000000000..53afd6761b --- /dev/null +++ b/Lang/Python/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Python \ No newline at end of file diff --git a/Lang/Python/Test-a-function b/Lang/Python/Test-a-function new file mode 120000 index 0000000000..cb9620e375 --- /dev/null +++ b/Lang/Python/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Python \ No newline at end of file diff --git a/Lang/Python/Text-processing-1 b/Lang/Python/Text-processing-1 new file mode 120000 index 0000000000..87d1830342 --- /dev/null +++ b/Lang/Python/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Python \ No newline at end of file diff --git a/Lang/Python/Text-processing-2 b/Lang/Python/Text-processing-2 new file mode 120000 index 0000000000..03488d785e --- /dev/null +++ b/Lang/Python/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Python \ No newline at end of file diff --git a/Lang/Python/Text-processing-Max-licenses-in-use b/Lang/Python/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..0b9854fa09 --- /dev/null +++ b/Lang/Python/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Python \ No newline at end of file diff --git a/Lang/Python/Tic-tac-toe b/Lang/Python/Tic-tac-toe new file mode 120000 index 0000000000..0c186571b0 --- /dev/null +++ b/Lang/Python/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Python \ No newline at end of file diff --git a/Lang/Python/Time-a-function b/Lang/Python/Time-a-function new file mode 120000 index 0000000000..1528229e37 --- /dev/null +++ b/Lang/Python/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Python \ No newline at end of file diff --git a/Lang/Python/Tokenize-a-string b/Lang/Python/Tokenize-a-string new file mode 120000 index 0000000000..fc90728e7f --- /dev/null +++ b/Lang/Python/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Python \ No newline at end of file diff --git a/Lang/Python/Top-rank-per-group b/Lang/Python/Top-rank-per-group new file mode 120000 index 0000000000..e4d6ff8a32 --- /dev/null +++ b/Lang/Python/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Python \ No newline at end of file diff --git a/Lang/Python/Topological-sort b/Lang/Python/Topological-sort new file mode 120000 index 0000000000..e2e96c3b93 --- /dev/null +++ b/Lang/Python/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Python \ No newline at end of file diff --git a/Lang/Python/Topswops b/Lang/Python/Topswops new file mode 120000 index 0000000000..014481faf1 --- /dev/null +++ b/Lang/Python/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Python \ No newline at end of file diff --git a/Lang/Python/Towers-of-Hanoi b/Lang/Python/Towers-of-Hanoi new file mode 120000 index 0000000000..d5f9c34d02 --- /dev/null +++ b/Lang/Python/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Python \ No newline at end of file diff --git a/Lang/Python/Trabb-Pardo-Knuth-algorithm b/Lang/Python/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..342bb3d9ac --- /dev/null +++ b/Lang/Python/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Python \ No newline at end of file diff --git a/Lang/Python/Tree-traversal b/Lang/Python/Tree-traversal new file mode 120000 index 0000000000..4cb6caac83 --- /dev/null +++ b/Lang/Python/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Python \ No newline at end of file diff --git a/Lang/Python/Trigonometric-functions b/Lang/Python/Trigonometric-functions new file mode 120000 index 0000000000..6ace182d23 --- /dev/null +++ b/Lang/Python/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Python \ No newline at end of file diff --git a/Lang/Python/Truncate-a-file b/Lang/Python/Truncate-a-file new file mode 120000 index 0000000000..ae1a63f5f8 --- /dev/null +++ b/Lang/Python/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Python \ No newline at end of file diff --git a/Lang/Python/Twelve-statements b/Lang/Python/Twelve-statements new file mode 120000 index 0000000000..eb12158775 --- /dev/null +++ b/Lang/Python/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Python \ No newline at end of file diff --git a/Lang/Python/URL-decoding b/Lang/Python/URL-decoding new file mode 120000 index 0000000000..eaa4f17b1f --- /dev/null +++ b/Lang/Python/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Python \ No newline at end of file diff --git a/Lang/Python/URL-encoding b/Lang/Python/URL-encoding new file mode 120000 index 0000000000..9973832c72 --- /dev/null +++ b/Lang/Python/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Python \ No newline at end of file diff --git a/Lang/Python/Unbias-a-random-generator b/Lang/Python/Unbias-a-random-generator new file mode 120000 index 0000000000..543d8fdc87 --- /dev/null +++ b/Lang/Python/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Python \ No newline at end of file diff --git a/Lang/Python/Undefined-values b/Lang/Python/Undefined-values new file mode 120000 index 0000000000..b17cbb5905 --- /dev/null +++ b/Lang/Python/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Python \ No newline at end of file diff --git a/Lang/Python/Unicode-strings b/Lang/Python/Unicode-strings new file mode 120000 index 0000000000..ac8d7e9e7b --- /dev/null +++ b/Lang/Python/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Python \ No newline at end of file diff --git a/Lang/Python/Unicode-variable-names b/Lang/Python/Unicode-variable-names new file mode 120000 index 0000000000..024c8c58d1 --- /dev/null +++ b/Lang/Python/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Python \ No newline at end of file diff --git a/Lang/Python/Update-a-configuration-file b/Lang/Python/Update-a-configuration-file new file mode 120000 index 0000000000..70cb193d4a --- /dev/null +++ b/Lang/Python/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Python \ No newline at end of file diff --git a/Lang/Python/Use-another-language-to-call-a-function b/Lang/Python/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..bf73040654 --- /dev/null +++ b/Lang/Python/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Python \ No newline at end of file diff --git a/Lang/Python/User-input-Graphical b/Lang/Python/User-input-Graphical new file mode 120000 index 0000000000..94f4b32c06 --- /dev/null +++ b/Lang/Python/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Python \ No newline at end of file diff --git a/Lang/Python/User-input-Text b/Lang/Python/User-input-Text new file mode 120000 index 0000000000..91f38f77a2 --- /dev/null +++ b/Lang/Python/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Python \ No newline at end of file diff --git a/Lang/Python/Vampire-number b/Lang/Python/Vampire-number new file mode 120000 index 0000000000..07b82ff9f1 --- /dev/null +++ b/Lang/Python/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Python \ No newline at end of file diff --git a/Lang/Python/Van-der-Corput-sequence b/Lang/Python/Van-der-Corput-sequence new file mode 120000 index 0000000000..1d3c24523e --- /dev/null +++ b/Lang/Python/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Python \ No newline at end of file diff --git a/Lang/Python/Variable-length-quantity b/Lang/Python/Variable-length-quantity new file mode 120000 index 0000000000..072810a9bf --- /dev/null +++ b/Lang/Python/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Python \ No newline at end of file diff --git a/Lang/Python/Variable-size-Get b/Lang/Python/Variable-size-Get new file mode 120000 index 0000000000..39de1490b2 --- /dev/null +++ b/Lang/Python/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Python \ No newline at end of file diff --git a/Lang/Python/Variadic-function b/Lang/Python/Variadic-function new file mode 120000 index 0000000000..632e912a9d --- /dev/null +++ b/Lang/Python/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Python \ No newline at end of file diff --git a/Lang/Python/Vector-products b/Lang/Python/Vector-products new file mode 120000 index 0000000000..88227413ed --- /dev/null +++ b/Lang/Python/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Python \ No newline at end of file diff --git a/Lang/Python/Verify-distribution-uniformity-Chi-squared-test b/Lang/Python/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..03aaf6068d --- /dev/null +++ b/Lang/Python/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Python \ No newline at end of file diff --git a/Lang/Python/Verify-distribution-uniformity-Naive b/Lang/Python/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..7e884f201a --- /dev/null +++ b/Lang/Python/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Python \ No newline at end of file diff --git a/Lang/Python/Vigen-re-cipher b/Lang/Python/Vigen-re-cipher new file mode 120000 index 0000000000..2c12766c14 --- /dev/null +++ b/Lang/Python/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Python \ No newline at end of file diff --git a/Lang/Python/Vigen-re-cipher-Cryptanalysis b/Lang/Python/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..64c8352a98 --- /dev/null +++ b/Lang/Python/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Python \ No newline at end of file diff --git a/Lang/Python/Visualize-a-tree b/Lang/Python/Visualize-a-tree new file mode 120000 index 0000000000..b56bae69a7 --- /dev/null +++ b/Lang/Python/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Python \ No newline at end of file diff --git a/Lang/Python/Voronoi-diagram b/Lang/Python/Voronoi-diagram new file mode 120000 index 0000000000..d82bb68c54 --- /dev/null +++ b/Lang/Python/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Python \ No newline at end of file diff --git a/Lang/Python/Walk-a-directory-Non-recursively b/Lang/Python/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..b0940159d8 --- /dev/null +++ b/Lang/Python/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Python \ No newline at end of file diff --git a/Lang/Python/Walk-a-directory-Recursively b/Lang/Python/Walk-a-directory-Recursively new file mode 120000 index 0000000000..9ad69588c3 --- /dev/null +++ b/Lang/Python/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Python \ No newline at end of file diff --git a/Lang/Python/Web-scraping b/Lang/Python/Web-scraping new file mode 120000 index 0000000000..adf5f21b59 --- /dev/null +++ b/Lang/Python/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Python \ No newline at end of file diff --git a/Lang/Python/Window-creation b/Lang/Python/Window-creation new file mode 120000 index 0000000000..7b0b449090 --- /dev/null +++ b/Lang/Python/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Python \ No newline at end of file diff --git a/Lang/Python/Window-creation-X11 b/Lang/Python/Window-creation-X11 new file mode 120000 index 0000000000..deed3718e1 --- /dev/null +++ b/Lang/Python/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Python \ No newline at end of file diff --git a/Lang/Python/Window-management b/Lang/Python/Window-management new file mode 120000 index 0000000000..50ab1c1107 --- /dev/null +++ b/Lang/Python/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Python \ No newline at end of file diff --git a/Lang/Python/Wireworld b/Lang/Python/Wireworld new file mode 120000 index 0000000000..111a32b450 --- /dev/null +++ b/Lang/Python/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Python \ No newline at end of file diff --git a/Lang/Python/Write-float-arrays-to-a-text-file b/Lang/Python/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d3c1a22caf --- /dev/null +++ b/Lang/Python/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Python \ No newline at end of file diff --git a/Lang/Python/Write-language-name-in-3D-ASCII b/Lang/Python/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..c5b02d39ed --- /dev/null +++ b/Lang/Python/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Python \ No newline at end of file diff --git a/Lang/Python/Write-to-Windows-event-log b/Lang/Python/Write-to-Windows-event-log new file mode 120000 index 0000000000..12fd3c1be0 --- /dev/null +++ b/Lang/Python/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Python \ No newline at end of file diff --git a/Lang/Python/XML-DOM-serialization b/Lang/Python/XML-DOM-serialization new file mode 120000 index 0000000000..a5bff6e176 --- /dev/null +++ b/Lang/Python/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Python \ No newline at end of file diff --git a/Lang/Python/XML-Input b/Lang/Python/XML-Input new file mode 120000 index 0000000000..f10bac16f8 --- /dev/null +++ b/Lang/Python/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Python \ No newline at end of file diff --git a/Lang/Python/XML-Output b/Lang/Python/XML-Output new file mode 120000 index 0000000000..baea1a3bc7 --- /dev/null +++ b/Lang/Python/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Python \ No newline at end of file diff --git a/Lang/Python/XML-XPath b/Lang/Python/XML-XPath new file mode 120000 index 0000000000..773b8b2198 --- /dev/null +++ b/Lang/Python/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Python \ No newline at end of file diff --git a/Lang/Python/Xiaolin-Wus-line-algorithm b/Lang/Python/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..28cdbdd465 --- /dev/null +++ b/Lang/Python/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Python \ No newline at end of file diff --git a/Lang/Python/Y-combinator b/Lang/Python/Y-combinator new file mode 120000 index 0000000000..2810fc9840 --- /dev/null +++ b/Lang/Python/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Python \ No newline at end of file diff --git a/Lang/Python/Yahoo--search-interface b/Lang/Python/Yahoo--search-interface new file mode 120000 index 0000000000..6f71246c7b --- /dev/null +++ b/Lang/Python/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Python \ No newline at end of file diff --git a/Lang/Python/Yin-and-yang b/Lang/Python/Yin-and-yang new file mode 120000 index 0000000000..af0d63157d --- /dev/null +++ b/Lang/Python/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Python \ No newline at end of file diff --git a/Lang/Python/Zebra-puzzle b/Lang/Python/Zebra-puzzle new file mode 120000 index 0000000000..8118fbcc56 --- /dev/null +++ b/Lang/Python/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Python \ No newline at end of file diff --git a/Lang/Python/Zeckendorf-number-representation b/Lang/Python/Zeckendorf-number-representation new file mode 120000 index 0000000000..b3dfee512b --- /dev/null +++ b/Lang/Python/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Python \ No newline at end of file diff --git a/Lang/Python/Zig-zag-matrix b/Lang/Python/Zig-zag-matrix new file mode 120000 index 0000000000..d9129dafd5 --- /dev/null +++ b/Lang/Python/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Python \ No newline at end of file diff --git a/Lang/Q/System-time b/Lang/Q/System-time new file mode 120000 index 0000000000..826c174487 --- /dev/null +++ b/Lang/Q/System-time @@ -0,0 +1 @@ +../../Task/System-time/Q \ No newline at end of file diff --git a/Lang/Qi/Sorting-algorithms-Bogosort b/Lang/Qi/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2de3a21ac2 --- /dev/null +++ b/Lang/Qi/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Qi \ No newline at end of file diff --git a/Lang/Qi/Sorting-algorithms-Bubble-sort b/Lang/Qi/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..bb78463007 --- /dev/null +++ b/Lang/Qi/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Qi \ No newline at end of file diff --git a/Lang/Qi/Sorting-algorithms-Insertion-sort b/Lang/Qi/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..877c87a5fc --- /dev/null +++ b/Lang/Qi/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Qi \ No newline at end of file diff --git a/Lang/Qi/Sorting-algorithms-Quicksort b/Lang/Qi/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..708e7fa65f --- /dev/null +++ b/Lang/Qi/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Qi \ No newline at end of file diff --git a/Lang/Qi/Sorting-algorithms-Selection-sort b/Lang/Qi/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..e6c72546c7 --- /dev/null +++ b/Lang/Qi/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Qi \ No newline at end of file diff --git a/Lang/Qi/Tree-traversal b/Lang/Qi/Tree-traversal new file mode 120000 index 0000000000..21c7665a86 --- /dev/null +++ b/Lang/Qi/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Qi \ No newline at end of file diff --git a/Lang/Qi/Variadic-function b/Lang/Qi/Variadic-function new file mode 120000 index 0000000000..a1026b3b47 --- /dev/null +++ b/Lang/Qi/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Qi \ No newline at end of file diff --git a/Lang/Qi/Zig-zag-matrix b/Lang/Qi/Zig-zag-matrix new file mode 120000 index 0000000000..c01b285516 --- /dev/null +++ b/Lang/Qi/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Qi \ No newline at end of file diff --git a/Lang/R/Seven-sided-dice-from-five-sided-dice b/Lang/R/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..bdf786c353 --- /dev/null +++ b/Lang/R/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/R \ No newline at end of file diff --git a/Lang/R/Shell-one-liner b/Lang/R/Shell-one-liner new file mode 120000 index 0000000000..fd82457918 --- /dev/null +++ b/Lang/R/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/R \ No newline at end of file diff --git a/Lang/R/Short-circuit-evaluation b/Lang/R/Short-circuit-evaluation new file mode 120000 index 0000000000..d8447e9953 --- /dev/null +++ b/Lang/R/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/R \ No newline at end of file diff --git a/Lang/R/Show-the-epoch b/Lang/R/Show-the-epoch new file mode 120000 index 0000000000..a2b1a40c2a --- /dev/null +++ b/Lang/R/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/R \ No newline at end of file diff --git a/Lang/R/Sierpinski-triangle b/Lang/R/Sierpinski-triangle new file mode 120000 index 0000000000..4299225174 --- /dev/null +++ b/Lang/R/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/R \ No newline at end of file diff --git a/Lang/R/Sieve-of-Eratosthenes b/Lang/R/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..5e8cc5eadd --- /dev/null +++ b/Lang/R/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/R \ No newline at end of file diff --git a/Lang/R/Simple-windowed-application b/Lang/R/Simple-windowed-application new file mode 120000 index 0000000000..ac9467a7ba --- /dev/null +++ b/Lang/R/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/R \ No newline at end of file diff --git a/Lang/R/Sleep b/Lang/R/Sleep new file mode 120000 index 0000000000..c59642ad06 --- /dev/null +++ b/Lang/R/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/R \ No newline at end of file diff --git a/Lang/R/Sort-an-array-of-composite-structures b/Lang/R/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..c4b6f2e955 --- /dev/null +++ b/Lang/R/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/R \ No newline at end of file diff --git a/Lang/R/Sort-an-integer-array b/Lang/R/Sort-an-integer-array new file mode 120000 index 0000000000..c8b0a51be8 --- /dev/null +++ b/Lang/R/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/R \ No newline at end of file diff --git a/Lang/R/Sort-disjoint-sublist b/Lang/R/Sort-disjoint-sublist new file mode 120000 index 0000000000..864703ca57 --- /dev/null +++ b/Lang/R/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/R \ No newline at end of file diff --git a/Lang/R/Sort-stability b/Lang/R/Sort-stability new file mode 120000 index 0000000000..5ad52e00e2 --- /dev/null +++ b/Lang/R/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Bogosort b/Lang/R/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..1ee42d3509 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Bubble-sort b/Lang/R/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..500a4e7b11 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Cocktail-sort b/Lang/R/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..0a9e29d18d --- /dev/null +++ b/Lang/R/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Counting-sort b/Lang/R/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..9e2e859fb4 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Gnome-sort b/Lang/R/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..16f128cabe --- /dev/null +++ b/Lang/R/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Insertion-sort b/Lang/R/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4b89ec2b9e --- /dev/null +++ b/Lang/R/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Merge-sort b/Lang/R/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..a2638f7e5b --- /dev/null +++ b/Lang/R/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Permutation-sort b/Lang/R/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..30158ac8a7 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Quicksort b/Lang/R/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..18eae6e871 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Selection-sort b/Lang/R/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..30904cc588 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/R \ No newline at end of file diff --git a/Lang/R/Spiral-matrix b/Lang/R/Spiral-matrix new file mode 120000 index 0000000000..45c6736270 --- /dev/null +++ b/Lang/R/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/R \ No newline at end of file diff --git a/Lang/R/Stack b/Lang/R/Stack new file mode 120000 index 0000000000..0322800e30 --- /dev/null +++ b/Lang/R/Stack @@ -0,0 +1 @@ +../../Task/Stack/R \ No newline at end of file diff --git a/Lang/R/Stack-traces b/Lang/R/Stack-traces new file mode 120000 index 0000000000..1c836d2920 --- /dev/null +++ b/Lang/R/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/R \ No newline at end of file diff --git a/Lang/R/Stair-climbing-puzzle b/Lang/R/Stair-climbing-puzzle new file mode 120000 index 0000000000..543f12c0b6 --- /dev/null +++ b/Lang/R/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/R \ No newline at end of file diff --git a/Lang/R/Standard-deviation b/Lang/R/Standard-deviation new file mode 120000 index 0000000000..791f5b6130 --- /dev/null +++ b/Lang/R/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/R \ No newline at end of file diff --git a/Lang/R/Stem-and-leaf-plot b/Lang/R/Stem-and-leaf-plot new file mode 120000 index 0000000000..6bd3ce82a9 --- /dev/null +++ b/Lang/R/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/R \ No newline at end of file diff --git a/Lang/R/String-case b/Lang/R/String-case new file mode 120000 index 0000000000..28f0644a4a --- /dev/null +++ b/Lang/R/String-case @@ -0,0 +1 @@ +../../Task/String-case/R \ No newline at end of file diff --git a/Lang/R/String-concatenation b/Lang/R/String-concatenation new file mode 120000 index 0000000000..8dda8b3da1 --- /dev/null +++ b/Lang/R/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/R \ No newline at end of file diff --git a/Lang/R/String-length b/Lang/R/String-length new file mode 120000 index 0000000000..0c4dd727d8 --- /dev/null +++ b/Lang/R/String-length @@ -0,0 +1 @@ +../../Task/String-length/R \ No newline at end of file diff --git a/Lang/R/Strip-comments-from-a-string b/Lang/R/Strip-comments-from-a-string new file mode 120000 index 0000000000..b6e1f6c8b0 --- /dev/null +++ b/Lang/R/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/R \ No newline at end of file diff --git a/Lang/R/Substring b/Lang/R/Substring new file mode 120000 index 0000000000..32ff26730f --- /dev/null +++ b/Lang/R/Substring @@ -0,0 +1 @@ +../../Task/Substring/R \ No newline at end of file diff --git a/Lang/R/Sum-and-product-of-an-array b/Lang/R/Sum-and-product-of-an-array new file mode 120000 index 0000000000..7fb5b1d37f --- /dev/null +++ b/Lang/R/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/R \ No newline at end of file diff --git a/Lang/R/Sum-of-a-series b/Lang/R/Sum-of-a-series new file mode 120000 index 0000000000..776c7c1452 --- /dev/null +++ b/Lang/R/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/R \ No newline at end of file diff --git a/Lang/R/Sum-of-squares b/Lang/R/Sum-of-squares new file mode 120000 index 0000000000..e590e002e1 --- /dev/null +++ b/Lang/R/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/R \ No newline at end of file diff --git a/Lang/R/Symmetric-difference b/Lang/R/Symmetric-difference new file mode 120000 index 0000000000..b5f61ac861 --- /dev/null +++ b/Lang/R/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/R \ No newline at end of file diff --git a/Lang/R/System-time b/Lang/R/System-time new file mode 120000 index 0000000000..d8b0a74fd5 --- /dev/null +++ b/Lang/R/System-time @@ -0,0 +1 @@ +../../Task/System-time/R \ No newline at end of file diff --git a/Lang/R/Take-notes-on-the-command-line b/Lang/R/Take-notes-on-the-command-line new file mode 120000 index 0000000000..cd1f5995eb --- /dev/null +++ b/Lang/R/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/R \ No newline at end of file diff --git a/Lang/R/Terminal-control-Ringing-the-terminal-bell b/Lang/R/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..1e9b4d9b60 --- /dev/null +++ b/Lang/R/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/R \ No newline at end of file diff --git a/Lang/R/Test-a-function b/Lang/R/Test-a-function new file mode 120000 index 0000000000..5b672a48ee --- /dev/null +++ b/Lang/R/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/R \ No newline at end of file diff --git a/Lang/R/Text-processing-1 b/Lang/R/Text-processing-1 new file mode 120000 index 0000000000..ec69d62b19 --- /dev/null +++ b/Lang/R/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/R \ No newline at end of file diff --git a/Lang/R/Text-processing-2 b/Lang/R/Text-processing-2 new file mode 120000 index 0000000000..a09440c525 --- /dev/null +++ b/Lang/R/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/R \ No newline at end of file diff --git a/Lang/R/Text-processing-Max-licenses-in-use b/Lang/R/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..5334e0e338 --- /dev/null +++ b/Lang/R/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/R \ No newline at end of file diff --git a/Lang/R/Time-a-function b/Lang/R/Time-a-function new file mode 120000 index 0000000000..f4c60b2825 --- /dev/null +++ b/Lang/R/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/R \ No newline at end of file diff --git a/Lang/R/Tokenize-a-string b/Lang/R/Tokenize-a-string new file mode 120000 index 0000000000..8e022d3cd3 --- /dev/null +++ b/Lang/R/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/R \ No newline at end of file diff --git a/Lang/R/Top-rank-per-group b/Lang/R/Top-rank-per-group new file mode 120000 index 0000000000..7733bf4862 --- /dev/null +++ b/Lang/R/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/R \ No newline at end of file diff --git a/Lang/R/Topological-sort b/Lang/R/Topological-sort new file mode 120000 index 0000000000..55597082af --- /dev/null +++ b/Lang/R/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/R \ No newline at end of file diff --git a/Lang/R/Towers-of-Hanoi b/Lang/R/Towers-of-Hanoi new file mode 120000 index 0000000000..5b0e78ffe3 --- /dev/null +++ b/Lang/R/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/R \ No newline at end of file diff --git a/Lang/R/Trabb-Pardo-Knuth-algorithm b/Lang/R/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..6e621ab917 --- /dev/null +++ b/Lang/R/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/R \ No newline at end of file diff --git a/Lang/R/Trigonometric-functions b/Lang/R/Trigonometric-functions new file mode 120000 index 0000000000..338162aae2 --- /dev/null +++ b/Lang/R/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/R \ No newline at end of file diff --git a/Lang/R/Undefined-values b/Lang/R/Undefined-values new file mode 120000 index 0000000000..e0777936d2 --- /dev/null +++ b/Lang/R/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/R \ No newline at end of file diff --git a/Lang/R/User-input-Graphical b/Lang/R/User-input-Graphical new file mode 120000 index 0000000000..fcc4bdb363 --- /dev/null +++ b/Lang/R/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/R \ No newline at end of file diff --git a/Lang/R/User-input-Text b/Lang/R/User-input-Text new file mode 120000 index 0000000000..3fddb8531b --- /dev/null +++ b/Lang/R/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/R \ No newline at end of file diff --git a/Lang/R/Variable-size-Get b/Lang/R/Variable-size-Get new file mode 120000 index 0000000000..4a7f1b272f --- /dev/null +++ b/Lang/R/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/R \ No newline at end of file diff --git a/Lang/R/Variables b/Lang/R/Variables new file mode 120000 index 0000000000..9d44fe0410 --- /dev/null +++ b/Lang/R/Variables @@ -0,0 +1 @@ +../../Task/Variables/R \ No newline at end of file diff --git a/Lang/R/Variadic-function b/Lang/R/Variadic-function new file mode 120000 index 0000000000..b0aab919c6 --- /dev/null +++ b/Lang/R/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/R \ No newline at end of file diff --git a/Lang/R/Vector-products b/Lang/R/Vector-products new file mode 120000 index 0000000000..599d761eb6 --- /dev/null +++ b/Lang/R/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/R \ No newline at end of file diff --git a/Lang/R/Verify-distribution-uniformity-Chi-squared-test b/Lang/R/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..3b919610c7 --- /dev/null +++ b/Lang/R/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/R \ No newline at end of file diff --git a/Lang/R/Verify-distribution-uniformity-Naive b/Lang/R/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..1c2a1c092f --- /dev/null +++ b/Lang/R/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/R \ No newline at end of file diff --git a/Lang/R/Vigen-re-cipher b/Lang/R/Vigen-re-cipher new file mode 120000 index 0000000000..e88e73a233 --- /dev/null +++ b/Lang/R/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/R \ No newline at end of file diff --git a/Lang/R/Walk-a-directory-Non-recursively b/Lang/R/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..761e62ef68 --- /dev/null +++ b/Lang/R/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/R \ No newline at end of file diff --git a/Lang/R/Walk-a-directory-Recursively b/Lang/R/Walk-a-directory-Recursively new file mode 120000 index 0000000000..d2d8145612 --- /dev/null +++ b/Lang/R/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/R \ No newline at end of file diff --git a/Lang/R/Web-scraping b/Lang/R/Web-scraping new file mode 120000 index 0000000000..c16d726a13 --- /dev/null +++ b/Lang/R/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/R \ No newline at end of file diff --git a/Lang/R/Window-creation b/Lang/R/Window-creation new file mode 120000 index 0000000000..eb1795e853 --- /dev/null +++ b/Lang/R/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/R \ No newline at end of file diff --git a/Lang/R/Write-float-arrays-to-a-text-file b/Lang/R/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..5853d20ed7 --- /dev/null +++ b/Lang/R/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/R \ No newline at end of file diff --git a/Lang/R/XML-Input b/Lang/R/XML-Input new file mode 120000 index 0000000000..883d4b56bf --- /dev/null +++ b/Lang/R/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/R \ No newline at end of file diff --git a/Lang/R/XML-Output b/Lang/R/XML-Output new file mode 120000 index 0000000000..9af75f8ade --- /dev/null +++ b/Lang/R/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/R \ No newline at end of file diff --git a/Lang/R/XML-XPath b/Lang/R/XML-XPath new file mode 120000 index 0000000000..f67f97a201 --- /dev/null +++ b/Lang/R/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/R \ No newline at end of file diff --git a/Lang/R/Y-combinator b/Lang/R/Y-combinator new file mode 120000 index 0000000000..b2f15857c9 --- /dev/null +++ b/Lang/R/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/R \ No newline at end of file diff --git a/Lang/R/Yahoo--search-interface b/Lang/R/Yahoo--search-interface new file mode 120000 index 0000000000..97a86ffa0f --- /dev/null +++ b/Lang/R/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/R \ No newline at end of file diff --git a/Lang/R/Yin-and-yang b/Lang/R/Yin-and-yang new file mode 120000 index 0000000000..a17c3b421c --- /dev/null +++ b/Lang/R/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/R \ No newline at end of file diff --git a/Lang/R/Zeckendorf-number-representation b/Lang/R/Zeckendorf-number-representation new file mode 120000 index 0000000000..f85dba7fe0 --- /dev/null +++ b/Lang/R/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/R \ No newline at end of file diff --git a/Lang/R/Zig-zag-matrix b/Lang/R/Zig-zag-matrix new file mode 120000 index 0000000000..c0d891f234 --- /dev/null +++ b/Lang/R/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/R \ No newline at end of file diff --git a/Lang/REALbasic/Sorting-algorithms-Insertion-sort b/Lang/REALbasic/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..f42fba8cdb --- /dev/null +++ b/Lang/REALbasic/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/URL-encoding b/Lang/REALbasic/URL-encoding new file mode 120000 index 0000000000..a9acf64501 --- /dev/null +++ b/Lang/REALbasic/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Walk-a-directory-Recursively b/Lang/REALbasic/Walk-a-directory-Recursively new file mode 120000 index 0000000000..8a5d869cce --- /dev/null +++ b/Lang/REALbasic/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/REALbasic \ No newline at end of file diff --git a/Lang/REBOL/Shell-one-liner b/Lang/REBOL/Shell-one-liner new file mode 120000 index 0000000000..3efd76bee3 --- /dev/null +++ b/Lang/REBOL/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-windowed-application b/Lang/REBOL/Simple-windowed-application new file mode 120000 index 0000000000..3eb2f5011a --- /dev/null +++ b/Lang/REBOL/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sleep b/Lang/REBOL/Sleep new file mode 120000 index 0000000000..49498dee8f --- /dev/null +++ b/Lang/REBOL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-an-integer-array b/Lang/REBOL/Sort-an-integer-array new file mode 120000 index 0000000000..be40906bd3 --- /dev/null +++ b/Lang/REBOL/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-stability b/Lang/REBOL/Sort-stability new file mode 120000 index 0000000000..7a6119bc4e --- /dev/null +++ b/Lang/REBOL/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stack b/Lang/REBOL/Stack new file mode 120000 index 0000000000..70bb3936ee --- /dev/null +++ b/Lang/REBOL/Stack @@ -0,0 +1 @@ +../../Task/Stack/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stair-climbing-puzzle b/Lang/REBOL/Stair-climbing-puzzle new file mode 120000 index 0000000000..935f1a3925 --- /dev/null +++ b/Lang/REBOL/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-case b/Lang/REBOL/String-case new file mode 120000 index 0000000000..2279191d8d --- /dev/null +++ b/Lang/REBOL/String-case @@ -0,0 +1 @@ +../../Task/String-case/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-concatenation b/Lang/REBOL/String-concatenation new file mode 120000 index 0000000000..8be78ed69f --- /dev/null +++ b/Lang/REBOL/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-interpolation--included- b/Lang/REBOL/String-interpolation--included- new file mode 120000 index 0000000000..e35c3095f9 --- /dev/null +++ b/Lang/REBOL/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-length b/Lang/REBOL/String-length new file mode 120000 index 0000000000..06c8f5cbd6 --- /dev/null +++ b/Lang/REBOL/String-length @@ -0,0 +1 @@ +../../Task/String-length/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Substring b/Lang/REBOL/Substring new file mode 120000 index 0000000000..ae87eb5a53 --- /dev/null +++ b/Lang/REBOL/Substring @@ -0,0 +1 @@ +../../Task/Substring/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sum-and-product-of-an-array b/Lang/REBOL/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5ce08d6535 --- /dev/null +++ b/Lang/REBOL/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Symmetric-difference b/Lang/REBOL/Symmetric-difference new file mode 120000 index 0000000000..27c9c680ad --- /dev/null +++ b/Lang/REBOL/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/REBOL \ No newline at end of file diff --git a/Lang/REBOL/System-time b/Lang/REBOL/System-time new file mode 120000 index 0000000000..7ea31d4a27 --- /dev/null +++ b/Lang/REBOL/System-time @@ -0,0 +1 @@ +../../Task/System-time/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Take-notes-on-the-command-line b/Lang/REBOL/Take-notes-on-the-command-line new file mode 120000 index 0000000000..f00a0f5d0a --- /dev/null +++ b/Lang/REBOL/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Tokenize-a-string b/Lang/REBOL/Tokenize-a-string new file mode 120000 index 0000000000..ee10fb0551 --- /dev/null +++ b/Lang/REBOL/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Towers-of-Hanoi b/Lang/REBOL/Towers-of-Hanoi new file mode 120000 index 0000000000..a173272546 --- /dev/null +++ b/Lang/REBOL/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Trigonometric-functions b/Lang/REBOL/Trigonometric-functions new file mode 120000 index 0000000000..8f4c11188c --- /dev/null +++ b/Lang/REBOL/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Graphical b/Lang/REBOL/User-input-Graphical new file mode 120000 index 0000000000..001538e055 --- /dev/null +++ b/Lang/REBOL/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Text b/Lang/REBOL/User-input-Text new file mode 120000 index 0000000000..b81fcf9c85 --- /dev/null +++ b/Lang/REBOL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Variadic-function b/Lang/REBOL/Variadic-function new file mode 120000 index 0000000000..c3eb7c285d --- /dev/null +++ b/Lang/REBOL/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Web-scraping b/Lang/REBOL/Web-scraping new file mode 120000 index 0000000000..4c37db2bfe --- /dev/null +++ b/Lang/REBOL/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Window-creation b/Lang/REBOL/Window-creation new file mode 120000 index 0000000000..d3c3450624 --- /dev/null +++ b/Lang/REBOL/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/XML-Input b/Lang/REBOL/XML-Input new file mode 120000 index 0000000000..f96cb4fd5e --- /dev/null +++ b/Lang/REBOL/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Y-combinator b/Lang/REBOL/Y-combinator new file mode 120000 index 0000000000..492c58627d --- /dev/null +++ b/Lang/REBOL/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/REBOL \ No newline at end of file diff --git a/Lang/REXX/Seven-sided-dice-from-five-sided-dice b/Lang/REXX/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..4bfc3d73a5 --- /dev/null +++ b/Lang/REXX/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/REXX \ No newline at end of file diff --git a/Lang/REXX/Shell-one-liner b/Lang/REXX/Shell-one-liner new file mode 120000 index 0000000000..72f59e68d5 --- /dev/null +++ b/Lang/REXX/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/REXX \ No newline at end of file diff --git a/Lang/REXX/Short-circuit-evaluation b/Lang/REXX/Short-circuit-evaluation new file mode 120000 index 0000000000..695fc39122 --- /dev/null +++ b/Lang/REXX/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/REXX \ No newline at end of file diff --git a/Lang/REXX/Show-the-epoch b/Lang/REXX/Show-the-epoch new file mode 120000 index 0000000000..7b71f3830b --- /dev/null +++ b/Lang/REXX/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/REXX \ No newline at end of file diff --git a/Lang/REXX/Sierpinski-carpet b/Lang/REXX/Sierpinski-carpet new file mode 120000 index 0000000000..132c74e4f1 --- /dev/null +++ b/Lang/REXX/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/REXX \ No newline at end of file diff --git a/Lang/REXX/Sierpinski-triangle b/Lang/REXX/Sierpinski-triangle new file mode 120000 index 0000000000..98a58f380b --- /dev/null +++ b/Lang/REXX/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/REXX \ No newline at end of file diff --git a/Lang/REXX/Sieve-of-Eratosthenes b/Lang/REXX/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..6de8ae0dd6 --- /dev/null +++ b/Lang/REXX/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/REXX \ No newline at end of file diff --git a/Lang/REXX/Singly-linked-list-Element-definition b/Lang/REXX/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..92ba8b0f1e --- /dev/null +++ b/Lang/REXX/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/REXX \ No newline at end of file diff --git a/Lang/REXX/Sleep b/Lang/REXX/Sleep new file mode 120000 index 0000000000..a29a779536 --- /dev/null +++ b/Lang/REXX/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/REXX \ No newline at end of file diff --git a/Lang/REXX/Sort-an-integer-array b/Lang/REXX/Sort-an-integer-array new file mode 120000 index 0000000000..ddf092b0c2 --- /dev/null +++ b/Lang/REXX/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/REXX \ No newline at end of file diff --git a/Lang/REXX/Sort-disjoint-sublist b/Lang/REXX/Sort-disjoint-sublist new file mode 120000 index 0000000000..34e34c1af1 --- /dev/null +++ b/Lang/REXX/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Bead-sort b/Lang/REXX/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..55b63a7615 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Bogosort b/Lang/REXX/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..3f4b1783fe --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Bubble-sort b/Lang/REXX/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..cb11950bc8 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Cocktail-sort b/Lang/REXX/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..de0a88aa18 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Comb-sort b/Lang/REXX/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..cceb46ace8 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Counting-sort b/Lang/REXX/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..9d5ab422b5 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Gnome-sort b/Lang/REXX/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..e420907687 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Heapsort b/Lang/REXX/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..e8a17d98b5 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Insertion-sort b/Lang/REXX/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..a350cbdf37 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Merge-sort b/Lang/REXX/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..8253849aef --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Pancake-sort b/Lang/REXX/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..39dbf8e59f --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Permutation-sort b/Lang/REXX/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..fb44bb18ea --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Quicksort b/Lang/REXX/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..24aa9c4a99 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Radix-sort b/Lang/REXX/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..297ef0d9af --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Selection-sort b/Lang/REXX/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..537bf342be --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Shell-sort b/Lang/REXX/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..ac1fbfd4a9 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Sleep-sort b/Lang/REXX/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..67642cf4c8 --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Stooge-sort b/Lang/REXX/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..bbe41c9bab --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-algorithms-Strand-sort b/Lang/REXX/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..1fd4a889bb --- /dev/null +++ b/Lang/REXX/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Soundex b/Lang/REXX/Soundex new file mode 120000 index 0000000000..a07ddc7956 --- /dev/null +++ b/Lang/REXX/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/REXX \ No newline at end of file diff --git a/Lang/REXX/Special-characters b/Lang/REXX/Special-characters new file mode 120000 index 0000000000..c73dc97332 --- /dev/null +++ b/Lang/REXX/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/REXX \ No newline at end of file diff --git a/Lang/REXX/Special-variables b/Lang/REXX/Special-variables new file mode 120000 index 0000000000..920240b877 --- /dev/null +++ b/Lang/REXX/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/REXX \ No newline at end of file diff --git a/Lang/REXX/Spiral-matrix b/Lang/REXX/Spiral-matrix new file mode 120000 index 0000000000..f0ed5c093c --- /dev/null +++ b/Lang/REXX/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/REXX \ No newline at end of file diff --git a/Lang/REXX/Stack b/Lang/REXX/Stack new file mode 120000 index 0000000000..a03608fff3 --- /dev/null +++ b/Lang/REXX/Stack @@ -0,0 +1 @@ +../../Task/Stack/REXX \ No newline at end of file diff --git a/Lang/REXX/Stair-climbing-puzzle b/Lang/REXX/Stair-climbing-puzzle new file mode 120000 index 0000000000..dfc808c6a2 --- /dev/null +++ b/Lang/REXX/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Standard-deviation b/Lang/REXX/Standard-deviation new file mode 120000 index 0000000000..40eb7a6df1 --- /dev/null +++ b/Lang/REXX/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/REXX \ No newline at end of file diff --git a/Lang/REXX/Start-from-a-main-routine b/Lang/REXX/Start-from-a-main-routine new file mode 120000 index 0000000000..244f6db4d5 --- /dev/null +++ b/Lang/REXX/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/REXX \ No newline at end of file diff --git a/Lang/REXX/Stem-and-leaf-plot b/Lang/REXX/Stem-and-leaf-plot new file mode 120000 index 0000000000..cf469f5c2d --- /dev/null +++ b/Lang/REXX/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/REXX \ No newline at end of file diff --git a/Lang/REXX/String-case b/Lang/REXX/String-case new file mode 120000 index 0000000000..b48d856e7f --- /dev/null +++ b/Lang/REXX/String-case @@ -0,0 +1 @@ +../../Task/String-case/REXX \ No newline at end of file diff --git a/Lang/REXX/String-comparison b/Lang/REXX/String-comparison new file mode 120000 index 0000000000..983df86001 --- /dev/null +++ b/Lang/REXX/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/REXX \ No newline at end of file diff --git a/Lang/REXX/String-concatenation b/Lang/REXX/String-concatenation new file mode 120000 index 0000000000..2244435f74 --- /dev/null +++ b/Lang/REXX/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/REXX \ No newline at end of file diff --git a/Lang/REXX/String-interpolation--included- b/Lang/REXX/String-interpolation--included- new file mode 120000 index 0000000000..70f0a65942 --- /dev/null +++ b/Lang/REXX/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/REXX \ No newline at end of file diff --git a/Lang/REXX/String-length b/Lang/REXX/String-length new file mode 120000 index 0000000000..a9aff0d6d3 --- /dev/null +++ b/Lang/REXX/String-length @@ -0,0 +1 @@ +../../Task/String-length/REXX \ No newline at end of file diff --git a/Lang/REXX/Strip-a-set-of-characters-from-a-string b/Lang/REXX/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..39566a1cfc --- /dev/null +++ b/Lang/REXX/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Strip-comments-from-a-string b/Lang/REXX/Strip-comments-from-a-string new file mode 120000 index 0000000000..e9c0b5bbce --- /dev/null +++ b/Lang/REXX/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Strip-control-codes-and-extended-characters-from-a-string b/Lang/REXX/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..aa98cbef31 --- /dev/null +++ b/Lang/REXX/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Strip-whitespace-from-a-string-Top-and-tail b/Lang/REXX/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..e0d027f37a --- /dev/null +++ b/Lang/REXX/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/REXX \ No newline at end of file diff --git a/Lang/REXX/Substring b/Lang/REXX/Substring new file mode 120000 index 0000000000..6524f7574a --- /dev/null +++ b/Lang/REXX/Substring @@ -0,0 +1 @@ +../../Task/Substring/REXX \ No newline at end of file diff --git a/Lang/REXX/Substring-Top-and-tail b/Lang/REXX/Substring-Top-and-tail new file mode 120000 index 0000000000..fe6c2b424f --- /dev/null +++ b/Lang/REXX/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/REXX \ No newline at end of file diff --git a/Lang/REXX/Subtractive-generator b/Lang/REXX/Subtractive-generator new file mode 120000 index 0000000000..6ff5d9a224 --- /dev/null +++ b/Lang/REXX/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/REXX \ No newline at end of file diff --git a/Lang/REXX/Sum-and-product-of-an-array b/Lang/REXX/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f2d73231df --- /dev/null +++ b/Lang/REXX/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/REXX \ No newline at end of file diff --git a/Lang/REXX/Sum-digits-of-an-integer b/Lang/REXX/Sum-digits-of-an-integer new file mode 120000 index 0000000000..de4af55920 --- /dev/null +++ b/Lang/REXX/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/REXX \ No newline at end of file diff --git a/Lang/REXX/Sum-of-a-series b/Lang/REXX/Sum-of-a-series new file mode 120000 index 0000000000..757202559d --- /dev/null +++ b/Lang/REXX/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/REXX \ No newline at end of file diff --git a/Lang/REXX/Sum-of-squares b/Lang/REXX/Sum-of-squares new file mode 120000 index 0000000000..a3167c456f --- /dev/null +++ b/Lang/REXX/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/REXX \ No newline at end of file diff --git a/Lang/REXX/Symmetric-difference b/Lang/REXX/Symmetric-difference new file mode 120000 index 0000000000..9d632231b0 --- /dev/null +++ b/Lang/REXX/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/REXX \ No newline at end of file diff --git a/Lang/REXX/System-time b/Lang/REXX/System-time new file mode 120000 index 0000000000..3ca8bff194 --- /dev/null +++ b/Lang/REXX/System-time @@ -0,0 +1 @@ +../../Task/System-time/REXX \ No newline at end of file diff --git a/Lang/REXX/Table-creation-Postal-addresses b/Lang/REXX/Table-creation-Postal-addresses new file mode 120000 index 0000000000..964e45ee8e --- /dev/null +++ b/Lang/REXX/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/REXX \ No newline at end of file diff --git a/Lang/REXX/Take-notes-on-the-command-line b/Lang/REXX/Take-notes-on-the-command-line new file mode 120000 index 0000000000..44c60fa0f7 --- /dev/null +++ b/Lang/REXX/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/REXX \ No newline at end of file diff --git a/Lang/REXX/Temperature-conversion b/Lang/REXX/Temperature-conversion new file mode 120000 index 0000000000..8b90cab05d --- /dev/null +++ b/Lang/REXX/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Coloured-text b/Lang/REXX/Terminal-control-Coloured-text new file mode 120000 index 0000000000..3bd33609f5 --- /dev/null +++ b/Lang/REXX/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Cursor-movement b/Lang/REXX/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..21871155c9 --- /dev/null +++ b/Lang/REXX/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Cursor-positioning b/Lang/REXX/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..d940908f8f --- /dev/null +++ b/Lang/REXX/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Dimensions b/Lang/REXX/Terminal-control-Dimensions new file mode 120000 index 0000000000..fbca49d0c1 --- /dev/null +++ b/Lang/REXX/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Display-an-extended-character b/Lang/REXX/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..98c8bed298 --- /dev/null +++ b/Lang/REXX/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Inverse-video b/Lang/REXX/Terminal-control-Inverse-video new file mode 120000 index 0000000000..b62e4c0aa5 --- /dev/null +++ b/Lang/REXX/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Positional-read b/Lang/REXX/Terminal-control-Positional-read new file mode 120000 index 0000000000..5dc65feb85 --- /dev/null +++ b/Lang/REXX/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Preserve-screen b/Lang/REXX/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..033682ebc2 --- /dev/null +++ b/Lang/REXX/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Ringing-the-terminal-bell b/Lang/REXX/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..aeff1d1f99 --- /dev/null +++ b/Lang/REXX/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/REXX \ No newline at end of file diff --git a/Lang/REXX/Ternary-logic b/Lang/REXX/Ternary-logic new file mode 120000 index 0000000000..32baf4a0df --- /dev/null +++ b/Lang/REXX/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/REXX \ No newline at end of file diff --git a/Lang/REXX/Test-a-function b/Lang/REXX/Test-a-function new file mode 120000 index 0000000000..959daba854 --- /dev/null +++ b/Lang/REXX/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/REXX \ No newline at end of file diff --git a/Lang/REXX/Text-processing-1 b/Lang/REXX/Text-processing-1 new file mode 120000 index 0000000000..e07b8d22f9 --- /dev/null +++ b/Lang/REXX/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/REXX \ No newline at end of file diff --git a/Lang/REXX/Text-processing-2 b/Lang/REXX/Text-processing-2 new file mode 120000 index 0000000000..1b485f6ff0 --- /dev/null +++ b/Lang/REXX/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/REXX \ No newline at end of file diff --git a/Lang/REXX/Text-processing-Max-licenses-in-use b/Lang/REXX/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..fd8435febb --- /dev/null +++ b/Lang/REXX/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/REXX \ No newline at end of file diff --git a/Lang/REXX/Tic-tac-toe b/Lang/REXX/Tic-tac-toe new file mode 120000 index 0000000000..62a37731fc --- /dev/null +++ b/Lang/REXX/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/REXX \ No newline at end of file diff --git a/Lang/REXX/Time-a-function b/Lang/REXX/Time-a-function new file mode 120000 index 0000000000..2cb8f7e4fe --- /dev/null +++ b/Lang/REXX/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/REXX \ No newline at end of file diff --git a/Lang/REXX/Tokenize-a-string b/Lang/REXX/Tokenize-a-string new file mode 120000 index 0000000000..e001a1a942 --- /dev/null +++ b/Lang/REXX/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/REXX \ No newline at end of file diff --git a/Lang/REXX/Top-rank-per-group b/Lang/REXX/Top-rank-per-group new file mode 120000 index 0000000000..65dd8bdd05 --- /dev/null +++ b/Lang/REXX/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/REXX \ No newline at end of file diff --git a/Lang/REXX/Topswops b/Lang/REXX/Topswops new file mode 120000 index 0000000000..f4bdb36ea7 --- /dev/null +++ b/Lang/REXX/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/REXX \ No newline at end of file diff --git a/Lang/REXX/Towers-of-Hanoi b/Lang/REXX/Towers-of-Hanoi new file mode 120000 index 0000000000..a0a122c15e --- /dev/null +++ b/Lang/REXX/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/REXX \ No newline at end of file diff --git a/Lang/REXX/Trabb-Pardo-Knuth-algorithm b/Lang/REXX/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..c527e2449c --- /dev/null +++ b/Lang/REXX/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/REXX \ No newline at end of file diff --git a/Lang/REXX/Tree-traversal b/Lang/REXX/Tree-traversal new file mode 120000 index 0000000000..3b4853a10a --- /dev/null +++ b/Lang/REXX/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/REXX \ No newline at end of file diff --git a/Lang/REXX/Trigonometric-functions b/Lang/REXX/Trigonometric-functions new file mode 120000 index 0000000000..463e81dcdc --- /dev/null +++ b/Lang/REXX/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/REXX \ No newline at end of file diff --git a/Lang/REXX/Truncatable-primes b/Lang/REXX/Truncatable-primes new file mode 120000 index 0000000000..f6df07dc5f --- /dev/null +++ b/Lang/REXX/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Twelve-statements b/Lang/REXX/Twelve-statements new file mode 120000 index 0000000000..bfaab45bca --- /dev/null +++ b/Lang/REXX/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/REXX \ No newline at end of file diff --git a/Lang/REXX/URL-decoding b/Lang/REXX/URL-decoding new file mode 120000 index 0000000000..fad1dee04a --- /dev/null +++ b/Lang/REXX/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/REXX \ No newline at end of file diff --git a/Lang/REXX/URL-encoding b/Lang/REXX/URL-encoding new file mode 120000 index 0000000000..5090d0760c --- /dev/null +++ b/Lang/REXX/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/REXX \ No newline at end of file diff --git a/Lang/REXX/Unbias-a-random-generator b/Lang/REXX/Unbias-a-random-generator new file mode 120000 index 0000000000..f79d90a7ee --- /dev/null +++ b/Lang/REXX/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/REXX \ No newline at end of file diff --git a/Lang/REXX/Undefined-values b/Lang/REXX/Undefined-values new file mode 120000 index 0000000000..08818b9ee2 --- /dev/null +++ b/Lang/REXX/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/REXX \ No newline at end of file diff --git a/Lang/REXX/User-input-Text b/Lang/REXX/User-input-Text new file mode 120000 index 0000000000..2a629013e2 --- /dev/null +++ b/Lang/REXX/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/REXX \ No newline at end of file diff --git a/Lang/REXX/Vampire-number b/Lang/REXX/Vampire-number new file mode 120000 index 0000000000..4fd33425ae --- /dev/null +++ b/Lang/REXX/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/REXX \ No newline at end of file diff --git a/Lang/REXX/Van-der-Corput-sequence b/Lang/REXX/Van-der-Corput-sequence new file mode 120000 index 0000000000..eb53413fd8 --- /dev/null +++ b/Lang/REXX/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/REXX \ No newline at end of file diff --git a/Lang/REXX/Variable-length-quantity b/Lang/REXX/Variable-length-quantity new file mode 120000 index 0000000000..a5cf0af619 --- /dev/null +++ b/Lang/REXX/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/REXX \ No newline at end of file diff --git a/Lang/REXX/Variable-size-Get b/Lang/REXX/Variable-size-Get new file mode 120000 index 0000000000..0c15e926dd --- /dev/null +++ b/Lang/REXX/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/REXX \ No newline at end of file diff --git a/Lang/REXX/Variable-size-Set b/Lang/REXX/Variable-size-Set new file mode 120000 index 0000000000..d58c6f23bc --- /dev/null +++ b/Lang/REXX/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/REXX \ No newline at end of file diff --git a/Lang/REXX/Variables b/Lang/REXX/Variables new file mode 120000 index 0000000000..4fa25ff990 --- /dev/null +++ b/Lang/REXX/Variables @@ -0,0 +1 @@ +../../Task/Variables/REXX \ No newline at end of file diff --git a/Lang/REXX/Variadic-function b/Lang/REXX/Variadic-function new file mode 120000 index 0000000000..4682fa8511 --- /dev/null +++ b/Lang/REXX/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/REXX \ No newline at end of file diff --git a/Lang/REXX/Vector-products b/Lang/REXX/Vector-products new file mode 120000 index 0000000000..ed3496d1ee --- /dev/null +++ b/Lang/REXX/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/REXX \ No newline at end of file diff --git a/Lang/REXX/Video-display-modes b/Lang/REXX/Video-display-modes new file mode 120000 index 0000000000..8208ed0dcc --- /dev/null +++ b/Lang/REXX/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/REXX \ No newline at end of file diff --git a/Lang/REXX/Vigen-re-cipher b/Lang/REXX/Vigen-re-cipher new file mode 120000 index 0000000000..6ddd814739 --- /dev/null +++ b/Lang/REXX/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/REXX \ No newline at end of file diff --git a/Lang/REXX/Word-wrap b/Lang/REXX/Word-wrap new file mode 120000 index 0000000000..1c4fde9466 --- /dev/null +++ b/Lang/REXX/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/REXX \ No newline at end of file diff --git a/Lang/REXX/Write-float-arrays-to-a-text-file b/Lang/REXX/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..a099361a61 --- /dev/null +++ b/Lang/REXX/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Write-language-name-in-3D-ASCII b/Lang/REXX/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..cfbb3bc6e0 --- /dev/null +++ b/Lang/REXX/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/REXX \ No newline at end of file diff --git a/Lang/REXX/Write-to-Windows-event-log b/Lang/REXX/Write-to-Windows-event-log new file mode 120000 index 0000000000..d50561c744 --- /dev/null +++ b/Lang/REXX/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/REXX \ No newline at end of file diff --git a/Lang/REXX/XML-Input b/Lang/REXX/XML-Input new file mode 120000 index 0000000000..2249fab80e --- /dev/null +++ b/Lang/REXX/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/REXX \ No newline at end of file diff --git a/Lang/REXX/XML-Output b/Lang/REXX/XML-Output new file mode 120000 index 0000000000..f300ccf395 --- /dev/null +++ b/Lang/REXX/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/REXX \ No newline at end of file diff --git a/Lang/REXX/Xiaolin-Wus-line-algorithm b/Lang/REXX/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..f9e0acda2f --- /dev/null +++ b/Lang/REXX/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/REXX \ No newline at end of file diff --git a/Lang/REXX/Y-combinator b/Lang/REXX/Y-combinator new file mode 120000 index 0000000000..942d0caf99 --- /dev/null +++ b/Lang/REXX/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/REXX \ No newline at end of file diff --git a/Lang/REXX/Zeckendorf-number-representation b/Lang/REXX/Zeckendorf-number-representation new file mode 120000 index 0000000000..3c9a4de8fb --- /dev/null +++ b/Lang/REXX/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/REXX \ No newline at end of file diff --git a/Lang/REXX/Zig-zag-matrix b/Lang/REXX/Zig-zag-matrix new file mode 120000 index 0000000000..6e2c6a0c81 --- /dev/null +++ b/Lang/REXX/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/REXX \ No newline at end of file diff --git a/Lang/RLaB/Sum-of-a-series b/Lang/RLaB/Sum-of-a-series new file mode 120000 index 0000000000..d9d3cd740c --- /dev/null +++ b/Lang/RLaB/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/RLaB \ No newline at end of file diff --git a/Lang/RLaB/Write-float-arrays-to-a-text-file b/Lang/RLaB/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..0e6f461bf0 --- /dev/null +++ b/Lang/RLaB/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/RLaB \ No newline at end of file diff --git a/Lang/Racket/SHA-1 b/Lang/Racket/SHA-1 new file mode 120000 index 0000000000..fff70b1a83 --- /dev/null +++ b/Lang/Racket/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Racket \ No newline at end of file diff --git a/Lang/Racket/Shell-one-liner b/Lang/Racket/Shell-one-liner new file mode 120000 index 0000000000..f121e93f77 --- /dev/null +++ b/Lang/Racket/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Racket \ No newline at end of file diff --git a/Lang/Racket/Short-circuit-evaluation b/Lang/Racket/Short-circuit-evaluation new file mode 120000 index 0000000000..390207d3e9 --- /dev/null +++ b/Lang/Racket/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Racket \ No newline at end of file diff --git a/Lang/Racket/Show-the-epoch b/Lang/Racket/Show-the-epoch new file mode 120000 index 0000000000..7484770a82 --- /dev/null +++ b/Lang/Racket/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Racket \ No newline at end of file diff --git a/Lang/Racket/Simple-windowed-application b/Lang/Racket/Simple-windowed-application new file mode 120000 index 0000000000..98be40c16c --- /dev/null +++ b/Lang/Racket/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Racket \ No newline at end of file diff --git a/Lang/Racket/Singleton b/Lang/Racket/Singleton new file mode 120000 index 0000000000..3a9c04455a --- /dev/null +++ b/Lang/Racket/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Racket \ No newline at end of file diff --git a/Lang/Racket/Sleep b/Lang/Racket/Sleep new file mode 120000 index 0000000000..470bbf14d9 --- /dev/null +++ b/Lang/Racket/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Racket \ No newline at end of file diff --git a/Lang/Racket/Sockets b/Lang/Racket/Sockets new file mode 120000 index 0000000000..b958284e18 --- /dev/null +++ b/Lang/Racket/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Bead-sort b/Lang/Racket/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..8040cdb82b --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Bogosort b/Lang/Racket/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..0cf185f622 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Insertion-sort b/Lang/Racket/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..9e7963726a --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-algorithms-Sleep-sort b/Lang/Racket/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..8d383c4641 --- /dev/null +++ b/Lang/Racket/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Stack b/Lang/Racket/Stack new file mode 120000 index 0000000000..f4ccaf8338 --- /dev/null +++ b/Lang/Racket/Stack @@ -0,0 +1 @@ +../../Task/Stack/Racket \ No newline at end of file diff --git a/Lang/Racket/Start-from-a-main-routine b/Lang/Racket/Start-from-a-main-routine new file mode 120000 index 0000000000..f4ca74e2ec --- /dev/null +++ b/Lang/Racket/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Racket \ No newline at end of file diff --git a/Lang/Racket/String-comparison b/Lang/Racket/String-comparison new file mode 120000 index 0000000000..4ed81de41d --- /dev/null +++ b/Lang/Racket/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Racket \ No newline at end of file diff --git a/Lang/Racket/String-interpolation--included- b/Lang/Racket/String-interpolation--included- new file mode 120000 index 0000000000..9a1b34fea4 --- /dev/null +++ b/Lang/Racket/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Racket \ No newline at end of file diff --git a/Lang/Racket/Substring-Top-and-tail b/Lang/Racket/Substring-Top-and-tail new file mode 120000 index 0000000000..8fedee020a --- /dev/null +++ b/Lang/Racket/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Racket \ No newline at end of file diff --git a/Lang/Racket/Sum-and-product-of-an-array b/Lang/Racket/Sum-and-product-of-an-array new file mode 120000 index 0000000000..081bb65e3e --- /dev/null +++ b/Lang/Racket/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Racket \ No newline at end of file diff --git a/Lang/Racket/Sum-of-a-series b/Lang/Racket/Sum-of-a-series new file mode 120000 index 0000000000..c331bb6e9e --- /dev/null +++ b/Lang/Racket/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Racket \ No newline at end of file diff --git a/Lang/Racket/Sum-of-squares b/Lang/Racket/Sum-of-squares new file mode 120000 index 0000000000..29fb6cd803 --- /dev/null +++ b/Lang/Racket/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Racket \ No newline at end of file diff --git a/Lang/Racket/Symmetric-difference b/Lang/Racket/Symmetric-difference new file mode 120000 index 0000000000..694a54b8f5 --- /dev/null +++ b/Lang/Racket/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Racket \ No newline at end of file diff --git a/Lang/Racket/Synchronous-concurrency b/Lang/Racket/Synchronous-concurrency new file mode 120000 index 0000000000..1ca73e3057 --- /dev/null +++ b/Lang/Racket/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Racket \ No newline at end of file diff --git a/Lang/Racket/System-time b/Lang/Racket/System-time new file mode 120000 index 0000000000..df14b54bc5 --- /dev/null +++ b/Lang/Racket/System-time @@ -0,0 +1 @@ +../../Task/System-time/Racket \ No newline at end of file diff --git a/Lang/Racket/Ternary-logic b/Lang/Racket/Ternary-logic new file mode 120000 index 0000000000..2e219f4af2 --- /dev/null +++ b/Lang/Racket/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Racket \ No newline at end of file diff --git a/Lang/Racket/Test-a-function b/Lang/Racket/Test-a-function new file mode 120000 index 0000000000..7e39b562dc --- /dev/null +++ b/Lang/Racket/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Text-processing-1 b/Lang/Racket/Text-processing-1 new file mode 120000 index 0000000000..a7b305b8f2 --- /dev/null +++ b/Lang/Racket/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Racket \ No newline at end of file diff --git a/Lang/Racket/Text-processing-2 b/Lang/Racket/Text-processing-2 new file mode 120000 index 0000000000..15ba64004c --- /dev/null +++ b/Lang/Racket/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Racket \ No newline at end of file diff --git a/Lang/Racket/Text-processing-Max-licenses-in-use b/Lang/Racket/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..e35da4046a --- /dev/null +++ b/Lang/Racket/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Racket \ No newline at end of file diff --git a/Lang/Racket/Time-a-function b/Lang/Racket/Time-a-function new file mode 120000 index 0000000000..a4f6708a05 --- /dev/null +++ b/Lang/Racket/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Racket \ No newline at end of file diff --git a/Lang/Racket/Tokenize-a-string b/Lang/Racket/Tokenize-a-string new file mode 120000 index 0000000000..61d08f115c --- /dev/null +++ b/Lang/Racket/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Racket \ No newline at end of file diff --git a/Lang/Racket/Towers-of-Hanoi b/Lang/Racket/Towers-of-Hanoi new file mode 120000 index 0000000000..7fbdd922e4 --- /dev/null +++ b/Lang/Racket/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Racket \ No newline at end of file diff --git a/Lang/Racket/URL-decoding b/Lang/Racket/URL-decoding new file mode 120000 index 0000000000..71c6627e49 --- /dev/null +++ b/Lang/Racket/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Racket \ No newline at end of file diff --git a/Lang/Racket/URL-encoding b/Lang/Racket/URL-encoding new file mode 120000 index 0000000000..b8e826a943 --- /dev/null +++ b/Lang/Racket/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Racket \ No newline at end of file diff --git a/Lang/Racket/Unicode-variable-names b/Lang/Racket/Unicode-variable-names new file mode 120000 index 0000000000..ee73dfad5d --- /dev/null +++ b/Lang/Racket/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Racket \ No newline at end of file diff --git a/Lang/Racket/Vampire-number b/Lang/Racket/Vampire-number new file mode 120000 index 0000000000..9878dc008d --- /dev/null +++ b/Lang/Racket/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Racket \ No newline at end of file diff --git a/Lang/Racket/Window-creation b/Lang/Racket/Window-creation new file mode 120000 index 0000000000..9a113e7e07 --- /dev/null +++ b/Lang/Racket/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Racket \ No newline at end of file diff --git a/Lang/Racket/XML-Input b/Lang/Racket/XML-Input new file mode 120000 index 0000000000..af68b73c65 --- /dev/null +++ b/Lang/Racket/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Racket \ No newline at end of file diff --git a/Lang/Racket/XML-Output b/Lang/Racket/XML-Output new file mode 120000 index 0000000000..8fc5aab08a --- /dev/null +++ b/Lang/Racket/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Racket \ No newline at end of file diff --git a/Lang/Racket/Yin-and-yang b/Lang/Racket/Yin-and-yang new file mode 120000 index 0000000000..484d008339 --- /dev/null +++ b/Lang/Racket/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Racket \ No newline at end of file diff --git a/Lang/Racket/Zebra-puzzle b/Lang/Racket/Zebra-puzzle new file mode 120000 index 0000000000..779a75f5ed --- /dev/null +++ b/Lang/Racket/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Racket \ No newline at end of file diff --git a/Lang/RapidQ/Simple-windowed-application b/Lang/RapidQ/Simple-windowed-application new file mode 120000 index 0000000000..101a95466a --- /dev/null +++ b/Lang/RapidQ/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Trigonometric-functions b/Lang/RapidQ/Trigonometric-functions new file mode 120000 index 0000000000..2e4dfc20cf --- /dev/null +++ b/Lang/RapidQ/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Variadic-function b/Lang/RapidQ/Variadic-function new file mode 120000 index 0000000000..bf2745a1cc --- /dev/null +++ b/Lang/RapidQ/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/RapidQ \ No newline at end of file diff --git a/Lang/Rascal/Sort-an-integer-array b/Lang/Rascal/Sort-an-integer-array new file mode 120000 index 0000000000..dcff544842 --- /dev/null +++ b/Lang/Rascal/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Sorting-algorithms-Gnome-sort b/Lang/Rascal/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..ac95e27fd8 --- /dev/null +++ b/Lang/Rascal/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Sorting-algorithms-Insertion-sort b/Lang/Rascal/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..cdcbf084d9 --- /dev/null +++ b/Lang/Rascal/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Sudoku b/Lang/Rascal/Sudoku new file mode 120000 index 0000000000..11e13b3d4b --- /dev/null +++ b/Lang/Rascal/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Towers-of-Hanoi b/Lang/Rascal/Towers-of-Hanoi new file mode 120000 index 0000000000..5338954046 --- /dev/null +++ b/Lang/Rascal/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Rascal \ No newline at end of file diff --git a/Lang/Rascal/User-input-Graphical b/Lang/Rascal/User-input-Graphical new file mode 120000 index 0000000000..26914b0f82 --- /dev/null +++ b/Lang/Rascal/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Rascal \ No newline at end of file diff --git a/Lang/Rascal/User-input-Text b/Lang/Rascal/User-input-Text new file mode 120000 index 0000000000..1d4d1935b9 --- /dev/null +++ b/Lang/Rascal/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Variables b/Lang/Rascal/Variables new file mode 120000 index 0000000000..7adafec570 --- /dev/null +++ b/Lang/Rascal/Variables @@ -0,0 +1 @@ +../../Task/Variables/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Walk-a-directory-Non-recursively b/Lang/Rascal/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..a298761211 --- /dev/null +++ b/Lang/Rascal/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Walk-a-directory-Recursively b/Lang/Rascal/Walk-a-directory-Recursively new file mode 120000 index 0000000000..ab575b5f23 --- /dev/null +++ b/Lang/Rascal/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Rascal \ No newline at end of file diff --git a/Lang/Rascal/XML-DOM-serialization b/Lang/Rascal/XML-DOM-serialization new file mode 120000 index 0000000000..c40e08b9f5 --- /dev/null +++ b/Lang/Rascal/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Rascal \ No newline at end of file diff --git a/Lang/Rascal/XML-Input b/Lang/Rascal/XML-Input new file mode 120000 index 0000000000..5c630c4528 --- /dev/null +++ b/Lang/Rascal/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Rascal \ No newline at end of file diff --git a/Lang/Rascal/XML-Output b/Lang/Rascal/XML-Output new file mode 120000 index 0000000000..8e80f402eb --- /dev/null +++ b/Lang/Rascal/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Rascal \ No newline at end of file diff --git a/Lang/Rascal/XML-XPath b/Lang/Rascal/XML-XPath new file mode 120000 index 0000000000..ded1c07a15 --- /dev/null +++ b/Lang/Rascal/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Yin-and-yang b/Lang/Rascal/Yin-and-yang new file mode 120000 index 0000000000..b7c0611faa --- /dev/null +++ b/Lang/Rascal/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Rascal \ No newline at end of file diff --git a/Lang/Rascal/Zig-zag-matrix b/Lang/Rascal/Zig-zag-matrix new file mode 120000 index 0000000000..de2d8aaa5e --- /dev/null +++ b/Lang/Rascal/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Rascal \ No newline at end of file diff --git a/Lang/Raven/SQL-based-authentication b/Lang/Raven/SQL-based-authentication new file mode 120000 index 0000000000..6514c48ec1 --- /dev/null +++ b/Lang/Raven/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Raven \ No newline at end of file diff --git a/Lang/Raven/Sort-an-integer-array b/Lang/Raven/Sort-an-integer-array new file mode 120000 index 0000000000..8c46d1e890 --- /dev/null +++ b/Lang/Raven/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Raven \ No newline at end of file diff --git a/Lang/Raven/Stack b/Lang/Raven/Stack new file mode 120000 index 0000000000..e4fb11c53a --- /dev/null +++ b/Lang/Raven/Stack @@ -0,0 +1 @@ +../../Task/Stack/Raven \ No newline at end of file diff --git a/Lang/Raven/String-case b/Lang/Raven/String-case new file mode 120000 index 0000000000..e110499779 --- /dev/null +++ b/Lang/Raven/String-case @@ -0,0 +1 @@ +../../Task/String-case/Raven \ No newline at end of file diff --git a/Lang/Raven/Sum-and-product-of-an-array b/Lang/Raven/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9836691f34 --- /dev/null +++ b/Lang/Raven/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Raven \ No newline at end of file diff --git a/Lang/Raven/Synchronous-concurrency b/Lang/Raven/Synchronous-concurrency new file mode 120000 index 0000000000..ce5d4633c2 --- /dev/null +++ b/Lang/Raven/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Raven \ No newline at end of file diff --git a/Lang/Raven/Tokenize-a-string b/Lang/Raven/Tokenize-a-string new file mode 120000 index 0000000000..d1998e10c1 --- /dev/null +++ b/Lang/Raven/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Raven \ No newline at end of file diff --git a/Lang/Raven/User-input-Text b/Lang/Raven/User-input-Text new file mode 120000 index 0000000000..bdad94b0e2 --- /dev/null +++ b/Lang/Raven/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Raven \ No newline at end of file diff --git a/Lang/Raven/Walk-a-directory-Non-recursively b/Lang/Raven/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..20018c0bb2 --- /dev/null +++ b/Lang/Raven/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Raven \ No newline at end of file diff --git a/Lang/Retro/Shell-one-liner b/Lang/Retro/Shell-one-liner new file mode 120000 index 0000000000..60b1b2df6f --- /dev/null +++ b/Lang/Retro/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Retro \ No newline at end of file diff --git a/Lang/Retro/Singly-linked-list-Traversal b/Lang/Retro/Singly-linked-list-Traversal new file mode 120000 index 0000000000..65e77fb452 --- /dev/null +++ b/Lang/Retro/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Retro \ No newline at end of file diff --git a/Lang/Retro/Sleep b/Lang/Retro/Sleep new file mode 120000 index 0000000000..e540e7b9aa --- /dev/null +++ b/Lang/Retro/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Retro \ No newline at end of file diff --git a/Lang/Retro/Stack b/Lang/Retro/Stack new file mode 120000 index 0000000000..bd95faa14b --- /dev/null +++ b/Lang/Retro/Stack @@ -0,0 +1 @@ +../../Task/Stack/Retro \ No newline at end of file diff --git a/Lang/Retro/String-case b/Lang/Retro/String-case new file mode 120000 index 0000000000..b5151bcf51 --- /dev/null +++ b/Lang/Retro/String-case @@ -0,0 +1 @@ +../../Task/String-case/Retro \ No newline at end of file diff --git a/Lang/Retro/String-concatenation b/Lang/Retro/String-concatenation new file mode 120000 index 0000000000..cea374b214 --- /dev/null +++ b/Lang/Retro/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Retro \ No newline at end of file diff --git a/Lang/Retro/String-length b/Lang/Retro/String-length new file mode 120000 index 0000000000..9cc121e790 --- /dev/null +++ b/Lang/Retro/String-length @@ -0,0 +1 @@ +../../Task/String-length/Retro \ No newline at end of file diff --git a/Lang/Retro/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Retro/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..a925ab6b96 --- /dev/null +++ b/Lang/Retro/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Retro \ No newline at end of file diff --git a/Lang/Retro/System-time b/Lang/Retro/System-time new file mode 120000 index 0000000000..f968fc7080 --- /dev/null +++ b/Lang/Retro/System-time @@ -0,0 +1 @@ +../../Task/System-time/Retro \ No newline at end of file diff --git a/Lang/Retro/Terminal-control-Clear-the-screen b/Lang/Retro/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..81a8dcaecc --- /dev/null +++ b/Lang/Retro/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Retro \ No newline at end of file diff --git a/Lang/Retro/Terminal-control-Cursor-positioning b/Lang/Retro/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..b81b44d8d7 --- /dev/null +++ b/Lang/Retro/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Retro \ No newline at end of file diff --git a/Lang/Retro/Terminal-control-Dimensions b/Lang/Retro/Terminal-control-Dimensions new file mode 120000 index 0000000000..d845c517d5 --- /dev/null +++ b/Lang/Retro/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Retro \ No newline at end of file diff --git a/Lang/Retro/Terminal-control-Ringing-the-terminal-bell b/Lang/Retro/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..97e7bbdb44 --- /dev/null +++ b/Lang/Retro/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Retro \ No newline at end of file diff --git a/Lang/Retro/Test-a-function b/Lang/Retro/Test-a-function new file mode 120000 index 0000000000..6de2f6c682 --- /dev/null +++ b/Lang/Retro/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Retro \ No newline at end of file diff --git a/Lang/Retro/Time-a-function b/Lang/Retro/Time-a-function new file mode 120000 index 0000000000..ea46253061 --- /dev/null +++ b/Lang/Retro/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Retro \ No newline at end of file diff --git a/Lang/Retro/Tokenize-a-string b/Lang/Retro/Tokenize-a-string new file mode 120000 index 0000000000..f5dbf3a3f9 --- /dev/null +++ b/Lang/Retro/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Retro \ No newline at end of file diff --git a/Lang/Retro/Towers-of-Hanoi b/Lang/Retro/Towers-of-Hanoi new file mode 120000 index 0000000000..5122dfec76 --- /dev/null +++ b/Lang/Retro/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Retro \ No newline at end of file diff --git a/Lang/Retro/URL-decoding b/Lang/Retro/URL-decoding new file mode 120000 index 0000000000..0f399cf97c --- /dev/null +++ b/Lang/Retro/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Retro \ No newline at end of file diff --git a/Lang/Retro/Unicode-variable-names b/Lang/Retro/Unicode-variable-names new file mode 120000 index 0000000000..d82cdc252f --- /dev/null +++ b/Lang/Retro/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Retro \ No newline at end of file diff --git a/Lang/Retro/User-input-Text b/Lang/Retro/User-input-Text new file mode 120000 index 0000000000..61f951332d --- /dev/null +++ b/Lang/Retro/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Retro \ No newline at end of file diff --git a/Lang/Rhope/Sockets b/Lang/Rhope/Sockets new file mode 120000 index 0000000000..f249a02209 --- /dev/null +++ b/Lang/Rhope/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Rhope \ No newline at end of file diff --git a/Lang/Ruby/SHA-1 b/Lang/Ruby/SHA-1 new file mode 120000 index 0000000000..557b7ae056 --- /dev/null +++ b/Lang/Ruby/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Ruby \ No newline at end of file diff --git a/Lang/Ruby/SHA-256 b/Lang/Ruby/SHA-256 new file mode 120000 index 0000000000..29b975b5bf --- /dev/null +++ b/Lang/Ruby/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Ruby \ No newline at end of file diff --git a/Lang/Ruby/SOAP b/Lang/Ruby/SOAP new file mode 120000 index 0000000000..5d21fe4f44 --- /dev/null +++ b/Lang/Ruby/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Seven-sided-dice-from-five-sided-dice b/Lang/Ruby/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..6952133920 --- /dev/null +++ b/Lang/Ruby/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Shell-one-liner b/Lang/Ruby/Shell-one-liner new file mode 120000 index 0000000000..23a2351bff --- /dev/null +++ b/Lang/Ruby/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Short-circuit-evaluation b/Lang/Ruby/Short-circuit-evaluation new file mode 120000 index 0000000000..ae0899be91 --- /dev/null +++ b/Lang/Ruby/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Show-the-epoch b/Lang/Ruby/Show-the-epoch new file mode 120000 index 0000000000..83daaa1188 --- /dev/null +++ b/Lang/Ruby/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sierpinski-carpet b/Lang/Ruby/Sierpinski-carpet new file mode 120000 index 0000000000..1721b9e028 --- /dev/null +++ b/Lang/Ruby/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sierpinski-triangle b/Lang/Ruby/Sierpinski-triangle new file mode 120000 index 0000000000..abb252edc1 --- /dev/null +++ b/Lang/Ruby/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sierpinski-triangle-Graphical b/Lang/Ruby/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..08569e87f8 --- /dev/null +++ b/Lang/Ruby/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sieve-of-Eratosthenes b/Lang/Ruby/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..a087317310 --- /dev/null +++ b/Lang/Ruby/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Simple-database b/Lang/Ruby/Simple-database new file mode 120000 index 0000000000..6f0ed8c956 --- /dev/null +++ b/Lang/Ruby/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Simple-windowed-application b/Lang/Ruby/Simple-windowed-application new file mode 120000 index 0000000000..0834986b78 --- /dev/null +++ b/Lang/Ruby/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Singleton b/Lang/Ruby/Singleton new file mode 120000 index 0000000000..4e9bb0c1c5 --- /dev/null +++ b/Lang/Ruby/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Singly-linked-list-Element-definition b/Lang/Ruby/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..0a32aaf81f --- /dev/null +++ b/Lang/Ruby/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Singly-linked-list-Element-insertion b/Lang/Ruby/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..58ace2bbf8 --- /dev/null +++ b/Lang/Ruby/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Singly-linked-list-Traversal b/Lang/Ruby/Singly-linked-list-Traversal new file mode 120000 index 0000000000..1f4f2b025a --- /dev/null +++ b/Lang/Ruby/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sleep b/Lang/Ruby/Sleep new file mode 120000 index 0000000000..59c26b5c39 --- /dev/null +++ b/Lang/Ruby/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sockets b/Lang/Ruby/Sockets new file mode 120000 index 0000000000..49143c052f --- /dev/null +++ b/Lang/Ruby/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Solve-a-Hidato-puzzle b/Lang/Ruby/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..131a92cc16 --- /dev/null +++ b/Lang/Ruby/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sort-an-array-of-composite-structures b/Lang/Ruby/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..c6fcba7672 --- /dev/null +++ b/Lang/Ruby/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sort-an-integer-array b/Lang/Ruby/Sort-an-integer-array new file mode 120000 index 0000000000..809b478a4b --- /dev/null +++ b/Lang/Ruby/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sort-disjoint-sublist b/Lang/Ruby/Sort-disjoint-sublist new file mode 120000 index 0000000000..419b0127a5 --- /dev/null +++ b/Lang/Ruby/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sort-stability b/Lang/Ruby/Sort-stability new file mode 120000 index 0000000000..bd1fcb983e --- /dev/null +++ b/Lang/Ruby/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sort-using-a-custom-comparator b/Lang/Ruby/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..b333847774 --- /dev/null +++ b/Lang/Ruby/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Bead-sort b/Lang/Ruby/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5b3a6e2b81 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Bogosort b/Lang/Ruby/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..3791590e0a --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Bubble-sort b/Lang/Ruby/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..f68aea0c25 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Cocktail-sort b/Lang/Ruby/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..c5264ef1a5 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Comb-sort b/Lang/Ruby/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..df61b334eb --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Counting-sort b/Lang/Ruby/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..30a20c466f --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Gnome-sort b/Lang/Ruby/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a9e9f74371 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Heapsort b/Lang/Ruby/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..12d9c42d10 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Insertion-sort b/Lang/Ruby/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..95e5d34fbe --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Merge-sort b/Lang/Ruby/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..956c914975 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Pancake-sort b/Lang/Ruby/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..ffd22402c1 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Permutation-sort b/Lang/Ruby/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..ff0f843f90 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Quicksort b/Lang/Ruby/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ff942f72b2 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Radix-sort b/Lang/Ruby/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..ba6c98681a --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Selection-sort b/Lang/Ruby/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..a6c655ec3e --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Shell-sort b/Lang/Ruby/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..c431d04b5b --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Sleep-sort b/Lang/Ruby/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..1b14b9b075 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Stooge-sort b/Lang/Ruby/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..de8271830b --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-algorithms-Strand-sort b/Lang/Ruby/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..317838c0b2 --- /dev/null +++ b/Lang/Ruby/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Soundex b/Lang/Ruby/Soundex new file mode 120000 index 0000000000..22d3e776d5 --- /dev/null +++ b/Lang/Ruby/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Speech-synthesis b/Lang/Ruby/Speech-synthesis new file mode 120000 index 0000000000..7a5786045c --- /dev/null +++ b/Lang/Ruby/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Spiral-matrix b/Lang/Ruby/Spiral-matrix new file mode 120000 index 0000000000..6513ecb675 --- /dev/null +++ b/Lang/Ruby/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stable-marriage-problem b/Lang/Ruby/Stable-marriage-problem new file mode 120000 index 0000000000..1feb9c623a --- /dev/null +++ b/Lang/Ruby/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stack b/Lang/Ruby/Stack new file mode 120000 index 0000000000..782b5ac8ea --- /dev/null +++ b/Lang/Ruby/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stack-traces b/Lang/Ruby/Stack-traces new file mode 120000 index 0000000000..ab7d96434e --- /dev/null +++ b/Lang/Ruby/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stair-climbing-puzzle b/Lang/Ruby/Stair-climbing-puzzle new file mode 120000 index 0000000000..fb423eebf4 --- /dev/null +++ b/Lang/Ruby/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Standard-deviation b/Lang/Ruby/Standard-deviation new file mode 120000 index 0000000000..b5b555580b --- /dev/null +++ b/Lang/Ruby/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Stem-and-leaf-plot b/Lang/Ruby/Stem-and-leaf-plot new file mode 120000 index 0000000000..ed026ccd5b --- /dev/null +++ b/Lang/Ruby/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-case b/Lang/Ruby/String-case new file mode 120000 index 0000000000..710ce3545f --- /dev/null +++ b/Lang/Ruby/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-concatenation b/Lang/Ruby/String-concatenation new file mode 120000 index 0000000000..959cb1b69c --- /dev/null +++ b/Lang/Ruby/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-interpolation--included- b/Lang/Ruby/String-interpolation--included- new file mode 120000 index 0000000000..0a42341bf2 --- /dev/null +++ b/Lang/Ruby/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Ruby \ No newline at end of file diff --git a/Lang/Ruby/String-length b/Lang/Ruby/String-length new file mode 120000 index 0000000000..4643a6ffab --- /dev/null +++ b/Lang/Ruby/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strip-a-set-of-characters-from-a-string b/Lang/Ruby/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b2775cd9c7 --- /dev/null +++ b/Lang/Ruby/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strip-block-comments b/Lang/Ruby/Strip-block-comments new file mode 120000 index 0000000000..5f21e7d1d6 --- /dev/null +++ b/Lang/Ruby/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strip-comments-from-a-string b/Lang/Ruby/Strip-comments-from-a-string new file mode 120000 index 0000000000..7fbade4020 --- /dev/null +++ b/Lang/Ruby/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Ruby/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..44db4e57ef --- /dev/null +++ b/Lang/Ruby/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Ruby/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..22b027ca06 --- /dev/null +++ b/Lang/Ruby/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Substring b/Lang/Ruby/Substring new file mode 120000 index 0000000000..4c9892207b --- /dev/null +++ b/Lang/Ruby/Substring @@ -0,0 +1 @@ +../../Task/Substring/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Substring-Top-and-tail b/Lang/Ruby/Substring-Top-and-tail new file mode 120000 index 0000000000..9f702893b1 --- /dev/null +++ b/Lang/Ruby/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Subtractive-generator b/Lang/Ruby/Subtractive-generator new file mode 120000 index 0000000000..bee8fea3a5 --- /dev/null +++ b/Lang/Ruby/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sudoku b/Lang/Ruby/Sudoku new file mode 120000 index 0000000000..6d2ec4f817 --- /dev/null +++ b/Lang/Ruby/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sum-and-product-of-an-array b/Lang/Ruby/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c676e594bc --- /dev/null +++ b/Lang/Ruby/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sum-digits-of-an-integer b/Lang/Ruby/Sum-digits-of-an-integer new file mode 120000 index 0000000000..32672a081c --- /dev/null +++ b/Lang/Ruby/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sum-of-a-series b/Lang/Ruby/Sum-of-a-series new file mode 120000 index 0000000000..d5b623b8a9 --- /dev/null +++ b/Lang/Ruby/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sum-of-squares b/Lang/Ruby/Sum-of-squares new file mode 120000 index 0000000000..27d2e138f8 --- /dev/null +++ b/Lang/Ruby/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sutherland-Hodgman-polygon-clipping b/Lang/Ruby/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..e013cae62a --- /dev/null +++ b/Lang/Ruby/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Symmetric-difference b/Lang/Ruby/Symmetric-difference new file mode 120000 index 0000000000..4796a64152 --- /dev/null +++ b/Lang/Ruby/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Synchronous-concurrency b/Lang/Ruby/Synchronous-concurrency new file mode 120000 index 0000000000..0ed6489849 --- /dev/null +++ b/Lang/Ruby/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Ruby \ No newline at end of file diff --git a/Lang/Ruby/System-time b/Lang/Ruby/System-time new file mode 120000 index 0000000000..ad75ad3574 --- /dev/null +++ b/Lang/Ruby/System-time @@ -0,0 +1 @@ +../../Task/System-time/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Table-creation-Postal-addresses b/Lang/Ruby/Table-creation-Postal-addresses new file mode 120000 index 0000000000..39c5eca97f --- /dev/null +++ b/Lang/Ruby/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Take-notes-on-the-command-line b/Lang/Ruby/Take-notes-on-the-command-line new file mode 120000 index 0000000000..56879e95ea --- /dev/null +++ b/Lang/Ruby/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Clear-the-screen b/Lang/Ruby/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..8ccbe7cd7a --- /dev/null +++ b/Lang/Ruby/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Coloured-text b/Lang/Ruby/Terminal-control-Coloured-text new file mode 120000 index 0000000000..92f506504c --- /dev/null +++ b/Lang/Ruby/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Cursor-positioning b/Lang/Ruby/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..c482f16634 --- /dev/null +++ b/Lang/Ruby/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Dimensions b/Lang/Ruby/Terminal-control-Dimensions new file mode 120000 index 0000000000..ad85194d46 --- /dev/null +++ b/Lang/Ruby/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Terminal-control-Ringing-the-terminal-bell b/Lang/Ruby/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b3b01f470a --- /dev/null +++ b/Lang/Ruby/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Ternary-logic b/Lang/Ruby/Ternary-logic new file mode 120000 index 0000000000..1034ae36f3 --- /dev/null +++ b/Lang/Ruby/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Test-a-function b/Lang/Ruby/Test-a-function new file mode 120000 index 0000000000..15b4422db7 --- /dev/null +++ b/Lang/Ruby/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Text-processing-1 b/Lang/Ruby/Text-processing-1 new file mode 120000 index 0000000000..1138c717d7 --- /dev/null +++ b/Lang/Ruby/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Text-processing-2 b/Lang/Ruby/Text-processing-2 new file mode 120000 index 0000000000..bee0538bb2 --- /dev/null +++ b/Lang/Ruby/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Text-processing-Max-licenses-in-use b/Lang/Ruby/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..562dfba5bd --- /dev/null +++ b/Lang/Ruby/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Tic-tac-toe b/Lang/Ruby/Tic-tac-toe new file mode 120000 index 0000000000..941668322e --- /dev/null +++ b/Lang/Ruby/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Time-a-function b/Lang/Ruby/Time-a-function new file mode 120000 index 0000000000..6961498a93 --- /dev/null +++ b/Lang/Ruby/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Tokenize-a-string b/Lang/Ruby/Tokenize-a-string new file mode 120000 index 0000000000..fc60222023 --- /dev/null +++ b/Lang/Ruby/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Top-rank-per-group b/Lang/Ruby/Top-rank-per-group new file mode 120000 index 0000000000..653b2e5241 --- /dev/null +++ b/Lang/Ruby/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Topological-sort b/Lang/Ruby/Topological-sort new file mode 120000 index 0000000000..1c77e64015 --- /dev/null +++ b/Lang/Ruby/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Towers-of-Hanoi b/Lang/Ruby/Towers-of-Hanoi new file mode 120000 index 0000000000..97e8c0e023 --- /dev/null +++ b/Lang/Ruby/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Trabb-Pardo-Knuth-algorithm b/Lang/Ruby/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..2b3a4d8c42 --- /dev/null +++ b/Lang/Ruby/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Tree-traversal b/Lang/Ruby/Tree-traversal new file mode 120000 index 0000000000..88e8ce159d --- /dev/null +++ b/Lang/Ruby/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Trigonometric-functions b/Lang/Ruby/Trigonometric-functions new file mode 120000 index 0000000000..6436c0b301 --- /dev/null +++ b/Lang/Ruby/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Truncatable-primes b/Lang/Ruby/Truncatable-primes new file mode 120000 index 0000000000..78c61fc478 --- /dev/null +++ b/Lang/Ruby/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Truncate-a-file b/Lang/Ruby/Truncate-a-file new file mode 120000 index 0000000000..797cbd60ba --- /dev/null +++ b/Lang/Ruby/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Twelve-statements b/Lang/Ruby/Twelve-statements new file mode 120000 index 0000000000..3718c16bf4 --- /dev/null +++ b/Lang/Ruby/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Ruby \ No newline at end of file diff --git a/Lang/Ruby/URL-decoding b/Lang/Ruby/URL-decoding new file mode 120000 index 0000000000..cb1f2b17ea --- /dev/null +++ b/Lang/Ruby/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Ruby \ No newline at end of file diff --git a/Lang/Ruby/URL-encoding b/Lang/Ruby/URL-encoding new file mode 120000 index 0000000000..75d0b98450 --- /dev/null +++ b/Lang/Ruby/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Undefined-values b/Lang/Ruby/Undefined-values new file mode 120000 index 0000000000..6ee3a334a3 --- /dev/null +++ b/Lang/Ruby/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Unicode-variable-names b/Lang/Ruby/Unicode-variable-names new file mode 120000 index 0000000000..704f45ec4c --- /dev/null +++ b/Lang/Ruby/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Universal-Turing-machine b/Lang/Ruby/Universal-Turing-machine new file mode 120000 index 0000000000..a566a6f9d0 --- /dev/null +++ b/Lang/Ruby/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Update-a-configuration-file b/Lang/Ruby/Update-a-configuration-file new file mode 120000 index 0000000000..abe5bac0a7 --- /dev/null +++ b/Lang/Ruby/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Ruby \ No newline at end of file diff --git a/Lang/Ruby/User-input-Graphical b/Lang/Ruby/User-input-Graphical new file mode 120000 index 0000000000..c199e98fca --- /dev/null +++ b/Lang/Ruby/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Ruby \ No newline at end of file diff --git a/Lang/Ruby/User-input-Text b/Lang/Ruby/User-input-Text new file mode 120000 index 0000000000..15b4dcfbe6 --- /dev/null +++ b/Lang/Ruby/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Vampire-number b/Lang/Ruby/Vampire-number new file mode 120000 index 0000000000..aad9d88f4a --- /dev/null +++ b/Lang/Ruby/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Van-der-Corput-sequence b/Lang/Ruby/Van-der-Corput-sequence new file mode 120000 index 0000000000..1da0cca05d --- /dev/null +++ b/Lang/Ruby/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Variable-length-quantity b/Lang/Ruby/Variable-length-quantity new file mode 120000 index 0000000000..7cdd3ca966 --- /dev/null +++ b/Lang/Ruby/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Variables b/Lang/Ruby/Variables new file mode 120000 index 0000000000..cd747735dc --- /dev/null +++ b/Lang/Ruby/Variables @@ -0,0 +1 @@ +../../Task/Variables/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Variadic-function b/Lang/Ruby/Variadic-function new file mode 120000 index 0000000000..8a81388238 --- /dev/null +++ b/Lang/Ruby/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Vector-products b/Lang/Ruby/Vector-products new file mode 120000 index 0000000000..abf4c4c0a0 --- /dev/null +++ b/Lang/Ruby/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Verify-distribution-uniformity-Naive b/Lang/Ruby/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..a7e1c44667 --- /dev/null +++ b/Lang/Ruby/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Vigen-re-cipher b/Lang/Ruby/Vigen-re-cipher new file mode 120000 index 0000000000..890207655c --- /dev/null +++ b/Lang/Ruby/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Voronoi-diagram b/Lang/Ruby/Voronoi-diagram new file mode 120000 index 0000000000..8bb33e9736 --- /dev/null +++ b/Lang/Ruby/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Walk-a-directory-Non-recursively b/Lang/Ruby/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..dbc1837145 --- /dev/null +++ b/Lang/Ruby/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Walk-a-directory-Recursively b/Lang/Ruby/Walk-a-directory-Recursively new file mode 120000 index 0000000000..28878e1c98 --- /dev/null +++ b/Lang/Ruby/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Web-scraping b/Lang/Ruby/Web-scraping new file mode 120000 index 0000000000..1afa8dfd1f --- /dev/null +++ b/Lang/Ruby/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Window-creation b/Lang/Ruby/Window-creation new file mode 120000 index 0000000000..b1c562c447 --- /dev/null +++ b/Lang/Ruby/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Word-wrap b/Lang/Ruby/Word-wrap new file mode 120000 index 0000000000..42f3e2d8e1 --- /dev/null +++ b/Lang/Ruby/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Write-float-arrays-to-a-text-file b/Lang/Ruby/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..bc4bf41a67 --- /dev/null +++ b/Lang/Ruby/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Write-to-Windows-event-log b/Lang/Ruby/Write-to-Windows-event-log new file mode 120000 index 0000000000..0d6bdb30bf --- /dev/null +++ b/Lang/Ruby/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Ruby \ No newline at end of file diff --git a/Lang/Ruby/XML-DOM-serialization b/Lang/Ruby/XML-DOM-serialization new file mode 120000 index 0000000000..3f59962590 --- /dev/null +++ b/Lang/Ruby/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Ruby \ No newline at end of file diff --git a/Lang/Ruby/XML-Input b/Lang/Ruby/XML-Input new file mode 120000 index 0000000000..d8c7a4096b --- /dev/null +++ b/Lang/Ruby/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Ruby \ No newline at end of file diff --git a/Lang/Ruby/XML-Output b/Lang/Ruby/XML-Output new file mode 120000 index 0000000000..910a227158 --- /dev/null +++ b/Lang/Ruby/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Ruby \ No newline at end of file diff --git a/Lang/Ruby/XML-XPath b/Lang/Ruby/XML-XPath new file mode 120000 index 0000000000..6b21222799 --- /dev/null +++ b/Lang/Ruby/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Xiaolin-Wus-line-algorithm b/Lang/Ruby/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..a93ca91b9a --- /dev/null +++ b/Lang/Ruby/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Y-combinator b/Lang/Ruby/Y-combinator new file mode 120000 index 0000000000..8c8faa1664 --- /dev/null +++ b/Lang/Ruby/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Yahoo--search-interface b/Lang/Ruby/Yahoo--search-interface new file mode 120000 index 0000000000..6ce97c972d --- /dev/null +++ b/Lang/Ruby/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Yin-and-yang b/Lang/Ruby/Yin-and-yang new file mode 120000 index 0000000000..5073fcf80b --- /dev/null +++ b/Lang/Ruby/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Zig-zag-matrix b/Lang/Ruby/Zig-zag-matrix new file mode 120000 index 0000000000..1f0e32f55b --- /dev/null +++ b/Lang/Ruby/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Shell-one-liner b/Lang/Run-BASIC/Shell-one-liner new file mode 120000 index 0000000000..7eae2775b6 --- /dev/null +++ b/Lang/Run-BASIC/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Show-the-epoch b/Lang/Run-BASIC/Show-the-epoch new file mode 120000 index 0000000000..a52b207ab7 --- /dev/null +++ b/Lang/Run-BASIC/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sierpinski-carpet b/Lang/Run-BASIC/Sierpinski-carpet new file mode 120000 index 0000000000..81deaccd00 --- /dev/null +++ b/Lang/Run-BASIC/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sierpinski-triangle-Graphical b/Lang/Run-BASIC/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..dd1e33e743 --- /dev/null +++ b/Lang/Run-BASIC/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sieve-of-Eratosthenes b/Lang/Run-BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d7a7a30da8 --- /dev/null +++ b/Lang/Run-BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Simple-database b/Lang/Run-BASIC/Simple-database new file mode 120000 index 0000000000..31689aff7e --- /dev/null +++ b/Lang/Run-BASIC/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Simple-windowed-application b/Lang/Run-BASIC/Simple-windowed-application new file mode 120000 index 0000000000..c54317edc1 --- /dev/null +++ b/Lang/Run-BASIC/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Singly-linked-list-Element-definition b/Lang/Run-BASIC/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..ef60567139 --- /dev/null +++ b/Lang/Run-BASIC/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Singly-linked-list-Traversal b/Lang/Run-BASIC/Singly-linked-list-Traversal new file mode 120000 index 0000000000..9ab6022dd0 --- /dev/null +++ b/Lang/Run-BASIC/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sort-an-array-of-composite-structures b/Lang/Run-BASIC/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..edc64cfab5 --- /dev/null +++ b/Lang/Run-BASIC/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sort-disjoint-sublist b/Lang/Run-BASIC/Sort-disjoint-sublist new file mode 120000 index 0000000000..44babd4c7b --- /dev/null +++ b/Lang/Run-BASIC/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Bubble-sort b/Lang/Run-BASIC/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..dcebc982d9 --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Cocktail-sort b/Lang/Run-BASIC/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..64a84e177c --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Insertion-sort b/Lang/Run-BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..31b290e5d4 --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Quicksort b/Lang/Run-BASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..91270d9781 --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Selection-sort b/Lang/Run-BASIC/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..3cb9c60cc1 --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sorting-algorithms-Shell-sort b/Lang/Run-BASIC/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..361b24010f --- /dev/null +++ b/Lang/Run-BASIC/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Soundex b/Lang/Run-BASIC/Soundex new file mode 120000 index 0000000000..15dc6c3d63 --- /dev/null +++ b/Lang/Run-BASIC/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Stack b/Lang/Run-BASIC/Stack new file mode 120000 index 0000000000..78b532febc --- /dev/null +++ b/Lang/Run-BASIC/Stack @@ -0,0 +1 @@ +../../Task/Stack/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Standard-deviation b/Lang/Run-BASIC/Standard-deviation new file mode 120000 index 0000000000..9d615fc9cc --- /dev/null +++ b/Lang/Run-BASIC/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-case b/Lang/Run-BASIC/String-case new file mode 120000 index 0000000000..e649a56195 --- /dev/null +++ b/Lang/Run-BASIC/String-case @@ -0,0 +1 @@ +../../Task/String-case/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-comparison b/Lang/Run-BASIC/String-comparison new file mode 120000 index 0000000000..cd4887cdf9 --- /dev/null +++ b/Lang/Run-BASIC/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-interpolation--included- b/Lang/Run-BASIC/String-interpolation--included- new file mode 120000 index 0000000000..96a7668615 --- /dev/null +++ b/Lang/Run-BASIC/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/String-length b/Lang/Run-BASIC/String-length new file mode 120000 index 0000000000..83c85bc3f3 --- /dev/null +++ b/Lang/Run-BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Run-BASIC/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..a68dd673c9 --- /dev/null +++ b/Lang/Run-BASIC/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Run-BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..7857931057 --- /dev/null +++ b/Lang/Run-BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Substring b/Lang/Run-BASIC/Substring new file mode 120000 index 0000000000..cc481c2bc0 --- /dev/null +++ b/Lang/Run-BASIC/Substring @@ -0,0 +1 @@ +../../Task/Substring/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Substring-Top-and-tail b/Lang/Run-BASIC/Substring-Top-and-tail new file mode 120000 index 0000000000..44e0107e7d --- /dev/null +++ b/Lang/Run-BASIC/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-and-product-of-an-array b/Lang/Run-BASIC/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9202379308 --- /dev/null +++ b/Lang/Run-BASIC/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-digits-of-an-integer b/Lang/Run-BASIC/Sum-digits-of-an-integer new file mode 120000 index 0000000000..41c990fac8 --- /dev/null +++ b/Lang/Run-BASIC/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-of-a-series b/Lang/Run-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..9c10d44356 --- /dev/null +++ b/Lang/Run-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Sum-of-squares b/Lang/Run-BASIC/Sum-of-squares new file mode 120000 index 0000000000..1c547d09ac --- /dev/null +++ b/Lang/Run-BASIC/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Table-creation-Postal-addresses b/Lang/Run-BASIC/Table-creation-Postal-addresses new file mode 120000 index 0000000000..d40ca4efa8 --- /dev/null +++ b/Lang/Run-BASIC/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Temperature-conversion b/Lang/Run-BASIC/Temperature-conversion new file mode 120000 index 0000000000..d6dbaf37ff --- /dev/null +++ b/Lang/Run-BASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Terminal-control-Inverse-video b/Lang/Run-BASIC/Terminal-control-Inverse-video new file mode 120000 index 0000000000..92c96c0f48 --- /dev/null +++ b/Lang/Run-BASIC/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Ternary-logic b/Lang/Run-BASIC/Ternary-logic new file mode 120000 index 0000000000..41c7a88054 --- /dev/null +++ b/Lang/Run-BASIC/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Text-processing-Max-licenses-in-use b/Lang/Run-BASIC/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..a709b74dda --- /dev/null +++ b/Lang/Run-BASIC/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Tic-tac-toe b/Lang/Run-BASIC/Tic-tac-toe new file mode 120000 index 0000000000..f85f3100a0 --- /dev/null +++ b/Lang/Run-BASIC/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Tokenize-a-string b/Lang/Run-BASIC/Tokenize-a-string new file mode 120000 index 0000000000..8f73f67ff1 --- /dev/null +++ b/Lang/Run-BASIC/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Top-rank-per-group b/Lang/Run-BASIC/Top-rank-per-group new file mode 120000 index 0000000000..87b8da8e19 --- /dev/null +++ b/Lang/Run-BASIC/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Towers-of-Hanoi b/Lang/Run-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..45d385b8db --- /dev/null +++ b/Lang/Run-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Trigonometric-functions b/Lang/Run-BASIC/Trigonometric-functions new file mode 120000 index 0000000000..1bf96ca835 --- /dev/null +++ b/Lang/Run-BASIC/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/URL-encoding b/Lang/Run-BASIC/URL-encoding new file mode 120000 index 0000000000..c75bd6f0ca --- /dev/null +++ b/Lang/Run-BASIC/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Verify-distribution-uniformity-Naive b/Lang/Run-BASIC/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..0b628f738a --- /dev/null +++ b/Lang/Run-BASIC/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Web-scraping b/Lang/Run-BASIC/Web-scraping new file mode 120000 index 0000000000..d3f7d640be --- /dev/null +++ b/Lang/Run-BASIC/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Window-creation b/Lang/Run-BASIC/Window-creation new file mode 120000 index 0000000000..d7e65e59cb --- /dev/null +++ b/Lang/Run-BASIC/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Word-wrap b/Lang/Run-BASIC/Word-wrap new file mode 120000 index 0000000000..ea1001a3f4 --- /dev/null +++ b/Lang/Run-BASIC/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Write-float-arrays-to-a-text-file b/Lang/Run-BASIC/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..285e419d41 --- /dev/null +++ b/Lang/Run-BASIC/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/XML-Input b/Lang/Run-BASIC/XML-Input new file mode 120000 index 0000000000..56f6a43fdf --- /dev/null +++ b/Lang/Run-BASIC/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Yahoo--search-interface b/Lang/Run-BASIC/Yahoo--search-interface new file mode 120000 index 0000000000..c990e34b68 --- /dev/null +++ b/Lang/Run-BASIC/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/Singly-linked-list-Element-definition b/Lang/Rust/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..ae0a81e4f9 --- /dev/null +++ b/Lang/Rust/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Sleep-sort b/Lang/Rust/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..02ea9e0410 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Vigen-re-cipher b/Lang/Rust/Vigen-re-cipher new file mode 120000 index 0000000000..28fd201706 --- /dev/null +++ b/Lang/Rust/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Rust \ No newline at end of file diff --git a/Lang/SAS/String-concatenation b/Lang/SAS/String-concatenation new file mode 120000 index 0000000000..1234a283cf --- /dev/null +++ b/Lang/SAS/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/SAS \ No newline at end of file diff --git a/Lang/SAS/String-length b/Lang/SAS/String-length new file mode 120000 index 0000000000..0d9993ee6f --- /dev/null +++ b/Lang/SAS/String-length @@ -0,0 +1 @@ +../../Task/String-length/SAS \ No newline at end of file diff --git a/Lang/SAS/Substring b/Lang/SAS/Substring new file mode 120000 index 0000000000..e40dc28a4c --- /dev/null +++ b/Lang/SAS/Substring @@ -0,0 +1 @@ +../../Task/Substring/SAS \ No newline at end of file diff --git a/Lang/SAS/Sum-and-product-of-an-array b/Lang/SAS/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5750af74cd --- /dev/null +++ b/Lang/SAS/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/SAS \ No newline at end of file diff --git a/Lang/SAS/Sum-of-a-series b/Lang/SAS/Sum-of-a-series new file mode 120000 index 0000000000..fa4e403bee --- /dev/null +++ b/Lang/SAS/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/SAS \ No newline at end of file diff --git a/Lang/SAS/Table-creation-Postal-addresses b/Lang/SAS/Table-creation-Postal-addresses new file mode 120000 index 0000000000..dc47d90f2f --- /dev/null +++ b/Lang/SAS/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/SAS \ No newline at end of file diff --git a/Lang/SAS/Trigonometric-functions b/Lang/SAS/Trigonometric-functions new file mode 120000 index 0000000000..039e399877 --- /dev/null +++ b/Lang/SAS/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/SAS \ No newline at end of file diff --git a/Lang/SAS/Write-float-arrays-to-a-text-file b/Lang/SAS/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..f0665ff6f4 --- /dev/null +++ b/Lang/SAS/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/SAS \ No newline at end of file diff --git a/Lang/SETL/Sorting-algorithms-Quicksort b/Lang/SETL/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..98b4545fb2 --- /dev/null +++ b/Lang/SETL/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/SETL \ No newline at end of file diff --git a/Lang/SETL/Sum-and-product-of-an-array b/Lang/SETL/Sum-and-product-of-an-array new file mode 120000 index 0000000000..59e68a9912 --- /dev/null +++ b/Lang/SETL/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/SETL \ No newline at end of file diff --git a/Lang/SMEQL/Top-rank-per-group b/Lang/SMEQL/Top-rank-per-group new file mode 120000 index 0000000000..2c47cd0922 --- /dev/null +++ b/Lang/SMEQL/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/SMEQL \ No newline at end of file diff --git a/Lang/SNOBOL4/Shell-one-liner b/Lang/SNOBOL4/Shell-one-liner new file mode 120000 index 0000000000..3047db6bca --- /dev/null +++ b/Lang/SNOBOL4/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Short-circuit-evaluation b/Lang/SNOBOL4/Short-circuit-evaluation new file mode 120000 index 0000000000..9b14115016 --- /dev/null +++ b/Lang/SNOBOL4/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sieve-of-Eratosthenes b/Lang/SNOBOL4/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..516921676b --- /dev/null +++ b/Lang/SNOBOL4/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sorting-algorithms-Bogosort b/Lang/SNOBOL4/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..3f65078ba7 --- /dev/null +++ b/Lang/SNOBOL4/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sorting-algorithms-Bubble-sort b/Lang/SNOBOL4/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ab4b6fdb4e --- /dev/null +++ b/Lang/SNOBOL4/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sorting-algorithms-Insertion-sort b/Lang/SNOBOL4/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4048d47925 --- /dev/null +++ b/Lang/SNOBOL4/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Soundex b/Lang/SNOBOL4/Soundex new file mode 120000 index 0000000000..f89ccf396d --- /dev/null +++ b/Lang/SNOBOL4/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/String-case b/Lang/SNOBOL4/String-case new file mode 120000 index 0000000000..38d4e898b3 --- /dev/null +++ b/Lang/SNOBOL4/String-case @@ -0,0 +1 @@ +../../Task/String-case/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/String-concatenation b/Lang/SNOBOL4/String-concatenation new file mode 120000 index 0000000000..5bae3965cb --- /dev/null +++ b/Lang/SNOBOL4/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/String-interpolation--included- b/Lang/SNOBOL4/String-interpolation--included- new file mode 120000 index 0000000000..c13ecad215 --- /dev/null +++ b/Lang/SNOBOL4/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/String-length b/Lang/SNOBOL4/String-length new file mode 120000 index 0000000000..244b4b2cb7 --- /dev/null +++ b/Lang/SNOBOL4/String-length @@ -0,0 +1 @@ +../../Task/String-length/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Substring b/Lang/SNOBOL4/Substring new file mode 120000 index 0000000000..2b41d4fd7f --- /dev/null +++ b/Lang/SNOBOL4/Substring @@ -0,0 +1 @@ +../../Task/Substring/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Substring-Top-and-tail b/Lang/SNOBOL4/Substring-Top-and-tail new file mode 120000 index 0000000000..08cc8d4603 --- /dev/null +++ b/Lang/SNOBOL4/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sum-and-product-of-an-array b/Lang/SNOBOL4/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4ce784d0e8 --- /dev/null +++ b/Lang/SNOBOL4/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Sum-of-squares b/Lang/SNOBOL4/Sum-of-squares new file mode 120000 index 0000000000..4ca13f413d --- /dev/null +++ b/Lang/SNOBOL4/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/System-time b/Lang/SNOBOL4/System-time new file mode 120000 index 0000000000..1fe09c9e9f --- /dev/null +++ b/Lang/SNOBOL4/System-time @@ -0,0 +1 @@ +../../Task/System-time/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Take-notes-on-the-command-line b/Lang/SNOBOL4/Take-notes-on-the-command-line new file mode 120000 index 0000000000..40e0ff15d0 --- /dev/null +++ b/Lang/SNOBOL4/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Tokenize-a-string b/Lang/SNOBOL4/Tokenize-a-string new file mode 120000 index 0000000000..287935b872 --- /dev/null +++ b/Lang/SNOBOL4/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Towers-of-Hanoi b/Lang/SNOBOL4/Towers-of-Hanoi new file mode 120000 index 0000000000..b0ff3dc40a --- /dev/null +++ b/Lang/SNOBOL4/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/User-input-Text b/Lang/SNOBOL4/User-input-Text new file mode 120000 index 0000000000..6ec7ac82a6 --- /dev/null +++ b/Lang/SNOBOL4/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Variables b/Lang/SNOBOL4/Variables new file mode 120000 index 0000000000..e9d086985e --- /dev/null +++ b/Lang/SNOBOL4/Variables @@ -0,0 +1 @@ +../../Task/Variables/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNUSP/Terminal-control-Ringing-the-terminal-bell b/Lang/SNUSP/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c615b130ef --- /dev/null +++ b/Lang/SNUSP/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/SNUSP \ No newline at end of file diff --git a/Lang/SPARK/Sorting-algorithms-Bubble-sort b/Lang/SPARK/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..6fbd8585ec --- /dev/null +++ b/Lang/SPARK/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/SPARK \ No newline at end of file diff --git a/Lang/SPARK/Stable-marriage-problem b/Lang/SPARK/Stable-marriage-problem new file mode 120000 index 0000000000..5ac4786a8b --- /dev/null +++ b/Lang/SPARK/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/SPARK \ No newline at end of file diff --git a/Lang/SQL/String-case b/Lang/SQL/String-case new file mode 120000 index 0000000000..1f7b00f783 --- /dev/null +++ b/Lang/SQL/String-case @@ -0,0 +1 @@ +../../Task/String-case/SQL \ No newline at end of file diff --git a/Lang/SQL/Sum-of-a-series b/Lang/SQL/Sum-of-a-series new file mode 120000 index 0000000000..e8d73e8825 --- /dev/null +++ b/Lang/SQL/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/SQL \ No newline at end of file diff --git a/Lang/SQL/Sum-of-squares b/Lang/SQL/Sum-of-squares new file mode 120000 index 0000000000..9fd7b85370 --- /dev/null +++ b/Lang/SQL/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/SQL \ No newline at end of file diff --git a/Lang/SQL/Symmetric-difference b/Lang/SQL/Symmetric-difference new file mode 120000 index 0000000000..6b2a4558b7 --- /dev/null +++ b/Lang/SQL/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/SQL \ No newline at end of file diff --git a/Lang/Sather/Short-circuit-evaluation b/Lang/Sather/Short-circuit-evaluation new file mode 120000 index 0000000000..8ab8272aaa --- /dev/null +++ b/Lang/Sather/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Sather \ No newline at end of file diff --git a/Lang/Sather/Sort-using-a-custom-comparator b/Lang/Sather/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..6357b6e296 --- /dev/null +++ b/Lang/Sather/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Sather \ No newline at end of file diff --git a/Lang/Sather/Sorting-algorithms-Bubble-sort b/Lang/Sather/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b86414f690 --- /dev/null +++ b/Lang/Sather/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Sather \ No newline at end of file diff --git a/Lang/Sather/Sorting-algorithms-Comb-sort b/Lang/Sather/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..57d75ca943 --- /dev/null +++ b/Lang/Sather/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Sather \ No newline at end of file diff --git a/Lang/Sather/Sorting-algorithms-Quicksort b/Lang/Sather/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..82e3425b47 --- /dev/null +++ b/Lang/Sather/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Sather \ No newline at end of file diff --git a/Lang/Sather/Stack b/Lang/Sather/Stack new file mode 120000 index 0000000000..5670987de2 --- /dev/null +++ b/Lang/Sather/Stack @@ -0,0 +1 @@ +../../Task/Stack/Sather \ No newline at end of file diff --git a/Lang/Sather/String-concatenation b/Lang/Sather/String-concatenation new file mode 120000 index 0000000000..588e27d689 --- /dev/null +++ b/Lang/Sather/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Sather \ No newline at end of file diff --git a/Lang/Sather/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Sather/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..aa78ce835b --- /dev/null +++ b/Lang/Sather/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Sather \ No newline at end of file diff --git a/Lang/Sather/Substring b/Lang/Sather/Substring new file mode 120000 index 0000000000..61df0930ce --- /dev/null +++ b/Lang/Sather/Substring @@ -0,0 +1 @@ +../../Task/Substring/Sather \ No newline at end of file diff --git a/Lang/Sather/Sum-and-product-of-an-array b/Lang/Sather/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c553679217 --- /dev/null +++ b/Lang/Sather/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Sather \ No newline at end of file diff --git a/Lang/Sather/Sum-of-squares b/Lang/Sather/Sum-of-squares new file mode 120000 index 0000000000..125cdf9b3d --- /dev/null +++ b/Lang/Sather/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Sather \ No newline at end of file diff --git a/Lang/Sather/Towers-of-Hanoi b/Lang/Sather/Towers-of-Hanoi new file mode 120000 index 0000000000..812f737777 --- /dev/null +++ b/Lang/Sather/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Sather \ No newline at end of file diff --git a/Lang/Scala/Shell-one-liner b/Lang/Scala/Shell-one-liner new file mode 120000 index 0000000000..74a2270446 --- /dev/null +++ b/Lang/Scala/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Scala \ No newline at end of file diff --git a/Lang/Scala/Short-circuit-evaluation b/Lang/Scala/Short-circuit-evaluation new file mode 120000 index 0000000000..a3c8163bfa --- /dev/null +++ b/Lang/Scala/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Scala \ No newline at end of file diff --git a/Lang/Scala/Show-the-epoch b/Lang/Scala/Show-the-epoch new file mode 120000 index 0000000000..ebc2307518 --- /dev/null +++ b/Lang/Scala/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Scala \ No newline at end of file diff --git a/Lang/Scala/Sierpinski-carpet b/Lang/Scala/Sierpinski-carpet new file mode 120000 index 0000000000..84813653db --- /dev/null +++ b/Lang/Scala/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Scala \ No newline at end of file diff --git a/Lang/Scala/Sierpinski-triangle b/Lang/Scala/Sierpinski-triangle new file mode 120000 index 0000000000..8550cd53be --- /dev/null +++ b/Lang/Scala/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Scala \ No newline at end of file diff --git a/Lang/Scala/Sieve-of-Eratosthenes b/Lang/Scala/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..912600bbab --- /dev/null +++ b/Lang/Scala/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Scala \ No newline at end of file diff --git a/Lang/Scala/Simple-windowed-application b/Lang/Scala/Simple-windowed-application new file mode 120000 index 0000000000..8146f4a380 --- /dev/null +++ b/Lang/Scala/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Scala \ No newline at end of file diff --git a/Lang/Scala/Singleton b/Lang/Scala/Singleton new file mode 120000 index 0000000000..cd7b61ef3d --- /dev/null +++ b/Lang/Scala/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Scala \ No newline at end of file diff --git a/Lang/Scala/Singly-linked-list-Element-definition b/Lang/Scala/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..9ea0562f3c --- /dev/null +++ b/Lang/Scala/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Scala \ No newline at end of file diff --git a/Lang/Scala/Singly-linked-list-Element-insertion b/Lang/Scala/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..ac98b071c8 --- /dev/null +++ b/Lang/Scala/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Scala \ No newline at end of file diff --git a/Lang/Scala/Singly-linked-list-Traversal b/Lang/Scala/Singly-linked-list-Traversal new file mode 120000 index 0000000000..d3bbd16e0e --- /dev/null +++ b/Lang/Scala/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Scala \ No newline at end of file diff --git a/Lang/Scala/Sleep b/Lang/Scala/Sleep new file mode 120000 index 0000000000..6121064b32 --- /dev/null +++ b/Lang/Scala/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Scala \ No newline at end of file diff --git a/Lang/Scala/Sort-an-integer-array b/Lang/Scala/Sort-an-integer-array new file mode 120000 index 0000000000..cdd69455f0 --- /dev/null +++ b/Lang/Scala/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Scala \ No newline at end of file diff --git a/Lang/Scala/Sort-stability b/Lang/Scala/Sort-stability new file mode 120000 index 0000000000..940a3da6ab --- /dev/null +++ b/Lang/Scala/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Scala \ No newline at end of file diff --git a/Lang/Scala/Sort-using-a-custom-comparator b/Lang/Scala/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..9df4f46787 --- /dev/null +++ b/Lang/Scala/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Bogosort b/Lang/Scala/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..4521c7f22a --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Bubble-sort b/Lang/Scala/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..709e1bcd0b --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Counting-sort b/Lang/Scala/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..8e4dce3751 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Heapsort b/Lang/Scala/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..758b5cf6e4 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Insertion-sort b/Lang/Scala/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..3c8014d6cf --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Merge-sort b/Lang/Scala/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..ea64647240 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Quicksort b/Lang/Scala/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..5b15657cc8 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Selection-sort b/Lang/Scala/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..11c6e4caf1 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Shell-sort b/Lang/Scala/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..e4178a95ba --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Sleep-sort b/Lang/Scala/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..e742fb20bb --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Soundex b/Lang/Scala/Soundex new file mode 120000 index 0000000000..2915c7dfb6 --- /dev/null +++ b/Lang/Scala/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Scala \ No newline at end of file diff --git a/Lang/Scala/Spiral-matrix b/Lang/Scala/Spiral-matrix new file mode 120000 index 0000000000..d53251af69 --- /dev/null +++ b/Lang/Scala/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Scala \ No newline at end of file diff --git a/Lang/Scala/Stack b/Lang/Scala/Stack new file mode 120000 index 0000000000..7c4e953fd7 --- /dev/null +++ b/Lang/Scala/Stack @@ -0,0 +1 @@ +../../Task/Stack/Scala \ No newline at end of file diff --git a/Lang/Scala/Stack-traces b/Lang/Scala/Stack-traces new file mode 120000 index 0000000000..10580ae11e --- /dev/null +++ b/Lang/Scala/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Scala \ No newline at end of file diff --git a/Lang/Scala/Stair-climbing-puzzle b/Lang/Scala/Stair-climbing-puzzle new file mode 120000 index 0000000000..68305a62ae --- /dev/null +++ b/Lang/Scala/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Scala \ No newline at end of file diff --git a/Lang/Scala/Stem-and-leaf-plot b/Lang/Scala/Stem-and-leaf-plot new file mode 120000 index 0000000000..255b10c845 --- /dev/null +++ b/Lang/Scala/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Scala \ No newline at end of file diff --git a/Lang/Scala/String-case b/Lang/Scala/String-case new file mode 120000 index 0000000000..1a9309bea3 --- /dev/null +++ b/Lang/Scala/String-case @@ -0,0 +1 @@ +../../Task/String-case/Scala \ No newline at end of file diff --git a/Lang/Scala/String-concatenation b/Lang/Scala/String-concatenation new file mode 120000 index 0000000000..6ec23e6ae5 --- /dev/null +++ b/Lang/Scala/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Scala \ No newline at end of file diff --git a/Lang/Scala/String-interpolation--included- b/Lang/Scala/String-interpolation--included- new file mode 120000 index 0000000000..1b9498f7f3 --- /dev/null +++ b/Lang/Scala/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Scala \ No newline at end of file diff --git a/Lang/Scala/Strip-a-set-of-characters-from-a-string b/Lang/Scala/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..64443273d9 --- /dev/null +++ b/Lang/Scala/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Strip-comments-from-a-string b/Lang/Scala/Strip-comments-from-a-string new file mode 120000 index 0000000000..e61305ce53 --- /dev/null +++ b/Lang/Scala/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Scala/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..0dc538f995 --- /dev/null +++ b/Lang/Scala/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Scala/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..0ba3269ef2 --- /dev/null +++ b/Lang/Scala/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Scala \ No newline at end of file diff --git a/Lang/Scala/Substring b/Lang/Scala/Substring new file mode 120000 index 0000000000..14989769d6 --- /dev/null +++ b/Lang/Scala/Substring @@ -0,0 +1 @@ +../../Task/Substring/Scala \ No newline at end of file diff --git a/Lang/Scala/Substring-Top-and-tail b/Lang/Scala/Substring-Top-and-tail new file mode 120000 index 0000000000..2608bd2365 --- /dev/null +++ b/Lang/Scala/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Scala \ No newline at end of file diff --git a/Lang/Scala/Sudoku b/Lang/Scala/Sudoku new file mode 120000 index 0000000000..7d683af209 --- /dev/null +++ b/Lang/Scala/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Scala \ No newline at end of file diff --git a/Lang/Scala/Sum-and-product-of-an-array b/Lang/Scala/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a74e1ffc36 --- /dev/null +++ b/Lang/Scala/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Scala \ No newline at end of file diff --git a/Lang/Scala/Sum-digits-of-an-integer b/Lang/Scala/Sum-digits-of-an-integer new file mode 120000 index 0000000000..e3f290a16f --- /dev/null +++ b/Lang/Scala/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Scala \ No newline at end of file diff --git a/Lang/Scala/Sum-of-a-series b/Lang/Scala/Sum-of-a-series new file mode 120000 index 0000000000..406cb6b25a --- /dev/null +++ b/Lang/Scala/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Scala \ No newline at end of file diff --git a/Lang/Scala/Sum-of-squares b/Lang/Scala/Sum-of-squares new file mode 120000 index 0000000000..a088abc1f9 --- /dev/null +++ b/Lang/Scala/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Scala \ No newline at end of file diff --git a/Lang/Scala/Symmetric-difference b/Lang/Scala/Symmetric-difference new file mode 120000 index 0000000000..fef4766e72 --- /dev/null +++ b/Lang/Scala/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Scala \ No newline at end of file diff --git a/Lang/Scala/Synchronous-concurrency b/Lang/Scala/Synchronous-concurrency new file mode 120000 index 0000000000..375594cfbb --- /dev/null +++ b/Lang/Scala/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Scala \ No newline at end of file diff --git a/Lang/Scala/System-time b/Lang/Scala/System-time new file mode 120000 index 0000000000..e9377e50d0 --- /dev/null +++ b/Lang/Scala/System-time @@ -0,0 +1 @@ +../../Task/System-time/Scala \ No newline at end of file diff --git a/Lang/Scala/Ternary-logic b/Lang/Scala/Ternary-logic new file mode 120000 index 0000000000..ec98c5565c --- /dev/null +++ b/Lang/Scala/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Scala \ No newline at end of file diff --git a/Lang/Scala/Test-a-function b/Lang/Scala/Test-a-function new file mode 120000 index 0000000000..1ea5168d9e --- /dev/null +++ b/Lang/Scala/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Text-processing-1 b/Lang/Scala/Text-processing-1 new file mode 120000 index 0000000000..23a0d4349e --- /dev/null +++ b/Lang/Scala/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Scala \ No newline at end of file diff --git a/Lang/Scala/Text-processing-2 b/Lang/Scala/Text-processing-2 new file mode 120000 index 0000000000..cc1452ef31 --- /dev/null +++ b/Lang/Scala/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Scala \ No newline at end of file diff --git a/Lang/Scala/Tic-tac-toe b/Lang/Scala/Tic-tac-toe new file mode 120000 index 0000000000..9d8b3fc5a5 --- /dev/null +++ b/Lang/Scala/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Scala \ No newline at end of file diff --git a/Lang/Scala/Time-a-function b/Lang/Scala/Time-a-function new file mode 120000 index 0000000000..8124ceb12f --- /dev/null +++ b/Lang/Scala/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Tokenize-a-string b/Lang/Scala/Tokenize-a-string new file mode 120000 index 0000000000..07eeb420e3 --- /dev/null +++ b/Lang/Scala/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Scala \ No newline at end of file diff --git a/Lang/Scala/Top-rank-per-group b/Lang/Scala/Top-rank-per-group new file mode 120000 index 0000000000..e692abd839 --- /dev/null +++ b/Lang/Scala/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Scala \ No newline at end of file diff --git a/Lang/Scala/Towers-of-Hanoi b/Lang/Scala/Towers-of-Hanoi new file mode 120000 index 0000000000..5dcdd56f8d --- /dev/null +++ b/Lang/Scala/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Scala \ No newline at end of file diff --git a/Lang/Scala/Tree-traversal b/Lang/Scala/Tree-traversal new file mode 120000 index 0000000000..04d82e948c --- /dev/null +++ b/Lang/Scala/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Scala \ No newline at end of file diff --git a/Lang/Scala/URL-decoding b/Lang/Scala/URL-decoding new file mode 120000 index 0000000000..01474e8a29 --- /dev/null +++ b/Lang/Scala/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Scala \ No newline at end of file diff --git a/Lang/Scala/Unicode-variable-names b/Lang/Scala/Unicode-variable-names new file mode 120000 index 0000000000..92eff869c1 --- /dev/null +++ b/Lang/Scala/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Scala \ No newline at end of file diff --git a/Lang/Scala/User-input-Text b/Lang/Scala/User-input-Text new file mode 120000 index 0000000000..306fe3a16f --- /dev/null +++ b/Lang/Scala/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Scala \ No newline at end of file diff --git a/Lang/Scala/Variable-length-quantity b/Lang/Scala/Variable-length-quantity new file mode 120000 index 0000000000..05c9af1d61 --- /dev/null +++ b/Lang/Scala/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Scala \ No newline at end of file diff --git a/Lang/Scala/Variadic-function b/Lang/Scala/Variadic-function new file mode 120000 index 0000000000..a1d7185418 --- /dev/null +++ b/Lang/Scala/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Vector-products b/Lang/Scala/Vector-products new file mode 120000 index 0000000000..cab895824a --- /dev/null +++ b/Lang/Scala/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Scala \ No newline at end of file diff --git a/Lang/Scala/Vigen-re-cipher b/Lang/Scala/Vigen-re-cipher new file mode 120000 index 0000000000..c28d5b13d7 --- /dev/null +++ b/Lang/Scala/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Scala \ No newline at end of file diff --git a/Lang/Scala/Walk-a-directory-Non-recursively b/Lang/Scala/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..069e744717 --- /dev/null +++ b/Lang/Scala/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Scala \ No newline at end of file diff --git a/Lang/Scala/Walk-a-directory-Recursively b/Lang/Scala/Walk-a-directory-Recursively new file mode 120000 index 0000000000..66e0fa0324 --- /dev/null +++ b/Lang/Scala/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Scala \ No newline at end of file diff --git a/Lang/Scala/Web-scraping b/Lang/Scala/Web-scraping new file mode 120000 index 0000000000..8673fef514 --- /dev/null +++ b/Lang/Scala/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Scala \ No newline at end of file diff --git a/Lang/Scala/Window-creation b/Lang/Scala/Window-creation new file mode 120000 index 0000000000..4cb7d5cbba --- /dev/null +++ b/Lang/Scala/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Scala \ No newline at end of file diff --git a/Lang/Scala/Write-language-name-in-3D-ASCII b/Lang/Scala/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..d9e5ed0dc1 --- /dev/null +++ b/Lang/Scala/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Scala \ No newline at end of file diff --git a/Lang/Scala/XML-DOM-serialization b/Lang/Scala/XML-DOM-serialization new file mode 120000 index 0000000000..8bfc573e63 --- /dev/null +++ b/Lang/Scala/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Scala \ No newline at end of file diff --git a/Lang/Scala/XML-Input b/Lang/Scala/XML-Input new file mode 120000 index 0000000000..8bf30d30b0 --- /dev/null +++ b/Lang/Scala/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Scala \ No newline at end of file diff --git a/Lang/Scala/XML-Output b/Lang/Scala/XML-Output new file mode 120000 index 0000000000..478d59fd97 --- /dev/null +++ b/Lang/Scala/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Scala \ No newline at end of file diff --git a/Lang/Scala/XML-XPath b/Lang/Scala/XML-XPath new file mode 120000 index 0000000000..35143d76ef --- /dev/null +++ b/Lang/Scala/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Scala \ No newline at end of file diff --git a/Lang/Scala/Y-combinator b/Lang/Scala/Y-combinator new file mode 120000 index 0000000000..261878e640 --- /dev/null +++ b/Lang/Scala/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Scala \ No newline at end of file diff --git a/Lang/Scala/Zeckendorf-number-representation b/Lang/Scala/Zeckendorf-number-representation new file mode 120000 index 0000000000..ac2b8e3109 --- /dev/null +++ b/Lang/Scala/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Scala \ No newline at end of file diff --git a/Lang/Scala/Zig-zag-matrix b/Lang/Scala/Zig-zag-matrix new file mode 120000 index 0000000000..fc88c570e4 --- /dev/null +++ b/Lang/Scala/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Scala \ No newline at end of file diff --git a/Lang/Scheme/Shell-one-liner b/Lang/Scheme/Shell-one-liner new file mode 120000 index 0000000000..8ab74af5bf --- /dev/null +++ b/Lang/Scheme/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Short-circuit-evaluation b/Lang/Scheme/Short-circuit-evaluation new file mode 120000 index 0000000000..9ee16c888a --- /dev/null +++ b/Lang/Scheme/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sierpinski-carpet b/Lang/Scheme/Sierpinski-carpet new file mode 120000 index 0000000000..d0806549f9 --- /dev/null +++ b/Lang/Scheme/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sierpinski-triangle b/Lang/Scheme/Sierpinski-triangle new file mode 120000 index 0000000000..63aff223dd --- /dev/null +++ b/Lang/Scheme/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sieve-of-Eratosthenes b/Lang/Scheme/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..1b43a06bbd --- /dev/null +++ b/Lang/Scheme/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Singly-linked-list-Element-definition b/Lang/Scheme/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..3bd2d403f4 --- /dev/null +++ b/Lang/Scheme/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Singly-linked-list-Element-insertion b/Lang/Scheme/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..2228447eab --- /dev/null +++ b/Lang/Scheme/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Singly-linked-list-Traversal b/Lang/Scheme/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8c1f4b23c9 --- /dev/null +++ b/Lang/Scheme/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sleep b/Lang/Scheme/Sleep new file mode 120000 index 0000000000..948a89e782 --- /dev/null +++ b/Lang/Scheme/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sockets b/Lang/Scheme/Sockets new file mode 120000 index 0000000000..9e7ca156bc --- /dev/null +++ b/Lang/Scheme/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sort-an-integer-array b/Lang/Scheme/Sort-an-integer-array new file mode 120000 index 0000000000..2b81a3bdc5 --- /dev/null +++ b/Lang/Scheme/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sort-using-a-custom-comparator b/Lang/Scheme/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..94a57c2fa5 --- /dev/null +++ b/Lang/Scheme/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Bubble-sort b/Lang/Scheme/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..41d8e45183 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Gnome-sort b/Lang/Scheme/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..8852885e34 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Heapsort b/Lang/Scheme/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..c54e0aac69 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Insertion-sort b/Lang/Scheme/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..74e6fecc30 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Merge-sort b/Lang/Scheme/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..029a300f70 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Permutation-sort b/Lang/Scheme/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..c4728ea2b8 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sorting-algorithms-Quicksort b/Lang/Scheme/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ca1aabc3c7 --- /dev/null +++ b/Lang/Scheme/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Soundex b/Lang/Scheme/Soundex new file mode 120000 index 0000000000..f0671bec32 --- /dev/null +++ b/Lang/Scheme/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Stack b/Lang/Scheme/Stack new file mode 120000 index 0000000000..3ce24ab5ee --- /dev/null +++ b/Lang/Scheme/Stack @@ -0,0 +1 @@ +../../Task/Stack/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Stair-climbing-puzzle b/Lang/Scheme/Stair-climbing-puzzle new file mode 120000 index 0000000000..4f280940fe --- /dev/null +++ b/Lang/Scheme/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Standard-deviation b/Lang/Scheme/Standard-deviation new file mode 120000 index 0000000000..914d7b76d9 --- /dev/null +++ b/Lang/Scheme/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/String-case b/Lang/Scheme/String-case new file mode 120000 index 0000000000..f90fadc0e4 --- /dev/null +++ b/Lang/Scheme/String-case @@ -0,0 +1 @@ +../../Task/String-case/Scheme \ No newline at end of file diff --git a/Lang/Scheme/String-concatenation b/Lang/Scheme/String-concatenation new file mode 120000 index 0000000000..f50e85039a --- /dev/null +++ b/Lang/Scheme/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/String-length b/Lang/Scheme/String-length new file mode 120000 index 0000000000..e77f8dae99 --- /dev/null +++ b/Lang/Scheme/String-length @@ -0,0 +1 @@ +../../Task/String-length/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Strip-comments-from-a-string b/Lang/Scheme/Strip-comments-from-a-string new file mode 120000 index 0000000000..2eb47253fd --- /dev/null +++ b/Lang/Scheme/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Substring b/Lang/Scheme/Substring new file mode 120000 index 0000000000..9b3b342483 --- /dev/null +++ b/Lang/Scheme/Substring @@ -0,0 +1 @@ +../../Task/Substring/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sum-and-product-of-an-array b/Lang/Scheme/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e19c37b3da --- /dev/null +++ b/Lang/Scheme/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sum-of-a-series b/Lang/Scheme/Sum-of-a-series new file mode 120000 index 0000000000..60240b2541 --- /dev/null +++ b/Lang/Scheme/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sum-of-squares b/Lang/Scheme/Sum-of-squares new file mode 120000 index 0000000000..6b1e133417 --- /dev/null +++ b/Lang/Scheme/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Scheme \ No newline at end of file diff --git a/Lang/Scheme/System-time b/Lang/Scheme/System-time new file mode 120000 index 0000000000..254a5431f5 --- /dev/null +++ b/Lang/Scheme/System-time @@ -0,0 +1 @@ +../../Task/System-time/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Table-creation-Postal-addresses b/Lang/Scheme/Table-creation-Postal-addresses new file mode 120000 index 0000000000..e091ef0172 --- /dev/null +++ b/Lang/Scheme/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Take-notes-on-the-command-line b/Lang/Scheme/Take-notes-on-the-command-line new file mode 120000 index 0000000000..4b1d59282c --- /dev/null +++ b/Lang/Scheme/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Time-a-function b/Lang/Scheme/Time-a-function new file mode 120000 index 0000000000..1f9d971288 --- /dev/null +++ b/Lang/Scheme/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Tokenize-a-string b/Lang/Scheme/Tokenize-a-string new file mode 120000 index 0000000000..3644a61984 --- /dev/null +++ b/Lang/Scheme/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Towers-of-Hanoi b/Lang/Scheme/Towers-of-Hanoi new file mode 120000 index 0000000000..c24bde91c8 --- /dev/null +++ b/Lang/Scheme/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Trigonometric-functions b/Lang/Scheme/Trigonometric-functions new file mode 120000 index 0000000000..12b022a0c3 --- /dev/null +++ b/Lang/Scheme/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Scheme \ No newline at end of file diff --git a/Lang/Scheme/User-input-Text b/Lang/Scheme/User-input-Text new file mode 120000 index 0000000000..a45d80a27c --- /dev/null +++ b/Lang/Scheme/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Variadic-function b/Lang/Scheme/Variadic-function new file mode 120000 index 0000000000..85d23dd78b --- /dev/null +++ b/Lang/Scheme/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Vector-products b/Lang/Scheme/Vector-products new file mode 120000 index 0000000000..39b8daa029 --- /dev/null +++ b/Lang/Scheme/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Walk-a-directory-Recursively b/Lang/Scheme/Walk-a-directory-Recursively new file mode 120000 index 0000000000..ea2317cfcb --- /dev/null +++ b/Lang/Scheme/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Web-scraping b/Lang/Scheme/Web-scraping new file mode 120000 index 0000000000..8757b5e1b5 --- /dev/null +++ b/Lang/Scheme/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Window-creation b/Lang/Scheme/Window-creation new file mode 120000 index 0000000000..9516f55177 --- /dev/null +++ b/Lang/Scheme/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Y-combinator b/Lang/Scheme/Y-combinator new file mode 120000 index 0000000000..2cadbc7031 --- /dev/null +++ b/Lang/Scheme/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Scheme \ No newline at end of file diff --git a/Lang/Sed/String-case b/Lang/Sed/String-case new file mode 120000 index 0000000000..be3880cc99 --- /dev/null +++ b/Lang/Sed/String-case @@ -0,0 +1 @@ +../../Task/String-case/Sed \ No newline at end of file diff --git a/Lang/Sed/String-interpolation--included- b/Lang/Sed/String-interpolation--included- new file mode 120000 index 0000000000..9ab9a0cc68 --- /dev/null +++ b/Lang/Sed/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Sed \ No newline at end of file diff --git a/Lang/Sed/Strip-a-set-of-characters-from-a-string b/Lang/Sed/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..8cf7a822e0 --- /dev/null +++ b/Lang/Sed/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Sed \ No newline at end of file diff --git a/Lang/Sed/Substring b/Lang/Sed/Substring new file mode 120000 index 0000000000..ce1be7ded2 --- /dev/null +++ b/Lang/Sed/Substring @@ -0,0 +1 @@ +../../Task/Substring/Sed \ No newline at end of file diff --git a/Lang/Seed7/Short-circuit-evaluation b/Lang/Seed7/Short-circuit-evaluation new file mode 120000 index 0000000000..bddd8cefd9 --- /dev/null +++ b/Lang/Seed7/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Show-the-epoch b/Lang/Seed7/Show-the-epoch new file mode 120000 index 0000000000..f264e0a68b --- /dev/null +++ b/Lang/Seed7/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sierpinski-carpet b/Lang/Seed7/Sierpinski-carpet new file mode 120000 index 0000000000..36f9198858 --- /dev/null +++ b/Lang/Seed7/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sierpinski-triangle b/Lang/Seed7/Sierpinski-triangle new file mode 120000 index 0000000000..cf5371da14 --- /dev/null +++ b/Lang/Seed7/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sierpinski-triangle-Graphical b/Lang/Seed7/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..f8d9f7e3de --- /dev/null +++ b/Lang/Seed7/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sieve-of-Eratosthenes b/Lang/Seed7/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..4e8c480ceb --- /dev/null +++ b/Lang/Seed7/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sleep b/Lang/Seed7/Sleep new file mode 120000 index 0000000000..d825711647 --- /dev/null +++ b/Lang/Seed7/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sockets b/Lang/Seed7/Sockets new file mode 120000 index 0000000000..456cd82c80 --- /dev/null +++ b/Lang/Seed7/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sort-an-array-of-composite-structures b/Lang/Seed7/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..affdc4d838 --- /dev/null +++ b/Lang/Seed7/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sort-an-integer-array b/Lang/Seed7/Sort-an-integer-array new file mode 120000 index 0000000000..79ccbaf679 --- /dev/null +++ b/Lang/Seed7/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Bubble-sort b/Lang/Seed7/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..64bd5f1d7c --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Heapsort b/Lang/Seed7/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..18f906c53a --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Insertion-sort b/Lang/Seed7/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..fe44a0f0c3 --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Merge-sort b/Lang/Seed7/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..89a38c384a --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Quicksort b/Lang/Seed7/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..fd8410a19b --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Selection-sort b/Lang/Seed7/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..01aeb93795 --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Shell-sort b/Lang/Seed7/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..88f87df315 --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Spiral-matrix b/Lang/Seed7/Spiral-matrix new file mode 120000 index 0000000000..b43e1f5e28 --- /dev/null +++ b/Lang/Seed7/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Stable-marriage-problem b/Lang/Seed7/Stable-marriage-problem new file mode 120000 index 0000000000..d4db35bb65 --- /dev/null +++ b/Lang/Seed7/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Stack b/Lang/Seed7/Stack new file mode 120000 index 0000000000..911d313785 --- /dev/null +++ b/Lang/Seed7/Stack @@ -0,0 +1 @@ +../../Task/Stack/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Stair-climbing-puzzle b/Lang/Seed7/Stair-climbing-puzzle new file mode 120000 index 0000000000..b470c766ec --- /dev/null +++ b/Lang/Seed7/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Stem-and-leaf-plot b/Lang/Seed7/Stem-and-leaf-plot new file mode 120000 index 0000000000..4f1b11c996 --- /dev/null +++ b/Lang/Seed7/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-concatenation b/Lang/Seed7/String-concatenation new file mode 120000 index 0000000000..723996ce75 --- /dev/null +++ b/Lang/Seed7/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-interpolation--included- b/Lang/Seed7/String-interpolation--included- new file mode 120000 index 0000000000..640e32cbaa --- /dev/null +++ b/Lang/Seed7/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/String-length b/Lang/Seed7/String-length new file mode 120000 index 0000000000..ede605ba88 --- /dev/null +++ b/Lang/Seed7/String-length @@ -0,0 +1 @@ +../../Task/String-length/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Strip-a-set-of-characters-from-a-string b/Lang/Seed7/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a5c0dad7e3 --- /dev/null +++ b/Lang/Seed7/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Strip-block-comments b/Lang/Seed7/Strip-block-comments new file mode 120000 index 0000000000..401cad57ed --- /dev/null +++ b/Lang/Seed7/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Strip-comments-from-a-string b/Lang/Seed7/Strip-comments-from-a-string new file mode 120000 index 0000000000..d8a3eaf15d --- /dev/null +++ b/Lang/Seed7/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Seed7/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..cae6f502ce --- /dev/null +++ b/Lang/Seed7/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Seed7/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..3f82b1bad8 --- /dev/null +++ b/Lang/Seed7/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Substring b/Lang/Seed7/Substring new file mode 120000 index 0000000000..821ecf651f --- /dev/null +++ b/Lang/Seed7/Substring @@ -0,0 +1 @@ +../../Task/Substring/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Substring-Top-and-tail b/Lang/Seed7/Substring-Top-and-tail new file mode 120000 index 0000000000..01e0dbd61e --- /dev/null +++ b/Lang/Seed7/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sum-and-product-of-an-array b/Lang/Seed7/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f24d640881 --- /dev/null +++ b/Lang/Seed7/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sum-digits-of-an-integer b/Lang/Seed7/Sum-digits-of-an-integer new file mode 120000 index 0000000000..b598f90115 --- /dev/null +++ b/Lang/Seed7/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sum-of-a-series b/Lang/Seed7/Sum-of-a-series new file mode 120000 index 0000000000..1e417fdeb7 --- /dev/null +++ b/Lang/Seed7/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sum-of-squares b/Lang/Seed7/Sum-of-squares new file mode 120000 index 0000000000..132a60f737 --- /dev/null +++ b/Lang/Seed7/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Symmetric-difference b/Lang/Seed7/Symmetric-difference new file mode 120000 index 0000000000..ec8f729f02 --- /dev/null +++ b/Lang/Seed7/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/System-time b/Lang/Seed7/System-time new file mode 120000 index 0000000000..420519ccaf --- /dev/null +++ b/Lang/Seed7/System-time @@ -0,0 +1 @@ +../../Task/System-time/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Take-notes-on-the-command-line b/Lang/Seed7/Take-notes-on-the-command-line new file mode 120000 index 0000000000..ad0d79bbdd --- /dev/null +++ b/Lang/Seed7/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Terminal-control-Clear-the-screen b/Lang/Seed7/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..4a6d05881a --- /dev/null +++ b/Lang/Seed7/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Terminal-control-Cursor-positioning b/Lang/Seed7/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..dcdc576bb7 --- /dev/null +++ b/Lang/Seed7/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Terminal-control-Dimensions b/Lang/Seed7/Terminal-control-Dimensions new file mode 120000 index 0000000000..813034cdcf --- /dev/null +++ b/Lang/Seed7/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Terminal-control-Display-an-extended-character b/Lang/Seed7/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..538e54eb2e --- /dev/null +++ b/Lang/Seed7/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Ternary-logic b/Lang/Seed7/Ternary-logic new file mode 120000 index 0000000000..20ce7dd467 --- /dev/null +++ b/Lang/Seed7/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Text-processing-Max-licenses-in-use b/Lang/Seed7/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..27a9bb40bf --- /dev/null +++ b/Lang/Seed7/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Time-a-function b/Lang/Seed7/Time-a-function new file mode 120000 index 0000000000..57376c9f2a --- /dev/null +++ b/Lang/Seed7/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Tokenize-a-string b/Lang/Seed7/Tokenize-a-string new file mode 120000 index 0000000000..2142ff7b49 --- /dev/null +++ b/Lang/Seed7/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Towers-of-Hanoi b/Lang/Seed7/Towers-of-Hanoi new file mode 120000 index 0000000000..4377b76794 --- /dev/null +++ b/Lang/Seed7/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Trigonometric-functions b/Lang/Seed7/Trigonometric-functions new file mode 120000 index 0000000000..d88819cc00 --- /dev/null +++ b/Lang/Seed7/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/URL-decoding b/Lang/Seed7/URL-decoding new file mode 120000 index 0000000000..669f79ed26 --- /dev/null +++ b/Lang/Seed7/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/URL-encoding b/Lang/Seed7/URL-encoding new file mode 120000 index 0000000000..0397eccd56 --- /dev/null +++ b/Lang/Seed7/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Unbias-a-random-generator b/Lang/Seed7/Unbias-a-random-generator new file mode 120000 index 0000000000..33119e027b --- /dev/null +++ b/Lang/Seed7/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/User-input-Text b/Lang/Seed7/User-input-Text new file mode 120000 index 0000000000..53cae2a3af --- /dev/null +++ b/Lang/Seed7/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Van-der-Corput-sequence b/Lang/Seed7/Van-der-Corput-sequence new file mode 120000 index 0000000000..efd49054c6 --- /dev/null +++ b/Lang/Seed7/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Variable-length-quantity b/Lang/Seed7/Variable-length-quantity new file mode 120000 index 0000000000..c15cdc3146 --- /dev/null +++ b/Lang/Seed7/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Variables b/Lang/Seed7/Variables new file mode 120000 index 0000000000..43748636a7 --- /dev/null +++ b/Lang/Seed7/Variables @@ -0,0 +1 @@ +../../Task/Variables/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Vector-products b/Lang/Seed7/Vector-products new file mode 120000 index 0000000000..322a09d2aa --- /dev/null +++ b/Lang/Seed7/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Vigen-re-cipher b/Lang/Seed7/Vigen-re-cipher new file mode 120000 index 0000000000..87ac0472e7 --- /dev/null +++ b/Lang/Seed7/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Voronoi-diagram b/Lang/Seed7/Voronoi-diagram new file mode 120000 index 0000000000..73a463e5e3 --- /dev/null +++ b/Lang/Seed7/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Walk-a-directory-Non-recursively b/Lang/Seed7/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..04e9595586 --- /dev/null +++ b/Lang/Seed7/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Web-scraping b/Lang/Seed7/Web-scraping new file mode 120000 index 0000000000..458309f03b --- /dev/null +++ b/Lang/Seed7/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Write-float-arrays-to-a-text-file b/Lang/Seed7/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..fa0e9b7abb --- /dev/null +++ b/Lang/Seed7/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Yin-and-yang b/Lang/Seed7/Yin-and-yang new file mode 120000 index 0000000000..4333a99b50 --- /dev/null +++ b/Lang/Seed7/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Zig-zag-matrix b/Lang/Seed7/Zig-zag-matrix new file mode 120000 index 0000000000..4876cffab0 --- /dev/null +++ b/Lang/Seed7/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Seed7 \ No newline at end of file diff --git a/Lang/Shiny/Shell-one-liner b/Lang/Shiny/Shell-one-liner new file mode 120000 index 0000000000..ef5a1fb494 --- /dev/null +++ b/Lang/Shiny/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Shiny \ No newline at end of file diff --git a/Lang/Slate/Shell-one-liner b/Lang/Slate/Shell-one-liner new file mode 120000 index 0000000000..af3f87f8a3 --- /dev/null +++ b/Lang/Slate/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Slate \ No newline at end of file diff --git a/Lang/Slate/Singleton b/Lang/Slate/Singleton new file mode 120000 index 0000000000..6dce4f41ca --- /dev/null +++ b/Lang/Slate/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Slate \ No newline at end of file diff --git a/Lang/Slate/Sockets b/Lang/Slate/Sockets new file mode 120000 index 0000000000..849d998e0c --- /dev/null +++ b/Lang/Slate/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Slate \ No newline at end of file diff --git a/Lang/Slate/Sort-an-integer-array b/Lang/Slate/Sort-an-integer-array new file mode 120000 index 0000000000..f4b512769b --- /dev/null +++ b/Lang/Slate/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Slate \ No newline at end of file diff --git a/Lang/Slate/Sort-using-a-custom-comparator b/Lang/Slate/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..49eb1f6f99 --- /dev/null +++ b/Lang/Slate/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Slate \ No newline at end of file diff --git a/Lang/Slate/Sorting-algorithms-Cocktail-sort b/Lang/Slate/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..53fe245dd9 --- /dev/null +++ b/Lang/Slate/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Slate \ No newline at end of file diff --git a/Lang/Slate/Sorting-algorithms-Counting-sort b/Lang/Slate/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..d5368052b7 --- /dev/null +++ b/Lang/Slate/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Slate \ No newline at end of file diff --git a/Lang/Slate/Stack b/Lang/Slate/Stack new file mode 120000 index 0000000000..a88ed6e68a --- /dev/null +++ b/Lang/Slate/Stack @@ -0,0 +1 @@ +../../Task/Stack/Slate \ No newline at end of file diff --git a/Lang/Slate/Stack-traces b/Lang/Slate/Stack-traces new file mode 120000 index 0000000000..01cab0d62c --- /dev/null +++ b/Lang/Slate/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Slate \ No newline at end of file diff --git a/Lang/Slate/String-case b/Lang/Slate/String-case new file mode 120000 index 0000000000..adbaa9aac9 --- /dev/null +++ b/Lang/Slate/String-case @@ -0,0 +1 @@ +../../Task/String-case/Slate \ No newline at end of file diff --git a/Lang/Slate/String-concatenation b/Lang/Slate/String-concatenation new file mode 120000 index 0000000000..20ce8e34fa --- /dev/null +++ b/Lang/Slate/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Slate \ No newline at end of file diff --git a/Lang/Slate/String-length b/Lang/Slate/String-length new file mode 120000 index 0000000000..f1f6cb2493 --- /dev/null +++ b/Lang/Slate/String-length @@ -0,0 +1 @@ +../../Task/String-length/Slate \ No newline at end of file diff --git a/Lang/Slate/Substring b/Lang/Slate/Substring new file mode 120000 index 0000000000..cabc458e61 --- /dev/null +++ b/Lang/Slate/Substring @@ -0,0 +1 @@ +../../Task/Substring/Slate \ No newline at end of file diff --git a/Lang/Slate/Sum-and-product-of-an-array b/Lang/Slate/Sum-and-product-of-an-array new file mode 120000 index 0000000000..b66e64087a --- /dev/null +++ b/Lang/Slate/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Slate \ No newline at end of file diff --git a/Lang/Slate/Sum-of-a-series b/Lang/Slate/Sum-of-a-series new file mode 120000 index 0000000000..1ce14d282e --- /dev/null +++ b/Lang/Slate/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Slate \ No newline at end of file diff --git a/Lang/Slate/Sum-of-squares b/Lang/Slate/Sum-of-squares new file mode 120000 index 0000000000..751901add2 --- /dev/null +++ b/Lang/Slate/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Slate \ No newline at end of file diff --git a/Lang/Slate/Time-a-function b/Lang/Slate/Time-a-function new file mode 120000 index 0000000000..8cd05422cc --- /dev/null +++ b/Lang/Slate/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Slate \ No newline at end of file diff --git a/Lang/Slate/Tokenize-a-string b/Lang/Slate/Tokenize-a-string new file mode 120000 index 0000000000..13664af838 --- /dev/null +++ b/Lang/Slate/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Slate \ No newline at end of file diff --git a/Lang/Slate/User-input-Text b/Lang/Slate/User-input-Text new file mode 120000 index 0000000000..bef0b9c263 --- /dev/null +++ b/Lang/Slate/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Slate \ No newline at end of file diff --git a/Lang/Slate/Variadic-function b/Lang/Slate/Variadic-function new file mode 120000 index 0000000000..aa09e82a56 --- /dev/null +++ b/Lang/Slate/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Slate \ No newline at end of file diff --git a/Lang/Slate/XML-Input b/Lang/Slate/XML-Input new file mode 120000 index 0000000000..cea8363dad --- /dev/null +++ b/Lang/Slate/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Slate \ No newline at end of file diff --git a/Lang/Slate/XML-Output b/Lang/Slate/XML-Output new file mode 120000 index 0000000000..36eccf3817 --- /dev/null +++ b/Lang/Slate/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Slate \ No newline at end of file diff --git a/Lang/Slate/Y-combinator b/Lang/Slate/Y-combinator new file mode 120000 index 0000000000..898c92be73 --- /dev/null +++ b/Lang/Slate/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Slate \ No newline at end of file diff --git a/Lang/Smalltalk/SHA-1 b/Lang/Smalltalk/SHA-1 new file mode 120000 index 0000000000..af8ca62ce7 --- /dev/null +++ b/Lang/Smalltalk/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Short-circuit-evaluation b/Lang/Smalltalk/Short-circuit-evaluation new file mode 120000 index 0000000000..dc4a0a95e3 --- /dev/null +++ b/Lang/Smalltalk/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Simple-windowed-application b/Lang/Smalltalk/Simple-windowed-application new file mode 120000 index 0000000000..ff44e14dfd --- /dev/null +++ b/Lang/Smalltalk/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sleep b/Lang/Smalltalk/Sleep new file mode 120000 index 0000000000..e8c027ab16 --- /dev/null +++ b/Lang/Smalltalk/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sockets b/Lang/Smalltalk/Sockets new file mode 120000 index 0000000000..963e01836a --- /dev/null +++ b/Lang/Smalltalk/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sort-an-integer-array b/Lang/Smalltalk/Sort-an-integer-array new file mode 120000 index 0000000000..214b78833c --- /dev/null +++ b/Lang/Smalltalk/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sort-using-a-custom-comparator b/Lang/Smalltalk/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..075b64ff78 --- /dev/null +++ b/Lang/Smalltalk/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Bogosort b/Lang/Smalltalk/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..79d0414d76 --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Bubble-sort b/Lang/Smalltalk/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..044122c205 --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Cocktail-sort b/Lang/Smalltalk/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..7159af17ab --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Counting-sort b/Lang/Smalltalk/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c1ff582df4 --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Gnome-sort b/Lang/Smalltalk/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..f3ccf677c6 --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sorting-algorithms-Stooge-sort b/Lang/Smalltalk/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..5e26ea7dfc --- /dev/null +++ b/Lang/Smalltalk/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Soundex b/Lang/Smalltalk/Soundex new file mode 120000 index 0000000000..dc4d2fbc45 --- /dev/null +++ b/Lang/Smalltalk/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Special-variables b/Lang/Smalltalk/Special-variables new file mode 120000 index 0000000000..4e5a53a35f --- /dev/null +++ b/Lang/Smalltalk/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Stack-traces b/Lang/Smalltalk/Stack-traces new file mode 120000 index 0000000000..9898ffb582 --- /dev/null +++ b/Lang/Smalltalk/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Stair-climbing-puzzle b/Lang/Smalltalk/Stair-climbing-puzzle new file mode 120000 index 0000000000..d950ddcee2 --- /dev/null +++ b/Lang/Smalltalk/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Standard-deviation b/Lang/Smalltalk/Standard-deviation new file mode 120000 index 0000000000..c8f148c743 --- /dev/null +++ b/Lang/Smalltalk/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/String-case b/Lang/Smalltalk/String-case new file mode 120000 index 0000000000..e21a843108 --- /dev/null +++ b/Lang/Smalltalk/String-case @@ -0,0 +1 @@ +../../Task/String-case/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/String-concatenation b/Lang/Smalltalk/String-concatenation new file mode 120000 index 0000000000..630c550638 --- /dev/null +++ b/Lang/Smalltalk/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/String-length b/Lang/Smalltalk/String-length new file mode 120000 index 0000000000..37e3459dac --- /dev/null +++ b/Lang/Smalltalk/String-length @@ -0,0 +1 @@ +../../Task/String-length/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Strip-a-set-of-characters-from-a-string b/Lang/Smalltalk/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..6165da7f5c --- /dev/null +++ b/Lang/Smalltalk/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Smalltalk/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..51ffdc4823 --- /dev/null +++ b/Lang/Smalltalk/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Substring b/Lang/Smalltalk/Substring new file mode 120000 index 0000000000..2d897dbbe8 --- /dev/null +++ b/Lang/Smalltalk/Substring @@ -0,0 +1 @@ +../../Task/Substring/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sum-and-product-of-an-array b/Lang/Smalltalk/Sum-and-product-of-an-array new file mode 120000 index 0000000000..744cc7b958 --- /dev/null +++ b/Lang/Smalltalk/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sum-of-a-series b/Lang/Smalltalk/Sum-of-a-series new file mode 120000 index 0000000000..961f9b90f5 --- /dev/null +++ b/Lang/Smalltalk/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Sum-of-squares b/Lang/Smalltalk/Sum-of-squares new file mode 120000 index 0000000000..764c6ca567 --- /dev/null +++ b/Lang/Smalltalk/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Symmetric-difference b/Lang/Smalltalk/Symmetric-difference new file mode 120000 index 0000000000..d6562d8743 --- /dev/null +++ b/Lang/Smalltalk/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/System-time b/Lang/Smalltalk/System-time new file mode 120000 index 0000000000..31153ce910 --- /dev/null +++ b/Lang/Smalltalk/System-time @@ -0,0 +1 @@ +../../Task/System-time/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Terminal-control-Clear-the-screen b/Lang/Smalltalk/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..3880a944d9 --- /dev/null +++ b/Lang/Smalltalk/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Time-a-function b/Lang/Smalltalk/Time-a-function new file mode 120000 index 0000000000..615fb0fcdf --- /dev/null +++ b/Lang/Smalltalk/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Tokenize-a-string b/Lang/Smalltalk/Tokenize-a-string new file mode 120000 index 0000000000..34e3ff7079 --- /dev/null +++ b/Lang/Smalltalk/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Undefined-values b/Lang/Smalltalk/Undefined-values new file mode 120000 index 0000000000..834743fcb6 --- /dev/null +++ b/Lang/Smalltalk/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/User-input-Text b/Lang/Smalltalk/User-input-Text new file mode 120000 index 0000000000..c9ee38ec72 --- /dev/null +++ b/Lang/Smalltalk/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Vigen-re-cipher b/Lang/Smalltalk/Vigen-re-cipher new file mode 120000 index 0000000000..687b2241bf --- /dev/null +++ b/Lang/Smalltalk/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Walk-a-directory-Non-recursively b/Lang/Smalltalk/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..643b27a00a --- /dev/null +++ b/Lang/Smalltalk/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Walk-a-directory-Recursively b/Lang/Smalltalk/Walk-a-directory-Recursively new file mode 120000 index 0000000000..8f7bcae217 --- /dev/null +++ b/Lang/Smalltalk/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Window-creation b/Lang/Smalltalk/Window-creation new file mode 120000 index 0000000000..d21571411a --- /dev/null +++ b/Lang/Smalltalk/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Y-combinator b/Lang/Smalltalk/Y-combinator new file mode 120000 index 0000000000..2549993764 --- /dev/null +++ b/Lang/Smalltalk/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Smalltalk \ No newline at end of file diff --git a/Lang/Standard-ML/Short-circuit-evaluation b/Lang/Standard-ML/Short-circuit-evaluation new file mode 120000 index 0000000000..f4010006a0 --- /dev/null +++ b/Lang/Standard-ML/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Show-the-epoch b/Lang/Standard-ML/Show-the-epoch new file mode 120000 index 0000000000..91e2fcf63e --- /dev/null +++ b/Lang/Standard-ML/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sleep b/Lang/Standard-ML/Sleep new file mode 120000 index 0000000000..0454b42465 --- /dev/null +++ b/Lang/Standard-ML/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sort-an-integer-array b/Lang/Standard-ML/Sort-an-integer-array new file mode 120000 index 0000000000..8c58a740eb --- /dev/null +++ b/Lang/Standard-ML/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sort-using-a-custom-comparator b/Lang/Standard-ML/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..616b28425a --- /dev/null +++ b/Lang/Standard-ML/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Bead-sort b/Lang/Standard-ML/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..338f0b5d97 --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Insertion-sort b/Lang/Standard-ML/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..4d9b5a0868 --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Merge-sort b/Lang/Standard-ML/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..d3ce1d385d --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Quicksort b/Lang/Standard-ML/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..7be276f34d --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Selection-sort b/Lang/Standard-ML/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..5580a0039c --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Stair-climbing-puzzle b/Lang/Standard-ML/Stair-climbing-puzzle new file mode 120000 index 0000000000..e6ec07558b --- /dev/null +++ b/Lang/Standard-ML/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/String-case b/Lang/Standard-ML/String-case new file mode 120000 index 0000000000..bf74be3445 --- /dev/null +++ b/Lang/Standard-ML/String-case @@ -0,0 +1 @@ +../../Task/String-case/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/String-concatenation b/Lang/Standard-ML/String-concatenation new file mode 120000 index 0000000000..633bc4d39e --- /dev/null +++ b/Lang/Standard-ML/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/String-length b/Lang/Standard-ML/String-length new file mode 120000 index 0000000000..3c7c5e5a79 --- /dev/null +++ b/Lang/Standard-ML/String-length @@ -0,0 +1 @@ +../../Task/String-length/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Strip-a-set-of-characters-from-a-string b/Lang/Standard-ML/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..07673c822b --- /dev/null +++ b/Lang/Standard-ML/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sum-and-product-of-an-array b/Lang/Standard-ML/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4733fa74ea --- /dev/null +++ b/Lang/Standard-ML/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sum-of-a-series b/Lang/Standard-ML/Sum-of-a-series new file mode 120000 index 0000000000..f86ffa2a3c --- /dev/null +++ b/Lang/Standard-ML/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sum-of-squares b/Lang/Standard-ML/Sum-of-squares new file mode 120000 index 0000000000..8cf6b88e02 --- /dev/null +++ b/Lang/Standard-ML/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/System-time b/Lang/Standard-ML/System-time new file mode 120000 index 0000000000..ca6e57da50 --- /dev/null +++ b/Lang/Standard-ML/System-time @@ -0,0 +1 @@ +../../Task/System-time/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Time-a-function b/Lang/Standard-ML/Time-a-function new file mode 120000 index 0000000000..3474f89991 --- /dev/null +++ b/Lang/Standard-ML/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Tokenize-a-string b/Lang/Standard-ML/Tokenize-a-string new file mode 120000 index 0000000000..993c39a029 --- /dev/null +++ b/Lang/Standard-ML/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/User-input-Text b/Lang/Standard-ML/User-input-Text new file mode 120000 index 0000000000..dca78a1cc6 --- /dev/null +++ b/Lang/Standard-ML/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Write-float-arrays-to-a-text-file b/Lang/Standard-ML/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..c5044953e2 --- /dev/null +++ b/Lang/Standard-ML/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Y-combinator b/Lang/Standard-ML/Y-combinator new file mode 120000 index 0000000000..ae1dd0910e --- /dev/null +++ b/Lang/Standard-ML/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Standard-ML \ No newline at end of file diff --git a/Lang/Suneido/Sleep b/Lang/Suneido/Sleep new file mode 120000 index 0000000000..ebb4e9cb15 --- /dev/null +++ b/Lang/Suneido/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Suneido \ No newline at end of file diff --git a/Lang/SystemVerilog/Synchronous-concurrency b/Lang/SystemVerilog/Synchronous-concurrency new file mode 120000 index 0000000000..459fb360c8 --- /dev/null +++ b/Lang/SystemVerilog/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/SystemVerilog \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Sierpinski-triangle b/Lang/TI-83-BASIC/Sierpinski-triangle new file mode 120000 index 0000000000..a5c3af4655 --- /dev/null +++ b/Lang/TI-83-BASIC/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Stair-climbing-puzzle b/Lang/TI-83-BASIC/Stair-climbing-puzzle new file mode 120000 index 0000000000..a1bda7e366 --- /dev/null +++ b/Lang/TI-83-BASIC/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/String-case b/Lang/TI-83-BASIC/String-case new file mode 120000 index 0000000000..b15fafd207 --- /dev/null +++ b/Lang/TI-83-BASIC/String-case @@ -0,0 +1 @@ +../../Task/String-case/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Strip-control-codes-and-extended-characters-from-a-string b/Lang/TI-83-BASIC/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..f1ee7d31c8 --- /dev/null +++ b/Lang/TI-83-BASIC/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/TI-83-BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..f1ec5518a0 --- /dev/null +++ b/Lang/TI-83-BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Towers-of-Hanoi b/Lang/TI-83-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..679b040f34 --- /dev/null +++ b/Lang/TI-83-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/User-input-Text b/Lang/TI-83-BASIC/User-input-Text new file mode 120000 index 0000000000..b76752fc7d --- /dev/null +++ b/Lang/TI-83-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Variables b/Lang/TI-83-BASIC/Variables new file mode 120000 index 0000000000..2f0f265a89 --- /dev/null +++ b/Lang/TI-83-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Simple-windowed-application b/Lang/TI-89-BASIC/Simple-windowed-application new file mode 120000 index 0000000000..3031c82cb0 --- /dev/null +++ b/Lang/TI-89-BASIC/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/String-concatenation b/Lang/TI-89-BASIC/String-concatenation new file mode 120000 index 0000000000..1a0763e510 --- /dev/null +++ b/Lang/TI-89-BASIC/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/String-length b/Lang/TI-89-BASIC/String-length new file mode 120000 index 0000000000..4f243c620f --- /dev/null +++ b/Lang/TI-89-BASIC/String-length @@ -0,0 +1 @@ +../../Task/String-length/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Sum-of-a-series b/Lang/TI-89-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..a861242966 --- /dev/null +++ b/Lang/TI-89-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/System-time b/Lang/TI-89-BASIC/System-time new file mode 120000 index 0000000000..5146d2f408 --- /dev/null +++ b/Lang/TI-89-BASIC/System-time @@ -0,0 +1 @@ +../../Task/System-time/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/User-input-Graphical b/Lang/TI-89-BASIC/User-input-Graphical new file mode 120000 index 0000000000..1b0d508251 --- /dev/null +++ b/Lang/TI-89-BASIC/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/User-input-Text b/Lang/TI-89-BASIC/User-input-Text new file mode 120000 index 0000000000..aa6344b25f --- /dev/null +++ b/Lang/TI-89-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Variables b/Lang/TI-89-BASIC/Variables new file mode 120000 index 0000000000..7afac61af6 --- /dev/null +++ b/Lang/TI-89-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Window-creation b/Lang/TI-89-BASIC/Window-creation new file mode 120000 index 0000000000..bef9e48129 --- /dev/null +++ b/Lang/TI-89-BASIC/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TIScript/Variadic-function b/Lang/TIScript/Variadic-function new file mode 120000 index 0000000000..0dd85351b7 --- /dev/null +++ b/Lang/TIScript/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/TIScript \ No newline at end of file diff --git a/Lang/TPP/Terminal-control-Inverse-video b/Lang/TPP/Terminal-control-Inverse-video new file mode 120000 index 0000000000..f21eac2848 --- /dev/null +++ b/Lang/TPP/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/TPP \ No newline at end of file diff --git a/Lang/TPP/Word-wrap b/Lang/TPP/Word-wrap new file mode 120000 index 0000000000..07a5005940 --- /dev/null +++ b/Lang/TPP/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/TPP \ No newline at end of file diff --git a/Lang/TSE-SAL/Soundex b/Lang/TSE-SAL/Soundex new file mode 120000 index 0000000000..f4355dd2fa --- /dev/null +++ b/Lang/TSE-SAL/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/TSE-SAL \ No newline at end of file diff --git a/Lang/TSE-SAL/Spiral-matrix b/Lang/TSE-SAL/Spiral-matrix new file mode 120000 index 0000000000..13542b18c7 --- /dev/null +++ b/Lang/TSE-SAL/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/TSE-SAL \ No newline at end of file diff --git a/Lang/TSE-SAL/Towers-of-Hanoi b/Lang/TSE-SAL/Towers-of-Hanoi new file mode 120000 index 0000000000..fc4bf17ee3 --- /dev/null +++ b/Lang/TSE-SAL/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/TSE-SAL \ No newline at end of file diff --git a/Lang/TUSCRIPT/Show-the-epoch b/Lang/TUSCRIPT/Show-the-epoch new file mode 120000 index 0000000000..312c565c21 --- /dev/null +++ b/Lang/TUSCRIPT/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Sleep b/Lang/TUSCRIPT/Sleep new file mode 120000 index 0000000000..cfaa0d4ab0 --- /dev/null +++ b/Lang/TUSCRIPT/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Sort-disjoint-sublist b/Lang/TUSCRIPT/Sort-disjoint-sublist new file mode 120000 index 0000000000..4227c8b865 --- /dev/null +++ b/Lang/TUSCRIPT/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Sort-using-a-custom-comparator b/Lang/TUSCRIPT/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..1ccd3c5da6 --- /dev/null +++ b/Lang/TUSCRIPT/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Soundex b/Lang/TUSCRIPT/Soundex new file mode 120000 index 0000000000..7740b0e76e --- /dev/null +++ b/Lang/TUSCRIPT/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Stem-and-leaf-plot b/Lang/TUSCRIPT/Stem-and-leaf-plot new file mode 120000 index 0000000000..5cc12e55c3 --- /dev/null +++ b/Lang/TUSCRIPT/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/String-case b/Lang/TUSCRIPT/String-case new file mode 120000 index 0000000000..3e6f2a5340 --- /dev/null +++ b/Lang/TUSCRIPT/String-case @@ -0,0 +1 @@ +../../Task/String-case/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/String-concatenation b/Lang/TUSCRIPT/String-concatenation new file mode 120000 index 0000000000..908dbdb885 --- /dev/null +++ b/Lang/TUSCRIPT/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/String-interpolation--included- b/Lang/TUSCRIPT/String-interpolation--included- new file mode 120000 index 0000000000..d8cae7d60b --- /dev/null +++ b/Lang/TUSCRIPT/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/String-length b/Lang/TUSCRIPT/String-length new file mode 120000 index 0000000000..6c504e9002 --- /dev/null +++ b/Lang/TUSCRIPT/String-length @@ -0,0 +1 @@ +../../Task/String-length/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Strip-a-set-of-characters-from-a-string b/Lang/TUSCRIPT/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..5382fbeb15 --- /dev/null +++ b/Lang/TUSCRIPT/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Strip-block-comments b/Lang/TUSCRIPT/Strip-block-comments new file mode 120000 index 0000000000..bf2d46666b --- /dev/null +++ b/Lang/TUSCRIPT/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Strip-comments-from-a-string b/Lang/TUSCRIPT/Strip-comments-from-a-string new file mode 120000 index 0000000000..20ddea3c71 --- /dev/null +++ b/Lang/TUSCRIPT/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Strip-whitespace-from-a-string-Top-and-tail b/Lang/TUSCRIPT/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..93b6ad0d13 --- /dev/null +++ b/Lang/TUSCRIPT/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Substring b/Lang/TUSCRIPT/Substring new file mode 120000 index 0000000000..bc739ae272 --- /dev/null +++ b/Lang/TUSCRIPT/Substring @@ -0,0 +1 @@ +../../Task/Substring/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Substring-Top-and-tail b/Lang/TUSCRIPT/Substring-Top-and-tail new file mode 120000 index 0000000000..b3982c0493 --- /dev/null +++ b/Lang/TUSCRIPT/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Sum-and-product-of-an-array b/Lang/TUSCRIPT/Sum-and-product-of-an-array new file mode 120000 index 0000000000..d049ab3c26 --- /dev/null +++ b/Lang/TUSCRIPT/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Sum-of-squares b/Lang/TUSCRIPT/Sum-of-squares new file mode 120000 index 0000000000..d7cd91921c --- /dev/null +++ b/Lang/TUSCRIPT/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Symmetric-difference b/Lang/TUSCRIPT/Symmetric-difference new file mode 120000 index 0000000000..dab9826fef --- /dev/null +++ b/Lang/TUSCRIPT/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/System-time b/Lang/TUSCRIPT/System-time new file mode 120000 index 0000000000..c689a42893 --- /dev/null +++ b/Lang/TUSCRIPT/System-time @@ -0,0 +1 @@ +../../Task/System-time/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Text-processing-Max-licenses-in-use b/Lang/TUSCRIPT/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..4f45a06939 --- /dev/null +++ b/Lang/TUSCRIPT/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Time-a-function b/Lang/TUSCRIPT/Time-a-function new file mode 120000 index 0000000000..8ce32be126 --- /dev/null +++ b/Lang/TUSCRIPT/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Tokenize-a-string b/Lang/TUSCRIPT/Tokenize-a-string new file mode 120000 index 0000000000..0dd961c769 --- /dev/null +++ b/Lang/TUSCRIPT/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Top-rank-per-group b/Lang/TUSCRIPT/Top-rank-per-group new file mode 120000 index 0000000000..b29ce66191 --- /dev/null +++ b/Lang/TUSCRIPT/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/URL-decoding b/Lang/TUSCRIPT/URL-decoding new file mode 120000 index 0000000000..15ed831915 --- /dev/null +++ b/Lang/TUSCRIPT/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/URL-encoding b/Lang/TUSCRIPT/URL-encoding new file mode 120000 index 0000000000..630a1495a6 --- /dev/null +++ b/Lang/TUSCRIPT/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/User-input-Text b/Lang/TUSCRIPT/User-input-Text new file mode 120000 index 0000000000..59cf8542e4 --- /dev/null +++ b/Lang/TUSCRIPT/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Variable-size-Get b/Lang/TUSCRIPT/Variable-size-Get new file mode 120000 index 0000000000..9ffa86efce --- /dev/null +++ b/Lang/TUSCRIPT/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Variables b/Lang/TUSCRIPT/Variables new file mode 120000 index 0000000000..58f2df3bc9 --- /dev/null +++ b/Lang/TUSCRIPT/Variables @@ -0,0 +1 @@ +../../Task/Variables/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Walk-a-directory-Non-recursively b/Lang/TUSCRIPT/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..143418d1db --- /dev/null +++ b/Lang/TUSCRIPT/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Web-scraping b/Lang/TUSCRIPT/Web-scraping new file mode 120000 index 0000000000..5d71568d2f --- /dev/null +++ b/Lang/TUSCRIPT/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/Word-wrap b/Lang/TUSCRIPT/Word-wrap new file mode 120000 index 0000000000..d8eaea8bbc --- /dev/null +++ b/Lang/TUSCRIPT/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/XML-Input b/Lang/TUSCRIPT/XML-Input new file mode 120000 index 0000000000..19e727f73b --- /dev/null +++ b/Lang/TUSCRIPT/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/XML-Output b/Lang/TUSCRIPT/XML-Output new file mode 120000 index 0000000000..40bcf48844 --- /dev/null +++ b/Lang/TUSCRIPT/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/TUSCRIPT \ No newline at end of file diff --git a/Lang/TUSCRIPT/XML-XPath b/Lang/TUSCRIPT/XML-XPath new file mode 120000 index 0000000000..b002d5c37f --- /dev/null +++ b/Lang/TUSCRIPT/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/TUSCRIPT \ No newline at end of file diff --git a/Lang/TXR/Shell-one-liner b/Lang/TXR/Shell-one-liner new file mode 120000 index 0000000000..7493da6d40 --- /dev/null +++ b/Lang/TXR/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/TXR \ No newline at end of file diff --git a/Lang/TXR/Short-circuit-evaluation b/Lang/TXR/Short-circuit-evaluation new file mode 120000 index 0000000000..6657063fa2 --- /dev/null +++ b/Lang/TXR/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/TXR \ No newline at end of file diff --git a/Lang/TXR/Soundex b/Lang/TXR/Soundex new file mode 120000 index 0000000000..c20b180535 --- /dev/null +++ b/Lang/TXR/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/TXR \ No newline at end of file diff --git a/Lang/TXR/Strip-a-set-of-characters-from-a-string b/Lang/TXR/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..751584984d --- /dev/null +++ b/Lang/TXR/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/TXR \ No newline at end of file diff --git a/Lang/TXR/Strip-whitespace-from-a-string-Top-and-tail b/Lang/TXR/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..3faf45222a --- /dev/null +++ b/Lang/TXR/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/TXR \ No newline at end of file diff --git a/Lang/TXR/Tokenize-a-string b/Lang/TXR/Tokenize-a-string new file mode 120000 index 0000000000..253a0f0917 --- /dev/null +++ b/Lang/TXR/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/TXR \ No newline at end of file diff --git a/Lang/TXR/Unicode-strings b/Lang/TXR/Unicode-strings new file mode 120000 index 0000000000..935f184175 --- /dev/null +++ b/Lang/TXR/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/TXR \ No newline at end of file diff --git a/Lang/TXR/Update-a-configuration-file b/Lang/TXR/Update-a-configuration-file new file mode 120000 index 0000000000..b4dd71a401 --- /dev/null +++ b/Lang/TXR/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/TXR \ No newline at end of file diff --git a/Lang/TXR/Variables b/Lang/TXR/Variables new file mode 120000 index 0000000000..a3a179ffbb --- /dev/null +++ b/Lang/TXR/Variables @@ -0,0 +1 @@ +../../Task/Variables/TXR \ No newline at end of file diff --git a/Lang/TXR/Vigen-re-cipher b/Lang/TXR/Vigen-re-cipher new file mode 120000 index 0000000000..a248abf275 --- /dev/null +++ b/Lang/TXR/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/TXR \ No newline at end of file diff --git a/Lang/TXR/Web-scraping b/Lang/TXR/Web-scraping new file mode 120000 index 0000000000..8572d771f5 --- /dev/null +++ b/Lang/TXR/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/TXR \ No newline at end of file diff --git a/Lang/TXR/XML-Input b/Lang/TXR/XML-Input new file mode 120000 index 0000000000..1deb425251 --- /dev/null +++ b/Lang/TXR/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/TXR \ No newline at end of file diff --git a/Lang/TXR/Yahoo--search-interface b/Lang/TXR/Yahoo--search-interface new file mode 120000 index 0000000000..272ff5fca6 --- /dev/null +++ b/Lang/TXR/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/TXR \ No newline at end of file diff --git a/Lang/Tcl/SHA-1 b/Lang/Tcl/SHA-1 new file mode 120000 index 0000000000..250a438666 --- /dev/null +++ b/Lang/Tcl/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Tcl \ No newline at end of file diff --git a/Lang/Tcl/SHA-256 b/Lang/Tcl/SHA-256 new file mode 120000 index 0000000000..b8f1efe7a3 --- /dev/null +++ b/Lang/Tcl/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Tcl \ No newline at end of file diff --git a/Lang/Tcl/SOAP b/Lang/Tcl/SOAP new file mode 120000 index 0000000000..d959154ff7 --- /dev/null +++ b/Lang/Tcl/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Tcl \ No newline at end of file diff --git a/Lang/Tcl/SQL-based-authentication b/Lang/Tcl/SQL-based-authentication new file mode 120000 index 0000000000..4b987285e9 --- /dev/null +++ b/Lang/Tcl/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Set-puzzle b/Lang/Tcl/Set-puzzle new file mode 120000 index 0000000000..355ae35f78 --- /dev/null +++ b/Lang/Tcl/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Seven-sided-dice-from-five-sided-dice b/Lang/Tcl/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..0ab655f462 --- /dev/null +++ b/Lang/Tcl/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Shell-one-liner b/Lang/Tcl/Shell-one-liner new file mode 120000 index 0000000000..ce41263280 --- /dev/null +++ b/Lang/Tcl/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Short-circuit-evaluation b/Lang/Tcl/Short-circuit-evaluation new file mode 120000 index 0000000000..c156e26c64 --- /dev/null +++ b/Lang/Tcl/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Show-the-epoch b/Lang/Tcl/Show-the-epoch new file mode 120000 index 0000000000..07aaeea0cb --- /dev/null +++ b/Lang/Tcl/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sierpinski-carpet b/Lang/Tcl/Sierpinski-carpet new file mode 120000 index 0000000000..51199be46c --- /dev/null +++ b/Lang/Tcl/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sierpinski-triangle b/Lang/Tcl/Sierpinski-triangle new file mode 120000 index 0000000000..98ecb13866 --- /dev/null +++ b/Lang/Tcl/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sierpinski-triangle-Graphical b/Lang/Tcl/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..44aa5ec2fe --- /dev/null +++ b/Lang/Tcl/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sieve-of-Eratosthenes b/Lang/Tcl/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2886bd7fdf --- /dev/null +++ b/Lang/Tcl/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Simple-database b/Lang/Tcl/Simple-database new file mode 120000 index 0000000000..2c4d4f3864 --- /dev/null +++ b/Lang/Tcl/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Simple-windowed-application b/Lang/Tcl/Simple-windowed-application new file mode 120000 index 0000000000..4beb714c57 --- /dev/null +++ b/Lang/Tcl/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Simulate-input-Keyboard b/Lang/Tcl/Simulate-input-Keyboard new file mode 120000 index 0000000000..dcea537080 --- /dev/null +++ b/Lang/Tcl/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Simulate-input-Mouse b/Lang/Tcl/Simulate-input-Mouse new file mode 120000 index 0000000000..36716a8080 --- /dev/null +++ b/Lang/Tcl/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Singleton b/Lang/Tcl/Singleton new file mode 120000 index 0000000000..97b23efb17 --- /dev/null +++ b/Lang/Tcl/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Singly-linked-list-Element-definition b/Lang/Tcl/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..4a419f58ee --- /dev/null +++ b/Lang/Tcl/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Singly-linked-list-Element-insertion b/Lang/Tcl/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..9eca178200 --- /dev/null +++ b/Lang/Tcl/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Singly-linked-list-Traversal b/Lang/Tcl/Singly-linked-list-Traversal new file mode 120000 index 0000000000..24a40231ac --- /dev/null +++ b/Lang/Tcl/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sleep b/Lang/Tcl/Sleep new file mode 120000 index 0000000000..aa60724c8f --- /dev/null +++ b/Lang/Tcl/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sockets b/Lang/Tcl/Sockets new file mode 120000 index 0000000000..ca9a324523 --- /dev/null +++ b/Lang/Tcl/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sokoban b/Lang/Tcl/Sokoban new file mode 120000 index 0000000000..2f550cc42e --- /dev/null +++ b/Lang/Tcl/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Solve-a-Hidato-puzzle b/Lang/Tcl/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..94881d7494 --- /dev/null +++ b/Lang/Tcl/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sort-an-array-of-composite-structures b/Lang/Tcl/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..9abbe57858 --- /dev/null +++ b/Lang/Tcl/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sort-an-integer-array b/Lang/Tcl/Sort-an-integer-array new file mode 120000 index 0000000000..71532c11ab --- /dev/null +++ b/Lang/Tcl/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sort-disjoint-sublist b/Lang/Tcl/Sort-disjoint-sublist new file mode 120000 index 0000000000..1e2b740efd --- /dev/null +++ b/Lang/Tcl/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sort-using-a-custom-comparator b/Lang/Tcl/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..3e819f6b43 --- /dev/null +++ b/Lang/Tcl/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Bead-sort b/Lang/Tcl/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5721672b87 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Bogosort b/Lang/Tcl/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2f316d028e --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Bubble-sort b/Lang/Tcl/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..ee4542826c --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Cocktail-sort b/Lang/Tcl/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..938b2ed328 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Comb-sort b/Lang/Tcl/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..fc9b1022b0 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Counting-sort b/Lang/Tcl/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..92fe9c5ccb --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Gnome-sort b/Lang/Tcl/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..cfa81aa501 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Heapsort b/Lang/Tcl/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..0af79dee61 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Insertion-sort b/Lang/Tcl/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..494bac6542 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Merge-sort b/Lang/Tcl/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..8567e3db49 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Pancake-sort b/Lang/Tcl/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..83ab0359c2 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Permutation-sort b/Lang/Tcl/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..a7fc0ca4ca --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Quicksort b/Lang/Tcl/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..c181baa73e --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Radix-sort b/Lang/Tcl/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..b5412948f6 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Selection-sort b/Lang/Tcl/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..7caab5c607 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Shell-sort b/Lang/Tcl/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..0b6d3b1d1f --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Sleep-sort b/Lang/Tcl/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..68d26a14c6 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Stooge-sort b/Lang/Tcl/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..87282cf0e3 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sorting-algorithms-Strand-sort b/Lang/Tcl/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..20dd966554 --- /dev/null +++ b/Lang/Tcl/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Soundex b/Lang/Tcl/Soundex new file mode 120000 index 0000000000..313e213856 --- /dev/null +++ b/Lang/Tcl/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Special-characters b/Lang/Tcl/Special-characters new file mode 120000 index 0000000000..0ac93a5471 --- /dev/null +++ b/Lang/Tcl/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Special-variables b/Lang/Tcl/Special-variables new file mode 120000 index 0000000000..7a1c2350c6 --- /dev/null +++ b/Lang/Tcl/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Speech-synthesis b/Lang/Tcl/Speech-synthesis new file mode 120000 index 0000000000..035ee4c089 --- /dev/null +++ b/Lang/Tcl/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Spiral-matrix b/Lang/Tcl/Spiral-matrix new file mode 120000 index 0000000000..9d68437ae8 --- /dev/null +++ b/Lang/Tcl/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stable-marriage-problem b/Lang/Tcl/Stable-marriage-problem new file mode 120000 index 0000000000..5fb00f97ff --- /dev/null +++ b/Lang/Tcl/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stack b/Lang/Tcl/Stack new file mode 120000 index 0000000000..1220fdfcd0 --- /dev/null +++ b/Lang/Tcl/Stack @@ -0,0 +1 @@ +../../Task/Stack/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stack-traces b/Lang/Tcl/Stack-traces new file mode 120000 index 0000000000..aa5851db13 --- /dev/null +++ b/Lang/Tcl/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stair-climbing-puzzle b/Lang/Tcl/Stair-climbing-puzzle new file mode 120000 index 0000000000..0575f4ac63 --- /dev/null +++ b/Lang/Tcl/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Standard-deviation b/Lang/Tcl/Standard-deviation new file mode 120000 index 0000000000..32fdc71153 --- /dev/null +++ b/Lang/Tcl/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stem-and-leaf-plot b/Lang/Tcl/Stem-and-leaf-plot new file mode 120000 index 0000000000..66e1cb66d2 --- /dev/null +++ b/Lang/Tcl/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-case b/Lang/Tcl/String-case new file mode 120000 index 0000000000..5beecec422 --- /dev/null +++ b/Lang/Tcl/String-case @@ -0,0 +1 @@ +../../Task/String-case/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-comparison b/Lang/Tcl/String-comparison new file mode 120000 index 0000000000..3b7b5c8112 --- /dev/null +++ b/Lang/Tcl/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-concatenation b/Lang/Tcl/String-concatenation new file mode 120000 index 0000000000..8b02764b51 --- /dev/null +++ b/Lang/Tcl/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-interpolation--included- b/Lang/Tcl/String-interpolation--included- new file mode 120000 index 0000000000..f2e62bfb23 --- /dev/null +++ b/Lang/Tcl/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Tcl \ No newline at end of file diff --git a/Lang/Tcl/String-length b/Lang/Tcl/String-length new file mode 120000 index 0000000000..3a45307970 --- /dev/null +++ b/Lang/Tcl/String-length @@ -0,0 +1 @@ +../../Task/String-length/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strip-a-set-of-characters-from-a-string b/Lang/Tcl/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..3a4332dddf --- /dev/null +++ b/Lang/Tcl/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strip-block-comments b/Lang/Tcl/Strip-block-comments new file mode 120000 index 0000000000..cbefc70544 --- /dev/null +++ b/Lang/Tcl/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strip-comments-from-a-string b/Lang/Tcl/Strip-comments-from-a-string new file mode 120000 index 0000000000..9e5fe2b518 --- /dev/null +++ b/Lang/Tcl/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Tcl/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..f17fc2f9bc --- /dev/null +++ b/Lang/Tcl/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Tcl/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..7b4640f473 --- /dev/null +++ b/Lang/Tcl/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Substring b/Lang/Tcl/Substring new file mode 120000 index 0000000000..042fcd851d --- /dev/null +++ b/Lang/Tcl/Substring @@ -0,0 +1 @@ +../../Task/Substring/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Substring-Top-and-tail b/Lang/Tcl/Substring-Top-and-tail new file mode 120000 index 0000000000..4b325a2b10 --- /dev/null +++ b/Lang/Tcl/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Subtractive-generator b/Lang/Tcl/Subtractive-generator new file mode 120000 index 0000000000..c2f2acbb52 --- /dev/null +++ b/Lang/Tcl/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sudoku b/Lang/Tcl/Sudoku new file mode 120000 index 0000000000..07ad99e832 --- /dev/null +++ b/Lang/Tcl/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sum-and-product-of-an-array b/Lang/Tcl/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4c32b76dc0 --- /dev/null +++ b/Lang/Tcl/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sum-digits-of-an-integer b/Lang/Tcl/Sum-digits-of-an-integer new file mode 120000 index 0000000000..cdd21ebfdc --- /dev/null +++ b/Lang/Tcl/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sum-of-a-series b/Lang/Tcl/Sum-of-a-series new file mode 120000 index 0000000000..f057b85b17 --- /dev/null +++ b/Lang/Tcl/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sum-of-squares b/Lang/Tcl/Sum-of-squares new file mode 120000 index 0000000000..89473d6f57 --- /dev/null +++ b/Lang/Tcl/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Sutherland-Hodgman-polygon-clipping b/Lang/Tcl/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..992c417728 --- /dev/null +++ b/Lang/Tcl/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Symmetric-difference b/Lang/Tcl/Symmetric-difference new file mode 120000 index 0000000000..a378cd9db6 --- /dev/null +++ b/Lang/Tcl/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Synchronous-concurrency b/Lang/Tcl/Synchronous-concurrency new file mode 120000 index 0000000000..17a25e2b78 --- /dev/null +++ b/Lang/Tcl/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Tcl \ No newline at end of file diff --git a/Lang/Tcl/System-time b/Lang/Tcl/System-time new file mode 120000 index 0000000000..80a297dd7c --- /dev/null +++ b/Lang/Tcl/System-time @@ -0,0 +1 @@ +../../Task/System-time/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Table-creation-Postal-addresses b/Lang/Tcl/Table-creation-Postal-addresses new file mode 120000 index 0000000000..d281fd3b8e --- /dev/null +++ b/Lang/Tcl/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Take-notes-on-the-command-line b/Lang/Tcl/Take-notes-on-the-command-line new file mode 120000 index 0000000000..956255a266 --- /dev/null +++ b/Lang/Tcl/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Temperature-conversion b/Lang/Tcl/Temperature-conversion new file mode 120000 index 0000000000..f9ca3503ec --- /dev/null +++ b/Lang/Tcl/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Clear-the-screen b/Lang/Tcl/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..cf6724be28 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Coloured-text b/Lang/Tcl/Terminal-control-Coloured-text new file mode 120000 index 0000000000..357520e55b --- /dev/null +++ b/Lang/Tcl/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Cursor-movement b/Lang/Tcl/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..06fc29a158 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Cursor-positioning b/Lang/Tcl/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..a204e052b7 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Dimensions b/Lang/Tcl/Terminal-control-Dimensions new file mode 120000 index 0000000000..007322dd82 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Display-an-extended-character b/Lang/Tcl/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..17cd186dae --- /dev/null +++ b/Lang/Tcl/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Hiding-the-cursor b/Lang/Tcl/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..248084c380 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Inverse-video b/Lang/Tcl/Terminal-control-Inverse-video new file mode 120000 index 0000000000..f4cdf7831a --- /dev/null +++ b/Lang/Tcl/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Preserve-screen b/Lang/Tcl/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..71ed993ad1 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Ringing-the-terminal-bell b/Lang/Tcl/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..5e1c2258e5 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Terminal-control-Unicode-output b/Lang/Tcl/Terminal-control-Unicode-output new file mode 120000 index 0000000000..6b6d0eec07 --- /dev/null +++ b/Lang/Tcl/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Ternary-logic b/Lang/Tcl/Ternary-logic new file mode 120000 index 0000000000..4057990dd2 --- /dev/null +++ b/Lang/Tcl/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Test-a-function b/Lang/Tcl/Test-a-function new file mode 120000 index 0000000000..5be865809b --- /dev/null +++ b/Lang/Tcl/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Text-processing-1 b/Lang/Tcl/Text-processing-1 new file mode 120000 index 0000000000..89f36fd200 --- /dev/null +++ b/Lang/Tcl/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Text-processing-2 b/Lang/Tcl/Text-processing-2 new file mode 120000 index 0000000000..74428d7f86 --- /dev/null +++ b/Lang/Tcl/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Text-processing-Max-licenses-in-use b/Lang/Tcl/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..252e187bdd --- /dev/null +++ b/Lang/Tcl/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Thieles-interpolation-formula b/Lang/Tcl/Thieles-interpolation-formula new file mode 120000 index 0000000000..8f42e234e3 --- /dev/null +++ b/Lang/Tcl/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Tic-tac-toe b/Lang/Tcl/Tic-tac-toe new file mode 120000 index 0000000000..c4706b6ea9 --- /dev/null +++ b/Lang/Tcl/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Time-a-function b/Lang/Tcl/Time-a-function new file mode 120000 index 0000000000..3aa45ec8ab --- /dev/null +++ b/Lang/Tcl/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Tokenize-a-string b/Lang/Tcl/Tokenize-a-string new file mode 120000 index 0000000000..d3f2fd4e47 --- /dev/null +++ b/Lang/Tcl/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Top-rank-per-group b/Lang/Tcl/Top-rank-per-group new file mode 120000 index 0000000000..6bdc2b8eaf --- /dev/null +++ b/Lang/Tcl/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Topological-sort b/Lang/Tcl/Topological-sort new file mode 120000 index 0000000000..a3b2055146 --- /dev/null +++ b/Lang/Tcl/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Topswops b/Lang/Tcl/Topswops new file mode 120000 index 0000000000..b7dc8f833b --- /dev/null +++ b/Lang/Tcl/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Towers-of-Hanoi b/Lang/Tcl/Towers-of-Hanoi new file mode 120000 index 0000000000..1bd73e3a57 --- /dev/null +++ b/Lang/Tcl/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Trabb-Pardo-Knuth-algorithm b/Lang/Tcl/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..467aa900ad --- /dev/null +++ b/Lang/Tcl/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Tree-traversal b/Lang/Tcl/Tree-traversal new file mode 120000 index 0000000000..2276cc19c6 --- /dev/null +++ b/Lang/Tcl/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Trigonometric-functions b/Lang/Tcl/Trigonometric-functions new file mode 120000 index 0000000000..8c5813073f --- /dev/null +++ b/Lang/Tcl/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Truncatable-primes b/Lang/Tcl/Truncatable-primes new file mode 120000 index 0000000000..0326308d74 --- /dev/null +++ b/Lang/Tcl/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Truncate-a-file b/Lang/Tcl/Truncate-a-file new file mode 120000 index 0000000000..572880095d --- /dev/null +++ b/Lang/Tcl/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Twelve-statements b/Lang/Tcl/Twelve-statements new file mode 120000 index 0000000000..cd81588ab8 --- /dev/null +++ b/Lang/Tcl/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Tcl \ No newline at end of file diff --git a/Lang/Tcl/URL-decoding b/Lang/Tcl/URL-decoding new file mode 120000 index 0000000000..b0a48fcefd --- /dev/null +++ b/Lang/Tcl/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Tcl \ No newline at end of file diff --git a/Lang/Tcl/URL-encoding b/Lang/Tcl/URL-encoding new file mode 120000 index 0000000000..555aa2f313 --- /dev/null +++ b/Lang/Tcl/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Unbias-a-random-generator b/Lang/Tcl/Unbias-a-random-generator new file mode 120000 index 0000000000..5ec700e5bf --- /dev/null +++ b/Lang/Tcl/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Undefined-values b/Lang/Tcl/Undefined-values new file mode 120000 index 0000000000..e51168ec47 --- /dev/null +++ b/Lang/Tcl/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Unicode-variable-names b/Lang/Tcl/Unicode-variable-names new file mode 120000 index 0000000000..500bc3a4bb --- /dev/null +++ b/Lang/Tcl/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Universal-Turing-machine b/Lang/Tcl/Universal-Turing-machine new file mode 120000 index 0000000000..8738d4fc24 --- /dev/null +++ b/Lang/Tcl/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Update-a-configuration-file b/Lang/Tcl/Update-a-configuration-file new file mode 120000 index 0000000000..a05ce75c98 --- /dev/null +++ b/Lang/Tcl/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Use-another-language-to-call-a-function b/Lang/Tcl/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..7e35e6e9c3 --- /dev/null +++ b/Lang/Tcl/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Tcl \ No newline at end of file diff --git a/Lang/Tcl/User-input-Graphical b/Lang/Tcl/User-input-Graphical new file mode 120000 index 0000000000..9d2484d580 --- /dev/null +++ b/Lang/Tcl/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Tcl \ No newline at end of file diff --git a/Lang/Tcl/User-input-Text b/Lang/Tcl/User-input-Text new file mode 120000 index 0000000000..ea779a3533 --- /dev/null +++ b/Lang/Tcl/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Vampire-number b/Lang/Tcl/Vampire-number new file mode 120000 index 0000000000..6afe2c3185 --- /dev/null +++ b/Lang/Tcl/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Van-der-Corput-sequence b/Lang/Tcl/Van-der-Corput-sequence new file mode 120000 index 0000000000..6163c1c653 --- /dev/null +++ b/Lang/Tcl/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Variable-length-quantity b/Lang/Tcl/Variable-length-quantity new file mode 120000 index 0000000000..b9ef05d6bb --- /dev/null +++ b/Lang/Tcl/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Variable-size-Get b/Lang/Tcl/Variable-size-Get new file mode 120000 index 0000000000..5fa2eaf25f --- /dev/null +++ b/Lang/Tcl/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Variable-size-Set b/Lang/Tcl/Variable-size-Set new file mode 120000 index 0000000000..8a6175be82 --- /dev/null +++ b/Lang/Tcl/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Variables b/Lang/Tcl/Variables new file mode 120000 index 0000000000..e7560a5383 --- /dev/null +++ b/Lang/Tcl/Variables @@ -0,0 +1 @@ +../../Task/Variables/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Variadic-function b/Lang/Tcl/Variadic-function new file mode 120000 index 0000000000..2e0b95ce65 --- /dev/null +++ b/Lang/Tcl/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Vector-products b/Lang/Tcl/Vector-products new file mode 120000 index 0000000000..38b89fe144 --- /dev/null +++ b/Lang/Tcl/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Verify-distribution-uniformity-Chi-squared-test b/Lang/Tcl/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..abfc28eb47 --- /dev/null +++ b/Lang/Tcl/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Verify-distribution-uniformity-Naive b/Lang/Tcl/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..9671c1b204 --- /dev/null +++ b/Lang/Tcl/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Vigen-re-cipher b/Lang/Tcl/Vigen-re-cipher new file mode 120000 index 0000000000..ba31a9ff92 --- /dev/null +++ b/Lang/Tcl/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Vigen-re-cipher-Cryptanalysis b/Lang/Tcl/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..047f630b6b --- /dev/null +++ b/Lang/Tcl/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Visualize-a-tree b/Lang/Tcl/Visualize-a-tree new file mode 120000 index 0000000000..2ec3f291de --- /dev/null +++ b/Lang/Tcl/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Voronoi-diagram b/Lang/Tcl/Voronoi-diagram new file mode 120000 index 0000000000..93b2a4dc53 --- /dev/null +++ b/Lang/Tcl/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Walk-a-directory-Non-recursively b/Lang/Tcl/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..ec10a8924f --- /dev/null +++ b/Lang/Tcl/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Walk-a-directory-Recursively b/Lang/Tcl/Walk-a-directory-Recursively new file mode 120000 index 0000000000..6926bd34e1 --- /dev/null +++ b/Lang/Tcl/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Web-scraping b/Lang/Tcl/Web-scraping new file mode 120000 index 0000000000..de94b9ae20 --- /dev/null +++ b/Lang/Tcl/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Window-creation b/Lang/Tcl/Window-creation new file mode 120000 index 0000000000..287acaa93c --- /dev/null +++ b/Lang/Tcl/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Window-creation-X11 b/Lang/Tcl/Window-creation-X11 new file mode 120000 index 0000000000..6852428f7f --- /dev/null +++ b/Lang/Tcl/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Window-management b/Lang/Tcl/Window-management new file mode 120000 index 0000000000..68c2a97d1a --- /dev/null +++ b/Lang/Tcl/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Word-wrap b/Lang/Tcl/Word-wrap new file mode 120000 index 0000000000..bc77805151 --- /dev/null +++ b/Lang/Tcl/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Write-float-arrays-to-a-text-file b/Lang/Tcl/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..8591446778 --- /dev/null +++ b/Lang/Tcl/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Write-language-name-in-3D-ASCII b/Lang/Tcl/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..e534b3759f --- /dev/null +++ b/Lang/Tcl/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Write-to-Windows-event-log b/Lang/Tcl/Write-to-Windows-event-log new file mode 120000 index 0000000000..7c78f2b565 --- /dev/null +++ b/Lang/Tcl/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Tcl \ No newline at end of file diff --git a/Lang/Tcl/XML-DOM-serialization b/Lang/Tcl/XML-DOM-serialization new file mode 120000 index 0000000000..01fdd83ce0 --- /dev/null +++ b/Lang/Tcl/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Tcl \ No newline at end of file diff --git a/Lang/Tcl/XML-Input b/Lang/Tcl/XML-Input new file mode 120000 index 0000000000..05a645374a --- /dev/null +++ b/Lang/Tcl/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Tcl \ No newline at end of file diff --git a/Lang/Tcl/XML-Output b/Lang/Tcl/XML-Output new file mode 120000 index 0000000000..34fcfdaff4 --- /dev/null +++ b/Lang/Tcl/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Tcl \ No newline at end of file diff --git a/Lang/Tcl/XML-XPath b/Lang/Tcl/XML-XPath new file mode 120000 index 0000000000..e6da0b6d72 --- /dev/null +++ b/Lang/Tcl/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Xiaolin-Wus-line-algorithm b/Lang/Tcl/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..41951d3d04 --- /dev/null +++ b/Lang/Tcl/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Yahoo--search-interface b/Lang/Tcl/Yahoo--search-interface new file mode 120000 index 0000000000..e5eff735ae --- /dev/null +++ b/Lang/Tcl/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Yin-and-yang b/Lang/Tcl/Yin-and-yang new file mode 120000 index 0000000000..22a2068759 --- /dev/null +++ b/Lang/Tcl/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Zebra-puzzle b/Lang/Tcl/Zebra-puzzle new file mode 120000 index 0000000000..8aaaaf7256 --- /dev/null +++ b/Lang/Tcl/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Zeckendorf-number-representation b/Lang/Tcl/Zeckendorf-number-representation new file mode 120000 index 0000000000..752edb39c8 --- /dev/null +++ b/Lang/Tcl/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Zig-zag-matrix b/Lang/Tcl/Zig-zag-matrix new file mode 120000 index 0000000000..52ca65c635 --- /dev/null +++ b/Lang/Tcl/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Tcl \ No newline at end of file diff --git a/Lang/Toka/Sockets b/Lang/Toka/Sockets new file mode 120000 index 0000000000..9d2ca0bb8c --- /dev/null +++ b/Lang/Toka/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Toka \ No newline at end of file diff --git a/Lang/Toka/Sort-an-integer-array b/Lang/Toka/Sort-an-integer-array new file mode 120000 index 0000000000..a390d224ea --- /dev/null +++ b/Lang/Toka/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Toka \ No newline at end of file diff --git a/Lang/Toka/Sorting-algorithms-Bubble-sort b/Lang/Toka/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8c1324b41b --- /dev/null +++ b/Lang/Toka/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Toka \ No newline at end of file diff --git a/Lang/Toka/String-length b/Lang/Toka/String-length new file mode 120000 index 0000000000..827e1c2129 --- /dev/null +++ b/Lang/Toka/String-length @@ -0,0 +1 @@ +../../Task/String-length/Toka \ No newline at end of file diff --git a/Lang/Toka/Sum-and-product-of-an-array b/Lang/Toka/Sum-and-product-of-an-array new file mode 120000 index 0000000000..1f6fe65f95 --- /dev/null +++ b/Lang/Toka/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Toka \ No newline at end of file diff --git a/Lang/Toka/Towers-of-Hanoi b/Lang/Toka/Towers-of-Hanoi new file mode 120000 index 0000000000..5085fffaa9 --- /dev/null +++ b/Lang/Toka/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Toka \ No newline at end of file diff --git a/Lang/Toka/User-input-Text b/Lang/Toka/User-input-Text new file mode 120000 index 0000000000..89d1cc3d10 --- /dev/null +++ b/Lang/Toka/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Toka \ No newline at end of file diff --git a/Lang/Toka/Variable-size-Get b/Lang/Toka/Variable-size-Get new file mode 120000 index 0000000000..96cce6deb5 --- /dev/null +++ b/Lang/Toka/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Toka \ No newline at end of file diff --git a/Lang/Toka/Walk-a-directory-Non-recursively b/Lang/Toka/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..cd4e493ae6 --- /dev/null +++ b/Lang/Toka/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Toka \ No newline at end of file diff --git a/Lang/TorqueScript/String-concatenation b/Lang/TorqueScript/String-concatenation new file mode 120000 index 0000000000..38a681fbfd --- /dev/null +++ b/Lang/TorqueScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/TorqueScript \ No newline at end of file diff --git a/Lang/TorqueScript/Time-a-function b/Lang/TorqueScript/Time-a-function new file mode 120000 index 0000000000..427d0989a3 --- /dev/null +++ b/Lang/TorqueScript/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/TorqueScript \ No newline at end of file diff --git a/Lang/Transact-SQL/Table-creation-Postal-addresses b/Lang/Transact-SQL/Table-creation-Postal-addresses new file mode 120000 index 0000000000..7d250da74d --- /dev/null +++ b/Lang/Transact-SQL/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Transact-SQL \ No newline at end of file diff --git a/Lang/Trith/Singly-linked-list-Traversal b/Lang/Trith/Singly-linked-list-Traversal new file mode 120000 index 0000000000..a2d12303d8 --- /dev/null +++ b/Lang/Trith/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Trith \ No newline at end of file diff --git a/Lang/Trith/String-length b/Lang/Trith/String-length new file mode 120000 index 0000000000..7e529a1f96 --- /dev/null +++ b/Lang/Trith/String-length @@ -0,0 +1 @@ +../../Task/String-length/Trith \ No newline at end of file diff --git a/Lang/Trith/Sum-and-product-of-an-array b/Lang/Trith/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a8c6fc9eea --- /dev/null +++ b/Lang/Trith/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Trith \ No newline at end of file diff --git a/Lang/Trith/Sum-of-squares b/Lang/Trith/Sum-of-squares new file mode 120000 index 0000000000..9080d8e41b --- /dev/null +++ b/Lang/Trith/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Trith \ No newline at end of file diff --git a/Lang/UNIX-Shell/SHA-1 b/Lang/UNIX-Shell/SHA-1 new file mode 120000 index 0000000000..1a072e24ec --- /dev/null +++ b/Lang/UNIX-Shell/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Shell-one-liner b/Lang/UNIX-Shell/Shell-one-liner new file mode 120000 index 0000000000..daa2d0a92c --- /dev/null +++ b/Lang/UNIX-Shell/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Short-circuit-evaluation b/Lang/UNIX-Shell/Short-circuit-evaluation new file mode 120000 index 0000000000..ef0c197fa9 --- /dev/null +++ b/Lang/UNIX-Shell/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Show-the-epoch b/Lang/UNIX-Shell/Show-the-epoch new file mode 120000 index 0000000000..3e8525713c --- /dev/null +++ b/Lang/UNIX-Shell/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sieve-of-Eratosthenes b/Lang/UNIX-Shell/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..68579734e7 --- /dev/null +++ b/Lang/UNIX-Shell/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Simple-database b/Lang/UNIX-Shell/Simple-database new file mode 120000 index 0000000000..d01ca7045c --- /dev/null +++ b/Lang/UNIX-Shell/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sleep b/Lang/UNIX-Shell/Sleep new file mode 120000 index 0000000000..6a289fc952 --- /dev/null +++ b/Lang/UNIX-Shell/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sockets b/Lang/UNIX-Shell/Sockets new file mode 120000 index 0000000000..72f161a6ea --- /dev/null +++ b/Lang/UNIX-Shell/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sort-an-array-of-composite-structures b/Lang/UNIX-Shell/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..fc036bbe8d --- /dev/null +++ b/Lang/UNIX-Shell/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sort-an-integer-array b/Lang/UNIX-Shell/Sort-an-integer-array new file mode 120000 index 0000000000..400e17bfc1 --- /dev/null +++ b/Lang/UNIX-Shell/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sorting-algorithms-Sleep-sort b/Lang/UNIX-Shell/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..caf0c10712 --- /dev/null +++ b/Lang/UNIX-Shell/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Speech-synthesis b/Lang/UNIX-Shell/Speech-synthesis new file mode 120000 index 0000000000..f699bbbda1 --- /dev/null +++ b/Lang/UNIX-Shell/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/String-case b/Lang/UNIX-Shell/String-case new file mode 120000 index 0000000000..058008e1ba --- /dev/null +++ b/Lang/UNIX-Shell/String-case @@ -0,0 +1 @@ +../../Task/String-case/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/String-comparison b/Lang/UNIX-Shell/String-comparison new file mode 120000 index 0000000000..921c3527a9 --- /dev/null +++ b/Lang/UNIX-Shell/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/String-concatenation b/Lang/UNIX-Shell/String-concatenation new file mode 120000 index 0000000000..ed1b20e0a4 --- /dev/null +++ b/Lang/UNIX-Shell/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/String-interpolation--included- b/Lang/UNIX-Shell/String-interpolation--included- new file mode 120000 index 0000000000..1c902be5d9 --- /dev/null +++ b/Lang/UNIX-Shell/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/String-length b/Lang/UNIX-Shell/String-length new file mode 120000 index 0000000000..e1369356a3 --- /dev/null +++ b/Lang/UNIX-Shell/String-length @@ -0,0 +1 @@ +../../Task/String-length/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Strip-a-set-of-characters-from-a-string b/Lang/UNIX-Shell/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..076f620cdc --- /dev/null +++ b/Lang/UNIX-Shell/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Strip-comments-from-a-string b/Lang/UNIX-Shell/Strip-comments-from-a-string new file mode 120000 index 0000000000..b8e7307d34 --- /dev/null +++ b/Lang/UNIX-Shell/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Substring b/Lang/UNIX-Shell/Substring new file mode 120000 index 0000000000..623c90596f --- /dev/null +++ b/Lang/UNIX-Shell/Substring @@ -0,0 +1 @@ +../../Task/Substring/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Substring-Top-and-tail b/Lang/UNIX-Shell/Substring-Top-and-tail new file mode 120000 index 0000000000..b38f6b07a0 --- /dev/null +++ b/Lang/UNIX-Shell/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Sum-and-product-of-an-array b/Lang/UNIX-Shell/Sum-and-product-of-an-array new file mode 120000 index 0000000000..371e38745e --- /dev/null +++ b/Lang/UNIX-Shell/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Symmetric-difference b/Lang/UNIX-Shell/Symmetric-difference new file mode 120000 index 0000000000..e66914bc28 --- /dev/null +++ b/Lang/UNIX-Shell/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/System-time b/Lang/UNIX-Shell/System-time new file mode 120000 index 0000000000..a77e13d2b9 --- /dev/null +++ b/Lang/UNIX-Shell/System-time @@ -0,0 +1 @@ +../../Task/System-time/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Take-notes-on-the-command-line b/Lang/UNIX-Shell/Take-notes-on-the-command-line new file mode 120000 index 0000000000..efaec7bc91 --- /dev/null +++ b/Lang/UNIX-Shell/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Clear-the-screen b/Lang/UNIX-Shell/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..014ebfbe3e --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Cursor-movement b/Lang/UNIX-Shell/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..924a8035f8 --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Cursor-positioning b/Lang/UNIX-Shell/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..61ae89316f --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Dimensions b/Lang/UNIX-Shell/Terminal-control-Dimensions new file mode 120000 index 0000000000..f6fcd7125d --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Hiding-the-cursor b/Lang/UNIX-Shell/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..3eabcfa4bf --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Inverse-video b/Lang/UNIX-Shell/Terminal-control-Inverse-video new file mode 120000 index 0000000000..f22a15e3f9 --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Preserve-screen b/Lang/UNIX-Shell/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..8e3ae30642 --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Ringing-the-terminal-bell b/Lang/UNIX-Shell/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..ca579fa6fd --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Terminal-control-Unicode-output b/Lang/UNIX-Shell/Terminal-control-Unicode-output new file mode 120000 index 0000000000..eb513756f6 --- /dev/null +++ b/Lang/UNIX-Shell/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Time-a-function b/Lang/UNIX-Shell/Time-a-function new file mode 120000 index 0000000000..8476458c0e --- /dev/null +++ b/Lang/UNIX-Shell/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Tokenize-a-string b/Lang/UNIX-Shell/Tokenize-a-string new file mode 120000 index 0000000000..03c4eef117 --- /dev/null +++ b/Lang/UNIX-Shell/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Topic-variable b/Lang/UNIX-Shell/Topic-variable new file mode 120000 index 0000000000..21402ff416 --- /dev/null +++ b/Lang/UNIX-Shell/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Topological-sort b/Lang/UNIX-Shell/Topological-sort new file mode 120000 index 0000000000..cce2db2fd6 --- /dev/null +++ b/Lang/UNIX-Shell/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Towers-of-Hanoi b/Lang/UNIX-Shell/Towers-of-Hanoi new file mode 120000 index 0000000000..52e6233820 --- /dev/null +++ b/Lang/UNIX-Shell/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Tree-traversal b/Lang/UNIX-Shell/Tree-traversal new file mode 120000 index 0000000000..f45300de16 --- /dev/null +++ b/Lang/UNIX-Shell/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Truncate-a-file b/Lang/UNIX-Shell/Truncate-a-file new file mode 120000 index 0000000000..b50e884c3d --- /dev/null +++ b/Lang/UNIX-Shell/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/URL-decoding b/Lang/UNIX-Shell/URL-decoding new file mode 120000 index 0000000000..2743c1e509 --- /dev/null +++ b/Lang/UNIX-Shell/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/URL-encoding b/Lang/UNIX-Shell/URL-encoding new file mode 120000 index 0000000000..292e976b05 --- /dev/null +++ b/Lang/UNIX-Shell/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Undefined-values b/Lang/UNIX-Shell/Undefined-values new file mode 120000 index 0000000000..6813d79f70 --- /dev/null +++ b/Lang/UNIX-Shell/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/User-input-Text b/Lang/UNIX-Shell/User-input-Text new file mode 120000 index 0000000000..d6e0c41b2f --- /dev/null +++ b/Lang/UNIX-Shell/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Variable-size-Get b/Lang/UNIX-Shell/Variable-size-Get new file mode 120000 index 0000000000..c96afde74c --- /dev/null +++ b/Lang/UNIX-Shell/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Variables b/Lang/UNIX-Shell/Variables new file mode 120000 index 0000000000..dfd35dbbcf --- /dev/null +++ b/Lang/UNIX-Shell/Variables @@ -0,0 +1 @@ +../../Task/Variables/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Video-display-modes b/Lang/UNIX-Shell/Video-display-modes new file mode 120000 index 0000000000..6a6dd4acd6 --- /dev/null +++ b/Lang/UNIX-Shell/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Walk-a-directory-Non-recursively b/Lang/UNIX-Shell/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..f9003f2c1b --- /dev/null +++ b/Lang/UNIX-Shell/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Walk-a-directory-Recursively b/Lang/UNIX-Shell/Walk-a-directory-Recursively new file mode 120000 index 0000000000..9dae226150 --- /dev/null +++ b/Lang/UNIX-Shell/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Web-scraping b/Lang/UNIX-Shell/Web-scraping new file mode 120000 index 0000000000..b6408481ac --- /dev/null +++ b/Lang/UNIX-Shell/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/UNIX-Shell \ No newline at end of file diff --git a/Lang/Unicon/Simple-windowed-application b/Lang/Unicon/Simple-windowed-application new file mode 120000 index 0000000000..4e05b395d7 --- /dev/null +++ b/Lang/Unicon/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Unicon \ No newline at end of file diff --git a/Lang/UnixPipes/Sorting-algorithms-Bubble-sort b/Lang/UnixPipes/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..b6dd1e6924 --- /dev/null +++ b/Lang/UnixPipes/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sorting-algorithms-Insertion-sort b/Lang/UnixPipes/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..ff4d9c71b2 --- /dev/null +++ b/Lang/UnixPipes/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sorting-algorithms-Merge-sort b/Lang/UnixPipes/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..2785d6eeb6 --- /dev/null +++ b/Lang/UnixPipes/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sorting-algorithms-Quicksort b/Lang/UnixPipes/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..e61bdea335 --- /dev/null +++ b/Lang/UnixPipes/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Stack b/Lang/UnixPipes/Stack new file mode 120000 index 0000000000..a87323a815 --- /dev/null +++ b/Lang/UnixPipes/Stack @@ -0,0 +1 @@ +../../Task/Stack/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/String-concatenation b/Lang/UnixPipes/String-concatenation new file mode 120000 index 0000000000..cecfd09c84 --- /dev/null +++ b/Lang/UnixPipes/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sum-and-product-of-an-array b/Lang/UnixPipes/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c05ecaf1cb --- /dev/null +++ b/Lang/UnixPipes/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sum-of-a-series b/Lang/UnixPipes/Sum-of-a-series new file mode 120000 index 0000000000..4b8cde6410 --- /dev/null +++ b/Lang/UnixPipes/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Sum-of-squares b/Lang/UnixPipes/Sum-of-squares new file mode 120000 index 0000000000..ea219159e1 --- /dev/null +++ b/Lang/UnixPipes/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Synchronous-concurrency b/Lang/UnixPipes/Synchronous-concurrency new file mode 120000 index 0000000000..1165001f50 --- /dev/null +++ b/Lang/UnixPipes/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Tokenize-a-string b/Lang/UnixPipes/Tokenize-a-string new file mode 120000 index 0000000000..7adfb4518a --- /dev/null +++ b/Lang/UnixPipes/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Walk-a-directory-Non-recursively b/Lang/UnixPipes/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..43539a8313 --- /dev/null +++ b/Lang/UnixPipes/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/UnixPipes \ No newline at end of file diff --git a/Lang/UnixPipes/Walk-a-directory-Recursively b/Lang/UnixPipes/Walk-a-directory-Recursively new file mode 120000 index 0000000000..c8568c2e50 --- /dev/null +++ b/Lang/UnixPipes/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/UnixPipes \ No newline at end of file diff --git a/Lang/Unlambda/Sierpinski-triangle b/Lang/Unlambda/Sierpinski-triangle new file mode 120000 index 0000000000..fb4a896fff --- /dev/null +++ b/Lang/Unlambda/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Unlambda \ No newline at end of file diff --git a/Lang/Ursala/Shell-one-liner b/Lang/Ursala/Shell-one-liner new file mode 120000 index 0000000000..c956f91457 --- /dev/null +++ b/Lang/Ursala/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sierpinski-carpet b/Lang/Ursala/Sierpinski-carpet new file mode 120000 index 0000000000..95e3065ae4 --- /dev/null +++ b/Lang/Ursala/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sierpinski-triangle b/Lang/Ursala/Sierpinski-triangle new file mode 120000 index 0000000000..9e4c5f9e4a --- /dev/null +++ b/Lang/Ursala/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sieve-of-Eratosthenes b/Lang/Ursala/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..85cb03c2c2 --- /dev/null +++ b/Lang/Ursala/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sort-an-array-of-composite-structures b/Lang/Ursala/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..806de3d4b5 --- /dev/null +++ b/Lang/Ursala/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sort-an-integer-array b/Lang/Ursala/Sort-an-integer-array new file mode 120000 index 0000000000..620fac2559 --- /dev/null +++ b/Lang/Ursala/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sort-disjoint-sublist b/Lang/Ursala/Sort-disjoint-sublist new file mode 120000 index 0000000000..d7e9ad7ee0 --- /dev/null +++ b/Lang/Ursala/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sort-using-a-custom-comparator b/Lang/Ursala/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..2b0f3c3a74 --- /dev/null +++ b/Lang/Ursala/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Bogosort b/Lang/Ursala/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..8147a9c883 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Bubble-sort b/Lang/Ursala/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..28ad0a3c0d --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Cocktail-sort b/Lang/Ursala/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..3df962ef31 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Gnome-sort b/Lang/Ursala/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..fc2793ed09 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Insertion-sort b/Lang/Ursala/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..3e24bca44a --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Merge-sort b/Lang/Ursala/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..517a85b745 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Permutation-sort b/Lang/Ursala/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..05e1e68539 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Quicksort b/Lang/Ursala/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..655f34f82c --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Selection-sort b/Lang/Ursala/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..96d5237188 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sorting-algorithms-Strand-sort b/Lang/Ursala/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..edc1fd1bf2 --- /dev/null +++ b/Lang/Ursala/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Spiral-matrix b/Lang/Ursala/Spiral-matrix new file mode 120000 index 0000000000..d573d9bb36 --- /dev/null +++ b/Lang/Ursala/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Stable-marriage-problem b/Lang/Ursala/Stable-marriage-problem new file mode 120000 index 0000000000..d633646c8a --- /dev/null +++ b/Lang/Ursala/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Stem-and-leaf-plot b/Lang/Ursala/Stem-and-leaf-plot new file mode 120000 index 0000000000..e5eebeefb1 --- /dev/null +++ b/Lang/Ursala/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Ursala \ No newline at end of file diff --git a/Lang/Ursala/String-case b/Lang/Ursala/String-case new file mode 120000 index 0000000000..897abf29dc --- /dev/null +++ b/Lang/Ursala/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ursala \ No newline at end of file diff --git a/Lang/Ursala/String-interpolation--included- b/Lang/Ursala/String-interpolation--included- new file mode 120000 index 0000000000..e3242cb563 --- /dev/null +++ b/Lang/Ursala/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Strip-a-set-of-characters-from-a-string b/Lang/Ursala/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..419175a258 --- /dev/null +++ b/Lang/Ursala/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Ursala/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..de5245aaad --- /dev/null +++ b/Lang/Ursala/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sudoku b/Lang/Ursala/Sudoku new file mode 120000 index 0000000000..75a9953034 --- /dev/null +++ b/Lang/Ursala/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sum-and-product-of-an-array b/Lang/Ursala/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c7b4706de4 --- /dev/null +++ b/Lang/Ursala/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sum-of-a-series b/Lang/Ursala/Sum-of-a-series new file mode 120000 index 0000000000..2650c0038b --- /dev/null +++ b/Lang/Ursala/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Sum-of-squares b/Lang/Ursala/Sum-of-squares new file mode 120000 index 0000000000..ed5abca414 --- /dev/null +++ b/Lang/Ursala/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Symmetric-difference b/Lang/Ursala/Symmetric-difference new file mode 120000 index 0000000000..e9f7108997 --- /dev/null +++ b/Lang/Ursala/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Ursala \ No newline at end of file diff --git a/Lang/Ursala/System-time b/Lang/Ursala/System-time new file mode 120000 index 0000000000..101ee3746d --- /dev/null +++ b/Lang/Ursala/System-time @@ -0,0 +1 @@ +../../Task/System-time/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Text-processing-1 b/Lang/Ursala/Text-processing-1 new file mode 120000 index 0000000000..48f95c34d0 --- /dev/null +++ b/Lang/Ursala/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Text-processing-2 b/Lang/Ursala/Text-processing-2 new file mode 120000 index 0000000000..f360921515 --- /dev/null +++ b/Lang/Ursala/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Text-processing-Max-licenses-in-use b/Lang/Ursala/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..4c40bdeaa5 --- /dev/null +++ b/Lang/Ursala/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Tokenize-a-string b/Lang/Ursala/Tokenize-a-string new file mode 120000 index 0000000000..87dfccc8e7 --- /dev/null +++ b/Lang/Ursala/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Top-rank-per-group b/Lang/Ursala/Top-rank-per-group new file mode 120000 index 0000000000..b129a563d3 --- /dev/null +++ b/Lang/Ursala/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Topological-sort b/Lang/Ursala/Topological-sort new file mode 120000 index 0000000000..1bff5557ea --- /dev/null +++ b/Lang/Ursala/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Towers-of-Hanoi b/Lang/Ursala/Towers-of-Hanoi new file mode 120000 index 0000000000..92101ce49b --- /dev/null +++ b/Lang/Ursala/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Tree-traversal b/Lang/Ursala/Tree-traversal new file mode 120000 index 0000000000..1d28be973c --- /dev/null +++ b/Lang/Ursala/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Variable-size-Get b/Lang/Ursala/Variable-size-Get new file mode 120000 index 0000000000..93506c72f2 --- /dev/null +++ b/Lang/Ursala/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Variable-size-Set b/Lang/Ursala/Variable-size-Set new file mode 120000 index 0000000000..f81cbf4b98 --- /dev/null +++ b/Lang/Ursala/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Variadic-function b/Lang/Ursala/Variadic-function new file mode 120000 index 0000000000..f2cf4c40a1 --- /dev/null +++ b/Lang/Ursala/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Web-scraping b/Lang/Ursala/Web-scraping new file mode 120000 index 0000000000..7f8ca6ae3f --- /dev/null +++ b/Lang/Ursala/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Wireworld b/Lang/Ursala/Wireworld new file mode 120000 index 0000000000..effa7ad307 --- /dev/null +++ b/Lang/Ursala/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Y-combinator b/Lang/Ursala/Y-combinator new file mode 120000 index 0000000000..0205d965ae --- /dev/null +++ b/Lang/Ursala/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Ursala \ No newline at end of file diff --git a/Lang/Ursala/Zig-zag-matrix b/Lang/Ursala/Zig-zag-matrix new file mode 120000 index 0000000000..e1feb95d70 --- /dev/null +++ b/Lang/Ursala/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Ursala \ No newline at end of file diff --git a/Lang/V/Sorting-algorithms-Merge-sort b/Lang/V/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e9963d702b --- /dev/null +++ b/Lang/V/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/V \ No newline at end of file diff --git a/Lang/V/Sorting-algorithms-Quicksort b/Lang/V/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..ba361a6aa1 --- /dev/null +++ b/Lang/V/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/V \ No newline at end of file diff --git a/Lang/V/Sum-and-product-of-an-array b/Lang/V/Sum-and-product-of-an-array new file mode 120000 index 0000000000..db2826a1e8 --- /dev/null +++ b/Lang/V/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/V \ No newline at end of file diff --git a/Lang/V/Sum-of-squares b/Lang/V/Sum-of-squares new file mode 120000 index 0000000000..223e77242a --- /dev/null +++ b/Lang/V/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/V \ No newline at end of file diff --git a/Lang/V/Variadic-function b/Lang/V/Variadic-function new file mode 120000 index 0000000000..1f6c2ef6e1 --- /dev/null +++ b/Lang/V/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/V \ No newline at end of file diff --git a/Lang/VBA/Sorting-algorithms-Pancake-sort b/Lang/VBA/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..eba04c18e5 --- /dev/null +++ b/Lang/VBA/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/VBA \ No newline at end of file diff --git a/Lang/VBA/Sorting-algorithms-Quicksort b/Lang/VBA/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..0fbfd8e20a --- /dev/null +++ b/Lang/VBA/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/VBA \ No newline at end of file diff --git a/Lang/VBA/Sorting-algorithms-Selection-sort b/Lang/VBA/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..1290d3ccaa --- /dev/null +++ b/Lang/VBA/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/VBA \ No newline at end of file diff --git a/Lang/VBA/Stack b/Lang/VBA/Stack new file mode 120000 index 0000000000..e5fc517c4f --- /dev/null +++ b/Lang/VBA/Stack @@ -0,0 +1 @@ +../../Task/Stack/VBA \ No newline at end of file diff --git a/Lang/VBA/Sudoku b/Lang/VBA/Sudoku new file mode 120000 index 0000000000..143450ab9c --- /dev/null +++ b/Lang/VBA/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/VBA \ No newline at end of file diff --git a/Lang/VBA/Zig-zag-matrix b/Lang/VBA/Zig-zag-matrix new file mode 120000 index 0000000000..4463c6f082 --- /dev/null +++ b/Lang/VBA/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/VBA \ No newline at end of file diff --git a/Lang/VBScript/SOAP b/Lang/VBScript/SOAP new file mode 120000 index 0000000000..95f81e8456 --- /dev/null +++ b/Lang/VBScript/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Seven-sided-dice-from-five-sided-dice b/Lang/VBScript/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..8bf6f28008 --- /dev/null +++ b/Lang/VBScript/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Simulate-input-Keyboard b/Lang/VBScript/Simulate-input-Keyboard new file mode 120000 index 0000000000..00c18e012a --- /dev/null +++ b/Lang/VBScript/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sleep b/Lang/VBScript/Sleep new file mode 120000 index 0000000000..315ea95d58 --- /dev/null +++ b/Lang/VBScript/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Bogosort b/Lang/VBScript/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..6ea5321db1 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Bubble-sort b/Lang/VBScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..f49a03588f --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Cocktail-sort b/Lang/VBScript/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..4276e43f65 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Counting-sort b/Lang/VBScript/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..85017e6d16 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Gnome-sort b/Lang/VBScript/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..79faa47b00 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Soundex b/Lang/VBScript/Soundex new file mode 120000 index 0000000000..57b53e0251 --- /dev/null +++ b/Lang/VBScript/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Speech-synthesis b/Lang/VBScript/Speech-synthesis new file mode 120000 index 0000000000..5007a21b86 --- /dev/null +++ b/Lang/VBScript/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Stack b/Lang/VBScript/Stack new file mode 120000 index 0000000000..169b81fefc --- /dev/null +++ b/Lang/VBScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/VBScript \ No newline at end of file diff --git a/Lang/VBScript/String-case b/Lang/VBScript/String-case new file mode 120000 index 0000000000..a5563a7dbe --- /dev/null +++ b/Lang/VBScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/VBScript \ No newline at end of file diff --git a/Lang/VBScript/String-length b/Lang/VBScript/String-length new file mode 120000 index 0000000000..c555bdf767 --- /dev/null +++ b/Lang/VBScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Tokenize-a-string b/Lang/VBScript/Tokenize-a-string new file mode 120000 index 0000000000..5a81646fd8 --- /dev/null +++ b/Lang/VBScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Topological-sort b/Lang/VBScript/Topological-sort new file mode 120000 index 0000000000..8d68d06618 --- /dev/null +++ b/Lang/VBScript/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/User-input-Graphical b/Lang/VBScript/User-input-Graphical new file mode 120000 index 0000000000..f55a236050 --- /dev/null +++ b/Lang/VBScript/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Verify-distribution-uniformity-Naive b/Lang/VBScript/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..b1abd5b6b6 --- /dev/null +++ b/Lang/VBScript/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/VBScript \ No newline at end of file diff --git a/Lang/Vala/Sieve-of-Eratosthenes b/Lang/Vala/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..a4fcd3bb64 --- /dev/null +++ b/Lang/Vala/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Vala \ No newline at end of file diff --git a/Lang/Vala/String-case b/Lang/Vala/String-case new file mode 120000 index 0000000000..cee47eb9bd --- /dev/null +++ b/Lang/Vala/String-case @@ -0,0 +1 @@ +../../Task/String-case/Vala \ No newline at end of file diff --git a/Lang/Vala/String-length b/Lang/Vala/String-length new file mode 120000 index 0000000000..a27882756d --- /dev/null +++ b/Lang/Vala/String-length @@ -0,0 +1 @@ +../../Task/String-length/Vala \ No newline at end of file diff --git a/Lang/Vala/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Vala/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..05087ad1eb --- /dev/null +++ b/Lang/Vala/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Vala \ No newline at end of file diff --git a/Lang/Vala/Substring b/Lang/Vala/Substring new file mode 120000 index 0000000000..ebc2b4a4bb --- /dev/null +++ b/Lang/Vala/Substring @@ -0,0 +1 @@ +../../Task/Substring/Vala \ No newline at end of file diff --git a/Lang/Vala/Substring-Top-and-tail b/Lang/Vala/Substring-Top-and-tail new file mode 120000 index 0000000000..7fda2a4c7b --- /dev/null +++ b/Lang/Vala/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Vala \ No newline at end of file diff --git a/Lang/Vala/Sum-and-product-of-an-array b/Lang/Vala/Sum-and-product-of-an-array new file mode 120000 index 0000000000..dfc33267a6 --- /dev/null +++ b/Lang/Vala/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Vala \ No newline at end of file diff --git a/Lang/Vala/Sum-of-a-series b/Lang/Vala/Sum-of-a-series new file mode 120000 index 0000000000..03e00e54c4 --- /dev/null +++ b/Lang/Vala/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Vala \ No newline at end of file diff --git a/Lang/Vala/System-time b/Lang/Vala/System-time new file mode 120000 index 0000000000..4364f3d20f --- /dev/null +++ b/Lang/Vala/System-time @@ -0,0 +1 @@ +../../Task/System-time/Vala \ No newline at end of file diff --git a/Lang/Vala/Tokenize-a-string b/Lang/Vala/Tokenize-a-string new file mode 120000 index 0000000000..eac4b84078 --- /dev/null +++ b/Lang/Vala/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Vala \ No newline at end of file diff --git a/Lang/Vala/Variable-size-Get b/Lang/Vala/Variable-size-Get new file mode 120000 index 0000000000..57d9ca6710 --- /dev/null +++ b/Lang/Vala/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Vala \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Shell-one-liner b/Lang/Vedit-macro-language/Shell-one-liner new file mode 120000 index 0000000000..6fa315dfef --- /dev/null +++ b/Lang/Vedit-macro-language/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Sierpinski-triangle b/Lang/Vedit-macro-language/Sierpinski-triangle new file mode 120000 index 0000000000..a5fb8929b7 --- /dev/null +++ b/Lang/Vedit-macro-language/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Simple-windowed-application b/Lang/Vedit-macro-language/Simple-windowed-application new file mode 120000 index 0000000000..d443a4c236 --- /dev/null +++ b/Lang/Vedit-macro-language/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Sleep b/Lang/Vedit-macro-language/Sleep new file mode 120000 index 0000000000..bce9814b56 --- /dev/null +++ b/Lang/Vedit-macro-language/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/String-case b/Lang/Vedit-macro-language/String-case new file mode 120000 index 0000000000..64614374a3 --- /dev/null +++ b/Lang/Vedit-macro-language/String-case @@ -0,0 +1 @@ +../../Task/String-case/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Text-processing-1 b/Lang/Vedit-macro-language/Text-processing-1 new file mode 120000 index 0000000000..333feb211a --- /dev/null +++ b/Lang/Vedit-macro-language/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Text-processing-2 b/Lang/Vedit-macro-language/Text-processing-2 new file mode 120000 index 0000000000..e13db5d486 --- /dev/null +++ b/Lang/Vedit-macro-language/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Text-processing-Max-licenses-in-use b/Lang/Vedit-macro-language/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..a8a8f77a50 --- /dev/null +++ b/Lang/Vedit-macro-language/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Tokenize-a-string b/Lang/Vedit-macro-language/Tokenize-a-string new file mode 120000 index 0000000000..3a805b03f4 --- /dev/null +++ b/Lang/Vedit-macro-language/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Towers-of-Hanoi b/Lang/Vedit-macro-language/Towers-of-Hanoi new file mode 120000 index 0000000000..b83f7d0f45 --- /dev/null +++ b/Lang/Vedit-macro-language/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/User-input-Graphical b/Lang/Vedit-macro-language/User-input-Graphical new file mode 120000 index 0000000000..99240ccd9a --- /dev/null +++ b/Lang/Vedit-macro-language/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/User-input-Text b/Lang/Vedit-macro-language/User-input-Text new file mode 120000 index 0000000000..a98be43e4a --- /dev/null +++ b/Lang/Vedit-macro-language/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Vigen-re-cipher b/Lang/Vedit-macro-language/Vigen-re-cipher new file mode 120000 index 0000000000..393eafaea0 --- /dev/null +++ b/Lang/Vedit-macro-language/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Vigen-re-cipher-Cryptanalysis b/Lang/Vedit-macro-language/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..736e1e2128 --- /dev/null +++ b/Lang/Vedit-macro-language/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/Window-creation b/Lang/Vedit-macro-language/Window-creation new file mode 120000 index 0000000000..20d793c5b0 --- /dev/null +++ b/Lang/Vedit-macro-language/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/XML-Input b/Lang/Vedit-macro-language/XML-Input new file mode 120000 index 0000000000..e7ba65399e --- /dev/null +++ b/Lang/Vedit-macro-language/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Vedit-macro-language/XML-Output b/Lang/Vedit-macro-language/XML-Output new file mode 120000 index 0000000000..23a049367c --- /dev/null +++ b/Lang/Vedit-macro-language/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Vedit-macro-language \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sieve-of-Eratosthenes b/Lang/Visual-Basic-.NET/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c93c3b6186 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Singly-linked-list-Traversal b/Lang/Visual-Basic-.NET/Singly-linked-list-Traversal new file mode 120000 index 0000000000..64ed5e234e --- /dev/null +++ b/Lang/Visual-Basic-.NET/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sockets b/Lang/Visual-Basic-.NET/Sockets new file mode 120000 index 0000000000..9c451caa4b --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sort-using-a-custom-comparator b/Lang/Visual-Basic-.NET/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..e06bb6f2cd --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sorting-algorithms-Bubble-sort b/Lang/Visual-Basic-.NET/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..429c2b8432 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/String-case b/Lang/Visual-Basic-.NET/String-case new file mode 120000 index 0000000000..a71ca0ff4f --- /dev/null +++ b/Lang/Visual-Basic-.NET/String-case @@ -0,0 +1 @@ +../../Task/String-case/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/String-concatenation b/Lang/Visual-Basic-.NET/String-concatenation new file mode 120000 index 0000000000..3fa8933933 --- /dev/null +++ b/Lang/Visual-Basic-.NET/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Sum-of-squares b/Lang/Visual-Basic-.NET/Sum-of-squares new file mode 120000 index 0000000000..f6948bcd70 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Synchronous-concurrency b/Lang/Visual-Basic-.NET/Synchronous-concurrency new file mode 120000 index 0000000000..66cba38eee --- /dev/null +++ b/Lang/Visual-Basic-.NET/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Take-notes-on-the-command-line b/Lang/Visual-Basic-.NET/Take-notes-on-the-command-line new file mode 120000 index 0000000000..c21c9c27a6 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Topological-sort b/Lang/Visual-Basic-.NET/Topological-sort new file mode 120000 index 0000000000..ea29683314 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Towers-of-Hanoi b/Lang/Visual-Basic-.NET/Towers-of-Hanoi new file mode 120000 index 0000000000..8ae0015258 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/User-input-Text b/Lang/Visual-Basic-.NET/User-input-Text new file mode 120000 index 0000000000..673a316f4f --- /dev/null +++ b/Lang/Visual-Basic-.NET/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Vector-products b/Lang/Visual-Basic-.NET/Vector-products new file mode 120000 index 0000000000..f355bef6cc --- /dev/null +++ b/Lang/Visual-Basic-.NET/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Walk-a-directory-Non-recursively b/Lang/Visual-Basic-.NET/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..0cd282482e --- /dev/null +++ b/Lang/Visual-Basic-.NET/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Walk-a-directory-Recursively b/Lang/Visual-Basic-.NET/Walk-a-directory-Recursively new file mode 120000 index 0000000000..834f69d57d --- /dev/null +++ b/Lang/Visual-Basic-.NET/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Web-scraping b/Lang/Visual-Basic-.NET/Web-scraping new file mode 120000 index 0000000000..c44b14304f --- /dev/null +++ b/Lang/Visual-Basic-.NET/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Window-creation b/Lang/Visual-Basic-.NET/Window-creation new file mode 120000 index 0000000000..ebbe95a4d8 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/XML-Input b/Lang/Visual-Basic-.NET/XML-Input new file mode 120000 index 0000000000..780c89be36 --- /dev/null +++ b/Lang/Visual-Basic-.NET/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/XML-Output b/Lang/Visual-Basic-.NET/XML-Output new file mode 120000 index 0000000000..b3bdbf0133 --- /dev/null +++ b/Lang/Visual-Basic-.NET/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/XML-XPath b/Lang/Visual-Basic-.NET/XML-XPath new file mode 120000 index 0000000000..7c7f8c9216 --- /dev/null +++ b/Lang/Visual-Basic-.NET/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Yin-and-yang b/Lang/Visual-Basic-.NET/Yin-and-yang new file mode 120000 index 0000000000..7a70f9417a --- /dev/null +++ b/Lang/Visual-Basic-.NET/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic/Show-the-epoch b/Lang/Visual-Basic/Show-the-epoch new file mode 120000 index 0000000000..ed2a278c53 --- /dev/null +++ b/Lang/Visual-Basic/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Simple-windowed-application b/Lang/Visual-Basic/Simple-windowed-application new file mode 120000 index 0000000000..b1341c8e08 --- /dev/null +++ b/Lang/Visual-Basic/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Spiral-matrix b/Lang/Visual-Basic/Spiral-matrix new file mode 120000 index 0000000000..16f685c45b --- /dev/null +++ b/Lang/Visual-Basic/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Start-from-a-main-routine b/Lang/Visual-Basic/Start-from-a-main-routine new file mode 120000 index 0000000000..a2e369771a --- /dev/null +++ b/Lang/Visual-Basic/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Tokenize-a-string b/Lang/Visual-Basic/Tokenize-a-string new file mode 120000 index 0000000000..7d3c8071a0 --- /dev/null +++ b/Lang/Visual-Basic/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Variadic-function b/Lang/Visual-Basic/Variadic-function new file mode 120000 index 0000000000..ce428f0c9d --- /dev/null +++ b/Lang/Visual-Basic/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Objects/SOAP b/Lang/Visual-Objects/SOAP new file mode 120000 index 0000000000..708f9d4bbf --- /dev/null +++ b/Lang/Visual-Objects/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Visual-Objects \ No newline at end of file diff --git a/Lang/Vorpal/Sieve-of-Eratosthenes b/Lang/Vorpal/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..78e1f57bee --- /dev/null +++ b/Lang/Vorpal/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Vorpal \ No newline at end of file diff --git a/Lang/Vorpal/Variadic-function b/Lang/Vorpal/Variadic-function new file mode 120000 index 0000000000..93769579e2 --- /dev/null +++ b/Lang/Vorpal/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Vorpal \ No newline at end of file diff --git a/Lang/X86-Assembly/Sierpinski-triangle b/Lang/X86-Assembly/Sierpinski-triangle new file mode 120000 index 0000000000..b00d008541 --- /dev/null +++ b/Lang/X86-Assembly/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Singly-linked-list-Element-definition b/Lang/X86-Assembly/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..61c3a3a6e3 --- /dev/null +++ b/Lang/X86-Assembly/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Sockets b/Lang/X86-Assembly/Sockets new file mode 120000 index 0000000000..fc14aa75ee --- /dev/null +++ b/Lang/X86-Assembly/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Sorting-algorithms-Bubble-sort b/Lang/X86-Assembly/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..a6d5518f8d --- /dev/null +++ b/Lang/X86-Assembly/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Terminal-control-Ringing-the-terminal-bell b/Lang/X86-Assembly/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..770649fe48 --- /dev/null +++ b/Lang/X86-Assembly/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Window-creation b/Lang/X86-Assembly/Window-creation new file mode 120000 index 0000000000..27418b6ca9 --- /dev/null +++ b/Lang/X86-Assembly/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/X86-Assembly \ No newline at end of file diff --git a/Lang/XPL0/Sierpinski-carpet b/Lang/XPL0/Sierpinski-carpet new file mode 120000 index 0000000000..145073e1c6 --- /dev/null +++ b/Lang/XPL0/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sierpinski-triangle b/Lang/XPL0/Sierpinski-triangle new file mode 120000 index 0000000000..9329e115be --- /dev/null +++ b/Lang/XPL0/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sierpinski-triangle-Graphical b/Lang/XPL0/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..7dd1412117 --- /dev/null +++ b/Lang/XPL0/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sieve-of-Eratosthenes b/Lang/XPL0/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..32e3531955 --- /dev/null +++ b/Lang/XPL0/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Simple-windowed-application b/Lang/XPL0/Simple-windowed-application new file mode 120000 index 0000000000..1d14bdd8ff --- /dev/null +++ b/Lang/XPL0/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Singly-linked-list-Element-definition b/Lang/XPL0/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..e29e413dfa --- /dev/null +++ b/Lang/XPL0/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Singly-linked-list-Traversal b/Lang/XPL0/Singly-linked-list-Traversal new file mode 120000 index 0000000000..373c360c01 --- /dev/null +++ b/Lang/XPL0/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sort-an-array-of-composite-structures b/Lang/XPL0/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..5156a76366 --- /dev/null +++ b/Lang/XPL0/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sort-an-integer-array b/Lang/XPL0/Sort-an-integer-array new file mode 120000 index 0000000000..79ddbd4906 --- /dev/null +++ b/Lang/XPL0/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Bead-sort b/Lang/XPL0/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..fba0fcda5a --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Bogosort b/Lang/XPL0/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..7f65c53b87 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Bubble-sort b/Lang/XPL0/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..da3aee1a41 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Cocktail-sort b/Lang/XPL0/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..8a883484fb --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Counting-sort b/Lang/XPL0/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..72174d1eaf --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Gnome-sort b/Lang/XPL0/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..2c7f2939e9 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Insertion-sort b/Lang/XPL0/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..ac5a6e7304 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Merge-sort b/Lang/XPL0/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..67b531e013 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Quicksort b/Lang/XPL0/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..5b2e5c0232 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Selection-sort b/Lang/XPL0/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..994fcc722a --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Shell-sort b/Lang/XPL0/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..1dbdf45f35 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Stooge-sort b/Lang/XPL0/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..b99f1e302a --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Soundex b/Lang/XPL0/Soundex new file mode 120000 index 0000000000..b33f49b9da --- /dev/null +++ b/Lang/XPL0/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Spiral-matrix b/Lang/XPL0/Spiral-matrix new file mode 120000 index 0000000000..26427482ac --- /dev/null +++ b/Lang/XPL0/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Stack b/Lang/XPL0/Stack new file mode 120000 index 0000000000..cac65e08a9 --- /dev/null +++ b/Lang/XPL0/Stack @@ -0,0 +1 @@ +../../Task/Stack/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Stair-climbing-puzzle b/Lang/XPL0/Stair-climbing-puzzle new file mode 120000 index 0000000000..b8de88afbf --- /dev/null +++ b/Lang/XPL0/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Standard-deviation b/Lang/XPL0/Standard-deviation new file mode 120000 index 0000000000..03d1b156f7 --- /dev/null +++ b/Lang/XPL0/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/String-case b/Lang/XPL0/String-case new file mode 120000 index 0000000000..8e5bbf3bee --- /dev/null +++ b/Lang/XPL0/String-case @@ -0,0 +1 @@ +../../Task/String-case/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/String-concatenation b/Lang/XPL0/String-concatenation new file mode 120000 index 0000000000..008f07a607 --- /dev/null +++ b/Lang/XPL0/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/String-length b/Lang/XPL0/String-length new file mode 120000 index 0000000000..6a21d8f300 --- /dev/null +++ b/Lang/XPL0/String-length @@ -0,0 +1 @@ +../../Task/String-length/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Strip-control-codes-and-extended-characters-from-a-string b/Lang/XPL0/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..10749467fb --- /dev/null +++ b/Lang/XPL0/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Strip-whitespace-from-a-string-Top-and-tail b/Lang/XPL0/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..87fff12397 --- /dev/null +++ b/Lang/XPL0/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Substring-Top-and-tail b/Lang/XPL0/Substring-Top-and-tail new file mode 120000 index 0000000000..5916ed1134 --- /dev/null +++ b/Lang/XPL0/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sudoku b/Lang/XPL0/Sudoku new file mode 120000 index 0000000000..1568e3b859 --- /dev/null +++ b/Lang/XPL0/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sum-and-product-of-an-array b/Lang/XPL0/Sum-and-product-of-an-array new file mode 120000 index 0000000000..3fe48a58ba --- /dev/null +++ b/Lang/XPL0/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sum-digits-of-an-integer b/Lang/XPL0/Sum-digits-of-an-integer new file mode 120000 index 0000000000..9b65194eef --- /dev/null +++ b/Lang/XPL0/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sum-of-a-series b/Lang/XPL0/Sum-of-a-series new file mode 120000 index 0000000000..4d4c99732a --- /dev/null +++ b/Lang/XPL0/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sum-of-squares b/Lang/XPL0/Sum-of-squares new file mode 120000 index 0000000000..73e7cc87f5 --- /dev/null +++ b/Lang/XPL0/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/System-time b/Lang/XPL0/System-time new file mode 120000 index 0000000000..84b4fcfc01 --- /dev/null +++ b/Lang/XPL0/System-time @@ -0,0 +1 @@ +../../Task/System-time/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Temperature-conversion b/Lang/XPL0/Temperature-conversion new file mode 120000 index 0000000000..58dec2a996 --- /dev/null +++ b/Lang/XPL0/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Clear-the-screen b/Lang/XPL0/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..0536192f37 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Coloured-text b/Lang/XPL0/Terminal-control-Coloured-text new file mode 120000 index 0000000000..b43c21d7c4 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Cursor-movement b/Lang/XPL0/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..25f82bc9e9 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Cursor-positioning b/Lang/XPL0/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..ec0f8b1618 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Dimensions b/Lang/XPL0/Terminal-control-Dimensions new file mode 120000 index 0000000000..3a40cbe6a5 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Display-an-extended-character b/Lang/XPL0/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..7a9516b1e0 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Hiding-the-cursor b/Lang/XPL0/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..5729ece9ea --- /dev/null +++ b/Lang/XPL0/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Inverse-video b/Lang/XPL0/Terminal-control-Inverse-video new file mode 120000 index 0000000000..79528043d8 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Positional-read b/Lang/XPL0/Terminal-control-Positional-read new file mode 120000 index 0000000000..000872239f --- /dev/null +++ b/Lang/XPL0/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Preserve-screen b/Lang/XPL0/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..4fec8ad3ca --- /dev/null +++ b/Lang/XPL0/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Terminal-control-Ringing-the-terminal-bell b/Lang/XPL0/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..d5e9b480a3 --- /dev/null +++ b/Lang/XPL0/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Tic-tac-toe b/Lang/XPL0/Tic-tac-toe new file mode 120000 index 0000000000..64c6838949 --- /dev/null +++ b/Lang/XPL0/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Time-a-function b/Lang/XPL0/Time-a-function new file mode 120000 index 0000000000..3b50dbe3cc --- /dev/null +++ b/Lang/XPL0/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Tokenize-a-string b/Lang/XPL0/Tokenize-a-string new file mode 120000 index 0000000000..7f929cb6a9 --- /dev/null +++ b/Lang/XPL0/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Topswops b/Lang/XPL0/Topswops new file mode 120000 index 0000000000..3051e24b9a --- /dev/null +++ b/Lang/XPL0/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Towers-of-Hanoi b/Lang/XPL0/Towers-of-Hanoi new file mode 120000 index 0000000000..55274f1c30 --- /dev/null +++ b/Lang/XPL0/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Trabb-Pardo-Knuth-algorithm b/Lang/XPL0/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..2288deef8f --- /dev/null +++ b/Lang/XPL0/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Trigonometric-functions b/Lang/XPL0/Trigonometric-functions new file mode 120000 index 0000000000..ab9da8a1ca --- /dev/null +++ b/Lang/XPL0/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Truncatable-primes b/Lang/XPL0/Truncatable-primes new file mode 120000 index 0000000000..cff4629358 --- /dev/null +++ b/Lang/XPL0/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/URL-decoding b/Lang/XPL0/URL-decoding new file mode 120000 index 0000000000..5c56401a7c --- /dev/null +++ b/Lang/XPL0/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/URL-encoding b/Lang/XPL0/URL-encoding new file mode 120000 index 0000000000..f59658d358 --- /dev/null +++ b/Lang/XPL0/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/User-input-Text b/Lang/XPL0/User-input-Text new file mode 120000 index 0000000000..d53165838e --- /dev/null +++ b/Lang/XPL0/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Van-der-Corput-sequence b/Lang/XPL0/Van-der-Corput-sequence new file mode 120000 index 0000000000..55a269eac3 --- /dev/null +++ b/Lang/XPL0/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Variable-size-Get b/Lang/XPL0/Variable-size-Get new file mode 120000 index 0000000000..c645d4f094 --- /dev/null +++ b/Lang/XPL0/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Variable-size-Set b/Lang/XPL0/Variable-size-Set new file mode 120000 index 0000000000..3b3b4e3594 --- /dev/null +++ b/Lang/XPL0/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Variadic-function b/Lang/XPL0/Variadic-function new file mode 120000 index 0000000000..31287fc336 --- /dev/null +++ b/Lang/XPL0/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Vector-products b/Lang/XPL0/Vector-products new file mode 120000 index 0000000000..8d602190dc --- /dev/null +++ b/Lang/XPL0/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Video-display-modes b/Lang/XPL0/Video-display-modes new file mode 120000 index 0000000000..dbbcf2b5a9 --- /dev/null +++ b/Lang/XPL0/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Vigen-re-cipher b/Lang/XPL0/Vigen-re-cipher new file mode 120000 index 0000000000..b40697da32 --- /dev/null +++ b/Lang/XPL0/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Wireworld b/Lang/XPL0/Wireworld new file mode 120000 index 0000000000..0c1ae00347 --- /dev/null +++ b/Lang/XPL0/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Write-language-name-in-3D-ASCII b/Lang/XPL0/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..0ee0161261 --- /dev/null +++ b/Lang/XPL0/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/XML-Input b/Lang/XPL0/XML-Input new file mode 120000 index 0000000000..dc6629f351 --- /dev/null +++ b/Lang/XPL0/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/XML-Output b/Lang/XPL0/XML-Output new file mode 120000 index 0000000000..df2a669675 --- /dev/null +++ b/Lang/XPL0/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Yin-and-yang b/Lang/XPL0/Yin-and-yang new file mode 120000 index 0000000000..f39e2e2dd4 --- /dev/null +++ b/Lang/XPL0/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Zeckendorf-number-representation b/Lang/XPL0/Zeckendorf-number-representation new file mode 120000 index 0000000000..1a91013ed0 --- /dev/null +++ b/Lang/XPL0/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Zig-zag-matrix b/Lang/XPL0/Zig-zag-matrix new file mode 120000 index 0000000000..a3a332f9f1 --- /dev/null +++ b/Lang/XPL0/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/XPL0 \ No newline at end of file diff --git a/Lang/XProc/XML-DOM-serialization b/Lang/XProc/XML-DOM-serialization new file mode 120000 index 0000000000..b7ea9dc4fc --- /dev/null +++ b/Lang/XProc/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/XProc \ No newline at end of file diff --git a/Lang/XProc/XML-XPath b/Lang/XProc/XML-XPath new file mode 120000 index 0000000000..1295c115ae --- /dev/null +++ b/Lang/XProc/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/XProc \ No newline at end of file diff --git a/Lang/XQuery/Towers-of-Hanoi b/Lang/XQuery/Towers-of-Hanoi new file mode 120000 index 0000000000..874911d34c --- /dev/null +++ b/Lang/XQuery/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/XQuery \ No newline at end of file diff --git a/Lang/XQuery/XML-DOM-serialization b/Lang/XQuery/XML-DOM-serialization new file mode 120000 index 0000000000..fe70c29fac --- /dev/null +++ b/Lang/XQuery/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/XQuery \ No newline at end of file diff --git a/Lang/XQuery/XML-XPath b/Lang/XQuery/XML-XPath new file mode 120000 index 0000000000..706c07c495 --- /dev/null +++ b/Lang/XQuery/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/XQuery \ No newline at end of file diff --git a/Lang/XSLT-2.0/Stable-marriage-problem b/Lang/XSLT-2.0/Stable-marriage-problem new file mode 120000 index 0000000000..8cd4858fcd --- /dev/null +++ b/Lang/XSLT-2.0/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/XSLT-2.0 \ No newline at end of file diff --git a/Lang/XSLT/String-length b/Lang/XSLT/String-length new file mode 120000 index 0000000000..842e52b7ef --- /dev/null +++ b/Lang/XSLT/String-length @@ -0,0 +1 @@ +../../Task/String-length/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Sum-and-product-of-an-array b/Lang/XSLT/Sum-and-product-of-an-array new file mode 120000 index 0000000000..32c69acda9 --- /dev/null +++ b/Lang/XSLT/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Towers-of-Hanoi b/Lang/XSLT/Towers-of-Hanoi new file mode 120000 index 0000000000..67751ab402 --- /dev/null +++ b/Lang/XSLT/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Variables b/Lang/XSLT/Variables new file mode 120000 index 0000000000..8447cf0dfc --- /dev/null +++ b/Lang/XSLT/Variables @@ -0,0 +1 @@ +../../Task/Variables/XSLT \ No newline at end of file diff --git a/Lang/XSLT/XML-DOM-serialization b/Lang/XSLT/XML-DOM-serialization new file mode 120000 index 0000000000..cfc466d63e --- /dev/null +++ b/Lang/XSLT/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/XSLT \ No newline at end of file diff --git a/Lang/XSLT/XML-XPath b/Lang/XSLT/XML-XPath new file mode 120000 index 0000000000..d2b887c0c6 --- /dev/null +++ b/Lang/XSLT/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/XSLT \ No newline at end of file diff --git a/Lang/Yorick/Simple-windowed-application b/Lang/Yorick/Simple-windowed-application new file mode 120000 index 0000000000..79e8a519e6 --- /dev/null +++ b/Lang/Yorick/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Sort-an-integer-array b/Lang/Yorick/Sort-an-integer-array new file mode 120000 index 0000000000..2e5a1a5dd2 --- /dev/null +++ b/Lang/Yorick/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Sorting-algorithms-Bubble-sort b/Lang/Yorick/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..f0e1bf330b --- /dev/null +++ b/Lang/Yorick/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Sorting-algorithms-Insertion-sort b/Lang/Yorick/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..78370840da --- /dev/null +++ b/Lang/Yorick/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Sorting-algorithms-Stooge-sort b/Lang/Yorick/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..4be58d2d81 --- /dev/null +++ b/Lang/Yorick/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Yorick \ No newline at end of file diff --git a/Lang/Yorick/String-concatenation b/Lang/Yorick/String-concatenation new file mode 120000 index 0000000000..51c5885409 --- /dev/null +++ b/Lang/Yorick/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Yorick \ No newline at end of file diff --git a/Lang/Yorick/String-length b/Lang/Yorick/String-length new file mode 120000 index 0000000000..6297f6bd7b --- /dev/null +++ b/Lang/Yorick/String-length @@ -0,0 +1 @@ +../../Task/String-length/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Substring b/Lang/Yorick/Substring new file mode 120000 index 0000000000..30ce3672b9 --- /dev/null +++ b/Lang/Yorick/Substring @@ -0,0 +1 @@ +../../Task/Substring/Yorick \ No newline at end of file diff --git a/Lang/Yorick/Sum-of-a-series b/Lang/Yorick/Sum-of-a-series new file mode 120000 index 0000000000..640b8482b1 --- /dev/null +++ b/Lang/Yorick/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Yorick \ No newline at end of file diff --git a/Lang/Z80-Assembly/Terminal-control-Preserve-screen b/Lang/Z80-Assembly/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..ffc42f68a2 --- /dev/null +++ b/Lang/Z80-Assembly/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Z80-Assembly \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Speech-synthesis b/Lang/ZX-Spectrum-Basic/Speech-synthesis new file mode 120000 index 0000000000..9c543b1543 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Start-from-a-main-routine b/Lang/ZX-Spectrum-Basic/Start-from-a-main-routine new file mode 120000 index 0000000000..6413a0997b --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/String-concatenation b/Lang/ZX-Spectrum-Basic/String-concatenation new file mode 120000 index 0000000000..c9090d6c07 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Substring-Top-and-tail b/Lang/ZX-Spectrum-Basic/Substring-Top-and-tail new file mode 120000 index 0000000000..bc8f8080da --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Temperature-conversion b/Lang/ZX-Spectrum-Basic/Temperature-conversion new file mode 120000 index 0000000000..6469c0fafa --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Terminal-control-Cursor-movement b/Lang/ZX-Spectrum-Basic/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..c164070261 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Terminal-control-Unicode-output b/Lang/ZX-Spectrum-Basic/Terminal-control-Unicode-output new file mode 120000 index 0000000000..47b6a1dc45 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Truncate-a-file b/Lang/ZX-Spectrum-Basic/Truncate-a-file new file mode 120000 index 0000000000..6f84745f8d --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/User-input-Text b/Lang/ZX-Spectrum-Basic/User-input-Text new file mode 120000 index 0000000000..975881ee80 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Variable-size-Set b/Lang/ZX-Spectrum-Basic/Variable-size-Set new file mode 120000 index 0000000000..d70cfc08a9 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Write-float-arrays-to-a-text-file b/Lang/ZX-Spectrum-Basic/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d69a6120e7 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII b/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..56aa7a4390 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Meta/Task.yaml b/Meta/Task.yaml index d07fddfc49..321fb23317 100644 --- a/Meta/Task.yaml +++ b/Meta/Task.yaml @@ -1936,6 +1936,22 @@ SEDOLs: name: SEDOLs path: SEDOLs url: SEDOLs +SHA-1: + name: SHA-1 + path: SHA-1 + url: SHA-1 +SHA-256: + name: SHA-256 + path: SHA-256 + url: SHA-256 +SOAP: + name: SOAP + path: SOAP + url: SOAP +SQL-based authentication: + name: SQL-based authentication + path: SQL-based-authentication + url: SQL-based_authentication Safe addition: name: Safe addition path: Safe-addition @@ -1996,3 +2012,655 @@ Set of real numbers: name: Set of real numbers path: Set-of-real-numbers url: Set_of_real_numbers +Set puzzle: + name: Set puzzle + path: Set-puzzle + url: Set_puzzle +Seven-sided dice from five-sided dice: + name: Seven-sided dice from five-sided dice + path: Seven-sided-dice-from-five-sided-dice + url: Seven-sided_dice_from_five-sided_dice +Shell one-liner: + name: Shell one-liner + path: Shell-one-liner + url: Shell_one-liner +Short-circuit evaluation: + name: Short-circuit evaluation + path: Short-circuit-evaluation + url: Short-circuit_evaluation +Show the epoch: + name: Show the epoch + path: Show-the-epoch + url: Show_the_epoch +Sierpinski carpet: + name: Sierpinski carpet + path: Sierpinski-carpet + url: Sierpinski_carpet +Sierpinski triangle: + name: Sierpinski triangle + path: Sierpinski-triangle + url: Sierpinski_triangle +Sierpinski triangle/Graphical: + name: Sierpinski triangle/Graphical + path: Sierpinski-triangle-Graphical + url: Sierpinski_triangle/Graphical +Sieve of Eratosthenes: + name: Sieve of Eratosthenes + path: Sieve-of-Eratosthenes + url: Sieve_of_Eratosthenes +Simple database: + name: Simple database + path: Simple-database + url: Simple_database +Simple windowed application: + name: Simple windowed application + path: Simple-windowed-application + url: Simple_windowed_application +Simulate input/Keyboard: + name: Simulate input/Keyboard + path: Simulate-input-Keyboard + url: Simulate_input/Keyboard +Simulate input/Mouse: + name: Simulate input/Mouse + path: Simulate-input-Mouse + url: Simulate_input/Mouse +Singleton: + name: Singleton + path: Singleton + url: Singleton +Singly-linked list/Element definition: + name: Singly-linked list/Element definition + path: Singly-linked-list-Element-definition + url: Singly-linked_list/Element_definition +Singly-linked list/Element insertion: + name: Singly-linked list/Element insertion + path: Singly-linked-list-Element-insertion + url: Singly-linked_list/Element_insertion +Singly-linked list/Traversal: + name: Singly-linked list/Traversal + path: Singly-linked-list-Traversal + url: Singly-linked_list/Traversal +Sleep: + name: Sleep + path: Sleep + url: Sleep +Sockets: + name: Sockets + path: Sockets + url: Sockets +Sokoban: + name: Sokoban + path: Sokoban + url: Sokoban +Solve a Hidato puzzle: + name: Solve a Hidato puzzle + path: Solve-a-Hidato-puzzle + url: Solve_a_Hidato_puzzle +Sort an array of composite structures: + name: Sort an array of composite structures + path: Sort-an-array-of-composite-structures + url: Sort_an_array_of_composite_structures +Sort an integer array: + name: Sort an integer array + path: Sort-an-integer-array + url: Sort_an_integer_array +Sort disjoint sublist: + name: Sort disjoint sublist + path: Sort-disjoint-sublist + url: Sort_disjoint_sublist +Sort stability: + name: Sort stability + path: Sort-stability + url: Sort_stability +Sort using a custom comparator: + name: Sort using a custom comparator + path: Sort-using-a-custom-comparator + url: Sort_using_a_custom_comparator +Sorting algorithms/Bead sort: + name: Sorting algorithms/Bead sort + path: Sorting-algorithms-Bead-sort + url: Sorting_algorithms/Bead_sort +Sorting algorithms/Bogosort: + name: Sorting algorithms/Bogosort + path: Sorting-algorithms-Bogosort + url: Sorting_algorithms/Bogosort +Sorting algorithms/Bubble sort: + name: Sorting algorithms/Bubble sort + path: Sorting-algorithms-Bubble-sort + url: Sorting_algorithms/Bubble_sort +Sorting algorithms/Cocktail sort: + name: Sorting algorithms/Cocktail sort + path: Sorting-algorithms-Cocktail-sort + url: Sorting_algorithms/Cocktail_sort +Sorting algorithms/Comb sort: + name: Sorting algorithms/Comb sort + path: Sorting-algorithms-Comb-sort + url: Sorting_algorithms/Comb_sort +Sorting algorithms/Counting sort: + name: Sorting algorithms/Counting sort + path: Sorting-algorithms-Counting-sort + url: Sorting_algorithms/Counting_sort +Sorting algorithms/Gnome sort: + name: Sorting algorithms/Gnome sort + path: Sorting-algorithms-Gnome-sort + url: Sorting_algorithms/Gnome_sort +Sorting algorithms/Heapsort: + name: Sorting algorithms/Heapsort + path: Sorting-algorithms-Heapsort + url: Sorting_algorithms/Heapsort +Sorting algorithms/Insertion sort: + name: Sorting algorithms/Insertion sort + path: Sorting-algorithms-Insertion-sort + url: Sorting_algorithms/Insertion_sort +Sorting algorithms/Merge sort: + name: Sorting algorithms/Merge sort + path: Sorting-algorithms-Merge-sort + url: Sorting_algorithms/Merge_sort +Sorting algorithms/Pancake sort: + name: Sorting algorithms/Pancake sort + path: Sorting-algorithms-Pancake-sort + url: Sorting_algorithms/Pancake_sort +Sorting algorithms/Permutation sort: + name: Sorting algorithms/Permutation sort + path: Sorting-algorithms-Permutation-sort + url: Sorting_algorithms/Permutation_sort +Sorting algorithms/Quicksort: + name: Sorting algorithms/Quicksort + path: Sorting-algorithms-Quicksort + url: Sorting_algorithms/Quicksort +Sorting algorithms/Radix sort: + name: Sorting algorithms/Radix sort + path: Sorting-algorithms-Radix-sort + url: Sorting_algorithms/Radix_sort +Sorting algorithms/Selection sort: + name: Sorting algorithms/Selection sort + path: Sorting-algorithms-Selection-sort + url: Sorting_algorithms/Selection_sort +Sorting algorithms/Shell sort: + name: Sorting algorithms/Shell sort + path: Sorting-algorithms-Shell-sort + url: Sorting_algorithms/Shell_sort +Sorting algorithms/Sleep sort: + name: Sorting algorithms/Sleep sort + path: Sorting-algorithms-Sleep-sort + url: Sorting_algorithms/Sleep_sort +Sorting algorithms/Stooge sort: + name: Sorting algorithms/Stooge sort + path: Sorting-algorithms-Stooge-sort + url: Sorting_algorithms/Stooge_sort +Sorting algorithms/Strand sort: + name: Sorting algorithms/Strand sort + path: Sorting-algorithms-Strand-sort + url: Sorting_algorithms/Strand_sort +Soundex: + name: Soundex + path: Soundex + url: Soundex +Special characters: + name: Special characters + path: Special-characters + url: Special_characters +Special variables: + name: Special variables + path: Special-variables + url: Special_variables +Speech synthesis: + name: Speech synthesis + path: Speech-synthesis + url: Speech_synthesis +Spiral matrix: + name: Spiral matrix + path: Spiral-matrix + url: Spiral_matrix +Stable marriage problem: + name: Stable marriage problem + path: Stable-marriage-problem + url: Stable_marriage_problem +Stack: + name: Stack + path: Stack + url: Stack +Stack traces: + name: Stack traces + path: Stack-traces + url: Stack_traces +Stair-climbing puzzle: + name: Stair-climbing puzzle + path: Stair-climbing-puzzle + url: Stair-climbing_puzzle +Standard deviation: + name: Standard deviation + path: Standard-deviation + url: Standard_deviation +Start from a main routine: + name: Start from a main routine + path: Start-from-a-main-routine + url: Start_from_a_main_routine +Stem-and-leaf plot: + name: Stem-and-leaf plot + path: Stem-and-leaf-plot + url: Stem-and-leaf_plot +String case: + name: String case + path: String-case + url: String_case +String comparison: + name: String comparison + path: String-comparison + url: String_comparison +String concatenation: + name: String concatenation + path: String-concatenation + url: String_concatenation +String interpolation (included): + name: String interpolation (included) + path: String-interpolation--included- + url: String_interpolation_(included) +String length: + name: String length + path: String-length + url: String_length +Strip a set of characters from a string: + name: Strip a set of characters from a string + path: Strip-a-set-of-characters-from-a-string + url: Strip_a_set_of_characters_from_a_string +Strip block comments: + name: Strip block comments + path: Strip-block-comments + url: Strip_block_comments +Strip comments from a string: + name: Strip comments from a string + path: Strip-comments-from-a-string + url: Strip_comments_from_a_string +Strip control codes and extended characters from a string: + name: Strip control codes and extended characters from a string + path: Strip-control-codes-and-extended-characters-from-a-string + url: Strip_control_codes_and_extended_characters_from_a_string +Strip whitespace from a string/Top and tail: + name: Strip whitespace from a string/Top and tail + path: Strip-whitespace-from-a-string-Top-and-tail + url: Strip_whitespace_from_a_string/Top_and_tail +Substring: + name: Substring + path: Substring + url: Substring +Substring/Top and tail: + name: Substring/Top and tail + path: Substring-Top-and-tail + url: Substring/Top_and_tail +Subtractive generator: + name: Subtractive generator + path: Subtractive-generator + url: Subtractive_generator +Sudoku: + name: Sudoku + path: Sudoku + url: Sudoku +Sum and product of an array: + name: Sum and product of an array + path: Sum-and-product-of-an-array + url: Sum_and_product_of_an_array +Sum digits of an integer: + name: Sum digits of an integer + path: Sum-digits-of-an-integer + url: Sum_digits_of_an_integer +Sum of a series: + name: Sum of a series + path: Sum-of-a-series + url: Sum_of_a_series +Sum of squares: + name: Sum of squares + path: Sum-of-squares + url: Sum_of_squares +Sutherland-Hodgman polygon clipping: + name: Sutherland-Hodgman polygon clipping + path: Sutherland-Hodgman-polygon-clipping + url: Sutherland-Hodgman_polygon_clipping +Symmetric difference: + name: Symmetric difference + path: Symmetric-difference + url: Symmetric_difference +Synchronous concurrency: + name: Synchronous concurrency + path: Synchronous-concurrency + url: Synchronous_concurrency +System time: + name: System time + path: System-time + url: System_time +Table creation/Postal addresses: + name: Table creation/Postal addresses + path: Table-creation-Postal-addresses + url: Table_creation/Postal_addresses +Take notes on the command line: + name: Take notes on the command line + path: Take-notes-on-the-command-line + url: Take_notes_on_the_command_line +Temperature conversion: + name: Temperature conversion + path: Temperature-conversion + url: Temperature_conversion +Terminal control/Clear the screen: + name: Terminal control/Clear the screen + path: Terminal-control-Clear-the-screen + url: Terminal_control/Clear_the_screen +Terminal control/Coloured text: + name: Terminal control/Coloured text + path: Terminal-control-Coloured-text + url: Terminal_control/Coloured_text +Terminal control/Cursor movement: + name: Terminal control/Cursor movement + path: Terminal-control-Cursor-movement + url: Terminal_control/Cursor_movement +Terminal control/Cursor positioning: + name: Terminal control/Cursor positioning + path: Terminal-control-Cursor-positioning + url: Terminal_control/Cursor_positioning +Terminal control/Dimensions: + name: Terminal control/Dimensions + path: Terminal-control-Dimensions + url: Terminal_control/Dimensions +Terminal control/Display an extended character: + name: Terminal control/Display an extended character + path: Terminal-control-Display-an-extended-character + url: Terminal_control/Display_an_extended_character +Terminal control/Hiding the cursor: + name: Terminal control/Hiding the cursor + path: Terminal-control-Hiding-the-cursor + url: Terminal_control/Hiding_the_cursor +Terminal control/Inverse video: + name: Terminal control/Inverse video + path: Terminal-control-Inverse-video + url: Terminal_control/Inverse_video +Terminal control/Positional read: + name: Terminal control/Positional read + path: Terminal-control-Positional-read + url: Terminal_control/Positional_read +Terminal control/Preserve screen: + name: Terminal control/Preserve screen + path: Terminal-control-Preserve-screen + url: Terminal_control/Preserve_screen +Terminal control/Ringing the terminal bell: + name: Terminal control/Ringing the terminal bell + path: Terminal-control-Ringing-the-terminal-bell + url: Terminal_control/Ringing_the_terminal_bell +Terminal control/Unicode output: + name: Terminal control/Unicode output + path: Terminal-control-Unicode-output + url: Terminal_control/Unicode_output +Ternary logic: + name: Ternary logic + path: Ternary-logic + url: Ternary_logic +Test a function: + name: Test a function + path: Test-a-function + url: Test_a_function +Text processing/1: + name: Text processing/1 + path: Text-processing-1 + url: Text_processing/1 +Text processing/2: + name: Text processing/2 + path: Text-processing-2 + url: Text_processing/2 +Text processing/Max licenses in use: + name: Text processing/Max licenses in use + path: Text-processing-Max-licenses-in-use + url: Text_processing/Max_licenses_in_use +Thiele's interpolation formula: + name: Thiele's interpolation formula + path: Thieles-interpolation-formula + url: Thiele's_interpolation_formula +Tic-tac-toe: + name: Tic-tac-toe + path: Tic-tac-toe + url: Tic-tac-toe +Time a function: + name: Time a function + path: Time-a-function + url: Time_a_function +Tokenize a string: + name: Tokenize a string + path: Tokenize-a-string + url: Tokenize_a_string +Top rank per group: + name: Top rank per group + path: Top-rank-per-group + url: Top_rank_per_group +Topic variable: + name: Topic variable + path: Topic-variable + url: Topic_variable +Topological sort: + name: Topological sort + path: Topological-sort + url: Topological_sort +Topswops: + name: Topswops + path: Topswops + url: Topswops +Towers of Hanoi: + name: Towers of Hanoi + path: Towers-of-Hanoi + url: Towers_of_Hanoi +Trabb Pardo–Knuth algorithm: + name: Trabb Pardo–Knuth algorithm + path: Trabb-Pardo-Knuth-algorithm + url: Trabb_Pardo–Knuth_algorithm +Tree traversal: + name: Tree traversal + path: Tree-traversal + url: Tree_traversal +Trigonometric functions: + name: Trigonometric functions + path: Trigonometric-functions + url: Trigonometric_functions +Truncatable primes: + name: Truncatable primes + path: Truncatable-primes + url: Truncatable_primes +Truncate a file: + name: Truncate a file + path: Truncate-a-file + url: Truncate_a_file +Twelve statements: + name: Twelve statements + path: Twelve-statements + url: Twelve_statements +URL decoding: + name: URL decoding + path: URL-decoding + url: URL_decoding +URL encoding: + name: URL encoding + path: URL-encoding + url: URL_encoding +Unbias a random generator: + name: Unbias a random generator + path: Unbias-a-random-generator + url: Unbias_a_random_generator +Undefined values: + name: Undefined values + path: Undefined-values + url: Undefined_values +Unicode strings: + name: Unicode strings + path: Unicode-strings + url: Unicode_strings +Unicode variable names: + name: Unicode variable names + path: Unicode-variable-names + url: Unicode_variable_names +Universal Turing machine: + name: Universal Turing machine + path: Universal-Turing-machine + url: Universal_Turing_machine +Update a configuration file: + name: Update a configuration file + path: Update-a-configuration-file + url: Update_a_configuration_file +Use another language to call a function: + name: Use another language to call a function + path: Use-another-language-to-call-a-function + url: Use_another_language_to_call_a_function +User input/Graphical: + name: User input/Graphical + path: User-input-Graphical + url: User_input/Graphical +User input/Text: + name: User input/Text + path: User-input-Text + url: User_input/Text +Vampire number: + name: Vampire number + path: Vampire-number + url: Vampire_number +Van der Corput sequence: + name: Van der Corput sequence + path: Van-der-Corput-sequence + url: Van_der_Corput_sequence +Variable size/Get: + name: Variable size/Get + path: Variable-size-Get + url: Variable_size/Get +Variable size/Set: + name: Variable size/Set + path: Variable-size-Set + url: Variable_size/Set +Variable-length quantity: + name: Variable-length quantity + path: Variable-length-quantity + url: Variable-length_quantity +Variables: + name: Variables + path: Variables + url: Variables +Variadic function: + name: Variadic function + path: Variadic-function + url: Variadic_function +Vector products: + name: Vector products + path: Vector-products + url: Vector_products +Verify distribution uniformity/Chi-squared test: + name: Verify distribution uniformity/Chi-squared test + path: Verify-distribution-uniformity-Chi-squared-test + url: Verify_distribution_uniformity/Chi-squared_test +Verify distribution uniformity/Naive: + name: Verify distribution uniformity/Naive + path: Verify-distribution-uniformity-Naive + url: Verify_distribution_uniformity/Naive +Video display modes: + name: Video display modes + path: Video-display-modes + url: Video_display_modes +Vigenère cipher: + name: Vigenère cipher + path: Vigen-re-cipher + url: Vigenère_cipher +Vigenère cipher/Cryptanalysis: + name: Vigenère cipher/Cryptanalysis + path: Vigen-re-cipher-Cryptanalysis + url: Vigenère_cipher/Cryptanalysis +Visualize a tree: + name: Visualize a tree + path: Visualize-a-tree + url: Visualize_a_tree +Voronoi diagram: + name: Voronoi diagram + path: Voronoi-diagram + url: Voronoi_diagram +Walk a directory/Non-recursively: + name: Walk a directory/Non-recursively + path: Walk-a-directory-Non-recursively + url: Walk_a_directory/Non-recursively +Walk a directory/Recursively: + name: Walk a directory/Recursively + path: Walk-a-directory-Recursively + url: Walk_a_directory/Recursively +Web scraping: + name: Web scraping + path: Web-scraping + url: Web_scraping +Window creation: + name: Window creation + path: Window-creation + url: Window_creation +Window creation/X11: + name: Window creation/X11 + path: Window-creation-X11 + url: Window_creation/X11 +Window management: + name: Window management + path: Window-management + url: Window_management +Wireworld: + name: Wireworld + path: Wireworld + url: Wireworld +Word wrap: + name: Word wrap + path: Word-wrap + url: Word_wrap +Write float arrays to a text file: + name: Write float arrays to a text file + path: Write-float-arrays-to-a-text-file + url: Write_float_arrays_to_a_text_file +Write language name in 3D ASCII: + name: Write language name in 3D ASCII + path: Write-language-name-in-3D-ASCII + url: Write_language_name_in_3D_ASCII +Write to Windows event log: + name: Write to Windows event log + path: Write-to-Windows-event-log + url: Write_to_Windows_event_log +XML/DOM serialization: + name: XML/DOM serialization + path: XML-DOM-serialization + url: XML/DOM_serialization +XML/Input: + name: XML/Input + path: XML-Input + url: XML/Input +XML/Output: + name: XML/Output + path: XML-Output + url: XML/Output +XML/XPath: + name: XML/XPath + path: XML-XPath + url: XML/XPath +Xiaolin Wu's line algorithm: + name: Xiaolin Wu's line algorithm + path: Xiaolin-Wus-line-algorithm + url: Xiaolin_Wu's_line_algorithm +Y combinator: + name: Y combinator + path: Y-combinator + url: Y_combinator +Yahoo! search interface: + name: Yahoo! search interface + path: Yahoo--search-interface + url: Yahoo!_search_interface +Yin and yang: + name: Yin and yang + path: Yin-and-yang + url: Yin_and_yang +Zebra puzzle: + name: Zebra puzzle + path: Zebra-puzzle + url: Zebra_puzzle +Zeckendorf arithmetic: + name: Zeckendorf arithmetic + path: Zeckendorf-arithmetic + url: Zeckendorf_arithmetic +Zeckendorf number representation: + name: Zeckendorf number representation + path: Zeckendorf-number-representation + url: Zeckendorf_number_representation +Zig-zag matrix: + name: Zig-zag matrix + path: Zig-zag-matrix + url: Zig-zag_matrix diff --git a/Task/SHA-1/0DESCRIPTION b/Task/SHA-1/0DESCRIPTION new file mode 100644 index 0000000000..ceae5f0925 --- /dev/null +++ b/Task/SHA-1/0DESCRIPTION @@ -0,0 +1,7 @@ +'''SHA-1''' or '''SHA1''' is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. + +A US government standard, [http://www.itl.nist.gov/fipspubs/fip180-1.htm FIPS 180-1], defines SHA-1. + +Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. + +{{alertbox|lightgray|'''Warning:''' SHA-1 has [https://en.wikinews.org/wiki/Chinese_researchers_crack_major_U.S._government_algorithm_used_in_digital_signatures known weaknesses]. Theoretical attacks may find a collision after [http://lwn.net/Articles/337745/ 252 operations], or perhaps fewer. This is much faster than a brute force attack of 280 operations. US government [http://csrc.nist.gov/groups/ST/hash/statement.html deprecated SHA-1]. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}} diff --git a/Task/SHA-1/1META.yaml b/Task/SHA-1/1META.yaml new file mode 100644 index 0000000000..397ec18e01 --- /dev/null +++ b/Task/SHA-1/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Checksums diff --git a/Task/SHA-1/Ada/sha-1.ada b/Task/SHA-1/Ada/sha-1.ada new file mode 100644 index 0000000000..f86f8fbdd1 --- /dev/null +++ b/Task/SHA-1/Ada/sha-1.ada @@ -0,0 +1,8 @@ +with Ada.Text_IO; +with GNAT.SHA1; + +procedure Main is +begin + Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & + GNAT.SHA1.Digest ("Rosetta Code")); +end Main; diff --git a/Task/SHA-1/BBC-BASIC/sha-1-1.bbc b/Task/SHA-1/BBC-BASIC/sha-1-1.bbc new file mode 100644 index 0000000000..81f3238705 --- /dev/null +++ b/Task/SHA-1/BBC-BASIC/sha-1-1.bbc @@ -0,0 +1,21 @@ + PRINT FNsha1("Rosetta Code") + END + + DEF FNsha1(message$) + LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% + CALG_SHA1 = &8004 + CRYPT_VERIFYCONTEXT = &F0000000 + HP_HASHVAL = 2 + PROV_RSA_FULL = 1 + buflen% = 64 + DIM buffer% LOCAL buflen%-1 + SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT + SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% + SYS "CryptHashData", hhash%, message$, LEN(message$), 0 + SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 + SYS "CryptDestroyHash", hhash% + SYS "CryptReleaseContext", hprov% + FOR i% = 0 TO buflen%-1 + hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) + NEXT + = hash$ diff --git a/Task/SHA-1/BBC-BASIC/sha-1-2.bbc b/Task/SHA-1/BBC-BASIC/sha-1-2.bbc new file mode 100644 index 0000000000..bb6d4e18b1 --- /dev/null +++ b/Task/SHA-1/BBC-BASIC/sha-1-2.bbc @@ -0,0 +1,102 @@ + *FLOAT64 + PRINT FNsha1("Rosetta Code") + END + + DEF FNsha1(message$) + LOCAL a%, b%, c%, d%, e%, f%, i%, j%, k%, l%, t% + LOCAL h0%, h1%, h2%, h3%, h4%, w%() + + REM Initialize variables: + h0% = &67452301 + h1% = &EFCDAB89 + h2% = &98BADCFE + h3% = &10325476 + h4% = &C3D2E1F0 + + l% = LEN(message$)*8 + + REM Pre-processing: + REM append the bit '1' to the message: + message$ += CHR$&80 + + REM append k bits '0', where k is the minimum number >= 0 such that + REM the resulting message length (in bits) is congruent to 448 (mod 512) + WHILE (LEN(message$) MOD 64) <> 56 + message$ += CHR$0 + ENDWHILE + + REM append length of message (before pre-processing), in bits, as + REM 64-bit big-endian integer + FOR i% = 56 TO 0 STEP -8 + message$ += CHR$(l% >>> i%) + NEXT + + REM Process the message in successive 512-bit chunks: + REM break message into 512-bit chunks, for each chunk + REM break chunk into sixteen 32-bit big-endian words w[i], 0 <= i <= 15 + + DIM w%(79) + FOR j% = 0 TO LEN(message$) DIV 64 - 1 + + FOR i% = 0 TO 15 + w%(i%) = !(!^message$ + 64*j% + 4*i%) + SWAP ?(^w%(i%)+0),?(^w%(i%)+3) + SWAP ?(^w%(i%)+1),?(^w%(i%)+2) + NEXT i% + + REM Extend the sixteen 32-bit words into eighty 32-bit words: + FOR i% = 16 TO 79 + w%(i%) = w%(i%-3) EOR w%(i%-8) EOR w%(i%-14) EOR w%(i%-16) + w%(i%) = (w%(i%) << 1) OR (w%(i%) >>> 31) + NEXT i% + + REM Initialize hash value for this chunk: + a% = h0% + b% = h1% + c% = h2% + d% = h3% + e% = h4% + + REM Main loop: + FOR i% = 0 TO 79 + CASE TRUE OF + WHEN 0 <= i% AND i% <= 19 + f% = (b% AND c%) OR ((NOT b%) AND d%) + k% = &5A827999 + WHEN 20 <= i% AND i% <= 39 + f% = b% EOR c% EOR d% + k% = &6ED9EBA1 + WHEN 40 <= i% AND i% <= 59 + f% = (b% AND c%) OR (b% AND d%) OR (c% AND d%) + k% = &8F1BBCDC + WHEN 60 <= i% AND i% <= 79 + f% = b% EOR c% EOR d% + k% = &CA62C1D6 + ENDCASE + + t% = FN32(((a% << 5) OR (a% >>> 27)) + f% + e% + k% + w%(i%)) + e% = d% + d% = c% + c% = (b% << 30) OR (b% >>> 2) + b% = a% + a% = t% + + NEXT i% + + REM Add this chunk's hash to result so far: + h0% = FN32(h0% + a%) + h1% = FN32(h1% + b%) + h2% = FN32(h2% + c%) + h3% = FN32(h3% + d%) + h4% = FN32(h4% + e%) + + NEXT j% + + = FNhex(h0%) + FNhex(h1%) + FNhex(h2%) + FNhex(h3%) + FNhex(h4%) + + DEF FNhex(A%) = RIGHT$("0000000"+STR$~A%,8) + + DEF FN32(n#) + WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE + WHILE n# < &80000000 : n# += 2^32 : ENDWHILE + = n# diff --git a/Task/SHA-1/C++/sha-1.cpp b/Task/SHA-1/C++/sha-1.cpp new file mode 100644 index 0000000000..d6a90324ca --- /dev/null +++ b/Task/SHA-1/C++/sha-1.cpp @@ -0,0 +1,20 @@ +#include +#include +#include "Poco/SHA1Engine.h" +#include "Poco/DigestStream.h" + +using Poco::DigestEngine ; +using Poco::SHA1Engine ; +using Poco::DigestOutputStream ; + +int main( ) { + std::string myphrase ( "Rosetta Code" ) ; + SHA1Engine sha1 ; + DigestOutputStream outstr( sha1 ) ; + outstr << myphrase ; + outstr.flush( ) ; //to pass everything to the digest engine + const DigestEngine::Digest& digest = sha1.digest( ) ; + std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) + << " !" << std::endl ; + return 0 ; +} diff --git a/Task/SHA-1/C-sharp/sha-1.cs b/Task/SHA-1/C-sharp/sha-1.cs new file mode 100644 index 0000000000..8eae20a359 --- /dev/null +++ b/Task/SHA-1/C-sharp/sha-1.cs @@ -0,0 +1,21 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace RosettaCode.SHA1 +{ + [TestClass] + public class SHA1CryptoServiceProviderTest + { + [TestMethod] + public void TestComputeHash() + { + var input = new UTF8Encoding().GetBytes("Rosetta Code"); + var output = new SHA1CryptoServiceProvider().ComputeHash(input); + Assert.AreEqual( + "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", + BitConverter.ToString(output)); + } + } +} diff --git a/Task/SHA-1/C/sha-1.c b/Task/SHA-1/C/sha-1.c new file mode 100644 index 0000000000..95bc0cbbfd --- /dev/null +++ b/Task/SHA-1/C/sha-1.c @@ -0,0 +1,18 @@ +#include +#include +#include +#include + +int main() +{ + int i; + unsigned char result[SHA_DIGEST_LENGTH]; + const char *string = "Rosetta Code"; + + SHA1(string, strlen(string), result); + + for(i = 0; i < SHA_DIGEST_LENGTH; i++) + printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); + + return EXIT_SUCCESS; +} diff --git a/Task/SHA-1/Common-Lisp/sha-1.lisp b/Task/SHA-1/Common-Lisp/sha-1.lisp new file mode 100644 index 0000000000..adbd8e7e4a --- /dev/null +++ b/Task/SHA-1/Common-Lisp/sha-1.lisp @@ -0,0 +1,6 @@ +;;; in addition to sha1, ironclad provides sha224, sha256, sha384, and sha512. +(defun sha1-hash (data) + (let ((sha1 (ironclad:make-digest 'ironclad:sha1)) + (bin-data (ironclad:ascii-string-to-byte-array data))) + (ironclad:update-digest sha1 bin-data) + (ironclad:byte-array-to-hex-string (ironclad:produce-digest sha1)))) diff --git a/Task/SHA-1/D/sha-1.d b/Task/SHA-1/D/sha-1.d new file mode 100644 index 0000000000..241192056f --- /dev/null +++ b/Task/SHA-1/D/sha-1.d @@ -0,0 +1,5 @@ +import std.stdio, std.digest.sha; + +void main() { + writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of()); +} diff --git a/Task/SHA-1/Go/sha-1.go b/Task/SHA-1/Go/sha-1.go new file mode 100644 index 0000000000..f12d627a3e --- /dev/null +++ b/Task/SHA-1/Go/sha-1.go @@ -0,0 +1,12 @@ +package main + +import ( + "crypto/sha1" + "fmt" +) + +func main() { + h := sha1.New() + h.Write([]byte("Rosetta Code")) + fmt.Printf("%x\n", h.Sum(nil)) +} diff --git a/Task/SHA-1/Mathematica/sha-1.math b/Task/SHA-1/Mathematica/sha-1.math new file mode 100644 index 0000000000..48a83a8f21 --- /dev/null +++ b/Task/SHA-1/Mathematica/sha-1.math @@ -0,0 +1,3 @@ +IntegerString[Hash["Rosetta Code", "SHA1"], 16] + +-> 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 diff --git a/Task/SHA-1/NetRexx/sha-1.netrexx b/Task/SHA-1/NetRexx/sha-1.netrexx new file mode 100644 index 0000000000..cb97c8a65f --- /dev/null +++ b/Task/SHA-1/NetRexx/sha-1.netrexx @@ -0,0 +1,50 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.security.MessageDigest + +SHA1('Rosetta Code', '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5') + +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method SHA1(messageText, verifyCheck) public static + + algorithm = 'SHA-1' + digestSum = getDigest(messageText, algorithm) + + say ''messageText'' + say Rexx('<'algorithm'>').right(12) || digestSum'' + say Rexx('').right(12) || verifyCheck'' + if digestSum == verifyCheck then say algorithm 'Confirmed' + else say algorithm 'Failed' + + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx + + algorithm = algorithm.upper + encoding = encoding.upper + + message = String(messageText) + messageBytes = byte[] + digestBytes = byte[] + digestSum = Rexx '' + + do + messageBytes = message.getBytes(encoding) + md = MessageDigest.getInstance(algorithm) + md.update(messageBytes) + digestBytes = md.digest + + loop b_ = 0 to digestBytes.length - 1 + bb = Rexx(digestBytes[b_]).d2x(2) + if lowercase then digestSum = digestSum || bb.lower + else digestSum = digestSum || bb.upper + end b_ + catch ex = Exception + ex.printStackTrace + end + + return digestSum diff --git a/Task/SHA-1/OCaml/sha-1.ocaml b/Task/SHA-1/OCaml/sha-1.ocaml new file mode 100644 index 0000000000..08e641959c --- /dev/null +++ b/Task/SHA-1/OCaml/sha-1.ocaml @@ -0,0 +1,5 @@ +$ ocaml -I +sha sha1.cma + Objective Caml version 3.12.1 + +# Sha1.to_hex (Sha1.string "Rosetta Code") ;; +- : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5" diff --git a/Task/SHA-1/PHP/sha-1.php b/Task/SHA-1/PHP/sha-1.php new file mode 100644 index 0000000000..e417621eb7 --- /dev/null +++ b/Task/SHA-1/PHP/sha-1.php @@ -0,0 +1,4 @@ + diff --git a/Task/SHA-1/Perl-6/sha-1.pl6 b/Task/SHA-1/Perl-6/sha-1.pl6 new file mode 100644 index 0000000000..46ae3e591d --- /dev/null +++ b/Task/SHA-1/Perl-6/sha-1.pl6 @@ -0,0 +1,44 @@ +sub postfix:(\x) { x % 2**32 } +sub infix:<⊕>(\x,\y) { (x + y)mod2³² } +sub S(\n,\X) { (X +< n)mod2³² +| (X +> (32-n)) } + +my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) }, + -> \B,\C,\D { B +^ C +^ D }, + -> \B,\C,\D { (B +& C) +| (B +& D) +| (C +& D) }, + -> \B,\C,\D { B +^ C +^ D }; + +my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6; + +sub sha1-pad(Buf $msg) +{ + my \bits = 8 * $msg.elems; + my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); + @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; +} + +sub sha1-block(@H is rw, @M) +{ + my @W = @M; + @W.push: S(1, @W[$_-3] +^ @W[$_-8] +^ @W[$_-14] +^ @W[$_-16]) for 16..79; + + my ($A,$B,$C,$D,$E) = @H; + for 0..79 -> \t { + my \TEMP = S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @W[t] ⊕ K[t div 20]; + $E = $D; $D = $C; $C = S(30,$B); $B = $A; $A = TEMP; + } + @H «⊕=» ($A,$B,$C,$D,$E); +} + +sub sha1(Buf $msg) +{ + my @M = sha1-pad($msg); + my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0; + sha1-block(@H,@M[$_..$_+15]) for 0,16...^+@M; + @H; +} + +say sha1($_.encode('ascii'))».base(16), " $_" + for 'abc', + 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + 'Rosetta Code', + 'Ars longa, vita brevis'; diff --git a/Task/SHA-1/Perl/sha-1-1.pl b/Task/SHA-1/Perl/sha-1-1.pl new file mode 100644 index 0000000000..e4cb144afa --- /dev/null +++ b/Task/SHA-1/Perl/sha-1-1.pl @@ -0,0 +1,3 @@ +use Digest::SHA qw(sha1_hex); + +print sha1_hex('Rosetta Code'), "\n"; diff --git a/Task/SHA-1/Perl/sha-1-2.pl b/Task/SHA-1/Perl/sha-1-2.pl new file mode 100644 index 0000000000..eac181d4c7 --- /dev/null +++ b/Task/SHA-1/Perl/sha-1-2.pl @@ -0,0 +1,5 @@ +use Digest::SHA; + +my $sha1 = Digest::SHA->new(1); +$sha1->add('Rosetta Code'); +print $sha1->hexdigest, "\n"; diff --git a/Task/SHA-1/PicoLisp/sha-1.l b/Task/SHA-1/PicoLisp/sha-1.l new file mode 100644 index 0000000000..3e893a227c --- /dev/null +++ b/Task/SHA-1/PicoLisp/sha-1.l @@ -0,0 +1,4 @@ +(let Str "Rosetta Code" + (pack + (mapcar '((B) (pad 2 (hex B))) + (native "libcrypto.so" "SHA1" '(B . 20) Str (length Str) '(NIL (20))) ) ) ) diff --git a/Task/SHA-1/Python/sha-1.py b/Task/SHA-1/Python/sha-1.py new file mode 100644 index 0000000000..9caca25f3d --- /dev/null +++ b/Task/SHA-1/Python/sha-1.py @@ -0,0 +1,5 @@ +import hashlib +h = hashlib.sha1() +h.update(bytes("Ars longa, vita brevis", encoding="ASCII")) +h.hexdigest() +# "e640d285242886eb96ab80cbf858389b3df52f43" diff --git a/Task/SHA-1/Racket/sha-1-1.rkt b/Task/SHA-1/Racket/sha-1-1.rkt new file mode 100644 index 0000000000..136fcc9e50 --- /dev/null +++ b/Task/SHA-1/Racket/sha-1-1.rkt @@ -0,0 +1,4 @@ +#lang racket +(require file/sha1) + +(sha1 (open-input-string "Rosetta Code")) diff --git a/Task/SHA-1/Racket/sha-1-2.rkt b/Task/SHA-1/Racket/sha-1-2.rkt new file mode 100644 index 0000000000..9af9d0a3dd --- /dev/null +++ b/Task/SHA-1/Racket/sha-1-2.rkt @@ -0,0 +1,4 @@ +#lang racket +(require openssl/sha1) + +(sha1 (open-input-string "Rosetta Code")) diff --git a/Task/SHA-1/Ruby/sha-1-1.rb b/Task/SHA-1/Ruby/sha-1-1.rb new file mode 100644 index 0000000000..5a642ed3ac --- /dev/null +++ b/Task/SHA-1/Ruby/sha-1-1.rb @@ -0,0 +1,2 @@ +require 'digest' +puts Digest::SHA1.hexdigest('Rosetta Code') diff --git a/Task/SHA-1/Ruby/sha-1-2.rb b/Task/SHA-1/Ruby/sha-1-2.rb new file mode 100644 index 0000000000..6b22289b7b --- /dev/null +++ b/Task/SHA-1/Ruby/sha-1-2.rb @@ -0,0 +1,2 @@ +require 'openssl' +puts OpenSSL::Digest::SHA1.hexdigest('Rosetta Code') diff --git a/Task/SHA-1/Ruby/sha-1-3.rb b/Task/SHA-1/Ruby/sha-1-3.rb new file mode 100644 index 0000000000..aab1d22736 --- /dev/null +++ b/Task/SHA-1/Ruby/sha-1-3.rb @@ -0,0 +1,92 @@ +require 'stringio' + +# Calculates SHA-1 message digest of _string_. Returns binary digest. +# For hexadecimal digest, use +*sha1(string).unpack('H*')+. +#-- +# This is a simple, pure-Ruby implementation of SHA-1, following +# the algorithm in FIPS 180-1. +#++ +def sha1(string) + # functions and constants + mask = (1 << 32) - 1 + s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))} + f = [ + proc {|b, c, d| (b & c) | (b.^(mask) & d)}, + proc {|b, c, d| b ^ c ^ d}, + proc {|b, c, d| (b & c) | (b & d) | (c & d)}, + proc {|b, c, d| b ^ c ^ d}, + ].freeze + k = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6].freeze + + # initial hash + h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] + + io = StringIO.new(string) + block = "" + term = false # appended "\x80" in second-last block? + last = false # last block? + until last + # Read next block of 16 words (64 bytes, 512 bits). + io.read(64, block) or ( + # Work around a bug in Rubinius 1.2.4. At eof, + # MRI and JRuby already replace block with "". + block.replace("") + ) + + # Unpack block into 32-bit words "N". + case len = block.length + when 64 + # Unpack 16 words. + w = block.unpack("N16") + when 56..63 + # Second-last block: append padding, unpack 16 words. + block.concat("\x80"); term = true + block.concat("\0" * (63 - len)) + w = block.unpack("N16") + when 0..55 + # Last block: append padding, unpack 14 words. + block.concat(term ? "\0" : "\x80") + block.concat("\0" * (55 - len)) + w = block.unpack("N14") + + # Append bit length, 2 words. + bit_len = string.length << 3 + w.push(bit_len >> 32, bit_len & mask) + last = true + else + fail "impossible" + end + + # Process block. + (16..79).each {|t| + w[t] = s[1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]]} + + a, b, c, d, e = h[0..4] + t = 0 + (0..3).each {|i| + 20.times { + temp = (s[5, a] + f[i][b, c, d] + e + w[t] + k[i]) & mask + e = d; d = c; c = s[30, b]; b = a; a = temp + t += 1}} + + h[0] = (h[0] + a) & mask + h[1] = (h[1] + b) & mask + h[2] = (h[2] + c) & mask + h[3] = (h[3] + d) & mask + h[4] = (h[4] + e) & mask + end + + h.pack("N5") +end + +if __FILE__ == $0 + # Print some example SHA-1 digests. + # FIPS 180-1 has correct digests for 'abc' and 'abc...opq'. + [ + 'abc', + 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq', + 'Rosetta Code', + ].each {|s| + printf("%s:\n %s\n", s, *sha1(s).unpack('H*')) + } +end diff --git a/Task/SHA-1/Smalltalk/sha-1-1.st b/Task/SHA-1/Smalltalk/sha-1-1.st new file mode 100644 index 0000000000..9976c57e1f --- /dev/null +++ b/Task/SHA-1/Smalltalk/sha-1-1.st @@ -0,0 +1,2 @@ +PackageLoader fileInPackage: 'Digest'. +(SHA1 hexDigestOf: 'Rosetta Code') displayNl. diff --git a/Task/SHA-1/Smalltalk/sha-1-2.st b/Task/SHA-1/Smalltalk/sha-1-2.st new file mode 100644 index 0000000000..3a5c7b2978 --- /dev/null +++ b/Task/SHA-1/Smalltalk/sha-1-2.st @@ -0,0 +1 @@ +(SHA1Stream hashValueOf:'Rosetta Code') diff --git a/Task/SHA-1/Tcl/sha-1.tcl b/Task/SHA-1/Tcl/sha-1.tcl new file mode 100644 index 0000000000..108fe51039 --- /dev/null +++ b/Task/SHA-1/Tcl/sha-1.tcl @@ -0,0 +1,2 @@ +package require sha1 +puts [sha1::sha1 "Rosetta Code"] diff --git a/Task/SHA-1/UNIX-Shell/sha-1-1.sh b/Task/SHA-1/UNIX-Shell/sha-1-1.sh new file mode 100644 index 0000000000..8641480a26 --- /dev/null +++ b/Task/SHA-1/UNIX-Shell/sha-1-1.sh @@ -0,0 +1,2 @@ +$ echo -n 'ASCII string' | sha1 +9e9aeefe5563845ec5c42c5630842048c0fc261b diff --git a/Task/SHA-1/UNIX-Shell/sha-1-2.sh b/Task/SHA-1/UNIX-Shell/sha-1-2.sh new file mode 100644 index 0000000000..b9a2f55022 --- /dev/null +++ b/Task/SHA-1/UNIX-Shell/sha-1-2.sh @@ -0,0 +1,2 @@ +$ echo -n 'ASCII string' | openssl sha1 | sed 's/.*= //' +9e9aeefe5563845ec5c42c5630842048c0fc261b diff --git a/Task/SHA-256/0DESCRIPTION b/Task/SHA-256/0DESCRIPTION new file mode 100644 index 0000000000..c61f7df0f8 --- /dev/null +++ b/Task/SHA-256/0DESCRIPTION @@ -0,0 +1,3 @@ +'''SHA-256''' is the recommended stronger alternative to [[SHA-1]]. + +Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf diff --git a/Task/SHA-256/1META.yaml b/Task/SHA-256/1META.yaml new file mode 100644 index 0000000000..0b9ae97960 --- /dev/null +++ b/Task/SHA-256/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Checksums diff --git a/Task/SHA-256/BBC-BASIC/sha-256-1.bbc b/Task/SHA-256/BBC-BASIC/sha-256-1.bbc new file mode 100644 index 0000000000..847774a279 --- /dev/null +++ b/Task/SHA-256/BBC-BASIC/sha-256-1.bbc @@ -0,0 +1,25 @@ + PRINT FNsha256("Rosetta code") + END + + DEF FNsha256(message$) + LOCAL buflen%, buffer%, hcont%, hprov%, hhash%, hash$, i% + CALG_SHA_256 = &800C + HP_HASHVAL = 2 + CRYPT_NEWKEYSET = 8 + PROV_RSA_AES = 24 + buflen% = 128 + DIM buffer% LOCAL buflen%-1 + SYS "CryptAcquireContext", ^hcont%, 0, \ + \ "Microsoft Enhanced RSA and AES Cryptographic Provider", \ + \ PROV_RSA_AES, CRYPT_NEWKEYSET + SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_AES, 0 + SYS "CryptCreateHash", hprov%, CALG_SHA_256, 0, 0, ^hhash% + SYS "CryptHashData", hhash%, message$, LEN(message$), 0 + SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 + SYS "CryptDestroyHash", hhash% + SYS "CryptReleaseContext", hprov% + SYS "CryptReleaseContext", hcont% + FOR i% = 0 TO buflen%-1 + hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) + NEXT + = hash$ diff --git a/Task/SHA-256/BBC-BASIC/sha-256-2.bbc b/Task/SHA-256/BBC-BASIC/sha-256-2.bbc new file mode 100644 index 0000000000..4043ff70ab --- /dev/null +++ b/Task/SHA-256/BBC-BASIC/sha-256-2.bbc @@ -0,0 +1,124 @@ + REM SHA-256 calculation by Richard Russell in BBC BASIC for Windows + + REM Must run in FLOAT64 mode: + *FLOAT64 + + REM Test message for validation: + message$ = "Rosetta code" + + REM Initialize variables: + h0% = &6A09E667 + h1% = &BB67AE85 + h2% = &3C6EF372 + h3% = &A54FF53A + h4% = &510E527F + h5% = &9B05688C + h6% = &1F83D9AB + h7% = &5BE0CD19 + + REM Create table of constants: + DIM k%(63) : k%() = \ + \ &428A2F98, &71374491, &B5C0FBCF, &E9B5DBA5, &3956C25B, &59F111F1, &923F82A4, &AB1C5ED5, \ + \ &D807AA98, &12835B01, &243185BE, &550C7DC3, &72BE5D74, &80DEB1FE, &9BDC06A7, &C19BF174, \ + \ &E49B69C1, &EFBE4786, &0FC19DC6, &240CA1CC, &2DE92C6F, &4A7484AA, &5CB0A9DC, &76F988DA, \ + \ &983E5152, &A831C66D, &B00327C8, &BF597FC7, &C6E00BF3, &D5A79147, &06CA6351, &14292967, \ + \ &27B70A85, &2E1B2138, &4D2C6DFC, &53380D13, &650A7354, &766A0ABB, &81C2C92E, &92722C85, \ + \ &A2BFE8A1, &A81A664B, &C24B8B70, &C76C51A3, &D192E819, &D6990624, &F40E3585, &106AA070, \ + \ &19A4C116, &1E376C08, &2748774C, &34B0BCB5, &391C0CB3, &4ED8AA4A, &5B9CCA4F, &682E6FF3, \ + \ &748F82EE, &78A5636F, &84C87814, &8CC70208, &90BEFFFA, &A4506CEB, &BEF9A3F7, &C67178F2 + + Length% = LEN(message$)*8 + + REM Pre-processing: + REM append the bit '1' to the message: + message$ += CHR$&80 + + REM append k bits '0', where k is the minimum number >= 0 such that + REM the resulting message length (in bits) is congruent to 448 (mod 512) + WHILE (LEN(message$) MOD 64) <> 56 + message$ += CHR$0 + ENDWHILE + + REM append length of message (before pre-processing), in bits, as + REM 64-bit big-endian integer: + FOR I% = 56 TO 0 STEP -8 + message$ += CHR$(Length% >>> I%) + NEXT + + REM Process the message in successive 512-bit chunks: + REM break message into 512-bit chunks, for each chunk + REM break chunk into sixteen 32-bit big-endian words w[i], 0 <= i <= 15 + + DIM w%(63) + FOR chunk% = 0 TO LEN(message$) DIV 64 - 1 + + FOR i% = 0 TO 15 + w%(i%) = !(!^message$ + 64*chunk% + 4*i%) + SWAP ?(^w%(i%)+0),?(^w%(i%)+3) + SWAP ?(^w%(i%)+1),?(^w%(i%)+2) + NEXT i% + + REM Extend the sixteen 32-bit words into sixty-four 32-bit words: + FOR i% = 16 TO 63 + s0% = FNrr(w%(i%-15),7) EOR FNrr(w%(i%-15),18) EOR (w%(i%-15) >>> 3) + s1% = FNrr(w%(i%-2),17) EOR FNrr(w%(i%-2),19) EOR (w%(i%-2) >>> 10) + w%(i%) = FN32(w%(i%-16) + s0% + w%(i%-7) + s1%) + NEXT i% + + REM Initialize hash value for this chunk: + a% = h0% + b% = h1% + c% = h2% + d% = h3% + e% = h4% + f% = h5% + g% = h6% + h% = h7% + + REM Main loop: + FOR i% = 0 TO 63 + s0% = FNrr(a%,2) EOR FNrr(a%,13) EOR FNrr(a%,22) + maj% = (a% AND b%) EOR (a% AND c%) EOR (b% AND c%) + t2% = FN32(s0% + maj%) + s1% = FNrr(e%,6) EOR FNrr(e%,11) EOR FNrr(e%,25) + ch% = (e% AND f%) EOR ((NOT e%) AND g%) + t1% = FN32(h% + s1% + ch% + k%(i%) + w%(i%)) + + h% = g% + g% = f% + f% = e% + e% = FN32(d% + t1%) + d% = c% + c% = b% + b% = a% + a% = FN32(t1% + t2%) + + NEXT i% + + REM Add this chunk's hash to result so far: + h0% = FN32(h0% + a%) + h1% = FN32(h1% + b%) + h2% = FN32(h2% + c%) + h3% = FN32(h3% + d%) + h4% = FN32(h4% + e%) + h5% = FN32(h5% + f%) + h6% = FN32(h6% + g%) + h7% = FN32(h7% + h%) + + NEXT chunk% + + REM Produce the final hash value (big-endian): + hash$ = FNhex(h0%) + " " + FNhex(h1%) + " " + FNhex(h2%) + " " + FNhex(h3%) + \ + \ " " + FNhex(h4%) + " " + FNhex(h5%) + " " + FNhex(h6%) + " " + FNhex(h7%) + + PRINT hash$ + END + + DEF FNrr(A%,I%) = (A% >>> I%) OR (A% << (32-I%)) + + DEF FNhex(A%) = RIGHT$("0000000"+STR$~A%,8) + + DEF FN32(n#) + WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE + WHILE n# < &80000000 : n# += 2^32 : ENDWHILE + = n# diff --git a/Task/SHA-256/C-sharp/sha-256.cs b/Task/SHA-256/C-sharp/sha-256.cs new file mode 100644 index 0000000000..a4a44f782d --- /dev/null +++ b/Task/SHA-256/C-sharp/sha-256.cs @@ -0,0 +1,22 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace RosettaCode.SHA256 +{ + [TestClass] + public class SHA256ManagedTest + { + [TestMethod] + public void TestComputeHash() + { + var buffer = Encoding.UTF8.GetBytes("Rosetta code"); + var hashAlgorithm = new SHA256Managed(); + var hash = hashAlgorithm.ComputeHash(buffer); + Assert.AreEqual( + "76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF", + BitConverter.ToString(hash)); + } + } +} diff --git a/Task/SHA-256/C/sha-256.c b/Task/SHA-256/C/sha-256.c new file mode 100644 index 0000000000..688dd2911d --- /dev/null +++ b/Task/SHA-256/C/sha-256.c @@ -0,0 +1,15 @@ +#include +#include +#include + +int main (void) { + const char *s = "Rosetta code"; + unsigned char *d = SHA256(s, strlen(s), 0); + + int i; + for (i = 0; i < SHA256_DIGEST_LENGTH; i++) + printf("%02x", d[i]); + putchar('\n'); + + return 0; +} diff --git a/Task/SHA-256/Go/sha-256.go b/Task/SHA-256/Go/sha-256.go new file mode 100644 index 0000000000..08c3e2437b --- /dev/null +++ b/Task/SHA-256/Go/sha-256.go @@ -0,0 +1,15 @@ +package main + +import ( + "crypto/sha256" + "fmt" + "log" +) + +func main() { + h := sha256.New() + if _, err := h.Write([]byte("Rosetta code")); err != nil { + log.Fatal(err) + } + fmt.Printf("%x\n", h.Sum(nil)) +} diff --git a/Task/SHA-256/Groovy/sha-256-1.groovy b/Task/SHA-256/Groovy/sha-256-1.groovy new file mode 100644 index 0000000000..d49c4c86e0 --- /dev/null +++ b/Task/SHA-256/Groovy/sha-256-1.groovy @@ -0,0 +1,4 @@ +def sha256Hash = { text -> + java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes) + .collect { String.format("%02x", it) }.join('') +} diff --git a/Task/SHA-256/Groovy/sha-256-2.groovy b/Task/SHA-256/Groovy/sha-256-2.groovy new file mode 100644 index 0000000000..dee3958762 --- /dev/null +++ b/Task/SHA-256/Groovy/sha-256-2.groovy @@ -0,0 +1 @@ +assert sha256Hash('Rosetta code') == '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' diff --git a/Task/SHA-256/Mathematica/sha-256.math b/Task/SHA-256/Mathematica/sha-256.math new file mode 100644 index 0000000000..657d5894c7 --- /dev/null +++ b/Task/SHA-256/Mathematica/sha-256.math @@ -0,0 +1 @@ +IntegerString[Hash["Rosetta code", "SHA256"], 16] diff --git a/Task/SHA-256/NetRexx/sha-256.netrexx b/Task/SHA-256/NetRexx/sha-256.netrexx new file mode 100644 index 0000000000..81a49dec0a --- /dev/null +++ b/Task/SHA-256/NetRexx/sha-256.netrexx @@ -0,0 +1,50 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.security.MessageDigest + +SHA256('Rosetta code', '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf') + +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method SHA256(messageText, verifyCheck) public static + + algorithm = 'SHA-256' + digestSum = getDigest(messageText, algorithm) + + say ''messageText'' + say Rexx('<'algorithm'>').right(12) || digestSum'' + say Rexx('').right(12) || verifyCheck'' + if digestSum == verifyCheck then say algorithm 'Confirmed' + else say algorithm 'Failed' + + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx + + algorithm = algorithm.upper + encoding = encoding.upper + + message = String(messageText) + messageBytes = byte[] + digestBytes = byte[] + digestSum = Rexx '' + + do + messageBytes = message.getBytes(encoding) + md = MessageDigest.getInstance(algorithm) + md.update(messageBytes) + digestBytes = md.digest + + loop b_ = 0 to digestBytes.length - 1 + bb = Rexx(digestBytes[b_]).d2x(2) + if lowercase then digestSum = digestSum || bb.lower + else digestSum = digestSum || bb.upper + end b_ + catch ex = Exception + ex.printStackTrace + end + + return digestSum diff --git a/Task/SHA-256/OCaml/sha-256.ocaml b/Task/SHA-256/OCaml/sha-256.ocaml new file mode 100644 index 0000000000..294d130e2c --- /dev/null +++ b/Task/SHA-256/OCaml/sha-256.ocaml @@ -0,0 +1,4 @@ +let () = + let s = "Rosetta code" in + let digest = Sha256.string s in + print_endline (Sha256.to_hex digest) diff --git a/Task/SHA-256/Objeck/sha-256.objeck b/Task/SHA-256/Objeck/sha-256.objeck new file mode 100644 index 0000000000..dd5ecda453 --- /dev/null +++ b/Task/SHA-256/Objeck/sha-256.objeck @@ -0,0 +1,8 @@ +class ShaHash { + function : Main(args : String[]) ~ Nil { + hash:= Encryption.Hash->SHA256("Rosetta code"->ToByteArray()); + str := hash->ToHexString()->ToLower(); + str->PrintLine(); + str->Equals("764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")->PrintLine(); + } +} diff --git a/Task/SHA-256/PHP/sha-256.php b/Task/SHA-256/PHP/sha-256.php new file mode 100644 index 0000000000..0bd3abec24 --- /dev/null +++ b/Task/SHA-256/PHP/sha-256.php @@ -0,0 +1,2 @@ + { ($^a + $^b) % 2**32 } +sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) } + +proto sha256($) returns Buf {*} +multi sha256(Str $str where all($str.ords) < 128) { + sha256 $str.encode: 'ascii' +} +multi sha256(Buf $data) { + constant K = init(* **(1/3))[^64]; + my $l = 8 * my @b = $data.list; + push @b, 0x80; push @b, 0 until (8*@b-448) %% 512; + + push @b, reverse gather for ^8 { take $l%256; $l div=256 } + my @word = :256[@b.shift xx 4] xx @b/4; + + my @H = init(&sqrt)[^8]; + my @w; + loop (my $i = 0; $i < @word; $i += 16) { + my @h = @H; + for ^64 -> $j { + @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !! + [m+] + rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3, + @w[$j-7], + rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10, + @w[$j-16]; + my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6]; + my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2]; + my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22; + my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; + my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; + my $t2 = $σ0 m+ $maj; + @h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; + } + @H = @H Z[m+] @h; + } + return Buf.new: map -> $word is rw { + reverse gather for ^4 { take $word % 256; $word div= 256 } + }, @H; +} diff --git a/Task/SHA-256/Perl/sha-256.pl b/Task/SHA-256/Perl/sha-256.pl new file mode 100644 index 0000000000..31b4022ac3 --- /dev/null +++ b/Task/SHA-256/Perl/sha-256.pl @@ -0,0 +1,7 @@ +#!/usr/bin/perl +use strict ; +use warnings ; +use Digest::SHA qw( sha256_hex ) ; + +my $digest = sha256_hex my $phrase = "Rosetta code" ; +print "SHA-256('$phrase'): $digest\n" ; diff --git a/Task/SHA-256/Python/sha-256.py b/Task/SHA-256/Python/sha-256.py new file mode 100644 index 0000000000..86ae372dea --- /dev/null +++ b/Task/SHA-256/Python/sha-256.py @@ -0,0 +1,4 @@ +>>> import hashlib +>>> hashlib.sha256( "Rosetta code" ).hexdigest() +'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' +>>> diff --git a/Task/SHA-256/Ruby/sha-256.rb b/Task/SHA-256/Ruby/sha-256.rb new file mode 100644 index 0000000000..73640f39bc --- /dev/null +++ b/Task/SHA-256/Ruby/sha-256.rb @@ -0,0 +1,2 @@ +require 'digest/sha2' +puts Digest::SHA256.hexdigest('Rosetta code') diff --git a/Task/SHA-256/Tcl/sha-256.tcl b/Task/SHA-256/Tcl/sha-256.tcl new file mode 100644 index 0000000000..cb66821179 --- /dev/null +++ b/Task/SHA-256/Tcl/sha-256.tcl @@ -0,0 +1,3 @@ +package require sha256 + +puts [sha2::sha256 -hex "Rosetta code"] diff --git a/Task/SOAP/0DESCRIPTION b/Task/SOAP/0DESCRIPTION new file mode 100644 index 0000000000..d0d8f935dc --- /dev/null +++ b/Task/SOAP/0DESCRIPTION @@ -0,0 +1,2 @@ +In this task, the goal is to create a SOAP client which accesses functions defined at '''http://example.com/soap/wsdl''', and calls the functions '''soapFunc( )''' and '''anotherSoapFunc( )'''. +{{Clarify_task}} diff --git a/Task/SOAP/1META.yaml b/Task/SOAP/1META.yaml new file mode 100644 index 0000000000..b9cc03ec34 --- /dev/null +++ b/Task/SOAP/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Less Than 10 Examples +note: Networking and Web Interaction diff --git a/Task/SOAP/ActionScript/soap.as b/Task/SOAP/ActionScript/soap.as new file mode 100644 index 0000000000..02209b0dee --- /dev/null +++ b/Task/SOAP/ActionScript/soap.as @@ -0,0 +1,16 @@ +import mx.rpc.soap.WebService; +import mx.rpc.events.ResultEvent; +var ws:WebService = new WebService(); +ws.wsdl = 'http://example.com/soap/wsdl'; +ws.soapFunc.addEventListener("result",soapFunc_Result); +ws.anotherSoapFunc.addEventListener("result",anotherSoapFunc_Result); +ws.loadWSDL(); +ws.soapFunc(); +ws.anotherSoapFunc(); +// method invocation callback handlers +private function soapFunc_Result(event:ResultEvent):void { + // do something +} +private function anotherSoapFunc_Result(event:ResultEvent):void { + // do another something +} diff --git a/Task/SOAP/AutoHotkey/soap.ahk b/Task/SOAP/AutoHotkey/soap.ahk new file mode 100644 index 0000000000..203dc071af --- /dev/null +++ b/Task/SOAP/AutoHotkey/soap.ahk @@ -0,0 +1,11 @@ +WS_Initialize() + WS_Exec("Set client = CreateObject(""MSSOAP.SoapClient"")") + WS_Exec("client.MSSoapInit ""http://example.com/soap/wsdl""") + callhello = client.soapFunc("hello") + callanother = client.anotherSoapFunc(34234) + + WS_Eval(result, callhello) + WS_Eval(result2, callanother) + Msgbox % result . "`n" . result2 + WS_Uninitialize() +#Include ws4ahk.ahk ; http://www.autohotkey.net/~easycom/ws4ahk_public_api.html diff --git a/Task/SOAP/ColdFusion/soap.cfm b/Task/SOAP/ColdFusion/soap.cfm new file mode 100644 index 0000000000..9d489d27f5 --- /dev/null +++ b/Task/SOAP/ColdFusion/soap.cfm @@ -0,0 +1,3 @@ + + + diff --git a/Task/SOAP/Mathematica/soap.math b/Task/SOAP/Mathematica/soap.math new file mode 100644 index 0000000000..95d7be0ef5 --- /dev/null +++ b/Task/SOAP/Mathematica/soap.math @@ -0,0 +1,3 @@ +InstallService["http://example.com/soap/wsdl"]; +soapFunc["Hello"]; +anotherSoapFunc[12345]; diff --git a/Task/SOAP/PHP/soap.php b/Task/SOAP/PHP/soap.php new file mode 100644 index 0000000000..e2e6d0196c --- /dev/null +++ b/Task/SOAP/PHP/soap.php @@ -0,0 +1,14 @@ +soapFunc("hello"); +$result = $client->anotherSoapFunc(34234); + +//SOAP Information +$client = new SoapClient("http://example.com/soap/definition.wsdl"); +//list of SOAP types +print_r($client->__getTypes()); +//list if SOAP Functions +print_r($client->__getFunctions()); +?> diff --git a/Task/SOAP/Perl/soap.pl b/Task/SOAP/Perl/soap.pl new file mode 100644 index 0000000000..ae60ea9d8f --- /dev/null +++ b/Task/SOAP/Perl/soap.pl @@ -0,0 +1,8 @@ +use SOAP::Lite; + +print SOAP::Lite + -> service('http://example.com/soap/wsdl') + -> soapFunc("hello"); +print SOAP::Lite + -> service('http://example.com/soap/wsdl') + -> anotherSoapFunc(34234); diff --git a/Task/SOAP/PureBasic/soap.purebasic b/Task/SOAP/PureBasic/soap.purebasic new file mode 100644 index 0000000000..019d30fa26 --- /dev/null +++ b/Task/SOAP/PureBasic/soap.purebasic @@ -0,0 +1,5 @@ +XIncludeFile "COMatePLUS.pbi" +Define.COMateObject soapObject = COMate_CreateObject("MSSOAP.SoapClient") +soapObject\Invoke("MSSoapInit('http://example.com/soap/wsdl')") +result = soapObject\Invoke("soapFunc('hello')") +result2 = soapObject\Invoke("anotherSoapFunc(34234)") diff --git a/Task/SOAP/Python/soap.py b/Task/SOAP/Python/soap.py new file mode 100644 index 0000000000..de56882c6b --- /dev/null +++ b/Task/SOAP/Python/soap.py @@ -0,0 +1,4 @@ +from SOAPpy import WSDL +proxy = WSDL.Proxy("http://example.com/soap/wsdl") +result = proxy.soapFunc("hello") +result = proxy.anotherSoapFunc(34234) diff --git a/Task/SOAP/Ruby/soap.rb b/Task/SOAP/Ruby/soap.rb new file mode 100644 index 0000000000..018cb06bfd --- /dev/null +++ b/Task/SOAP/Ruby/soap.rb @@ -0,0 +1,10 @@ +require 'soap/wsdlDriver' + +wsdl = SOAP::WSDLDriverFactory.new("http://example.com/soap/wsdl") +soap = wsdl.create_rpc_driver + +response1 = soap.soapFunc(:elementName => "value") +puts response1.soapFuncReturn + +response2 = soap.anotherSoapFunc(:aNumber => 42) +puts response2.anotherSoapFuncReturn diff --git a/Task/SOAP/Tcl/soap.tcl b/Task/SOAP/Tcl/soap.tcl new file mode 100644 index 0000000000..cedf46b3be --- /dev/null +++ b/Task/SOAP/Tcl/soap.tcl @@ -0,0 +1,9 @@ +package require WS::Client + +# Grok the service, and generate stubs +::WS::Client::GetAndParseWsdl http://example.com/soap/wsdl +::WS::Client::CreateStubs ExampleService ;# Assume that's the service name... + +# Do the calls +set result1 [ExampleService::soapFunc "hello"] +set result2 [ExampleService::anotherSoapFunc 34234] diff --git a/Task/SOAP/VBScript/soap.vbscript b/Task/SOAP/VBScript/soap.vbscript new file mode 100644 index 0000000000..1a31341912 --- /dev/null +++ b/Task/SOAP/VBScript/soap.vbscript @@ -0,0 +1,6 @@ +Dim client +Dim result +Set client = CreateObject("MSSOAP.SoapClient") +client.MSSoapInit "http://example.com/soap/wsdl" +result = client.soapFunc("hello") +result = client.anotherSoapFunc(34234) diff --git a/Task/SOAP/Visual-Objects/soap.vobj b/Task/SOAP/Visual-Objects/soap.vobj new file mode 100644 index 0000000000..ba138b5122 --- /dev/null +++ b/Task/SOAP/Visual-Objects/soap.vobj @@ -0,0 +1,10 @@ +LOCAL oSoapClient AS OLEAUTOOBJECT +LOCAL cUrl AS STRING +LOCAL uResult AS USUAL +oSoapClient := OLEAutoObject{"MSSOAP.SoapClient30"} +cUrl := "http://example.com/soap/wsdl" +IF oSoapClient:fInit + oSoapClient:mssoapinit(cUrl,"", "", "" ) + uResult := oSoapClient:soapFunc("hello") + uResult := oSoapClient:anotherSoapFunc(34234) +ENDIF diff --git a/Task/SQL-based-authentication/0DESCRIPTION b/Task/SQL-based-authentication/0DESCRIPTION new file mode 100644 index 0000000000..49a0979e0e --- /dev/null +++ b/Task/SQL-based-authentication/0DESCRIPTION @@ -0,0 +1,15 @@ +This task has three parts: +* Connect to a [[MySQL]] database (connect_db) +* Create user/password records in the following table (create_user) +* Authenticate login requests against the table (authenticate_user) + +This is the table definition: +create table users ( + userid int primary key auto_increment, + username varchar(32) unique key not null, + pass_salt tinyblob not null, + -- a string of 16 random bytes + pass_md5 tinyblob not null + -- binary MD5 hash of pass_salt concatenated with the password +); +(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.) diff --git a/Task/SQL-based-authentication/1META.yaml b/Task/SQL-based-authentication/1META.yaml new file mode 100644 index 0000000000..7fec23b86a --- /dev/null +++ b/Task/SQL-based-authentication/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Database operations diff --git a/Task/SQL-based-authentication/C/sql-based-authentication.c b/Task/SQL-based-authentication/C/sql-based-authentication.c new file mode 100644 index 0000000000..7a6b9408a1 --- /dev/null +++ b/Task/SQL-based-authentication/C/sql-based-authentication.c @@ -0,0 +1,174 @@ +#include +#include +#include +#include +#include + +#include +#include + +void end_with_db(void); + +MYSQL *mysql = NULL; // global... + +bool connect_db(const char *host, const char *user, const char *pwd, + const char *db, unsigned int port) +{ + if ( mysql == NULL ) + { + if (mysql_library_init(0, NULL, NULL)) return false; + mysql = mysql_init(NULL); if ( mysql == NULL ) return false; + MYSQL *myp = mysql_real_connect(mysql, host, user, pwd, db, port, NULL, 0); + if (myp == NULL) { + fprintf(stderr, "connection error: %s\n", mysql_error(mysql)); + end_with_db(); + return false; + } + } + return true; // already connected... ? +} + +#define USERNAMELIMIT 32 +// no part of the spec, but it is reasonable!! +#define PASSWORDLIMIT 32 +#define SALTBYTE 16 +bool create_user(const char *username, const char *password) +{ + int i; + char binarysalt[SALTBYTE]; + char salt[SALTBYTE*2+1]; + char md5hash[MD5_DIGEST_LENGTH]; + char saltpass[SALTBYTE+PASSWORDLIMIT+1]; + char pass_md5[MD5_DIGEST_LENGTH*2 + 1]; + char user[USERNAMELIMIT*2 + 1]; + char *q = NULL; + static const char query[] = + "INSERT INTO users " + "(username,pass_salt,pass_md5) " + "VALUES ('%s', X'%s', X'%s')"; + static const size_t qlen = sizeof query; + + + for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ; + if ( username[i] != '\0' ) return false; + for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ; + if ( password[i] != '\0' ) return false; + + srand(time(NULL)); + + for(i=0; i < SALTBYTE; i++) + { + // this skews the distribution but it is lazyness-compliant;) + binarysalt[i] = rand()%256; + } + + (void)mysql_hex_string(salt, binarysalt, SALTBYTE); + + for(i=0; i < SALTBYTE; i++) saltpass[i] = binarysalt[i]; + strcpy(saltpass+SALTBYTE, password); + (void)MD5(saltpass, SALTBYTE + strlen(password), md5hash); + (void)mysql_hex_string(pass_md5, md5hash, MD5_DIGEST_LENGTH); + + (void)mysql_real_escape_string(mysql, user, username, strlen(username)); + + // salt, pass_md5, user are db-query-ready + q = malloc(qlen + USERNAMELIMIT*2 + MD5_DIGEST_LENGTH*2 + SALTBYTE*2 + 1); + if ( q == NULL ) return false; + sprintf(q, query, user, salt, pass_md5); +#if defined(DEBUG) + fprintf(stderr, "QUERY:\n%s\n\n", q); +#endif + int res = mysql_query(mysql, q); + free(q); + if ( res != 0 ) + { + fprintf(stderr, "create_user query error: %s\n", mysql_error(mysql)); + return false; + } + return true; +} + + +bool authenticate_user(const char *username, const char *password) +{ + char user[USERNAMELIMIT*2 + 1]; + char md5hash[MD5_DIGEST_LENGTH]; + char saltpass[SALTBYTE+PASSWORDLIMIT+1]; + bool authok = false; + char *q = NULL; + int i; + static const char query[] = + "SELECT * FROM users WHERE username='%s'"; + static const size_t qlen = sizeof query; + + // can't be authenticated with invalid username or password + for(i=0; username[i] != '\0' && i < USERNAMELIMIT; i++) ; + if ( username[i] != '\0' ) return false; + for(i=0; password[i] != '\0' && i < PASSWORDLIMIT; i++) ; + if ( password[i] != '\0' ) return false; + + (void)mysql_real_escape_string(mysql, user, username, strlen(username)); + + q = malloc(qlen + strlen(user) + 1); + if (q == NULL) return false; + sprintf(q, query, username); + + int res = mysql_query(mysql, q); + free(q); + if ( res != 0 ) + { + fprintf(stderr, "authenticate_user query error: %s\n", mysql_error(mysql)); + return false; + } + + MYSQL_RES *qr = mysql_store_result(mysql); + if ( qr == NULL ) return false; + + // should be only a result, or none + if ( mysql_num_rows(qr) != 1 ) { + mysql_free_result(qr); + return false; + } + + MYSQL_ROW row = mysql_fetch_row(qr); // 1 row must exist + unsigned long *len = mysql_fetch_lengths(qr); // and should have 4 cols... + + memcpy(saltpass, row[2], len[2]); // len[2] should be SALTBYTE + memcpy(saltpass + len[2], password, strlen(password)); + (void)MD5(saltpass, SALTBYTE + strlen(password), md5hash); + + authok = memcmp(md5hash, row[3], len[3]) == 0; + mysql_free_result(qr); + + return authok; +} + +void end_with_db(void) +{ + mysql_close(mysql); mysql = NULL; + mysql_library_end(); +} + +int main(int argc, char **argv) +{ + + if ( argc < 4 ) return EXIT_FAILURE; + + if ( connect_db("localhost", "devel", "", "test", 0 ) ) + { + if ( strcmp(argv[1], "add") == 0 ) + { + if (create_user(argv[2], argv[3])) + printf("created\n"); + } else if ( strcmp(argv[1], "auth") == 0 ) { + if (authenticate_user(argv[2], argv[3])) + printf("authorized\n"); + else + printf("access denied\n"); + } else { + printf("unknown command\n"); + } + end_with_db(); + } + return EXIT_SUCCESS; +} diff --git a/Task/SQL-based-authentication/Java/sql-based-authentication.java b/Task/SQL-based-authentication/Java/sql-based-authentication.java new file mode 100644 index 0000000000..da2e1a760f --- /dev/null +++ b/Task/SQL-based-authentication/Java/sql-based-authentication.java @@ -0,0 +1,142 @@ +import java.io.UnsupportedEncodingException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.math.BigInteger; + + +class UserManager { + private Connection dbConnection; + + public UserManager() { + } + + private String md5(String aString) throws NoSuchAlgorithmException, UnsupportedEncodingException { + MessageDigest md; + String hex; + StringBuffer hexString; + byte[] bytesOfMessage; + byte[] theDigest; + + hexString = new StringBuffer(); + bytesOfMessage = aString.getBytes("UTF-8"); + md = MessageDigest.getInstance("MD5"); + theDigest = md.digest(bytesOfMessage); + + for (int i = 0; i < theDigest.length; i++) { + hex = Integer.toHexString(0xff & theDigest[i]); + if (hex.length() == 1) { + hexString.append('0'); + } + hexString.append(hex); + } + + return hexString.toString(); + } + + public void connectDB(String host, int port, String db, String user, String password) + throws ClassNotFoundException, SQLException { + + Class.forName("com.mysql.jdbc.Driver"); + + this.dbConnection = DriverManager.getConnection("jdbc:mysql://" + + host + + ":" + + port + + "/" + + db, user, password); + } + + public boolean createUser(String user, String password) { + SecureRandom random; + String insert; + String salt; + + random = new SecureRandom(); + salt = new BigInteger(130, random).toString(16); + + insert = "INSERT INTO users " + + "(username, pass_salt, pass_md5) " + + "VALUES (?, ?, ?)"; + + try (PreparedStatement pstmt = this.dbConnection.prepareStatement(insert)) { + pstmt.setString(1, user); + pstmt.setString(2, salt); + pstmt.setString(3, this.md5(salt + password)); + pstmt.executeUpdate(); + + return true; + } catch(NoSuchAlgorithmException | SQLException | UnsupportedEncodingException ex) { + return false; + } + } + + public boolean authenticateUser(String user, String password) { + String pass_md5; + String pass_salt; + String select; + ResultSet res; + + select = "SELECT pass_salt, pass_md5 FROM users WHERE username = ?"; + res = null; + + try(PreparedStatement pstmt = this.dbConnection.prepareStatement(select)) { + pstmt.setString(1, user); + res = pstmt.executeQuery(); + + res.next(); // We assume that username is unique + + pass_salt = res.getString(1); + pass_md5 = res.getString(2); + + if (pass_md5.equals(this.md5(pass_salt + password))) { + return true; + } else { + return false; + } + + } catch(NoSuchAlgorithmException | SQLException | UnsupportedEncodingException ex) { + return false; + } finally { + try { + if (res instanceof ResultSet && !res.isClosed()) { + res.close(); + } + } catch(SQLException ex) { + } + } + } + + public void closeConnection() { + try { + this.dbConnection.close(); + } catch(NullPointerException | SQLException ex) { + } + } + + public static void main(String[] args) { + UserManager um; + + um = new UserManager(); + try { + um.connectDB("localhost", 3306, "test", "root", "admin"); + + if (um.createUser("johndoe", "test")) { + System.out.println("User created"); + } + + if (um.authenticateUser("johndoe", "test")) { + System.out.println("User authenticated"); + } + } catch(ClassNotFoundException | SQLException ex) { + ex.printStackTrace(); + } finally { + um.closeConnection(); + } + } +} diff --git a/Task/SQL-based-authentication/PHP/sql-based-authentication.php b/Task/SQL-based-authentication/PHP/sql-based-authentication.php new file mode 100644 index 0000000000..da9292c3ed --- /dev/null +++ b/Task/SQL-based-authentication/PHP/sql-based-authentication.php @@ -0,0 +1,69 @@ +function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) { + // Returns a MySQL link identifier (handle) on success + // Returns false or dies() on error depending on the setting of parameter $die + // Parameter $die configures error handling, setting it any non-false value will die() on error + // Parameters $host, $port and $die have sensible defaults and are not usually required + + if(!$db_handle = @mysql_connect($host.($port ? ':'.$port : ''), $db_user, $db_password)) { + if($die) + die("Can't connect to MySQL server:\r\n".mysql_error()); + else + return false; + } + if(!@mysql_select_db($database, $db_handle)) { + if($die) + die("Can't select database '$database':\r\n".mysql_error()); + else + return false; + } + return $db_handle; +} + +function create_user($username, $password, $db_handle) { + // Returns the record ID on success or false on failure + // Username limit is 32 characters (part of spec) + if(strlen($username) > 32) + return false; + + // Salt limited to ASCII 32 thru 254 (not part of spec) + $salt = ''; + do { + $salt .= chr(mt_rand(32, 254)); + } while(strlen($salt) < 16); + + // Create pass_md5 + $pass_md5 = md5($salt.$password); + + // Make it all binary safe + $username = mysql_real_escape_string($username); + $salt = mysql_real_escape_string($salt); + + // Try to insert it into the table - Return false on failure + if(!@mysql_query("INSERT INTO users (username,pass_salt,pass_md5) VALUES('$username','$salt','$pass_md5')", $db_handle)) + return false; + + // Return the record ID + return mysql_insert_id($db_handle); +} + +function authenticate_user($username, $password, $db_handle) { + // Checks a username/password combination against the database + // Returns false on failure or the record ID on success + + // Make the username parmeter binary-safe + $safe_username = mysql_real_escape_string($username); + + // Grab the record (if it exists) - Return false on failure + if(!$result = @mysql_query("SELECT * FROM users WHERE username='$safe_username'", $db_handle)) + return false; + + // Grab the row + $row = @mysql_fetch_assoc($result); + + // Check the password and return false if incorrect + if(md5($row['pass_salt'].$password) != $row['pass_md5']) + return false; + + // Return the record ID + return $row['userid']; +} diff --git a/Task/SQL-based-authentication/Perl/sql-based-authentication.pl b/Task/SQL-based-authentication/Perl/sql-based-authentication.pl new file mode 100644 index 0000000000..75ca55b512 --- /dev/null +++ b/Task/SQL-based-authentication/Perl/sql-based-authentication.pl @@ -0,0 +1,30 @@ +use DBI; + + # returns a database handle configured to throw an exception on query errors +sub connect_db { + my ($dbname, $host, $user, $pass) = @_; + my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass) + or die $DBI::errstr; + $db->{RaiseError} = 1; + $db +} + + # if the user was successfully created, returns its user id. + # if the name was already in use, returns undef. +sub create_user { + my ($db, $user, $pass) = @_; + my $salt = pack "C*", map {int rand 256} 1..16; + $db->do("INSERT IGNORE INTO users (username, pass_salt, pass_md5) + VALUES (?, ?, unhex(md5(concat(pass_salt, ?))))", + undef, $user, $salt, $pass) + and $db->{mysql_insertid} or undef +} + + # if the user is authentic, returns its user id. otherwise returns undef. +sub authenticate_user { + my ($db, $user, $pass) = @_; + my $userid = $db->selectrow_array("SELECT userid FROM users WHERE + username=? AND pass_md5=unhex(md5(concat(pass_salt, ?)))", + undef, $user, $pass); + $userid +} diff --git a/Task/SQL-based-authentication/Python/sql-based-authentication.py b/Task/SQL-based-authentication/Python/sql-based-authentication.py new file mode 100644 index 0000000000..dcd9edda34 --- /dev/null +++ b/Task/SQL-based-authentication/Python/sql-based-authentication.py @@ -0,0 +1,82 @@ +import mysql.connector +import hashlib + +import sys +import random + +DB_HOST = "localhost" +DB_USER = "devel" +DB_PASS = "devel" +DB_NAME = "test" + +def connect_db(): + ''' Try to connect DB and return DB instance, if not, return False ''' + try: + return mysql.connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME) + except: + return False + +def create_user(username, passwd): + ''' if user was successfully created, returns its ID; returns None on error ''' + db = connect_db() + if not db: + print "Can't connect MySQL!" + return None + + cursor = db.cursor() + + salt = randomValue(16) + passwd_md5 = hashlib.md5(salt+passwd).hexdigest() + + # If username already taken, inform it + try: + cursor.execute("INSERT INTO users (`username`, `pass_salt`, `pass_md5`) VALUES (%s, %s, %s)", (username, salt, passwd_md5)) + cursor.execute("SELECT userid FROM users WHERE username=%s", (username,) ) + id = cursor.fetchone() + db.commit() + cursor.close() + db.close() + return id[0] + except: + print 'Username was already taken. Please select another' + return None + +def authenticate_user(username, passwd): + db = connect_db() + if not db: + print "Can't connect MySQL!" + return False + + cursor = db.cursor() + + cursor.execute("SELECT pass_salt, pass_md5 FROM users WHERE username=%s", (username,)) + + row = cursor.fetchone() + cursor.close() + db.close() + if row is None: # username not found + return False + salt = row[0] + correct_md5 = row[1] + tried_md5 = hashlib.md5(salt+passwd).hexdigest() + return correct_md5 == tried_md5 + +def randomValue(length): + ''' Creates random value with given length''' + salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789' + + return ''.join(random.choice(salt_chars) for x in range(length)) + +if __name__ == '__main__': + user = randomValue(10) + passwd = randomValue(16) + + new_user_id = create_user(user, passwd) + if new_user_id is None: + print 'Failed to create user %s' % user + sys.exit(1) + auth = authenticate_user(user, passwd) + if auth: + print 'User %s authenticated successfully' % user + else: + print 'User %s failed' % user diff --git a/Task/SQL-based-authentication/Raven/sql-based-authentication.raven b/Task/SQL-based-authentication/Raven/sql-based-authentication.raven new file mode 100644 index 0000000000..14d1f8764c --- /dev/null +++ b/Task/SQL-based-authentication/Raven/sql-based-authentication.raven @@ -0,0 +1,31 @@ + 'mysql://root@localhost/test' open as mysql +'abcdefghijklmnopqrstuvwxyz0123456789' as $salt_chars + +# return userid for success and FALSE for failure. +define create_user use $user, $pass + group 16 each as i + $salt_chars choose chr + join as $pass_salt + "%($pass_salt)s%($pass)s" md5 as $pass_md5 + $user copy mysql escape as $user_name + group 'INSERT IGNORE into users (username, pass_md5, pass_salt)' + " VALUES ('%($user_name)s', unhex('%($pass_md5)s'), '%($pass_salt)s')" + join mysql query inserted + +# return userid for success and FALSE for failure. +define authenticate_user use $user, $pass + FALSE as $userid + $user copy mysql escape as $user_name + group 'SELECT userid, pass_salt, hex(pass_md5)' + " FROM users WHERE username = '%($user_name)s'" + join mysql query as rs + rs selected + if rs fetch values into $possible_userid, $pass_salt, $pass_md5 + "%($pass_salt)s%($pass)s" md5 $pass_md5 lower = + if $possible_userid as $userid + $userid + +'foo' 'bar' create_user !if "could not create user\n" print bye +'foo' 'bar' authenticate_user !if "could not authenticate user\n" print bye + +"user successfully created and authenticated!\n" print diff --git a/Task/SQL-based-authentication/Tcl/sql-based-authentication.tcl b/Task/SQL-based-authentication/Tcl/sql-based-authentication.tcl new file mode 100644 index 0000000000..7307bf64a1 --- /dev/null +++ b/Task/SQL-based-authentication/Tcl/sql-based-authentication.tcl @@ -0,0 +1,36 @@ +package require tdbc + +proc connect_db {handleName dbname host user pass} { + package require tdbc::mysql + tdbc::mysql::connection create $handleName -user $user -passwd $pass \ + -host $host -database $dbname + return $handleName +} + +# A simple helper to keep code shorter +proc r64k {} { + expr int(65536*rand()) +} + +proc create_user {handle user pass} { + set salt [binary format ssssssss \ + [r64k] [r64k] [r64k] [r64k] [r64k] [r64k] [r64k] [r64k]] + # Note that we are using named parameters below, :user :salt :pass + # They are bound automatically to local variables with the same name + $handle allrows { + INSERT IGNORE INTO users (username, pass_salt, pass_md5) + VALUES (:user, :salt, unhex(md5(concat(:salt, :pass)))) + } + return ;# Ignore the result of the allrows method +} + +proc authenticate_user {handle user pass} { + $handle foreach row { + SELECT userid FROM users WHERE + username=:user AND pass_md5=unhex(md5(concat(pass_salt, :pass))) + } { + return [dict get $row userid] + } + # Only get here if no rows selected + error "authentication failed for user \"$user\"" +} diff --git a/Task/Set-puzzle/0DESCRIPTION b/Task/Set-puzzle/0DESCRIPTION new file mode 100644 index 0000000000..872f652a4d --- /dev/null +++ b/Task/Set-puzzle/0DESCRIPTION @@ -0,0 +1,62 @@ +Set Puzzles are created with a deck of cards from the [[wp:Set (game)|Set Game™]]. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: ''color, symbol, number and shading''. + +; there are three colors: '''red''', '''green''', or '''purple''' + +; there are three symbols: '''oval''', '''squiggle''', or '''diamond''' + +; there is a number of symbols on the card: '''one''', '''two''', or '''three''' + +; there are three shadings: '''solid''', '''open''', or '''striped''' + +Three cards form a ''set'' if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. + +There are two degrees of difficulty: [http://www.setgame.com/set/rules_basic.htm ''basic''] and [http://www.setgame.com/set/rules_advanced.htm ''advanced'']. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets. When creating sets you may use the same card more than once. The task is to write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. For instance: + +'''DEALT 9 CARDS:''' + +:green, one, oval, striped + +:green, one, diamond, open + +:green, one, diamond, striped + +:green, one, diamond, solid + +:purple, one, diamond, open + +:purple, two, squiggle, open + +:purple, three, oval, open + +:red, three, oval, open + +:red, three, diamond, solid + +'''CONTAINING 4 SETS:''' + +:green, one, oval, striped + +:purple, two, squiggle, open + +:red, three, diamond, solid + + +:green, one, diamond, open + +:green, one, diamond, striped + +:green, one, diamond, solid + + +:green, one, diamond, open + +:purple, two, squiggle, open + +:red, three, oval, open + + +:purple, one, diamond, open + +:purple, two, squiggle, open + +:purple, three, oval, open diff --git a/Task/Set-puzzle/C/set-puzzle.c b/Task/Set-puzzle/C/set-puzzle.c new file mode 100644 index 0000000000..7957141e68 --- /dev/null +++ b/Task/Set-puzzle/C/set-puzzle.c @@ -0,0 +1,95 @@ +#include +#include + +char *names[4][3] = { + { "red", "green", "purple" }, + { "oval", "squiggle", "diamond" }, + { "one", "two", "three" }, + { "solid", "open", "striped" } +}; + +int set[81][81]; + +void init_sets(void) +{ + int i, j, t, a, b; + for (i = 0; i < 81; i++) { + for (j = 0; j < 81; j++) { + for (t = 27; t; t /= 3) { + a = (i / t) % 3; + b = (j / t) % 3; + set[i][j] += t * (a == b ? a : 3 - a - b); + } + } + } +} + +void deal(int *out, int n) +{ + int i, j, t, c[81]; + for (i = 0; i < 81; i++) c[i] = i; + for (i = 0; i < n; i++) { + j = i + (rand() % (81 - i)); + t = c[i], c[i] = out[i] = c[j], c[j] = t; + } +} + +int get_sets(int *cards, int n, int sets[][3]) +{ + int i, j, k, s = 0; + for (i = 0; i < n; i++) { + for (j = i + 1; j < n; j++) { + for (k = j + 1; k < n; k++) { + if (set[cards[i]][cards[j]] == cards[k]) + sets[s][0] = i, + sets[s][1] = j, + sets[s][2] = k, + s++; + } + } + } + + return s; +} + +void show_card(int c) +{ + int i, t; + for (i = 0, t = 27; t; i++, t /= 3) + printf("%9s", names[i][(c/t)%3]); + putchar('\n'); +} + +void deal_sets(int ncard, int nset) +{ + int c[81]; + int csets[81][3]; // might not be enough for large ncard + int i, j, s; + + do deal(c, ncard); while ((s = get_sets(c, ncard, csets)) != nset); + + printf("dealt %d cards\n", ncard); + for (i = 0; i < ncard; i++) { + printf("%2d:", i); + show_card(c[i]); + } + printf("\nsets:\n"); + + for (i = 0; i < s; i++) { + for (j = 0; j < 3; j++) { + printf("%2d:", csets[i][j]); + show_card(c[csets[i][j]]); + } + putchar('\n'); + } +} + +int main(void) +{ + init_sets(); + deal_sets(9, 4); + + while (1) deal_sets(12, 6); + + return 0; +} diff --git a/Task/Set-puzzle/D/set-puzzle.d b/Task/Set-puzzle/D/set-puzzle.d new file mode 100644 index 0000000000..ccad40f77e --- /dev/null +++ b/Task/Set-puzzle/D/set-puzzle.d @@ -0,0 +1,108 @@ +import std.stdio, std.random, std.array, std.conv, std.traits, + std.exception; + +const class SetDealer { + protected { + enum Color : ubyte {green, purple, red} + enum Number : ubyte {one, two, three} + enum Symbol : ubyte {oval, diamond, squiggle} + enum Fill : ubyte {open, striped, solid} + + static struct Card { + Color c; + Number n; + Symbol s; + Fill f; + } + + immutable Card[81] deck; + } + + this() pure nothrow { + Card[] tmpdeck; + + immutable colors = [EnumMembers!Color]; + immutable numbers = [EnumMembers!Number]; + immutable symbols = [EnumMembers!Symbol]; + immutable fill = [EnumMembers!Fill]; + + foreach (immutable i; 0 .. deck.length) + tmpdeck ~= Card(colors[i / 27], + numbers[(i / 9) % 3], + symbols[(i / 3) % 3], + fill[i % 3]); + + // randomShuffle(tmpdeck); /* not pure nothrow */ + + deck = assumeUnique(tmpdeck); + } + + // randomSample produces a sorted output that's convenient in our + // case because we're printing to stout. Normally you would want + // to shuffle. + immutable(Card)[] deal(in uint numCards) const { + enforce(numCards < deck.length, "number of cards too large"); + return deck[].randomSample(numCards).array(); + } + + // The summed enums of valid sets are always zero or a multiple + // of 3. + bool validSet(in ref Card c1, in ref Card c2, in ref Card c3) + const pure nothrow { + return !((c1.c + c2.c + c3.c) % 3 || + (c1.n + c2.n + c3.n) % 3 || + (c1.s + c2.s + c3.s) % 3 || + (c1.f + c2.f + c3.f) % 3); + } + + immutable(Card)[3][] findSets(in Card[] cards, in uint target = 0) + const pure nothrow { + immutable len = cards.length; + if (len < 3) + return null; + + typeof(return) sets; + foreach (immutable i; 0 .. len - 2) + foreach (immutable j; i + 1 .. len - 1) + foreach (immutable k; j + 1 .. len) + if (validSet(cards[i], cards[j], cards[k])) { + sets ~= [cards[i], cards[j], cards[k]]; + if (target != 0 && sets.length > target) + return null; + } + return sets; + } +} + +const final class SetPuzzleDealer : SetDealer { + enum {basic = 9, advanced = 12} + + override immutable(Card)[] deal(in uint numCards = basic) const { + immutable numSets = numCards / 2; + typeof(return) cards; + + do { + cards = super.deal(numCards); + } while (findSets(cards, numSets).length != numSets); + + return cards; + } +} + +void main() { + const dealer = new SetPuzzleDealer(); + const cards = dealer.deal(); + + writefln("\nDEALT %d CARDS:\n", cards.length); + foreach (c; cards) + writeln(cast()c); + + immutable sets = dealer.findSets(cards); + immutable len = sets.length; + writefln("\nFOUND %d %s:\n", len, len == 1 ? "SET" : "SETS"); + foreach (set; sets) { + foreach (c; set) + writeln(cast()c); + writeln(); + } +} diff --git a/Task/Set-puzzle/J/set-puzzle-1.j b/Task/Set-puzzle/J/set-puzzle-1.j new file mode 100644 index 0000000000..91a8bb01d4 --- /dev/null +++ b/Task/Set-puzzle/J/set-puzzle-1.j @@ -0,0 +1,24 @@ +require 'stats/base' + +Number=: ;:'one two three' +Colour=: ;:'red green purple' +Fill=: ;:'solid open striped' +Symbol=: ;:'oval squiggle diamond' +Features=: Number ; Colour ; Fill ;< Symbol +Deck=: > ; <"1 { i.@#&.> Features +sayCards=: (', ' joinstring Features {&>~ ])"1 +drawRandom=: ] {~ (? #) +isSet=: *./@:(1 3 e.~ [: #@~."1 |:)"2 +getSets=: ([: (] #~ isSet) ] {~ 3 comb #) +countSets=: #@:getSets + +set_puzzle=: verb define + target=. <. -: y + whilst. target ~: countSets Hand do. + Hand=. y drawRandom Deck + end. + echo 'Dealt ',(": y),' Cards:' + echo sayCards Hand + echo 'Found ',(":target),' Sets:' + echo sayCards getSets Hand +) diff --git a/Task/Set-puzzle/J/set-puzzle-2.j b/Task/Set-puzzle/J/set-puzzle-2.j new file mode 100644 index 0000000000..080de3666c --- /dev/null +++ b/Task/Set-puzzle/J/set-puzzle-2.j @@ -0,0 +1,27 @@ + set_puzzle 9 +Dealt 9 Cards: +three, purple, open, oval +three, green, open, diamond +three, red, solid, squiggle +three, green, solid, oval +three, purple, striped, oval +three, red, open, oval +one, red, solid, oval +one, green, open, squiggle +two, purple, striped, squiggle +Found 4 Sets: +three, green, open, diamond +three, red, solid, squiggle +three, purple, striped, oval + +three, green, open, diamond +one, red, solid, oval +two, purple, striped, squiggle + +three, red, solid, squiggle +one, green, open, squiggle +two, purple, striped, squiggle + +three, green, solid, oval +three, purple, striped, oval +three, red, open, oval diff --git a/Task/Set-puzzle/Java/set-puzzle.java b/Task/Set-puzzle/Java/set-puzzle.java new file mode 100644 index 0000000000..7d8742b42d --- /dev/null +++ b/Task/Set-puzzle/Java/set-puzzle.java @@ -0,0 +1,126 @@ +import java.util.*; +import org.apache.commons.lang3.ArrayUtils; + +public class SetPuzzle { + + enum Color { + GREEN(0), PURPLE(1), RED(2); + + private Color(int v) { + val = v; + } + public final int val; + } + + enum Number { + ONE(0), TWO(1), THREE(2); + + private Number(int v) { + val = v; + } + public final int val; + } + + enum Symbol { + OVAL(0), DIAMOND(1), SQUIGGLE(2); + + private Symbol(int v) { + val = v; + } + public final int val; + } + + enum Fill { + OPEN(0), STRIPED(1), SOLID(2); + + private Fill(int v) { + val = v; + } + public final int val; + } + + private static class Card implements Comparable { + Color c; + Number n; + Symbol s; + Fill f; + + public String toString() { + return String.format("[Card: %s, %s, %s, %s]", c, n, s, f); + } + + public int compareTo(Card o) { + return (c.val - o.c.val) * 10 + (n.val - o.n.val); + } + } + + private static Card[] deck; + + public static void main(String[] args) { + deck = new Card[81]; + Color[] colors = Color.values(); + Number[] numbers = Number.values(); + Symbol[] symbols = Symbol.values(); + Fill[] fillmodes = Fill.values(); + for (int i = 0; i < deck.length; i++) { + deck[i] = new Card(); + deck[i].c = colors[i / 27]; + deck[i].n = numbers[(i / 9) % 3]; + deck[i].s = symbols[(i / 3) % 3]; + deck[i].f = fillmodes[i % 3]; + } + findSets(12); + } + + private static void findSets(int numCards) { + int target = numCards / 2; + Card[] cards; + Card[][] sets = new Card[target][3]; + int cnt; + do { + Collections.shuffle(Arrays.asList(deck)); + cards = ArrayUtils.subarray(deck, 0, numCards); + cnt = 0; + + outer: + for (int i = 0; i < cards.length - 2; i++) { + for (int j = i + 1; j < cards.length - 1; j++) { + for (int k = j + 1; k < cards.length; k++) { + if (validSet(cards[i], cards[j], cards[k])) { + if (cnt < target) + sets[cnt] = new Card[]{cards[i], cards[j], cards[k]}; + if (++cnt > target) { + break outer; + } + } + } + } + } + } while (cnt != target); + + Arrays.sort(cards); + + System.out.printf("GIVEN %d CARDS:\n\n", numCards); + for (Card c : cards) { + System.out.println(c); + } + System.out.println(); + + System.out.println("FOUND " + target + " SETS:\n"); + for (Card[] set : sets) { + for (Card c : set) { + System.out.println(c); + } + System.out.println(); + } + } + + private static boolean validSet(Card c1, Card c2, Card c3) { + int tot = 0; + tot += (c1.c.val + c2.c.val + c3.c.val) % 3; + tot += (c1.n.val + c2.n.val + c3.n.val) % 3; + tot += (c1.s.val + c2.s.val + c3.s.val) % 3; + tot += (c1.f.val + c2.f.val + c3.f.val) % 3; + return tot == 0; + } +} diff --git a/Task/Set-puzzle/Perl-6/set-puzzle.pl6 b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 new file mode 100644 index 0000000000..85bf2ea774 --- /dev/null +++ b/Task/Set-puzzle/Perl-6/set-puzzle.pl6 @@ -0,0 +1,26 @@ +enum Color (red => 0o1000, green => 0o2000, purple => 0o4000); +enum Count (one => 0o100, two => 0o200, three => 0o400); +enum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40); +enum Style (solid => 0o1, open => 0o2, striped => 0o4); + +my @deck := (Color.enums X Count.enums X Shape.enums X Style.enums).tree; + +sub MAIN($DRAW = 9, $GOAL = $DRAW div 2) { + my @combinations = combine(3, [^$DRAW]); + my @draw; + repeat until (my @sets) == $GOAL { + @draw = @deck.pick($DRAW); + my @bits = @draw.map: { [+] @^enums».value } + @sets = gather for @combinations -> @c { + take @draw[@c].item when /^ <[1247]>+ $/ given ( [+|] @bits[@c] ).base(8); + } + } + say "Drew $DRAW cards:"; + show-cards @draw; + for @sets.kv -> $i, @cards { + say "\nSet {$i+1}:"; + show-cards @cards; + } +} + +sub show-cards(@c) { for @c -> $c { printf " %-6s %-5s %-8s %s\n", $c».key } } diff --git a/Task/Set-puzzle/Python/set-puzzle.py b/Task/Set-puzzle/Python/set-puzzle.py new file mode 100644 index 0000000000..1cade56f39 --- /dev/null +++ b/Task/Set-puzzle/Python/set-puzzle.py @@ -0,0 +1,46 @@ +#!/usr/bin/python + +from itertools import product, combinations +from random import sample + +## Major constants +features = [ 'green purple red'.split(), + 'one two three'.split(), + 'oval diamond squiggle'.split(), + 'open striped solid'.split() ] + +deck = list(product(list(range(3)), repeat=4)) + +dealt = 9 + +## Functions +def printcard(card): + print(' '.join('%8s' % f[i] for f,i in zip(features, card))) + +def getdeal(dealt=dealt): + deal = sample(deck, dealt) + return deal + +def getsets(deal): + good_feature_count = set([1, 3]) + sets = [ comb for comb in combinations(deal, 3) + if all( [(len(set(feature)) in good_feature_count) + for feature in zip(*comb)] + ) ] + return sets + +def printit(deal, sets): + print('Dealt %i cards:' % len(deal)) + for card in deal: printcard(card) + print('\nFound %i sets:' % len(sets)) + for s in sets: + for card in s: printcard(card) + print('') + +if __name__ == '__main__': + while True: + deal = getdeal() + sets = getsets(deal) + if len(sets) == dealt / 2: + break + printit(deal, sets) diff --git a/Task/Set-puzzle/Tcl/set-puzzle-1.tcl b/Task/Set-puzzle/Tcl/set-puzzle-1.tcl new file mode 100644 index 0000000000..4d0c56b442 --- /dev/null +++ b/Task/Set-puzzle/Tcl/set-puzzle-1.tcl @@ -0,0 +1,82 @@ +# Generate random integer uniformly on range [0..$n-1] +proc random n {expr {int(rand() * $n)}} + +# Generate a shuffled deck of all cards; the card encoding was stolen from the +# Perl6 solution. This is done once and then used as a constant. Note that the +# rest of the code assumes that all cards in the deck are unique. +set ::AllCards [apply {{} { + set cards {} + foreach color {1 2 4} { + foreach symbol {1 2 4} { + foreach number {1 2 4} { + foreach shading {1 2 4} { + lappend cards [list $color $symbol $number $shading] + } + } + } + } + # Knuth-Morris-Pratt shuffle (not that it matters) + for {set i [llength $cards]} {$i > 0} {} { + set j [random $i] + set tmp [lindex $cards [incr i -1]] + lset cards $i [lindex $cards $j] + lset cards $j $tmp + } + return $cards +}}] + +# Randomly pick a hand of cards from the deck (itself in a global for +# convenience). +proc drawCards n { + set cards $::AllCards; # Copies... + for {set i 0} {$i < $n} {incr i} { + set idx [random [llength $cards]] + lappend hand [lindex $cards $idx] + set cards [lreplace $cards $idx $idx] + } + return $hand +} + +# Test if a particular group of three cards is a valid set +proc isValidSet {a b c} { + expr { + ([lindex $a 0]|[lindex $b 0]|[lindex $c 0]) in {1 2 4 7} && + ([lindex $a 1]|[lindex $b 1]|[lindex $c 1]) in {1 2 4 7} && + ([lindex $a 2]|[lindex $b 2]|[lindex $c 2]) in {1 2 4 7} && + ([lindex $a 3]|[lindex $b 3]|[lindex $c 3]) in {1 2 4 7} + } +} + +# Get all unique valid sets of three cards in a hand. +proc allValidSets {hand} { + set sets {} + for {set i 0} {$i < [llength $hand]} {incr i} { + set a [lindex $hand $i] + set hand [set cards2 [lreplace $hand $i $i]] + for {set j 0} {$j < [llength $cards2]} {incr j} { + set b [lindex $cards2 $j] + set cards2 [set cards3 [lreplace $cards2 $j $j]] + foreach c $cards3 { + if {[isValidSet $a $b $c]} { + lappend sets [list $a $b $c] + } + } + } + } + return $sets +} + +# Solve a particular version of the set puzzle, by picking random hands until +# one is found that satisfies the constraints. This is usually much faster +# than a systematic search. On success, returns the hand found and the card +# sets within that hand. +proc SetPuzzle {numCards numSets} { + while 1 { + set hand [drawCards $numCards] + set sets [allValidSets $hand] + if {[llength $sets] == $numSets} { + break + } + } + return [list $hand $sets] +} diff --git a/Task/Set-puzzle/Tcl/set-puzzle-2.tcl b/Task/Set-puzzle/Tcl/set-puzzle-2.tcl new file mode 100644 index 0000000000..c44e16118d --- /dev/null +++ b/Task/Set-puzzle/Tcl/set-puzzle-2.tcl @@ -0,0 +1,29 @@ +# Render a hand (or any list) of cards (the "."s are just placeholders). +proc PrettyHand {hand {separator \n}} { + set Co {. red green . purple} + set Sy {. oval squiggle . diamond} + set Nu {. one two . three} + set Sh {. solid open . striped} + foreach card $hand { + lassign $card co s n sh + lappend result [format "(%s,%s,%s,%s)" \ + [lindex $Co $co] [lindex $Sy $s] [lindex $Nu $n] [lindex $Sh $sh]] + } + return $separator[join $result $separator] +} + +# Render the output of the Set Puzzle solver. +proc PrettyOutput {setResult} { + lassign $setResult hand sets + set sep "\n " + puts "Hand (with [llength $hand] cards) was:[PrettyHand $hand $sep]" + foreach s $sets { + puts "Found set [incr n]:[PrettyHand $s $sep]" + } +} + +# Demonstrate on the two cases +puts "=== BASIC PUZZLE =========" +PrettyOutput [SetPuzzle 9 4] +puts "=== ADVANCED PUZZLE ======" +PrettyOutput [SetPuzzle 12 6] diff --git a/Task/Seven-sided-dice-from-five-sided-dice/0DESCRIPTION b/Task/Seven-sided-dice-from-five-sided-dice/0DESCRIPTION new file mode 100644 index 0000000000..7a4b8bb037 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/0DESCRIPTION @@ -0,0 +1,11 @@ +Given an equal-probability generator of one of the integers 1 to 5 +as dice5; create dice7 that generates a pseudo-random integer from +1 to 7 in equal probability using only dice5 as a source of random +numbers, and check the distribution for at least 1000000 calls using the function created in [[Simple Random Distribution Checker]]. + +'''Implementation suggestion:''' +dice7 might call dice5 twice, re-call if four of the 25 +combinations are given, otherwise split the other 21 combinations +into 7 groups of three, and return the group index from the rolls. + +(Task adapted from an answer [http://stackoverflow.com/questions/90715/what-are-the-best-programming-puzzles-you-came-across here]) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/1META.yaml b/Task/Seven-sided-dice-from-five-sided-dice/1META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Seven-sided-dice-from-five-sided-dice/ALGOL-68/seven-sided-dice-from-five-sided-dice.alg b/Task/Seven-sided-dice-from-five-sided-dice/ALGOL-68/seven-sided-dice-from-five-sided-dice.alg new file mode 100644 index 0000000000..b8490234c6 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/ALGOL-68/seven-sided-dice-from-five-sided-dice.alg @@ -0,0 +1,35 @@ +PROC dice5 = INT: + 1 + ENTIER (5*random); + +PROC mulby5 = (INT n)INT: + ABS (BIN n SHL 2) + n; + +PROC dice7 = INT: ( + INT d55 := 0; + INT m := 1; + WHILE + m := ABS ((2r1 AND BIN m) SHL 2) + ABS (BIN m SHR 1); # repeats 4 - 2 - 1 # + d55 := mulby5(mulby5(d55)) + mulby5(dice5) + dice5 - 6; +# WHILE # d55 < m DO SKIP OD; + + m := 1; + WHILE d55>0 DO + d55 +:= m; + m := ABS (BIN d55 AND 2r111); # modulas by 8 # + d55 := ABS (BIN d55 SHR 3) # divide by 8 # + OD; + m +); + +PROC distcheck = (PROC INT dice, INT count, upb)VOID: ( + [upb]INT sum; FOR i TO UPB sum DO sum[i] := 0 OD; + FOR i TO count DO sum[dice]+:=1 OD; + FOR i TO UPB sum WHILE print(whole(sum[i],0)); i /= UPB sum DO print(", ") OD; + print(new line) +); + +main: +( + distcheck(dice5, 1000000, 5); + distcheck(dice7, 1000000, 7) +) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-1.ada b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-1.ada new file mode 100644 index 0000000000..9cd42ceca5 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-1.ada @@ -0,0 +1,10 @@ +package Random_57 is + + type Mod_7 is mod 7; + + function Random7 return Mod_7; + -- a "fast" implementation, minimazing the calls to the Random5 generator + function Simple_Random7 return Mod_7; + -- a simple implementation + +end Random_57; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-2.ada b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-2.ada new file mode 100644 index 0000000000..7e7e881613 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-2.ada @@ -0,0 +1,57 @@ + with Ada.Numerics.Discrete_Random; + +package body Random_57 is + type M5 is mod 5; + + package Rand_5 is new Ada.Numerics.Discrete_Random(M5); + Gen: Rand_5.Generator; + function Random7 return Mod_7 is + N: Natural; + + begin + loop + N := Integer(Rand_5.Random(Gen))* 5 + Integer(Rand_5.Random(Gen)); + -- N is uniformly distributed in 0 .. 24 + if N < 21 then + return Mod_7(N/3); + else -- (N-21) is in 0 .. 3 + N := (N-21) * 5 + Integer(Rand_5.Random(Gen)); -- N is in 0 .. 19 + if N < 14 then + return Mod_7(N / 2); + else -- (N-14) is in 0 .. 5 + N := (N-14) * 5 + Integer(Rand_5.Random(Gen)); -- N is in 0 .. 29 + if N < 28 then + return Mod_7(N/4); + else -- (N-28) is in 0 .. 1 + N := (N-28) * 5 + Integer(Rand_5.Random(Gen)); -- 0 .. 9 + if N < 7 then + return Mod_7(N); + else -- (N-7) is in 0, 1, 2 + N := (N-7)* 5 + Integer(Rand_5.Random(Gen)); -- 0 .. 14 + if N < 14 then + return Mod_7(N/2); + else -- (N-14) is 0. This is not useful for us! + null; + end if; + end if; + end if; + end if; + end if; + end loop; + + end Random7; + + function Simple_Random7 return Mod_7 is + N: Natural := + Integer(Rand_5.Random(Gen))* 5 + Integer(Rand_5.Random(Gen)); + -- N is uniformly distributed in 0 .. 24 + begin + while N > 20 loop + N := Integer(Rand_5.Random(Gen))* 5 + Integer(Rand_5.Random(Gen)); + end loop; -- Now I <= 20 + return Mod_7(N / 3); + end Simple_Random7; + +begin + Rand_5.Reset(Gen); +end Random_57; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-3.ada b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-3.ada new file mode 100644 index 0000000000..0d15b8dbae --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-3.ada @@ -0,0 +1,51 @@ +with Ada.Text_IO, Random_57; + +procedure R57 is + + use Random_57; + + type Fun is access function return Mod_7; + + function Rand return Mod_7 renames Random_57.Random7; + -- change this to "... renames Random_57.Simple_Random;" if you like + + procedure Test(Sample_Size: Positive; Rand: Fun; Precision: Float := 0.3) is + + Counter: array(Mod_7) of Natural := (others => 0); + Expected: Natural := Sample_Size/7; + Small: Mod_7 := Mod_7'First; + Large: Mod_7 := Mod_7'First; + + Result: Mod_7; + begin + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line("Sample Size: " & Integer'Image(Sample_Size)); + Ada.Text_IO.Put( " Bins:"); + for I in 1 .. Sample_Size loop + Result := Rand.all; + Counter(Result) := Counter(Result) + 1; + end loop; + for J in Mod_7 loop + Ada.Text_IO.Put(Integer'Image(Counter(J))); + if Counter(J) < Counter(Small) then Small := J; end if; + if Counter(J) > Counter(Large) then Large := J; end if; + end loop; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line(" Small Bin:" & Integer'Image(Counter(Small))); + Ada.Text_IO.Put_Line(" Large Bin: " & Integer'Image(Counter(Large))); + + if Float(Counter(Small)*7) * (1.0+Precision) < Float(Sample_Size) then + Ada.Text_IO.Put_Line("Failed! Small too small!"); + elsif Float(Counter(Large)*7) * (1.0-Precision) > Float(Sample_Size) then + Ada.Text_IO.Put_Line("Failed! Large too large!"); + else + Ada.Text_IO.Put_Line("Passed"); + end if; + end Test; + +begin + Test( 10_000, Rand'Access, 0.08); + Test( 100_000, Rand'Access, 0.04); + Test( 1_000_000, Rand'Access, 0.02); + Test(10_000_000, Rand'Access, 0.01); +end R57; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/AutoHotkey/seven-sided-dice-from-five-sided-dice.ahk b/Task/Seven-sided-dice-from-five-sided-dice/AutoHotkey/seven-sided-dice-from-five-sided-dice.ahk new file mode 100644 index 0000000000..9cf348068c --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/AutoHotkey/seven-sided-dice-from-five-sided-dice.ahk @@ -0,0 +1,11 @@ +dice5() +{ Random, v, 1, 5 + Return, v +} + +dice7() +{ Loop + { v := 5 * dice5() + dice5() - 6 + IfLess v, 21, Return, (v // 3) + 1 + } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/BBC-BASIC/seven-sided-dice-from-five-sided-dice.bbc b/Task/Seven-sided-dice-from-five-sided-dice/BBC-BASIC/seven-sided-dice-from-five-sided-dice.bbc new file mode 100644 index 0000000000..c6a12d561f --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/BBC-BASIC/seven-sided-dice-from-five-sided-dice.bbc @@ -0,0 +1,31 @@ + MAXRND = 7 + FOR r% = 2 TO 5 + check% = FNdistcheck(FNdice7, 10^r%, 0.1) + PRINT "Over "; 10^r% " runs dice7 "; + IF check% THEN + PRINT "failed distribution check with "; check% " bin(s) out of range" + ELSE + PRINT "passed distribution check" + ENDIF + NEXT + END + + DEF FNdice7 + LOCAL x% : x% = FNdice5 + 5*FNdice5 + IF x%>26 THEN = FNdice7 ELSE = (x%+1) MOD 7 + 1 + + DEF FNdice5 = RND(5) + + DEF FNdistcheck(RETURN func%, repet%, delta) + LOCAL i%, m%, r%, s%, bins%() + DIM bins%(MAXRND) + FOR i% = 1 TO repet% + r% = FN(^func%) + bins%(r%) += 1 + IF r%>m% m% = r% + NEXT + FOR i% = 1 TO m% + IF bins%(i%)/(repet%/m%) > 1+delta s% += 1 + IF bins%(i%)/(repet%/m%) < 1-delta s% += 1 + NEXT + = s% diff --git a/Task/Seven-sided-dice-from-five-sided-dice/C++/seven-sided-dice-from-five-sided-dice.cpp b/Task/Seven-sided-dice-from-five-sided-dice/C++/seven-sided-dice-from-five-sided-dice.cpp new file mode 100644 index 0000000000..d91289dca9 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/C++/seven-sided-dice-from-five-sided-dice.cpp @@ -0,0 +1,49 @@ +template class fivetoseven +{ +public: + fivetoseven(F f): d5(f), rem(0), max(1) {} + int operator()(); +private: + F d5; + int rem, max; +}; + +template + int fivetoseven::operator()() +{ + while (rem/7 == max/7) + { + while (max < 7) + { + int rand5 = d5()-1; + max *= 5; + rem = 5*rem + rand5; + } + + int groups = max / 7; + if (rem >= 7*groups) + { + rem -= 7*groups; + max -= 7*groups; + } + } + + int result = rem % 7; + rem /= 7; + max /= 7; + return result+1; +} + +int d5() +{ + return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; +} + +fivetoseven d7(d5); + +int main() +{ + srand(time(0)); + test_distribution(d5, 1000000, 0.001); + test_distribution(d7, 1000000, 0.001); +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/C/seven-sided-dice-from-five-sided-dice.c b/Task/Seven-sided-dice-from-five-sided-dice/C/seven-sided-dice-from-five-sided-dice.c new file mode 100644 index 0000000000..46342e7c67 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/C/seven-sided-dice-from-five-sided-dice.c @@ -0,0 +1,20 @@ +int rand5() +{ + int r, rand_max = RAND_MAX - (RAND_MAX % 5); + while ((r = rand()) >= rand_max); + return r / (rand_max / 5) + 1; +} + +int rand5_7() +{ + int r; + while ((r = rand5() * 5 + rand5()) >= 27); + return r / 3 - 1; +} + +int main() +{ + printf(check(rand5, 5, 1000000, .05) ? "flat\n" : "not flat\n"); + printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n"); + return 0; +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Clojure/seven-sided-dice-from-five-sided-dice.clj b/Task/Seven-sided-dice-from-five-sided-dice/Clojure/seven-sided-dice-from-five-sided-dice.clj new file mode 100644 index 0000000000..09f5e39ba9 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Clojure/seven-sided-dice-from-five-sided-dice.clj @@ -0,0 +1,15 @@ +(def dice5 #(rand-int 5)) + +(defn dice7 [] + (quot (->> dice5 ; do the following to dice5 + (repeatedly 2) ; call it twice + (apply #(+ %1 (* 5 %2))) ; d1 + 5*d2 => 0..24 + #() ; wrap that up in a function + repeatedly ; make infinite sequence of the above + (drop-while #(> % 20)) ; throw away anything > 20 + first) ; grab first acceptable element + 3)) ; divide by three rounding down + +(doseq [n [100 1000 10000] [num count okay?] (verify dice7 n)] + (println "Saw" num count "times:" + (if okay? "that's" " not") "acceptable")) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Common-Lisp/seven-sided-dice-from-five-sided-dice.lisp b/Task/Seven-sided-dice-from-five-sided-dice/Common-Lisp/seven-sided-dice-from-five-sided-dice.lisp new file mode 100644 index 0000000000..099dfa0d7d --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Common-Lisp/seven-sided-dice-from-five-sided-dice.lisp @@ -0,0 +1,7 @@ +(defun d5 () + (1+ (random 5))) + +(defun d7 () + (loop for d55 = (+ (* 5 (d5)) (d5) -6) + until (< d55 21) + finally (return (1+ (mod d55 7))))) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d b/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d new file mode 100644 index 0000000000..3e5742a3eb --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d @@ -0,0 +1,47 @@ +import std.random; +import verify_distribution_uniformity_naive: distCheck; + +/// Generates a random number in [1, 5]. +int dice5() /*pure nothrow*/ { + return uniform(1, 6); +} + +/// Naive, generates a random number in [1, 7] using dice5. +int fiveToSevenNaive() /*pure nothrow*/ { + immutable int r = dice5() + dice5() * 5 - 6; + return (r < 21) ? (r % 7) + 1 : fiveToSevenNaive(); +} + +/** +Generates a random number in [1, 7] using dice5, +minimizing calls to dice5. +*/ +int fiveToSevenSmart() { + static int rem = 0, max = 1; + + while (rem / 7 == max / 7) { + while (max < 7) { + immutable int rand5 = dice5() - 1; + max *= 5; + rem = 5 * rem + rand5; + } + + immutable int groups = max / 7; + if (rem >= 7 * groups) { + rem -= 7 * groups; + max -= 7 * groups; + } + } + + immutable int result = rem % 7; + rem /= 7; + max /= 7; + return result + 1; +} + +void main() { + enum int N = 400_000; + distCheck(&dice5, N, 1); + distCheck(&fiveToSevenNaive, N, 1); + distCheck(&fiveToSevenSmart, N, 1); +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-1.e b/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-1.e new file mode 100644 index 0000000000..1e1c141ce8 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-1.e @@ -0,0 +1,9 @@ +def dice5() { + return entropy.nextInt(5) + 1 +} + +def dice7() { + var d55 := null + while ((d55 := 5 * dice5() + dice5() - 6) >= 21) {} + return d55 %% 7 + 1 +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-2.e b/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-2.e new file mode 100644 index 0000000000..3d396f0320 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/E/seven-sided-dice-from-five-sided-dice-2.e @@ -0,0 +1,5 @@ +def bins := ([0] * 7).diverge() +for x in 1..1000 { + bins[dice7() - 1] += 1 +} +println(bins.snapshot()) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Fortran/seven-sided-dice-from-five-sided-dice.f b/Task/Seven-sided-dice-from-five-sided-dice/Fortran/seven-sided-dice-from-five-sided-dice.f new file mode 100644 index 0000000000..14bf23f7c6 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Fortran/seven-sided-dice-from-five-sided-dice.f @@ -0,0 +1,37 @@ +module rand_mod + implicit none + +contains + +function rand5() + integer :: rand5 + real :: r + + call random_number(r) + rand5 = 5*r + 1 +end function + +function rand7() + integer :: rand7 + + do + rand7 = 5*rand5() + rand5() - 6 + if (rand7 < 21) then + rand7 = rand7 / 3 + 1 + return + end if + end do +end function +end module + +program Randtest + use rand_mod + implicit none + + integer, parameter :: samples = 1000000 + + call distcheck(rand7, samples, 0.005) + write(*,*) + call distcheck(rand7, samples, 0.001) + +end program diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Go/seven-sided-dice-from-five-sided-dice.go b/Task/Seven-sided-dice-from-five-sided-dice/Go/seven-sided-dice-from-five-sided-dice.go new file mode 100644 index 0000000000..99be996c41 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Go/seven-sided-dice-from-five-sided-dice.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "time" +) + +// "given" +func dice5() int { + return rand.Intn(5) + 1 +} + +// function specified by task "Seven-sided dice from five-sided dice" +func dice7() (i int) { + for { + i = 5*dice5() + dice5() + if i < 27 { + break + } + } + return (i / 3) - 1 +} + +// function specified by task "Verify distribution uniformity/Naive" +// +// Parameter "f" is expected to return a random integer in the range 1..n. +// (Values out of range will cause an unceremonious crash.) +// "Max" is returned as an "indication of distribution achieved." +// It is the maximum delta observed from the count representing a perfectly +// uniform distribution. +// Also returned is a boolean, true if "max" is less than threshold +// parameter "delta." +func distCheck(f func() int, n int, + repeats int, delta float64) (max float64, flatEnough bool) { + count := make([]int, n) + for i := 0; i < repeats; i++ { + count[f()-1]++ + } + expected := float64(repeats) / float64(n) + for _, c := range count { + max = math.Max(max, math.Abs(float64(c)-expected)) + } + return max, max < delta +} + +// Driver, produces output satisfying both tasks. +func main() { + rand.Seed(time.Now().UnixNano()) + const calls = 1000000 + max, flatEnough := distCheck(dice7, 7, calls, 500) + fmt.Println("Max delta:", max, "Flat enough:", flatEnough) + max, flatEnough = distCheck(dice7, 7, calls, 500) + fmt.Println("Max delta:", max, "Flat enough:", flatEnough) +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-1.groovy b/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-1.groovy new file mode 100644 index 0000000000..56550e9dce --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-1.groovy @@ -0,0 +1,13 @@ +random = new Random() + +int rand5() { + random.nextInt(5) + 1 +} + +int rand7From5() { + def raw = 25 + while (raw > 21) { + raw = 5*(rand5() - 1) + rand5() + } + (raw % 7) + 1 +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-2.groovy b/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-2.groovy new file mode 100644 index 0000000000..862b3f2d62 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Groovy/seven-sided-dice-from-five-sided-dice-2.groovy @@ -0,0 +1,26 @@ +def test = { + (1..6). each { + def counts = [0g, 0g, 0g, 0g, 0g, 0g, 0g] + def target = 10g**it + def popSize = 7*target + (0..<(popSize)).each { + def i = rand7From5() - 1 + counts[i] = counts[i] + 1g + } + BigDecimal stdDev = (counts.collect { it - target}.collect { it * it }.sum() / popSize) ** 0.5g + def countMap = (0.. map + [(index+1):counts[index]] } + + println """\ + counts: ${countMap} +population size: ${popSize} + std dev: ${stdDev.round(new java.math.MathContext(3))} +""" + } +} + +4.times { + println """ +TRIAL #${it+1} +==============""" + test(it) +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-1.hs b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-1.hs new file mode 100644 index 0000000000..9574c22a0a --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-1.hs @@ -0,0 +1,9 @@ +import System.Random +import Data.List + +sevenFrom5Dice = do + d51 <- randomRIO(1,5) :: IO Int + d52 <- randomRIO(1,5) :: IO Int + let d7 = 5*d51+d52-6 + if d7 > 20 then sevenFrom5Dice + else return $ 1 + d7 `mod` 7 diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-2.hs b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-2.hs new file mode 100644 index 0000000000..734d2f0d02 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-2.hs @@ -0,0 +1,2 @@ +*Main> replicateM 10 sevenFrom5Dice +[2,3,1,1,6,2,5,6,5,3] diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-3.hs b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-3.hs new file mode 100644 index 0000000000..7310ddbf42 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Haskell/seven-sided-dice-from-five-sided-dice-3.hs @@ -0,0 +1,8 @@ +*Main> mapM_ print .sort =<< distribCheck sevenFrom5Dice 1000000 3 +(1,(142759,True)) +(2,(143078,True)) +(3,(142706,True)) +(4,(142403,True)) +(5,(142896,True)) +(6,(143028,True)) +(7,(143130,True)) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Icon/seven-sided-dice-from-five-sided-dice.icon b/Task/Seven-sided-dice-from-five-sided-dice/Icon/seven-sided-dice-from-five-sided-dice.icon new file mode 100644 index 0000000000..e01bc02726 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Icon/seven-sided-dice-from-five-sided-dice.icon @@ -0,0 +1,15 @@ +$include "distribution-checker.icn" + +# return a uniformly distributed number from 1 to 7, +# but only using a random number in range 1 to 5. +procedure die_7 () + while rnd := 5*?5 + ?5 - 6 do { + if rnd < 21 then suspend rnd % 7 + 1 + } +end + +procedure main () + if verify_uniform (create (|die_7()), 1000000, 0.01) + then write ("uniform") + else write ("skewed") +end diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-1.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-1.j new file mode 100644 index 0000000000..a6534f1466 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-1.j @@ -0,0 +1,7 @@ +rollD5=: [: >: ] ?@$ 5: NB. makes a y shape array of 5s, "rolls" the array and increments. +roll2xD5=: [: rollD5 2 ,~ */ NB. rolls D5 twice for each desired D7 roll (y rows, 2 cols) +toBase10=: 5 #. <: NB. decrements and converts rows from base 5 to 10 +keepGood=: #~ 21&> NB. compress out values not less than 21 +groupin3s=: [: >. >: % 3: NB. increments, divides by 3 and takes ceiling + +getD7=: groupin3s@keepGood@toBase10@roll2xD5 diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-2.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-2.j new file mode 100644 index 0000000000..b824464383 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-2.j @@ -0,0 +1,2 @@ +getD7b=: 0 8 -.~ 3 >.@%~ 5 #. [: <:@rollD5 2 ,~ ] +getD7c=: [: (#~ 7&>:) 3 >.@%~ [: 5&#.&.:<:@rollD5 ] , 2: diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j new file mode 100644 index 0000000000..39141ac0ab --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j @@ -0,0 +1,8 @@ +rollD7x=: monad define + n=. */y NB. product of vector y is total number of D7 rolls required + rolls=. '' NB. initialize empty noun rolls + while. n > #res do. NB. checks if if enough D7 rolls accumulated + rolls=. rolls, getD7 >. 0.75 * n NB. calcs 3/4 of required rolls and accumulates getD7 rolls + end. + y $ rolls NB. shape the result according to the vector y +) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-4.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-4.j new file mode 100644 index 0000000000..b859b595de --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-4.j @@ -0,0 +1,5 @@ +getNumRolls=: [: >. 0.75 * */@[ NB. calc approx 3/4 of the required rolls +accumD7Rolls=: ] , getD7@getNumRolls NB. accumulates getD7 rolls +isNotEnough=: */@[ > #@] NB. checks if enough D7 rolls accumulated + +rollD7t=: ] $ (accumD7Rolls ^: isNotEnough ^:_)&'' diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-5.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-5.j new file mode 100644 index 0000000000..2942b35804 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-5.j @@ -0,0 +1,19 @@ + rollD7t 10 NB. 10 rolls of D7 +6 4 5 1 4 2 4 5 2 5 + rollD7t 2 5 NB. 2 by 5 array of D7 rolls +5 1 5 1 3 +3 4 3 5 6 + rollD7t 2 3 5 NB. 2 by 3 by 5 array of D7 rolls +4 7 7 5 7 +3 7 1 4 5 +5 4 5 7 6 + +1 1 7 6 3 +4 4 1 4 4 +1 1 1 6 5 + +NB. check results from rollD7x and rollD7t have same shape + ($@rollD7x -: $@rollD7t) 10 +1 + ($@rollD7x -: $@rollD7t) 2 3 5 +1 diff --git a/Task/Seven-sided-dice-from-five-sided-dice/JavaScript/seven-sided-dice-from-five-sided-dice.js b/Task/Seven-sided-dice-from-five-sided-dice/JavaScript/seven-sided-dice-from-five-sided-dice.js new file mode 100644 index 0000000000..ee245abb6a --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/JavaScript/seven-sided-dice-from-five-sided-dice.js @@ -0,0 +1,18 @@ +function dice5() +{ + return 1 + Math.floor(5 * Math.random()); +} + +function dice7() +{ + while (true) + { + var dice55 = 5 * dice5() + dice5() - 6; + if (dice55 < 21) + return dice55 % 7 + 1; + } +} + +distcheck(dice5, 1000000); +print(); +distcheck(dice7, 1000000); diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Lua/seven-sided-dice-from-five-sided-dice.lua b/Task/Seven-sided-dice-from-five-sided-dice/Lua/seven-sided-dice-from-five-sided-dice.lua new file mode 100644 index 0000000000..8a99339894 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Lua/seven-sided-dice-from-five-sided-dice.lua @@ -0,0 +1,7 @@ +dice5 = function() return math.random(5) end + +function dice7() + x = dice5() * 5 + dice5() - 6 + if x > 20 then return dice7() end + return x%7 + 1 +end diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Mathematica/seven-sided-dice-from-five-sided-dice.math b/Task/Seven-sided-dice-from-five-sided-dice/Mathematica/seven-sided-dice-from-five-sided-dice.math new file mode 100644 index 0000000000..3a7bc12995 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Mathematica/seven-sided-dice-from-five-sided-dice.math @@ -0,0 +1,2 @@ +sevenFrom5Dice := (tmp$ = 5*RandomInteger[{1, 5}] + RandomInteger[{1, 5}] - 6; + If [tmp$ < 21, 1 + Mod[tmp$ , 7], sevenFrom5Dice]) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/OCaml/seven-sided-dice-from-five-sided-dice.ocaml b/Task/Seven-sided-dice-from-five-sided-dice/OCaml/seven-sided-dice-from-five-sided-dice.ocaml new file mode 100644 index 0000000000..7176b58890 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/OCaml/seven-sided-dice-from-five-sided-dice.ocaml @@ -0,0 +1,17 @@ +let dice5() = 1 + Random.int 5 ;; + +let dice7 = + let rolls2answer = Hashtbl.create 25 in + let n = ref 0 in + for roll1 = 1 to 5 do + for roll2 = 1 to 5 do + Hashtbl.add rolls2answer (roll1,roll2) (!n / 3 +1); + incr n + done; + done; + let rec aux() = + let trial = Hashtbl.find rolls2answer (dice5(),dice5()) in + if trial <= 7 then trial else aux() + in + aux +;; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/PARI-GP/seven-sided-dice-from-five-sided-dice.pari b/Task/Seven-sided-dice-from-five-sided-dice/PARI-GP/seven-sided-dice-from-five-sided-dice.pari new file mode 100644 index 0000000000..3868c0ed45 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/PARI-GP/seven-sided-dice-from-five-sided-dice.pari @@ -0,0 +1,7 @@ +dice5()=random(5)+1; + +dice7()={ + my(t); + while((t=dice5()*5+dice5()) > 21,); + (t+2)\3 +}; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-1.pl6 b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-1.pl6 new file mode 100644 index 0000000000..e8f8b36926 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-1.pl6 @@ -0,0 +1,8 @@ +my $d5 = 1..5; +sub d5() { $d5.roll; } # 1d5 + +sub d7() { + my $flat = 21; + $flat = 5 * d5() - d5() until $flat < 21; + $flat % 7 + 1; +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-2.pl6 b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-2.pl6 new file mode 100644 index 0000000000..22d4029294 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice-2.pl6 @@ -0,0 +1,10 @@ +my @dist; +my $n = 1_000_000; +my $expect = $n / 7; + +loop ($_ = $n; $n; --$n) { @dist[d7()]++; } + +say "Expect\t",$expect.fmt("%.3f"); +for @dist.kv -> $i, $v { + say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v; +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/PicoLisp/seven-sided-dice-from-five-sided-dice.l b/Task/Seven-sided-dice-from-five-sided-dice/PicoLisp/seven-sided-dice-from-five-sided-dice.l new file mode 100644 index 0000000000..730633d92f --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/PicoLisp/seven-sided-dice-from-five-sided-dice.l @@ -0,0 +1,7 @@ +(de dice5 () + (rand 1 5) ) + +(de dice7 () + (use R + (until (> 21 (setq R (+ (* 5 (dice5)) (dice5) -6)))) + (inc (% R 7)) ) ) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/PureBasic/seven-sided-dice-from-five-sided-dice.purebasic b/Task/Seven-sided-dice-from-five-sided-dice/PureBasic/seven-sided-dice-from-five-sided-dice.purebasic new file mode 100644 index 0000000000..20b42e5150 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/PureBasic/seven-sided-dice-from-five-sided-dice.purebasic @@ -0,0 +1,14 @@ +Procedure dice5() + ProcedureReturn Random(4) + 1 +EndProcedure + +Procedure dice7() + Protected x + + x = dice5() * 5 + dice5() - 6 + If x > 20 + ProcedureReturn dice7() + EndIf + + ProcedureReturn x % 7 + 1 +EndProcedure diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Python/seven-sided-dice-from-five-sided-dice.py b/Task/Seven-sided-dice-from-five-sided-dice/Python/seven-sided-dice-from-five-sided-dice.py new file mode 100644 index 0000000000..e6a3aae49b --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Python/seven-sided-dice-from-five-sided-dice.py @@ -0,0 +1,8 @@ +from random import randint + +def dice5(): + return randint(1, 5) + +def dice7(): + r = dice5() + dice5() * 5 - 6 + return (r % 7) + 1 if r < 21 else dice7() diff --git a/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-1.r b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-1.r new file mode 100644 index 0000000000..1d1a3cc300 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-1.r @@ -0,0 +1 @@ +dice5 <- function(n=1) sample(5, n, replace=TRUE) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-2.r b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-2.r new file mode 100644 index 0000000000..df991f1b39 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-2.r @@ -0,0 +1,11 @@ +dice7.while <- function(n=1) +{ + score <- numeric() + while(length(score) < n) + { + total <- sum(c(5,1) * dice5(2)) - 3 + if(total < 24) score <- c(score, total %/% 3) + } + score +} +system.time(dice7.while(1e6)) # longer than 4 minutes diff --git a/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-3.r b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-3.r new file mode 100644 index 0000000000..9f53da7b98 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/R/seven-sided-dice-from-five-sided-dice-3.r @@ -0,0 +1,18 @@ +dice7.vec <- function(n=1, checkLength=TRUE) +{ + morethan2n <- 3 * n + 10 + (n %% 2) #need more than 2*n samples, because some are discarded + twoDfive <- matrix(dice5(morethan2n), nrow=2) + total <- colSums(c(5, 1) * twoDfive) - 3 + score <- ifelse(total < 24, total %/% 3, NA) + score <- score[!is.na(score)] + #If length is less than n (very unlikely), add some more samples + if(checkLength) + { + while(length(score) < n) + { + score <- c(score, dice7(n, FALSE)) + } + score[1:n] + } else score +} +system.time(dice7.vec(1e6)) # ~1 sec diff --git a/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx new file mode 100644 index 0000000000..26498a468a --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx @@ -0,0 +1,22 @@ +/*REXX program to simulate 7-sided die based on a 5-sided throw. */ +parse arg trials sample . /*get arguments from command line*/ +if trials=='' then trials=1 /*Not specified? Then use default*/ +if sample=='' then sample=1000000 /* " " " " " */ + + do t=1 for trials /*performe the number of trials. */ + die.=0; k=0 + do until k==sample; r=5*random(1,5)+random(1,5)-6 + if r>20 then iterate + k=k+1; r=r//7+1; die.r=die.r+1 + end /*until*/ + expect=sample%7 + say + say center('trial:'right(t,4) ' ' sample 'samples, expect='expect,79,'─') + say + + do j=1 for 7 + say ' side' j "had " die.j ' occurences', + ' difference from expected:'right(die.j-expect,length(sample)) + end /*j*/ + end /*t*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb b/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb new file mode 100644 index 0000000000..ebdb5bd664 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ruby/seven-sided-dice-from-five-sided-dice.rb @@ -0,0 +1,15 @@ +require './distcheck.rb' + +def d5 + 1 + rand(5) +end + +def d7 + loop do + d55 = 5*d5() + d5() - 6 + return (d55 % 7 + 1) if d55 < 21 + end +end + +distcheck(1_000_000) {d5} +distcheck(1_000_000) {d7} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Tcl/seven-sided-dice-from-five-sided-dice.tcl b/Task/Seven-sided-dice-from-five-sided-dice/Tcl/seven-sided-dice-from-five-sided-dice.tcl new file mode 100644 index 0000000000..9034727969 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Tcl/seven-sided-dice-from-five-sided-dice.tcl @@ -0,0 +1,10 @@ +proc D5 {} {expr {1 + int(5 * rand())}} + +proc D7 {} { + while 1 { + set d55 [expr {5 * [D5] + [D5] - 6}] + if {$d55 < 21} { + return [expr {$d55 % 7 + 1}] + } + } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/VBScript/seven-sided-dice-from-five-sided-dice.vbscript b/Task/Seven-sided-dice-from-five-sided-dice/VBScript/seven-sided-dice-from-five-sided-dice.vbscript new file mode 100644 index 0000000000..e56284e5d2 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/VBScript/seven-sided-dice-from-five-sided-dice.vbscript @@ -0,0 +1,13 @@ +Option Explicit + +function dice5 + dice5 = int(rnd*5) + 1 +end function + +function dice7 + dim j + do + j = 5 * dice5 + dice5 - 6 + loop until j < 21 + dice7 = j mod 7 + 1 +end function diff --git a/Task/Shell-one-liner/0DESCRIPTION b/Task/Shell-one-liner/0DESCRIPTION new file mode 100644 index 0000000000..9eccb028a6 --- /dev/null +++ b/Task/Shell-one-liner/0DESCRIPTION @@ -0,0 +1,3 @@ +Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. + +Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples. diff --git a/Task/Shell-one-liner/1META.yaml b/Task/Shell-one-liner/1META.yaml new file mode 100644 index 0000000000..f6d82c59ad --- /dev/null +++ b/Task/Shell-one-liner/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming environment operations diff --git a/Task/Shell-one-liner/ACL2/shell-one-liner.acl2 b/Task/Shell-one-liner/ACL2/shell-one-liner.acl2 new file mode 100644 index 0000000000..baf3bd0670 --- /dev/null +++ b/Task/Shell-one-liner/ACL2/shell-one-liner.acl2 @@ -0,0 +1 @@ +$ acl2 <<< '(cw "Hello.")' diff --git a/Task/Shell-one-liner/ALGOL-68/shell-one-liner-1.alg b/Task/Shell-one-liner/ALGOL-68/shell-one-liner-1.alg new file mode 100644 index 0000000000..e654367dd8 --- /dev/null +++ b/Task/Shell-one-liner/ALGOL-68/shell-one-liner-1.alg @@ -0,0 +1 @@ +$ a68g -e 'print(("Hello",new line))' diff --git a/Task/Shell-one-liner/ALGOL-68/shell-one-liner-2.alg b/Task/Shell-one-liner/ALGOL-68/shell-one-liner-2.alg new file mode 100644 index 0000000000..6bc5f62211 --- /dev/null +++ b/Task/Shell-one-liner/ALGOL-68/shell-one-liner-2.alg @@ -0,0 +1,6 @@ +code='print(("Hello", new line))' +a=/tmp/algol$$ s=/usr/share/algol68toc; +echo -e "PROGRAM algol$$ CONTEXT VOID\nUSE standard\nBEGIN\n$code\nEND\nFINISH\n" > $a.a68 && +a68toc -lib $s -dir $s -uname TMP -tmp $a.a68 && rm $a.a68 && +gcc $s/Afirst.o $a.c -l{a68s,a68,m,c} -o $a && rm $a.c && +$a; rm $a diff --git a/Task/Shell-one-liner/AWK/shell-one-liner-1.awk b/Task/Shell-one-liner/AWK/shell-one-liner-1.awk new file mode 100644 index 0000000000..66ff6112e9 --- /dev/null +++ b/Task/Shell-one-liner/AWK/shell-one-liner-1.awk @@ -0,0 +1 @@ +$ awk 'BEGIN { print "Hello"; }' diff --git a/Task/Shell-one-liner/AWK/shell-one-liner-2.awk b/Task/Shell-one-liner/AWK/shell-one-liner-2.awk new file mode 100644 index 0000000000..ee676d6640 --- /dev/null +++ b/Task/Shell-one-liner/AWK/shell-one-liner-2.awk @@ -0,0 +1 @@ +$ awk '/IN/ { print $2, $4; }' x.adb; gnatmake x; ./x; rm x.adb x.ali x.o x diff --git a/Task/Shell-one-liner/Aikido/shell-one-liner.aikido b/Task/Shell-one-liner/Aikido/shell-one-liner.aikido new file mode 100644 index 0000000000..0619342bcb --- /dev/null +++ b/Task/Shell-one-liner/Aikido/shell-one-liner.aikido @@ -0,0 +1 @@ +echo 'println ("Hello")' | aikido diff --git a/Task/Shell-one-liner/Aime/shell-one-liner.aime b/Task/Shell-one-liner/Aime/shell-one-liner.aime new file mode 100644 index 0000000000..e5d68ac45e --- /dev/null +++ b/Task/Shell-one-liner/Aime/shell-one-liner.aime @@ -0,0 +1 @@ +$ src/aime -c 'o_text("Hello, World!\n");' diff --git a/Task/Shell-one-liner/BASIC/shell-one-liner-1.basic b/Task/Shell-one-liner/BASIC/shell-one-liner-1.basic new file mode 100644 index 0000000000..dd3afc3512 --- /dev/null +++ b/Task/Shell-one-liner/BASIC/shell-one-liner-1.basic @@ -0,0 +1 @@ +echo 'print "foo"'|basic diff --git a/Task/Shell-one-liner/BASIC/shell-one-liner-2.basic b/Task/Shell-one-liner/BASIC/shell-one-liner-2.basic new file mode 100644 index 0000000000..247078fc61 --- /dev/null +++ b/Task/Shell-one-liner/BASIC/shell-one-liner-2.basic @@ -0,0 +1 @@ +echo print "foo"|basic diff --git a/Task/Shell-one-liner/BASIC/shell-one-liner-3.basic b/Task/Shell-one-liner/BASIC/shell-one-liner-3.basic new file mode 100644 index 0000000000..3a58a709ce --- /dev/null +++ b/Task/Shell-one-liner/BASIC/shell-one-liner-3.basic @@ -0,0 +1 @@ +PRINT "Hello World!" diff --git a/Task/Shell-one-liner/Burlesque/shell-one-liner.blq b/Task/Shell-one-liner/Burlesque/shell-one-liner.blq new file mode 100644 index 0000000000..60fe584628 --- /dev/null +++ b/Task/Shell-one-liner/Burlesque/shell-one-liner.blq @@ -0,0 +1 @@ +Burlesque.exe --no-stdin "5 5 .+" diff --git a/Task/Shell-one-liner/C/shell-one-liner.c b/Task/Shell-one-liner/C/shell-one-liner.c new file mode 100644 index 0000000000..61670c0305 --- /dev/null +++ b/Task/Shell-one-liner/C/shell-one-liner.c @@ -0,0 +1 @@ +$ echo 'main() {printf("Hello\n");}' | gcc -w -x c -; ./a.out diff --git a/Task/Shell-one-liner/CMake/shell-one-liner.cmake b/Task/Shell-one-liner/CMake/shell-one-liner.cmake new file mode 100644 index 0000000000..6a7ef2573b --- /dev/null +++ b/Task/Shell-one-liner/CMake/shell-one-liner.cmake @@ -0,0 +1 @@ +echo 'message(STATUS "Goodbye, World!")' | cmake -P /dev/stdin diff --git a/Task/Shell-one-liner/Clojure/shell-one-liner.clj b/Task/Shell-one-liner/Clojure/shell-one-liner.clj new file mode 100644 index 0000000000..320f823b27 --- /dev/null +++ b/Task/Shell-one-liner/Clojure/shell-one-liner.clj @@ -0,0 +1,3 @@ +$ clj-env-dir -e "(defn add2 [x] (inc (inc x))) (add2 40)" +#'user/add2 +42 diff --git a/Task/Shell-one-liner/Common-Lisp/shell-one-liner-1.lisp b/Task/Shell-one-liner/Common-Lisp/shell-one-liner-1.lisp new file mode 100644 index 0000000000..113aac52ef --- /dev/null +++ b/Task/Shell-one-liner/Common-Lisp/shell-one-liner-1.lisp @@ -0,0 +1 @@ +sbcl --noinform --eval '(progn (princ "Hello") (terpri) (quit))' diff --git a/Task/Shell-one-liner/Common-Lisp/shell-one-liner-2.lisp b/Task/Shell-one-liner/Common-Lisp/shell-one-liner-2.lisp new file mode 100644 index 0000000000..5351132254 --- /dev/null +++ b/Task/Shell-one-liner/Common-Lisp/shell-one-liner-2.lisp @@ -0,0 +1 @@ +clisp.exe -q -x "(progn (format t \"Hello from CLISP\") (quit))" diff --git a/Task/Shell-one-liner/D/shell-one-liner.d b/Task/Shell-one-liner/D/shell-one-liner.d new file mode 100644 index 0000000000..5304121f92 --- /dev/null +++ b/Task/Shell-one-liner/D/shell-one-liner.d @@ -0,0 +1 @@ +rdmd --eval="writeln(q{Hello World!})" diff --git a/Task/Shell-one-liner/Dc/shell-one-liner.dc b/Task/Shell-one-liner/Dc/shell-one-liner.dc new file mode 100644 index 0000000000..746402538c --- /dev/null +++ b/Task/Shell-one-liner/Dc/shell-one-liner.dc @@ -0,0 +1 @@ +dc -e '22 7/p' diff --git a/Task/Shell-one-liner/E/shell-one-liner-1.e b/Task/Shell-one-liner/E/shell-one-liner-1.e new file mode 100644 index 0000000000..5175b4ff4b --- /dev/null +++ b/Task/Shell-one-liner/E/shell-one-liner-1.e @@ -0,0 +1 @@ +rune --src.e 'println("Hello")' diff --git a/Task/Shell-one-liner/E/shell-one-liner-2.e b/Task/Shell-one-liner/E/shell-one-liner-2.e new file mode 100644 index 0000000000..bb0e1c6c7b --- /dev/null +++ b/Task/Shell-one-liner/E/shell-one-liner-2.e @@ -0,0 +1 @@ +rune --src.e-awt 'def f := <swing:makeJFrame>("Hello"); f.show(); f.addWindowListener(def _{to windowClosing(_) {interp.continueAtTop()} match _{}}); interp.blockAtTop()' diff --git a/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-1.l b/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-1.l new file mode 100644 index 0000000000..631e0d94d9 --- /dev/null +++ b/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-1.l @@ -0,0 +1 @@ +emacs -batch -eval '(princ "Hello World!\n")' diff --git a/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-2.l b/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-2.l new file mode 100644 index 0000000000..a3565800b3 --- /dev/null +++ b/Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-2.l @@ -0,0 +1 @@ +emacs -batch sample.c --eval '(indent-region (point-min) (point-max) nil)' -f save-buffer diff --git a/Task/Shell-one-liner/Erlang/shell-one-liner.erl b/Task/Shell-one-liner/Erlang/shell-one-liner.erl new file mode 100644 index 0000000000..c51341a18e --- /dev/null +++ b/Task/Shell-one-liner/Erlang/shell-one-liner.erl @@ -0,0 +1,2 @@ +$ erl -noshell -eval 'io:format("hello~n").' -s erlang halt +hello diff --git a/Task/Shell-one-liner/Factor/shell-one-liner.factor b/Task/Shell-one-liner/Factor/shell-one-liner.factor new file mode 100644 index 0000000000..16ff63c300 --- /dev/null +++ b/Task/Shell-one-liner/Factor/shell-one-liner.factor @@ -0,0 +1 @@ +$ factor -run=none -e="USE: io \"hi\" print" diff --git a/Task/Shell-one-liner/Forth/shell-one-liner.fth b/Task/Shell-one-liner/Forth/shell-one-liner.fth new file mode 100644 index 0000000000..d28d54dcd1 --- /dev/null +++ b/Task/Shell-one-liner/Forth/shell-one-liner.fth @@ -0,0 +1,2 @@ +$ gforth -e ".( Hello) cr bye" +Hello diff --git a/Task/Shell-one-liner/Gema/shell-one-liner.gema b/Task/Shell-one-liner/Gema/shell-one-liner.gema new file mode 100644 index 0000000000..458c618d29 --- /dev/null +++ b/Task/Shell-one-liner/Gema/shell-one-liner.gema @@ -0,0 +1,2 @@ +$ gema -p '\B=Hello\n@end' +Hello diff --git a/Task/Shell-one-liner/Go/shell-one-liner-1.go b/Task/Shell-one-liner/Go/shell-one-liner-1.go new file mode 100644 index 0000000000..c3ae3fd36f --- /dev/null +++ b/Task/Shell-one-liner/Go/shell-one-liner-1.go @@ -0,0 +1 @@ +echo 'package main;func main(){println("hllowrld")}'>8.go;8g 8.go;8l 8.8;8.out diff --git a/Task/Shell-one-liner/Go/shell-one-liner-2.go b/Task/Shell-one-liner/Go/shell-one-liner-2.go new file mode 100644 index 0000000000..40f403c5fe --- /dev/null +++ b/Task/Shell-one-liner/Go/shell-one-liner-2.go @@ -0,0 +1 @@ +echo 'package main;func main(){println("hllowrld")}'>/tmp/8.go;gorun /tmp/8.go diff --git a/Task/Shell-one-liner/Groovy/shell-one-liner-1.groovy b/Task/Shell-one-liner/Groovy/shell-one-liner-1.groovy new file mode 100644 index 0000000000..183fd59839 --- /dev/null +++ b/Task/Shell-one-liner/Groovy/shell-one-liner-1.groovy @@ -0,0 +1,2 @@ +$ groovysh -q "println 'Hello'" +Hello diff --git a/Task/Shell-one-liner/Groovy/shell-one-liner-2.groovy b/Task/Shell-one-liner/Groovy/shell-one-liner-2.groovy new file mode 100644 index 0000000000..7720e6ac38 --- /dev/null +++ b/Task/Shell-one-liner/Groovy/shell-one-liner-2.groovy @@ -0,0 +1,2 @@ +C:\Users\user> groovysh -q "println 'Hello'" +Hello diff --git a/Task/Shell-one-liner/Haskell/shell-one-liner.hs b/Task/Shell-one-liner/Haskell/shell-one-liner.hs new file mode 100644 index 0000000000..e9a462c118 --- /dev/null +++ b/Task/Shell-one-liner/Haskell/shell-one-liner.hs @@ -0,0 +1,2 @@ +$ ghc -e 'putStrLn "Hello"' +Hello diff --git a/Task/Shell-one-liner/J/shell-one-liner.j b/Task/Shell-one-liner/J/shell-one-liner.j new file mode 100644 index 0000000000..3d9d0eca6c --- /dev/null +++ b/Task/Shell-one-liner/J/shell-one-liner.j @@ -0,0 +1,2 @@ +$ jconsole -js "exit echo 'Hello'" +Hello diff --git a/Task/Shell-one-liner/Java/shell-one-liner-1.java b/Task/Shell-one-liner/Java/shell-one-liner-1.java new file mode 100644 index 0000000000..6749c34033 --- /dev/null +++ b/Task/Shell-one-liner/Java/shell-one-liner-1.java @@ -0,0 +1,3 @@ +$ echo 'public class X{public static void main(String[]args){' \ +> 'System.out.println("Hello Java!");}}' >X.java +$ javac X.java && java X diff --git a/Task/Shell-one-liner/Java/shell-one-liner-2.java b/Task/Shell-one-liner/Java/shell-one-liner-2.java new file mode 100644 index 0000000000..c5d4f81f07 --- /dev/null +++ b/Task/Shell-one-liner/Java/shell-one-liner-2.java @@ -0,0 +1 @@ +$ echo 'public class X{public static void main(String[]args){System.out.println("Hello Java!");}}'>X.java;javac X.java&&java X diff --git a/Task/Shell-one-liner/Java/shell-one-liner-3.java b/Task/Shell-one-liner/Java/shell-one-liner-3.java new file mode 100644 index 0000000000..96ed7014ce --- /dev/null +++ b/Task/Shell-one-liner/Java/shell-one-liner-3.java @@ -0,0 +1,2 @@ +C:\>echo public class X{public static void main(String[] args){System.out.println("Hello Java!");}}>X.java&&javac X.java&&java X +Hello Java! diff --git a/Task/Shell-one-liner/JavaScript/shell-one-liner.js b/Task/Shell-one-liner/JavaScript/shell-one-liner.js new file mode 100644 index 0000000000..8cff6b456d --- /dev/null +++ b/Task/Shell-one-liner/JavaScript/shell-one-liner.js @@ -0,0 +1,2 @@ +$ js -e 'print("hello")' +hello diff --git a/Task/Shell-one-liner/Julia/shell-one-liner.julia b/Task/Shell-one-liner/Julia/shell-one-liner.julia new file mode 100644 index 0000000000..fdacd8ac7b --- /dev/null +++ b/Task/Shell-one-liner/Julia/shell-one-liner.julia @@ -0,0 +1,3 @@ +$ julia -e 'for x in ARGS; println(x); end' foo bar +foo +bar diff --git a/Task/Shell-one-liner/K/shell-one-liner.k b/Task/Shell-one-liner/K/shell-one-liner.k new file mode 100644 index 0000000000..6bd2b3e7b1 --- /dev/null +++ b/Task/Shell-one-liner/K/shell-one-liner.k @@ -0,0 +1 @@ +$ k -e "\`0: \"hello\\n\"" diff --git a/Task/Shell-one-liner/Liberty-BASIC/shell-one-liner.liberty b/Task/Shell-one-liner/Liberty-BASIC/shell-one-liner.liberty new file mode 100644 index 0000000000..eb71a2b1d7 --- /dev/null +++ b/Task/Shell-one-liner/Liberty-BASIC/shell-one-liner.liberty @@ -0,0 +1 @@ +echo print "hello">oneLiner.bas & liberty -r oneLiner.bas echo print "hello">oneLiner.bas & liberty -r oneLiner.bas diff --git a/Task/Shell-one-liner/Lua/shell-one-liner.lua b/Task/Shell-one-liner/Lua/shell-one-liner.lua new file mode 100644 index 0000000000..6a5fbdd7dd --- /dev/null +++ b/Task/Shell-one-liner/Lua/shell-one-liner.lua @@ -0,0 +1 @@ +lua -e 'print "Hello World!"' diff --git a/Task/Shell-one-liner/Mathematica/shell-one-liner.math b/Task/Shell-one-liner/Mathematica/shell-one-liner.math new file mode 100644 index 0000000000..bbb580878e --- /dev/null +++ b/Task/Shell-one-liner/Mathematica/shell-one-liner.math @@ -0,0 +1 @@ +echo Print[2+2] > file & math.exe -script file diff --git a/Task/Shell-one-liner/NetRexx/shell-one-liner.netrexx b/Task/Shell-one-liner/NetRexx/shell-one-liner.netrexx new file mode 100644 index 0000000000..e9ab75e972 --- /dev/null +++ b/Task/Shell-one-liner/NetRexx/shell-one-liner.netrexx @@ -0,0 +1 @@ +$ TNRX=`mktemp T_XXXXXXXXXXXX` && test ! -e $TNRX.* && (echo 'say "Goodbye, World!"' >$TNRX; nrc -exec $TNRX; rm $TNRX $TNRX.*; unset TNRX) diff --git a/Task/Shell-one-liner/NewLISP/shell-one-liner.newlisp b/Task/Shell-one-liner/NewLISP/shell-one-liner.newlisp new file mode 100644 index 0000000000..c90234a7aa --- /dev/null +++ b/Task/Shell-one-liner/NewLISP/shell-one-liner.newlisp @@ -0,0 +1,2 @@ +newlisp -e "\"Hello\" +->"Hello" diff --git a/Task/Shell-one-liner/OCaml/shell-one-liner.ocaml b/Task/Shell-one-liner/OCaml/shell-one-liner.ocaml new file mode 100644 index 0000000000..871983c74e --- /dev/null +++ b/Task/Shell-one-liner/OCaml/shell-one-liner.ocaml @@ -0,0 +1,2 @@ +$ ocaml <(echo 'print_endline "Hello"') +Hello diff --git a/Task/Shell-one-liner/Objeck/shell-one-liner.objeck b/Task/Shell-one-liner/Objeck/shell-one-liner.objeck new file mode 100644 index 0000000000..fcd4bd293d --- /dev/null +++ b/Task/Shell-one-liner/Objeck/shell-one-liner.objeck @@ -0,0 +1 @@ +./obc -run '"Hello"->PrintLine();' -dest hello.obe ; ./obr hello.obe diff --git a/Task/Shell-one-liner/Oz/shell-one-liner.oz b/Task/Shell-one-liner/Oz/shell-one-liner.oz new file mode 100644 index 0000000000..461d94dc25 --- /dev/null +++ b/Task/Shell-one-liner/Oz/shell-one-liner.oz @@ -0,0 +1,2 @@ +echo >tmp.oz "{System.show hello}"; ozc -l System -e tmp.oz +hello diff --git a/Task/Shell-one-liner/PARI-GP/shell-one-liner.pari b/Task/Shell-one-liner/PARI-GP/shell-one-liner.pari new file mode 100644 index 0000000000..d650263417 --- /dev/null +++ b/Task/Shell-one-liner/PARI-GP/shell-one-liner.pari @@ -0,0 +1 @@ +echo "print(Pi)" | gp -q diff --git a/Task/Shell-one-liner/PHP/shell-one-liner.php b/Task/Shell-one-liner/PHP/shell-one-liner.php new file mode 100644 index 0000000000..afda8746cf --- /dev/null +++ b/Task/Shell-one-liner/PHP/shell-one-liner.php @@ -0,0 +1,2 @@ +$ php -r 'echo "Hello\n";' +Hello diff --git a/Task/Shell-one-liner/Pascal/shell-one-liner.pascal b/Task/Shell-one-liner/Pascal/shell-one-liner.pascal new file mode 100644 index 0000000000..698d476e8d --- /dev/null +++ b/Task/Shell-one-liner/Pascal/shell-one-liner.pascal @@ -0,0 +1,2 @@ +$ echo "begin writeln('Hello World') end." >OneLiner.pas; fpc -Fe/dev/null OneLiner.pas; ./OneLiner +Hello World diff --git a/Task/Shell-one-liner/Perl-6/shell-one-liner.pl6 b/Task/Shell-one-liner/Perl-6/shell-one-liner.pl6 new file mode 100644 index 0000000000..68d95af060 --- /dev/null +++ b/Task/Shell-one-liner/Perl-6/shell-one-liner.pl6 @@ -0,0 +1,2 @@ +$ perl6 -e 'say "Hello, world!"' +Hello, world! diff --git a/Task/Shell-one-liner/Perl/shell-one-liner.pl b/Task/Shell-one-liner/Perl/shell-one-liner.pl new file mode 100644 index 0000000000..0b9ed01079 --- /dev/null +++ b/Task/Shell-one-liner/Perl/shell-one-liner.pl @@ -0,0 +1,2 @@ +$ perl -e 'print "Hello\n"' +Hello diff --git a/Task/Shell-one-liner/PicoLisp/shell-one-liner.l b/Task/Shell-one-liner/PicoLisp/shell-one-liner.l new file mode 100644 index 0000000000..9ba268a893 --- /dev/null +++ b/Task/Shell-one-liner/PicoLisp/shell-one-liner.l @@ -0,0 +1,2 @@ +$ picolisp -'prinl "Hello world!"' -bye +Hello world! diff --git a/Task/Shell-one-liner/Pike/shell-one-liner.pike b/Task/Shell-one-liner/Pike/shell-one-liner.pike new file mode 100644 index 0000000000..fade995a78 --- /dev/null +++ b/Task/Shell-one-liner/Pike/shell-one-liner.pike @@ -0,0 +1,2 @@ +$ pike -e 'write("Hello\n");' +Hello diff --git a/Task/Shell-one-liner/PowerShell/shell-one-liner.psh b/Task/Shell-one-liner/PowerShell/shell-one-liner.psh new file mode 100644 index 0000000000..a620bbb7aa --- /dev/null +++ b/Task/Shell-one-liner/PowerShell/shell-one-liner.psh @@ -0,0 +1,2 @@ +> powershell -Command "Write-Host 'Hello'" +Hello diff --git a/Task/Shell-one-liner/PureBasic/shell-one-liner.purebasic b/Task/Shell-one-liner/PureBasic/shell-one-liner.purebasic new file mode 100644 index 0000000000..9290076c7f --- /dev/null +++ b/Task/Shell-one-liner/PureBasic/shell-one-liner.purebasic @@ -0,0 +1 @@ +$ echo 'messagerequester("Greetings","hello")' > "dib.pb" && ./pbcompiler dib.pb -e "dib" && ./dib diff --git a/Task/Shell-one-liner/Python/shell-one-liner-1.py b/Task/Shell-one-liner/Python/shell-one-liner-1.py new file mode 100644 index 0000000000..c6a4cea05e --- /dev/null +++ b/Task/Shell-one-liner/Python/shell-one-liner-1.py @@ -0,0 +1,2 @@ +$ python -c 'print "Hello"' +Hello diff --git a/Task/Shell-one-liner/Python/shell-one-liner-2.py b/Task/Shell-one-liner/Python/shell-one-liner-2.py new file mode 100644 index 0000000000..13183b9f71 --- /dev/null +++ b/Task/Shell-one-liner/Python/shell-one-liner-2.py @@ -0,0 +1 @@ +python -m CGIHTTPServer diff --git a/Task/Shell-one-liner/R/shell-one-liner-1.r b/Task/Shell-one-liner/R/shell-one-liner-1.r new file mode 100644 index 0000000000..4b19f7c98f --- /dev/null +++ b/Task/Shell-one-liner/R/shell-one-liner-1.r @@ -0,0 +1,2 @@ +$ echo 'cat("Hello\n")' | R --slave +Hello diff --git a/Task/Shell-one-liner/R/shell-one-liner-2.r b/Task/Shell-one-liner/R/shell-one-liner-2.r new file mode 100644 index 0000000000..91167e94c9 --- /dev/null +++ b/Task/Shell-one-liner/R/shell-one-liner-2.r @@ -0,0 +1,2 @@ +$ Rscript -e 'cat("Hello\n")' +Hello diff --git a/Task/Shell-one-liner/REBOL/shell-one-liner.rebol b/Task/Shell-one-liner/REBOL/shell-one-liner.rebol new file mode 100644 index 0000000000..2e3690b097 --- /dev/null +++ b/Task/Shell-one-liner/REBOL/shell-one-liner.rebol @@ -0,0 +1 @@ +rebview -vswq --do "print {Hello!} quit" diff --git a/Task/Shell-one-liner/REXX/shell-one-liner.rexx b/Task/Shell-one-liner/REXX/shell-one-liner.rexx new file mode 100644 index 0000000000..9051912099 --- /dev/null +++ b/Task/Shell-one-liner/REXX/shell-one-liner.rexx @@ -0,0 +1,5 @@ + ┌────────────────────────────────────────────────┐ + │ from the MS Windows® command line (cmd.exe) │ + └────────────────────────────────────────────────┘ + +echo do j=10 by 20 for 4;say right('hello',j);end | regina diff --git a/Task/Shell-one-liner/Racket/shell-one-liner.rkt b/Task/Shell-one-liner/Racket/shell-one-liner.rkt new file mode 100644 index 0000000000..095f38dcdb --- /dev/null +++ b/Task/Shell-one-liner/Racket/shell-one-liner.rkt @@ -0,0 +1,2 @@ +$ racket -e "(displayln \"Hello World\")" +Hello World diff --git a/Task/Shell-one-liner/Retro/shell-one-liner.retro b/Task/Shell-one-liner/Retro/shell-one-liner.retro new file mode 100644 index 0000000000..5a5a0f3d62 --- /dev/null +++ b/Task/Shell-one-liner/Retro/shell-one-liner.retro @@ -0,0 +1 @@ +echo '"hello\n" puts bye' | ./retro diff --git a/Task/Shell-one-liner/Ruby/shell-one-liner-1.rb b/Task/Shell-one-liner/Ruby/shell-one-liner-1.rb new file mode 100644 index 0000000000..ca872c5e97 --- /dev/null +++ b/Task/Shell-one-liner/Ruby/shell-one-liner-1.rb @@ -0,0 +1,2 @@ +$ ruby -e 'puts "Hello"' +Hello diff --git a/Task/Shell-one-liner/Ruby/shell-one-liner-2.rb b/Task/Shell-one-liner/Ruby/shell-one-liner-2.rb new file mode 100644 index 0000000000..6aa7417ea5 --- /dev/null +++ b/Task/Shell-one-liner/Ruby/shell-one-liner-2.rb @@ -0,0 +1,2 @@ +$ jruby -e 'puts "Hello from JRuby"' +Hello from JRuby diff --git a/Task/Shell-one-liner/Ruby/shell-one-liner-3.rb b/Task/Shell-one-liner/Ruby/shell-one-liner-3.rb new file mode 100644 index 0000000000..3621c82cde --- /dev/null +++ b/Task/Shell-one-liner/Ruby/shell-one-liner-3.rb @@ -0,0 +1,2 @@ +$ rbx -e 'puts "Hello from Rubinius"' +Hello from Rubinius diff --git a/Task/Shell-one-liner/Run-BASIC/shell-one-liner.run b/Task/Shell-one-liner/Run-BASIC/shell-one-liner.run new file mode 100644 index 0000000000..7137a8c576 --- /dev/null +++ b/Task/Shell-one-liner/Run-BASIC/shell-one-liner.run @@ -0,0 +1 @@ +print shell$("echo hello world") diff --git a/Task/Shell-one-liner/SNOBOL4/shell-one-liner-1.sno b/Task/Shell-one-liner/SNOBOL4/shell-one-liner-1.sno new file mode 100644 index 0000000000..83d1041ad6 --- /dev/null +++ b/Task/Shell-one-liner/SNOBOL4/shell-one-liner-1.sno @@ -0,0 +1 @@ +echo 'a output = "Hello, World!";end' | snobol4 -b diff --git a/Task/Shell-one-liner/SNOBOL4/shell-one-liner-2.sno b/Task/Shell-one-liner/SNOBOL4/shell-one-liner-2.sno new file mode 100644 index 0000000000..365bfb56fd --- /dev/null +++ b/Task/Shell-one-liner/SNOBOL4/shell-one-liner-2.sno @@ -0,0 +1 @@ +snobol4 -b <<<'a output = "Hello, World!";end' diff --git a/Task/Shell-one-liner/Scala/shell-one-liner.scala b/Task/Shell-one-liner/Scala/shell-one-liner.scala new file mode 100644 index 0000000000..f35ada5371 --- /dev/null +++ b/Task/Shell-one-liner/Scala/shell-one-liner.scala @@ -0,0 +1,2 @@ +C:\>scala -e "println(\"Hello\")" +Hello diff --git a/Task/Shell-one-liner/Scheme/shell-one-liner.ss b/Task/Shell-one-liner/Scheme/shell-one-liner.ss new file mode 100644 index 0000000000..8bff2a267e --- /dev/null +++ b/Task/Shell-one-liner/Scheme/shell-one-liner.ss @@ -0,0 +1 @@ +guile -c '(display "Hello, world!\n")' diff --git a/Task/Shell-one-liner/Shiny/shell-one-liner.shiny b/Task/Shell-one-liner/Shiny/shell-one-liner.shiny new file mode 100644 index 0000000000..674da32127 --- /dev/null +++ b/Task/Shell-one-liner/Shiny/shell-one-liner.shiny @@ -0,0 +1 @@ +shiny -e "say 'hi'" diff --git a/Task/Shell-one-liner/Slate/shell-one-liner.slate b/Task/Shell-one-liner/Slate/shell-one-liner.slate new file mode 100644 index 0000000000..036550bf4f --- /dev/null +++ b/Task/Shell-one-liner/Slate/shell-one-liner.slate @@ -0,0 +1 @@ +./slate --eval "[inform: 'hello'] ensure: [exit: 0].". diff --git a/Task/Shell-one-liner/TXR/shell-one-liner.txr b/Task/Shell-one-liner/TXR/shell-one-liner.txr new file mode 100644 index 0000000000..ca8c9ea44c --- /dev/null +++ b/Task/Shell-one-liner/TXR/shell-one-liner.txr @@ -0,0 +1,4 @@ +$ echo 123-456-7890 | txr -c '@a-@b-@c' - +a="123" +b="456" +c="7890" diff --git a/Task/Shell-one-liner/Tcl/shell-one-liner.tcl b/Task/Shell-one-liner/Tcl/shell-one-liner.tcl new file mode 100644 index 0000000000..e477b937ff --- /dev/null +++ b/Task/Shell-one-liner/Tcl/shell-one-liner.tcl @@ -0,0 +1,2 @@ +$ echo 'puts Hello' | tclsh +Hello diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-1.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-1.sh new file mode 100644 index 0000000000..56861af9ed --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-1.sh @@ -0,0 +1 @@ +$ sh -c ls diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-2.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-2.sh new file mode 100644 index 0000000000..03e5cb0a3f --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-2.sh @@ -0,0 +1 @@ +$ sh -c "echo hello" diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-3.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-3.sh new file mode 100644 index 0000000000..e7bcd67a8a --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-3.sh @@ -0,0 +1,3 @@ +$ bash -c 'paste <(echo 1) <(echo 2)' +$ ksh -c 'let i=3+4; print $i' +$ zsh -c 'if [[ 5 -lt 6 ]] { echo ok };' diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-4.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-4.sh new file mode 100644 index 0000000000..6cbdc2f36e --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-4.sh @@ -0,0 +1,3 @@ +$ VAR=`echo hello` # obsolescent backtick notation +$ VAR=$(echo hello) # modern POSIX notation +$ (echo hello) # execute in another shell process, not in this one diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-5.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-5.sh new file mode 100644 index 0000000000..849b370dac --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-5.sh @@ -0,0 +1 @@ +$ csh -fc 'if (5 < 6) echo ok' diff --git a/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-6.sh b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-6.sh new file mode 100644 index 0000000000..e9cb3bce79 --- /dev/null +++ b/Task/Shell-one-liner/UNIX-Shell/shell-one-liner-6.sh @@ -0,0 +1 @@ +$ es -c 'if {test 5 -lt 6} {echo ok}' diff --git a/Task/Shell-one-liner/Ursala/shell-one-liner.ursala b/Task/Shell-one-liner/Ursala/shell-one-liner.ursala new file mode 100644 index 0000000000..61d2c9237b --- /dev/null +++ b/Task/Shell-one-liner/Ursala/shell-one-liner.ursala @@ -0,0 +1,6 @@ +$ fun --main=-[hello]- --show +hello +$ fun --main="power/2 32" --cast %n +4294967296 +$ fun --m="..mp2str mpfr..pi 120" --c %s +'3.1415926535897932384626433832795028847E+00' diff --git a/Task/Shell-one-liner/Vedit-macro-language/shell-one-liner.vedit b/Task/Shell-one-liner/Vedit-macro-language/shell-one-liner.vedit new file mode 100644 index 0000000000..4596c30e3b --- /dev/null +++ b/Task/Shell-one-liner/Vedit-macro-language/shell-one-liner.vedit @@ -0,0 +1 @@ +vpw -c'Get_Key("Hello!") exit' diff --git a/Task/Short-circuit-evaluation/0DESCRIPTION b/Task/Short-circuit-evaluation/0DESCRIPTION new file mode 100644 index 0000000000..63491a505d --- /dev/null +++ b/Task/Short-circuit-evaluation/0DESCRIPTION @@ -0,0 +1,18 @@ +{{Control Structures}} +Assume functions a and b return boolean values, and further, the execution of function b takes considerable resources without side effects, and is to be minimised. + +If we needed to compute the conjunction (and): +:x = a() and b() +Then it would be best to not compute the value of b() if the value of a() is computed as \mathrm{false}, as the value of x can then only ever be \mathrm{false}. + +Similarly, if we needed to compute the disjunction (or): +:y = a() or b() +Then it would be best to not compute the value of b() if the value of a() is computed as \mathrm{true}, as the value of y can then only ever be \mathrm{true}. + +Some languages will stop further computation of boolean equations as soon as the result is known, so-called [[wp:Short-circuit evaluation|short-circuit evaluation]] of boolean expressions + +;Task Description +The task is to create two functions named a and b, that take and return the same boolean value. The functions should also print their name whenever they are called. Calculate and assign the values of the following equations to a variable in such a way that function b is only called when necessary: +:x = a(i) and b(j) +:y = a(i) or b(j) +If the language does not have short-circuit evaluation, this might be achieved with nested if statements. diff --git a/Task/Short-circuit-evaluation/1META.yaml b/Task/Short-circuit-evaluation/1META.yaml new file mode 100644 index 0000000000..c78e2d9a80 --- /dev/null +++ b/Task/Short-circuit-evaluation/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming language concepts diff --git a/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-1.alg b/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-1.alg new file mode 100644 index 0000000000..cbb7f93085 --- /dev/null +++ b/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-1.alg @@ -0,0 +1,38 @@ +PRIO ORELSE = 2, ANDTHEN = 3; # user defined operators # +OP ORELSE = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ), + ANDTHEN = (BOOL a, PROC BOOL b)BOOL: ( a | b | a ); + +# user defined Short-circuit_evaluation procedures # +PROC or else = (BOOL a, PROC BOOL b)BOOL: ( a | a | b ), + and then = (BOOL a, PROC BOOL b)BOOL: ( a | b | a ); + +test:( + + PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a), + b = (BOOL b)BOOL: ( print(("b=",b,", ")); b); + +CO +# Valid for Algol 68 Rev0: using "user defined" operators # +# Note: here BOOL is being automatically "procedured" to PROC BOOL # + print(("T ORELSE F = ", a(TRUE) ORELSE b(FALSE), new line)); + print(("F ANDTHEN T = ", a(FALSE) ANDTHEN b(TRUE), new line)); + + print(("or else(T, F) = ", or else(a(TRUE), b(FALSE)), new line)); + print(("and then(F, T) = ", and then(a(FALSE), b(TRUE)), new line)); +END CO + +# Valid for Algol68 Rev1: using "user defined" operators # +# Note: BOOL must be manually "procedured" to PROC BOOL # + print(("T ORELSE F = ", a(TRUE) ORELSE (BOOL:b(FALSE)), new line)); + print(("T ORELSE T = ", a(TRUE) ORELSE (BOOL:b(TRUE)), new line)); + + print(("F ANDTHEN F = ", a(FALSE) ANDTHEN (BOOL:b(FALSE)), new line)); + print(("F ANDTHEN T = ", a(FALSE) ANDTHEN (BOOL:b(TRUE)), new line)); + + print(("F ORELSE F = ", a(FALSE) ORELSE (BOOL:b(FALSE)), new line)); + print(("F ORELSE T = ", a(FALSE) ORELSE (BOOL:b(TRUE)), new line)); + + print(("T ANDTHEN F = ", a(TRUE) ANDTHEN (BOOL:b(FALSE)), new line)); + print(("T ANDTHEN T = ", a(TRUE) ANDTHEN (BOOL:b(TRUE)), new line)) + +) diff --git a/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-2.alg b/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-2.alg new file mode 100644 index 0000000000..b5e9a90e33 --- /dev/null +++ b/Task/Short-circuit-evaluation/ALGOL-68/short-circuit-evaluation-2.alg @@ -0,0 +1,25 @@ +test:( + + PROC a = (BOOL a)BOOL: ( print(("a=",a,", ")); a), + b = (BOOL b)BOOL: ( print(("b=",b,", ")); b); + +# Valid for Algol 68G and 68RS using non standard operators # + print(("T OREL F = ", a(TRUE) OREL b(FALSE), new line)); + print(("T OREL T = ", a(TRUE) OREL b(TRUE), new line)); + + print(("F ANDTH F = ", a(FALSE) ANDTH b(FALSE), new line)); + print(("F ANDTH T = ", a(FALSE) ANDTH b(TRUE), new line)); + + print(("F OREL F = ", a(FALSE) OREL b(FALSE), new line)); + print(("F OREL T = ", a(FALSE) OREL b(TRUE), new line)); + + print(("T ANDTH F = ", a(TRUE) ANDTH b(FALSE), new line)); + print(("T ANDTH T = ", a(TRUE) ANDTH b(TRUE), new line)) + +CO; +# Valid for Algol 68G and 68C using non standard operators # + print(("T ORF F = ", a(TRUE) ORF b(FALSE), new line)); + print(("F ANDF T = ", a(FALSE) ANDF b(TRUE), new line)) +END CO + +) diff --git a/Task/Short-circuit-evaluation/Ada/short-circuit-evaluation.ada b/Task/Short-circuit-evaluation/Ada/short-circuit-evaluation.ada new file mode 100644 index 0000000000..b6931bf0c5 --- /dev/null +++ b/Task/Short-circuit-evaluation/Ada/short-circuit-evaluation.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Short_Circuit is + function A (Value : Boolean) return Boolean is + begin + Put (" A=" & Boolean'Image (Value)); + return Value; + end A; + function B (Value : Boolean) return Boolean is + begin + Put (" B=" & Boolean'Image (Value)); + return Value; + end B; +begin + for I in Boolean'Range loop + for J in Boolean'Range loop + Put (" (A and then B)=" & Boolean'Image (A (I) and then B (J))); + New_Line; + end loop; + end loop; + for I in Boolean'Range loop + for J in Boolean'Range loop + Put (" (A or else B)=" & Boolean'Image (A (I) or else B (J))); + New_Line; + end loop; + end loop; +end Test_Short_Circuit; diff --git a/Task/Short-circuit-evaluation/AutoHotkey/short-circuit-evaluation.ahk b/Task/Short-circuit-evaluation/AutoHotkey/short-circuit-evaluation.ahk new file mode 100644 index 0000000000..dcbe2b1d30 --- /dev/null +++ b/Task/Short-circuit-evaluation/AutoHotkey/short-circuit-evaluation.ahk @@ -0,0 +1,16 @@ +i = 1 +j = 1 +x := a(i) and b(j) +y := a(i) or b(j) + +a(p) +{ + MsgBox, a() was called with the parameter "%p%". + Return, p +} + +b(p) +{ + MsgBox, b() was called with the parameter "%p%". + Return, p +} diff --git a/Task/Short-circuit-evaluation/BBC-BASIC/short-circuit-evaluation.bbc b/Task/Short-circuit-evaluation/BBC-BASIC/short-circuit-evaluation.bbc new file mode 100644 index 0000000000..6fe0058de5 --- /dev/null +++ b/Task/Short-circuit-evaluation/BBC-BASIC/short-circuit-evaluation.bbc @@ -0,0 +1,28 @@ + REM TRUE is represented as -1, FALSE as 0 + FOR i% = TRUE TO FALSE + FOR j% = TRUE TO FALSE + PRINT "For x=a(";FNboolstring(i%);") AND b(";FNboolstring(j%);")" + x% = FALSE + REM Short-circuit AND can be simulated by cascaded IFs: + IF FNa(i%) IF FNb(j%) THEN x%=TRUE + PRINT "x is ";FNboolstring(x%) + PRINT + PRINT "For y=a(";FNboolstring(i%);") OR b(";FNboolstring(j%);")" + y% = FALSE + REM Short-circuit OR can be simulated by De Morgan's laws: + IF NOTFNa(i%) IF NOTFNb(j%) ELSE y%=TRUE : REM Note ELSE without THEN + PRINT "y is ";FNboolstring(y%) + PRINT + NEXT:NEXT + END + + DEFFNa(bool%) + PRINT "Function A used; "; + =bool% + + DEFFNb(bool%) + PRINT "Function B used; "; + =bool% + + DEFFNboolstring(bool%) + IF bool%=0 THEN ="FALSE" ELSE="TRUE" diff --git a/Task/Short-circuit-evaluation/C++/short-circuit-evaluation.cpp b/Task/Short-circuit-evaluation/C++/short-circuit-evaluation.cpp new file mode 100644 index 0000000000..d75d9ba633 --- /dev/null +++ b/Task/Short-circuit-evaluation/C++/short-circuit-evaluation.cpp @@ -0,0 +1,27 @@ +#include + +bool a(bool in) +{ + std::cout << "a" << std::endl; + return in; +} + +bool b(bool in) +{ + std::cout << "b" << std::endl; + return in; +} + +void test(bool i, bool j) { + std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; + std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; +} + +int main() +{ + test(false, false); + test(false, true); + test(true, false); + test(true, true); + return 0; +} diff --git a/Task/Short-circuit-evaluation/C/short-circuit-evaluation.c b/Task/Short-circuit-evaluation/C/short-circuit-evaluation.c new file mode 100644 index 0000000000..498496326e --- /dev/null +++ b/Task/Short-circuit-evaluation/C/short-circuit-evaluation.c @@ -0,0 +1,32 @@ +#include +#include + +bool a(bool in) +{ + printf("I am a\n"); + return in; +} + +bool b(bool in) +{ + printf("I am b\n"); + return in; +} + +#define TEST(X,Y,O) \ + do { \ + x = a(X) O b(Y); \ + printf(#X " " #O " " #Y " = %s\n\n", x ? "true" : "false"); \ + } while(false); + +int main() +{ + bool x; + + TEST(false, true, &&); // b is not evaluated + TEST(true, false, ||); // b is not evaluated + TEST(true, false, &&); // b is evaluated + TEST(false, false, ||); // b is evaluated + + return 0; +} diff --git a/Task/Short-circuit-evaluation/Clojure/short-circuit-evaluation.clj b/Task/Short-circuit-evaluation/Clojure/short-circuit-evaluation.clj new file mode 100644 index 0000000000..b054dbe0a1 --- /dev/null +++ b/Task/Short-circuit-evaluation/Clojure/short-circuit-evaluation.clj @@ -0,0 +1,7 @@ +(letfn [(a [bool] (print "(a)") bool) + (b [bool] (print "(b)") bool)] + (doseq [i [true false] j [true false]] + (print i "OR" j "= ") + (println (or (a i) (b j))) + (print i "AND" j " = ") + (println (and (a i) (b j))))) diff --git a/Task/Short-circuit-evaluation/Common-Lisp/short-circuit-evaluation.lisp b/Task/Short-circuit-evaluation/Common-Lisp/short-circuit-evaluation.lisp new file mode 100644 index 0000000000..2b6f3b7b88 --- /dev/null +++ b/Task/Short-circuit-evaluation/Common-Lisp/short-circuit-evaluation.lisp @@ -0,0 +1,13 @@ +(defun a (F) + (print 'a) + F ) + +(defun b (F) + (print 'b) + F ) + +(dolist (x '((nil nil) (nil T) (T T) (T nil))) + (format t "~%(and ~S)" x) + (and (a (car x)) (b (car(cdr x)))) + (format t "~%(or ~S)" x) + (or (a (car x)) (b (car(cdr x))))) diff --git a/Task/Short-circuit-evaluation/D/short-circuit-evaluation.d b/Task/Short-circuit-evaluation/D/short-circuit-evaluation.d new file mode 100644 index 0000000000..2e6d81ac50 --- /dev/null +++ b/Task/Short-circuit-evaluation/D/short-circuit-evaluation.d @@ -0,0 +1,21 @@ +import std.stdio, std.algorithm; + +T a(T)(T answer) { + writefln(" # Called function a(%s) -> %s", answer, answer); + return answer; +} + +T b(T)(T answer) { + writefln(" # Called function b(%s) -> %s", answer, answer); + return answer; +} + +void main() { + foreach (immutable x, immutable y; + [false, true].cartesianProduct([false, true])) { + writeln("\nCalculating: r1 = a(x) && b(y)"); + immutable r1 = a(x) && b(y); + writeln("Calculating: r2 = a(x) || b(y)"); + immutable r2 = a(x) || b(y); + } +} diff --git a/Task/Short-circuit-evaluation/Delphi/short-circuit-evaluation.delphi b/Task/Short-circuit-evaluation/Delphi/short-circuit-evaluation.delphi new file mode 100644 index 0000000000..269df923e7 --- /dev/null +++ b/Task/Short-circuit-evaluation/Delphi/short-circuit-evaluation.delphi @@ -0,0 +1,32 @@ +program ShortCircuitEvaluation; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +function A(aValue: Boolean): Boolean; +begin + Writeln('a'); + Result := aValue; +end; + +function B(aValue: Boolean): Boolean; +begin + Writeln('b'); + Result := aValue; +end; + +var + i, j: Boolean; +begin + for i in [False, True] do + begin + for j in [False, True] do + begin + Writeln(Format('%s and %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) and B(j), True)])); + Writeln; + Writeln(Format('%s or %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) or B(j), True)])); + Writeln; + end; + end; +end. diff --git a/Task/Short-circuit-evaluation/E/short-circuit-evaluation-1.e b/Task/Short-circuit-evaluation/E/short-circuit-evaluation-1.e new file mode 100644 index 0000000000..0f63252fcb --- /dev/null +++ b/Task/Short-circuit-evaluation/E/short-circuit-evaluation-1.e @@ -0,0 +1,5 @@ +def a(v) { println("a"); return v } +def b(v) { println("b"); return v } + +def x := a(i) && b(j) +def y := b(i) || b(j) diff --git a/Task/Short-circuit-evaluation/E/short-circuit-evaluation-2.e b/Task/Short-circuit-evaluation/E/short-circuit-evaluation-2.e new file mode 100644 index 0000000000..ec415bf2ec --- /dev/null +++ b/Task/Short-circuit-evaluation/E/short-circuit-evaluation-2.e @@ -0,0 +1 @@ +def x := a(i) && (def funky := b(j)) diff --git a/Task/Short-circuit-evaluation/Fantom/short-circuit-evaluation.fantom b/Task/Short-circuit-evaluation/Fantom/short-circuit-evaluation.fantom new file mode 100644 index 0000000000..3e6de96c6f --- /dev/null +++ b/Task/Short-circuit-evaluation/Fantom/short-circuit-evaluation.fantom @@ -0,0 +1,28 @@ +class Main +{ + static Bool a (Bool value) + { + echo ("in a") + return value + } + + static Bool b (Bool value) + { + echo ("in b") + return value + } + + public static Void main () + { + [false,true].each |i| + { + [false,true].each |j| + { + Bool result := a(i) && b(j) + echo ("a($i) && b($j): " + result) + result = a(i) || b(j) + echo ("a($i) || b($j): " + result) + } + } + } +} diff --git a/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth b/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth new file mode 100644 index 0000000000..454406fbec --- /dev/null +++ b/Task/Short-circuit-evaluation/Forth/short-circuit-evaluation.fth @@ -0,0 +1,20 @@ +\ short-circuit conditional syntax, from Wil Baden +: COND 0 ; immediate +: THENS BEGIN dup WHILE postpone THEN REPEAT DROP ; immediate +: ORIF s" ?DUP 0= IF" evaluate ; immediate +: ANDIF s" DUP IF DROP" evaluate ; immediate + +: .bool IF ." true " ELSE ." false" THEN ; +: A ." A=" dup .bool ; +: B ." B=" dup .bool ; + +: test + 1 -1 DO 1 -1 DO + CR I A drop space J B drop space + ." : ANDIF " COND I A ANDIF drop J B IF ." (BOTH)" THENS + ." , ORIF " COND I A ORIF drop J B 0= IF ." (NEITHER)" THENS + LOOP LOOP ; + +\ a more typical example +: alnum? ( char -- ? ) + COND dup lower? ORIF dup upper? ORIF dup digit? THENS nip ; diff --git a/Task/Short-circuit-evaluation/Fortran/short-circuit-evaluation.f b/Task/Short-circuit-evaluation/Fortran/short-circuit-evaluation.f new file mode 100644 index 0000000000..26abf391ca --- /dev/null +++ b/Task/Short-circuit-evaluation/Fortran/short-circuit-evaluation.f @@ -0,0 +1,51 @@ +program Short_Circuit_Eval + implicit none + + logical :: x, y + logical, dimension(2) :: l = (/ .false., .true. /) + integer :: i, j + + do i = 1, 2 + do j = 1, 2 + write(*, "(a,l1,a,l1,a)") "Calculating x = a(", l(i), ") and b(", l(j), ")" + ! a AND b + x = a(l(i)) + if(x) then + x = b(l(j)) + write(*, "(a,l1)") "x = ", x + else + write(*, "(a,l1)") "x = ", x + end if + + write(*,*) + write(*, "(a,l1,a,l1,a)") "Calculating y = a(", l(i), ") or b(", l(j), ")" + ! a OR b + y = a(l(i)) + if(y) then + write(*, "(a,l1)") "y = ", y + else + y = b(l(j)) + write(*, "(a,l1)") "y = ", y + end if + write(*,*) + end do + end do + +contains + +function a(value) + logical :: a + logical, intent(in) :: value + + a = value + write(*, "(a,l1,a)") "Called function a(", value, ")" +end function + +function b(value) + logical :: b + logical, intent(in) :: value + + b = value + write(*, "(a,l1,a)") "Called function b(", value, ")" +end function +end program diff --git a/Task/Short-circuit-evaluation/Go/short-circuit-evaluation.go b/Task/Short-circuit-evaluation/Go/short-circuit-evaluation.go new file mode 100644 index 0000000000..9d66b3d000 --- /dev/null +++ b/Task/Short-circuit-evaluation/Go/short-circuit-evaluation.go @@ -0,0 +1,32 @@ +package main + +import "fmt" + +func a(v bool) bool { + fmt.Print("a") + return v +} + +func b(v bool) bool { + fmt.Print("b") + return v +} + +func test(i, j bool) { + fmt.Printf("Testing a(%t) && b(%t)\n", i, j) + fmt.Print("Trace: ") + fmt.Println("\nResult:", a(i) && b(j)) + + fmt.Printf("Testing a(%t) || b(%t)\n", i, j) + fmt.Print("Trace: ") + fmt.Println("\nResult:", a(i) || b(j)) + + fmt.Println("") +} + +func main() { + test(false, false) + test(false, true) + test(true, false) + test(true, true) +} diff --git a/Task/Short-circuit-evaluation/Groovy/short-circuit-evaluation.groovy b/Task/Short-circuit-evaluation/Groovy/short-circuit-evaluation.groovy new file mode 100644 index 0000000000..bf8486a937 --- /dev/null +++ b/Task/Short-circuit-evaluation/Groovy/short-circuit-evaluation.groovy @@ -0,0 +1,15 @@ +def f = { println ' AHA!'; it instanceof String } +def g = { printf ('%5d ', it); it > 50 } + +println 'bitwise' +assert g(100) & f('sss') +assert g(2) | f('sss') +assert ! (g(1) & f('sss')) +assert g(200) | f('sss') + +println ''' +logical''' +assert g(100) && f('sss') +assert g(2) || f('sss') +assert ! (g(1) && f('sss')) +assert g(200) || f('sss') diff --git a/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-1.hs b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-1.hs new file mode 100644 index 0000000000..31ce187060 --- /dev/null +++ b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-1.hs @@ -0,0 +1,18 @@ +module ShortCircuit where + +import Prelude hiding ((&&), (||)) +import Debug.Trace + +False && _ = False +True && False = False +_ && _ = True + +True || _ = True +False || True = True +_ || _ = False + +a p = trace ("") p +b p = trace ("") p + +main = mapM_ print ( [ a p || b q | p <- [False, True], q <- [False, True] ] + ++ [ a p && b q | p <- [False, True], q <- [False, True] ]) diff --git a/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-2.hs b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-2.hs new file mode 100644 index 0000000000..909857d229 --- /dev/null +++ b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-2.hs @@ -0,0 +1,7 @@ +_ && False = False +False && True = False +_ && _ = True + +_ || True = True +True || False = True +_ || _ = False diff --git a/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-3.hs b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-3.hs new file mode 100644 index 0000000000..fcc4655e3e --- /dev/null +++ b/Task/Short-circuit-evaluation/Haskell/short-circuit-evaluation-3.hs @@ -0,0 +1,11 @@ +p && q = case p of + False -> False + _ -> case q of + False -> False + _ -> True + +p || q = case p of + True -> True + _ -> case q of + True -> True + _ -> False diff --git a/Task/Short-circuit-evaluation/Icon/short-circuit-evaluation.icon b/Task/Short-circuit-evaluation/Icon/short-circuit-evaluation.icon new file mode 100644 index 0000000000..e1066eac9b --- /dev/null +++ b/Task/Short-circuit-evaluation/Icon/short-circuit-evaluation.icon @@ -0,0 +1,19 @@ +procedure main() +&trace := -1 # ensures functions print their names + +every (i := false | true ) & ( j := false | true) do { + write("i,j := ",image(i),", ",image(j)) + write("i & j:") + x := i() & j() # invoke true/false + write("i | j:") + y := i() | j() # invoke true/false + } +end + +procedure true() #: succeeds always (returning null) +return +end + +procedure false() #: fails always +fail # for clarity but not needed as running into end has the same effect +end diff --git a/Task/Short-circuit-evaluation/J/short-circuit-evaluation-1.j b/Task/Short-circuit-evaluation/J/short-circuit-evaluation-1.j new file mode 100644 index 0000000000..7070022beb --- /dev/null +++ b/Task/Short-circuit-evaluation/J/short-circuit-evaluation-1.j @@ -0,0 +1,5 @@ +labeled=:1 :'[ smoutput@,&":~&m' +A=: 'A ' labeled +B=: 'B ' labeled +and=: ^: +or=: 2 :'u^:(-.@v)' diff --git a/Task/Short-circuit-evaluation/J/short-circuit-evaluation-2.j b/Task/Short-circuit-evaluation/J/short-circuit-evaluation-2.j new file mode 100644 index 0000000000..d68dece8a7 --- /dev/null +++ b/Task/Short-circuit-evaluation/J/short-circuit-evaluation-2.j @@ -0,0 +1,14 @@ + (A and B) 1 +B 1 +A 1 +1 + (A and B) 0 +B 0 +0 + (A or B) 1 +B 1 +1 + (A or B) 0 +B 0 +A 0 +0 diff --git a/Task/Short-circuit-evaluation/Java/short-circuit-evaluation.java b/Task/Short-circuit-evaluation/Java/short-circuit-evaluation.java new file mode 100644 index 0000000000..6bc71f06b6 --- /dev/null +++ b/Task/Short-circuit-evaluation/Java/short-circuit-evaluation.java @@ -0,0 +1,25 @@ +public class ShortCirc { + public static void main(String[] args){ + System.out.println("F and F = " + (a(false) && b(false)) + "\n"); + System.out.println("F or F = " + (a(false) || b(false)) + "\n"); + + System.out.println("F and T = " + (a(false) && b(true)) + "\n"); + System.out.println("F or T = " + (a(false) || b(true)) + "\n"); + + System.out.println("T and F = " + (a(true) && b(false)) + "\n"); + System.out.println("T or F = " + (a(true) || b(false)) + "\n"); + + System.out.println("T and T = " + (a(true) && b(true)) + "\n"); + System.out.println("T or T = " + (a(true) || b(true)) + "\n"); + } + + public static boolean a(boolean a){ + System.out.println("a"); + return a; + } + + public static boolean b(boolean b){ + System.out.println("b"); + return b; + } +} diff --git a/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia b/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia new file mode 100644 index 0000000000..a158c07445 --- /dev/null +++ b/Task/Short-circuit-evaluation/Julia/short-circuit-evaluation.julia @@ -0,0 +1,6 @@ +a(x) = (println(" # Called function a($x) -> $x"); return x) +b(x) = (println(" # Called function a($x) -> $x"); return x) +for i in [true,false], j in [true, false] + println("\nCalculating: x = a(i) && b(j)"); x = a(i) && b(j) + println("\nCalculating: y = a(i) || b(j)"); y = a(i) && b(j) +end diff --git a/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty b/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty new file mode 100644 index 0000000000..67046c98aa --- /dev/null +++ b/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty @@ -0,0 +1,35 @@ +print "AND" +for i = 0 to 1 + for j = 0 to 1 + print "a("; i; ") AND b( "; j; ")" + res =a( i) 'call always + if res <>0 then 'short circuit if 0 + res = b( j) + end if + print "=>",res + next +next + +print "---------------------------------" +print "OR" +for i = 0 to 1 + for j = 0 to 1 + print "a("; i; ") AND b("; j; ")" + res =a( i) 'call always + if res = 0 then 'short circuit if <>0 + res = b( j) + end if + print "=>", res + next +next + +'---------------------------------------- +function a( t) + print ,"calls func a" + a = t +end function + +function b( t) + print ,"calls func b" + b = t +end function diff --git a/Task/Short-circuit-evaluation/Logo/short-circuit-evaluation.logo b/Task/Short-circuit-evaluation/Logo/short-circuit-evaluation.logo new file mode 100644 index 0000000000..16b0b3426b --- /dev/null +++ b/Task/Short-circuit-evaluation/Logo/short-circuit-evaluation.logo @@ -0,0 +1,2 @@ +and [notequal? :x 0] [1/:x > 3] +(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y < 3]) diff --git a/Task/Short-circuit-evaluation/Lua/short-circuit-evaluation.lua b/Task/Short-circuit-evaluation/Lua/short-circuit-evaluation.lua new file mode 100644 index 0000000000..d4a3eaec0a --- /dev/null +++ b/Task/Short-circuit-evaluation/Lua/short-circuit-evaluation.lua @@ -0,0 +1,17 @@ +function a(i) + print "Function a(i) called." + return i +end + +function b(i) + print "Function b(i) called." + return i +end + +i = true +x = a(i) and b(i); print "" +y = a(i) or b(i); print "" + +i = false +x = a(i) and b(i); print "" +y = a(i) or b(i) diff --git a/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-1.m b/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-1.m new file mode 100644 index 0000000000..a2d9270cd7 --- /dev/null +++ b/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-1.m @@ -0,0 +1,11 @@ + function x=a(x) + printf('a: %i\n',x); + end; + function x=b(x) + printf('b: %i\n',x); + end; + + a(1) && b(1) + a(0) && b(1) + a(1) || b(1) + a(0) || b(1) diff --git a/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-2.m b/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-2.m new file mode 100644 index 0000000000..f8677eb205 --- /dev/null +++ b/Task/Short-circuit-evaluation/MATLAB/short-circuit-evaluation-2.m @@ -0,0 +1,10 @@ + > a(1) && b(1); + a: 1 + b: 1 + > a(0) && b(1); + a: 0 + > a(1) || b(1); + a: 1 + > a(0) || b(1); + a: 0 + b: 1 diff --git a/Task/Short-circuit-evaluation/MUMPS/short-circuit-evaluation.mumps b/Task/Short-circuit-evaluation/MUMPS/short-circuit-evaluation.mumps new file mode 100644 index 0000000000..6c5a1ba3a0 --- /dev/null +++ b/Task/Short-circuit-evaluation/MUMPS/short-circuit-evaluation.mumps @@ -0,0 +1,22 @@ +SSEVAL1(IN) + WRITE !,?10,$STACK($STACK,"PLACE") + QUIT IN +SSEVAL2(IN) + WRITE !,?10,$STACK($STACK,"PLACE") + QUIT IN +SSEVAL3 + NEW Z + WRITE "1 AND 1" + SET Z=$$SSEVAL1(1) SET:Z Z=Z&$$SSEVAL2(1) + WRITE !,$SELECT(Z:"TRUE",1:"FALSE") + WRITE !!,"0 AND 1" + SET Z=$$SSEVAL1(0) SET:Z Z=Z&$$SSEVAL2(1) + WRITE !,$SELECT(Z:"TRUE",1:"FALSE") + WRITE !!,"1 OR 1" + SET Z=$$SSEVAL1(1) SET:'Z Z=Z!$$SSEVAL2(1) + WRITE !,$SELECT(Z:"TRUE",1:"FALSE") + WRITE !!,"0 OR 1" + SET Z=$$SSEVAL1(0) SET:'Z Z=Z!$$SSEVAL2(1) + WRITE !,$SELECT(Z:"TRUE",1:"FALSE") + KILL Z + QUIT diff --git a/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-1.math b/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-1.math new file mode 100644 index 0000000000..436f8e66cc --- /dev/null +++ b/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-1.math @@ -0,0 +1,5 @@ +a[in_] := (Print["a"]; in) +b[in_] := (Print["b"]; in) + +a[False] && b[True] +a[True] || b[False] diff --git a/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-2.math b/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-2.math new file mode 100644 index 0000000000..76b6c9fcdd --- /dev/null +++ b/Task/Short-circuit-evaluation/Mathematica/short-circuit-evaluation-2.math @@ -0,0 +1 @@ +a[True] && b[False] diff --git a/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-1.nemerle b/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-1.nemerle new file mode 100644 index 0000000000..d3611d7ef8 --- /dev/null +++ b/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-1.nemerle @@ -0,0 +1,31 @@ +using System.Console; + +class ShortCircuit +{ + public static a(x : bool) : bool + { + WriteLine("a"); + x + } + + public static b(x : bool) : bool + { + WriteLine("b"); + x + } + + public static Main() : void + { + def t = true; + def f = false; + + WriteLine("True && True : {0}", a(t) && b(t)); + WriteLine("True && False: {0}", a(t) && b(f)); + WriteLine("False && True : {0}", a(f) && b(t)); + WriteLine("False && False: {0}", a(f) && b(f)); + WriteLine("True || True : {0}", a(t) || b(t)); + WriteLine("True || False: {0}", a(t) || b(f)); + WriteLine("False || True : {0}", a(f) || b(t)); + WriteLine("False || False: {0}", a(f) || b(f)); + } +} diff --git a/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-2.nemerle b/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-2.nemerle new file mode 100644 index 0000000000..72f5241ef6 --- /dev/null +++ b/Task/Short-circuit-evaluation/Nemerle/short-circuit-evaluation-2.nemerle @@ -0,0 +1,20 @@ +a +b +True && True : True +a +b +True && False: False +a +False && True : False +a +False && False: False +a +True || True : True +a +True || False: True +a +b +False || True : True +a +b +False || False: False diff --git a/Task/Short-circuit-evaluation/OCaml/short-circuit-evaluation.ocaml b/Task/Short-circuit-evaluation/OCaml/short-circuit-evaluation.ocaml new file mode 100644 index 0000000000..bb8446ecf1 --- /dev/null +++ b/Task/Short-circuit-evaluation/OCaml/short-circuit-evaluation.ocaml @@ -0,0 +1,24 @@ +let a r = print_endline " > function a called"; r +let b r = print_endline " > function b called"; r + +let test_and b1 b2 = + Printf.printf "# testing (%b && %b)\n" b1 b2; + ignore (a b1 && b b2) + +let test_or b1 b2 = + Printf.printf "# testing (%b || %b)\n" b1 b2; + ignore (a b1 || b b2) + +let test_this test = + test true true; + test true false; + test false true; + test false false; +;; + +let () = + print_endline "==== Testing and ===="; + test_this test_and; + print_endline "==== Testing or ===="; + test_this test_or; +;; diff --git a/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck b/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck new file mode 100644 index 0000000000..dfe0f7cd02 --- /dev/null +++ b/Task/Short-circuit-evaluation/Objeck/short-circuit-evaluation.objeck @@ -0,0 +1,27 @@ +bundle Default { + class ShortCircuit { + function : a(a : Bool) ~ Bool { + "a"->PrintLine(); + return a; + } + + function : b(b : Bool) ~ Bool { + "b"->PrintLine(); + return b; + } + + function : Main(args : String[]) ~ Nil { + IO.Console->Instance()->Print("F and F = ")->PrintLine(a(false) & b(false)); + IO.Console->Instance()->Print("F or F = ")->PrintLine(a(false) | b(false)); + + IO.Console->Instance()->Print("F and T = ")->PrintLine(a(false) & b(true)); + IO.Console->Instance()->Print("F or T = ")->PrintLine(a(false) | b(true)); + + IO.Console->Instance()->Print("T and F = ")->PrintLine(a(true) & b(false)); + IO.Console->Instance()->Print("T or F = ")->PrintLine(a(true) | b(false)); + + IO.Console->Instance()->Print("T and T = ")->PrintLine(a(true) & b(true)); + IO.Console->Instance()->Print("T or T = ")->PrintLine(a(true) | b(true)); + } + } +} diff --git a/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-1.oz b/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-1.oz new file mode 100644 index 0000000000..bce3ac7f44 --- /dev/null +++ b/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-1.oz @@ -0,0 +1,25 @@ +declare + fun {A Answer} + AnswerS = {Value.toVirtualString Answer 1 1} + in + {System.showInfo " % Called function {A "#AnswerS#"} -> "#AnswerS} + Answer + end + + fun {B Answer} + AnswerS = {Value.toVirtualString Answer 1 1} + in + {System.showInfo " % Called function {B "#AnswerS#"} -> "#AnswerS} + Answer + end +in + for I in [false true] do + for J in [false true] do + X Y + in + {System.showInfo "\nCalculating: X = {A I} andthen {B J}"} + X = {A I} andthen {B J} + {System.showInfo "Calculating: Y = {A I} orelse {B J}"} + Y = {A I} orelse {B J} + end + end diff --git a/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-2.oz b/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-2.oz new file mode 100644 index 0000000000..2f8f617ff5 --- /dev/null +++ b/Task/Short-circuit-evaluation/Oz/short-circuit-evaluation-2.oz @@ -0,0 +1,23 @@ +Calculating: X = {A I} andthen {B J} + % Called function {A false} -> false +Calculating: Y = {A I} orelse {B J} + % Called function {A false} -> false + % Called function {B false} -> false + +Calculating: X = {A I} andthen {B J} + % Called function {A false} -> false +Calculating: Y = {A I} orelse {B J} + % Called function {A false} -> false + % Called function {B true} -> true + +Calculating: X = {A I} andthen {B J} + % Called function {A true} -> true + % Called function {B false} -> false +Calculating: Y = {A I} orelse {B J} + % Called function {A true} -> true + +Calculating: X = {A I} andthen {B J} + % Called function {A true} -> true + % Called function {B true} -> true +Calculating: Y = {A I} orelse {B J} + % Called function {A true} -> true diff --git a/Task/Short-circuit-evaluation/PARI-GP/short-circuit-evaluation.pari b/Task/Short-circuit-evaluation/PARI-GP/short-circuit-evaluation.pari new file mode 100644 index 0000000000..d6931575a4 --- /dev/null +++ b/Task/Short-circuit-evaluation/PARI-GP/short-circuit-evaluation.pari @@ -0,0 +1,14 @@ +a(n)={ + print(a"("n")"); + a +}; +b(n)={ + print("b("n")"); + n +}; +or(A,B)={ + a(A) || b(B) +}; +and(A,B)={ + a(A) && b(B) +}; diff --git a/Task/Short-circuit-evaluation/PL-I/short-circuit-evaluation.pli b/Task/Short-circuit-evaluation/PL-I/short-circuit-evaluation.pli new file mode 100644 index 0000000000..74d5bcb9fd --- /dev/null +++ b/Task/Short-circuit-evaluation/PL-I/short-circuit-evaluation.pli @@ -0,0 +1,35 @@ +short_circuit_evaluation: + procedure options (main); + declare (true initial ('1'b), false initial ('0'b) ) bit (1); + declare (i, j, x, y) bit (1); + +a: procedure (bv) returns (bit(1)); + declare bv bit(1); + put ('Procedure ' || procedurename() || ' called.'); + return (bv); +end a; +b: procedure (bv) returns (bit(1)); + declare bv bit(1); + put ('Procedure ' || procedurename() || ' called.'); + return (bv); +end b; + + do i = true, false; + do j = true, false; + put skip(2) list ('Evaluating x with with ' || i || ' and with ' || j); + put skip; + if a(i) then + x = b(j); + else + x = false; + put skip data (x); + put skip(2) list ('Evaluating y with with ' || i || ' and with ' || j); + put skip; + if a(i) then + y = true; + else + y = b(j); + put skip data (y); + end; + end; +end short_circuit_evaluation; diff --git a/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-1.pascal b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-1.pascal new file mode 100644 index 0000000000..e8a0b4bc0f --- /dev/null +++ b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-1.pascal @@ -0,0 +1,41 @@ +program shortcircuit(output); + +function a(value: boolean): boolean; + begin + writeln('a(', value, ')'); + a := value + end; + +function b(value:boolean): boolean; + begin + writeln('b(', value, ')'); + b := value + end; + +procedure scandor(value1, value2: boolean); + var + result: boolean; + begin + {and} + if a(value1) + then + result := b(value2) + else + result := false; + writeln(value1, ' and ', value2, ' = ', result); + + {or} + if a(value1) + then + result := true + else + result := b(value2) + writeln(value1, ' or ', value2, ' = ', result); + end; + +begin + scandor(false, false); + scandor(false, true); + scandor(true, false); + scandor(true, true); +end. diff --git a/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-2.pascal b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-2.pascal new file mode 100644 index 0000000000..cabc469e37 --- /dev/null +++ b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-2.pascal @@ -0,0 +1,32 @@ +program shortcircuit; + +function a(value: boolean): boolean; + begin + writeln('a(', value, ')'); + a := value; + end; + +function b(value:boolean): boolean; + begin + writeln('b(', value, ')'); + b := value; + end; + +{$B-} {enable short circuit evaluation} +procedure scandor(value1, value2: boolean); + var + result: boolean; + begin + result := a(value1) and b(value); + writeln(value1, ' and ', value2, ' = ', result); + + result := a(value1) or b(value2); + writeln(value1, ' or ', value2, ' = ', result); + end; + +begin + scandor(false, false); + scandor(false, true); + scandor(true, false); + scandor(true, true); +end. diff --git a/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-3.pascal b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-3.pascal new file mode 100644 index 0000000000..2f5e52b0f7 --- /dev/null +++ b/Task/Short-circuit-evaluation/Pascal/short-circuit-evaluation-3.pascal @@ -0,0 +1,31 @@ +program shortcircuit(output); + +function a(value: boolean): boolean; + begin + writeln('a(', value, ')'); + a := value + end; + +function b(value:boolean): boolean; + begin + writeln('b(', value, ')'); + b := value + end; + +procedure scandor(value1, value2: boolean); + var + result: integer; + begin + result := a(value1) and_then b(value) + writeln(value1, ' and ', value2, ' = ', result); + + result := a(value1) or_else b(value2); + writeln(value1, ' or ', value2, ' = ', result) + end; + +begin + scandor(false, false); + scandor(false, true); + scandor(true, false); + scandor(true, true); +end. diff --git a/Task/Short-circuit-evaluation/Perl-6/short-circuit-evaluation.pl6 b/Task/Short-circuit-evaluation/Perl-6/short-circuit-evaluation.pl6 new file mode 100644 index 0000000000..ec267ad643 --- /dev/null +++ b/Task/Short-circuit-evaluation/Perl-6/short-circuit-evaluation.pl6 @@ -0,0 +1,11 @@ +sub a ($p) { print 'a'; $p } +sub b ($p) { print 'b'; $p } + +for '&&', '||' -> $op { + for True, False X True, False -> $p, $q { + my $s = "a($p) $op b($q)"; + print "$s: "; + eval $s; + print "\n"; + } +} diff --git a/Task/Short-circuit-evaluation/Perl/short-circuit-evaluation.pl b/Task/Short-circuit-evaluation/Perl/short-circuit-evaluation.pl new file mode 100644 index 0000000000..5fd2214cbd --- /dev/null +++ b/Task/Short-circuit-evaluation/Perl/short-circuit-evaluation.pl @@ -0,0 +1,14 @@ +sub a { print 'A'; return $_[0] } +sub b { print 'B'; return $_[0] } + +# Test-driver +sub test { + for my $op ('&&','||') { + for (qw(1,1 1,0 0,1 0,0)) { + my ($x,$y) = /(.),(.)/; + print my $str = "a($x) $op b($y)", ': '; + eval $str; print "\n"; } } +} + +# Test and display +test(); diff --git a/Task/Short-circuit-evaluation/PicoLisp/short-circuit-evaluation.l b/Task/Short-circuit-evaluation/PicoLisp/short-circuit-evaluation.l new file mode 100644 index 0000000000..38a4d637bd --- /dev/null +++ b/Task/Short-circuit-evaluation/PicoLisp/short-circuit-evaluation.l @@ -0,0 +1,14 @@ +(de a (F) + (msg 'a) + F ) + +(de b (F) + (msg 'b) + F ) + +(mapc + '((I J) + (for Op '(and or) + (println I Op J '-> (Op (a I) (b J))) ) ) + '(NIL NIL T T) + '(NIL T NIL T) ) diff --git a/Task/Short-circuit-evaluation/Pike/short-circuit-evaluation.pike b/Task/Short-circuit-evaluation/Pike/short-circuit-evaluation.pike new file mode 100644 index 0000000000..15a7ebc803 --- /dev/null +++ b/Task/Short-circuit-evaluation/Pike/short-circuit-evaluation.pike @@ -0,0 +1,20 @@ +int(0..1) a(int(0..1) i) +{ + write(" a\n"); + return i; +} + +int(0..1) b(int(0..1) i) +{ + write(" b\n"); + return i; +} + +foreach(({ ({ false, false }), ({ false, true }), ({ true, true }), ({ true, false }) });; array(int) args) +{ + write(" %d && %d\n", @args); + a(args[0]) && b(args[1]); + + write(" %d || %d\n", @args); + a(args[0]) || b(args[1]); +} diff --git a/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-1.pro b/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-1.pro new file mode 100644 index 0000000000..6881bf7318 --- /dev/null +++ b/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-1.pro @@ -0,0 +1,26 @@ +short_circuit :- + ( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl, + ( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_and_b(true, true)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_and_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_and_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl, + ( a_and_b(false, false)-> writeln('==> true'); writeln('==> false')) . + + +a_and_b(X, Y) :- + format('a(~w) and b(~w)~n', [X, Y]), + ( a(X), b(Y)). + +a_or_b(X, Y) :- + format('a(~w) or b(~w)~n', [X, Y]), + ( a(X); b(Y)). + +a(X) :- + format('a(~w)~n', [X]), + X. + +b(X) :- + format('b(~w)~n', [X]), + X. diff --git a/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-2.pro b/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-2.pro new file mode 100644 index 0000000000..c69fa53f30 --- /dev/null +++ b/Task/Short-circuit-evaluation/Prolog/short-circuit-evaluation-2.pro @@ -0,0 +1,38 @@ +?- short_circuit. +a(true) or b(true) +a(true) +==> true + +a(true) or b(false) +a(true) +==> true + +a(false) or b(true) +a(false) +b(true) +==> true + +a(false) or b(false) +a(false) +b(false) +==> false + +a(true) and b(true) +a(true) +b(true) +==> true + +a(true) and b(false) +a(true) +b(false) +==> false + +a(false) and b(true) +a(false) +==> false + +a(false) and b(false) +a(false) +==> false + +true. diff --git a/Task/Short-circuit-evaluation/PureBasic/short-circuit-evaluation.purebasic b/Task/Short-circuit-evaluation/PureBasic/short-circuit-evaluation.purebasic new file mode 100644 index 0000000000..693964d39b --- /dev/null +++ b/Task/Short-circuit-evaluation/PureBasic/short-circuit-evaluation.purebasic @@ -0,0 +1,20 @@ +Procedure a(arg) + PrintN(" # Called function a("+Str(arg)+")") + ProcedureReturn arg +EndProcedure + +Procedure b(arg) + PrintN(" # Called function b("+Str(arg)+")") + ProcedureReturn arg +EndProcedure + +OpenConsole() +For a=#False To #True + For b=#False To #True + PrintN(#CRLF$+"Calculating: x = a("+Str(a)+") And b("+Str(b)+")") + x= a(a) And b(b) + PrintN("Calculating: x = a("+Str(a)+") Or b("+Str(b)+")") + y= a(a) Or b(b) + Next +Next +Input() diff --git a/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-1.py b/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-1.py new file mode 100644 index 0000000000..9153eb5031 --- /dev/null +++ b/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-1.py @@ -0,0 +1,40 @@ +>>> def a(answer): + print(" # Called function a(%r) -> %r" % (answer, answer)) + return answer + +>>> def b(answer): + print(" # Called function b(%r) -> %r" % (answer, answer)) + return answer + +>>> for i in (False, True): + for j in (False, True): + print ("\nCalculating: x = a(i) and b(j)") + x = a(i) and b(j) + print ("Calculating: y = a(i) or b(j)") + y = a(i) or b(j) + + + +Calculating: x = a(i) and b(j) + # Called function a(False) -> False +Calculating: y = a(i) or b(j) + # Called function a(False) -> False + # Called function b(False) -> False + +Calculating: x = a(i) and b(j) + # Called function a(False) -> False +Calculating: y = a(i) or b(j) + # Called function a(False) -> False + # Called function b(True) -> True + +Calculating: x = a(i) and b(j) + # Called function a(True) -> True + # Called function b(False) -> False +Calculating: y = a(i) or b(j) + # Called function a(True) -> True + +Calculating: x = a(i) and b(j) + # Called function a(True) -> True + # Called function b(True) -> True +Calculating: y = a(i) or b(j) + # Called function a(True) -> True diff --git a/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-2.py b/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-2.py new file mode 100644 index 0000000000..829fbac19c --- /dev/null +++ b/Task/Short-circuit-evaluation/Python/short-circuit-evaluation-2.py @@ -0,0 +1,32 @@ +>>> for i in (False, True): + for j in (False, True): + print ("\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False") + x = b(j) if a(i) else False + print ("Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True") + y = b(j) if not a(i) else True + + + +Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False + # Called function a(False) -> False +Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True + # Called function a(False) -> False + # Called function b(False) -> False + +Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False + # Called function a(False) -> False +Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True + # Called function a(False) -> False + # Called function b(True) -> True + +Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False + # Called function a(True) -> True + # Called function b(False) -> False +Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True + # Called function a(True) -> True + +Calculating: x = a(i) and b(j) using x = b(j) if a(i) else False + # Called function a(True) -> True + # Called function b(True) -> True +Calculating: y = a(i) or b(j) using y = b(j) if not a(i) else True + # Called function a(True) -> True diff --git a/Task/Short-circuit-evaluation/R/short-circuit-evaluation-1.r b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-1.r new file mode 100644 index 0000000000..51c40eb272 --- /dev/null +++ b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-1.r @@ -0,0 +1,9 @@ +a <- function(x) {cat("a called\n"); x} +b <- function(x) {cat("b called\n"); x} + +tests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0)) + +invisible(apply(tests, 1, function(row) { + call <- substitute(op(a(x),b(y)), row) + cat(deparse(call), "->", eval(call), "\n\n") +})) diff --git a/Task/Short-circuit-evaluation/R/short-circuit-evaluation-2.r b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-2.r new file mode 100644 index 0000000000..c695a7568e --- /dev/null +++ b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-2.r @@ -0,0 +1,27 @@ +a called +a(1) || b(1) -> TRUE + +a called +b called +a(1) && b(1) -> TRUE + +a called +b called +a(0) || b(1) -> TRUE + +a called +a(0) && b(1) -> FALSE + +a called +a(1) || b(0) -> TRUE + +a called +b called +a(1) && b(0) -> FALSE + +a called +b called +a(0) || b(0) -> FALSE + +a called +a(0) && b(0) -> FALSE diff --git a/Task/Short-circuit-evaluation/R/short-circuit-evaluation-3.r b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-3.r new file mode 100644 index 0000000000..bd6be28628 --- /dev/null +++ b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-3.r @@ -0,0 +1,5 @@ +switchop <- function(s, x, y) { + if(s < 0) x || y + else if (s > 0) x && y + else xor(x, y) +} diff --git a/Task/Short-circuit-evaluation/R/short-circuit-evaluation-4.r b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-4.r new file mode 100644 index 0000000000..469c7bf3b4 --- /dev/null +++ b/Task/Short-circuit-evaluation/R/short-circuit-evaluation-4.r @@ -0,0 +1,14 @@ +> switchop(-1, a(1), b(1)) +a called +[1] TRUE +> switchop(1, a(1), b(1)) +a called +b called +[1] TRUE +> switchop(1, a(0), b(1)) +a called +[1] FALSE +> switchop(0, a(0), b(1)) +a called +b called +[1] TRUE diff --git a/Task/Short-circuit-evaluation/REXX/short-circuit-evaluation.rexx b/Task/Short-circuit-evaluation/REXX/short-circuit-evaluation.rexx new file mode 100644 index 0000000000..4e3ec8332f --- /dev/null +++ b/Task/Short-circuit-evaluation/REXX/short-circuit-evaluation.rexx @@ -0,0 +1,12 @@ +/*REXX programs demonstrates short-circuit evaulation testing. */ + + do i=-2 to 2 + x=a(i) & b(i) + y=a(i) + if \y then y=b(i) + say copies('─',30) 'x='||x 'y='y 'i='i + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +a: say 'A entered with:' arg(1);return abs(arg(1)//2) /*1=odd, 0=even */ +b: say 'B entered with:' arg(1);return arg(1)<0 /*1=neg, 0=if not*/ diff --git a/Task/Short-circuit-evaluation/Racket/short-circuit-evaluation.rkt b/Task/Short-circuit-evaluation/Racket/short-circuit-evaluation.rkt new file mode 100644 index 0000000000..67c14e59e5 --- /dev/null +++ b/Task/Short-circuit-evaluation/Racket/short-circuit-evaluation.rkt @@ -0,0 +1,18 @@ +#lang racket +(define (a x) + (display (~a "a:" x " ")) + x) + +(define (b x) + (display (~a "b:" x " ")) + x) + +(for* ([x '(#t #f)] + [y '(#t #f)]) + (displayln `(and (a ,x) (b ,y))) + (and (a x) (b y)) + (newline) + + (displayln `(or (a ,x) (b ,y))) + (or (a x) (b y)) + (newline)) diff --git a/Task/Short-circuit-evaluation/Ruby/short-circuit-evaluation.rb b/Task/Short-circuit-evaluation/Ruby/short-circuit-evaluation.rb new file mode 100644 index 0000000000..df6f678d61 --- /dev/null +++ b/Task/Short-circuit-evaluation/Ruby/short-circuit-evaluation.rb @@ -0,0 +1,18 @@ +def a( bool ) + puts "a( #{bool} ) called" + bool +end + +def b( bool ) + puts "b( #{bool} ) called" + bool +end + + [true, false].each do |a_val| + [true, false].each do |b_val| + puts "a( #{a_val} ) and b( #{b_val} ) is #{a( a_val ) and b( b_val )}." + puts + puts "a( #{a_val} ) or b( #{b_val} ) is #{a( a_val) or b( b_val )}." + puts + end + end diff --git a/Task/Short-circuit-evaluation/SNOBOL4/short-circuit-evaluation.sno b/Task/Short-circuit-evaluation/SNOBOL4/short-circuit-evaluation.sno new file mode 100644 index 0000000000..63e4c77ea7 --- /dev/null +++ b/Task/Short-circuit-evaluation/SNOBOL4/short-circuit-evaluation.sno @@ -0,0 +1,26 @@ + define('a(val)') :(a_end) +a out = 'A ' + eq(val,1) :s(return)f(freturn) +a_end + + define('b(val)') :(b_end) +b out = 'B ' + eq(val,1) :s(return)f(freturn) +b_end + +* # Test and display + &fullscan = 1 + output(.out,1,'-[-r1]') ;* Macro Spitbol +* output(.out,1,'B','-') ;* CSnobol + define('nl()'):(nlx);nl output = :(return);nlx + + out = 'T and T: '; null ? *a(1) *b(1); nl() + out = 'T and F: '; null ? *a(1) *b(0); nl() + out = 'F and T: '; null ? *a(0) *b(1); nl() + out = 'F and F: '; null ? *a(0) *b(0); nl() + output = + out = 'T or T: '; null ? *a(1) | *b(1); nl() + out = 'T or F: '; null ? *a(1) | *b(0); nl() + out = 'F or T: '; null ? *a(0) | *b(1); nl() + out = 'F or F: '; null ? *a(0) | *b(0); nl() +end diff --git a/Task/Short-circuit-evaluation/Sather/short-circuit-evaluation.sa b/Task/Short-circuit-evaluation/Sather/short-circuit-evaluation.sa new file mode 100644 index 0000000000..998caa4cd1 --- /dev/null +++ b/Task/Short-circuit-evaluation/Sather/short-circuit-evaluation.sa @@ -0,0 +1,26 @@ +class MAIN is + a(v:BOOL):BOOL is + #OUT + "executing a\n"; + return v; + end; + b(v:BOOL):BOOL is + #OUT + "executing b\n"; + return v; + end; + + main is + x:BOOL; + + x := a(false) and b(true); + #OUT + "F and T = " + x + "\n\n"; + + x := a(true) or b(true); + #OUT + "T or T = " + x + "\n\n"; + + x := a(true) and b(false); + #OUT + "T and T = " + x + "\n\n"; + + x := a(false) or b(true); + #OUT + "F or T = " + x + "\n\n"; + end; +end; diff --git a/Task/Short-circuit-evaluation/Scala/short-circuit-evaluation.scala b/Task/Short-circuit-evaluation/Scala/short-circuit-evaluation.scala new file mode 100644 index 0000000000..8f6a4043de --- /dev/null +++ b/Task/Short-circuit-evaluation/Scala/short-circuit-evaluation.scala @@ -0,0 +1,17 @@ +object ShortCircuit { + def a(b:Boolean)={print("Called A=%5b".format(b));b} + def b(b:Boolean)={print(" -> B=%5b".format(b));b} + + def main(args: Array[String]): Unit = { + val boolVals=List(false,true) + for(aa<-boolVals; bb<-boolVals){ + print("\nTesting A=%5b AND B=%5b -> ".format(aa, bb)) + a(aa) && b(bb) + } + for(aa<-boolVals; bb<-boolVals){ + print("\nTesting A=%5b OR B=%5b -> ".format(aa, bb)) + a(aa) || b(bb) + } + println + } +} diff --git a/Task/Short-circuit-evaluation/Scheme/short-circuit-evaluation.ss b/Task/Short-circuit-evaluation/Scheme/short-circuit-evaluation.ss new file mode 100644 index 0000000000..ed105219f8 --- /dev/null +++ b/Task/Short-circuit-evaluation/Scheme/short-circuit-evaluation.ss @@ -0,0 +1,34 @@ +>(define (a x) + (display "a\n") + x) +>(define (b x) + (display "b\n") + x) +>(for-each (lambda (i) + (for-each (lambda (j) + (display i) (display " and ") (display j) (newline) + (and (a i) (b j)) + (display i) (display " or ") (display j) (newline) + (or (a i) (b j)) + ) '(#t #f)) + ) '(#t #f)) +#t and #t +a +b +#t or #t +a +#t and #f +a +b +#t or #f +a +#f and #t +a +#f or #t +a +b +#f and #f +a +#f or #f +a +b diff --git a/Task/Short-circuit-evaluation/Seed7/short-circuit-evaluation.seed7 b/Task/Short-circuit-evaluation/Seed7/short-circuit-evaluation.seed7 new file mode 100644 index 0000000000..77b678465c --- /dev/null +++ b/Task/Short-circuit-evaluation/Seed7/short-circuit-evaluation.seed7 @@ -0,0 +1,31 @@ +$ include "seed7_05.s7i"; + +const func boolean: a (in boolean: aBool) is func + result + var boolean: result is FALSE; + begin + writeln("a"); + result := aBool; + end func; + +const func boolean: b (in boolean: aBool) is func + result + var boolean: result is FALSE; + begin + writeln("b"); + result := aBool; + end func; + +const proc: test (in boolean: param1, in boolean: param2) is func + begin + writeln(param1 <& " and " <& param2 <& " = " <& a(param1) and b(param2)); + writeln(param1 <& " or " <& param2 <& " = " <& a(param1) or b(param2)); + end func; + +const proc: main is func + begin + test(FALSE, FALSE); + test(FALSE, TRUE); + test(TRUE, FALSE); + test(TRUE, TRUE); + end func; diff --git a/Task/Short-circuit-evaluation/Smalltalk/short-circuit-evaluation.st b/Task/Short-circuit-evaluation/Smalltalk/short-circuit-evaluation.st new file mode 100644 index 0000000000..401c70d036 --- /dev/null +++ b/Task/Short-circuit-evaluation/Smalltalk/short-circuit-evaluation.st @@ -0,0 +1,21 @@ +Smalltalk at: #a put: nil. +Smalltalk at: #b put: nil. + +a := [:x| 'executing a' displayNl. x]. +b := [:x| 'executing b' displayNl. x]. + +('false and false = %1' % + { (a value: false) and: [ b value: false ] }) + displayNl. + +('true or false = %1' % + { (a value: true) or: [ b value: false ] }) + displayNl. + +('false or true = %1' % + { (a value: false) or: [ b value: true ] }) + displayNl. + +('true and false = %1' % + { (a value: true) and: [ b value: false ] }) + displayNl. diff --git a/Task/Short-circuit-evaluation/Standard-ML/short-circuit-evaluation.ml b/Task/Short-circuit-evaluation/Standard-ML/short-circuit-evaluation.ml new file mode 100644 index 0000000000..2736416e78 --- /dev/null +++ b/Task/Short-circuit-evaluation/Standard-ML/short-circuit-evaluation.ml @@ -0,0 +1,22 @@ +fun a r = ( print " > function a called\n"; r ) +fun b r = ( print " > function b called\n"; r ) + +fun test_and b1 b2 = ( + print ("# testing (" ^ Bool.toString b1 ^ " andalso " ^ Bool.toString b2 ^ ")\n"); + ignore (a b1 andalso b b2) ) + +fun test_or b1 b2 = ( + print ("# testing (" ^ Bool.toString b1 ^ " orelse " ^ Bool.toString b2 ^ ")\n"); + ignore (a b1 orelse b b2) ) + +fun test_this test = ( + test true true; + test true false; + test false true; + test false false ) +; + +print "==== Testing and ====\n"; +test_this test_and; +print "==== Testing or ====\n"; +test_this test_or; diff --git a/Task/Short-circuit-evaluation/TXR/short-circuit-evaluation.txr b/Task/Short-circuit-evaluation/TXR/short-circuit-evaluation.txr new file mode 100644 index 0000000000..15bb78dbe7 --- /dev/null +++ b/Task/Short-circuit-evaluation/TXR/short-circuit-evaluation.txr @@ -0,0 +1,35 @@ +@(define a (x out)) +@ (output) + a (@x) called +@ (end) +@ (bind out x) +@(end) +@(define b (x out)) +@ (output) + b (@x) called +@ (end) +@ (bind out x) +@(end) +@(define short_circuit_demo (i j)) +@ (output) +a(@i) and b(@j): +@ (end) +@ (maybe) +@ (a i "1") +@ (b j "1") +@ (end) +@ (output) +a(@i) or b(@j): +@ (end) +@ (cases) +@ (a i "1") +@ (or) +@ (b j "1") +@ (or) +@ (accept) +@ (end) +@(end) +@(short_circuit_demo "0" "0") +@(short_circuit_demo "0" "1") +@(short_circuit_demo "1" "0") +@(short_circuit_demo "1" "1") diff --git a/Task/Short-circuit-evaluation/Tcl/short-circuit-evaluation.tcl b/Task/Short-circuit-evaluation/Tcl/short-circuit-evaluation.tcl new file mode 100644 index 0000000000..adfb4b449b --- /dev/null +++ b/Task/Short-circuit-evaluation/Tcl/short-circuit-evaluation.tcl @@ -0,0 +1,19 @@ +package require Tcl 8.5 +proc tcl::mathfunc::a boolean { + puts "a($boolean) called" + return $boolean +} +proc tcl::mathfunc::b boolean { + puts "b($boolean) called" + return $boolean +} + +foreach i {false true} { + foreach j {false true} { + set x [expr {a($i) && b($j)}] + puts "x = a($i) && b($j) = $x" + set y [expr {a($i) || b($j)}] + puts "y = a($i) || b($j) = $y" + puts ""; # Blank line for clarity + } +} diff --git a/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-1.sh b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-1.sh new file mode 100644 index 0000000000..3eb793320a --- /dev/null +++ b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-1.sh @@ -0,0 +1,19 @@ +a() { + echo "Called a $1" + "$1" +} + +b() { + echo "Called b $1" + "$1" +} + +for i in false true; do + for j in false true; do + a $i && b $j && x=true || x=false + echo " $i && $j is $x" + + a $i || b $j && y=true || y=false + echo " $i || $j is $y" + done +done diff --git a/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-2.sh b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-2.sh new file mode 100644 index 0000000000..adfbce1a17 --- /dev/null +++ b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-2.sh @@ -0,0 +1,12 @@ +alias a eval \''echo "Called a \!:1"; "\!:1"'\' +alias b eval \''echo "Called b \!:1"; "\!:1"'\' + +foreach i (false true) + foreach j (false true) + a $i && b $j && set x=true || set x=false + echo " $i && $j is $x" + + a $i || b $j && set x=true || set x=false + echo " $i || $j is $x" + end +end diff --git a/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-3.sh b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-3.sh new file mode 100644 index 0000000000..e4837f53b6 --- /dev/null +++ b/Task/Short-circuit-evaluation/UNIX-Shell/short-circuit-evaluation-3.sh @@ -0,0 +1,8 @@ +# Succeeds, only prints "ok". +if ( 1 || { echo This command never runs. } ) echo ok + +# Fails, aborts shell with "bad: Undefined variable". +if ( 1 || $bad ) echo ok + +# Prints "error", then "ok". +if ( 1 || `echo error >/dev/stderr` ) echo ok diff --git a/Task/Show-the-epoch/0DESCRIPTION b/Task/Show-the-epoch/0DESCRIPTION new file mode 100644 index 0000000000..1b374aa928 --- /dev/null +++ b/Task/Show-the-epoch/0DESCRIPTION @@ -0,0 +1,3 @@ +Choose popular date libraries used by your language and show the [[wp:Epoch_(reference_date)#Computing|epoch]] those libraries use. A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. + +See also: [[Date format]] diff --git a/Task/Show-the-epoch/AWK/show-the-epoch.awk b/Task/Show-the-epoch/AWK/show-the-epoch.awk new file mode 100644 index 0000000000..3bd53e7454 --- /dev/null +++ b/Task/Show-the-epoch/AWK/show-the-epoch.awk @@ -0,0 +1,6 @@ +# syntax: GAWK -f SHOW_THE_EPOCH.AWK +# requires GNU Awk 4.0.1 or later +BEGIN { + print(strftime("%Y-%m-%d %H:%M:%S",0,1)) + exit(0) +} diff --git a/Task/Show-the-epoch/Ada/show-the-epoch.ada b/Task/Show-the-epoch/Ada/show-the-epoch.ada new file mode 100644 index 0000000000..abb45e91c4 --- /dev/null +++ b/Task/Show-the-epoch/Ada/show-the-epoch.ada @@ -0,0 +1,9 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Calendar; use Ada.Calendar; +with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; +with Ada.Calendar.Conversions; use Ada.Calendar.Conversions; +procedure ShowEpoch is + etime : Time := To_Ada_Time (0); +begin + Put_Line (Image (Date => etime)); +end ShowEpoch; diff --git a/Task/Show-the-epoch/BBC-BASIC/show-the-epoch.bbc b/Task/Show-the-epoch/BBC-BASIC/show-the-epoch.bbc new file mode 100644 index 0000000000..da89fa1316 --- /dev/null +++ b/Task/Show-the-epoch/BBC-BASIC/show-the-epoch.bbc @@ -0,0 +1,2 @@ + INSTALL @lib$+"DATELIB" + PRINT FN_date$(0, "dd-MMM-yyyy") diff --git a/Task/Show-the-epoch/C++/show-the-epoch-1.cpp b/Task/Show-the-epoch/C++/show-the-epoch-1.cpp new file mode 100644 index 0000000000..6db9095185 --- /dev/null +++ b/Task/Show-the-epoch/C++/show-the-epoch-1.cpp @@ -0,0 +1,10 @@ +#include +#include +#include +int main() +{ + std::chrono::system_clock::time_point epoch; + std::time_t t = std::chrono::system_clock::to_time_t(epoch); + std::cout << std::asctime(std::gmtime(&t)) << '\n'; + return 0; +} diff --git a/Task/Show-the-epoch/C++/show-the-epoch-2.cpp b/Task/Show-the-epoch/C++/show-the-epoch-2.cpp new file mode 100644 index 0000000000..67825fd099 --- /dev/null +++ b/Task/Show-the-epoch/C++/show-the-epoch-2.cpp @@ -0,0 +1,7 @@ +#include +#include +int main() +{ + std::cout << boost::posix_time::ptime( boost::posix_time::min_date_time ) << '\n'; + return 0; +} diff --git a/Task/Show-the-epoch/C/show-the-epoch-1.c b/Task/Show-the-epoch/C/show-the-epoch-1.c new file mode 100644 index 0000000000..29ce0b5d8b --- /dev/null +++ b/Task/Show-the-epoch/C/show-the-epoch-1.c @@ -0,0 +1,8 @@ +#include +#include + +int main() { + time_t t = 0; + printf("%s", asctime(gmtime(&t))); + return 0; +} diff --git a/Task/Show-the-epoch/C/show-the-epoch-2.c b/Task/Show-the-epoch/C/show-the-epoch-2.c new file mode 100644 index 0000000000..18321621e6 --- /dev/null +++ b/Task/Show-the-epoch/C/show-the-epoch-2.c @@ -0,0 +1,34 @@ +#include +#include +#include + +int +main() +{ + FILETIME ft = {dwLowDateTime: 0, dwHighDateTime: 0}; /* Epoch */ + SYSTEMTIME st; + wchar_t date[80], time[80]; + + /* + * Convert FILETIME (which counts 100-nanosecond intervals since + * the epoch) to SYSTEMTIME (which has year, month, and so on). + * + * The time is in UTC, because we never call + * SystemTimeToTzSpecificLocalTime() to convert it to local time. + */ + FileTimeToSystemTime(&ft, &st); + + /* + * Format SYSTEMTIME as a string. + */ + if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, + date, sizeof date / sizeof date[0]) == 0 || + GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, + time, sizeof time / sizeof time[0]) == 0) { + fwprintf(stderr, L"Error!\n"); + return 1; + } + + wprintf(L"FileTime epoch is %ls, at %ls (UTC).\n", date, time); + return 0; +} diff --git a/Task/Show-the-epoch/Common-Lisp/show-the-epoch.lisp b/Task/Show-the-epoch/Common-Lisp/show-the-epoch.lisp new file mode 100644 index 0000000000..6105805473 --- /dev/null +++ b/Task/Show-the-epoch/Common-Lisp/show-the-epoch.lisp @@ -0,0 +1,2 @@ +(multiple-value-bind (second minute hour day month year) (decode-universal-time 0 0) + (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second)) diff --git a/Task/Show-the-epoch/Dart/show-the-epoch.dart b/Task/Show-the-epoch/Dart/show-the-epoch.dart new file mode 100644 index 0000000000..0e28a9ec12 --- /dev/null +++ b/Task/Show-the-epoch/Dart/show-the-epoch.dart @@ -0,0 +1,3 @@ +main() { + print(new Date.fromEpoch(0,new TimeZone.utc())); +} diff --git a/Task/Show-the-epoch/Delphi/show-the-epoch.delphi b/Task/Show-the-epoch/Delphi/show-the-epoch.delphi new file mode 100644 index 0000000000..abf269266f --- /dev/null +++ b/Task/Show-the-epoch/Delphi/show-the-epoch.delphi @@ -0,0 +1,9 @@ +program ShowEpoch; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +begin + Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0)); +end. diff --git a/Task/Show-the-epoch/Forth/show-the-epoch.fth b/Task/Show-the-epoch/Forth/show-the-epoch.fth new file mode 100644 index 0000000000..2e52bbbb1f --- /dev/null +++ b/Task/Show-the-epoch/Forth/show-the-epoch.fth @@ -0,0 +1,2 @@ +include lib/longjday.4th +0 posix>jday .longjday cr diff --git a/Task/Show-the-epoch/Go/show-the-epoch.go b/Task/Show-the-epoch/Go/show-the-epoch.go new file mode 100644 index 0000000000..55f868137a --- /dev/null +++ b/Task/Show-the-epoch/Go/show-the-epoch.go @@ -0,0 +1,6 @@ +package main +import ("fmt"; "time") + +func main() { + fmt.Println(time.Time{}) +} diff --git a/Task/Show-the-epoch/Groovy/show-the-epoch.groovy b/Task/Show-the-epoch/Groovy/show-the-epoch.groovy new file mode 100644 index 0000000000..dd31857266 --- /dev/null +++ b/Task/Show-the-epoch/Groovy/show-the-epoch.groovy @@ -0,0 +1,4 @@ +def date = new Date(0) +def format = new java.text.SimpleDateFormat('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ') +format.timeZone = TimeZone.getTimeZone('UTC') +println (format.format(date)) diff --git a/Task/Show-the-epoch/Haskell/show-the-epoch-1.hs b/Task/Show-the-epoch/Haskell/show-the-epoch-1.hs new file mode 100644 index 0000000000..a7579ae5d5 --- /dev/null +++ b/Task/Show-the-epoch/Haskell/show-the-epoch-1.hs @@ -0,0 +1,3 @@ +import System.Time + +main = putStrLn $ calendarTimeToString $ toUTCTime $ TOD 0 0 diff --git a/Task/Show-the-epoch/Haskell/show-the-epoch-2.hs b/Task/Show-the-epoch/Haskell/show-the-epoch-2.hs new file mode 100644 index 0000000000..bb2d768147 --- /dev/null +++ b/Task/Show-the-epoch/Haskell/show-the-epoch-2.hs @@ -0,0 +1,3 @@ +import Data.Time + +main = print $ UTCTime (ModifiedJulianDay 0) 0 diff --git a/Task/Show-the-epoch/Icon/show-the-epoch.icon b/Task/Show-the-epoch/Icon/show-the-epoch.icon new file mode 100644 index 0000000000..5d43159a3c --- /dev/null +++ b/Task/Show-the-epoch/Icon/show-the-epoch.icon @@ -0,0 +1,12 @@ +link printf,datetime + +procedure main() + # Unicon + now := gettimeofday().sec + if now = &now then printf("&now and gettimeofday().sec are equal\n") + printf("Now (UTC) %s, (local) %s\n",gtime(now),ctime(now)) + printf("Epoch %s\n",gtime(0)) + # Icon and Unicon + now := DateToSec(&date) + ClockToSec(&clock) + printf("Now is also %s and %s\n",SecToDate(now),SecToDateLine(now)) +end diff --git a/Task/Show-the-epoch/J/show-the-epoch-1.j b/Task/Show-the-epoch/J/show-the-epoch-1.j new file mode 100644 index 0000000000..49902d558f --- /dev/null +++ b/Task/Show-the-epoch/J/show-the-epoch-1.j @@ -0,0 +1,2 @@ + 6!:0'' +2011 8 8 20 25 44.725 diff --git a/Task/Show-the-epoch/J/show-the-epoch-2.j b/Task/Show-the-epoch/J/show-the-epoch-2.j new file mode 100644 index 0000000000..a3cbfd852e --- /dev/null +++ b/Task/Show-the-epoch/J/show-the-epoch-2.j @@ -0,0 +1,3 @@ + require'dates' + todate 0 +1800 1 1 diff --git a/Task/Show-the-epoch/Java/show-the-epoch.java b/Task/Show-the-epoch/Java/show-the-epoch.java new file mode 100644 index 0000000000..8b164db473 --- /dev/null +++ b/Task/Show-the-epoch/Java/show-the-epoch.java @@ -0,0 +1,12 @@ +import java.text.DateFormat; +import java.util.Date; +import java.util.TimeZone; + +public class DateTest{ + public static void main(String[] args) { + Date date = new Date(0); + DateFormat format = DateFormat.getDateTimeInstance(); + format.setTimeZone(TimeZone.getTimeZone("UTC")); + System.out.println(format.format(date)); + } +} diff --git a/Task/Show-the-epoch/JavaScript/show-the-epoch.js b/Task/Show-the-epoch/JavaScript/show-the-epoch.js new file mode 100644 index 0000000000..1e99d07e72 --- /dev/null +++ b/Task/Show-the-epoch/JavaScript/show-the-epoch.js @@ -0,0 +1 @@ +document.write(new Date(0).toUTCString()); diff --git a/Task/Show-the-epoch/MATLAB/show-the-epoch.m b/Task/Show-the-epoch/MATLAB/show-the-epoch.m new file mode 100644 index 0000000000..07aba00932 --- /dev/null +++ b/Task/Show-the-epoch/MATLAB/show-the-epoch.m @@ -0,0 +1,5 @@ +d = [0,1,2,3.5,-3.5,1000*365,1000*366,now+[-1,0,1]]; +for k=1:length(d) + printf('day %f\t%s\n',d(k),datestr(d(k),0)) + disp(datevec(d(k))) +end; diff --git a/Task/Show-the-epoch/Mathematica/show-the-epoch.math b/Task/Show-the-epoch/Mathematica/show-the-epoch.math new file mode 100644 index 0000000000..da362dd8ef --- /dev/null +++ b/Task/Show-the-epoch/Mathematica/show-the-epoch.math @@ -0,0 +1 @@ +DateString[0] diff --git a/Task/Show-the-epoch/Maxima/show-the-epoch.maxima b/Task/Show-the-epoch/Maxima/show-the-epoch.maxima new file mode 100644 index 0000000000..81c3744a1e --- /dev/null +++ b/Task/Show-the-epoch/Maxima/show-the-epoch.maxima @@ -0,0 +1,2 @@ +timedate(0); +"1900-01-01 10:00:00+10:00" diff --git a/Task/Show-the-epoch/NetRexx/show-the-epoch.netrexx b/Task/Show-the-epoch/NetRexx/show-the-epoch.netrexx new file mode 100644 index 0000000000..9980d49e0a --- /dev/null +++ b/Task/Show-the-epoch/NetRexx/show-the-epoch.netrexx @@ -0,0 +1,10 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.text.DateFormat + +edate = Date(0) +zulu = DateFormat.getDateTimeInstance() +zulu.setTimeZone(TimeZone.getTimeZone('UTC')) +say zulu.format(edate) +return diff --git a/Task/Show-the-epoch/NewLISP/show-the-epoch.newlisp b/Task/Show-the-epoch/NewLISP/show-the-epoch.newlisp new file mode 100644 index 0000000000..ee5fb699f7 --- /dev/null +++ b/Task/Show-the-epoch/NewLISP/show-the-epoch.newlisp @@ -0,0 +1,2 @@ +(date 0) +->"Thu Jan 01 01:00:00 1970" diff --git a/Task/Show-the-epoch/OCaml/show-the-epoch.ocaml b/Task/Show-the-epoch/OCaml/show-the-epoch.ocaml new file mode 100644 index 0000000000..cae55252ea --- /dev/null +++ b/Task/Show-the-epoch/OCaml/show-the-epoch.ocaml @@ -0,0 +1,8 @@ +open Unix + +let months = [| "January"; "February"; "March"; "April"; "May"; "June"; + "July"; "August"; "September"; "October"; "November"; "December" |] + +let () = + let t = Unix.gmtime 0.0 in + Printf.printf "%s %d, %d\n" months.(t.tm_mon) t.tm_mday (1900 + t.tm_year) diff --git a/Task/Show-the-epoch/Objective-C/show-the-epoch.m b/Task/Show-the-epoch/Objective-C/show-the-epoch.m new file mode 100644 index 0000000000..d27fca0a74 --- /dev/null +++ b/Task/Show-the-epoch/Objective-C/show-the-epoch.m @@ -0,0 +1,14 @@ +#import + +int main(int argc, const char *argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSDate *t = [NSDate dateWithTimeIntervalSinceReferenceDate:0]; + NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; + [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; + [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"]; + NSLog(@"%@", [dateFormatter stringFromDate:t]); + + [pool release]; + return 0; +} diff --git a/Task/Show-the-epoch/PHP/show-the-epoch.php b/Task/Show-the-epoch/PHP/show-the-epoch.php new file mode 100644 index 0000000000..e4c7bdcd96 --- /dev/null +++ b/Task/Show-the-epoch/PHP/show-the-epoch.php @@ -0,0 +1,3 @@ + diff --git a/Task/Show-the-epoch/PL-I/show-the-epoch.pli b/Task/Show-the-epoch/PL-I/show-the-epoch.pli new file mode 100644 index 0000000000..0ea5e5d952 --- /dev/null +++ b/Task/Show-the-epoch/PL-I/show-the-epoch.pli @@ -0,0 +1,4 @@ +show_epoch: procedure options (main); /* 14 Sept. 2012 */ + put (datetime('DDMmmYYYY')); + put (time()); +end show_epoch; diff --git a/Task/Show-the-epoch/Pascal/show-the-epoch.pascal b/Task/Show-the-epoch/Pascal/show-the-epoch.pascal new file mode 100644 index 0000000000..66a2f58297 --- /dev/null +++ b/Task/Show-the-epoch/Pascal/show-the-epoch.pascal @@ -0,0 +1,9 @@ +Program ShowEpoch; + +uses + SysUtils; + +begin + Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now)); + Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0)); +end. diff --git a/Task/Show-the-epoch/Perl-6/show-the-epoch.pl6 b/Task/Show-the-epoch/Perl-6/show-the-epoch.pl6 new file mode 100644 index 0000000000..415af9625a --- /dev/null +++ b/Task/Show-the-epoch/Perl-6/show-the-epoch.pl6 @@ -0,0 +1 @@ +say DateTime.new(0) diff --git a/Task/Show-the-epoch/Perl/show-the-epoch.pl b/Task/Show-the-epoch/Perl/show-the-epoch.pl new file mode 100644 index 0000000000..665d9ac096 --- /dev/null +++ b/Task/Show-the-epoch/Perl/show-the-epoch.pl @@ -0,0 +1 @@ +print scalar gmtime 0, "\n"; diff --git a/Task/Show-the-epoch/PicoLisp/show-the-epoch.l b/Task/Show-the-epoch/PicoLisp/show-the-epoch.l new file mode 100644 index 0000000000..0e20f85d6e --- /dev/null +++ b/Task/Show-the-epoch/PicoLisp/show-the-epoch.l @@ -0,0 +1,2 @@ +: (date 1) +-> (0 3 1) # Year zero, March 1st diff --git a/Task/Show-the-epoch/PowerShell/show-the-epoch.psh b/Task/Show-the-epoch/PowerShell/show-the-epoch.psh new file mode 100644 index 0000000000..e2888eb91e --- /dev/null +++ b/Task/Show-the-epoch/PowerShell/show-the-epoch.psh @@ -0,0 +1 @@ +[datetime] 0 diff --git a/Task/Show-the-epoch/PureBasic/show-the-epoch.purebasic b/Task/Show-the-epoch/PureBasic/show-the-epoch.purebasic new file mode 100644 index 0000000000..5bb1d05276 --- /dev/null +++ b/Task/Show-the-epoch/PureBasic/show-the-epoch.purebasic @@ -0,0 +1,6 @@ +If OpenConsole() + PrintN(FormatDate("Y = %yyyy M = %mm D = %dd, %hh:%ii:%ss", 0)) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Show-the-epoch/Python/show-the-epoch.py b/Task/Show-the-epoch/Python/show-the-epoch.py new file mode 100644 index 0000000000..8e74e73b14 --- /dev/null +++ b/Task/Show-the-epoch/Python/show-the-epoch.py @@ -0,0 +1,4 @@ +>>> import time +>>> time.asctime(time.gmtime(0)) +'Thu Jan 1 00:00:00 1970' +>>> diff --git a/Task/Show-the-epoch/R/show-the-epoch.r b/Task/Show-the-epoch/R/show-the-epoch.r new file mode 100644 index 0000000000..73c5f5436f --- /dev/null +++ b/Task/Show-the-epoch/R/show-the-epoch.r @@ -0,0 +1,4 @@ +> epoch <- 0 +> class(epoch) <- class(Sys.time()) +> format(epoch, "%Y-%m-%d %H:%M:%S %Z") +[1] "1970-01-01 00:00:00 UTC" diff --git a/Task/Show-the-epoch/REXX/show-the-epoch.rexx b/Task/Show-the-epoch/REXX/show-the-epoch.rexx new file mode 100644 index 0000000000..7ae795cc81 --- /dev/null +++ b/Task/Show-the-epoch/REXX/show-the-epoch.rexx @@ -0,0 +1,11 @@ +/*REXX program shows the # of days since the epoch for the DATE function*/ + +say ' today is' date() /*today's is format: mm MON YYYY */ + +days=date('Basedate') /*only 1st char of option is used*/ +say right(days,35) "days since the REXX base date of January 1st, year 1" + +say 'and today is:' date(,days,'B') /*this should be today (still). */ + + /*──────── The above statement is only valid for the newer REXXes,*/ + /*──────── older versions don't support the 2nd and 3rd arguments.*/ diff --git a/Task/Show-the-epoch/Racket/show-the-epoch.rkt b/Task/Show-the-epoch/Racket/show-the-epoch.rkt new file mode 100644 index 0000000000..9cc10a56f2 --- /dev/null +++ b/Task/Show-the-epoch/Racket/show-the-epoch.rkt @@ -0,0 +1,3 @@ +#lang racket +(require racket/date) +(date->string (seconds->date 0 #f)) diff --git a/Task/Show-the-epoch/Ruby/show-the-epoch.rb b/Task/Show-the-epoch/Ruby/show-the-epoch.rb new file mode 100644 index 0000000000..e626bc433b --- /dev/null +++ b/Task/Show-the-epoch/Ruby/show-the-epoch.rb @@ -0,0 +1,2 @@ +irb(main):001:0> Time.at(0).utc +=> 1970-01-01 00:00:00 UTC diff --git a/Task/Show-the-epoch/Run-BASIC/show-the-epoch.run b/Task/Show-the-epoch/Run-BASIC/show-the-epoch.run new file mode 100644 index 0000000000..1aaaed752c --- /dev/null +++ b/Task/Show-the-epoch/Run-BASIC/show-the-epoch.run @@ -0,0 +1,3 @@ +eDate$ = date$("01/01/0001") +cDate$ = date$(0) ' 01/01/1901 +sDate$ = date$("01/01/1970") diff --git a/Task/Show-the-epoch/Scala/show-the-epoch.scala b/Task/Show-the-epoch/Scala/show-the-epoch.scala new file mode 100644 index 0000000000..723840a9b3 --- /dev/null +++ b/Task/Show-the-epoch/Scala/show-the-epoch.scala @@ -0,0 +1,6 @@ +import java.util.{Date, TimeZone, Locale} +import java.text.DateFormat + +val df=DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH) +df.setTimeZone(TimeZone.getTimeZone("UTC")) +println(df.format(new Date(0))) diff --git a/Task/Show-the-epoch/Seed7/show-the-epoch.seed7 b/Task/Show-the-epoch/Seed7/show-the-epoch.seed7 new file mode 100644 index 0000000000..a0ed5aa8d3 --- /dev/null +++ b/Task/Show-the-epoch/Seed7/show-the-epoch.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "time.s7i"; + +const proc: main is func + begin + writeln(time.value); + end func; diff --git a/Task/Show-the-epoch/Standard-ML/show-the-epoch.ml b/Task/Show-the-epoch/Standard-ML/show-the-epoch.ml new file mode 100644 index 0000000000..e3daf966a2 --- /dev/null +++ b/Task/Show-the-epoch/Standard-ML/show-the-epoch.ml @@ -0,0 +1,2 @@ +- Date.toString (Date.fromTimeUniv Time.zeroTime); +val it = "Thu Jan 1 00:00:00 1970" : string diff --git a/Task/Show-the-epoch/TUSCRIPT/show-the-epoch.tuscript b/Task/Show-the-epoch/TUSCRIPT/show-the-epoch.tuscript new file mode 100644 index 0000000000..ddd754bb15 --- /dev/null +++ b/Task/Show-the-epoch/TUSCRIPT/show-the-epoch.tuscript @@ -0,0 +1,10 @@ +$$ MODE TUSCRIPT +- epoch +number=1 +dayofweeknr=DATE (date,day,month,year,number) +epoch=JOIN(year,"-",month,day) +PRINT "epoch: ", epoch," (daynumber ",number,")" +- today's daynumber +dayofweeknr=DATE (today,day,month,year,number) +date=JOIN (year,"-",month,day) +PRINT "today's date: ", date," (daynumber ", number,")" diff --git a/Task/Show-the-epoch/Tcl/show-the-epoch.tcl b/Task/Show-the-epoch/Tcl/show-the-epoch.tcl new file mode 100644 index 0000000000..a567fbc32e --- /dev/null +++ b/Task/Show-the-epoch/Tcl/show-the-epoch.tcl @@ -0,0 +1,2 @@ +% clock format 0 -gmt 1 +Thu Jan 01 00:00:00 GMT 1970 diff --git a/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh new file mode 100644 index 0000000000..fab910f3c4 --- /dev/null +++ b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh @@ -0,0 +1,2 @@ +$ date -ur 0 +Thu Jan 1 00:00:00 UTC 1970 diff --git a/Task/Show-the-epoch/Visual-Basic/show-the-epoch.vb b/Task/Show-the-epoch/Visual-Basic/show-the-epoch.vb new file mode 100644 index 0000000000..14af38b16a --- /dev/null +++ b/Task/Show-the-epoch/Visual-Basic/show-the-epoch.vb @@ -0,0 +1,3 @@ +Sub Main() + Debug.Print Format(0, "dd mmm yyyy hh:mm") +End Sub diff --git a/Task/Sierpinski-carpet/0DESCRIPTION b/Task/Sierpinski-carpet/0DESCRIPTION new file mode 100644 index 0000000000..7541748723 --- /dev/null +++ b/Task/Sierpinski-carpet/0DESCRIPTION @@ -0,0 +1,32 @@ +Produce a graphical or ASCII-art representation of a [[wp:Sierpinski carpet|Sierpinski carpet]] of order N. For example, the Sierpinski carpet of order 3 should look like this: +
###########################
+# ## ## ## ## ## ## ## ## #
+###########################
+###   ######   ######   ###
+# #   # ## #   # ## #   # #
+###   ######   ######   ###
+###########################
+# ## ## ## ## ## ## ## ## #
+###########################
+#########         #########
+# ## ## #         # ## ## #
+#########         #########
+###   ###         ###   ###
+# #   # #         # #   # #
+###   ###         ###   ###
+#########         #########
+# ## ## #         # ## ## #
+#########         #########
+###########################
+# ## ## ## ## ## ## ## ## #
+###########################
+###   ######   ######   ###
+# #   # ## #   # ## #   # #
+###   ######   ######   ###
+###########################
+# ## ## ## ## ## ## ## ## #
+###########################
+ +The use of # characters is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. + +See also [[Sierpinski triangle]] diff --git a/Task/Sierpinski-carpet/1META.yaml b/Task/Sierpinski-carpet/1META.yaml new file mode 100644 index 0000000000..bf76cfa1e6 --- /dev/null +++ b/Task/Sierpinski-carpet/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Fractals diff --git a/Task/Sierpinski-carpet/ALGOL-68/sierpinski-carpet.alg b/Task/Sierpinski-carpet/ALGOL-68/sierpinski-carpet.alg new file mode 100644 index 0000000000..0ca176a033 --- /dev/null +++ b/Task/Sierpinski-carpet/ALGOL-68/sierpinski-carpet.alg @@ -0,0 +1,29 @@ +PROC in carpet = (INT in x, in y)BOOL: ( + INT x := in x, y := in y; + BOOL out; + DO + IF x = 0 OR y = 0 THEN + out := TRUE; GO TO stop iteration + ELIF x MOD 3 = 1 AND y MOD 3 = 1 THEN + out := FALSE; GO TO stop iteration + FI; + + x %:= 3; + y %:= 3 + OD; + stop iteration: out +); + +PROC carpet = (INT n)VOID: + FOR i TO 3 ** n DO + FOR j TO 3 ** n DO + IF in carpet(i-1, j-1) THEN + print("* ") + ELSE + print(" ") + FI + OD; + print(new line) + OD; + +carpet(3) diff --git a/Task/Sierpinski-carpet/AWK/sierpinski-carpet.awk b/Task/Sierpinski-carpet/AWK/sierpinski-carpet.awk new file mode 100644 index 0000000000..f7634094b0 --- /dev/null +++ b/Task/Sierpinski-carpet/AWK/sierpinski-carpet.awk @@ -0,0 +1,64 @@ +# WSC.AWK - Waclaw Sierpinski's carpet contributed by Dan Nielsen +# +# syntax: GAWK -f WSC.AWK [-v o={a|A}{b|B}] [-v X=anychar] iterations +# +# -v o=ab default +# a|A loose weave | tight weave +# b|B don't show | show how the carpet is built +# -v X=? Carpet is built with X's. The character assigned to X replaces all X's. +# +# iterations +# The number of iterations. The default is 0 which produces one carpet. +# +# what is the difference between a loose weave and a tight weave: +# loose tight +# X X X X X X X X X XXXXXXXXX +# X X X X X X X XX XX X +# X X X X X X X X X XXXXXXXXX +# X X X X X X XXX XXX +# X X X X X X X X +# X X X X X X XXX XXX +# X X X X X X X X X XXXXXXXXX +# X X X X X X X XX XX X +# X X X X X X X X X XXXXXXXXX +# +# examples: +# GAWK -f WSC.AWK 2 +# GAWK -f WSC.AWK -v o=Ab -v X=# 2 +# GAWK -f WSC.AWK -v o=Ab -v X=\xDB 2 +# +BEGIN { + optns = (o == "") ? "ab" : o + n = ARGV[1] + 0 # iterations + if (n !~ /^[0-9]+$/) { exit(1) } + seed = (optns ~ /A/) ? "XXX,X X,XXX" : "X X X ,X X ,X X X " # tight/loose weave + leng = row = split(seed,A,",") # seed the array + for (i=1; i<=n; i++) { # build carpet + for (a=1; a<=3; a++) { + row = 0 + for (b=1; b<=3; b++) { + for (c=1; c<=leng; c++) { + row++ + tmp = (a == 2 && b == 2) ? sprintf("%*s",length(A[c]),"") : A[c] + B[row] = B[row] tmp + } + if (optns ~ /B/) { # show how the carpet is built + if (max_row < row+0) { max_row = row } + for (r=1; r<=max_row; r++) { + printf("i=%d row=%02d a=%d b=%d '%s'\n",i,r,a,b,B[r]) + } + print("") + } + } + } + leng = row + for (j=1; j<=row; j++) { A[j] = B[j] } # re-seed the array + for (j in B) { delete B[j] } # delete work array + } + for (j=1; j<=row; j++) { # print carpet + if (X != "") { gsub(/X/,substr(X,1,1),A[j]) } + sub(/ +$/,"",A[j]) + printf("%s\n",A[j]) + } + exit(0) +} diff --git a/Task/Sierpinski-carpet/Ada/sierpinski-carpet.ada b/Task/Sierpinski-carpet/Ada/sierpinski-carpet.ada new file mode 100644 index 0000000000..1de0331b5e --- /dev/null +++ b/Task/Sierpinski-carpet/Ada/sierpinski-carpet.ada @@ -0,0 +1,76 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Sierpinski_Carpet is + subtype Index_Type is Integer range 1..81; + type Pattern_Array is array(Index_Type range <>, Index_Type range <>) of Boolean; + Pattern : Pattern_Array(1..81,1..81) := (Others =>(others => true)); + procedure Clear_Center(P : in out Pattern_Array; X1 : Index_Type; X2 : Index_Type; + Y1 : Index_Type; Y2 : Index_Type) is + Xfirst : Index_Type; + Xlast : Index_Type; + Yfirst : Index_Type; + Ylast : Index_Type; + Diff : Integer; + begin + Xfirst :=(X2 - X1 + 1) / 3 + X1; + Diff := Xfirst - X1; + Xlast := Xfirst + Diff; + Yfirst := (Y2 - Y1) / 3 + Y1; + YLast := YFirst + Diff; + + for I in XFirst..XLast loop + for J in YFirst..YLast loop + P(I, J) := False; + end loop; + end loop; + end Clear_Center; + + procedure Print(P : Pattern_Array) is + begin + for I in P'range(1) loop + for J in P'range(2) loop + if P(I,J) then + Put('*'); + else + Put(' '); + end if; + end loop; + New_Line; + end loop; + end Print; + + procedure Divide_Square(P : in out Pattern_Array; Order : Positive) is + Factor : Natural := 0; + X1, X2 : Index_Type; + Y1, Y2 : Index_Type; + Division : Index_Type; + Num_Sections : Index_Type; + begin + while Factor < Order loop + Num_Sections := 3**Factor; + Factor := Factor + 1; + X1 := P'First; + Division := P'Last / Num_Sections; + X2 := Division; + Y1 := X1; + Y2 := X2; + loop + loop + Clear_Center(P, X1, X2, Y1, Y2); + exit when X2 = P'Last; + X1 := X2; + X2 := X2 + Division; + end loop; + exit when Y2 = P'Last; + Y1 := Y2; + Y2 := Y2 + Division; + X1 := P'First; + X2 := Division; + end loop; + end loop; + end Divide_Square; + +begin + Divide_Square(Pattern, 3); + Print(Pattern); +end Sierpinski_Carpet; diff --git a/Task/Sierpinski-carpet/Asymptote/sierpinski-carpet.asymptote b/Task/Sierpinski-carpet/Asymptote/sierpinski-carpet.asymptote new file mode 100644 index 0000000000..cae76192db --- /dev/null +++ b/Task/Sierpinski-carpet/Asymptote/sierpinski-carpet.asymptote @@ -0,0 +1,50 @@ +path across(path p, real node) { + return + point(p, node + 1/3) + point(p, node - 1/3) - point(p, node); +} + +path corner_subquad(path p, real node) { + return + point(p, node) -- + point(p, node + 1/3) -- + across(p, node) -- + point(p, node - 1/3) -- + cycle; +} + +path noncorner_subquad(path p, real node1, real node2) { + return + point(p, node1 + 1/3) -- + across(p, node1) -- + across(p, node2) -- + point(p, node2 - 1/3) -- + cycle; +} + +void carpet(path p, int order) { + if (order == 0) + fill(p); + else { + for (real node : sequence(0, 3)) { + carpet(corner_subquad(p, node), order - 1); + carpet(noncorner_subquad(p, node, node + 1), order - 1); + } + } +} + +path q = + // A square + unitsquare + // An oblong rhombus + // (0, 0) -- (5, 3) -- (0, 6) -- (-5, 3) -- cycle + // A trapezoid + // (0, 0) -- (4, 2) -- (6, 2) -- (10, 0) -- cycle + // A less regular quadrilateral + // (0, 0) -- (4, 1) -- (9, -4) -- (1, -1) -- cycle + // A concave shape + // (0, 0) -- (5, 3) -- (10, 0) -- (5, 1) -- cycle + ; + +size(9 inches, 6 inches); + +carpet(q, 5); diff --git a/Task/Sierpinski-carpet/AutoHotkey/sierpinski-carpet.ahk b/Task/Sierpinski-carpet/AutoHotkey/sierpinski-carpet.ahk new file mode 100644 index 0000000000..2f94b1a1f5 --- /dev/null +++ b/Task/Sierpinski-carpet/AutoHotkey/sierpinski-carpet.ahk @@ -0,0 +1,20 @@ +Loop 4 + MsgBox % Carpet(A_Index) + +Carpet(n) { + Loop % 3**n { + x := A_Index-1 + Loop % 3**n + t .= Dot(x,A_Index-1) + t .= "`n" + } + Return t +} + +Dot(x,y) { + While x>0 && y>0 + If (mod(x,3)=1 && mod(y,3)=1) + Return " " + Else x //= 3, y //= 3 + Return "." +} diff --git a/Task/Sierpinski-carpet/BBC-BASIC/sierpinski-carpet.bbc b/Task/Sierpinski-carpet/BBC-BASIC/sierpinski-carpet.bbc new file mode 100644 index 0000000000..9b83f4a952 --- /dev/null +++ b/Task/Sierpinski-carpet/BBC-BASIC/sierpinski-carpet.bbc @@ -0,0 +1,18 @@ + Order% = 3 + side% = 3^Order% + VDU 23,22,8*side%;8*side%;64,64,16,128 + FOR Y% = 0 TO side%-1 + FOR X% = 0 TO side%-1 + IF FNincarpet(X%,Y%) PLOT X%*16,Y%*16+15 + NEXT + NEXT Y% + REPEAT WAIT 1 : UNTIL FALSE + END + + DEF FNincarpet(X%,Y%) + REPEAT + IF X% MOD 3 = 1 IF Y% MOD 3 = 1 THEN = FALSE + X% DIV= 3 + Y% DIV= 3 + UNTIL X%=0 AND Y%=0 + = TRUE diff --git a/Task/Sierpinski-carpet/C/sierpinski-carpet-1.c b/Task/Sierpinski-carpet/C/sierpinski-carpet-1.c new file mode 100644 index 0000000000..4789e1ce3d --- /dev/null +++ b/Task/Sierpinski-carpet/C/sierpinski-carpet-1.c @@ -0,0 +1,21 @@ +#include + +int main() +{ + int i, j, dim, d; + int depth = 3; + + for (i = 0, dim = 1; i < depth; i++, dim *= 3); + + for (i = 0; i < dim; i++) { + for (j = 0; j < dim; j++) { + for (d = dim / 3; d; d /= 3) + if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1) + break; + printf(d ? " " : "##"); + } + printf("\n"); + } + + return 0; +} diff --git a/Task/Sierpinski-carpet/C/sierpinski-carpet-2.c b/Task/Sierpinski-carpet/C/sierpinski-carpet-2.c new file mode 100644 index 0000000000..d37b2201c5 --- /dev/null +++ b/Task/Sierpinski-carpet/C/sierpinski-carpet-2.c @@ -0,0 +1,92 @@ +#include +#include +#include + +typedef struct sCarpet { + int dim; // dimension + char *data; // character data + char **rows; // pointers to data rows +} *Carpet; + +/* Clones a tile into larger carpet, or blank if center */ +void TileCarpet( Carpet d, int r, int c, Carpet tile ) +{ + int y0 = tile->dim*r; + int x0 = tile->dim*c; + int k,m; + + if ((r==1) && (c==1)) { + for(k=0; k < tile->dim; k++) { + for (m=0; m < tile->dim; m++) { + d->rows[y0+k][x0+m] = ' '; + } + } + } + else { + for(k=0; k < tile->dim; k++) { + for (m=0; m < tile->dim; m++) { + d->rows[y0+k][x0+m] = tile->rows[k][m]; + } + } + } +} + +/* define a 1x1 starting carpet */ +static char s1[]= "#"; +static char *r1[] = {s1}; +static struct sCarpet single = { 1, s1, r1}; + +Carpet Sierpinski( int n ) +{ + Carpet carpet; + Carpet subCarpet; + int row,col, rb; + int spc_rqrd; + + subCarpet = (n > 1) ? Sierpinski(n-1) : &single; + + carpet = malloc(sizeof(struct sCarpet)); + carpet->dim = 3*subCarpet->dim; + spc_rqrd = (2*subCarpet->dim) * (carpet->dim); + carpet->data = malloc(spc_rqrd*sizeof(char)); + carpet->rows = malloc( carpet->dim*sizeof(char *)); + for (row=0; rowdim; row++) { + carpet->rows[row] = carpet->data + row*carpet->dim; + rb = row+subCarpet->dim; + carpet->rows[rb] = carpet->data + rb*carpet->dim; + rb = row+2*subCarpet->dim; + carpet->rows[rb] = carpet->data + row*carpet->dim; + } + + for (col=0; col < 3; col++) { + /* 2 rows of tiles to copy - third group points to same data a first */ + for (row=0; row < 2; row++) + TileCarpet( carpet, row, col, subCarpet ); + } + if (subCarpet != &single ) { + free(subCarpet->rows); + free(subCarpet->data); + free(subCarpet); + } + + return carpet; +} + +void CarpetPrint( FILE *fout, Carpet carp) +{ + char obuf[730]; + int row; + for (row=0; row < carp->dim; row++) { + strncpy(obuf, carp->rows[row], carp->dim); + fprintf(fout, "%s\n", obuf); + } + fprintf(fout,"\n"); +} + +int main(int argc, char *argv[]) +{ +// FILE *f = fopen("sierp.txt","w"); + CarpetPrint(stdout, Sierpinski(3)); +// fclose(f); + return 0; +} diff --git a/Task/Sierpinski-carpet/C/sierpinski-carpet-3.c b/Task/Sierpinski-carpet/C/sierpinski-carpet-3.c new file mode 100644 index 0000000000..0f393e8d34 --- /dev/null +++ b/Task/Sierpinski-carpet/C/sierpinski-carpet-3.c @@ -0,0 +1,81 @@ +#include +#include + +typedef struct _PartialGrid{ + char** base; + int xbegin, xend, ybegin, yend; // yend strictly not used +} PartialGrid; + +void sierpinski_hollow(PartialGrid G){ + int len = G.xend - G.xbegin+1; + int unit = len/3; + for(int i = G.xbegin+unit; i nextCarpet(a[n - 1]))(); + writefln("%-(%s\n%)", c.dropExactly(3).front); +} diff --git a/Task/Sierpinski-carpet/DWScript/sierpinski-carpet.dwscript b/Task/Sierpinski-carpet/DWScript/sierpinski-carpet.dwscript new file mode 100644 index 0000000000..603fecd690 --- /dev/null +++ b/Task/Sierpinski-carpet/DWScript/sierpinski-carpet.dwscript @@ -0,0 +1,28 @@ +function InCarpet(x, y : Integer) : Boolean; +begin + while (x<>0) and (y<>0) do begin + if ((x mod 3)=1) and ((y mod 3)=1) then + Exit(False); + x := x div 3; + y := y div 3; + end; + Result := True; +end; + +procedure Carpet(n : Integer); +var + i, j, p : Integer; +begin + p := Round(IntPower(3, n)); + + for i:=0 to p-1 do begin + for j:=0 to p-1 do begin + if InCarpet(i, j) then + Print('#') + else Print(' '); + end; + PrintLn(''); + end; +end; + +Carpet(3); diff --git a/Task/Sierpinski-carpet/E/sierpinski-carpet.e b/Task/Sierpinski-carpet/E/sierpinski-carpet.e new file mode 100644 index 0000000000..8843beed78 --- /dev/null +++ b/Task/Sierpinski-carpet/E/sierpinski-carpet.e @@ -0,0 +1,19 @@ +def inCarpet(var x, var y) { + while (x > 0 && y > 0) { + if (x %% 3 <=> 1 && y %% 3 <=> 1) { + return false + } + x //= 3 + y //= 3 + } + return true +} + +def carpet(order) { + for y in 0..!(3**order) { + for x in 0..!(3**order) { + print(inCarpet(x, y).pick("#", " ")) + } + println() + } +} diff --git a/Task/Sierpinski-carpet/Fan/sierpinski-carpet.fan b/Task/Sierpinski-carpet/Fan/sierpinski-carpet.fan new file mode 100644 index 0000000000..9c9976f24d --- /dev/null +++ b/Task/Sierpinski-carpet/Fan/sierpinski-carpet.fan @@ -0,0 +1,40 @@ +** +** Generates a square Sierpinski gasket +** +class SierpinskiCarpet +{ + public static Bool inCarpet(Int x, Int y){ + while(x!=0 && y!=0){ + if (x % 3 == 1 && y % 3 == 1) + return false; + x /= 3; + y /= 3; + } + return true; + } + + static Int pow(Int n, Int exp) + { + rslt := 1 + exp.times { rslt *= n } + return rslt + } + + public static Void carpet(Int n){ + for(i := 0; i < pow(3, n); i++){ + buf := StrBuf() + for(j := 0; j < pow(3, n); j++){ + if( inCarpet(i, j)) + buf.add("*"); + else + buf.add(" "); + } + echo(buf); + } + } + + Void main() + { + carpet(4) + } +} diff --git a/Task/Sierpinski-carpet/Forth/sierpinski-carpet.fth b/Task/Sierpinski-carpet/Forth/sierpinski-carpet.fth new file mode 100644 index 0000000000..6111532782 --- /dev/null +++ b/Task/Sierpinski-carpet/Forth/sierpinski-carpet.fth @@ -0,0 +1,16 @@ +\ Generates a square Sierpinski gasket +: 1? over 3 mod 1 = ; ( n1 n2 -- n1 n2 f) +: 3/ 3 / swap ; ( n1 n2 -- n2/3 n1) + \ is this cell in the carpet? +: incarpet ( n1 n2 -- f) + begin over over or while 1? 1? and if 2drop false exit then 3/ 3/ repeat + 2drop true \ return true if in the carpet +; + \ draw a carpet of n size +: carpet ( n --) + 1 swap 0 ?do 3 * loop dup \ calculate power of 3 + 0 ?do dup 0 ?do i j incarpet if [char] # else bl then emit loop cr loop + drop \ evaluate every cell in the carpet +; + +cr 4 carpet diff --git a/Task/Sierpinski-carpet/Fortran/sierpinski-carpet.f b/Task/Sierpinski-carpet/Fortran/sierpinski-carpet.f new file mode 100644 index 0000000000..20560eb811 --- /dev/null +++ b/Task/Sierpinski-carpet/Fortran/sierpinski-carpet.f @@ -0,0 +1,42 @@ +program Sierpinski_carpet + implicit none + + call carpet(4) + +contains + +function In_carpet(a, b) + logical :: in_carpet + integer, intent(in) :: a, b + integer :: x, y + + x = a ; y = b + do + if(x == 0 .or. y == 0) then + In_carpet = .true. + return + else if(mod(x, 3) == 1 .and. mod(y, 3) == 1) then + In_carpet = .false. + return + end if + x = x / 3 + y = y / 3 + end do +end function + +subroutine Carpet(n) + integer, intent(in) :: n + integer :: i, j + + do i = 0, 3**n - 1 + do j = 0, 3**n - 1 + if(In_carpet(i, j)) then + write(*, "(a)", advance="no") "#" + else + write(*, "(a)", advance="no") " " + end if + end do + write(*,*) + end do +end subroutine Carpet +end program Sierpinski_carpet diff --git a/Task/Sierpinski-carpet/Go/sierpinski-carpet.go b/Task/Sierpinski-carpet/Go/sierpinski-carpet.go new file mode 100644 index 0000000000..1e736df3b2 --- /dev/null +++ b/Task/Sierpinski-carpet/Go/sierpinski-carpet.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +var order = 3 +var grain = "#" + +func main() { + carpet := []string{grain} + for ; order > 0; order-- { + // repeat expression allows for multiple character + // grain and for multi-byte UTF-8 characters. + hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0])) + middle := make([]string, len(carpet)) + for i, s := range carpet { + middle[i] = s + hole + s + carpet[i] = strings.Repeat(s, 3) + } + carpet = append(append(carpet, middle...), carpet...) + } + for _, r := range carpet { + fmt.Println(r) + } +} diff --git a/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-1.groovy b/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-1.groovy new file mode 100644 index 0000000000..f31ddba509 --- /dev/null +++ b/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-1.groovy @@ -0,0 +1,19 @@ +def base3 = { BigInteger i -> i.toString(3) } + +def sierpinskiCarpet = { int order -> + StringBuffer sb = new StringBuffer() + def positions = 0..<(3**order) + def digits = 0..<([order,1].max()) + + positions.each { i -> + String i3 = base3(i).padLeft(order, '0') + + positions.each { j -> + String j3 = base3(j).padLeft(order, '0') + + sb << (digits.any{ i3[it] == '1' && j3[it] == '1' } ? ' ' : order.toString().padRight(2) ) + } + sb << '\n' + } + sb.toString() +} diff --git a/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-2.groovy b/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-2.groovy new file mode 100644 index 0000000000..4b9d62b9d9 --- /dev/null +++ b/Task/Sierpinski-carpet/Groovy/sierpinski-carpet-2.groovy @@ -0,0 +1 @@ +(0..4).each { println sierpinskiCarpet(it) } diff --git a/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-1.hs b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-1.hs new file mode 100644 index 0000000000..26a386caa4 --- /dev/null +++ b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-1.hs @@ -0,0 +1,16 @@ +inCarpet :: Int -> Int -> Bool +inCarpet 0 _ = True +inCarpet _ 0 = True +inCarpet x y = not ((xr == 1) && (yr == 1)) && inCarpet xq yq + where ((xq, xr), (yq, yr)) = (x `divMod` 3, y `divMod` 3) + +carpet :: Int -> [String] +carpet n = map + (zipWith + (\x y -> if inCarpet x y then '#' else ' ') + [0..3^n-1] + . repeat) + [0..3^n-1] + +printCarpet :: Int -> IO () +printCarpet = mapM_ putStrLn . carpet diff --git a/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-2.hs b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-2.hs new file mode 100644 index 0000000000..cfe6d3e902 --- /dev/null +++ b/Task/Sierpinski-carpet/Haskell/sierpinski-carpet-2.hs @@ -0,0 +1,10 @@ +nextCarpet :: [String] -> [String] +nextCarpet carpet = border ++ map f carpet ++ border + where border = map (concat . replicate 3) carpet + f x = x ++ map (const ' ') x ++ x + +sierpinskiCarpet :: Int -> [String] +sierpinskiCarpet n = iterate nextCarpet ["#"] !! n + +main :: IO () +main = mapM_ putStrLn $ sierpinskiCarpet 3 diff --git a/Task/Sierpinski-carpet/Icon/sierpinski-carpet.icon b/Task/Sierpinski-carpet/Icon/sierpinski-carpet.icon new file mode 100644 index 0000000000..e59873c4e1 --- /dev/null +++ b/Task/Sierpinski-carpet/Icon/sierpinski-carpet.icon @@ -0,0 +1,24 @@ +$define FILLER "*" # the filler character + +procedure main(A) + + width := 3 ^ ( order := (0 < \A[1]) | 3 ) + write("Carpet order= ",order) + + every !(canvas := list(width)) := list(width," ") # prime the canvas + + every y := 1 to width & x := 1 to width do # traverse it + if IsFilled(x-1,y-1) then canvas[x,y] := FILLER # fill + + every x := 1 to width & y := 1 to width do + writes((y=1,"\n")|"",canvas[x,y]," ") # print +end + +procedure IsFilled(x,y) # succeed if x,y should be filled + while x ~= 0 & y ~= 0 do { + if x % 3 = y %3 = 1 then fail + x /:= 3 + y /:=3 + } + return +end diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-1.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-1.j new file mode 100644 index 0000000000..ee47b613c1 --- /dev/null +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-1.j @@ -0,0 +1,2 @@ +N=:3 +(a:(<1;1)}3 3$<)^:N' ' diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j new file mode 100644 index 0000000000..47a6f121b8 --- /dev/null +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j @@ -0,0 +1 @@ +((#:7 5 7){_2{.<)^:N' ' diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j new file mode 100644 index 0000000000..2672852bbb --- /dev/null +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j @@ -0,0 +1,10 @@ + ' #'{~(#:7 5 7) ,/@(1 3 ,/"2@|: */)^:N ,.1 +######### +# ## ## # +######### +### ### +# # # # +### ### +######### +# ## ## # +######### diff --git a/Task/Sierpinski-carpet/Java/sierpinski-carpet.java b/Task/Sierpinski-carpet/Java/sierpinski-carpet.java new file mode 100644 index 0000000000..87176aa82a --- /dev/null +++ b/Task/Sierpinski-carpet/Java/sierpinski-carpet.java @@ -0,0 +1,19 @@ +public static boolean inCarpet(long x, long y) { + while (x!=0 && y!=0) { + if (x % 3 == 1 && y % 3 == 1) + return false; + x /= 3; + y /= 3; + } + return true; +} + +public static void carpet(final int n) { + final double power = Math.pow(3,n); + for(long i = 0; i < power; i++) { + for(long j = 0; j < power; j++) { + System.out.print(inCarpet(i, j) ? "*" : " "); + } + System.out.println(); + } +} diff --git a/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet.js b/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet.js new file mode 100644 index 0000000000..494d05cd74 --- /dev/null +++ b/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet.js @@ -0,0 +1,72 @@ + + + + +Sierpinski Carpet + + + + + +

+
+ + + + + diff --git a/Task/Sierpinski-carpet/Liberty-BASIC/sierpinski-carpet.liberty b/Task/Sierpinski-carpet/Liberty-BASIC/sierpinski-carpet.liberty new file mode 100644 index 0000000000..4a2095dac9 --- /dev/null +++ b/Task/Sierpinski-carpet/Liberty-BASIC/sierpinski-carpet.liberty @@ -0,0 +1,45 @@ +NoMainWin +WindowWidth = 508 +WindowHeight = 575 +Open "Sierpinski Carpets" For Graphics_nsb_nf As #g +#g "Down; TrapClose [halt]" + +'labels +#g "Place 90 15;\Order 0" +#g "Place 340 15;\Order 1" +#g "Place 90 286;\Order 2" +#g "Place 340 286;\Order 3" +'carpets +Call carpet 5, 20, 243, 0 +Call carpet 253, 20, 243, 1 +Call carpet 5, 293, 243, 2 +Call carpet 253, 293, 243, 3 +#g "Flush" +Wait + +[halt] +Close #g +End + +Sub carpet x, y, size, order + #g "Color 0 0 128; BackColor 0 0 128" + #g "Place ";x;" ";y + #g "BoxFilled ";x+size-1;" ";y+size-1 + #g "Color white; BackColor white" + side = Int(size/3) + newX = x+side + newY = y+side + #g "Place ";newX;" ";newY + #g "BoxFilled ";newX+side-1;" ";newY+side-1 + order = order - 1 + If order > -1 Then + Call carpet newX-side, newY-side+1, side, order + Call carpet newX, newY-side+1, side, order + Call carpet newX+side, newY-side+1, side, order + Call carpet newX+side, newY, side, order + Call carpet newX+side, newY+side, side, order + Call carpet newX, newY+side, side, order + Call carpet newX-side, newY+side, side, order + Call carpet newX-side, newY, side, order + End If +End Sub diff --git a/Task/Sierpinski-carpet/Mathematica/sierpinski-carpet.math b/Task/Sierpinski-carpet/Mathematica/sierpinski-carpet.math new file mode 100644 index 0000000000..38ca34e8b4 --- /dev/null +++ b/Task/Sierpinski-carpet/Mathematica/sierpinski-carpet.math @@ -0,0 +1,4 @@ +full={{1,1,1},{1,0,1},{1,1,1}} +empty={{0,0,0},{0,0,0},{0,0,0}} +n=3; +Grid[Nest[ArrayFlatten[#/.{0->empty,1->full}]&,{{1}},n]//.{0->" ",1->"#"}] diff --git a/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-1.ocaml b/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-1.ocaml new file mode 100644 index 0000000000..0427c2918d --- /dev/null +++ b/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-1.ocaml @@ -0,0 +1,18 @@ +let rec in_carpet x y = + if x = 0 || y = 0 then true + else if x mod 3 = 1 && y mod 3 = 1 then false + else in_carpet (x / 3) (y / 3) + +(* I define my own operator for integer exponentiation *) +let rec (^:) a b = + if b = 0 then 1 + else if b mod 2 = 0 then let x = a ^: (b / 2) in x * x + else a * (a ^: (b - 1)) + +let carpet n = + for i = 0 to (3 ^: n) - 1 do + for j = 0 to (3 ^: n) - 1 do + print_char (if in_carpet i j then '*' else ' ') + done; + print_newline () + done diff --git a/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-2.ocaml b/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-2.ocaml new file mode 100644 index 0000000000..cbc53b86b4 --- /dev/null +++ b/Task/Sierpinski-carpet/OCaml/sierpinski-carpet-2.ocaml @@ -0,0 +1,14 @@ +let nextCarpet carpet = + List.map (fun x -> x ^ x ^ x) carpet @ + List.map (fun x -> x ^ String.make (String.length x) ' ' ^ x) carpet @ + List.map (fun x -> x ^ x ^ x) carpet + +let rec sierpinskiCarpet n = + let rec aux n carpet = + if n = 0 then carpet + else aux (n-1) (nextCarpet carpet) + in + aux n ["#"] + +let () = + List.iter print_endline (sierpinskiCarpet 3) diff --git a/Task/Sierpinski-carpet/Order/sierpinski-carpet.order b/Task/Sierpinski-carpet/Order/sierpinski-carpet.order new file mode 100644 index 0000000000..a290fcfe86 --- /dev/null +++ b/Task/Sierpinski-carpet/Order/sierpinski-carpet.order @@ -0,0 +1,39 @@ +#include + +#define ORDER_PP_DEF_8in_carpet ORDER_PP_FN( \ +8fn(8X, 8Y, \ + 8if(8or(8is_0(8X), 8is_0(8Y)), \ + 8true, \ + 8let((8Q, 8quotient(8X, 3)) \ + (8R, 8remainder(8X, 3)) \ + (8S, 8quotient(8Y, 3)) \ + (8T, 8remainder(8Y, 3)), \ + 8and(8not(8and(8equal(8R, 1), 8equal(8T, 1))), \ + 8in_carpet(8Q, 8S))))) ) + +#define ORDER_PP_DEF_8carpet ORDER_PP_FN( \ +8fn(8N, \ + 8lets((8R, 8seq_iota(0, 8pow(3, 8N))) \ + (8G, 8seq_map(8fn(8Y, 8seq_map(8fn(8X, 8pair(8X, 8Y)), \ + 8R)), \ + 8R)), \ + 8seq_map(8fn(8S, 8seq_map(8fn(8P, 8apply(8in_carpet, 8P)), \ + 8S)), \ + 8G))) ) + +#define ORDER_PP_DEF_8carpet_to_string ORDER_PP_FN( \ +8fn(8C, \ + 8seq_fold( \ + 8fn(8R, 8S, \ + 8adjoin(8R, \ + 8seq_fold(8fn(8P, 8B, 8adjoin(8P, 8if(8B, 8("#"), 8(" ")))), \ + 8nil, 8S), \ + 8("\n"))), \ + 8nil, 8C)) ) + +#include + +int main(void) { + printf(ORDER_PP( 8carpet_to_string(8carpet(3)) )); + return 0; +} diff --git a/Task/Sierpinski-carpet/Oz/sierpinski-carpet.oz b/Task/Sierpinski-carpet/Oz/sierpinski-carpet.oz new file mode 100644 index 0000000000..3f2dac183c --- /dev/null +++ b/Task/Sierpinski-carpet/Oz/sierpinski-carpet.oz @@ -0,0 +1,22 @@ +declare + %% A carpet is a list of lines. + fun {NextCarpet Carpet} + {Flatten + [{Map Carpet XXX} + {Map Carpet X_X} + {Map Carpet XXX} + ]} + end + + fun {XXX X} X#X#X end + fun {X_X X} X#{Spaces {VirtualString.length X}}#X end + fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end + + fun lazy {Iterate F X} + X|{Iterate F {F X}} + end + + SierpinskiCarpets = {Iterate NextCarpet ["#"]} +in + %% print all lines of the Sierpinski carpet of order 3 + {ForAll {Nth SierpinskiCarpets 4} System.showInfo} diff --git a/Task/Sierpinski-carpet/Pascal/sierpinski-carpet.pascal b/Task/Sierpinski-carpet/Pascal/sierpinski-carpet.pascal new file mode 100644 index 0000000000..d1dec4027e --- /dev/null +++ b/Task/Sierpinski-carpet/Pascal/sierpinski-carpet.pascal @@ -0,0 +1,51 @@ +Program SierpinskiCarpet; + +uses + Math; + +function In_carpet(a, b: longint): boolean; + + var + x, y: longint; + + begin + x := a; + y := b; + while true do + begin + if (x = 0) or (y = 0) then + begin + In_carpet := true; + break; + end + else + if ( (x mod 3) = 1 ) and ((y mod 3) = 1) then + begin + In_carpet := false; + break; + end; + x := x div 3; + y := y div 3; + end; + end; + +procedure Carpet(n: integer); + + var + i, j: longint; + + begin + for i := 0 to 3**n - 1 do + begin + for j := 0 to 3**n - 1 do + if In_carpet(i, j) then + write('*') + else + write(' '); + writeln; + end; + end; + +begin + Carpet(3); +end. diff --git a/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-1.pl6 b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-1.pl6 new file mode 100644 index 0000000000..b7cc419383 --- /dev/null +++ b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-1.pl6 @@ -0,0 +1,10 @@ +sub carpet +{ + (['#'], -> @c { + [ @c.map({$_ x 3}), + @c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}), + @c.map({$_ x 3}) ] + } ... *).map: { .join("\n") }; +} + +say carpet[3]; diff --git a/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-2.pl6 b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-2.pl6 new file mode 100644 index 0000000000..01a642c27d --- /dev/null +++ b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet-2.pl6 @@ -0,0 +1,9 @@ +sub weave ( @c ) {[ + @c.map({ $_ x 3 }), + @c.map({ $_ ~ .trans( '#' => ' ' ) ~ $_ }), + @c.map({ $_ x 3 }), +]} + +my @carpet := ( ['#'], &weave ... * ).map: { .join: "\n" }; + +say @carpet[3]; diff --git a/Task/Sierpinski-carpet/Perl/sierpinski-carpet.pl b/Task/Sierpinski-carpet/Perl/sierpinski-carpet.pl new file mode 100644 index 0000000000..6b98572bbd --- /dev/null +++ b/Task/Sierpinski-carpet/Perl/sierpinski-carpet.pl @@ -0,0 +1,4 @@ +my @c = '##'; +@c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c)) + for 1 .. 3; +print join("\n", @c), "\n"; diff --git a/Task/Sierpinski-carpet/PicoLisp/sierpinski-carpet.l b/Task/Sierpinski-carpet/PicoLisp/sierpinski-carpet.l new file mode 100644 index 0000000000..2378379934 --- /dev/null +++ b/Task/Sierpinski-carpet/PicoLisp/sierpinski-carpet.l @@ -0,0 +1,12 @@ +(de carpet (N) + (let Carpet '("#") + (do N + (setq Carpet + (conc + (mapcar '((S) (pack S S S)) Carpet) + (mapcar + '((S) (pack S (replace (chop S) "#" " ") S)) + Carpet ) + (mapcar '((S) (pack S S S)) Carpet) ) ) ) ) ) + +(mapc prinl (carpet 3)) diff --git a/Task/Sierpinski-carpet/PostScript/sierpinski-carpet.ps b/Task/Sierpinski-carpet/PostScript/sierpinski-carpet.ps new file mode 100644 index 0000000000..dc6258790a --- /dev/null +++ b/Task/Sierpinski-carpet/PostScript/sierpinski-carpet.ps @@ -0,0 +1,20 @@ +%!PS-Adobe-3.0 +%%BoundingBox 0 0 300 300 + +/r { moveto 0 -1 1 0 0 1 3 { rlineto } repeat closepath fill } def +/serp { gsave + 3 1 roll translate + 1 3 div dup scale + 1 1 r + dup 1 sub dup 0 eq not { + 0 0 0 1 0 2 1 0 1 2 2 0 2 1 2 2 17 -1 roll 8 { serp } repeat + } if pop + grestore +} def + +300 300 scale 0 0 r 1 setgray + +0 0 5 serp + +pop showpage +%%EOF diff --git a/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh b/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh new file mode 100644 index 0000000000..89f83e6560 --- /dev/null +++ b/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh @@ -0,0 +1,19 @@ +function inCarpet($x, $y) { + while ($x -ne 0 -and $y -ne 0) { + if ($x % 3 -eq 1 -and $y % 3 -eq 1) { + return " " + } + $x = [Math]::Truncate($x / 3) + $y = [Math]::Truncate($y / 3) + } + return "█" +} + +function carpet($n) { + for ($y = 0; $y -lt [Math]::Pow(3, $n); $y++) { + for ($x = 0; $x -lt [Math]::Pow(3, $n); $x++) { + Write-Host -NoNewline (inCarpet $x $y) + } + Write-Host + } +} diff --git a/Task/Sierpinski-carpet/PureBasic/sierpinski-carpet.purebasic b/Task/Sierpinski-carpet/PureBasic/sierpinski-carpet.purebasic new file mode 100644 index 0000000000..1c8003bf5e --- /dev/null +++ b/Task/Sierpinski-carpet/PureBasic/sierpinski-carpet.purebasic @@ -0,0 +1,23 @@ +Procedure in_carpet(x,y) + While x>0 And y>0 + If x%3=1 And y%3=1 + ProcedureReturn #False + EndIf + y/3: x/3 + Wend + ProcedureReturn #True +EndProcedure + +Procedure carpet(n) + Define i, j, l=Pow(3,n)-1 + For i=0 To l + For j=0 To l + If in_carpet(i,j) + Print("#") + Else + Print(" ") + EndIf + Next + PrintN("") + Next +EndProcedure diff --git a/Task/Sierpinski-carpet/Python/sierpinski-carpet-1.py b/Task/Sierpinski-carpet/Python/sierpinski-carpet-1.py new file mode 100644 index 0000000000..ab2df41f36 --- /dev/null +++ b/Task/Sierpinski-carpet/Python/sierpinski-carpet-1.py @@ -0,0 +1,18 @@ +def in_carpet(x, y): + while True: + if x == 0 or y == 0: + return True + elif x % 3 == 1 and y % 3 == 1: + return False + + x /= 3 + y /= 3 + +def carpet(n): + for i in xrange(3 ** n): + for j in xrange(3 ** n): + if in_carpet(i, j): + print '*', + else: + print ' ', + print diff --git a/Task/Sierpinski-carpet/Python/sierpinski-carpet-2.py b/Task/Sierpinski-carpet/Python/sierpinski-carpet-2.py new file mode 100644 index 0000000000..6b71fa22f9 --- /dev/null +++ b/Task/Sierpinski-carpet/Python/sierpinski-carpet-2.py @@ -0,0 +1,9 @@ +def sierpinski_carpet(n): + carpet = ["#"] + for i in xrange(n): + carpet = [x + x + x for x in carpet] + \ + [x + x.replace("#"," ") + x for x in carpet] + \ + [x + x + x for x in carpet] + return "\n".join(carpet) + +print sierpinski_carpet(3) diff --git a/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx new file mode 100644 index 0000000000..a2862f5dc2 --- /dev/null +++ b/Task/Sierpinski-carpet/REXX/sierpinski-carpet.rexx @@ -0,0 +1,31 @@ +/*REXX program draws any order Sierpinski carpet up to order 15. */ + /*order 1k would be 1Mx1M carpet.*/ +parse arg n char . /*get the order of the carpet. */ +if n=='' | n==',' then n=3 /*if none specified, assume 3. */ +if char=='' then char='*' /*use the default of an asterisk.*/ +if length(char)==2 then char=x2c(char) /*it was specified in hexadecimal*/ +if length(char)==3 then char=d2c(char) /*it was specified in decimal. */ + /*LINESIZE isn't in some REXXes. */ +/* width=linesize() */ /*maximum width of the screen. */ + width=132 + + do j=0 for 3**n; z= /* z is the line to be displayed.*/ + + do k=0 for 3**n; jj=j; kk=k; xChar=char + + do while jj\==0 & kk\==0 /*one symbol for not is \ */ + if jj//3==1 & kk//3==1 then do /* // = remainder.*/ + xChar=' ' /*use a blank. */ + leave /*leaves DO while.*/ + end + jj=jj%3 + kk=kk%3 /*% means it's integer division.*/ + end /*while*/ + + z=z || xChar /*it's either black or white. */ + end /*k*/ + + if length(z) x + x + x) ::: + carpet.map(x => x + x.replace('#', ' ') + x) ::: + carpet.map(x => x + x + x)) + +def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println diff --git a/Task/Sierpinski-carpet/Scheme/sierpinski-carpet.ss b/Task/Sierpinski-carpet/Scheme/sierpinski-carpet.ss new file mode 100644 index 0000000000..c1123c3cee --- /dev/null +++ b/Task/Sierpinski-carpet/Scheme/sierpinski-carpet.ss @@ -0,0 +1,15 @@ +(define (carpet n) + (define (in-carpet? x y) + (cond ((or (zero? x) (zero? y)) + #t) + ((and (= 1 (remainder x 3)) (= 1 (remainder y 3))) + #f) + (else + (in-carpet? (quotient x 3) (quotient y 3))))) + + (do ((i 0 (+ i 1))) ((not (< i (expt 3 n)))) + (do ((j 0 (+ j 1))) ((not (< j (expt 3 n)))) + (display (if (in-carpet? i j) + #\* + #\space))) + (newline))) diff --git a/Task/Sierpinski-carpet/Seed7/sierpinski-carpet.seed7 b/Task/Sierpinski-carpet/Seed7/sierpinski-carpet.seed7 new file mode 100644 index 0000000000..af07bfebbb --- /dev/null +++ b/Task/Sierpinski-carpet/Seed7/sierpinski-carpet.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + +const func boolean: inCarpet (in var integer: x, in var integer: y) is func + result + var boolean: result is TRUE; + begin + while result and x <> 0 and y <> 0 do + if x rem 3 = 1 and y rem 3 = 1 then + result := FALSE; + else + x := x div 3; + y := y div 3; + end if; + end while; + end func; + +const proc: carpet (in integer: n) is func + local + var integer: i is 0; + var integer: j is 0; + begin + for i range 0 to pred(3 ** n) do + for j range 0 to pred(3 ** n) do + if inCarpet(i, j) then + write("#"); + else + write(" "); + end if; + end for; + writeln; + end for; + end func; + +const proc: main is func + begin + carpet(3); + end func; diff --git a/Task/Sierpinski-carpet/Tcl/sierpinski-carpet.tcl b/Task/Sierpinski-carpet/Tcl/sierpinski-carpet.tcl new file mode 100644 index 0000000000..6f2cfc251a --- /dev/null +++ b/Task/Sierpinski-carpet/Tcl/sierpinski-carpet.tcl @@ -0,0 +1,22 @@ +package require Tcl 8.5 + +proc map {lambda list} { + foreach elem $list { + lappend result [apply $lambda $elem] + } + return $result +} + +proc sierpinski_carpet n { + set carpet [list "#"] + for {set i 1} {$i <= $n} {incr i} { + set carpet [concat \ + [map {x {subst {$x$x$x}}} $carpet] \ + [map {x {subst {$x[string map {"#" " "} $x]$x}}} $carpet] \ + [map {x {subst {$x$x$x}}} $carpet] \ + ] + } + return [join $carpet \n] +} + +puts [sierpinski_carpet 3] diff --git a/Task/Sierpinski-carpet/Ursala/sierpinski-carpet.ursala b/Task/Sierpinski-carpet/Ursala/sierpinski-carpet.ursala new file mode 100644 index 0000000000..64f88d1780 --- /dev/null +++ b/Task/Sierpinski-carpet/Ursala/sierpinski-carpet.ursala @@ -0,0 +1,8 @@ +#import std +#import nat + +carpet = ~&a^?\<<&>>! (-*<7,5,7>; *=DS ~&K7+ ~&B**DS*=rlDS)^|R/~& predecessor + +#show+ + +test = mat0 ~&?(`#!,` !)*** carpet* <0,1,2,3> diff --git a/Task/Sierpinski-carpet/XPL0/sierpinski-carpet.xpl0 b/Task/Sierpinski-carpet/XPL0/sierpinski-carpet.xpl0 new file mode 100644 index 0000000000..8e416d24f0 --- /dev/null +++ b/Task/Sierpinski-carpet/XPL0/sierpinski-carpet.xpl0 @@ -0,0 +1,19 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +proc DrawPat(X0, Y0, S); \Draw 3x3 pattern with hole in middle +int X0, Y0, S; \coordinate of upper-left corner, size +int X, Y; +[for Y:= 0 to 2 do + for X:= 0 to 2 do + if X#1 or Y#1 then \don't draw middle pattern + [if S>1 then \recurse + DrawPat(X*S+X0, Y*S+Y0, S/3) + else Point(X+X0, Y+Y0, 4\red\); + ]; +]; + +[SetVid($13); \set 320x200 graphic video mode +DrawPat(0, 0, 3*3*3); \draw Sierpinski carpet +if ChIn(1) then []; \wait for keystroke +SetVid($3); \restore normal text mode +] diff --git a/Task/Sierpinski-triangle-Graphical/0DESCRIPTION b/Task/Sierpinski-triangle-Graphical/0DESCRIPTION new file mode 100644 index 0000000000..ab71f68559 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/0DESCRIPTION @@ -0,0 +1,4 @@ +Produce a graphical representation of a [[wp:Sierpinski triangle|Sierpinski triangle]] of order N in any orientation. + +An example of Sierpinski's triangle (order = 8) looks like this:

+[[File:Sierpinski_Triangle_Unicon.PNG]] diff --git a/Task/Sierpinski-triangle-Graphical/Asymptote/sierpinski-triangle-graphical.asymptote b/Task/Sierpinski-triangle-Graphical/Asymptote/sierpinski-triangle-graphical.asymptote new file mode 100644 index 0000000000..415ff6229a --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Asymptote/sierpinski-triangle-graphical.asymptote @@ -0,0 +1,19 @@ +path subtriangle(path p, real node) { + return + point(p, node) -- + point(p, node + 1/2) -- + point(p, node - 1/2) -- + cycle; +} + +void sierpinski(path p, int order) { + if (order == 0) + fill(p); + else { + sierpinski(subtriangle(p, 0), order - 1); + sierpinski(subtriangle(p, 1), order - 1); + sierpinski(subtriangle(p, 2), order - 1); + } +} + +sierpinski((0, 0) -- (5 inch, 1 inch) -- (2 inch, 6 inch) -- cycle, 10); diff --git a/Task/Sierpinski-triangle-Graphical/BBC-BASIC/sierpinski-triangle-graphical.bbc b/Task/Sierpinski-triangle-Graphical/BBC-BASIC/sierpinski-triangle-graphical.bbc new file mode 100644 index 0000000000..6ce0a8a829 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/BBC-BASIC/sierpinski-triangle-graphical.bbc @@ -0,0 +1,8 @@ + order% = 8 + size% = 2^order% + VDU 23,22,size%;size%;8,8,16,128 + FOR Y% = 0 TO size%-1 + FOR X% = 0 TO size%-1 + IF (X% AND Y%)=0 PLOT X%*2,Y%*2 + NEXT + NEXT Y% diff --git a/Task/Sierpinski-triangle-Graphical/C/sierpinski-triangle-graphical.c b/Task/Sierpinski-triangle-Graphical/C/sierpinski-triangle-graphical.c new file mode 100644 index 0000000000..55ce2cb4a0 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/C/sierpinski-triangle-graphical.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include + +long long x, y, dx, dy, scale, clen, cscale; +typedef struct { double r, g, b; } rgb; +rgb ** pix; + +void sc_up() +{ + scale *= 2; x *= 2; y *= 2; + cscale *= 3; +} + +void h_rgb(long long x, long long y) +{ + rgb *p = &pix[y][x]; + +# define SAT 1 + double h = 6.0 * clen / cscale; + double VAL = 1; + double c = SAT * VAL; + double X = c * (1 - fabs(fmod(h, 2) - 1)); + + 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 iter_string(const char * str, int d) +{ + long long len; + while (*str != '\0') { + switch(*(str++)) { + case 'X': + if (d) iter_string("XHXVX", d - 1); + else{ + clen ++; + h_rgb(x/scale, y/scale); + x += dx; + y -= dy; + } + continue; + case 'V': + len = 1LLU << d; + while (len--) { + clen ++; + h_rgb(x/scale, y/scale); + y += dy; + } + continue; + case 'H': + len = 1LLU << d; + while(len --) { + clen ++; + h_rgb(x/scale, y/scale); + x -= dx; + } + continue; + } + } +} + +void sierp(long leng, int depth) +{ + long i; + long h = leng + 20, w = leng + 20; + + /* allocate pixel buffer */ + rgb *buf = malloc(sizeof(rgb) * w * h); + pix = malloc(sizeof(rgb *) * h); + for (i = 0; i < h; i++) + pix[i] = buf + w * i; + memset(buf, 0, sizeof(rgb) * w * h); + + /* init coords; scale up to desired; exec string */ + x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; + for (i = 0; i < depth; i++) sc_up(); + iter_string("VXH", depth); + + /* write color PNM file */ + unsigned char *fpix = malloc(w * h * 3); + double maxv = 0, *dbuf = (double*)buf; + + for (i = 3 * w * h - 1; i >= 0; i--) + if (dbuf[i] > maxv) maxv = dbuf[i]; + for (i = 3 * h * w - 1; i >= 0; i--) + fpix[i] = 255 * dbuf[i] / maxv; + + printf("P6\n%ld %ld\n255\n", w, h); + fflush(stdout); /* printf and fwrite may treat buffer differently */ + fwrite(fpix, h * w * 3, 1, stdout); +} + +int main(int c, char ** v) +{ + int size, depth; + + depth = (c > 1) ? atoi(v[1]) : 10; + size = 1 << depth; + + fprintf(stderr, "size: %d depth: %d\n", size, depth); + sierp(size, depth + 2); + + return 0; +} diff --git a/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d b/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d new file mode 100644 index 0000000000..90b9fcb301 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d @@ -0,0 +1,16 @@ +import grayscale_image; + +void main() { + enum order = 8, + margin = 10, + width = 2 ^^ order; + + auto im = new Image!Gray(width + 2 * margin, width + 2 * margin); + im.clear(Gray.white); + + foreach (y; 0 .. width) + foreach (x; 0 .. width) + if ((x & y) == 0) + im[x + margin, y + margin] = Gray.black; + im.savePGM("sierpinski.pgm"); +} diff --git a/Task/Sierpinski-triangle-Graphical/Go/sierpinski-triangle-graphical.go b/Task/Sierpinski-triangle-Graphical/Go/sierpinski-triangle-graphical.go new file mode 100644 index 0000000000..88e7d3eb0b --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Go/sierpinski-triangle-graphical.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "image" + "image/color" + "image/draw" + "image/png" + "os" +) + +func main() { + const order = 8 + const width = 1 << order + const margin = 10 + bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) + im := image.NewGray(bounds) + gBlack := color.Gray{0} + gWhite := color.Gray{255} + draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) + + for y := 0; y < width; y++ { + for x := 0; x < width; x++ { + if x&y == 0 { + im.SetGray(x, y, gBlack) + } + } + } + f, err := os.Create("sierpinski.png") + if err != nil { + fmt.Println(err) + return + } + if err = png.Encode(f, im); err != nil { + fmt.Println(err) + } + if err = f.Close(); err != nil { + fmt.Println(err) + } +} diff --git a/Task/Sierpinski-triangle-Graphical/Haskell/sierpinski-triangle-graphical.hs b/Task/Sierpinski-triangle-Graphical/Haskell/sierpinski-triangle-graphical.hs new file mode 100644 index 0000000000..8018b70e9d --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Haskell/sierpinski-triangle-graphical.hs @@ -0,0 +1,12 @@ +import Diagrams.Prelude +import Diagrams.Backend.Cairo.CmdLine + +triangle = eqTriangle # fc black # lw 0 + +reduce t = t + === + (t ||| t) + +sierpinski = iterate reduce triangle + +main = defaultMain $ sierpinski !! 7 diff --git a/Task/Sierpinski-triangle-Graphical/Icon/sierpinski-triangle-graphical.icon b/Task/Sierpinski-triangle-Graphical/Icon/sierpinski-triangle-graphical.icon new file mode 100644 index 0000000000..feba65c485 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Icon/sierpinski-triangle-graphical.icon @@ -0,0 +1,16 @@ +link wopen + +procedure main(A) + local width, margin, x, y + + width := 2 ^ (order := (0 < integer(\A[1])) | 8) + wsize := width + 2 * (margin := 30 ) + WOpen("label=Sierpinski", "size="||wsize||","||wsize) | + stop("*** cannot open window") + + every y := 0 to width - 1 do + every x := 0 to width - 1 do + if iand(x, y) = 0 then DrawPoint(x + margin, y + margin) + + Event() +end diff --git a/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-1.j b/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-1.j new file mode 100644 index 0000000000..6e379fab53 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-1.j @@ -0,0 +1,2 @@ + load 'viewmat' + 'rgb'viewmat--. |. (~:_1&|.)^:(<@#) (2^8){.1 diff --git a/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-2.j b/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-2.j new file mode 100644 index 0000000000..17f6e591da --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/J/sierpinski-triangle-graphical-2.j @@ -0,0 +1,2 @@ +load'viewmat' +viewmat(,~,.~)^:8,1 diff --git a/Task/Sierpinski-triangle-Graphical/Liberty-BASIC/sierpinski-triangle-graphical.liberty b/Task/Sierpinski-triangle-Graphical/Liberty-BASIC/sierpinski-triangle-graphical.liberty new file mode 100644 index 0000000000..6615edc8a2 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Liberty-BASIC/sierpinski-triangle-graphical.liberty @@ -0,0 +1,39 @@ +nomainwin + +open "test" for graphics_nsb_fs as #gr + +#gr "trapclose quit" +#gr "down; home" +#gr "posxy cx cy" + +order =10 + +w =cx *2: h =cy *2 + +dim a( h, h) 'line, col + +#gr "trapclose quit" +#gr "down; home" + +a( 1, 1) =1 + +for i = 2 to 2^order -1 + scan + a( i, 1) =1 + a( i, i) =1 + for j = 2 to i -1 + 'a(i,j)=a(i-1,j-1)+a(i-1,j) 'LB is quite capable for crunching BIG numbers + a( i, j) =(a( i -1, j -1) +a( i -1, j)) mod 2 'but for this task, last bit is enough (and it much faster) + next + for j = 1 to i + if a( i, j) mod 2 then #gr "set "; cx +j -i /2; " "; i + next +next +#gr "flush" + +wait + +sub quit handle$ + close #handle$ + end +end sub diff --git a/Task/Sierpinski-triangle-Graphical/Logo/sierpinski-triangle-graphical.logo b/Task/Sierpinski-triangle-Graphical/Logo/sierpinski-triangle-graphical.logo new file mode 100644 index 0000000000..aff3462f95 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Logo/sierpinski-triangle-graphical.logo @@ -0,0 +1,5 @@ +to sierpinski :n :length + if :n = 0 [stop] + repeat 3 [sierpinski :n-1 :length/2 fd :length rt 120] +end +seth 30 sierpinski 5 200 diff --git a/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math new file mode 100644 index 0000000000..9fa00fd02f --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math @@ -0,0 +1,8 @@ +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/OCaml/sierpinski-triangle-graphical.ocaml b/Task/Sierpinski-triangle-Graphical/OCaml/sierpinski-triangle-graphical.ocaml new file mode 100644 index 0000000000..755f3baf8f --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/OCaml/sierpinski-triangle-graphical.ocaml @@ -0,0 +1,47 @@ +open Graphics + +let round v = + int_of_float (floor (v +. 0.5)) + +let middle (x1, y1) (x2, y2) = + ((x1 +. x2) /. 2.0, + (y1 +. y2) /. 2.0) + +let draw_line (x1, y1) (x2, y2) = + moveto (round x1) (round y1); + lineto (round x2) (round y2); +;; + +let draw_triangle (p1, p2, p3) = + draw_line p1 p2; + draw_line p2 p3; + draw_line p3 p1; +;; + +let () = + open_graph ""; + let width = float (size_x ()) in + let height = float (size_y ()) in + let pad = 20.0 in + let initial_triangle = + ( (pad, pad), + (width -. pad, pad), + (width /. 2.0, height -. pad) ) + in + let rec loop step tris = + if step <= 0 then tris else + loop (pred step) ( + List.fold_left (fun acc (p1, p2, p3) -> + let m1 = middle p1 p2 + and m2 = middle p2 p3 + and m3 = middle p3 p1 in + let tri1 = (p1, m1, m3) + and tri2 = (p2, m2, m1) + and tri3 = (p3, m3, m2) in + tri1 :: tri2 :: tri3 :: acc + ) [] tris + ) + in + let res = loop 6 [ initial_triangle ] in + List.iter draw_triangle res; + ignore (read_key ()) diff --git a/Task/Sierpinski-triangle-Graphical/Perl-6/sierpinski-triangle-graphical.pl6 b/Task/Sierpinski-triangle-Graphical/Perl-6/sierpinski-triangle-graphical.pl6 new file mode 100644 index 0000000000..1be35cf968 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Perl-6/sierpinski-triangle-graphical.pl6 @@ -0,0 +1,46 @@ +my $side = 512; +my $height = get_height($side); +my $levels = 8; + +sub get_height ($side) { $side * 3.sqrt / 2 } + +sub triangle ( $x1, $y1, $x2, $y2, $x3, $y3, $fill?, $animate? ) { + print "\n \n" + } + else + { + say ' />'; + } +} + +sub fractal ( $x1, $y1, $x2, $y2, $x3, $y3, $r is copy ) { + triangle( $x1, $y1, $x2, $y2, $x3, $y3 ); + return unless --$r; + my $side = abs($x3 - $x2) / 2; + my $height = get_height($side); + fractal( $x1, $y1-$height*2, $x1-$side/2, $y1-3*$height, $x1+$side/2, $y1-3*$height, $r); + fractal( $x2, $y1, $x2-$side/2, $y1-$height, $x2+$side/2, $y1-$height, $r); + fractal( $x3, $y1, $x3-$side/2, $y1-$height, $x3+$side/2, $y1-$height, $r); +} + +say ' + + + + + + + + +'; + +triangle( $side/2, 0, 0, $height, $side, $height, 'url(#basegradient)' ); +triangle( $side/2, 0, 0, $height, $side, $height, '#000', 'animate' ); +say ''; +fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ); +say ''; diff --git a/Task/Sierpinski-triangle-Graphical/Perl/sierpinski-triangle-graphical.pl b/Task/Sierpinski-triangle-Graphical/Perl/sierpinski-triangle-graphical.pl new file mode 100644 index 0000000000..6086c1c444 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Perl/sierpinski-triangle-graphical.pl @@ -0,0 +1,29 @@ +use List::Util qw'min max sum'; + +sub write_eps { + my @x = @_[0, 2, 4]; + my @y = @_[1, 3, 5]; + my $sx = sum(@x) / 3; + my $sy = sum(@y) / 3; + @x = map { $_ - $sx } @x; + @y = map { $_ - $sy } @y; + + print <<"HEAD"; +%!PS-Adobe-3.0 +%%BoundingBox: @{[min(@x) - 10]} @{[min(@y) - 10]} @{[max(@x) + 10]} @{[max(@y) + 10]} +/v1 { $x[0] $y[0] } def /v2 { $x[1] $y[1] } def /v3 { $x[2] $y[2] } def +/t { translate } def +/r { .5 .5 scale 2 copy t 2 index sierp pop neg exch neg exch t 2 2 scale } def + +/sierp { dup 1 sub dup 0 ne + { v1 r v2 r v3 r } + { v1 moveto v2 lineto v3 lineto} ifelse + pop +} def + +9 sierp fill pop showpage +%%EOF +HEAD +} + +write_eps 0, 0, 300, 215, -25, 200; diff --git a/Task/Sierpinski-triangle-Graphical/PicoLisp/sierpinski-triangle-graphical.l b/Task/Sierpinski-triangle-Graphical/PicoLisp/sierpinski-triangle-graphical.l new file mode 100644 index 0000000000..91405dfbeb --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/PicoLisp/sierpinski-triangle-graphical.l @@ -0,0 +1,15 @@ +(de sierpinski (N) + (let (D '("1") S "0") + (do N + (setq + D (conc + (mapcar '((X) (pack S X S)) D) + (mapcar '((X) (pack X "0" X)) D) ) + S (pack S S) ) ) + D ) ) + +(out '(display -) + (let Img (sierpinski 7) + (prinl "P1") + (prinl (length (car Img)) " " (length Img)) + (mapc prinl Img) ) ) diff --git a/Task/Sierpinski-triangle-Graphical/PostScript/sierpinski-triangle-graphical.ps b/Task/Sierpinski-triangle-Graphical/PostScript/sierpinski-triangle-graphical.ps new file mode 100644 index 0000000000..effe5d48d2 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/PostScript/sierpinski-triangle-graphical.ps @@ -0,0 +1,32 @@ +%!PS + +/sierp { % level ax ay bx by cx cy + 6 cpy triangle + sierpr +} bind def + +/sierpr { + 12 cpy + 10 -4 2 { + 5 1 roll exch 4 -1 roll + add 0.5 mul 3 1 roll + add 0.5 mul 3 -1 roll + 2 roll + } for % l a b c bc ac ab + 13 -1 roll dup 0 gt { + 1 sub + dup 4 cpy 18 -2 roll sierpr + dup 7 index 7 index 2 cpy 16 -2 roll sierpr + 9 3 roll 1 index 1 index 2 cpy 13 4 roll sierpr + } { 13 -6 roll 7 { pop } repeat } ifelse + triangle +} bind def + +/cpy { { 5 index } repeat } bind def + +/triangle { + newpath moveto lineto lineto closepath stroke +} bind def + +6 50 100 550 100 300 533 sierp +showpage diff --git a/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-1.pro b/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-1.pro new file mode 100644 index 0000000000..e6607aebf4 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-1.pro @@ -0,0 +1,30 @@ +sierpinski(N) :- + sformat(A, 'Sierpinski order ~w', [N]), + new(D, picture(A)), + draw_Sierpinski(D, N, point(350,50), 600), + send(D, size, size(690,690)), + send(D, open). + +draw_Sierpinski(Window, 1, point(X, Y), Len) :- + X1 is X - round(Len/2), + X2 is X + round(Len/2), + Y1 is Y + Len * sqrt(3) / 2, + send(Window, display, new(Pa, path)), + ( + send(Pa, append, point(X, Y)), + send(Pa, append, point(X1, Y1)), + send(Pa, append, point(X2, Y1)), + send(Pa, closed, @on), + send(Pa, fill_pattern, colour(@default, 0, 0, 0)) + ). + + +draw_Sierpinski(Window, N, point(X, Y), Len) :- + Len1 is round(Len/2), + X1 is X - round(Len/4), + X2 is X + round(Len/4), + Y1 is Y + Len * sqrt(3) / 4, + N1 is N - 1, + draw_Sierpinski(Window, N1, point(X, Y), Len1), + draw_Sierpinski(Window, N1, point(X1, Y1), Len1), + draw_Sierpinski(Window, N1, point(X2, Y1), Len1). diff --git a/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-2.pro b/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-2.pro new file mode 100644 index 0000000000..0f6f5a8218 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Prolog/sierpinski-triangle-graphical-2.pro @@ -0,0 +1,40 @@ +:- dynamic top/1. + +sierpinski_iterate(N) :- + retractall(top(_)), + sformat(A, 'Sierpinski order ~w', [N]), + new(D, picture(A)), + draw_Sierpinski_iterate(D, N, point(550, 50)), + send(D, open). + +draw_Sierpinski_iterate(Window, N, point(X,Y)) :- + assert(top([point(X,Y)])), + NbTours is 2 ** (N - 1), + % Size is given here to preserve the "small" triangles when N is big + Len is 10, + forall(between(1, NbTours, _I), + ( retract(top(Lst)), + assert(top([])), + forall(member(P, Lst), + draw_Sierpinski(Window, P, Len)))). + +draw_Sierpinski(Window, point(X, Y), Len) :- + X1 is X - round(Len/2), + X2 is X + round(Len/2), + Y1 is Y + round(Len * sqrt(3) / 2), + send(Window, display, new(Pa, path)), + ( + send(Pa, append, point(X, Y)), + send(Pa, append, point(X1, Y1)), + send(Pa, append, point(X2, Y1)), + send(Pa, closed, @on), + send(Pa, fill_pattern, colour(@default, 0, 0, 0)) + ), + retract(top(Lst)), + ( member(point(X1, Y1), Lst) -> select(point(X1,Y1), Lst, Lst1) + ; Lst1 = [point(X1, Y1)|Lst]), + + ( member(point(X2, Y1), Lst1) -> select(point(X2,Y1), Lst1, Lst2) + ; Lst2 = [point(X2, Y1)|Lst1]), + + assert(top(Lst2)). diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py new file mode 100644 index 0000000000..0a4e4ea172 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +################################################################################################ +# import necessary modules +# ------------------------ +from numpy import * +import turtle +################################################################################################ +# Functions defining the drawing actions (used by the function DrawSierpinskiTriangle). +# ------------------------------------------------------------------------------------- +def Left(turn, point, fwd, angle, turt): + turt.left(angle) + return [turn, point, fwd, angle, turt] +def Right(turn, point, fwd, angle, turt): + turt.right(angle) + return [turn, point, fwd, angle, turt] +def Forward(turn, point, fwd, angle, turt): + turt.forward(fwd) + return [turn, point, fwd, angle, turt] +################################################################################################ +# The drawing function +# -------------------- +# +# level level of Sierpinski triangle (minimum value = 1) +# ss screensize (Draws on a screen of size ss x ss. Default value = 400.) +#----------------------------------------------------------------------------------------------- +def DrawSierpinskiTriangle(level, ss=400): + # typical values + turn = 0 # initial turn (0 to start horizontally) + angle=60.0 # in degrees + + # Initialize the turtle + turtle.hideturtle() + turtle.screensize(ss,ss) + turtle.penup() + turtle.degrees() + + # The starting point on the canvas + fwd0 = float(ss) + point=array([-fwd0/2.0, -fwd0/2.0]) + + # Setting up the Lindenmayer system + # Assuming that the triangle will be drawn in the following way: + # 1.) Start at a point + # 2.) Draw a straight line - the horizontal line (H) + # 3.) Bend twice by 60 degrees to the left (--) + # 4.) Draw a straight line - the slanted line (X) + # 5.) Bend twice by 60 degrees to the left (--) + # 6.) Draw a straight line - another slanted line (X) + # This produces the triangle in the first level. (so the axiom to begin with is H--X--X) + # 7.) For the next level replace each horizontal line using + # X->XX + # H -> H--X++H++X--H + # The lengths will be halved. + + + decode = {'-':Left, '+':Right, 'X':Forward, 'H':Forward} + axiom = 'H--X--X' + + # Start the drawing + turtle.goto(point[0], point[1]) + turtle.pendown() + turtle.hideturtle() + turt=turtle.getpen() + startposition=turt.clone() + + # Get the triangle in the Lindenmayer system + fwd = fwd0/(2.0**level) + path = axiom + for i in range(0,level): + path=path.replace('X','XX') + path=path.replace('H','H--X++H++X--H') + + # Draw it. + for i in path: + [turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt) +################################################################################################ + +DrawSierpinskiTriangle(5) diff --git a/Task/Sierpinski-triangle-Graphical/Ruby/sierpinski-triangle-graphical.rb b/Task/Sierpinski-triangle-Graphical/Ruby/sierpinski-triangle-graphical.rb new file mode 100644 index 0000000000..4448179a65 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Ruby/sierpinski-triangle-graphical.rb @@ -0,0 +1,41 @@ +Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do + def triangle(slot, tri, color) + x, y, len = tri + slot.append do + fill color + shape do + move_to(x,y) + dx = len * Math::cos(Math::PI/3) + dy = len * Math::sin(Math::PI/3) + line_to(x-dx, y+dy) + line_to(x+dx, y+dy) + line_to(x,y) + end + end + end + @s = stack(:width => 520, :height => 520) {} + @s.move(10,10) + + length = 512 + @triangles = [[length/2,0,length]] + triangle(@s, @triangles[0], rgb(0,0,0)) + + @n = 1 + animate(1) do + if @n <= 7 + @triangles = @triangles.inject([]) do |sum, (x, y, len)| + dx = len/2 * Math::cos(Math::PI/3) + dy = len/2 * Math::sin(Math::PI/3) + triangle(@s, [x, y+2*dy, -len/2], rgb(255,255,255)) + sum += [[x, y, len/2], [x-dx, y+dy, len/2], [x+dx, y+dy, len/2]] + end + end + @n += 1 + end + + keypress do |key| + case key + when :control_q, "\x11" then exit + end + end +end diff --git a/Task/Sierpinski-triangle-Graphical/Run-BASIC/sierpinski-triangle-graphical.run b/Task/Sierpinski-triangle-Graphical/Run-BASIC/sierpinski-triangle-graphical.run new file mode 100644 index 0000000000..b35dae0571 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Run-BASIC/sierpinski-triangle-graphical.run @@ -0,0 +1,18 @@ +graphic #g, 300,300 +order = 8 +width = 100 +w = width * 11 +dim canvas(w,w) +canvas(1,1) = 1 + +for x = 2 to 2^order -1 + canvas(x,1) = 1 + canvas(x,x) = 1 + for y = 2 to x -1 + canvas( x, y) = (canvas(x -1,y -1) + canvas(x -1, y)) mod 2 + if canvas(x,y) mod 2 then #g "set "; width + (order*3) + y - x / 2;" "; x + next y +next x +render #g +#g "flush" +wait diff --git a/Task/Sierpinski-triangle-Graphical/Seed7/sierpinski-triangle-graphical.seed7 b/Task/Sierpinski-triangle-Graphical/Seed7/sierpinski-triangle-graphical.seed7 new file mode 100644 index 0000000000..2d229c496d --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Seed7/sierpinski-triangle-graphical.seed7 @@ -0,0 +1,24 @@ +$ include "seed7_05.s7i"; + include "draw.s7i"; + include "keybd.s7i"; + +const proc: main is func + local + const integer: order is 8; + const integer: width is 1 << order; + const integer: margin is 10; + var integer: x is 0; + var integer: y is 0; + begin + screen(width + 2 * margin, width + 2 * margin); + clear(curr_win, white); + KEYBOARD := GRAPH_KEYBOARD; + for y range 0 to pred(width) do + for x range 0 to pred(width) do + if bitset conv x & bitset conv y = bitset.value then + point(margin + x, margin + y, black); + end if; + end for; + end for; + ignore(getc(KEYBOARD)); + end func; diff --git a/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical.tcl b/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical.tcl new file mode 100644 index 0000000000..65627eabca --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical.tcl @@ -0,0 +1,25 @@ +package require Tcl 8.5 +package require Tk + +proc mean args {expr {[::tcl::mathop::+ {*}$args] / [llength $args]}} +proc sierpinski {canv coords order} { + $canv create poly $coords -fill black -outline {} + set queue [list [list {*}$coords $order]] + while {[llength $queue]} { + lassign [lindex $queue 0] x1 y1 x2 y2 x3 y3 order + set queue [lrange $queue 1 end] + if {[incr order -1] < 0} continue + set x12 [mean $x1 $x2]; set y12 [mean $y1 $y2] + set x23 [mean $x2 $x3]; set y23 [mean $y2 $y3] + set x31 [mean $x3 $x1]; set y31 [mean $y3 $y1] + $canv create poly $x12 $y12 $x23 $y23 $x31 $y31 -fill white -outline {} + update idletasks; # So we can see progress + lappend queue [list $x1 $y1 $x12 $y12 $x31 $y31 $order] \ + [list $x12 $y12 $x2 $y2 $x23 $y23 $order] \ + [list $x31 $y31 $x23 $y23 $x3 $y3 $order] + } +} + +pack [canvas .c -width 400 -height 400 -background white] +update; # So we can see progress +sierpinski .c {200 10 390 390 10 390} 7 diff --git a/Task/Sierpinski-triangle-Graphical/XPL0/sierpinski-triangle-graphical.xpl0 b/Task/Sierpinski-triangle-Graphical/XPL0/sierpinski-triangle-graphical.xpl0 new file mode 100644 index 0000000000..c9e7f479a8 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/XPL0/sierpinski-triangle-graphical.xpl0 @@ -0,0 +1,10 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +def Order=7, Size=1< + * + * * + * * + * * * * + * * + * * * * + * * * * + * * * * * * * * + * * + * * * * + * * * * + * * * * * * * * + * * * * + * * * * * * * * + * * * * * * * * + * * * * * * * * * * * * * * * * + + +See [[Sierpinski triangle/Graphical]] for graphics images of this pattern. See also [[Sierpinski carpet]] diff --git a/Task/Sierpinski-triangle/1META.yaml b/Task/Sierpinski-triangle/1META.yaml new file mode 100644 index 0000000000..bf76cfa1e6 --- /dev/null +++ b/Task/Sierpinski-triangle/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Fractals diff --git a/Task/Sierpinski-triangle/ACL2/sierpinski-triangle.acl2 b/Task/Sierpinski-triangle/ACL2/sierpinski-triangle.acl2 new file mode 100644 index 0000000000..3a9df22b79 --- /dev/null +++ b/Task/Sierpinski-triangle/ACL2/sierpinski-triangle.acl2 @@ -0,0 +1,39 @@ +(defun pascal-row (prev) + (if (endp (rest prev)) + (list 1) + (cons (+ (first prev) (second prev)) + (pascal-row (rest prev))))) + +(defun pascal-triangle-r (rows prev) + (if (zp rows) + nil + (let ((curr (cons 1 (pascal-row prev)))) + (cons curr (pascal-triangle-r (1- rows) curr))))) + +(defun pascal-triangle (rows) + (cons (list 1) + (pascal-triangle-r rows (list 1)))) + +(defun print-odds-row (row) + (if (endp row) + (cw "~%") + (prog2$ (cw (if (oddp (first row)) "[]" " ")) + (print-odds-row (rest row))))) + +(defun print-spaces (n) + (if (zp n) + nil + (prog2$ (cw " ") + (print-spaces (1- n))))) + +(defun print-odds (triangle height) + (if (endp triangle) + nil + (progn$ (print-spaces height) + (print-odds-row (first triangle)) + (print-odds (rest triangle) (1- height))))) + +(defun print-sierpenski (levels) + (let ((height (1- (expt 2 levels)))) + (print-odds (pascal-triangle height) + height))) diff --git a/Task/Sierpinski-triangle/ALGOL-68/sierpinski-triangle.alg b/Task/Sierpinski-triangle/ALGOL-68/sierpinski-triangle.alg new file mode 100644 index 0000000000..b1782feabb --- /dev/null +++ b/Task/Sierpinski-triangle/ALGOL-68/sierpinski-triangle.alg @@ -0,0 +1,16 @@ +PROC sierpinski = (INT n)[]STRING: ( + FLEX[0]STRING d := "*"; + FOR i TO n DO + [UPB d * 2]STRING next; + STRING sp := " " * (2 ** (i-1)); + FOR x TO UPB d DO + STRING dx = d[x]; + next[x] := sp+dx+sp; + next[UPB d+x] := dx+" "+dx + OD; + d := next + OD; + d +); + +printf(($gl$,sierpinski(4))) diff --git a/Task/Sierpinski-triangle/AWK/sierpinski-triangle.awk b/Task/Sierpinski-triangle/AWK/sierpinski-triangle.awk new file mode 100644 index 0000000000..cd68430c45 --- /dev/null +++ b/Task/Sierpinski-triangle/AWK/sierpinski-triangle.awk @@ -0,0 +1,23 @@ +# WST.AWK - Waclaw Sierpinski's triangle contributed by Dan Nielsen +# syntax: GAWK -f WST.AWK [-v X=anychar] iterations +# example: GAWK -f WST.AWK -v X=* 2 +BEGIN { + n = ARGV[1] + 0 # iterations + if (n !~ /^[0-9]+$/) { exit(1) } + if (n == 0) { width = 3 } + row = split("X,X X,X X,X X X X",A,",") # seed the array + for (i=1; i<=n; i++) { # build triangle + width = length(A[row]) + for (j=1; j<=row; j++) { + str = A[j] + A[j+row] = sprintf("%-*s %-*s",width,str,width,str) + } + row *= 2 + } + for (j=1; j<=row; j++) { # print triangle + if (X != "") { gsub(/X/,substr(X,1,1),A[j]) } + sub(/ +$/,"",A[j]) + printf("%*s%s\n",width-j+1,"",A[j]) + } + exit(0) +} diff --git a/Task/Sierpinski-triangle/Ada/sierpinski-triangle-1.ada b/Task/Sierpinski-triangle/Ada/sierpinski-triangle-1.ada new file mode 100644 index 0000000000..680bd57fe5 --- /dev/null +++ b/Task/Sierpinski-triangle/Ada/sierpinski-triangle-1.ada @@ -0,0 +1,53 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Strings.Fixed; +with Interfaces; use Interfaces; + +procedure Sieteri_Triangles is + subtype Practical_Order is Unsigned_32 range 0..4; + + + function Pow(X : Unsigned_32; N : Unsigned_32) return Unsigned_32 is + begin + if N = 0 then + return 1; + else + return X * Pow(X, N - 1); + end if; + end Pow; + + procedure Print(Item : Unsigned_32) is + use Ada.Strings.Fixed; + package Ord_Io is new Ada.Text_Io.Modular_Io(Unsigned_32); + use Ord_Io; + Temp : String(1..36) := (others => ' '); + First : Positive; + Last : Positive; + begin + Put(To => Temp, Item => Item, Base => 2); + First := Index(Temp, "#") + 1; + Last := Index(Temp(First..Temp'Last), "#") - 1; + for I in reverse First..Last loop + if Temp(I) = '0' then + Put(' '); + else + Put(Temp(I)); + end if; + end loop; + New_Line; + end Print; + + procedure Sierpinski (N : Practical_Order) is + Size : Unsigned_32 := Pow(2, N); + V : Unsigned_32 := Pow(2, Size); + begin + for I in 0..Size - 1 loop + Print(V); + V := Shift_Left(V, 1) xor Shift_Right(V,1); + end loop; + end Sierpinski; + +begin + for N in Practical_Order loop + Sierpinski(N); + end loop; +end Sieteri_Triangles; diff --git a/Task/Sierpinski-triangle/Ada/sierpinski-triangle-2.ada b/Task/Sierpinski-triangle/Ada/sierpinski-triangle-2.ada new file mode 100644 index 0000000000..959b2a5b92 --- /dev/null +++ b/Task/Sierpinski-triangle/Ada/sierpinski-triangle-2.ada @@ -0,0 +1,28 @@ +with Ada.Command_Line; +with Ada.Text_IO; + +procedure Main is + subtype Order is Natural range 1 .. 32; + type Mod_Int is mod 2 ** Order'Last; + + procedure Sierpinski (N : Order) is + begin + for Line in Mod_Int range 0 .. 2 ** N - 1 loop + for Col in Mod_Int range 0 .. 2 ** N - 1 loop + if (Line and Col) = 0 then + Ada.Text_IO.Put ('X'); + else + Ada.Text_IO.Put (' '); + end if; + end loop; + Ada.Text_IO.New_Line; + end loop; + end Sierpinski; + + N : Order := 4; +begin + if Ada.Command_Line.Argument_Count = 1 then + N := Order'Value (Ada.Command_Line.Argument (1)); + end if; + Sierpinski (N); +end Main; diff --git a/Task/Sierpinski-triangle/AutoHotkey/sierpinski-triangle.ahk b/Task/Sierpinski-triangle/AutoHotkey/sierpinski-triangle.ahk new file mode 100644 index 0000000000..f55c827f41 --- /dev/null +++ b/Task/Sierpinski-triangle/AutoHotkey/sierpinski-triangle.ahk @@ -0,0 +1,19 @@ +Loop 6 + MsgBox % Triangle(A_Index) + +Triangle(n,x=0,y=1) { ; Triangle(n) -> string of dots and spaces of Sierpinski triangle + Static t, l ; put chars in a static string + If (x < 1) { ; when called with one parameter + l := 2*x := 1<<(n-1) ; - compute location, string size + VarSetCapacity(t,l*x,32) ; - allocate memory filled with spaces + Loop %x% + NumPut(13,t,A_Index*l-1,"char") ; - new lines in the end of rows + } + If (n = 1) ; at the bottom of recursion + Return t, NumPut(46,t,x-1+(y-1)*l,"char") ; - write "." (better at proportional fonts) + u := 1<<(n-2) + Triangle(n-1,x,y) ; draw smaller triangle here + Triangle(n-1,x-u,y+u) ; smaller triangle down-left + Triangle(n-1,x+u,y+u) ; smaller triangle down right + Return t +} diff --git a/Task/Sierpinski-triangle/BASIC/sierpinski-triangle.basic b/Task/Sierpinski-triangle/BASIC/sierpinski-triangle.basic new file mode 100644 index 0000000000..6e67634474 --- /dev/null +++ b/Task/Sierpinski-triangle/BASIC/sierpinski-triangle.basic @@ -0,0 +1,14 @@ +DECLARE SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER) + +CLS +triangle 1, 1, 16, 5 + +SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER) + IF n = 0 THEN + LOCATE y, x: PRINT "*"; + ELSE + triangle x, y + length, length / 2, n - 1 + triangle x + length, y, length / 2, n - 1 + triangle x + length * 2, y + length, length / 2, n - 1 + END IF +END SUB diff --git a/Task/Sierpinski-triangle/BBC-BASIC/sierpinski-triangle.bbc b/Task/Sierpinski-triangle/BBC-BASIC/sierpinski-triangle.bbc new file mode 100644 index 0000000000..90a9435bee --- /dev/null +++ b/Task/Sierpinski-triangle/BBC-BASIC/sierpinski-triangle.bbc @@ -0,0 +1,17 @@ + MODE 8 + OFF + + order% = 5 + PROCsierpinski(0, 0, 2^(order%-1)) + REPEAT UNTIL GET + END + + DEF PROCsierpinski(x%, y%, l%) + IF l% = 0 THEN + PRINT TAB(x%,y%) "*"; + ELSE + PROCsierpinski(x%, y%+l%, l% DIV 2) + PROCsierpinski(x%+l%, y%, l% DIV 2) + PROCsierpinski(x%+l%+l%, y%+l%, l% DIV 2) + ENDIF + ENDPROC diff --git a/Task/Sierpinski-triangle/C++/sierpinski-triangle.cpp b/Task/Sierpinski-triangle/C++/sierpinski-triangle.cpp new file mode 100644 index 0000000000..85c2f40e45 --- /dev/null +++ b/Task/Sierpinski-triangle/C++/sierpinski-triangle.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include + +using namespace std; + +template +void sierpinski(int n, OutIt result) +{ + if( n == 0 ) + { + *result++ = "*"; + } + else + { + list prev; + sierpinski(n-1, back_inserter(prev)); + + string sp(1 << (n-1), ' '); + result = transform(prev.begin(), prev.end(), + result, + [sp](const string& x) { return sp + x + sp; }); + transform(prev.begin(), prev.end(), + result, + [sp](const string& x) { return x + " " + x; }); + } +} + +int main() +{ + sierpinski(4, ostream_iterator(cout, "\n")); + return 0; +} diff --git a/Task/Sierpinski-triangle/C/sierpinski-triangle-1.c b/Task/Sierpinski-triangle/C/sierpinski-triangle-1.c new file mode 100644 index 0000000000..e454989345 --- /dev/null +++ b/Task/Sierpinski-triangle/C/sierpinski-triangle-1.c @@ -0,0 +1,13 @@ +#include + +#define SIZE (1 << 4) +int main() +{ + int x, y, i; + for (y = SIZE - 1; y >= 0; y--, putchar('\n')) { + for (i = 0; i < y; i++) putchar(' '); + for (x = 0; x + y < SIZE; x++) + printf((x & y) ? " " : "* "); + } + return 0; +} diff --git a/Task/Sierpinski-triangle/C/sierpinski-triangle-2.c b/Task/Sierpinski-triangle/C/sierpinski-triangle-2.c new file mode 100644 index 0000000000..69e534928c --- /dev/null +++ b/Task/Sierpinski-triangle/C/sierpinski-triangle-2.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include + +#ifndef _POSIX_C_SOURCE +char *strdup(const char *s) +{ + int l = strlen(s); + char *r = malloc(l+1); + memcpy(r, s, l+1); + return r; +} +#endif + +#define truth(X) ((X)=='*'?true:false) +void rule_90(char *evstr) +{ + int i; + int l = strlen(evstr); + bool s[3]; + char *cp = strdup(evstr); + + for(i=0;i < l; i++) { + s[1] = truth(cp[i]); + s[0] = (i-1) < 0 ? false : truth(cp[i-1]); + s[2] = (i+1) < l ? truth(cp[i+1]) : false; + if ( (s[0] && !s[2]) || (!s[0] && s[2]) ) { + evstr[i] = '*'; + } else { + evstr[i] = ' '; + } + } + free(cp); +} diff --git a/Task/Sierpinski-triangle/C/sierpinski-triangle-3.c b/Task/Sierpinski-triangle/C/sierpinski-triangle-3.c new file mode 100644 index 0000000000..b310996518 --- /dev/null +++ b/Task/Sierpinski-triangle/C/sierpinski-triangle-3.c @@ -0,0 +1,18 @@ +void sierpinski_triangle(int n) +{ + int i; + int l = 1<<(n+1); + char *b = malloc(l+1); + + memset(b, ' ', l); + b[l] = 0; + b[l>>1] = '*'; + + printf("%s\n", b); + for(i=0; i < l/2-1;i++) { + rule_90(b); + printf("%s\n", b); + } + + free(b); +} diff --git a/Task/Sierpinski-triangle/C/sierpinski-triangle-4.c b/Task/Sierpinski-triangle/C/sierpinski-triangle-4.c new file mode 100644 index 0000000000..47f47bf5e1 --- /dev/null +++ b/Task/Sierpinski-triangle/C/sierpinski-triangle-4.c @@ -0,0 +1,5 @@ +int main() +{ + sierpinski_triangle(4); + return EXIT_SUCCESS; +} diff --git a/Task/Sierpinski-triangle/Clojure/sierpinski-triangle.clj b/Task/Sierpinski-triangle/Clojure/sierpinski-triangle.clj new file mode 100644 index 0000000000..86a91fde87 --- /dev/null +++ b/Task/Sierpinski-triangle/Clojure/sierpinski-triangle.clj @@ -0,0 +1,26 @@ +(ns example + (:require [clojure.contrib.math :as math])) + +; Length of integer in binary +; (copied from a private multimethod in clojure.contrib.math) +(defmulti #^{:private true} integer-length class) + +(defmethod integer-length java.lang.Integer [n] + (count (Integer/toBinaryString n))) +(defmethod integer-length java.lang.Long [n] + (count (Long/toBinaryString n))) +(defmethod integer-length java.math.BigInteger [n] + (count (.toString n 2))) + +(defn sierpinski-triangle [order] + (loop [size (math/expt 2 order) + v (math/expt 2 (- size 1))] + (when (pos? size) + (println + (apply str (map #(if (bit-test v %) "*" " ") + (range (integer-length v))))) + (recur + (dec size) + (bit-xor (bit-shift-left v 1) (bit-shift-right v 1)))))) + +(sierpinski-triangle 4) diff --git a/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-1.lisp b/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-1.lisp new file mode 100644 index 0000000000..ba68014163 --- /dev/null +++ b/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-1.lisp @@ -0,0 +1,7 @@ +(defun print-sierpinski (order) + (loop with size = (expt 2 order) + repeat size + for v = (expt 2 (1- size)) then (logxor (ash v -1) (ash v 1)) + do (fresh-line) + (loop for i below (integer-length v) + do (princ (if (logbitp i v) "*" " "))))) diff --git a/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-2.lisp b/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-2.lisp new file mode 100644 index 0000000000..d7d3a859e8 --- /dev/null +++ b/Task/Sierpinski-triangle/Common-Lisp/sierpinski-triangle-2.lisp @@ -0,0 +1,6 @@ +(defun sierpinski (n) + (if (= n 0) '("*") + (nconc (mapcar (lambda (e) (format nil "~A~A~0@*~A" (make-string (expt 2 (1- n)) :initial-element #\ ) e)) (sierpinski (1- n))) + (mapcar (lambda (e) (format nil "~A ~A" e e)) (sierpinski (1- n)))))) + +(mapc #'print (sierpinski 4)) diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d new file mode 100644 index 0000000000..d92d68fcdb --- /dev/null +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d @@ -0,0 +1,12 @@ +import std.stdio, std.algorithm, std.string, std.array; + +void main() { + enum level = 4; + auto d = ["*"]; + foreach (n; 0 .. level) { + const sp = " ".replicate(2 ^^ n); + d = d.map!(a => sp ~ a ~ sp)().array() ~ + d.map!(a => a ~ " " ~ a)().array(); + } + d.join("\n").writeln(); +} diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d new file mode 100644 index 0000000000..a30aae41c9 --- /dev/null +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d @@ -0,0 +1,19 @@ +import std.string; + +string sierpinski(int n) { + auto parts = ["*"]; + auto space = " "; + foreach (i; 0 .. n) { + string[] parts2; + foreach (x; parts) + parts2 ~= space ~ x ~ space; + foreach (x; parts) + parts2 ~= x ~ " " ~ x; + parts = parts2; + space ~= space; + } + return parts.join("\n"); +} + +pragma(msg, sierpinski(4)); +void main() {} diff --git a/Task/Sierpinski-triangle/DWScript/sierpinski-triangle.dwscript b/Task/Sierpinski-triangle/DWScript/sierpinski-triangle.dwscript new file mode 100644 index 0000000000..74784a60be --- /dev/null +++ b/Task/Sierpinski-triangle/DWScript/sierpinski-triangle.dwscript @@ -0,0 +1,17 @@ +procedure PrintSierpinski(order : Integer); +var + x, y, size : Integer; +begin + size := (1 shl order)-1; + for y:=size downto 0 do begin + Print(StringOfChar(' ', y)); + for x:=0 to size-y do begin + if (x and y)=0 then + Print('* ') + else Print(' '); + end; + PrintLn(''); + end; +end; + +PrintSierpinski(4); diff --git a/Task/Sierpinski-triangle/Delphi/sierpinski-triangle.delphi b/Task/Sierpinski-triangle/Delphi/sierpinski-triangle.delphi new file mode 100644 index 0000000000..01f30b2f5f --- /dev/null +++ b/Task/Sierpinski-triangle/Delphi/sierpinski-triangle.delphi @@ -0,0 +1,26 @@ +program SierpinskiTriangle; + +{$APPTYPE CONSOLE} + +procedure PrintSierpinski(order: Integer); +var + x, y, size: Integer; +begin + size := (1 shl order) - 1; + for y := size downto 0 do + begin + Write(StringOfChar(' ', y)); + for x := 0 to size - y do + begin + if (x and y) = 0 then + Write('* ') + else + Write(' '); + end; + Writeln; + end; +end; + +begin + PrintSierpinski(4); +end. diff --git a/Task/Sierpinski-triangle/E/sierpinski-triangle-1.e b/Task/Sierpinski-triangle/E/sierpinski-triangle-1.e new file mode 100644 index 0000000000..61a67bd06d --- /dev/null +++ b/Task/Sierpinski-triangle/E/sierpinski-triangle-1.e @@ -0,0 +1,10 @@ +def printSierpinski(order, out) { + def size := 2**order + for y in (0..!size).descending() { + out.print(" " * y) + for x in 0..!(size-y) { + out.print((x & y).isZero().pick("* ", " ")) + } + out.println() + } +} diff --git a/Task/Sierpinski-triangle/E/sierpinski-triangle-2.e b/Task/Sierpinski-triangle/E/sierpinski-triangle-2.e new file mode 100644 index 0000000000..2e6d336b64 --- /dev/null +++ b/Task/Sierpinski-triangle/E/sierpinski-triangle-2.e @@ -0,0 +1 @@ +? printSierpinski(4, stdout) diff --git a/Task/Sierpinski-triangle/E/sierpinski-triangle-3.e b/Task/Sierpinski-triangle/E/sierpinski-triangle-3.e new file mode 100644 index 0000000000..e978f4131f --- /dev/null +++ b/Task/Sierpinski-triangle/E/sierpinski-triangle-3.e @@ -0,0 +1,10 @@ +def printSierpinski(order, out) { + def size := 2**order + for y in (0..!size).descending() { + out.print(" " * y) + for x in 0..!(size-y) { + out.print((x & y).isZero().pick("◢◣", "  ")) + } + out.println() + } +} diff --git a/Task/Sierpinski-triangle/Erlang/sierpinski-triangle.erl b/Task/Sierpinski-triangle/Erlang/sierpinski-triangle.erl new file mode 100644 index 0000000000..b3f1945e64 --- /dev/null +++ b/Task/Sierpinski-triangle/Erlang/sierpinski-triangle.erl @@ -0,0 +1,11 @@ +-module(sierpinski). +-export([triangle/1]). + +triangle(N) -> + F = fun(X) -> io:format("~s~n",[X]) end, + lists:foreach(F, triangle(N, ["*"], " ")). + +triangle(0, Down, _) -> Down; +triangle(N, Down, Sp) -> + NewDown = [Sp++X++Sp || X<-Down]++[X++" "++X || X <- Down], + triangle(N-1, NewDown, Sp++Sp). diff --git a/Task/Sierpinski-triangle/Euphoria/sierpinski-triangle.euphoria b/Task/Sierpinski-triangle/Euphoria/sierpinski-triangle.euphoria new file mode 100644 index 0000000000..0529a4dcea --- /dev/null +++ b/Task/Sierpinski-triangle/Euphoria/sierpinski-triangle.euphoria @@ -0,0 +1,12 @@ +procedure triangle(integer x, integer y, integer len, integer n) + if n = 0 then + position(y,x) puts(1,'*') + else + triangle (x, y+len, floor(len/2), n-1) + triangle (x+len, y, floor(len/2), n-1) + triangle (x+len*2, y+len, floor(len/2), n-1) + end if +end procedure + +clear_screen() +triangle(1,1,8,4) diff --git a/Task/Sierpinski-triangle/FALSE/sierpinski-triangle.false b/Task/Sierpinski-triangle/FALSE/sierpinski-triangle.false new file mode 100644 index 0000000000..a784ab9d56 --- /dev/null +++ b/Task/Sierpinski-triangle/FALSE/sierpinski-triangle.false @@ -0,0 +1,6 @@ +[[$][$1&["*"]?$~1&[" "]?2/]#%" +"]s: { stars } +[$@$@|@@&~&]x: { xor } +[1\[$][1-\2*\]#%]e: { 2^n } +[e;!1\[$][\$s;!$2*x;!\1-]#%%]t: +4t;! diff --git a/Task/Sierpinski-triangle/Factor/sierpinski-triangle.factor b/Task/Sierpinski-triangle/Factor/sierpinski-triangle.factor new file mode 100644 index 0000000000..d1f79da2d8 --- /dev/null +++ b/Task/Sierpinski-triangle/Factor/sierpinski-triangle.factor @@ -0,0 +1,17 @@ +USING: io kernel math sequences ; +IN: sierpinski + +: iterate-triangle ( triange spaces -- triangle' ) + [ [ dup surround ] curry map ] + [ drop [ dup " " glue ] map ] 2bi append ; + +: (sierpinski) ( triangle spaces n -- triangle' ) + dup 0 = [ 2drop "\n" join ] [ + [ + [ iterate-triangle ] + [ nip dup append ] 2bi + ] dip 1 - (sierpinski) + ] if ; + +: sierpinski ( n -- ) + [ { "*" } " " ] dip (sierpinski) print ; diff --git a/Task/Sierpinski-triangle/Forth/sierpinski-triangle.fth b/Task/Sierpinski-triangle/Forth/sierpinski-triangle.fth new file mode 100644 index 0000000000..27b5683acb --- /dev/null +++ b/Task/Sierpinski-triangle/Forth/sierpinski-triangle.fth @@ -0,0 +1,14 @@ +: stars ( mask -- ) + begin + dup 1 and if [char] * else bl then emit + 1 rshift dup + while space repeat drop ; + +: triangle ( order -- ) + 1 swap lshift ( 2^order ) + 1 over 0 do + cr over i - spaces dup stars + dup 2* xor + loop 2drop ; + +5 triangle diff --git a/Task/Sierpinski-triangle/Fortran/sierpinski-triangle.f b/Task/Sierpinski-triangle/Fortran/sierpinski-triangle.f new file mode 100644 index 0000000000..d4f3a5df5d --- /dev/null +++ b/Task/Sierpinski-triangle/Fortran/sierpinski-triangle.f @@ -0,0 +1,29 @@ +program Sierpinski_triangle + implicit none + + call Triangle(4) + +contains + +subroutine Triangle(n) + implicit none + integer, parameter :: i64 = selected_int_kind(18) + integer, intent(in) :: n + integer :: i, k + integer(i64) :: c + + do i = 0, n*4-1 + c = 1 + write(*, "(a)", advance="no") repeat(" ", 2 * (n*4 - 1 - i)) + do k = 0, i + if(mod(c, 2) == 0) then + write(*, "(a)", advance="no") " " + else + write(*, "(a)", advance="no") " * " + end if + c = c * (i - k) / (k + 1) + end do + write(*,*) + end do +end subroutine Triangle +end program Sierpinski_triangle diff --git a/Task/Sierpinski-triangle/GAP/sierpinski-triangle.gap b/Task/Sierpinski-triangle/GAP/sierpinski-triangle.gap new file mode 100644 index 0000000000..6be677e3ff --- /dev/null +++ b/Task/Sierpinski-triangle/GAP/sierpinski-triangle.gap @@ -0,0 +1,38 @@ +# Using parity of binomial coefficients +SierpinskiTriangle := function(n) + local i, j, s, b; + n := 2^n - 1; + b := " "; + while Size(b) < n do + b := Concatenation(b, b); + od; + for i in [0 .. n] do + s := ""; + for j in [0 .. i] do + if IsEvenInt(Binomial(i, j)) then + Append(s, " "); + else + Append(s, "* "); + fi; + od; + Print(b{[1 .. n - i]}, s, "\n"); + od; +end; + +SierpinskiTriangle(4); + * + * * + * * + * * * * + * * + * * * * + * * * * + * * * * * * * * + * * + * * * * + * * * * + * * * * * * * * + * * * * + * * * * * * * * + * * * * * * * * +* * * * * * * * * * * * * * * * diff --git a/Task/Sierpinski-triangle/Go/sierpinski-triangle.go b/Task/Sierpinski-triangle/Go/sierpinski-triangle.go new file mode 100644 index 0000000000..2bfb21dfd4 --- /dev/null +++ b/Task/Sierpinski-triangle/Go/sierpinski-triangle.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "strings" + "unicode/utf8" +) + +var order = 4 +var grain = "*" + +func main() { + t := []string{grain + strings.Repeat(" ", utf8.RuneCountInString(grain))} + for ; order > 0; order-- { + sp := strings.Repeat(" ", utf8.RuneCountInString(t[0])/2) + top := make([]string, len(t)) + for i, s := range t { + top[i] = sp + s + sp + t[i] += s + } + t = append(top, t...) + } + for _, r := range t { + fmt.Println(r) + } +} diff --git a/Task/Sierpinski-triangle/Groovy/sierpinski-triangle-1.groovy b/Task/Sierpinski-triangle/Groovy/sierpinski-triangle-1.groovy new file mode 100644 index 0000000000..3bbd30d3cf --- /dev/null +++ b/Task/Sierpinski-triangle/Groovy/sierpinski-triangle-1.groovy @@ -0,0 +1,16 @@ +def stPoints; +stPoints = { order, base=[0,0] -> + def right = [base[0], base[1]+2**order] + def up = [base[0]+2**(order-1), base[1]+2**(order-1)] + (order == 0) \ + ? [base] + : (stPoints(order-1, base) + stPoints(order-1, right) + stPoints(order-1, up)) +} + +def stGrid = { order -> + def h = 2**order + def w = 2**(order+1) - 1 + def grid = (0..(); + + for (i in 0...(n*2)) line[i] = SPACE; + + line[n] = '*'; + + for (i in 0...n) { + Sys.println(line.join('')); + var u ='*'; + var start = n - i; + var end = n + i + 1; + var t = SPACE; + for (j in start...end) { + t = (line[j-1] == line[j+1] ? SPACE : STAR); + line[j-1] = u; + u = t; + } + + line[n+i] = t; + line[n+i+1] = STAR; + } + } +} diff --git a/Task/Sierpinski-triangle/IDL/sierpinski-triangle.idl b/Task/Sierpinski-triangle/IDL/sierpinski-triangle.idl new file mode 100644 index 0000000000..6a870de0af --- /dev/null +++ b/Task/Sierpinski-triangle/IDL/sierpinski-triangle.idl @@ -0,0 +1,8 @@ +pro sierp,n + s = (t = bytarr(3+2^(n+1))+32b) + t[2^n+1] = 42b + for lines = 1,2^n do begin + print,string( (s = t) ) + for i=1,n_elements(t)-2 do if s[i-1] eq s[i+1] then t[i]=32b else t[i]=42b + end +end diff --git a/Task/Sierpinski-triangle/Icon/sierpinski-triangle.icon b/Task/Sierpinski-triangle/Icon/sierpinski-triangle.icon new file mode 100644 index 0000000000..3ac1f47d76 --- /dev/null +++ b/Task/Sierpinski-triangle/Icon/sierpinski-triangle.icon @@ -0,0 +1,15 @@ +# text based adaptaion of + +procedure main(A) + + width := 2 ^ ( 1 + (order := 0 < integer(\A[1]) | 4)) # order of arg[1] or 4 + write("Triangle order= ",order) + + every !(canvas := list(width)) := list(width," ") # prime the canvas + every y := 1 to width & x := 1 to width do # traverse it + if iand(x - 1, y - 1) = 0 then canvas[x,y] := "*" # fill + + every x := 1 to width & y := 1 to width do + writes((y=1,"\n")|"",canvas[x,y]," ") # print + +end diff --git a/Task/Sierpinski-triangle/J/sierpinski-triangle-1.j b/Task/Sierpinski-triangle/J/sierpinski-triangle-1.j new file mode 100644 index 0000000000..ebd3e32a9a --- /dev/null +++ b/Task/Sierpinski-triangle/J/sierpinski-triangle-1.j @@ -0,0 +1 @@ + |. _31]\ ,(,.~ , ])^:4 ,: '* ' diff --git a/Task/Sierpinski-triangle/J/sierpinski-triangle-2.j b/Task/Sierpinski-triangle/J/sierpinski-triangle-2.j new file mode 100644 index 0000000000..a4037e397d --- /dev/null +++ b/Task/Sierpinski-triangle/J/sierpinski-triangle-2.j @@ -0,0 +1 @@ + ' *' {~ '1' = (- |."_1 [: ": 2 | !/~) i._16 diff --git a/Task/Sierpinski-triangle/Java/sierpinski-triangle-1.java b/Task/Sierpinski-triangle/Java/sierpinski-triangle-1.java new file mode 100644 index 0000000000..2c1b6bf28e --- /dev/null +++ b/Task/Sierpinski-triangle/Java/sierpinski-triangle-1.java @@ -0,0 +1,20 @@ +public static void triangle(int n){ + n= 1 << n; + StringBuilder line= new StringBuilder(); //use a "mutable String" + char t= 0; + char u= 0; // avoid warnings + for(int i= 0;i <= 2 * n;++i) + line.append(" "); //start empty + line.setCharAt(n, '*'); //with the top point of the triangle + for(int i= 0;i < n;++i){ + System.out.println(line); + u= '*'; + for(int j= n - i;j < n + i + 1;++j){ + t= (line.charAt(j - 1) == line.charAt(j + 1) ? ' ' : '*'); + line.setCharAt(j - 1, u); + u= t; + } + line.setCharAt(n + i, t); + line.setCharAt(n + i + 1, '*'); + } +} diff --git a/Task/Sierpinski-triangle/Java/sierpinski-triangle-2.java b/Task/Sierpinski-triangle/Java/sierpinski-triangle-2.java new file mode 100644 index 0000000000..d3c6fd1182 --- /dev/null +++ b/Task/Sierpinski-triangle/Java/sierpinski-triangle-2.java @@ -0,0 +1,27 @@ +import java.util.*; + +public class Sierpinski +{ + public static List sierpinski(int n) + { + List down = Arrays.asList("*"); + String space = " "; + for (int i = 0; i < n; i++) { + List newDown = new ArrayList(); + for (String x : down) + newDown.add(space + x + space); + for (String x : down) + newDown.add(x + " " + x); + + down = newDown; + space += space; + } + return down; + } + + public static void main(String[] args) + { + for (String x : sierpinski(4)) + System.out.println(x); + } +} diff --git a/Task/Sierpinski-triangle/JavaFX-Script/sierpinski-triangle.javafx b/Task/Sierpinski-triangle/JavaFX-Script/sierpinski-triangle.javafx new file mode 100644 index 0000000000..4a218f8fd0 --- /dev/null +++ b/Task/Sierpinski-triangle/JavaFX-Script/sierpinski-triangle.javafx @@ -0,0 +1,14 @@ +function sierpinski(n : Integer) { + var down = ["*"]; + var space = " "; + for (i in [1..n]) { + down = [for (x in down) "{space}{x}{space}", for (x in down) "{x} {x}"]; + space = "{space}{space}"; + } + + for (x in down) { + println("{x}") + } +} + +sierpinski(4); diff --git a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle.js b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle.js new file mode 100644 index 0000000000..1ae62d0c05 --- /dev/null +++ b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle.js @@ -0,0 +1,19 @@ +function triangle(o) { + var n = 1<\n"); +triangle(6); +document.write(""); diff --git a/Task/Sierpinski-triangle/Liberty-BASIC/sierpinski-triangle.liberty b/Task/Sierpinski-triangle/Liberty-BASIC/sierpinski-triangle.liberty new file mode 100644 index 0000000000..b52a1c20e9 --- /dev/null +++ b/Task/Sierpinski-triangle/Liberty-BASIC/sierpinski-triangle.liberty @@ -0,0 +1,15 @@ +nOrder=4 +call triangle 1, 1, nOrder +end + +SUB triangle x, y, n + IF n = 0 THEN + LOCATE x,y: PRINT "*"; + ELSE + n=n-1 + length=2^n + call triangle x, y+length, n + call triangle x+length, y, n + call triangle x+length*2, y+length, n + END IF +END SUB diff --git a/Task/Sierpinski-triangle/Logo/sierpinski-triangle.logo b/Task/Sierpinski-triangle/Logo/sierpinski-triangle.logo new file mode 100644 index 0000000000..f898f01add --- /dev/null +++ b/Task/Sierpinski-triangle/Logo/sierpinski-triangle.logo @@ -0,0 +1,14 @@ +; Print rows of the triangle from 0 to :limit inclusive. +; limit=15 gives the order 4 form per the task. +; The range of :y is arbitrary, any rows of the triangle can be printed. + +make "limit 15 +for [y 0 :limit] [ + for [x -:limit :y] [ + type ifelse (and :y+:x >= 0 ; blank left of triangle + (remainder :y+:x 2) = 0 ; only "even" squares + (bitand :y+:x :y-:x) = 0 ; Sierpinski bit test + ) ["*] ["| |] ; star or space + ] + print [] +] diff --git a/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle.math b/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle.math new file mode 100644 index 0000000000..3d1c5fc630 --- /dev/null +++ b/Task/Sierpinski-triangle/Mathematica/sierpinski-triangle.math @@ -0,0 +1 @@ +n=4;Grid[CellularAutomaton[90,{{1},0},2^n-1]/.{0->" ",1->"*"},ItemSize->All] diff --git a/Task/Sierpinski-triangle/OCaml/sierpinski-triangle.ocaml b/Task/Sierpinski-triangle/OCaml/sierpinski-triangle.ocaml new file mode 100644 index 0000000000..54bd7a53d1 --- /dev/null +++ b/Task/Sierpinski-triangle/OCaml/sierpinski-triangle.ocaml @@ -0,0 +1,13 @@ +let sierpinski n = + let rec loop down space n = + if n = 0 then + down + else + loop (List.map (fun x -> space ^ x ^ space) down @ + List.map (fun x -> x ^ " " ^ x) down) + (space ^ space) + (n - 1) + in loop ["*"] " " n + +let () = + List.iter print_endline (sierpinski 4) diff --git a/Task/Sierpinski-triangle/Oz/sierpinski-triangle.oz b/Task/Sierpinski-triangle/Oz/sierpinski-triangle.oz new file mode 100644 index 0000000000..d5efb9268d --- /dev/null +++ b/Task/Sierpinski-triangle/Oz/sierpinski-triangle.oz @@ -0,0 +1,19 @@ +declare + fun {NextTriangle Triangle} + Sp = {Spaces {Length Triangle}} + in + {Flatten + [{Map Triangle fun {$ X} Sp#X#Sp end} + {Map Triangle fun {$ X} X#" "#X end} + ]} + end + + fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end + + fun lazy {Iterate F X} + X|{Iterate F {F X}} + end + + SierpinskiTriangles = {Iterate NextTriangle ["*"]} +in + {ForAll {Nth SierpinskiTriangles 5} System.showInfo} diff --git a/Task/Sierpinski-triangle/PL-I/sierpinski-triangle.pli b/Task/Sierpinski-triangle/PL-I/sierpinski-triangle.pli new file mode 100644 index 0000000000..b75301e2d0 --- /dev/null +++ b/Task/Sierpinski-triangle/PL-I/sierpinski-triangle.pli @@ -0,0 +1,49 @@ +sierpinski: procedure options (main); /* 2010-03-30 */ + declare t (79,79) char (1); + declare (i, j, k) fixed binary; + declare (y, xs, ys, xll, xrr, ixrr, limit) fixed binary; + + t = ' '; + xs = 40; ys = 1; + /* Make initial triangle */ + call make_triangle (xs, ys); + y = ys + 4; + xll = xs-4; xrr = xs+4; + do k = 1 to 3; + limit = 0; + do forever; + ixrr = xrr; + do i = xll to xll+limit by 8; + if t(y-1, i) = ' ' then + do; + call make_triangle (i, y); + if t(y+3,i-5) = '*' then + t(y+3,i-4), t(y+3,ixrr+4) = '*'; + call make_triangle (ixrr, y); + end; + ixrr = ixrr - 8; + end; + xll = xll - 4; xrr = xrr + 4; + y = y + 4; + limit = limit + 8; + if xll+limit > xs-1 then leave; + end; + t(y-1,xs) = '*'; + end; + + /* Finished generation; now print the Sierpinski triangle. */ + put edit (t) (skip, (hbound(t,2)) a); + +make_triangle: procedure (x, y); + declare (x, y) fixed binary; + declare i fixed binary; + + do i = 0 to 3; + t(y+i, x-i), t(y+i, x+i) = '*'; + end; + do i = x-2 to x+2; /* The base of the triangle. */ + t(y+3, i) = '*'; + end; +end make_triangle; + +end sierpinski; diff --git a/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-1.pascal b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-1.pascal new file mode 100644 index 0000000000..a1b9f6dcf3 --- /dev/null +++ b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-1.pascal @@ -0,0 +1,18 @@ +program Sierpinski; + +function ipow(b, n : Integer) : Integer; +var + i : Integer; +begin + ipow := 1; + for i := 1 to n do + ipow := ipow * b +end; + +function truth(a : Char) : Boolean; +begin + if a = '*' then + truth := true + else + truth := false +end; diff --git a/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-2.pascal b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-2.pascal new file mode 100644 index 0000000000..46a16da75a --- /dev/null +++ b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-2.pascal @@ -0,0 +1,41 @@ +function rule_90(ev : String) : String; +var + l, i : Integer; + cp : String; + s : Array[0..1] of Boolean; +begin + l := length(ev); + cp := copy(ev, 1, l); + for i := 1 to l do begin + if (i-1) < 1 then + s[0] := false + else + s[0] := truth(ev[i-1]); + if (i+1) > l then + s[1] := false + else + s[1] := truth(ev[i+1]); + if ( (s[0] and not s[1]) or (s[1] and not s[0]) ) then + cp[i] := '*' + else + cp[i] := ' '; + end; + rule_90 := cp +end; + +procedure triangle(n : Integer); +var + i, l : Integer; + b : String; +begin + l := ipow(2, n+1); + b := ' '; + for i := 1 to l do + b := concat(b, ' '); + b[round(l/2)] := '*'; + writeln(b); + for i := 1 to (round(l/2)-1) do begin + b := rule_90(b); + writeln(b) + end +end; diff --git a/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-3.pascal b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-3.pascal new file mode 100644 index 0000000000..ebb018011d --- /dev/null +++ b/Task/Sierpinski-triangle/Pascal/sierpinski-triangle-3.pascal @@ -0,0 +1,3 @@ +begin + triangle(4) +end. diff --git a/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 new file mode 100644 index 0000000000..5fd4048634 --- /dev/null +++ b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 @@ -0,0 +1,11 @@ +sub sierpinski ($n) { + my @down = '*'; + my $space = ' '; + for ^$n { + @down = @down.map({"$space$_$space"}), @down.map({"$_ $_"}); + $space ~= $space; + } + return @down; +} + +.say for sierpinski 4; diff --git a/Task/Sierpinski-triangle/Perl/sierpinski-triangle.pl b/Task/Sierpinski-triangle/Perl/sierpinski-triangle.pl new file mode 100644 index 0000000000..2c420e7225 --- /dev/null +++ b/Task/Sierpinski-triangle/Perl/sierpinski-triangle.pl @@ -0,0 +1,12 @@ +sub sierpinski { + my ($n) = @_; + my @down = '*'; + my $space = ' '; + foreach (1..$n) { + @down = (map("$space$_$space", @down), map("$_ $_", @down)); + $space = "$space$space"; + } + return @down; +} + +print "$_\n" foreach sierpinski 4; diff --git a/Task/Sierpinski-triangle/PicoLisp/sierpinski-triangle.l b/Task/Sierpinski-triangle/PicoLisp/sierpinski-triangle.l new file mode 100644 index 0000000000..46a5beb765 --- /dev/null +++ b/Task/Sierpinski-triangle/PicoLisp/sierpinski-triangle.l @@ -0,0 +1,11 @@ +(de sierpinski (N) + (let (D '("*") S " ") + (do N + (setq + D (conc + (mapcar '((X) (pack S X S)) D) + (mapcar '((X) (pack X " " X)) D) ) + S (pack S S) ) ) + D ) ) + +(mapc prinl (sierpinski 4)) diff --git a/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-1.pop11 b/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-1.pop11 new file mode 100644 index 0000000000..d38fd1c828 --- /dev/null +++ b/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-1.pop11 @@ -0,0 +1,21 @@ +define triangle(n); + lvars k = 2**n, j, l, oline, nline; + initv(2*k+3) -> oline; + initv(2*k+3) -> nline; + for l from 1 to 2*k+3 do 0 -> oline(l) ; endfor; + 1 -> oline(k+2); + 0 -> nline(1); + 0 -> nline(2*k+3); + for j from 1 to k do + for l from 1 to 2*k+3 do + printf(if oline(l) = 0 then ' ' else '*' endif); + endfor; + printf('\n'); + for l from 2 to 2*k+2 do + (oline(l-1) + oline(l+1)) rem 2 -> nline(l); + endfor; + (oline, nline) -> (nline, oline); + endfor; +enddefine; + +triangle(4); diff --git a/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-2.pop11 b/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-2.pop11 new file mode 100644 index 0000000000..d5b504143e --- /dev/null +++ b/Task/Sierpinski-triangle/Pop11/sierpinski-triangle-2.pop11 @@ -0,0 +1,11 @@ +define triangle2(n); + lvars acc = ['*'], spaces = ' ', j; + for j from 1 to n do + maplist(acc, procedure(x); spaces >< x >< spaces ; endprocedure) + <> maplist(acc, procedure(x); x >< ' ' >< x ; endprocedure) -> acc; + spaces >< spaces -> spaces; + endfor; + applist(acc, procedure(x); printf(x, '%p\n'); endprocedure); +enddefine; + +triangle2(4); diff --git a/Task/Sierpinski-triangle/PostScript/sierpinski-triangle.ps b/Task/Sierpinski-triangle/PostScript/sierpinski-triangle.ps new file mode 100644 index 0000000000..8b934f8ee6 --- /dev/null +++ b/Task/Sierpinski-triangle/PostScript/sierpinski-triangle.ps @@ -0,0 +1,15 @@ +%!PS-Adobe-3.0 +%%BoundingBox 0 0 300 300 + +/F { 1 0 rlineto } def +/+ { 120 rotate } def +/- {-120 rotate } def +/v {.5 .5 scale } def +/^ { 2 2 scale } def +/!0{ dup 1 sub dup -1 eq not } def + +/X { !0 { v X + F - X - F + X ^ } { F } ifelse pop } def + +0 1 8 { 300 300 scale 0 1 12 div moveto + X + F + F fill showpage } for +%%EOF diff --git a/Task/Sierpinski-triangle/PowerShell/sierpinski-triangle.psh b/Task/Sierpinski-triangle/PowerShell/sierpinski-triangle.psh new file mode 100644 index 0000000000..33667d6717 --- /dev/null +++ b/Task/Sierpinski-triangle/PowerShell/sierpinski-triangle.psh @@ -0,0 +1,21 @@ +function triangle($o) { + $n = [Math]::Pow(2, $o) + $line = ,' '*(2*$n+1) + $line[$n] = '█' + $OFS = '' + for ($i = 0; $i -lt $n; $i++) { + Write-Host $line + $u = '█' + for ($j = $n - $i; $j -lt $n + $i + 1; $j++) { + if ($line[$j-1] -eq $line[$j+1]) { + $t = ' ' + } else { + $t = '█' + } + $line[$j-1] = $u + $u = $t + } + $line[$n+$i] = $t + $line[$n+$i+1] = '█' + } +} diff --git a/Task/Sierpinski-triangle/Prolog/sierpinski-triangle.pro b/Task/Sierpinski-triangle/Prolog/sierpinski-triangle.pro new file mode 100644 index 0000000000..0e06f7f1e6 --- /dev/null +++ b/Task/Sierpinski-triangle/Prolog/sierpinski-triangle.pro @@ -0,0 +1,40 @@ +sierpinski_triangle(N) :- + Len is 2 ** (N+1) - 1, + length(L, Len), + numlist(1, Len, LN), + maplist(init(N), L, LN), + atomic_list_concat(L, Line), + writeln(Line), + NbTours is 2**N - 1, + loop(NbTours, LN, Len, L). + +init(N, Cell, Num) :- + ( Num is 2 ** N + 1 -> Cell = *; Cell = ' '). + +loop(0, _, _, _) :- !. + +loop(N, LN, Len, L) :- + maplist(compute_next_line(Len, L), LN, L1), + atomic_list_concat(L1, Line), + writeln(Line), + N1 is N - 1, + loop(N1, LN, Len, L1). + + + +compute_next_line(Len, L, I, V) :- + I1 is I - 1, + I2 is I+1, + ( I = 1 -> V0 = ' '; nth1(I1, L, V0)), + nth1(I, L, V1), + ( I = Len -> V2 = ' '; nth1(I2, L, V2)), + rule_90(V0, V1, V2, V). + +rule_90('*','*','*', ' '). +rule_90('*','*',' ', '*'). +rule_90('*',' ','*', ' '). +rule_90('*',' ',' ', '*'). +rule_90(' ','*','*', '*'). +rule_90(' ','*',' ', ' '). +rule_90(' ',' ','*', '*'). +rule_90(' ',' ',' ', ' '). diff --git a/Task/Sierpinski-triangle/PureBasic/sierpinski-triangle.purebasic b/Task/Sierpinski-triangle/PureBasic/sierpinski-triangle.purebasic new file mode 100644 index 0000000000..2b795dedd3 --- /dev/null +++ b/Task/Sierpinski-triangle/PureBasic/sierpinski-triangle.purebasic @@ -0,0 +1,20 @@ +Procedure Triangle (X,Y, Length, N) + If N = 0 + DrawText( Y,X, "*",#Blue) + Else + Triangle (X+Length, Y, Length/2, N-1) + Triangle (X, Y+Length, Length/2, N-1) + Triangle (X+Length, Y+Length*2, Length/2, N-1) + EndIf +EndProcedure + + +OpenWindow(0, 100, 100,700,500 ,"Sierpinski triangle", #PB_Window_SystemMenu |1) +StartDrawing(WindowOutput(0)) + DrawingMode(#PB_2DDrawing_Transparent ) + Triangle(10,10,120,5) +StopDrawing() + +Repeat +Until WaitWindowEvent()=#PB_Event_CloseWindow +End diff --git a/Task/Sierpinski-triangle/Python/sierpinski-triangle-1.py b/Task/Sierpinski-triangle/Python/sierpinski-triangle-1.py new file mode 100644 index 0000000000..9d211978d5 --- /dev/null +++ b/Task/Sierpinski-triangle/Python/sierpinski-triangle-1.py @@ -0,0 +1,8 @@ +def sierpinski(n): + d = ["*"] + for i in xrange(n): + sp = " " * (2 ** i) + d = [sp+x+sp for x in d] + [x+" "+x for x in d] + return d + +print "\n".join(sierpinski(4)) diff --git a/Task/Sierpinski-triangle/Python/sierpinski-triangle-2.py b/Task/Sierpinski-triangle/Python/sierpinski-triangle-2.py new file mode 100644 index 0000000000..e63977ebe0 --- /dev/null +++ b/Task/Sierpinski-triangle/Python/sierpinski-triangle-2.py @@ -0,0 +1,11 @@ +import functools + +def sierpinski(n): + + def aggregate(TRIANGLE, I): + SPACE = " " * (2 ** I) + return [SPACE+X+SPACE for X in TRIANGLE] + [X+" "+X for X in TRIANGLE] + + return functools.reduce(aggregate, range(n), ["*"]) + +print("\n".join(sierpinski(4))) diff --git a/Task/Sierpinski-triangle/R/sierpinski-triangle-1.r b/Task/Sierpinski-triangle/R/sierpinski-triangle-1.r new file mode 100644 index 0000000000..ea27c43a70 --- /dev/null +++ b/Task/Sierpinski-triangle/R/sierpinski-triangle-1.r @@ -0,0 +1,13 @@ +sierpinski.triangle = function(n) { + len <- 2^(n+1) + b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2)) + for (i in 1:(len/2)) + { + cat(paste(ifelse(b,"*"," "),collapse=""),"\n") + n <- rep(FALSE,len+1) + n[which(b)-1]<-TRUE + n[which(b)+1]<-xor(n[which(b)+1],TRUE) + b <- n + } +} +sierpinski.triangle(5) diff --git a/Task/Sierpinski-triangle/R/sierpinski-triangle-2.r b/Task/Sierpinski-triangle/R/sierpinski-triangle-2.r new file mode 100644 index 0000000000..6a982c4ad1 --- /dev/null +++ b/Task/Sierpinski-triangle/R/sierpinski-triangle-2.r @@ -0,0 +1,4 @@ +sierpinski.triangle = function(n) { + c(paste(ifelse(b<<- c(rep(FALSE,2^(n+1)/2),TRUE,rep(FALSE,2^(n+1)/2)),"*"," "),collapse=""),replicate(2^n-1,paste(ifelse(b<<-xor(c(FALSE,b[1:2^(n+1)]),c(b[2:(2^(n+1)+1)],FALSE)),"*"," "),collapse=""))) +} +cat(sierpinski.triangle(5),sep="\n") diff --git a/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx b/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx new file mode 100644 index 0000000000..a91980184e --- /dev/null +++ b/Task/Sierpinski-triangle/REXX/sierpinski-triangle.rexx @@ -0,0 +1,17 @@ +/*REXX program draws a Sierpinski triangle of up to around order 10k. */ +parse arg n mk . /*get the order of the triangle. */ +if n=='' | n==',' then n=4 /*if none specified, assume 4. */ +if mk=='' then mk='*' /*use the default of an asterisk.*/ +if length(mk)==2 then mk=x2c(mk) /*MK was specified in hexadecimal*/ +if length(mk)==3 then mk=d2c(mk) /*MK was specified in decimal. */ +numeric digits 12000 /*this otta handle the die-hards.*/ + + do j=0 for n*4; !=1; z=left('',n*4-1-j) /*indent the line. */ + do k=0 to j /*build the line with J+1 parts*/ + if !//2==0 then z=z' ' /*it's either a blank, or ... */ + else z=z mk /*it's one of them thar character*/ + !=!*(j-k)%(k+1) /*calculate a handy-dandy thingy.*/ + end /*k*/ + say z /*display a line of the triangle.*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb new file mode 100644 index 0000000000..a4cd0712ef --- /dev/null +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb @@ -0,0 +1 @@ +ruby -le'16.times{|y|print" "*(15-y),(0..y).map{|x|~y&x>0?" ":" *"}}' diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb new file mode 100644 index 0000000000..c3f6244522 --- /dev/null +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb @@ -0,0 +1,11 @@ +def sierpinski_triangle(n) + triangle = ["*"] + n.times do |i| + sp = " " * (2**i) + triangle = triangle.collect {|x| sp + x + sp} + \ + triangle.collect {|x| x + " " + x} + end + triangle.join("\n") +end + +puts sierpinski_triangle(4) diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb new file mode 100644 index 0000000000..4236273765 --- /dev/null +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb @@ -0,0 +1,9 @@ +def sierpinski_triangle(n) + + (0..(n-1)).inject(["*"]) {|triangle, i| + space = " " * (2**i) + triangle.map {|x| space + x + space} + triangle.map {|x| x + " " + x} + } +end + +puts sierpinski_triangle(4) diff --git a/Task/Sierpinski-triangle/Scala/sierpinski-triangle-1.scala b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-1.scala new file mode 100644 index 0000000000..3d5253a3e8 --- /dev/null +++ b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-1.scala @@ -0,0 +1 @@ +scala -e "for(y<-0 to 15){println(\" \"*(15-y)++(0 to y).map(x=>if((~y&x)>0)\" \"else\" *\")mkString)}" diff --git a/Task/Sierpinski-triangle/Scala/sierpinski-triangle-2.scala b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-2.scala new file mode 100644 index 0000000000..1596537a63 --- /dev/null +++ b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-2.scala @@ -0,0 +1,10 @@ +def sierpinski(n: Int) { + def star(n: Long) = if ((n & 1L) == 1L) "*" else " " + def stars(n: Long): String = if (n == 0L) "" else star(n) + " " + stars(n >> 1) + def spaces(n: Int) = " " * n + ((1 << n) - 1 to 0 by -1).foldLeft(1L) { + case (bitmap, remainingLines) => + println(spaces(remainingLines) + stars(bitmap)) + (bitmap << 1) ^ bitmap + } +} diff --git a/Task/Sierpinski-triangle/Scala/sierpinski-triangle-3.scala b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-3.scala new file mode 100644 index 0000000000..a6265f2492 --- /dev/null +++ b/Task/Sierpinski-triangle/Scala/sierpinski-triangle-3.scala @@ -0,0 +1,12 @@ +def printSierpinski(n: Int) { + def sierpinski(n: Int): List[String] = { + lazy val down = sierpinski(n - 1) + lazy val space = " " * (1 << (n - 1)) + n match { + case 0 => List("*") + case _ => (down map (space + _ + space)) ::: + (down map (List.fill(2)(_) mkString " ")) + } + } + sierpinski(n) foreach println +} diff --git a/Task/Sierpinski-triangle/Scheme/sierpinski-triangle.ss b/Task/Sierpinski-triangle/Scheme/sierpinski-triangle.ss new file mode 100644 index 0000000000..e681ab2206 --- /dev/null +++ b/Task/Sierpinski-triangle/Scheme/sierpinski-triangle.ss @@ -0,0 +1,12 @@ +(define (sierpinski n) + (for-each + (lambda (x) (display (list->string x)) (newline)) + (let loop ((acc (list (list #\*))) (spaces (list #\ )) (n n)) + (if (zero? n) + acc + (loop + (append + (map (lambda (x) (append spaces x spaces)) acc) + (map (lambda (x) (append x (list #\ ) x)) acc)) + (append spaces spaces) + (- n 1)))))) diff --git a/Task/Sierpinski-triangle/Seed7/sierpinski-triangle.seed7 b/Task/Sierpinski-triangle/Seed7/sierpinski-triangle.seed7 new file mode 100644 index 0000000000..fd068e54b0 --- /dev/null +++ b/Task/Sierpinski-triangle/Seed7/sierpinski-triangle.seed7 @@ -0,0 +1,28 @@ +$ include "seed7_05.s7i"; + +const func array string: sierpinski (in integer: n) is func + result + var array string: parts is 1 times "*"; + local + var integer: i is 0; + var string: space is " "; + var array string: parts2 is 0 times ""; + var string: x is ""; + begin + for i range 1 to n do + parts2 := 0 times ""; + for x range parts do + parts2 &:= [] (space & x & space); + end for; + for x range parts do + parts2 &:= [] (x & " " & x); + end for; + parts := parts2; + space &:= space; + end for; + end func; + +const proc: main is func + begin + writeln(join(sierpinski(4), "\n")); + end func; diff --git a/Task/Sierpinski-triangle/TI-83-BASIC/sierpinski-triangle.ti-83 b/Task/Sierpinski-triangle/TI-83-BASIC/sierpinski-triangle.ti-83 new file mode 100644 index 0000000000..2a8cb47ed6 --- /dev/null +++ b/Task/Sierpinski-triangle/TI-83-BASIC/sierpinski-triangle.ti-83 @@ -0,0 +1,30 @@ +PROGRAM:SIRPNSKI +:ClrHome +:Output(1,8,"^") +:{0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}→L1 +:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}→L2 +:L2→L3 +:For(X,2,8,1) +:For(Y,2,17,1) +:If L1(Y-1) +:Then +:4→N +:End +:If L1(Y) +:Then +:N+2→N +:End +:If L1(Y+1) +:Then +:N+1→N +:End +:If N=1 or N=3 or N=4 or N=6 +:Then +:1→L2(Y) +:Output(X,Y-1,"^") +:End +:0→N +:End +:L2→L1 +:L3→L2 +:End diff --git a/Task/Sierpinski-triangle/Tcl/sierpinski-triangle.tcl b/Task/Sierpinski-triangle/Tcl/sierpinski-triangle.tcl new file mode 100644 index 0000000000..35d741acf1 --- /dev/null +++ b/Task/Sierpinski-triangle/Tcl/sierpinski-triangle.tcl @@ -0,0 +1,23 @@ +package require Tcl 8.5 + +proc map {lambda list} { + foreach elem $list { + lappend result [apply $lambda $elem] + } + return $result +} + +proc sierpinski_triangle n { + set down [list *] + set space " " + for {set i 1} {$i <= $n} {incr i} { + set down [concat \ + [map [subst -nocommands {x {expr {"$space[set x]$space"}}}] $down] \ + [map {x {expr {"$x $x"}}} $down] \ + ] + append space $space + } + return [join $down \n] +} + +puts [sierpinski_triangle 4] diff --git a/Task/Sierpinski-triangle/Unlambda/sierpinski-triangle.unlambda b/Task/Sierpinski-triangle/Unlambda/sierpinski-triangle.unlambda new file mode 100644 index 0000000000..309cc875da --- /dev/null +++ b/Task/Sierpinski-triangle/Unlambda/sierpinski-triangle.unlambda @@ -0,0 +1,5 @@ +```ci``s``s`ks``s`k`s``s`kc``s``s``si`kr`k. `k.*k +`k``s``s``s``s`s`k`s``s`ksk`k``s``si`kk`k``s`kkk +`k``s`k`s``si`kk``s`kk``s``s``s``si`kk`k`s`k`s``s`ksk`k`s`k`s`k`si``si`k`ki +`k``s`k`s``si`k`ki``s`kk``s``s``s``si`kk`k`s`k`s`k`si`k`s`k`s``s`ksk``si`k`ki +`k`ki``s`k`s`k`si``s`kkk diff --git a/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-1.ursala b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-1.ursala new file mode 100644 index 0000000000..8c9bbf96df --- /dev/null +++ b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-1.ursala @@ -0,0 +1,3 @@ +#import nat + +triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor diff --git a/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-2.ursala b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-2.ursala new file mode 100644 index 0000000000..cff3167dfd --- /dev/null +++ b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-2.ursala @@ -0,0 +1,6 @@ +#import std +#import nat + +rule = -$<0,&,0,0,&,0,0,0>@rSS zipp0*ziD iota8 +evolve "n" = @iNC ~&x+ rep"n" ^C\~& @h rule*+ swin3+ :/0+ --<0> +sierpinski = iota; --<&>@NS; iota; ^H/evolve@z @NS ^T/~& :/& diff --git a/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-3.ursala b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-3.ursala new file mode 100644 index 0000000000..f8e3d1a5b1 --- /dev/null +++ b/Task/Sierpinski-triangle/Ursala/sierpinski-triangle-3.ursala @@ -0,0 +1,3 @@ +#show+ + +examples = mat0 ~&?(`*!,` !)*** diff --git a/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-1.vedit b/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-1.vedit new file mode 100644 index 0000000000..3495ca5d8d --- /dev/null +++ b/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-1.vedit @@ -0,0 +1,18 @@ +#3 = 16 // size (height) of the triangle +Buf_Switch(Buf_Free) // Open a new buffer for output +Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces +Ins_Newline +Line(-1) Goto_Col(#3) +Ins_Char('*', OVERWRITE) // the top of triangle +for (#10=0; #10 < #3-1; #10++) { + BOL Reg_Copy(9,1) Reg_Ins(9) // duplicate the line + #20 = '*' + for (#11 = #3-#10; #11 < #3+#10+1; #11++) { + Goto_Col(#11-1) + if (Cur_Char==Cur_Char(2)) { #21=' ' } else { #21='*' } + Ins_Char(#20, OVERWRITE) + #20 = #21 + } + Ins_Char(#21, OVERWRITE) + Ins_Char('*', OVERWRITE) +} diff --git a/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-2.vedit b/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-2.vedit new file mode 100644 index 0000000000..c4bb8cc163 --- /dev/null +++ b/Task/Sierpinski-triangle/Vedit-macro-language/sierpinski-triangle-2.vedit @@ -0,0 +1,29 @@ +#1 = 1 // x +#2 = 1 // y +#3 = 16 // length (height of the triangle / 2) +#4 = 5 // depth of recursion + +Buf_Switch(Buf_Free) // Open a new buffer for output +Ins_Newline(#3*2) // Create as many empty lines as needed +Call("Triangle") // Draw the triangle +BOF +Return + +:Triangle: +if (#4 == 0) { + Goto_Line(#2) + EOL Ins_Char(' ', COUNT, #1-Cur_Col+1) // add spaces if needed + Goto_Col(#1) + Ins_Char('*', OVERWRITE) +} else { + Num_Push(1,4) + #2 += #3; #3 /= 2; #4--; Call("Triangle") + Num_Pop(1,4) + Num_Push(1,4) + #1 += #3; #3 /= 2; #4--; Call("Triangle") + Num_Pop(1,4) + Num_Push(1,4) + #1 += 2*#3; #2 += #3; #3 /= 2; #4--; Call("Triangle") + Num_Pop(1,4) +} +Return diff --git a/Task/Sierpinski-triangle/X86-Assembly/sierpinski-triangle.x86 b/Task/Sierpinski-triangle/X86-Assembly/sierpinski-triangle.x86 new file mode 100644 index 0000000000..a231b45ad5 --- /dev/null +++ b/Task/Sierpinski-triangle/X86-Assembly/sierpinski-triangle.x86 @@ -0,0 +1,28 @@ + .model tiny + .code + .486 + org 100h +start: xor ebx, ebx ;S1:= 0 + mov edx, 8000h ;S2:= $8000 + mov cx, 16 ;for I:= Size downto 1 +tri10: mov ebx, edx ; S1:= S2 +tri15: test edx, edx ; while S2#0 + je tri20 + mov al, '*' ; ChOut + test dl, 01h ; if S2&1 then '*' else ' ' + jne tri18 + mov al, ' ' +tri18: int 29h + shr edx, 1 ; S2>>1 + jmp tri15 +tri20: mov al, 0Dh ;new line + int 29h + mov al, 0Ah + int 29h + shl ebx, 1 ;S2:= S2 xor S1<<1 + xor edx, ebx + shr ebx, 2 ;S2:= S2 xor S1>>1 + xor edx, ebx + loop tri10 ;next I + ret + end start diff --git a/Task/Sierpinski-triangle/XPL0/sierpinski-triangle.xpl0 b/Task/Sierpinski-triangle/XPL0/sierpinski-triangle.xpl0 new file mode 100644 index 0000000000..51db9e7b06 --- /dev/null +++ b/Task/Sierpinski-triangle/XPL0/sierpinski-triangle.xpl0 @@ -0,0 +1,13 @@ +code ChOut=8, CrLf=9; +def Order=4, Size=1<>1]; + CrLf(0); + S2:= S2 xor S1<<1; + S2:= S2 xor S1>>1; + ]; +] diff --git a/Task/Sieve-of-Eratosthenes/0DESCRIPTION b/Task/Sieve-of-Eratosthenes/0DESCRIPTION new file mode 100644 index 0000000000..1e7e8981ac --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/0DESCRIPTION @@ -0,0 +1,11 @@ +{{clarified-review}} +The [[wp:Sieve_of_Eratosthenes|Sieve of Eratosthenes]] is a simple algorithm that finds the prime numbers up to a given integer. Implement this algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed ''wheels'', i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. + +If there's an easy way to add such a wheel based optimization, implement this as an alternative version. + +;Note: +* It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. + +;Cf: +* [[Primality by trial division]]. +* [[Prime decomposition]]. diff --git a/Task/Sieve-of-Eratosthenes/1META.yaml b/Task/Sieve-of-Eratosthenes/1META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Sieve-of-Eratosthenes/ACL2/sieve-of-eratosthenes.acl2 b/Task/Sieve-of-Eratosthenes/ACL2/sieve-of-eratosthenes.acl2 new file mode 100644 index 0000000000..d174a8ed16 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ACL2/sieve-of-eratosthenes.acl2 @@ -0,0 +1,30 @@ +(defun nats-to-from (n i) + (declare (xargs :measure (nfix (- n i)))) + (if (zp (- n i)) + nil + (cons i (nats-to-from n (+ i 1))))) + +(defun remove-multiples-up-to-r (factor limit xs i) + (declare (xargs :measure (nfix (- limit i)))) + (if (or (> i limit) + (zp (- limit i)) + (zp factor)) + xs + (remove-multiples-up-to-r + factor + limit + (remove i xs) + (+ i factor)))) + +(defun remove-multiples-up-to (factor limit xs) + (remove-multiples-up-to-r factor limit xs (* factor 2))) + +(defun sieve-r (factor limit) + (declare (xargs :measure (nfix (- limit factor)))) + (if (zp (- limit factor)) + (nats-to-from limit 2) + (remove-multiples-up-to factor (+ limit 1) + (sieve-r (1+ factor) limit)))) + +(defun sieve (limit) + (sieve-r 2 limit)) diff --git a/Task/Sieve-of-Eratosthenes/ALGOL-68/sieve-of-eratosthenes.alg b/Task/Sieve-of-Eratosthenes/ALGOL-68/sieve-of-eratosthenes.alg new file mode 100644 index 0000000000..0bca3596a8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ALGOL-68/sieve-of-eratosthenes.alg @@ -0,0 +1,18 @@ +BOOL prime = TRUE, non prime = FALSE; +PROC eratosthenes = (INT n)[]BOOL: +( + [n]BOOL sieve; + FOR i TO UPB sieve DO sieve[i] := prime OD; + INT m = ENTIER sqrt(n); + sieve[1] := non prime; + FOR i FROM 2 TO m DO + IF sieve[i] = prime THEN + FOR j FROM i*i BY i TO n DO + sieve[j] := non prime + OD + FI + OD; + sieve +); + + print((eratosthenes(80),new line)) diff --git a/Task/Sieve-of-Eratosthenes/Ada/sieve-of-eratosthenes.ada b/Task/Sieve-of-Eratosthenes/Ada/sieve-of-eratosthenes.ada new file mode 100644 index 0000000000..ae5e5508bb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ada/sieve-of-eratosthenes.ada @@ -0,0 +1,28 @@ +with Ada.Text_IO, Ada.Command_Line; + +procedure Eratos is + + Last: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + Prime: array(1 .. Last) of Boolean := (1 => False, others => True); + Base: Positive := 2; + Cnt: Positive; +begin + loop + exit when Base * Base > Last; + if Prime(Base) then + Cnt := Base + Base; + loop + exit when Cnt > Last; + Prime(Cnt) := False; + Cnt := Cnt + Base; + end loop; + end if; + Base := Base + 1; + end loop; + Ada.Text_IO.Put("Primes less or equal" & Positive'Image(Last) &" are:"); + for Number in Prime'Range loop + if Prime(Number) then + Ada.Text_IO.Put(Positive'Image(Number)); + end if; + end loop; +end Eratos; diff --git a/Task/Sieve-of-Eratosthenes/AutoHotkey/sieve-of-eratosthenes.ahk b/Task/Sieve-of-Eratosthenes/AutoHotkey/sieve-of-eratosthenes.ahk new file mode 100644 index 0000000000..6375103d26 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/AutoHotkey/sieve-of-eratosthenes.ahk @@ -0,0 +1,16 @@ +MsgBox % "12345678901234567890`n" Sieve(20) + +Sieve(n) { ; Sieve of Eratosthenes => string of 0|1 chars, 1 at position k: k is prime + Static zero := 48, one := 49 ; Asc("0"), Asc("1") + VarSetCapacity(S,n,one) + NumPut(zero,S,0,"char") + i := 2 + Loop % sqrt(n)-1 { + If (NumGet(S,i-1,"char") = one) + Loop % n//i + If (A_Index > 1) + NumPut(zero,S,A_Index*i-1,"char") + i += 1+(i>2) + } + Return S +} diff --git a/Task/Sieve-of-Eratosthenes/AutoIt/sieve-of-eratosthenes.autoit b/Task/Sieve-of-Eratosthenes/AutoIt/sieve-of-eratosthenes.autoit new file mode 100644 index 0000000000..d726913ee1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/AutoIt/sieve-of-eratosthenes.autoit @@ -0,0 +1,15 @@ +#include +$M = InputBox("Integer", "Enter biggest Integer") +Global $a[$M], $r[$M], $c = 1 +For $i = 2 To $M -1 + If Not $a[$i] Then + $r[$c] = $i + $c += 1 + For $k = $i To $M -1 Step $i + $a[$k] = True + Next + EndIf +Next +$r[0] = $c - 1 +ReDim $r[$c] +_ArrayDisplay($r) diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-1.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-1.basic new file mode 100644 index 0000000000..d10a9604a7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-1.basic @@ -0,0 +1,17 @@ +DIM n AS Integer, k AS Integer, limit AS Integer + +INPUT "Enter number to search to: "; limit +DIM flags(limit) AS Integer + +FOR n = 2 TO SQR(limit) + IF flags(n) = 0 THEN + FOR k = n*n TO limit STEP n + flags(k) = 1 + NEXT k + END IF +NEXT n + +' Display the primes +FOR n = 2 TO limit + IF flags(n) = 0 THEN PRINT n; ", "; +NEXT n diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-2.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-2.basic new file mode 100644 index 0000000000..949290fc89 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-2.basic @@ -0,0 +1,12 @@ +10 INPUT "ENTER NUMBER TO SEARCH TO: ";LIMIT +20 DIM FLAGS(LIMIT) +30 FOR N = 2 TO SQR (LIMIT) +40 IF FLAGS(N) < > 0 GOTO 80 +50 FOR K = N * N TO LIMIT STEP N +60 FLAGS(K) = 1 +70 NEXT K +80 NEXT N +90 REM DISPLAY THE PRIMES +100 FOR N = 2 TO LIMIT +110 IF FLAGS(N) = 0 THEN PRINT N;", "; +120 NEXT N diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-3.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-3.basic new file mode 100644 index 0000000000..bfdb78c672 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-3.basic @@ -0,0 +1,12 @@ +10 DEFINT a-z +20 INPUT "Limit";limit +30 DIM f(limit) +40 FOR n=2 TO SQR(limit) +50 IF f(n)=1 THEN 90 +60 FOR k=n*n TO limit STEP n +70 f(k)=1 +80 NEXT k +90 NEXT n +100 FOR n=2 TO limit +110 IF f(n)=0 THEN PRINT n;","; +120 NEXT diff --git a/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-4.basic b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-4.basic new file mode 100644 index 0000000000..62e826386b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BASIC/sieve-of-eratosthenes-4.basic @@ -0,0 +1,12 @@ +10 INPUT "Enter number to search to: ";l +20 DIM p(l) +30 FOR n=2 TO SQR l +40 IF p(n)<>0 THEN NEXT n +50 FOR k=n*n TO l STEP n +60 LET p(k)=1 +70 NEXT k +80 NEXT n +90 REM Display the primes +100 FOR n=2 TO l +110 IF p(n)=0 THEN PRINT n;", "; +120 NEXT n diff --git a/Task/Sieve-of-Eratosthenes/BBC-BASIC/sieve-of-eratosthenes.bbc b/Task/Sieve-of-Eratosthenes/BBC-BASIC/sieve-of-eratosthenes.bbc new file mode 100644 index 0000000000..511f39a959 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/BBC-BASIC/sieve-of-eratosthenes.bbc @@ -0,0 +1,15 @@ + limit% = 100000 + DIM sieve% limit% + + prime% = 2 + WHILE prime%^2 < limit% + FOR I% = prime%*2 TO limit% STEP prime% + sieve%?I% = 1 + NEXT + REPEAT prime% += 1 : UNTIL sieve%?prime%=0 + ENDWHILE + + REM Display the primes: + FOR I% = 1 TO limit% + IF sieve%?I% = 0 PRINT I%; + NEXT diff --git a/Task/Sieve-of-Eratosthenes/Bracmat/sieve-of-eratosthenes.bracmat b/Task/Sieve-of-Eratosthenes/Bracmat/sieve-of-eratosthenes.bracmat new file mode 100644 index 0000000000..0fe8d12892 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Bracmat/sieve-of-eratosthenes.bracmat @@ -0,0 +1,22 @@ +( ( eratosthenes + = n j i + . !arg:?n + & 1:?i + & whl + ' ( (1+!i:?i)^2:~>!n:?j + & ( !!i + | whl + ' ( !j:~>!n + & nonprime:?!j + & !j+!i:?j + ) + ) + ) + & 1:?i + & whl + ' ( 1+!i:~>!n:?i + & (!!i|put$(!i " ")) + ) + ) +& eratosthenes$100 +) diff --git a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp new file mode 100644 index 0000000000..23ba066f33 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp @@ -0,0 +1,20 @@ +// yield all prime numbers less than limit. +template +void primesupto(int limit, UnaryFunction yield) +{ + std::vector is_prime(limit, true); + + const int sqrt_limit = static_cast(std::sqrt(limit)); + for (int n = 2; n <= sqrt_limit; ++n) + if (is_prime[n]) { + yield(n); + + for (unsigned k = n*n, ulim = static_cast(limit); k < ulim; k += n) + //NOTE: "unsigned" is used to avoid an overflow in `k+=n` for `limit` near INT_MAX + is_prime[k] = false; + } + + for (int n = sqrt_limit + 1; n < limit; ++n) + if (is_prime[n]) + yield(n); +} diff --git a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp new file mode 100644 index 0000000000..9c213d01c0 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp @@ -0,0 +1,42 @@ +/** + $ g++ -I/path/to/boost sieve.cpp -o sieve && sieve 10000000 + */ +#include // uintmax_t +#include +#include +#include +#include +#include + +#include + + +int main(int argc, char *argv[]) +{ + using namespace std; + using namespace boost::lambda; + + int limit = 10000; + if (argc == 2) { + stringstream ss(argv[--argc]); + ss >> limit; + + if (limit < 1 or ss.fail()) { + cerr << "USAGE:\n sieve LIMIT\n\nwhere LIMIT in the range [1, " + << numeric_limits::max() << ")" << endl; + return 2; + } + } + + // print primes less then 100 + primesupto(100, cout << _1 << " "); + cout << endl; + + // find number of primes less then limit and their sum + int count = 0; + uintmax_t sum = 0; + primesupto(limit, (var(sum) += _1, var(count) += 1)); + + cout << "limit sum pi(n)\n" + << limit << " " << sum << " " << count << endl; +} diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c new file mode 100644 index 0000000000..b2229c3d6b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c @@ -0,0 +1,29 @@ +#include +#include + +char* eratosthenes (int n, int *c) +{ + char* sieve; + int i, j, m; + + if (n < 2) { *c = 0; return NULL; } + + *c = n-1; /* primes count */ + m = (int) sqrt ((double) n); + + /* calloc initializes to zero */ + sieve = calloc (n+1, sizeof(char)); + sieve[0] = 1; + sieve[1] = 1; + for (i = 2; i <= m; i++) { + if (sieve[i] == 0) { + for (j = i*i; j <= n; j += i) { + if (sieve[j] == 0) { + sieve[j] = 1; + --(*c); + } + } + } + } + return sieve; +} diff --git a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake new file mode 100644 index 0000000000..f393b5d6c1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-1.cmake @@ -0,0 +1,35 @@ +function(eratosthenes var limit) + # Check for integer overflow. With CMake using 32-bit signed integer, + # this check fails when limit > 46340. + if(NOT limit EQUAL 0) # Avoid division by zero. + math(EXPR i "(${limit} * ${limit}) / ${limit}") + if(NOT limit EQUAL ${i}) + message(FATAL_ERROR "limit is too large, would cause integer overflow") + endif() + endif() + + # Use local variables prime_2, prime_3, ..., prime_${limit} as array. + # Initialize array to y => yes it is prime. + foreach(i RANGE 2 ${limit}) + set(prime_${i} y) + endforeach(i) + + # Gather a list of prime numbers. + set(list) + foreach(i RANGE 2 ${limit}) + if(prime_${i}) + # Append this prime to list. + list(APPEND list ${i}) + + # For each multiple of i, set n => no it is not prime. + # Optimization: start at i squared. + math(EXPR square "${i} * ${i}") + if(NOT square GREATER ${limit}) # Avoid fatal error. + foreach(m RANGE ${square} ${limit} ${i}) + set(prime_${m} n) + endforeach(m) + endif() + endif(prime_${i}) + endforeach(i) + set(${var} ${list} PARENT_SCOPE) +endfunction(eratosthenes) diff --git a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake new file mode 100644 index 0000000000..00a57372d4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes-2.cmake @@ -0,0 +1,3 @@ +# Print all prime numbers through 100. +eratosthenes(primes 100) +message(STATUS "${primes}") diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj new file mode 100644 index 0000000000..b861c756fb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj @@ -0,0 +1,23 @@ +(defn primes-up-to [n] + (let [n (int n)] + "Returns a list of all primes from 2 to n" + (let [root (int (Math/round (Math/floor (Math/sqrt n))))] + (loop [i (int 3) + a (int-array n) + result (transient [2])] + (if (>= i n) + (persistent! result) + (recur (+ i (int 2)) + (if (<= i root) + (loop [arr a + inc (+ i i) + j (* i i)] + (if (>= j n) + arr + (recur (do (aset arr j (int 1)) arr) + inc + (+ j inc)))) + a) + (if (zero? (aget a i)) + (conj! result i) + result))))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj new file mode 100644 index 0000000000..67ce5a32ba --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj @@ -0,0 +1,19 @@ +(defn primes [max-prime] + (let [new-sieve (fn [] + (let [v (reduce conj (vector-of :boolean) (range (inc max-prime)))] + (assoc (assoc v 0 false) 1 false))), + + sieve (fn [S] + (loop [s S, n 2] + (let [n**2 (* n n)] + (if (<= n**2 max-prime) + (recur (if (s n) + (reduce #(assoc %1 %2 false) s (range n**2 (inc max-prime) n)) + s) + (inc n)) + s)))), + + bitset-contents (fn [S] + (map second (filter first (map vector S (range (count S))))))] + + (bitset-contents (sieve (new-sieve))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj new file mode 100644 index 0000000000..738b69bf30 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj @@ -0,0 +1,8 @@ +(def prime-gen + (let [primes (atom [])] + (for [n (iterate inc 2) + :when (not-any? #(zero? (rem n %)) + (filter #(<= % (Math/sqrt n)) + @primes))] + (do (swap! primes conj n) + n)))) diff --git a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp new file mode 100644 index 0000000000..4c52808bbf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp @@ -0,0 +1,9 @@ +(defun sieve-of-eratosthenes (maximum) + (let ((sieve (make-array (1+ maximum) :element-type 'bit + :initial-element 0))) + (loop for candidate from 2 to maximum + when (zerop (bit sieve candidate)) + collect candidate + and do (loop for composite from (expt candidate 2) + to maximum by candidate + do (setf (bit sieve composite) 1))))) diff --git a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp new file mode 100644 index 0000000000..bb21ec1457 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp @@ -0,0 +1,10 @@ +(defun sieve-odds (maximum) "sieve for odd numbers" + (cons 2 + (let ((maxi (ash (1- maximum) -1)) (stop (ash (isqrt maximum) -1))) + (let ((sieve (make-array (1+ maxi) :element-type 'bit :initial-element 0))) + (loop for i from 1 to maxi + when (zerop (sbit sieve i)) + collect (1+ (ash i 1)) + and when (<= i stop) do + (loop for j from (ash (* i (1+ i)) 1) to maxi by (1+ (ash i 1)) + do (setf (sbit sieve j) 1))))))) diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d new file mode 100644 index 0000000000..9c1e32abca --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm, std.range, std.functional; + +uint[] sieve(in uint limit) { + if (limit < 2) + return []; + auto composite = new bool[limit]; + + foreach (immutable uint n; 2 .. cast(uint)(limit ^^ 0.5) + 1) + if (!composite[n]) + for (uint k = n * n; k < limit; k += n) + composite[k] = true; + + //return iota(2, limit).filter!(not!composite)().array(); + return iota(2, limit).filter!(i => !composite[i])().array(); +} + +void main() { + writeln(sieve(50)); +} diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d new file mode 100644 index 0000000000..bbebd19895 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-2.d @@ -0,0 +1,39 @@ +import std.stdio, std.math, std.array; + +size_t[] sieve(in size_t m) /*pure nothrow*/ { + if (m < 3) + return null; + immutable size_t n = m - 1; + enum size_t bpc = size_t.sizeof * 8; + auto F = new size_t[((n + 2) / 2) / bpc + 1]; + F[] = size_t.max; + + size_t isSet(in size_t i) nothrow { + immutable size_t offset = i / bpc; + immutable size_t mask = 1 << (i % bpc); + return F[offset] & mask; + } + + void resetBit(in size_t i) nothrow { + immutable size_t offset = i / bpc; + immutable size_t mask = 1 << (i % bpc); + if ((F[offset] & mask) != 0) + F[offset] = F[offset] ^ mask; + } + + for (size_t i = 3; i <= sqrt(cast(real)n); i += 2) + if (isSet((i - 3) / 2)) + for (size_t j = i * i; j <= n; j += 2 * i) + resetBit((j - 3) / 2); + + Appender!(size_t[]) result; + result ~= 2; + for (size_t i = 3; i <= n; i += 2) + if (isSet((i - 3) / 2)) + result ~= i; + return result.data; +} + +void main() { + writeln(sieve(50)); +} diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d new file mode 100644 index 0000000000..df19a63f30 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d @@ -0,0 +1,40 @@ +import std.algorithm, std.bitmanip; + +/// Extensible Sieve of Eratosthenes. +struct IsPrime { + //__gshared static BitArray multiples = [true, true, false]; + __gshared static BitArray multiples; + + static this() { + multiples.length = 3; + multiples[0] = true; + multiples[1] = true; + } + + static bool opCall(in size_t n) /*nothrow*/ { + if (n >= multiples.length) { + // Extend the sieve. + immutable oldLen = multiples.length; // Not nothrow. + immutable newMax = max((oldLen - 1) * 2, n); + multiples.length = newMax + 1; + foreach (immutable p; 2 .. oldLen) + if (!multiples[p]) + for (size_t i = p * ((oldLen + p) / p); + i < newMax + 1; i += p) + multiples[i] = true; + foreach (immutable i; oldLen .. newMax + 1) + if (!multiples[i]) + for (size_t j = i * 2; j < newMax + 1; j += i) + multiples[j] = true; + } + return !multiples[n]; + } +} + +version (eratosthenes3_main) { + import std.stdio, std.range; + void main() { + // iota(50).filter!IsPrime().writeln(); + iota(50).filter!(i => IsPrime(i))().writeln(); + } +} diff --git a/Task/Sieve-of-Eratosthenes/DWScript/sieve-of-eratosthenes.dwscript b/Task/Sieve-of-Eratosthenes/DWScript/sieve-of-eratosthenes.dwscript new file mode 100644 index 0000000000..2fccb1ec36 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/DWScript/sieve-of-eratosthenes.dwscript @@ -0,0 +1,21 @@ +function Primes(limit : Integer) : array of Integer; +var + n, k : Integer; + sieve := new Boolean[limit+1]; +begin + for n := 2 to Round(Sqrt(limit)) do begin + if not sieve[n] then begin + for k := n*n to limit step n do + sieve[k] := True; + end; + end; + + for k:=2 to limit do + if not sieve[k] then + Result.Add(k); +end; + +var r := Primes(50); +var i : Integer; +for i:=0 to r.High do + PrintLn(r[i]); diff --git a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart new file mode 100644 index 0000000000..f6b4871b18 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart @@ -0,0 +1,34 @@ +// helper function to pretty print an Iterable +String iterableToString(Iterable seq) { + String str = "["; + Iterator i = seq.iterator(); + while(i.hasNext()) { + str += i.next(); + if(i.hasNext()) { + str += ","; + } + } + return str + "]"; +} + +main() { + int limit = 1000; + Set sieve = new Set(); + + for(int i = 2; i <= limit; i++) { + sieve.add(i); + } + for(int i = 2; i * i <= limit; i++) { + if(sieve.contains(i)) { + for(int j = i * i; j <= limit; j += i) { + sieve.remove(j); + } + } + } + var sortedValues = new List.from(sieve); + sortedValues.sort((int arg1, int arg2) { + return arg1.compareTo(arg2); + }); + print(iterableToString(sortedValues)); + Expect.equals(168, sieve.length); +} diff --git a/Task/Sieve-of-Eratosthenes/Dylan/sieve-of-eratosthenes.dylan b/Task/Sieve-of-Eratosthenes/Dylan/sieve-of-eratosthenes.dylan new file mode 100644 index 0000000000..2bfa74d34b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Dylan/sieve-of-eratosthenes.dylan @@ -0,0 +1,24 @@ +define method primes(n) + let limit = floor(n ^ 0.5) + 1; + let sieve = make(limited(, of: ), size: n + 1, fill: #t); + let last-prime = 2; + + while (last-prime < limit) + for (x from last-prime ^ 2 to n by last-prime) + sieve[x] := #f; + end for; + block (found-prime) + for (n from last-prime + 1 below limit) + if (sieve[n] = #f) + last-prime := n; + found-prime() + end; + end; + last-prime := limit; + end block; + end while; + + for (x from 2 to n) + if (sieve[x]) format-out("Prime: %d\n", x); end; + end; +end; diff --git a/Task/Sieve-of-Eratosthenes/Eiffel/sieve-of-eratosthenes.e b/Task/Sieve-of-Eratosthenes/Eiffel/sieve-of-eratosthenes.e new file mode 100644 index 0000000000..37b6b7d8c4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Eiffel/sieve-of-eratosthenes.e @@ -0,0 +1,35 @@ +class + APPLICATION + +create + make + +feature + make + -- Run application. + do + across primes_through (100) as ic loop print (ic.item.out + " ") end + end + + primes_through (a_limit: INTEGER): LINKED_LIST [INTEGER] + -- Prime numbers through `a_limit' + require + valid_upper_limit: a_limit >= 2 + local + l_tab: ARRAY [BOOLEAN] + do + create Result.make + create l_tab.make_filled (True, 2, a_limit) + across + l_tab as ic + loop + if ic.item then + Result.extend (ic.target_index) + across ((ic.target_index * ic.target_index) |..| l_tab.upper).new_cursor.with_step (ic.target_index) as id + loop + l_tab [id.item] := False + end + end + end + end +end diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl new file mode 100644 index 0000000000..9bf1560c45 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl @@ -0,0 +1,38 @@ +%% Task: Implementation of Sieve of Eratosthenes +%% Author: Abhay Jain + +-module(sieve_module). +-export([find_primes_below/1]). + + +find_primes_below(N) -> + NumList = lists:seq(1, N), + determine_primes(NumList, 1, []). + +%% Sieve of Eratosthenes algorithm +determine_primes(NumList, Index, Primes) -> + case next_prime(NumList, Index+1, length(NumList)) of + {Prime, PrimeIndex, NewNumList} -> + NewPrimes = lists:append(Primes, [Prime]), + determine_primes(NewNumList, PrimeIndex, NewPrimes); + _ -> + %% All prime numbers have been calculated + Primes + end. + +next_prime(NumList, Index, Length) -> + if Index > Length -> + false; + true -> + case lists:nth(Index, NumList) of + 0 -> + next_prime(NumList, Index+1, Length); + Prime -> + NewNumList = lists:map(fun(A) -> + if A > Index andalso A rem Index == 0 -> 0; + true -> A + end + end, NumList), + {Prime, Index, NewNumList} + end + end. diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl new file mode 100644 index 0000000000..36abe84913 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl @@ -0,0 +1 @@ +[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] diff --git a/Task/Sieve-of-Eratosthenes/Euphoria/sieve-of-eratosthenes.euphoria b/Task/Sieve-of-Eratosthenes/Euphoria/sieve-of-eratosthenes.euphoria new file mode 100644 index 0000000000..f71a8d3171 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Euphoria/sieve-of-eratosthenes.euphoria @@ -0,0 +1,18 @@ +constant limit = 1000 +sequence flags,primes +flags = repeat(1, limit) +for i = 2 to sqrt(limit) do + if flags[i] then + for k = i*i to limit by i do + flags[k] = 0 + end for + end if +end for + +primes = {} +for i = 2 to limit do + if flags[i] = 1 then + primes &= i + end if +end for +? primes diff --git a/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-1.f b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-1.f new file mode 100644 index 0000000000..a60212b207 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-1.f @@ -0,0 +1,18 @@ +program sieve + + implicit none + integer, parameter :: i_max = 100 + integer :: i + logical, dimension (i_max) :: is_prime + + is_prime = .true. + is_prime (1) = .false. + do i = 2, int (sqrt (real (i_max))) + if (is_prime (i)) is_prime (i * i : i_max : i) = .false. + end do + do i = 1, i_max + if (is_prime (i)) write (*, '(i0, 1x)', advance = 'no') i + end do + write (*, *) + +end program sieve diff --git a/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-2.f b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-2.f new file mode 100644 index 0000000000..1783309f06 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-2.f @@ -0,0 +1 @@ +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 diff --git a/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-3.f b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-3.f new file mode 100644 index 0000000000..edbece4124 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-3.f @@ -0,0 +1,19 @@ +program sieve_wheel_2 + + implicit none + integer, parameter :: i_max = 100 + integer :: i + logical, dimension (i_max) :: is_prime + + is_prime = .true. + is_prime (1) = .false. + is_prime (4 : i_max : 2) = .false. + do i = 3, int (sqrt (real (i_max))), 2 + if (is_prime (i)) is_prime (i * i : i_max : 2 * i) = .false. + end do + do i = 1, i_max + if (is_prime (i)) write (*, '(i0, 1x)', advance = 'no') i + end do + write (*, *) + +end program sieve_wheel_2 diff --git a/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-4.f b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-4.f new file mode 100644 index 0000000000..1783309f06 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Fortran/sieve-of-eratosthenes-4.f @@ -0,0 +1 @@ +2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 diff --git a/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap b/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap new file mode 100644 index 0000000000..b98bf39ed0 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap @@ -0,0 +1,20 @@ +Eratosthenes := function(n) + local sieve, cur, mul; + sieve := [1 .. n]*0; + sieve[1] := 1; + cur := 1; + while cur <= n do + if sieve[cur] = 0 then + mul := cur*cur; + while mul <= n do + sieve[mul] := 1; + mul := mul + cur; + od; + fi; + cur := cur + 1; + od; + return Filtered([1 .. n], x -> sieve[x] = 0); +end; + +Eratosthenes(100); +# [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 ] diff --git a/Task/Sieve-of-Eratosthenes/GLBasic/sieve-of-eratosthenes.glbasic b/Task/Sieve-of-Eratosthenes/GLBasic/sieve-of-eratosthenes.glbasic new file mode 100644 index 0000000000..f3eb8449f1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/GLBasic/sieve-of-eratosthenes.glbasic @@ -0,0 +1,24 @@ +// Sieve of Eratosthenes (find primes) +// GLBasic implementation + + +GLOBAL n%, k%, limit%, flags%[] + +limit = 100 // search primes up to this number + +DIM flags[limit+1] // GLBasic arrays start at 0 + +FOR n = 2 TO SQR(limit) + IF flags[n] = 0 + FOR k = n*n TO limit STEP n + flags[k] = 1 + NEXT + ENDIF +NEXT + +// Display the primes +FOR n = 2 TO limit + IF flags[n] = 0 THEN STDOUT n + ", " +NEXT + +KEYWAIT diff --git a/Task/Sieve-of-Eratosthenes/GW-BASIC/sieve-of-eratosthenes.gw-basic b/Task/Sieve-of-Eratosthenes/GW-BASIC/sieve-of-eratosthenes.gw-basic new file mode 100644 index 0000000000..949290fc89 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/GW-BASIC/sieve-of-eratosthenes.gw-basic @@ -0,0 +1,12 @@ +10 INPUT "ENTER NUMBER TO SEARCH TO: ";LIMIT +20 DIM FLAGS(LIMIT) +30 FOR N = 2 TO SQR (LIMIT) +40 IF FLAGS(N) < > 0 GOTO 80 +50 FOR K = N * N TO LIMIT STEP N +60 FLAGS(K) = 1 +70 NEXT K +80 NEXT N +90 REM DISPLAY THE PRIMES +100 FOR N = 2 TO LIMIT +110 IF FLAGS(N) = 0 THEN PRINT N;", "; +120 NEXT N diff --git a/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-1.go b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-1.go new file mode 100644 index 0000000000..5fbf911f6c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-1.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" +) + +func main() { + const limit = 201 // means sieve numbers < 201 + + // sieve + c := make([]bool, limit) // c for composite. false means prime candidate + c[1] = true // 1 not considered prime + p := 2 + for { + // first allowed optimization: outer loop only goes to sqrt(limit) + p2 := p * p + if p2 >= limit { + break + } + // second allowed optimization: inner loop starts at sqr(p) + for i := p2; i < limit; i += p { + c[i] = true // it's a composite + + } + // scan to get next prime for outer loop + for { + p++ + if !c[p] { + break + } + } + } + + // sieve complete. now print a representation. + for n := 1; n < limit; n++ { + if c[n] { + fmt.Print(" .") + } else { + fmt.Printf("%3d", n) + } + if n%20 == 0 { + fmt.Println("") + } + } +} diff --git a/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-2.go b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-2.go new file mode 100644 index 0000000000..7365c6db0e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-2.go @@ -0,0 +1,61 @@ +package main +import "fmt" + +type xint uint64 +type xgen func()(xint) + +func primes() func()(xint) { + pp, psq := make([]xint, 0), xint(25) + + var sieve func(xint, xint)xgen + sieve = func(p, n xint) xgen { + m, next := xint(0), xgen(nil) + return func()(r xint) { + if next == nil { + r = n + if r <= psq { + n += p + return + } + + next = sieve(pp[0] * 2, psq) // chain in + pp = pp[1:] + psq = pp[0] * pp[0] + + m = next() + } + switch { + case n < m: r, n = n, n + p + case n > m: r, m = m, next() + default: r, n, m = n, n + p, next() + } + return + } + } + + f := sieve(6, 9) + n, p := f(), xint(0) + + return func()(xint) { + switch { + case p < 2: p = 2 + case p < 3: p = 3 + default: + for p += 2; p == n; { + p += 2 + if p > n { + n = f() + } + } + pp = append(pp, p) + } + return p + } +} + + +func main() { + for i, p := 0, primes(); i < 100000; i++ { + fmt.Println(p()) + } +} diff --git a/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy b/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy new file mode 100644 index 0000000000..16490d2ef3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy @@ -0,0 +1,11 @@ +def sievePrimes = { bound -> + def isPrime = new BitSet(bound) + isPrime[0..1] = false + isPrime[2.. + if (isPrime[pc]) { + ((pc**2).. UArray Integer Bool +primeSieve top = runSTUArray $ do + a <- newArray (2,top) True -- :: ST s (STUArray s Integer Bool) + let r = ceiling . sqrt $ fromInteger top + forM_ [2..r] $ \i -> do + ai <- readArray a i + when ai $ do + forM_ [i*i,i*i+i..top] $ \j -> do + writeArray a j False + return a + +-- Return primes from sieve as list: +primesTo :: Integer -> [Integer] +primesTo top = [p | (p,True) <- assocs $ primeSieve top] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs new file mode 100644 index 0000000000..36afb6f779 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-2.hs @@ -0,0 +1,15 @@ +sieveUO :: Int -> UArray Int Bool +sieveUO top = runSTUArray $ do + let m = (top-1) `div` 2 + r = floor . sqrt $ fromIntegral top + 1 + sieve <- newArray (1,m) True -- :: ST s (STUArray s Int Bool) + forM_ [1..r `div` 2] $ \i -> do + isPrime <- readArray sieve i -- ((2*i+1)^2-1)`div`2 = 2*i*(i+1) + when isPrime $ do + forM_ [2*i*(i+1), 2*i*(i+2)+1..m] $ \j -> do + writeArray sieve j False + return sieve + +primesToUO :: Int -> [Int] +primesToUO top | top > 1 = 2 : [2*p + 1 | (p,True) <- assocs $ sieveUO top] + | otherwise = [] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs new file mode 100644 index 0000000000..96d3206031 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-3.hs @@ -0,0 +1,8 @@ +import Data.Array.Unboxed + +primesToA m = sieve 3 (array (3,m) [(i,odd i) | i<-[3..m]] :: UArray Int Bool) + where + sieve p a + | p*p > m = 2 : [i | (i,True) <- assocs a] + | a!p = sieve (p+2) $ a//[(i,False) | i <- [p*p, p*p+2*p..m]] + | otherwise = sieve (p+2) a diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs new file mode 100644 index 0000000000..33c1d62e85 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs @@ -0,0 +1,9 @@ +primesTo m = 2 : eratos [3,5..m] where + eratos (p : xs) | p*p>m = p : xs + | True = p : eratos (xs `minus` [p*p, p*p+2*p..]) + +minus a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : minus xs b + EQ -> minus xs ys + GT -> minus a ys +minus a b = a diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs new file mode 100644 index 0000000000..c21c8cbdb7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs @@ -0,0 +1,18 @@ +primes :: [Integer] -- unbounded merging idea due to Richard Bird +primes = 2 : g (fix g) -- double staged production idea due to Melissa O'Neill + where -- tree merging idea Dave Bayer / simplified formulation Will Ness + g xs = 3 : gaps 5 (unionAll [[p*p, p*p+2*p..] | p <- xs]) + +fix g = xs where xs = g xs -- global definition to prevent space leak + +gaps k s@(x:xs) | k < x = k:gaps (k+2) s -- [k,k+2..]`minus`s, k<=x ! + | otherwise = gaps (k+2) xs + +unionAll ((x:xs):t) = x : union xs (unionAll (pairs t)) + where + pairs ((x:xs):ys:t) = (x : union xs ys) : pairs t + +union a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : union xs b + EQ -> x : union xs ys + GT -> y : union a ys diff --git a/Task/Sieve-of-Eratosthenes/HicEst/sieve-of-eratosthenes.hicest b/Task/Sieve-of-Eratosthenes/HicEst/sieve-of-eratosthenes.hicest new file mode 100644 index 0000000000..4a7a7f3683 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/HicEst/sieve-of-eratosthenes.hicest @@ -0,0 +1,14 @@ +REAL :: N=100, sieve(N) + +sieve = $ > 1 ! = 0 1 1 1 1 ... +DO i = 1, N^0.5 + IF( sieve(i) ) THEN + DO j = i^2, N, i + sieve(j) = 0 + ENDDO + ENDIF +ENDDO + +DO i = 1, N + IF( sieve(i) ) WRITE() i +ENDDO diff --git a/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-1.icon b/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-1.icon new file mode 100644 index 0000000000..3b4d4abe41 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-1.icon @@ -0,0 +1,11 @@ + procedure main() + sieve(100) + end + + procedure sieve(n) + local p,i,j + p:=list(n, 1) + every i:=2 to sqrt(n) & j:= i+i to n by i & p[i] == 1 + do p[j] := 0 + every write(i:=2 to n & p[i] == 1 & i) + end diff --git a/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-2.icon b/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-2.icon new file mode 100644 index 0000000000..e925dbfe59 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Icon/sieve-of-eratosthenes-2.icon @@ -0,0 +1,12 @@ + procedure main() + sieve(100) + end + + procedure sieve(n) + primes := set() + every insert(primes,1 to n) + every member(primes,i := 2 to n) do + every delete(primes,i + i to n by i) + delete(primes,1) + every write(!sort(primes)) +end diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-1.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-1.java new file mode 100644 index 0000000000..020a016c75 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-1.java @@ -0,0 +1,22 @@ +import java.util.LinkedList; + +public class Sieve{ + public static LinkedList sieve(int n){ + if(n < 2) return new LinkedList(); + LinkedList primes = new LinkedList(); + LinkedList nums = new LinkedList(); + + for(int i = 2;i <= n;i++){ //unoptimized + nums.add(i); + } + + while(nums.size() > 0){ + int nextPrime = nums.remove(); + for(int i = nextPrime * nextPrime;i <= n;i += nextPrime){ + nums.removeFirstOccurrence(i); + } + primes.add(nextPrime); + } + return primes; + } +} diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-2.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-2.java new file mode 100644 index 0000000000..366bf9779e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-2.java @@ -0,0 +1,4 @@ +nums.add(2); +for(int i = 3;i <= n;i += 2){ + nums.add(i); +} diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java new file mode 100644 index 0000000000..addb96f711 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-3.java @@ -0,0 +1,16 @@ +import java.util.LinkedList; +import java.util.BitSet; + +public class Sieve{ + public static LinkedList sieve(int n){ + LinkedList primes = new LinkedList(); + BitSet nonPrimes = new BitSet(n+1); + + for (int p = 2; p * p <= n ; p = nonPrimes.nextClearBit(p+1)) { + for (int i = p * p; i <= n; i += p) + nonPrimes.set(i); + primes.add(p); + } + return primes; + } +} diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js new file mode 100644 index 0000000000..2e122f5a29 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js @@ -0,0 +1,27 @@ +function erasthenes(limit) { + var primes = []; + if (limit >= 2) { + var nums = new Array(limit-1); + for (var i = 2; i <= limit; i++) + nums[i-2] = i; + + var last_prime; + var idx = 0; + while ((last_prime = nums[idx]) <= Math.sqrt(limit)) { + if (last_prime != null) + for (var i = idx + last_prime; i < limit - 1; i += last_prime) + nums[i] = null; + idx++; + } + for (var i = 0; i < nums.length; i++) + if (nums[i] != null) + primes.push(nums[i]); + } + return primes; +} + +var primes = erasthenes(100); + +if (typeof print == "undefined") + print = (typeof WScript != "undefined") ? WScript.Echo : alert; +print(primes); diff --git a/Task/Sieve-of-Eratosthenes/Liberty-BASIC/sieve-of-eratosthenes.liberty b/Task/Sieve-of-Eratosthenes/Liberty-BASIC/sieve-of-eratosthenes.liberty new file mode 100644 index 0000000000..481e332e12 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Liberty-BASIC/sieve-of-eratosthenes.liberty @@ -0,0 +1,25 @@ + 'Notice that arrays are globally visible to functions. + 'The sieve() function uses the flags() array. + 'This is a Sieve benchmark adapted from BYTE 1985 + ' May, page 286 + + size = 7000 + dim flags(7001) + start = time$("ms") + print sieve(size); " primes found." + print "End of iteration. Elapsed time in milliseconds: "; time$("ms")-start + end + + function sieve(size) + for i = 0 to size + if flags(i) = 0 then + prime = i + i + 3 + k = i + prime + while k <= size + flags(k) = 1 + k = k + prime + wend + sieve = sieve + 1 + end if + next i + end function diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua new file mode 100644 index 0000000000..dd1bd150c4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua @@ -0,0 +1,6 @@ +function erato(n) + local t = {0, 2} + for i = 3, n, 2 do t[i], t[i+1] = i, 0 end + for i = 3, math.sqrt(n) do for j = i*i, n, 2*i do t[j] = 0 end end + return t +end diff --git a/Task/Sieve-of-Eratosthenes/M4/sieve-of-eratosthenes.m4 b/Task/Sieve-of-Eratosthenes/M4/sieve-of-eratosthenes.m4 new file mode 100644 index 0000000000..5fbac38220 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/M4/sieve-of-eratosthenes.m4 @@ -0,0 +1,11 @@ +define(`lim',100)dnl +define(`for', + `ifelse($#,0, + ``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl +for(`j',2,lim,1, + `ifdef(a[j], + `', + `j for(`k',eval(j*j),lim,j, + `define(a[k],1)')')') diff --git a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m new file mode 100644 index 0000000000..e2e8acb011 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m @@ -0,0 +1,15 @@ +function primeList = sieveOfEratosthenes(lastNumber) + + list = (2:lastNumber); %Construct list of numbers + primeList = []; %Preallocate prime list + + while( list(1)^2 1 &]]; + +Eratosthenes[100] diff --git a/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima b/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima new file mode 100644 index 0000000000..d637ff8b11 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Maxima/sieve-of-eratosthenes.maxima @@ -0,0 +1,12 @@ +sieve(n) := block([u, j, m], + u: makelist(i, i, 1, n), + u[1]: -1, + j: 1, + do ( + j: j + 1, + while u[j] < 0 do j: j + 1, + m: j*j, + if m > n then return(sublist(u, nonnegintegerp)), + for k from m step j while k <= n do u[k]: -1 + ) +)$ diff --git a/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-1.mod3 b/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-1.mod3 new file mode 100644 index 0000000000..e5deb1c490 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-1.mod3 @@ -0,0 +1,27 @@ +MODULE Prime EXPORTS Main; + +IMPORT IO; + +CONST LastNum = 1000; + +VAR a: ARRAY [2..LastNum] OF BOOLEAN; + +BEGIN + FOR i := FIRST(a) TO LAST(a) DO + a[i] := TRUE; + END; + + FOR i := FIRST(a) TO LAST(a) DO + IF a[i] THEN + IO.PutInt(i); + IO.Put(" "); + FOR j := FIRST(a) TO LAST(a) DO + IF j MOD i = 0 THEN + a[j] := FALSE; + END; + END; + END; + END; + IO.Put("\n"); + +END Prime. diff --git a/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-2.mod3 b/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-2.mod3 new file mode 100644 index 0000000000..ecde368c7e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Modula-3/sieve-of-eratosthenes-2.mod3 @@ -0,0 +1,26 @@ +(* From the CM3 examples folder (comments removed). *) + +MODULE Sieve EXPORTS Main; + +IMPORT IO; + +TYPE + Number = [2..1000]; + Set = SET OF Number; + +VAR + prime: Set := Set {FIRST(Number) .. LAST(Number)}; + +BEGIN + FOR i := FIRST(Number) TO LAST(Number) DO + IF i IN prime THEN + IO.PutInt(i); + IO.Put(" "); + + FOR j := i TO LAST(Number) BY i DO + prime := prime - Set{j}; + END; + END; + END; + IO.Put("\n"); +END Sieve. diff --git a/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-1.netrexx b/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-1.netrexx new file mode 100644 index 0000000000..b1e12ceb43 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-1.netrexx @@ -0,0 +1,56 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +parse arg loWatermark hiWatermark . +if loWatermark = '' | loWatermark = '.' then loWatermark = 1 +if hiWatermark = '' | hiWatermark = '.' then hiWatermark = 200 + +do + if \loWatermark.datatype('w') | \hiWatermark.datatype('w') then - + signal NumberFormatException('arguments must be whole numbers') + if loWatermark > hiWatermark then - + signal IllegalArgumentException('the start value must be less than the end value') + + seive = sieveOfEratosthenes(hiWatermark) + primes = getPrimes(seive, loWatermark, hiWatermark).strip + + say 'List of prime numbers from' loWatermark 'to' hiWatermark 'via a "Sieve of Eratosthenes" algorithm:' + say ' 'primes.changestr(' ', ',') + say ' Count of primes:' primes.words +catch ex = Exception + ex.printStackTrace +end + +return + +method sieveOfEratosthenes(hn = long) public static binary returns Rexx + + sv = Rexx(isTrue) + sv[1] = isFalse + ix = long + jx = long + + loop ix = 2 while ix * ix <= hn + if sv[ix] then loop jx = ix * ix by ix while jx <= hn + sv[jx] = isFalse + end jx + end ix + + return sv + +method getPrimes(seive = Rexx, lo = long, hi = long) private constant binary returns Rexx + + primes = Rexx('') + loop p_ = lo to hi + if \seive[p_] then iterate p_ + primes = primes p_ + end p_ + + return primes + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue diff --git a/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-2.netrexx b/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-2.netrexx new file mode 100644 index 0000000000..ca812cee50 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/NetRexx/sieve-of-eratosthenes-2.netrexx @@ -0,0 +1,67 @@ +/* NetRexx ************************************************************ +* Essential improvements:Use boolean instead of Rexx for sv +* and remove methods isTrue and isFalse +* 24.07.2012 Walter Pachl courtesy Kermit Kiser +**********************************************************************/ + +options replace format comments java crossref savelog symbols binary + +parse arg loWatermark hiWatermark . +if loWatermark = '' | loWatermark = '.' then loWatermark = 1 +if hiWatermark = '' | hiWatermark = '.' then hiWatermark = 200000 + +startdate=Date Date() +do + if \loWatermark.datatype('w') | \hiWatermark.datatype('w') then - + signal NumberFormatException('arguments must be whole numbers') + if loWatermark > hiWatermark then - + signal IllegalArgumentException(- + 'the start value must be less than the end value') + sieve = sieveOfEratosthenes(hiWatermark) + primes = getPrimes(sieve, loWatermark, hiWatermark).strip + if hiWatermark = 200 Then do + say 'List of prime numbers from' loWatermark 'to' hiWatermark + say ' 'primes.changestr(' ', ',') + end +catch ex = Exception + ex.printStackTrace +end +enddate=Date Date() +Numeric Digits 20 +say (enddate.getTime-startdate.getTime)/1000 'seconds elapsed' +say ' Count of primes:' primes.words + +return + +method sieveOfEratosthenes(hn = int) - + public static binary returns boolean[] + true = boolean 1 + false = boolean 0 + sv = boolean[hn+1] + sv[1] = false + + ix = int + jx = int + + loop ix=2 to hn + sv[ix]=true + end ix + + loop ix = 2 while ix * ix <= hn + if sv[ix] then loop jx = ix * ix by ix while jx <= hn + sv[jx] = false + end jx + end ix + + return sv + +method getPrimes(sieve = boolean[], lo = int, hi = int) - + private constant binary Returns Rexx + p_ = int + primes = Rexx('') + loop p_ = lo to hi + if \sieve[p_] then iterate p_ + primes = primes p_ + end p_ + + return primes diff --git a/Task/Sieve-of-Eratosthenes/Niue/sieve-of-eratosthenes.niue b/Task/Sieve-of-Eratosthenes/Niue/sieve-of-eratosthenes.niue new file mode 100644 index 0000000000..092132fbd9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Niue/sieve-of-eratosthenes.niue @@ -0,0 +1,21 @@ +[ dup 2 < ] '<2 ; +[ 1 + 'count ; [ <2 [ , ] when ] count times ] 'fill-stack ; + +0 'n ; 0 'v ; + +[ .clr 0 'n ; 0 'v ; ] 'reset ; +[ len 1 - n - at 'v ; ] 'set-base ; +[ n 1 + 'n ; ] 'incr-n ; +[ mod 0 = ] 'is-factor ; +[ dup * ] 'sqr ; + +[ set-base + v sqr 2 at > not + [ [ dup v = not swap v is-factor and ] remove-if incr-n run ] when ] 'run ; + +[ fill-stack run ] 'sieve ; + +( tests ) + +10 sieve .s ( => 2 3 5 7 9 ) reset newline +30 sieve .s ( => 2 3 5 7 11 13 17 19 23 29 ) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ocaml new file mode 100644 index 0000000000..885e521b47 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ocaml @@ -0,0 +1,12 @@ +let sieve n = + let is_prime = Array.create n true in + let limit = truncate(sqrt (float n)) in + for i = 2 to pred limit do + if is_prime.(i) then + let j = ref (i*i) in + try while true do + is_prime.(!j) <- false; + j := !j + i; + done with _ -> () + done; + (is_prime) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml new file mode 100644 index 0000000000..bf5d16820e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml @@ -0,0 +1,9 @@ +let primes n = + let _, primes = + Array.fold_left (fun (i,acc) -> function + | true -> (i+1, i::acc) + | false -> (i+1, acc)) + (0, []) + (sieve n) + in + List.tl(List.tl(List.rev primes)) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ocaml new file mode 100644 index 0000000000..16b1622838 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ocaml @@ -0,0 +1,49 @@ +(* first define some iterators *) +# let fold_iter f init a b = + let rec aux acc i = + if i > b + then (acc) + else aux (f acc i) (succ i) + in + aux init a ;; +val fold_iter : ('a -> int -> 'a) -> 'a -> int -> int -> 'a = + +# let fold_step f init a b step = + let rec aux acc i = + if i > b + then (acc) + else aux (f acc i) (i + step) + in + aux init a ;; +val fold_step : ('a -> int -> 'a) -> 'a -> int -> int -> int -> 'a = + +(* remove a given value from a list *) +# let remove li v = + let rec aux acc = function + | hd::tl when hd = v -> (List.rev_append acc tl) + | hd::tl -> aux (hd::acc) tl + | [] -> li + in + aux [] li ;; +val remove : 'a list -> 'a -> 'a list = + +(* the main function *) +# let primes n = + let li = + (* create a list [from 2; ... until n] *) + List.rev(fold_iter (fun acc i -> (i::acc)) [] 2 n) + in + let limit = truncate(sqrt(float n)) in + fold_iter (fun li i -> + if List.mem i li (* test if (i) is prime *) + then (fold_step remove li (i*i) n i) + else li) + li 2 (pred limit) + ;; +val primes : int -> int list = + +# primes 200 ;; +- : int list = +[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71; + 73; 79; 83; 89; 97; 101; 103; 107; 109; 113; 127; 131; 137; 139; 149; 151; + 157; 163; 167; 173; 179; 181; 191; 193; 197; 199] diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ocaml new file mode 100644 index 0000000000..12490f972a --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ocaml @@ -0,0 +1,23 @@ +# let rec strike_nth k n l = match l with + | [] -> [] + | h :: t -> + if k = 0 then 0 :: strike_nth (n-1) n t + else h :: strike_nth (k-1) n t;; +val strike_nth : int -> int -> int list -> int list = + +# let primes n = + let limit = truncate(sqrt(float n)) in + let rec range a b = if a > b then [] else a :: range (a+1) b in + let rec sieve_primes l = match l with + | [] -> [] + | 0 :: t -> sieve_primes t + | h :: t -> if h > limit then List.filter ((<) 0) l else + h :: sieve_primes (strike_nth (h-1) h t) in + sieve_primes (range 2 n) ;; +val primes : int -> int list = + +# primes 200;; +- : int list = +[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71; + 73; 79; 83; 89; 97; 101; 103; 107; 109; 113; 127; 131; 137; 139; 149; 151; + 157; 163; 167; 173; 179; 181; 191; 193; 197; 199] diff --git a/Task/Sieve-of-Eratosthenes/Oberon-2/sieve-of-eratosthenes.oberon-2 b/Task/Sieve-of-Eratosthenes/Oberon-2/sieve-of-eratosthenes.oberon-2 new file mode 100644 index 0000000000..6b73ae1cf9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Oberon-2/sieve-of-eratosthenes.oberon-2 @@ -0,0 +1,34 @@ +MODULE Primes; + + IMPORT Out, Math; + + CONST N = 1000; + + VAR a: ARRAY N OF BOOLEAN; + i, j, m: INTEGER; + +BEGIN + (* Set all elements of a to TRUE. *) + FOR i := 1 TO N - 1 DO + a[i] := TRUE; + END; + + (* Compute square root of N and convert back to INTEGER. *) + m := ENTIER(Math.Sqrt(N)); + + FOR i := 2 TO m DO + IF a[i] THEN + FOR j := 2 TO (N - 1) DIV i DO + a[i*j] := FALSE; + END; + END; + END; + + (* Print all the elements of a that are TRUE. *) + FOR i := 2 TO N - 1 DO + IF a[i] THEN + Out.Int(i, 4); + END; + END; + Out.Ln; +END Primes. diff --git a/Task/Sieve-of-Eratosthenes/Oz/sieve-of-eratosthenes.oz b/Task/Sieve-of-Eratosthenes/Oz/sieve-of-eratosthenes.oz new file mode 100644 index 0000000000..39ee2dbb88 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Oz/sieve-of-eratosthenes.oz @@ -0,0 +1,24 @@ +declare + fun {Sieve N} + S = {Array.new 2 N true} + M = {Float.toInt {Sqrt {Int.toFloat N}}} + in + for I in 2..M do + if S.I then + for J in I*I..N;I do + S.J := false + end + end + end + S + end + + fun {Primes N} + S = {Sieve N} + in + for I in 2..N collect:C do + if S.I then {C I} end + end + end +in + {Show {Primes 30}} diff --git a/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari new file mode 100644 index 0000000000..30a9500c87 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-1.pari @@ -0,0 +1,9 @@ +Eratosthenes(lim)={ + my(v=Vectorsmall(lim,unused,1)); + forprime(p=2,sqrt(lim), + forstep(i=p^2,lim,p, + v[i]=0 + ) + ); + for(i=1,lim,if(v[i],print1(i", "))) +}; diff --git a/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-2.pari b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-2.pari new file mode 100644 index 0000000000..d513dee4fd --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PARI-GP/sieve-of-eratosthenes-2.pari @@ -0,0 +1,8 @@ +Sieve(n)= +{ +v=vector(n,unused,1); +for(i=2,sqrt(n), + if(v[i], + forstep(j=i^2,n,i,v[j]=0))); +for(i=2,n,if(v[i],print1(i))) +}; diff --git a/Task/Sieve-of-Eratosthenes/PHP/sieve-of-eratosthenes.php b/Task/Sieve-of-Eratosthenes/PHP/sieve-of-eratosthenes.php new file mode 100644 index 0000000000..89a93213d2 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PHP/sieve-of-eratosthenes.php @@ -0,0 +1,20 @@ +function iprimes_upto($limit) +{ + for ($i = 2; $i < $limit; $i++) + { + $primes[$i] = true; + } + + for ($n = 2; $n < $limit; $n++) + { + if ($primes[$n]) + { + for ($i = $n*$n; $i < $limit; $i += $n) + { + $primes[$i] = false; + } + } + } + + return $primes; +} diff --git a/Task/Sieve-of-Eratosthenes/PL-I/sieve-of-eratosthenes.pli b/Task/Sieve-of-Eratosthenes/PL-I/sieve-of-eratosthenes.pli new file mode 100644 index 0000000000..0474386308 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PL-I/sieve-of-eratosthenes.pli @@ -0,0 +1,37 @@ +eratos: proc options (main) reorder; + +dcl i fixed bin (31); +dcl j fixed bin (31); +dcl n fixed bin (31); +dcl sn fixed bin (31); + +dcl hbound builtin; +dcl sqrt builtin; + +dcl sysin file; +dcl sysprint file; + +get list (n); +sn = sqrt(n); + +begin; + dcl primes(n) bit (1) aligned init ((*)((1)'1'b)); + + i = 2; + + do while(i <= sn); + do j = i ** 2 by i to hbound(primes, 1); + /* Adding a test would just slow down processing! */ + primes(j) = '0'b; + end; + + do i = i + 1 to sn until(primes(i)); + end; + end; + + do i = 2 to hbound(primes, 1); + if primes(i) then + put data(i); + end; +end; +end eratos; diff --git a/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes.pascal b/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes.pascal new file mode 100644 index 0000000000..4697477ac7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes.pascal @@ -0,0 +1,40 @@ +program primes(output) + +const + PrimeLimit = 1000; + +var + primes: set of 1 .. PrimeLimit; + n, k: integer; + needcomma: boolean; + +begin + { calculate the primes } + primes := [2 .. PrimeLimit]; + for n := 1 to trunc(sqrt(PrimeLimit)) do + begin + if n in primes + then + begin + k := n*n; + while k < PrimeLimit do + begin + primes := primes - [k]; + k := k + n + end + end + end; + + { output the primes } + needcomma := false; + for n := 1 to PrimeLimit do + if n in primes + then + begin + if needcomma + then + write(', '); + write(n); + needcomma := true + end +end. diff --git a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-1.pl6 b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-1.pl6 new file mode 100644 index 0000000000..d1a0d47dab --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-1.pl6 @@ -0,0 +1,12 @@ +sub sieve( Int $limit ) { + my @is-prime = False, False, True xx $limit - 1; + + gather for @is-prime.kv -> $number, $is-prime { + if $is-prime { + take $number; + @is-prime[$_] = False if $_ %% $number for $number**2 .. $limit; + } + } +} + +(sieve 100).join(",").say; diff --git a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 new file mode 100644 index 0000000000..3769d61e13 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-2.pl6 @@ -0,0 +1,5 @@ +multi erat(Int $N) { erat 2 .. $N } +multi erat(@a where @a[0] > sqrt @a[*-1]) { @a } +multi erat(@a) { @a[0], erat(@a.grep: * % @a[0]) } +  +say erat 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 new file mode 100644 index 0000000000..f857874e5c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl-6/sieve-of-eratosthenes-3.pl6 @@ -0,0 +1,12 @@ +role Filter[Int $factor] { + method next { repeat until $.value % $factor { callsame } } +} + +class Stream { + has Int $.value is rw = 1; + + method next { ++$.value } + method filter { self but Filter[$.value] } +} + +.next, say .value for Stream.new, *.filter ... *; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl new file mode 100644 index 0000000000..9fbe234679 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl @@ -0,0 +1,12 @@ +$max= $ARGV[0]; +@primes= (); +@tested= (1); +$j= 1; +while ($j < $max) { + next if $tested[$j++]; + push @primes, $j; + for ($k= $j; $k <= $max; $k+=$j) { + $tested[$k-1]= 1; + } +} +print "@primes\n"; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl new file mode 100644 index 0000000000..d0a9d4c2a9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl @@ -0,0 +1,16 @@ +sub simple_sieve { + my($max) = @_; + return () if $max < 2; return (2) if $max < 3; + + my @c; + for(my $t=3; $t*$t<=$max; $t+=2) { + if (!$c[$t]) { + for(my $s=$t*$t; $s<=$max; $s+=$t*2) { $c[$s]++ } + } + } + my @primes = (2); + for(my $t=3; $t<=$max; $t+=2) { + $c[$t] || push @primes, $t; + } + @primes; +} diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl new file mode 100644 index 0000000000..695e79530c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl @@ -0,0 +1,16 @@ +sub dj_vector { + my($end) = @_; + return () if $end < 2; return (2) if $end < 3; + $end-- if ($end & 1) == 0; # Ensure end is odd + + my ($sieve, $n, $limit, $s_end) = ( '', 3, int(sqrt($end)), $end >> 1 ); + while ( $n <= $limit ) { + for (my $s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { + vec($sieve, $s, 1) = 1; + } + do { $n += 2 } while vec($sieve, $n >> 1, 1) != 0; + } + my @primes = (2); + do { push @primes, 2*$_+1 if !vec($sieve,$_,1) } for (1..int(($end-1)/2)); + @primes; +} diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl new file mode 100644 index 0000000000..0bea95f6c8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl @@ -0,0 +1,26 @@ +sub dj_string { + my($end) = @_; + return () if $end < 2; return (2) if $end < 3; + $end-- if ($end & 1) == 0; + my $s_end = $end >> 1; + + my $whole = int( ($end>>1) / 15); # prefill with 3 and 5 marked + my $sieve = '100010010010110' . '011010010010110' x $whole; + substr($sieve, ($end>>1)+1) = ''; + my ($n, $limit) = ( 7, int(sqrt($end)) ); + while ( $n <= $limit ) { + for (my $s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { + substr($sieve, $s, 1) = '1'; + } + do { $n += 2 } while substr($sieve, $n>>1, 1); + } + # If you just want the count, it's very fast: + # my $count = 1 + $sieve =~ tr/0//; + my @primes = (2, 3, 5); + $n = 7-2; + foreach my $s (split("0", substr($sieve, 3), -1)) { + $n += 2 + 2 * length($s); + push @primes, $n if $n <= $end; + } + @primes; +} diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl new file mode 100644 index 0000000000..b9b9db360d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl @@ -0,0 +1,7 @@ +sub sieve{ my (@s, $i); + grep { not $s[ $i = $_ ] and do + { $s[ $i += $_ ]++ while $i <= $_[0]; 1 } + } 2..$_[0] +} + +print join ", " => sieve 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl new file mode 100644 index 0000000000..d1c4825ca1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl @@ -0,0 +1,7 @@ +sub sieve{ my ($s, $i); + grep { not vec $s, $i = $_, 1 and do + { (vec $s, $i += $_, 1) = 1 while $i <= $_[0]; 1 } + } 2..$_[0] +} + +print join ", " => sieve 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl new file mode 100644 index 0000000000..f8936deb18 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl @@ -0,0 +1,6 @@ +sub erat { + my $p = shift; + return $p, $p**2 > $_[$#_] ? @_ : erat(grep $_%$p, @_) +} + +print join ', ' => erat 2..100000; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl new file mode 100644 index 0000000000..8d9cc27e14 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl @@ -0,0 +1,12 @@ +sub sieve { + my ($s, $p) = "." . ("x" x shift); + + 1 while ++$p + and $s =~ /^(.{$p,}?)x/g + and $p = length($1) + and $s =~ s/(.{$p})./${1}./g + and substr($s, $p, 1) = "x"; + $s +} + +print sieve(1000); diff --git a/Task/Sieve-of-Eratosthenes/PicoLisp/sieve-of-eratosthenes.l b/Task/Sieve-of-Eratosthenes/PicoLisp/sieve-of-eratosthenes.l new file mode 100644 index 0000000000..9b0dd2aba5 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PicoLisp/sieve-of-eratosthenes.l @@ -0,0 +1,8 @@ +(de sieve (N) + (let Sieve (range 1 N) + (set Sieve) + (for I (cdr Sieve) + (when I + (for (S (nth Sieve (* I I)) S (nth (cdr S) I)) + (set S) ) ) ) + (filter bool Sieve) ) ) diff --git a/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes.psh b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes.psh new file mode 100644 index 0000000000..a8ecb74947 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes.psh @@ -0,0 +1,12 @@ +function Sieve ( [int] $num ) +{ + $isprime = @{} + 2..$num | Where-Object { + $isprime[$_] -eq $null } | ForEach-Object { + $_ + $isprime[$_] = $true + $i=$_*$_ + for ( ; $i -le $num; $i += $_ ) + { $isprime[$i] = $false } + } +} diff --git a/Task/Sieve-of-Eratosthenes/Processing/sieve-of-eratosthenes. b/Task/Sieve-of-Eratosthenes/Processing/sieve-of-eratosthenes. new file mode 100644 index 0000000000..fea2e49f22 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Processing/sieve-of-eratosthenes. @@ -0,0 +1,49 @@ +int maxx,maxy; +int max; +boolean[] sieve; + +void plot(int pos, boolean active) { + set(pos%maxx,pos/maxx, active?#000000:#ffffff); +} + +void setup() { + size(1000, 1000, P2D); + frameRate(2); + maxx=width; + maxy=height; + max=width*height; + sieve=new boolean[max+1]; + + sieve[1]=false; + plot(0,false); + plot(1,false); + for(int i=2;i<=max;i++) { + sieve[i]=true; + plot(i,true); + } +} + +int i=2; + +void draw() { + if(!sieve[i]) { + while(i*i sieve_O(I1,N,PS) + ; ( I =< N / I -> + ISq is I*I, DI is 2*I, add_mults(DI,ISq,N) + ; true + ), + PS = [I|T], + sieve_O(I1,N,T) + ). +sieve_O(I,N,[]) :- I > N. + +add_mults(DI,I,N) :- + I =< N, !, + ( mult(I) -> true ; assert(mult(I)) ), + I1 is I+DI, + add_mults(DI,I1,N). +add_mults(_,I,N) :- I > N. diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro new file mode 100644 index 0000000000..3405beff59 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-2.pro @@ -0,0 +1,26 @@ +?- use_module(library(heaps)). + +prime(2). +prime(N) :- prime_heap(N, _). + +prime_heap(3, H) :- list_to_heap([9-6], H). +prime_heap(N, H) :- + prime_heap(M, H0), N0 is M + 2, + next_prime(N0, H0, N, H). + +next_prime(N0, H0, N, H) :- + \+ min_of_heap(H0, N0, _), + N = N0, Composite is N*N, Skip is N+N, + add_to_heap(H0, Composite, Skip, H). +next_prime(N0, H0, N, H) :- + min_of_heap(H0, N0, _), + adjust_heap(H0, N0, H1), N1 is N0 + 2, + next_prime(N1, H1, N, H). + +adjust_heap(H0, N, H) :- + min_of_heap(H0, N, _), + get_from_heap(H0, N, Skip, H1), + Composite is N + Skip, add_to_heap(H1, Composite, Skip, H2), + adjust_heap(H2, N, H). +adjust_heap(H, N, H) :- + \+ min_of_heap(H, N, _). diff --git a/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-1.purebasic b/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-1.purebasic new file mode 100644 index 0000000000..9052cc44c7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-1.purebasic @@ -0,0 +1,9 @@ +For n=2 To Sqr(lim) + If Nums(n)=0 + m=n*n + While m<=lim + Nums(m)=1 + m+n + Wend + EndIf +Next n diff --git a/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-2.purebasic b/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-2.purebasic new file mode 100644 index 0000000000..859c705f09 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PureBasic/sieve-of-eratosthenes-2.purebasic @@ -0,0 +1,37 @@ +Dim Nums.i(0) +Define l, n, m, lim + +If OpenConsole() + + ; Ask for the limit to search, get that input and allocate a Array + Print("Enter limit for this search: ") + lim=Val(Input()) + ReDim Nums(lim) + + ; Use a basic Sieve of Eratosthenes + For n=2 To Sqr(lim) + If Nums(n)=#False + m=n*n + While m<=lim + Nums(m)=#True + m+n + Wend + EndIf + Next n + + ;Present the result to our user + PrintN(#CRLF$+"The Prims up to "+Str(lim)+" are;") + m=0: l=Log10(lim)+1 + For n=2 To lim + If Nums(n)=#False + Print(RSet(Str(n),l)+" ") + m+1 + If m>72/(l+1) + m=0: PrintN("") + EndIf + EndIf + Next + + Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py new file mode 100644 index 0000000000..e5ff7b8cce --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py @@ -0,0 +1,9 @@ +def eratosthenes(n): + multiples = [] + for i in xrange(2, n+1): + if i not in multiples: + print i + for j in xrange(i*i, n+1, i): + multiples.append(j) + +eratosthenes(100) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py new file mode 100644 index 0000000000..8e0d9d5a89 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py @@ -0,0 +1,28 @@ +def primes(): + yield 2 ; yield 3 ; yield 5 ; yield 7 ; + ps = (p for p in primes()) # additional primes supply + p = ps.next() and ps.next() # discard 2, then get 3 + q = p*p # 9 - square of next prime to be put + sieve = {} # into sieve dict + n = 9 # the candidate number + while True: + if n not in sieve: # is not a multiple of previously recorded primes + if n < q: # n is prime + yield n + else: + add(sieve, q + 2*p, 2*p) # n==p*p: for prime p, under p*p + 2*p, + p = ps.next() # add 2*p as incremental step + q = p*p + else: + s = sieve.pop(n) + add(sieve, n + s, s) + n += 2 # work on odds only + +def add(sieve,next,step): + while next in sieve: # ensure each entry is unique + next += step + sieve[next] = step # next non-marked multiple of a prime + +import itertools +def primes_up_to(limit): + return list(itertools.takewhile(lambda p: p <= limit, primes())) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py new file mode 100644 index 0000000000..b175f484a9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py @@ -0,0 +1,8 @@ +def eratosthenes2(n): + multiples = set() + for i in xrange(2, n+1): + if i not in multiples: + print i + multiples.update(xrange(i*i, n+1, i)) + +eratosthenes2(100) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py new file mode 100644 index 0000000000..274d00b5e3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py @@ -0,0 +1,7 @@ +def primes_upto(limit): + is_prime = [False] * 2 + [True] * (limit - 1) + for n in xrange(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)`` + if is_prime[n]: + for i in xrange(n*n, limit+1, n): + is_prime[i] = False + return [i for i, prime in enumerate(is_prime) if prime] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py new file mode 100644 index 0000000000..d4e7013487 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py @@ -0,0 +1,7 @@ +def iprimes_upto(limit): + is_prime = [False] * 2 + [True] * (limit - 1) + for n in range(limit + 1): + if is_prime[n]: + yield n + for i in range(n*n, limit+1, n): # start at ``n`` squared + is_prime[i] = False diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py new file mode 100644 index 0000000000..7162985457 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py @@ -0,0 +1,2 @@ +>>> list(iprimes_upto(15)) +[2, 3, 5, 7, 11, 13] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py new file mode 100644 index 0000000000..53b4e9ef99 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py @@ -0,0 +1,7 @@ +import numpy +def primes_upto2(limit): + is_prime = numpy.ones(limit + 1, dtype=numpy.bool) + for n in xrange(2, int(limit**0.5 + 1.5)): + if is_prime[n]: + is_prime[n*n::n] = 0 + return numpy.nonzero(is_prime)[0][2:] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py new file mode 100644 index 0000000000..1cdb64c793 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py @@ -0,0 +1,20 @@ +from numpy import array, bool_, multiply, nonzero, ones, put, resize +# +def makepattern(smallprimes): + pattern = ones(multiply.reduce(smallprimes), dtype=bool_) + pattern[0] = 0 + for p in smallprimes: + pattern[p::p] = 0 + return pattern +# +def primes_upto3(limit, smallprimes=(2,3,5,7,11)): + sp = array(smallprimes) + if limit <= sp.max(): return sp[sp <= limit] + # + isprime = resize(makepattern(sp), limit + 1) + isprime[:2] = 0; put(isprime, sp, 1) + # + for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): + if isprime[n]: + isprime[n*n::n] = 0 + return nonzero(isprime)[0] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py new file mode 100644 index 0000000000..5ada4786d0 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py @@ -0,0 +1,12 @@ +>>> primes_upto3(10**6, smallprimes=(2,3)) # Wall time: 0.17 +array([ 2, 3, 5, ..., 999961, 999979, 999983]) +>>> primes_upto3(10**7, smallprimes=(2,3)) # Wall time: '''2.13''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(15) +array([ 2, 3, 5, 7, 11, 13]) +>>> primes_upto3(10**7, smallprimes=primes_upto3(15)) # Wall time: '''1.31''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto2(10**7) # Wall time: '''1.39''' <-- version ''without'' wheels +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(10**7) # Wall time: '''1.30''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py new file mode 100644 index 0000000000..8022a40075 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py @@ -0,0 +1,28 @@ +import heapq + +# generates all prime numbers +def sieve(): + # priority queue of the sequences of non-primes + # the priority queue allows us to get the "next" non-prime quickly + nonprimes = [] + + i = 2 + while True: + if nonprimes and i == nonprimes[0][0]: # non-prime + while nonprimes[0][0] == i: + # for each sequence that generates this number, + # have it go to the next number (simply add the prime) + # and re-position it in the priority queue + x = nonprimes[0] + x[0] += x[1] + heapq.heapreplace(nonprimes, x) + + else: # prime + # insert a 2-element list into the priority queue: + # [current multiple, prime] + # the first element allows sorting by value of current multiple + # we start with i^2 + heapq.heappush(nonprimes, [i*i, i]) + yield i + + i += 1 diff --git a/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r b/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r new file mode 100644 index 0000000000..ae58dfae5d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/R/sieve-of-eratosthenes.r @@ -0,0 +1,16 @@ +sieve <- function(n) +{ + n <- as.integer(n) + if(n > 1e6) stop("n too large") + primes <- rep(TRUE, n) + primes[1] <- FALSE + last.prime <- 2L + for(i in last.prime:floor(sqrt(n))) + { + primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE + last.prime <- last.prime + min(which(primes[(last.prime+1):n])) + } + which(primes) +} + +sieve(1000) diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx new file mode 100644 index 0000000000..7d45c93104 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx @@ -0,0 +1,14 @@ +/*REXX program generates primes via the sieve of Eratosthenes algorithm.*/ +parse arg H .; if H=='' then H=200 /*let the highest # be specified.*/ +w = length(H); prime=right('prime',20) /*W is used for formatting output*/ +@.=1 /*assume all numbers are prime. */ + do j=2 while j*j <= H /*all integers up to √H inclusive*/ + if @.j then do m=j*j to H by J /*Prime? Then strike mutliples.*/ + @.m=0 /*mark all multiples of J ¬prime.*/ + end /*m*/ + end /*j*/ +#=0 /*count of primes listed so far. */ + do n=2 to H /* [↓] if prime, then display it.*/ + if @.n then do; # = #+1; say prime right(#,w) " ───► " right(n,w); end + end /*n*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx new file mode 100644 index 0000000000..8c946745e4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -0,0 +1,20 @@ +/*REXX pgm gens primes via a wheeled sieve of Eratosthenes algorithm.*/ +parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ +oH=H; H=abs(H); w=length(H) /*neg H suppresses prime listing.*/ +if 2<=H & oH>0 then say right(1,w+20)'st prime ───► ' right(2,w) +@.=1 /*assume all numbers are prime. */ + do j=3 by 2 while j*j <= H /*odd integers up to √H inclusive*/ + if @.j then do m=j*j to H by j+j /*Prime? Then strike multiples.*/ + @.m = 0 /*mark odd multiples of J ¬prime.*/ + end /*m*/ + end /*j*/ +#= H>1 /*count of primes found so far. */ + do n=3 to H by 2 /*count primes & maybe show them.*/ + if @.n then do; #=#+1; if oH>0 then say right(#,w+20)th(#)' prime ───► ' right(n,w); end + end /*n*/ +say; say right(#,w+20+2) 'prime's(#) "found." +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────S subroutine────────────────────────*/ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ +/*──────────────────────────────────TH subroutine───────────────────────*/ +th: procedure;parse arg x;x=abs(x);return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx new file mode 100644 index 0000000000..1f82279be2 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx @@ -0,0 +1,15 @@ +/*REXX pgm gens primes via a wheeled sieve of Eratosthenes algorithm.*/ +parse arg H .; if H=='' then H=200 /*high# can be specified on C.L. */ +w = length(H); prime=right('prime',20) /*W is used for formatting output*/ +if 2 <= H then say prime right(1,w) " ───► " right(2,w) +@.=1 /*assume all numbers are prime. */ + do j=3 by 2 while j*j <= H /*odd integers up to √H inclusive*/ + if @.j then do m=j*j to H by j+j /*Prime? Then strike multiples.*/ + @.m = 0 /*mark odd multiples of J ¬prime.*/ + end /*m*/ + end /*j*/ +#=1 /*display a list of odd primes.*/ + do n=3 to H by 2 /* [↓] if prime, then display it.*/ + if @.n then do; #=#+1; say prime right(#,w) " ───► " right(n,w); end + end /*n*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx new file mode 100644 index 0000000000..a232b3bdbf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx @@ -0,0 +1,29 @@ +/*REXX program generates primes via sieve of Eratosthenes algorithm. +* 21.07.2012 Walter Pachl derived from above Rexx version +* avoid symbols @ and # (not supported by ooRexx) +* avoid negations (think positive) +**********************************************************************/ + highest=200 /*define highest number to use. */ + is_prime.=1 /*assume all numbers are prime. */ + w=length(highest) /*width of the biggest number, */ + /* it's used for aligned output.*/ + Do j=3 To highest By 2, /*strike multiples of odd ints. */ + While j*j<=highest /* up to sqrt(highest) */ + If is_prime.j Then Do + Do jm=j*3 To highest By j+j /*start with next odd mult. of J */ + is_prime.jm=0 /*mark odd mult. of J not prime. */ + End + End + End + np=0 /*number of primes shown */ + Call tell 2 + Do n=3 To highest By 2 /*list all the primes found. */ + If is_prime.n Then Do + Call tell n + End + End + Exit +tell: Parse Arg prime + np=np+1 + Say ' prime number' right(np,w) " --> " right(prime,w) + Return diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb new file mode 100644 index 0000000000..a4b9aca107 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-1.rb @@ -0,0 +1,11 @@ +def eratosthenes(n) + nums = [0, 0] + (2..n).to_a + (2..Math.sqrt(n).to_i).each do |i| + if nums[i].nonzero? + (i**2..n).step(i) {|m| nums[m] = 0} + end + end + nums.find_all {|m| m.nonzero?} +end + +p eratosthenes(100) diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb new file mode 100644 index 0000000000..b9c80a0e24 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-2.rb @@ -0,0 +1,44 @@ +def eratosthenes2(n) + # For odd i, if i is prime, nums[i >> 1] is true. + # Set false for all multiples of 3. + nums = [true, false, true] * ((n + 5) / 6) + nums[0] = false # 1 is not prime. + nums[1] = true # 3 is prime. + + # Outer loop and both inner loops are skipping multiples of 2 and 3. + # Outer loop checks i * i > n, same as i > Math.sqrt(n). + i = 5 + until(m = i * i + m > n) do + if nums[i >> 1] + i_times_2 = i << 1 + i_times_4 = i << 2 + while m <= n + nums[m >> 1] = false + m += i_times_2 + nums[m >> 1] = false + m += i_times_4 # When i = 5, skip 45, 75, 105, ... + end + end + i += 2 + if nums[i >> 1] + m = i * i + i_times_2 = i << 1 + i_times_4 = i << 2 + while m <= n + nums[m >> 1] = false + m += i_times_4 # When i = 7, skip 63, 105, 147, ... + nums[m >> 1] = false + m += i_times_2 + end + end + i += 4 + end + + primes = [2] + nums.each_index {|i| primes << (i * 2 + 1) if nums[i]} + primes.pop while primes.last > n + return primes +end + +p eratosthenes2(100) diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-3.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-3.rb new file mode 100644 index 0000000000..d0cba9d4cd --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-3.rb @@ -0,0 +1,5 @@ +require 'benchmark' +Benchmark.bmbm {|x| + x.report("eratosthenes") { eratosthenes(1_000_000) } + x.report("eratosthenes2") { eratosthenes2(1_000_000) } +} diff --git a/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-4.rb b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-4.rb new file mode 100644 index 0000000000..5baf483d71 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ruby/sieve-of-eratosthenes-4.rb @@ -0,0 +1,2 @@ +require 'prime' +p Prime::EratosthenesGenerator.new.take_while {|i| i <= 100} diff --git a/Task/Sieve-of-Eratosthenes/Run-BASIC/sieve-of-eratosthenes.run b/Task/Sieve-of-Eratosthenes/Run-BASIC/sieve-of-eratosthenes.run new file mode 100644 index 0000000000..abfa70f9ed --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Run-BASIC/sieve-of-eratosthenes.run @@ -0,0 +1,8 @@ +input "Gimme the limit:"; limit +dim flags(limit) +for i = 2 to limit + for k = i*i to limit step i + flags(k) = 1 + next k +if flags(i) = 0 then print i;", "; +next i diff --git a/Task/Sieve-of-Eratosthenes/SNOBOL4/sieve-of-eratosthenes.sno b/Task/Sieve-of-Eratosthenes/SNOBOL4/sieve-of-eratosthenes.sno new file mode 100644 index 0000000000..528cf24bb1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/SNOBOL4/sieve-of-eratosthenes.sno @@ -0,0 +1,17 @@ + define('sieve(n)i,j,k,p,str,res') :(sieve_end) +sieve i = lt(i,n - 1) i + 1 :f(sv1) + str = str (i + 1) ' ' :(sieve) +sv1 str break(' ') . j span(' ') = :f(return) + sieve = sieve j ' ' + sieve = gt(j ^ 2,n) sieve str :s(return) ;* Opt1 + res = '' + str (arb ' ') @p ((j ^ 2) ' ') ;* Opt2 + str len(p) . res = ;* Opt2 +sv2 str break(' ') . k span(' ') = :f(sv3) + res = ne(remdr(k,j),0) res k ' ' :(sv2) +sv3 str = res :(sv1) +sieve_end + +* # Test and display + output = sieve(100) +end diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala new file mode 100644 index 0000000000..f4d1e20dde --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala @@ -0,0 +1,12 @@ +def sieveOfEratosthenes(n: Int) = { + val primes = new scala.collection.mutable.BitSet(n) + primes ++= (2 to n) + val sqrt = Math.sqrt(n).toInt + for { + candidate <- 2 to sqrt + if primes contains candidate + } primes --= candidate * candidate to n by candidate + primes +} + +println( sieveOfEratosthenes(30) ) diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala new file mode 100644 index 0000000000..b3ebbbf6b1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala @@ -0,0 +1,7 @@ +def ints(n:Int):Stream[Int] = Stream.cons(n,ints(n+1)) +def sieve(nums:Stream[Int]):Stream[Int] = + Stream.cons(nums.head, sieve((nums.tail) filter (_%nums.head != 0))) +def primes = sieve(ints(2)) + +println( primes take 10 toList ) +println( primes takeWhile (_<30) toList ) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.ss new file mode 100644 index 0000000000..9ea47ab740 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.ss @@ -0,0 +1,21 @@ +; Tail-recursive solution : +(define (sieve n) + (define (aux u v) + (let ((p (car v))) + (if (> (* p p) n) + (let rev-append ((u u) (v v)) + (if (null? u) v (rev-append (cdr u) (cons (car u) v)))) + (aux (cons p u) + (let wheel ((u '()) (v (cdr v)) (a (* p p))) + (cond ((null? v) (reverse u)) + ((= (car v) a) (wheel u (cdr v) (+ a p))) + ((> (car v) a) (wheel u v (+ a p))) + (else (wheel (cons (car v) u) (cdr v) a)))))))) + (aux '(2) + (let range ((v '()) (k (if (odd? n) n (- n 1)))) + (if (< k 3) v (range (cons k v) (- k 2)))))) + +; > (sieve 100) +; (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) +; > (length (sieve 10000000)) +; 664579 diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.ss new file mode 100644 index 0000000000..d0f91e40bf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.ss @@ -0,0 +1,23 @@ +; Simpler solution, with the penalty that none of 'iota, 'strike or 'sieve is tail-recursive : +(define (iota start stop stride) + (if (> start stop) + (list) + (cons start (iota (+ start stride) stop stride)))) + +(define (strike lst start stride) + (cond ((null? lst) lst) + ((= (car lst) start) (strike (cdr lst) (+ start stride) stride)) + ((> (car lst) start) (strike lst (+ start stride) stride)) + (else (cons (car lst) (strike (cdr lst) start stride))))) + +(define (primes limit) + (let ((stop (sqrt limit))) + (define (sieve lst) + (let ((p (car lst))) + (if (> p stop) + lst + (cons p (sieve (strike (cdr lst) (* p p) p)))))) + (sieve (iota 2 limit 1)))) + +(display (primes 100)) +(newline) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.ss new file mode 100644 index 0000000000..4102e8a351 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.ss @@ -0,0 +1 @@ +(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.ss new file mode 100644 index 0000000000..b0e382f598 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.ss @@ -0,0 +1,11 @@ +(define (primes-wheel-2 limit) + (let ((stop (sqrt limit))) + (define (sieve lst) + (let ((p (car lst))) + (if (> p stop) + lst + (cons p (sieve (strike (cdr lst) (* p p) (* 2 p))))))) + (cons 2 (sieve (iota 3 limit 2))))) + +(display (primes-wheel-2 100)) +(newline) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.ss new file mode 100644 index 0000000000..4102e8a351 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.ss @@ -0,0 +1 @@ +(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.ss new file mode 100644 index 0000000000..9310ad964d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.ss @@ -0,0 +1,43 @@ +; initialize v to vector of sequential integers +(define (initialize! v) + (define (iter v n) (if (>= n (vector-length v)) + (values) + (begin (vector-set! v n n) (iter v (+ n 1))))) + (iter v 0)) + +; set every nth element of vector v to 0, +; starting with element m +(define (strike! v m n) + (cond ((>= m (vector-length v)) (values)) + (else (begin + (vector-set! v m 0) + (strike! v (+ m n) n))))) + +; lowest non-zero index of vector v >= n +(define (nextprime v n) + (if (zero? (vector-ref v n)) + (nextprime v (+ n 1)) + (vector-ref v n))) + +; remove elements satisfying pred? from list lst +(define (remove pred? lst) + (cond + ((null? lst) '()) + ((pred? (car lst))(remove pred? (cdr lst))) + (else (cons (car lst) (remove pred? (cdr lst)))))) + +; the sieve itself +(define (sieve n) + (define stop (sqrt n)) + (define (iter v p) + (cond + ((> p stop) v) + (else + (begin + (strike! v (* p p) p) + (iter v (nextprime v (+ p 1))))))) + + (let ((v (make-vector (+ n 1)))) + (initialize! v) + (vector-set! v 1 0) ; 1 is not a prime + (remove zero? (vector->list (iter v 2))))) diff --git a/Task/Sieve-of-Eratosthenes/Seed7/sieve-of-eratosthenes.seed7 b/Task/Sieve-of-Eratosthenes/Seed7/sieve-of-eratosthenes.seed7 new file mode 100644 index 0000000000..83215b0df7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Seed7/sieve-of-eratosthenes.seed7 @@ -0,0 +1,23 @@ +$ include "seed7_05.s7i"; + +const func set of integer: eratosthenes (in integer: n) is func + result + var set of integer: sieve is EMPTY_SET; + local + var integer: i is 0; + var integer: j is 0; + begin + sieve := {2 .. n}; + for i range 2 to sqrt(n) do + if i in sieve then + for j range i ** 2 to n step i do + excl(sieve, j); + end for; + end if; + end for; + end func; + +const proc: main is func + begin + writeln(card(eratosthenes(10000000))); + end func; diff --git a/Task/Sieve-of-Eratosthenes/Tcl/sieve-of-eratosthenes.tcl b/Task/Sieve-of-Eratosthenes/Tcl/sieve-of-eratosthenes.tcl new file mode 100644 index 0000000000..ac46efbc94 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Tcl/sieve-of-eratosthenes.tcl @@ -0,0 +1,26 @@ +package require Tcl 8.5 + +proc sieve n { + if {$n < 2} {return {}} + + # create a container to hold the sequence of numbers. + # use a dictionary for its speedy access (like an associative array) + # and for its insertion order preservation (like a list) + set nums [dict create] + for {set i 2} {$i <= $n} {incr i} { + # the actual value is never used + dict set nums $i "" + } + + set primes [list] + while {[set nextPrime [lindex [dict keys $nums] 0]] <= sqrt($n)} { + dict unset nums $nextPrime + for {set i [expr {$nextPrime ** 2}]} {$i <= $n} {incr i $nextPrime} { + dict unset nums $i + } + lappend primes $nextPrime + } + return [concat $primes [dict keys $nums]] +} + +puts [sieve 100] ;# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-1.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-1.sh new file mode 100644 index 0000000000..f5bbc2cc7f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-1.sh @@ -0,0 +1,22 @@ +#!/usr/bin/zsh + +function primes() { + typeset -a a + typeset i j + + a[1]="" + for (( i = 2; i <= $1; i++ )); do + a[$i]=$i + done + + for (( i = 2; i * i <= $1; i++ )); do + if [[ ! -z $a[$i] ]]; then + for (( j = i * i; j <= $1; j += i )); do + a[$j]="" + done + fi + done + print $a +} + +primes 1000 diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-2.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-2.sh new file mode 100644 index 0000000000..105208542b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-2.sh @@ -0,0 +1,23 @@ +function primes { + typeset a i=2 j m=$1 + # No for (( ... )) loop in pdksh. Use while loop. + while (( i <= m )); do + a[$i]=$i + (( i++ )) + done + + i=2 + while (( j = i * i, j <= m )); do + if [[ -n ${a[$i]} ]]; then + while (( j <= m )); do + unset a[$j] + (( j += i )) + done + fi + (( i++ )) + done + # No print command in bash. Use echo command. + echo ${a[*]} +} + +primes 1000 diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-3.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-3.sh new file mode 100644 index 0000000000..366f99f56f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-3.sh @@ -0,0 +1,43 @@ +#! /bin/sh + +LIMIT=1000 + +# As a workaround for missing arrays, we use variables p2, p3, ..., +# p$LIMIT, to represent the primes. Values are true or false. +# eval p$i=true # Set value. +# eval \$p$i # Run command: true or false. +# +# A previous version of this script created a temporary directory and +# used files named 2, 3, ..., $LIMIT to represent the primes. We now use +# variables so that a killed script does not leave extra files. About +# performance, variables are about as slow as files. + +i=2 +while [ $i -le $LIMIT ] +do + eval p$i=true # was touch $i + i=`expr $i + 1` +done + +i=2 +while + j=`expr $i '*' $i` + [ $j -le $LIMIT ] +do + if eval \$p$i # was if [ -f $i ] + then + while [ $j -le $LIMIT ] + do + eval p$j=false # was rm -f $j + j=`expr $j + $i` + done + fi + i=`expr $i + 1` +done + +# was echo `ls|sort -n` +echo `i=2 + while [ $i -le $LIMIT ]; do + eval \\$p$i && echo $i + i=\`expr $i + 1\` + done` diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh new file mode 100644 index 0000000000..0db4f06487 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh @@ -0,0 +1,33 @@ +# Fill $1 characters with $2. +fill () { + # This pipeline would begin + # head -c $1 /dev/zero | ... + # but some systems have no head -c. Use dd. + dd if=/dev/zero bs=$1 count=1 2>/dev/null | tr '\0' $2 +} + +filter () { + # Use sed to put an 'x' after each multiple of $1, remove + # first 'x', and mark non-primes with '0'. + sed -e s/$2/\&x/g -e s/x// -e s/.x/0/g | { + if expr $1 '*' $1 '<' $3 > /dev/null; then + filter `expr $1 + 1` .$2 $3 + else + cat + fi + } +} + +# Generate a sequence of 1s and 0s indicating primality. +oz () { + fill $1 1 | sed s/1/0/ | filter 2 .. $1 +} + +# Echo prime numbers from 2 to $1. +prime () { + # Escape backslash inside backquotes. sed sees one backslash. + echo `oz $1 | sed 's/./&\\ +/g' | grep -n 1 | sed s/:1//` +} + +prime 1000 diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-5.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-5.sh new file mode 100644 index 0000000000..c319ce0e45 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-5.sh @@ -0,0 +1,28 @@ +# Sieve of Eratosthenes: Echoes all prime numbers through $limit. +@ limit = 80 + +if ( ( $limit * $limit ) / $limit != $limit ) then + echo limit is too large, would cause integer overflow. + exit 1 +endif + +# Use $prime[2], $prime[3], ..., $prime[$limit] as array of booleans. +# Initialize values to 1 => yes it is prime. +set prime=( `repeat $limit echo 1` ) + +# Find and echo prime numbers. +@ i = 2 +while ( $i <= $limit ) + if ( $prime[$i] ) then + echo $i + + # For each multiple of i, set 0 => no it is not prime. + # Optimization: start at i squared. + @ m = $i * $i + while ( $m <= $limit ) + set prime[$m] = 0 + @ m += $i + end + endif + @ i += 1 +end diff --git a/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-1.ursala b/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-1.ursala new file mode 100644 index 0000000000..ad61c50634 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-1.ursala @@ -0,0 +1,3 @@ +#import nat + +sieve = ~<{0,1}&& iota; @NttPX ~&r->lx ^/~&rhPlC remainder@rlX~|@r diff --git a/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-2.ursala b/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-2.ursala new file mode 100644 index 0000000000..c4beba7dc7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Ursala/sieve-of-eratosthenes-2.ursala @@ -0,0 +1,3 @@ +#cast %nL + +example = sieve 50 diff --git a/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala b/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala new file mode 100644 index 0000000000..7d0f849c8b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala @@ -0,0 +1,38 @@ +using Gee; + +ArrayList primes(int limit){ + var sieve = new ArrayList(); + var prime_list = new ArrayList(); + + for(int i = 0; i <= limit; i++){ + sieve.add(true); + } + + sieve[0] = false; + sieve[1] = false; + + for (int i = 2; i <= limit/2; i++){ + if (sieve[i] != false){ + for (int j = 2; i*j <= limit; j++){ + sieve[i*j] = false; + } + } + } + + for (int i = 0; i < sieve.size; i++){ + if (sieve[i] != false){ + prime_list.add(i); + } + } + + return prime_list; +} // end primes + +public static void main(){ + var prime_list = primes(50); + + foreach(var prime in prime_list) + stdout.printf("%s ", prime.to_string()); + + stdout.printf("\n"); +} diff --git a/Task/Sieve-of-Eratosthenes/Visual-Basic-.NET/sieve-of-eratosthenes.visual b/Task/Sieve-of-Eratosthenes/Visual-Basic-.NET/sieve-of-eratosthenes.visual new file mode 100644 index 0000000000..e567093c1d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Visual-Basic-.NET/sieve-of-eratosthenes.visual @@ -0,0 +1,18 @@ +Dim n As Integer, k As Integer, limit As Integer +Console.WriteLine("Enter number to search to: ") +limit = Console.ReadLine +Dim flags(limit) As Integer +For n As Integer = 2 To Math.Sqrt(limit) + If flags(n) = 0 Then + For k As Integer = n * n To limit Step n + flags(k) = 1 + Next k + End If +Next n + +' Display the primes +For n = 2 To limit + If flags(n) = 0 Then + Console.WriteLine(n) + End If +Next n diff --git a/Task/Sieve-of-Eratosthenes/Vorpal/sieve-of-eratosthenes.vorpal b/Task/Sieve-of-Eratosthenes/Vorpal/sieve-of-eratosthenes.vorpal new file mode 100644 index 0000000000..b1c9cbfbf4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Vorpal/sieve-of-eratosthenes.vorpal @@ -0,0 +1,23 @@ +self.print_primes = method(m){ + p = new() + p.fill(0, m, 1, true) + + count = 0 + i = 2 + while(i < m){ + if(p[i] == true){ + p.fill(i+i, m, i, false) + count = count + 1 + } + i = i + 1 + } + ('primes: ' + count + ' in ' + m).print() + for(i = 2, i < m, i = i + 1){ + if(p[i] == true){ + ('' + i + ', ').put() + } + } + ''.print() +} + +self.print_primes(100) diff --git a/Task/Sieve-of-Eratosthenes/XPL0/sieve-of-eratosthenes.xpl0 b/Task/Sieve-of-Eratosthenes/XPL0/sieve-of-eratosthenes.xpl0 new file mode 100644 index 0000000000..80e681c3cf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/XPL0/sieve-of-eratosthenes.xpl0 @@ -0,0 +1,17 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +int Size, Prime, I, Kill; +char Flag; +[Size:= IntIn(0); +Flag:= Reserve(Size+1); +for I:= 2 to Size do Flag(I):= true; +for I:= 2 to Size do + if Flag(I) then \found a prime + [Prime:= I; + IntOut(0, Prime); CrLf(0); + Kill:= Prime + Prime; \first multiple to kill + while Kill <= Size do + [Flag(Kill):= false; \zero a non-prime + Kill:= Kill + Prime; \next multiple + ]; + ]; +] diff --git a/Task/Simple-database/0DESCRIPTION b/Task/Simple-database/0DESCRIPTION new file mode 100644 index 0000000000..788d8989df --- /dev/null +++ b/Task/Simple-database/0DESCRIPTION @@ -0,0 +1,23 @@ +Write a simple tool to track a small set of data. +The tool should have a commandline interface to enter at least two different values. +The entered data should be stored in a structured format and saved to disk. + +It does not matter what kind of data is being tracked. It could be your CD collection, your friends birthdays, or diary. + +You should track the following details: +* A description of the item. (e.g., title, name) +* A category or tag (genre, topic, relationship such as “friend” or “family”) +* A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually +* Other optional fields + +The command should support the following [[Command-line arguments]] to run: +* Add a new entry +* Print the latest entry +* Print the latest entry for each category +* Print all entries sorted by a date + +The category may be realized as a tag or as structure (by making all entries in that category subitems) + +The file format on disk should be human readable, but it need not be standardized. A natively available format that doesn't need an external library is preferred. Avoid developing your own format however if you can use an already existing one. If there is no existing format available pick one of: [[JSON]], [[S-Expressions]], [[YAML]], or [[wp:Comparison_of_data_serialization_formats|others]]. + +See also [[Take notes on the command line]] for a related task. diff --git a/Task/Simple-database/1META.yaml b/Task/Simple-database/1META.yaml new file mode 100644 index 0000000000..32d20151af --- /dev/null +++ b/Task/Simple-database/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Data Structures diff --git a/Task/Simple-database/C/simple-database.c b/Task/Simple-database/C/simple-database.c new file mode 100644 index 0000000000..0eca6b6697 --- /dev/null +++ b/Task/Simple-database/C/simple-database.c @@ -0,0 +1,193 @@ +#include +#include /* malloc */ +#include /* strlen */ +#define _XOPEN_SOURCE /* requred for time functions */ +#define __USE_XOPEN +#include +#define DB "database.csv" /* database name */ +#define TRY(a) if (!(a)) {perror(#a);exit(1);} +#define TRY2(a) if((a)<0) {perror(#a);exit(1);} +#define FREE(a) if(a) {free(a);a=NULL;} +#define sort_by(foo) \ +static int by_##foo (pdb_t *p1, pdb_t *p2) { \ + return strcmp ((*p1)->foo, (*p2)->foo); } +typedef struct db { + char title[26]; + char first_name[26]; + char last_name[26]; + time_t date; + char publ[100]; + struct db *next; +} +db_t,*pdb_t; +typedef int (sort)(pdb_t*, pdb_t*); +typedef int (*compfn)(const void*, const void*); +enum {CREATE,PRINT,TITLE,DATE,AUTH,READLINE,READ,SORT,DESTROY}; +static pdb_t dao (int cmd, FILE *f, pdb_t db, sort sortby); +static char *time2str (time_t *time); +static time_t str2time (char *date); +/* qsort callbacks */ +sort_by(last_name); +sort_by(title); +static sort by_date; +/* main */ +int main (int argc, char **argv) { + char buf[100], *commands[]={"-c", "-p", "-t", "-d", "-a", NULL}; + db_t db; + db.next=NULL; + pdb_t dblist; + int i; + FILE *f; + TRY (f=fopen(DB,"a+")); + if (argc<2) { +usage: printf ("Usage: %s [commands]\n" + "-c Create new entry.\n" + "-p Print the latest entry.\n" + "-t Print all entries sorted by title.\n" + "-d Print all entries sorted by date.\n" + "-a Print all entries sorted by author.\n",argv[0]); + fclose (f); + return 0; + } + for (i=0;commands[i]&&strcmp(argv[1],commands[i]);i++); + switch (i) { + case CREATE: + printf("-c Create a new entry.\n"); + printf("Title :");if((scanf(" %25[^\n]",db.title ))<0)break; + printf("Author Firstname:");if((scanf(" %25[^\n]",db.first_name))<0)break; + printf("Author Lastname :");if((scanf(" %25[^\n]",db.last_name ))<0)break; + printf("Date 10-12-2000 :");if((scanf(" %10[^\n]",buf ))<0)break; + printf("Publication :");if((scanf(" %99[^\n]",db.publ ))<0)break; + db.date=str2time (buf); + dao (CREATE,f,&db,NULL); + break; + case PRINT: + printf ("-p Print the latest entry.\n"); + while (!feof(f)) dao (READLINE,f,&db,NULL); + dao (PRINT,f,&db,NULL); + break; + case TITLE: + printf ("-t Print all entries sorted by title.\n"); + dblist = dao (READ,f,&db,NULL); + dblist = dao (SORT,f,dblist,by_title); + dao (PRINT,f,dblist,NULL); + dao (DESTROY,f,dblist,NULL); + break; + case DATE: + printf ("-d Print all entries sorted by date.\n"); + dblist = dao (READ,f,&db,NULL); + dblist = dao (SORT,f,dblist,by_date); + dao (PRINT,f,dblist,NULL); + dao (DESTROY,f,dblist,NULL); + break; + case AUTH: + printf ("-a Print all entries sorted by author.\n"); + dblist = dao (READ,f,&db,NULL); + dblist = dao (SORT,f,dblist,by_last_name); + dao (PRINT,f,dblist,NULL); + dao (DESTROY,f,dblist,NULL); + break; + default: { + printf ("Unknown command: %s.\n",strlen(argv[1])<10?argv[1]:""); + goto usage; + } } + fclose (f); + return 0; +} +/* Data Access Object (DAO) */ +static pdb_t dao (int cmd, FILE *f, pdb_t in_db, sort sortby) { + pdb_t *pdb=NULL,rec=NULL,hd=NULL; + int i=0,ret; + char buf[100]; + switch (cmd) { + case CREATE: + fprintf (f,"\"%s\",",in_db->title); + fprintf (f,"\"%s\",",in_db->first_name); + fprintf (f,"\"%s\",",in_db->last_name); + fprintf (f,"\"%s\",",time2str(&in_db->date)); + fprintf (f,"\"%s\" \n",in_db->publ); + break; + case PRINT: + for (;in_db;i++) { + printf ("Title : %s\n", in_db->title); + printf ("Author : %s %s\n", in_db->first_name, in_db->last_name); + printf ("Date : %s\n", time2str(&in_db->date)); + printf ("Publication : %s\n\n", in_db->publ); + if (!((i+1)%3)) { + printf ("Press Enter to continue.\n"); + ret = scanf ("%*[^\n]"); + if (ret<0) return rec; /* handle EOF */ + else getchar(); + } + in_db=in_db->next; + } + break; + case READLINE: + if((fscanf(f," \"%[^\"]\",",in_db->title ))<0)break; + if((fscanf(f," \"%[^\"]\",",in_db->first_name))<0)break; + if((fscanf(f," \"%[^\"]\",",in_db->last_name ))<0)break; + if((fscanf(f," \"%[^\"]\",",buf ))<0)break; + if((fscanf(f," \"%[^\"]\" ",in_db->publ ))<0)break; + in_db->date=str2time (buf); + break; + case READ: + while (!feof(f)) { + dao (READLINE,f,in_db,NULL); + TRY (rec=malloc(sizeof(db_t))); + *rec=*in_db; /* copy contents */ + rec->next=hd;/* to linked list */ + hd=rec;i++; + } + if (i<2) { + puts ("Empty database. Please create some entries."); + fclose (f); + exit (0); + } + break; + case SORT: + rec=in_db; + for (;in_db;i++) in_db=in_db->next; + TRY (pdb=malloc(i*sizeof(pdb_t))); + in_db=rec; + for (i=0;in_db;i++) { + pdb[i]=in_db; + in_db=in_db->next; + } + qsort (pdb,i,sizeof in_db,(compfn)sortby); + pdb[i-1]->next=NULL; + for (;i;i--) { + pdb[i-1]->next=pdb[i]; + } + rec=pdb[0]; + FREE (pdb); + pdb=NULL; + break; + case DESTROY: { + while ((rec=in_db)) { + in_db=in_db->next; + FREE (rec); + } } } + return rec; +} +/* convert numeric time to date string */ +static char *time2str (time_t *time) { + static char buf[255]; + struct tm *ptm; + ptm=localtime (time); + strftime(buf, 255, "%m-%d-%Y", ptm); + return buf; +} +/* convert date string to numeric time */ +static time_t str2time (char *date) { + struct tm tm; + memset (&tm, 0, sizeof(struct tm)); + strptime(date, "%m-%d-%Y", &tm); + return mktime(&tm); +} +/* sort by date callback for qsort */ +static int by_date (pdb_t *p1, pdb_t *p2) { + if ((*p1)->date < (*p2)->date) { + return -1; + } + else return ((*p1)->date > (*p2)->date); +} diff --git a/Task/Simple-database/Common-Lisp/simple-database.lisp b/Task/Simple-database/Common-Lisp/simple-database.lisp new file mode 100644 index 0000000000..5739760805 --- /dev/null +++ b/Task/Simple-database/Common-Lisp/simple-database.lisp @@ -0,0 +1,396 @@ +(defvar *db* nil) + +(defstruct series description tags episodes) + +(defstruct (episode (:print-function print-episode-struct)) + series title season episode part date tags) + +(defun format-ymd (date) + (format nil "~{~a.~a.~a~}" date)) + +(defun print-episode-struct (ep stream level) + (let ((*print-pretty* nil)) + (format stream (if *print-escape* + "#s(episode~@{~*~@[ :~1:*~a ~s~]~})" + "~32<~*~a~; ~*~@[~d-~]~*~d~> ~45<~*~@[~a ~]~*~@[(~a) ~]~;~*~@[(~a)~]~>~*~@[ (~{~a~^ ~})~]") + :series (episode-series ep) + :season (episode-season ep) + :episode (episode-episode ep) + :title (episode-title ep) + :part (episode-part ep) + :date (if *print-escape* + (episode-date ep) + (when (episode-date ep) + (format-ymd (episode-date ep)))) + :tags (episode-tags ep)))) + +(defun get-value (key alist) + (cdr (assoc key alist))) + + +(defun get-latest (database) + (when database + (cons (car (series-episodes (cdar database))) (get-latest (cdr database))))) + +(defun get-all (database) + (when database + (append (series-episodes (cdar database)) (get-all (cdr database))))) + +(defun compare-date (a b) + (cond ((not a) t) + ((not b) nil) + ((= (first a) (first b)) + (compare-date (rest a) (rest b))) + (t (< (first a) (first b))))) + +(defun compare-by-date (a b) + (compare-date (episode-date a) (episode-date b))) + +(defun prompt-read (prompt &optional default) + (format *query-io* "~a~@[ (~a)~]: " prompt default) + (force-output *query-io*) + (let ((answer (read-line *query-io*))) + (if (string= answer "") + default + answer))) + +(defun split (seperator string) + (loop for i = 0 then (1+ j) + as j = (search seperator string :start2 i) + collect (subseq string i j) + while j)) + +(defun get-current-date () + (multiple-value-bind + (second minute hour date month year day-of-week dst-p tz) + (get-decoded-time) + (declare (ignore second minute hour day-of-week dst-p tz)) + (list date month year))) + + +(defun parse-date (date) + (reverse (mapcar #'parse-integer (split "." date)))) + +(defun parse-tags (tags) + (when (and tags (string-not-equal "" tags)) + (mapcar #'intern (split " " (string-upcase tags))))) + +(defun parse-number (number) + (if (stringp number) + (parse-integer number :junk-allowed t) + number)) + +(defun prompt-for-episode (&optional last) + (when (not last) + (setf last (make-episode))) + (let* ((series (prompt-read "Series Title" (episode-series last))) + (title (prompt-read "Title")) + (season (parse-number (prompt-read "Season" (episode-season last)))) + (episode (parse-number (prompt-read "Episode" + (if (eq (episode-season last) season) + (1+ (episode-episode last)) + 1)))) + (part (parse-number (prompt-read "Part" + (when (and (episode-part last) + (or (eq (episode-season last) season) + (eq (episode-part last) 1))) + (1+ (episode-part last)))))) + (date (parse-date (prompt-read "Date watched" (format-ymd (get-current-date))))) + (tags (parse-tags (prompt-read "Tags")))) + (make-episode + :series series + :title title + :season season + :episode episode + :part part + :date date + :tags tags))) + +(defun parse-integer-quietly (&rest args) + (ignore-errors (apply #'parse-integer args))) + +(defun get-next-version (basename) + (flet ((parse-version (pathname) + (or (parse-integer-quietly + (string-left-trim (file-namestring basename) + (file-namestring pathname)) + :start 1) 0))) + (let* ((files (directory (format nil "~A,*" (namestring basename)))) + (max (if files + (reduce #'max files :key #'parse-version) + 0))) + (merge-pathnames (format nil "~a,~d" (file-namestring basename) (1+ max)) + basename)))) + +(defun save-db (dbfile database) + (let ((file (probe-file dbfile))) + (rename-file file (get-next-version file)) + (with-open-file (out file :direction :output) + (with-standard-io-syntax + (let ((*print-case* :downcase)) + (pprint database out)))))) + +(defun watch-save (dbfile) + (save-db dbfile *db*)) + +(defun load-db (dbfile) + (with-open-file (in dbfile) + (with-standard-io-syntax + (read in)))) + +(defun get-series (name database) + (cdr (assoc name database :test #'string-equal))) + +(defun get-episode-list (series database) + (series-episodes (get-series series database))) + +(defun print-series (title series) + (format t "~&~30a ~@[ (~{~a~^ ~})~]~%~@[ ~a~%~]" title (series-tags series) + (series-description series)) + (format t "~{~& ~a~%~}" (reverse (series-episodes series)))) + +(defun watch-series (title) + (let ((series (get-series title *db*))) + (when series + (print-series title series)))) + +(defun print-all-series (database) + (loop for (title . series) + in (sort database #'(lambda (a b)(compare-by-date (car (series-episodes (cdr a))) + (car (series-episodes (cdr b)))))) + do (terpri) (print-series title series))) + +(defun watch-all-series () + (print-all-series *db*)) + +(defun watch-latest () + (format t "~{~& ~a~%~}" (sort (get-latest *db*) #'compare-by-date))) + +(defun timeline-all (database) + (let* ((all (get-all database)) + (max (length all)) + (count max) + (all-series-names nil) + (all-series (make-hash-table :test 'equal))) + (loop for episode in (reverse (sort all #'compare-by-date)) + do (unless (gethash (episode-series episode) all-series) + (setf (gethash (episode-series episode) all-series) + (make-array max :initial-element nil)) + (setf all-series-names + (cons (episode-series episode) all-series-names))) + (setf (elt (gethash (episode-series episode) all-series) (decf count)) + episode)) + (values all-series all-series-names max))) + +(defun watch-timeline () + (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) + (loop for series in all-series-names + do (format t "~30a (~{~:[ ~;•~]~})~%" series + (coerce (subseq (gethash series all-series) (- max 60)) 'list))))) + +(defun watch-timelinec () + (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) + (let ((chart (make-array (list (length all-series-names) max) :initial-element nil)) + (newcol 0) + (oldrow -1)) + (loop for oldcol upto (1- max) + do (loop for series in all-series-names + for row from 0 upto (length all-series-names) + do (when (elt (gethash series all-series) oldcol) + (when (<= row oldrow) + (incf newcol)) + (setf (aref chart row newcol) + (elt (gethash series all-series) oldcol)) + (setf oldrow row)))) + (loop for series in all-series-names + for i from 0 upto (length all-series-names) + do (format t "~30a (" series) + (loop for j from (- newcol 60) upto newcol + do (format t "~:[ ~;•~]" (aref chart i j)) + (if (= j newcol) + (format t ")~%"))))))) + +(defun watch-timelinev () + (multiple-value-bind (all-series all-series-names max) (timeline-all *db*) + (loop for series in all-series-names + counting series into count + do (format t "~va ~30a~%" count " " series )) + (loop for i from 0 upto (1- max) + do (let ((episode nil)) + (loop for series in all-series-names + do (format t "~:[ ~;~:*~02a~]" + (when (elt (gethash series all-series) i) + (setf episode (elt (gethash series all-series) i)) + (episode-episode episode)))) + (format t " (~a)~%" (episode-series episode)))))) + +(defun watch-all () + (format t "~{~& ~a~%~}" (sort (get-all *db*) #'compare-by-date))) + +(defun watch-new-series (&key name description tags) + (cdar (push (cons name (make-series :description description :tags tags)) *db*))) + +(defun get-or-add-series (name database) + (or (get-series name database) + (if (y-or-n-p "Add new series? [y/n]: ") + (watch-new-series + :name name + :description (prompt-read "Description" name) + :tags (parse-tags (prompt-read "Tags" "active"))) + nil))) + +(defun watch-add () + (let* ((series (loop thereis (get-or-add-series (prompt-read "Series") *db*))) + (episode (prompt-for-episode (car (series-episodes series))))) + (push episode (series-episodes series)))) + +(defun watch-series-names () + (format T "~{~& ~a~%~}" + (sort (mapcar #'car *db*) + (lambda (series1 series2) + (compare-by-date (car (series-episodes (get-value series1 *db*))) + (car (series-episodes (get-value series2 *db*)))))))) + +(defun exact-match (term text) + (string-equal (format nil "~{~a~^ ~}" term) text)) + +(defun fuzzy-match (term text) + (loop for word in term + when (search word text :test 'string-equal) + collect it)) + +(defun match-tags (term tags) + (intersection (mapcar #'intern term) tags)) + +(defun search-title (term database) + (loop for episode in (get-all database) + when (exact-match term (episode-title episode)) + collect episode)) + +(defun search-tags (term database) + (sort (loop for episode in (get-all database) + for matches = (match-tags term (episode-tags episode)) + when matches collect (list (length matches) episode)) + #'> :key #'car)) + +(defun search-title-fuzzy (term database) + (sort (loop for episode in (get-all database) + for matches = (fuzzy-match term (episode-title episode)) + when matches collect (list (length matches) episode)) + #'> :key #'car)) + +(defun search-all (term database) + (let ((exact-results '()) + (fuzzy-results '()) + (tag-results '())) + (dolist (episode (get-all database)) + (cond ((exact-match term (episode-title episode)) + (push episode exact-results)) + ((fuzzy-match term (episode-title episode)) + (push episode fuzzy-results)) + ((match-tags term (episode-tags episode)) + (push episode tag-results)))) + (append (sort exact-results #'compare-by-date) + (sort tag-results #'compare-by-date) + (sort fuzzy-results #'compare-by-date)))) + +(defun watch-search (term) + (format t "~{~& ~a~%~}" (search-all term *db*))) + +(defun list-all-tags (database) + (let ((tags (make-hash-table :test 'equal))) + (dolist (tag (apply #'append (mapcar #'episode-tags (get-all database)))) + (setf (gethash tag tags) (1+ (or (gethash tag tags) 0)))) + tags)) + +(defun watch-tags () + (maphash #'(lambda (tag count) (format t "~a (~d) " tag count)) + (list-all-tags *db*)) + (terpri)) + +(defun find-series-episode (term database) + (let ((series (get-series (format nil "~{~a~^ ~}" (butlast term)) database))) + (if series + (let* ((season-episode (car (last term))) + (pos (position #\- season-episode)) + (season-str (when pos (subseq season-episode 0 pos))) + (season (or (parse-integer-quietly season-str) season-str)) + (episode-str (if pos + (subseq season-episode (1+ pos)) + season-episode)) + (episode-nr (or (parse-integer-quietly episode-str) episode-str))) + (loop for episode in (series-episodes series) + when (and (equal (episode-episode episode) episode-nr) + (equal (episode-season episode) season)) + collect episode)) + (let ((series (get-series (format nil "~{~a~^ ~}" term) database))) + (if series + (list (car (series-episodes series)))))))) + + +(defun find-episode (term database) + (or (find-series-episode term database) + (search-title term database) + (let* ((res (or (search-tags term database) + (search-title-fuzzy term database))) + (max (caar res))) + (loop for (matches episode) in res when (equal matches max) collect episode)))) + +(defun edit-episode (episode database) + (format t "editing:~%~a~%" episode) + (setf (episode-series episode) + (prompt-read "Series Title" (episode-series episode))) + (setf (episode-title episode) + (prompt-read "Title" (episode-title episode))) + (setf (episode-season episode) + (parse-number (prompt-read "Season" (episode-season episode)))) + (setf (episode-episode episode) + (parse-number (prompt-read "Episode" (episode-episode episode)))) + (setf (episode-part episode) + (parse-number (prompt-read "Part" (episode-part episode)))) + (setf (episode-date episode) + (parse-date (prompt-read "Date watched" (format-ymd (episode-date episode))))) + (setf (episode-tags episode) + (parse-tags (prompt-read "Tags" (format nil "~{~a~^ ~}" (episode-tags episode)))))) + +(defun watch-edit (term) + (let ((episodes (find-episode term *db*))) + (if (> (length episodes) 1) + (format t "found more than one episode, please be more specific:~%~{~& ~a~%~}" episodes) + (edit-episode (car episodes) *db*)))) + +(defun watch-load (dbfile) + (setf *db* (load-db dbfile))) + + +(defun argv () + (or + #+clisp (ext:argv) + #+sbcl sb-ext:*posix-argv* + #+clozure (ccl::command-line-arguments) + #+gcl si:*command-args* + #+ecl (loop for i from 0 below (si:argc) collect (si:argv i)) + #+cmu extensions:*command-line-strings* + #+allegro (sys:command-line-arguments) + #+lispworks sys:*line-arguments-list* + nil)) + +(defun main (argv) + (let ((dbfile (make-pathname :name "lwatch" :type nil :defaults *load-pathname*))) + (watch-load dbfile) + (format t "loaded db~%") + (cond ((equal (cadr argv) "add") (watch-add) (watch-save dbfile)) + ((equal (cadr argv) "latest") (watch-latest)) + ((null (cadr argv)) (watch-latest)) + ((equal (cadr argv) "series") (watch-series-names)) + ((and (equal (cadr argv) "all") (equal (caddr argv) "series")) (watch-all-series)) + ((equal (cadr argv) "all") (watch-all)) + ((equal (cadr argv) "tags") (watch-tags)) + ((equal (cadr argv) "search") (watch-search (cddr argv))) + ((equal (cadr argv) "edit") (watch-edit (cddr argv)) (watch-save dbfile)) + ((equal (cadr argv) "timeline") (watch-timeline)) + ((equal (cadr argv) "timelinev") (watch-timelinev)) + ((equal (cadr argv) "timelinec") (watch-timelinec)) + (T (watch-series (format nil "~{~a~^ ~}" (cdr argv))))))) + +(main (argv)) diff --git a/Task/Simple-database/D/simple-database.d b/Task/Simple-database/D/simple-database.d new file mode 100644 index 0000000000..0e0b050a3f --- /dev/null +++ b/Task/Simple-database/D/simple-database.d @@ -0,0 +1,87 @@ +import std.stdio, std.algorithm, std.string, std.conv, std.array, + std.file, std.csv, std.datetime; + +private { + immutable filename = "simdb.csv"; + + struct Item { + string name, date, category; + } + + void addItem(in string[] item) { + if (item.length < 3) + return printUsage(); + auto db = load(); + const date = text(cast(DateTime)Clock.currTime); + const cat = (item.length == 4) ? item[3] : "none"; + db ~= Item(item[2], date, cat); + store(db); + } + + void printLatest(in string[] a) { + auto db = load(); + if (db.empty) + return writeln("No entries in database."); + db.sort!q{ a.date > b.date }; + if (a.length == 3) { + foreach (item; db) + if (item.category == a[2]) + writefln("%s, %s, %s", item.tupleof); + } else { + writefln("%s, %s, %s", db[0].tupleof); + } + } + + void printAll() { + auto db = load(); + if (db.empty) + return writeln("No entries in database."); + db.sort!q{ a.date < b.date }; + foreach (item; db) + writefln("%s, %s, %s", item.tupleof); + } + + Item[] load() { + Item[] db; + if (filename.exists && filename.isFile) { + try { + const text = filename.readText; + if (!text.empty) + db = csvReader!Item(text).array; + } catch (CSVException e) { + writeln(e.msg); + } + } + return db; + } + + void store(in Item[] db) { + auto f = File(filename, "w+"); + foreach (item; db) + f.writefln("%s,%s,%s", item.tupleof); + } + + void printUsage() { + writeln( +`Usage: + simdb cmd [categoryName] + + add add item, followed by optional category + latest print last added item(s), followed by optional category + all print all + + For instance: add "some item name" "some category name"`); + } +} + +void main(in string[] args) { + if (args.length < 2 || args.length > 4) + return printUsage(); + + switch (args[1].toLower) { + case "add": addItem(args); break; + case "latest": printLatest(args); break; + case "all": printAll(); break; + default: printUsage(); break; + } +} diff --git a/Task/Simple-database/Forth/simple-database.fth b/Task/Simple-database/Forth/simple-database.fth new file mode 100644 index 0000000000..a5881b6a18 --- /dev/null +++ b/Task/Simple-database/Forth/simple-database.fth @@ -0,0 +1,129 @@ +\ sdb.fs Simple database. Gforth 0.7.0 specific +' noop is bootmessage + +wordlist constant USER: \ USER functions +wordlist constant SDB \ DB keys +wordlist constant FIELDS \ DB fields + +: -SDB?EXIT ( -- ; Continue if `SDB' non-empty ) + SDB cell+ @ 0= IF rdrop exit THEN ; + +\ MACROS +: |comp| ( MACRO: | code to be compiled | ) + char parse evaluate ; immediate +: LIST ( node -- ) ]] BEGIN @ dup WHILE >R [[ ; immediate +: LOOP-LIST ( -- ) ]] R> REPEAT drop [[ ; immediate +: UNLIST ( -- ) POSTPONE rdrop ; immediate + +\ Helper words +: .; [char] ; emit ; +: !+ dup cell+ -rot ! ; +: ($+) ( cas us cad ud -- cad us+ud ; append source string to destination ) + swap >R 2dup + R> swap >R tuck + swap >R swap move R> R> ; + +\ --- Working Record Fields +current @ FIELDS current ! +2variable person +2variable birthday +2variable relationship +2variable hobby +current ! FIELDS >order + +\ --- Ring list +: new-node ( -- node ; root of circular list ) + here dup , ; +: do-link ( node new-node -- ; do link after current node ) + over @ over ! swap ! ; +: empty-ring? ( node -- f ) dup @ = ; + +: RING ( node -- ) ]] dup BEGIN @ 2dup <> WHILE 2>R [[ ; immediate +: LOOP-RING ( -- ) ]] 2R> REPEAT 2drop [[ ; immediate +: UNRING ( -- ) postpone 2RDROP ; immediate + +:noname + s" " person 2! s" 9999.01.01" birthday 2! s" " relationship 2! s" " hobby 2! ; +new-node swap , CONSTANT OLD + +\ --- Insertion into ring +: node>xt ( node -- xt ) cell+ @ ; +: bday@ ( node -- ca u ) node>xt execute birthday 2@ ; +: datecmp ( node node -- -1|0|1 ) bday@ rot bday@ compare ; + +: search-by-date ( new-node node -- node' ; Linear search by birth date ) + dup + RING ( new-node node ) + over I datecmp 0< + IF nip UNRING exit + ELSE drop I THEN + LOOP-RING nip ; + +: insert-ordered ( new-node -- ) + OLD dup empty-ring? 0= + IF over swap search-by-date THEN swap do-link ; + +\ --- Field compiling +: fld: [char] ; parse postpone sliteral ; immediate + +: _sdb-walk ( MACRO: | xt[--] -- | ) + ]] -SDB?EXIT here dup SDB cell+ + LIST I name>int swap !+ LOOP-LIST [[ 1 cells ]] literal - + DO I @ |comp| [[ -1 cells ]] literal +LOOP [[ ; immediate + +2variable category +: msg_nocategory ( -- ) + ." No such category!" cr ; + +\ --- USER definitions +user: >order current @ USER: current ! +: bye bye ; +: .s .s ; +: newline cr ; +: godb SDB >order ; +: .keys SDB wordlist-words ; +: .person person 2@ type ; +: .birthday birthday 2@ type ; +: .relationship relationship 2@ type ; +: .hobby hobby 2@ type ; +: .record .person 1 spaces .birthday .; .relationship .; .hobby .; ; + +: .last SDB cell+ @ dup + IF name>int execute .record ELSE drop THEN ; + +: .lastbycategory ( "field-name" -- ) + here 0 category 2! parse-name FIELDS search-wordlist + IF sdb cell+ + LIST ( xt ) + I name>int execute dup execute 2@ category 2@ 2swap search nip nip 0= + IF .record cr dup execute 2@ category 2@ ($+) category 2! THEN + LOOP-LIST drop + ELSE ['] msg_nocategory stderr OUTFILE-EXECUTE THEN ; + +: .bydate ( -- ) + OLD RING I node>xt execute .record cr LOOP-RING ; + +: .sdb _sdb-walk | execute .record cr | ; +: sdb-dump _sdb-walk | execute ." +: " .record cr | ; + +: dump ( "db-file" -- ) + parse-name w/o + CREATE-FILE throw dup + ['] sdb-dump swap OUTFILE-EXECUTE + CLOSE-FILE throw ; + +: load ( "db-file" -- ) include ; + +: +: ( "person birth-day;relationship;hobby; -- ) + new-node dup cell+ >R 0 , \ post `xt' + current @ SDB current ! \ compile into `sdb' wordlist + : latestxt dup R> ! \ fix-up `xt' + ]] literal >name name>string person 2! fld: birthday 2! fld: relationship 2! fld: hobby 2! ; [[ + current ! + insert-ordered ; + +: HELP cr + cr ." KEYWORDS: " USER: wordlist-words cr ." ---" + cr ." Prefix `.' means print" + cr ." To add a record, type: +: name yyyy.mm.dd;relationship;hobby;" + cr cr ; +current ! +SEAL godb diff --git a/Task/Simple-database/Go/simple-database.go b/Task/Simple-database/Go/simple-database.go new file mode 100644 index 0000000000..a7ac6a390a --- /dev/null +++ b/Task/Simple-database/Go/simple-database.go @@ -0,0 +1,340 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "os" + "sort" + "strings" + "time" + "unicode" +) + +// Database record format. Time stamp and name are required. +// Tags and notes are optional. +type Item struct { + Stamp time.Time + Name string + Tags []string `json:",omitempty"` + Notes string `json:",omitempty"` +} + +// Item implements stringer interface +func (i *Item) String() string { + s := i.Stamp.Format(time.ANSIC) + "\n Name: " + i.Name + if len(i.Tags) > 0 { + s = fmt.Sprintf("%s\n Tags: %v", s, i.Tags) + } + if i.Notes > "" { + s += "\n Notes: " + i.Notes + } + return s +} + +// collection of Items +type db []*Item + +// db implements sort.Interface +func (d db) Len() int { return len(d) } +func (d db) Swap(i, j int) { d[i], d[j] = d[j], d[i] } +func (d db) Less(i, j int) bool { return d[i].Stamp.Before(d[j].Stamp) } + +// hard coded database file name +const fn = "sdb.json" + +func main() { + if len(os.Args) == 1 { + latest() + return + } + switch os.Args[1] { + case "add": + add() + case "latest": + latest() + case "tags": + tags() + case "all": + all() + case "help": + help() + default: + usage("unrecognized command") + } +} + +func usage(err string) { + if err > "" { + fmt.Println(err) + } + fmt.Println(`usage: sdb [command] [data] + where command is one of add, latest, tags, all, or help.`) +} + +func help() { + usage("") + fmt.Println(` +Commands must be in lower case. +If no command is specified, the default command is latest. + +Latest prints the latest item. +All prints all items in chronological order. +Tags prints the lastest item for each tag. +Help prints this message. + +Add adds data as a new record. The format is, + + name [tags] [notes] + +Name is the name of the item and is required for the add command. + +Tags are optional. A tag is a single word. +A single tag can be specified without enclosing brackets. +Multiple tags can be specified by enclosing them in square brackets. + +Text remaining after tags is taken as notes. Notes do not have to be +enclosed in quotes or brackets. The brackets above are only showing +that notes are optional. + +Quotes may be useful however--as recognized by your operating system shell +or command line--to allow entry of arbitrary text. In particular, quotes +or escape characters may be needed to prevent the shell from trying to +interpret brackets or other special characters. + +Examples: +sdb add Bookends // no tags, no notes +sdb add Bookends rock my favorite // tag: rock, notes: my favorite +sdb add Bookends [rock folk] // two tags +sdb add Bookends [] "Simon & Garfunkel" // notes, no tags +sdb add "Simon&Garfunkel [artist]" // name: Simon&Garfunkel, tag: artist + +As shown in the last example, if you use features of your shell to pass +all data as a single string, the item name and tags will still be identified +by separating whitespace. + +The database is stored in JSON format in the file "sdb.json" +`) +} + +// load data for read only purposes. +func load() (db, bool) { + d, f, ok := open() + if ok { + f.Close() + if len(d) == 0 { + fmt.Println("no items") + ok = false + } + } + return d, ok +} + +// open database, leave open +func open() (d db, f *os.File, ok bool) { + var err error + f, err = os.OpenFile(fn, os.O_RDWR|os.O_CREATE, 0666) + if err != nil { + fmt.Println("cant open??") + fmt.Println(err) + return + } + jd := json.NewDecoder(f) + err = jd.Decode(&d) + // EOF just means file was empty. That's okay with us. + if err != nil && err != io.EOF { + fmt.Println(err) + f.Close() + return + } + ok = true + return +} + +// handle latest command +func latest() { + d, ok := load() + if !ok { + return + } + sort.Sort(d) + fmt.Println(d[len(d)-1]) +} + +// handle all command +func all() { + d, ok := load() + if !ok { + return + } + sort.Sort(d) + for _, i := range d { + fmt.Println("-----------------------------------") + fmt.Println(i) + } + fmt.Println("-----------------------------------") +} + +// handle tags command +func tags() { + d, ok := load() + if !ok { + return + } + // we have to traverse the entire list to collect tags so there + // is no point in sorting at this point. + // collect set of unique tags associated with latest item for each + latest := make(map[string]*Item) + for _, item := range d { + for _, tag := range item.Tags { + li, ok := latest[tag] + if !ok || item.Stamp.After(li.Stamp) { + latest[tag] = item + } + } + } + // invert to set of unique items, associated with subset of tags + // for which the item is the latest. + type itemTags struct { + item *Item + tags []string + } + inv := make(map[*Item][]string) + for tag, item := range latest { + inv[item] = append(inv[item], tag) + } + // now we sort just the items we will output + li := make(db, len(inv)) + i := 0 + for item := range inv { + li[i] = item + i++ + } + sort.Sort(li) + // finally ready to print + for _, item := range li { + tags := inv[item] + fmt.Println("-----------------------------------") + fmt.Println("Latest item with tags", tags) + fmt.Println(item) + } + fmt.Println("-----------------------------------") +} + +// handle add command +func add() { + if len(os.Args) < 3 { + usage("add command requires data") + return + } else if len(os.Args) == 3 { + add1() + } else { + add4() + } +} + +// add command with one data string. look for ws as separators. +func add1() { + data := strings.TrimLeftFunc(os.Args[2], unicode.IsSpace) + if data == "" { + // data must have at least some non-whitespace + usage("invalid name") + return + } + sep := strings.IndexFunc(data, unicode.IsSpace) + if sep < 0 { + // data consists only of a name + addItem(data, nil, "") + return + } + name := data[:sep] + data = strings.TrimLeftFunc(data[sep:], unicode.IsSpace) + if data == "" { + // nevermind trailing ws, it's still only a name + addItem(name, nil, "") + return + } + if data[0] == '[' { + sep = strings.Index(data, "]") + if sep < 0 { + // close bracketed list for the user. no notes. + addItem(name, strings.Fields(data[1:]), "") + } else { + // brackets make things easy + addItem(name, strings.Fields(data[1:sep]), + strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) + } + return + } + sep = strings.IndexFunc(data, unicode.IsSpace) + if sep < 0 { + // remaining word is a tag + addItem(name, []string{data}, "") + } else { + // there's a tag and some data + addItem(name, []string{data[:sep]}, + strings.TrimLeftFunc(data[sep+1:], unicode.IsSpace)) + } +} + +// add command with multiple strings remaining on command line +func add4() { + name := os.Args[2] + tag1 := os.Args[3] + if tag1[0] != '[' { + // no brackets makes things easy + addItem(name, []string{tag1}, strings.Join(os.Args[4:], " ")) + return + } + if tag1[len(tag1)-1] == ']' { + // tags all in one os.Arg is easy too + addItem(name, strings.Fields(tag1[1:len(tag1)-1]), + strings.Join(os.Args[4:], " ")) + return + } + // start a list for tags + var tags []string + if tag1 > "[" { + tags = []string{tag1[1:]} + } + for x, tag := range os.Args[4:] { + if tag[len(tag)-1] != ']' { + tags = append(tags, tag) + } else { + // found end of tag list + if tag > "]" { + tags = append(tags, tag[:len(tag)-1]) + } + addItem(name, tags, strings.Join(os.Args[5+x:], " ")) + return + } + } + // close bracketed list for the user. no notes. + addItem(name, tags, "") +} + +// complete the add command +func addItem(name string, tags []string, notes string) { + db, f, ok := open() + if !ok { + return + } + defer f.Close() + // add the item and format JSON + db = append(db, &Item{time.Now(), name, tags, notes}) + sort.Sort(db) + js, err := json.MarshalIndent(db, "", " ") + if err != nil { + fmt.Println(err) + return + } + // time to overwrite the file + if _, err = f.Seek(0, 0); err != nil { + fmt.Println(err) + return + } + f.Truncate(0) + if _, err = f.Write(js); err != nil { + fmt.Println(err) + } +} diff --git a/Task/Simple-database/Haskell/simple-database.hs b/Task/Simple-database/Haskell/simple-database.hs new file mode 100644 index 0000000000..291c860614 --- /dev/null +++ b/Task/Simple-database/Haskell/simple-database.hs @@ -0,0 +1,128 @@ +import Control.Monad.State +import Data.List (sortBy, nub) +import System.Environment (getArgs, getProgName) +import System.Directory (doesFileExist) +import System.IO (openFile, hGetContents, hClose, IOMode(..), + Handle, hPutStrLn) + +-- for storing dates +data Date = Date Integer Int Int deriving (Show, Read, Eq, Ord) + +-- for storing database items +data Item = Item {description :: String + ,category :: [String] + ,date :: Date + ,optional :: [String]} + deriving (Show, Read) + +-- a state monad transformer which wraps IO actions. +-- the database (state) is passed implicitly between functions. +type ItemList a = StateT [Item] IO a + +-- add an item to the database +addItem :: Item -> ItemList () +addItem i = modify (++ [i]) + +-- get the newest of a list of items +latest :: [Item] -> [Item] +latest [] = [] +latest [x]= [x] +latest xs = take 1 $ sortBy newer xs + +-- compare two items to see which one is newer +newer :: Item -> Item -> Ordering +newer a b = compare (date b) (date a) + +-- list all different categories (no duplicates) +categories :: ItemList [String] +categories = liftM (nub . concatMap category) get + +-- list only the items with the given category tag +filterByCategory :: String -> ItemList [Item] +filterByCategory c = liftM (filter (\i -> c `elem` category i)) get + +-- get the newest of all items +lastOfAll :: ItemList [Item] +lastOfAll = liftM latest get + +-- get the newest item in each category +latestByCategory :: ItemList [Item] +latestByCategory = do + cats <- categories + filt <- mapM filterByCategory cats + return $ concatMap latest filt + +-- sort all items chronologically, newest first +sortByDate :: ItemList [Item] +sortByDate = liftM (sortBy newer) get + +toScreen :: Item -> IO () +toScreen (Item desc cats (Date y m d) opt) = putStrLn $ + "Description:\t" ++ desc ++ "\nCategories:\t" ++ show cats ++ + "\nDate:\t\t" ++ show y ++ "-" ++ show m ++ "-" ++ show d ++ + "\nOther info:\t" ++ show opt + +-- command line argument handling +-- if the user called the program with the option "add", the +-- new item is returned to main so that it can be saved to disk. +-- the argument "opt" is a list. +arguments :: ItemList [Item] +arguments = do + args <- liftIO getArgs + case args of + ("add":desc:cat:year:month:day:opt) -> do + let newItem = parseItem args + addItem newItem + return [newItem] + ("latest":[]) -> do + item <- lastOfAll + lift $ mapM_ toScreen item + return [] + ("category":[]) -> do + items <- latestByCategory + lift $ mapM_ toScreen items + return [] + ("all":[]) -> do + sorted <- sortByDate + lift $ mapM_ toScreen sorted + return [] + _ -> do + lift usage + return [] + +parseItem :: [String] -> Item +parseItem (_:desc:cat:year:month:day:opt) = + Item {description = desc, category = words cat, + date = Date (read year) (read month) (read day), + optional = opt} + +usage :: IO () +usage = do + progName <- getProgName + putStrLn $ "Usage: " ++ progName ++ " add|all|category|latest \ + \OPTIONS\n\nadd \"description\" \"category1 category2\"... \ + \year month day [\"note1\" \"note2\"...]\n\tAdds a new record \ + \to the database.\n\nall\n\tPrints all items in chronological \ + \order.\n\ncategory\n\tPrints the latest item for each category.\ + \\n\nlatest\n\tPrints the latest item." + +-- the program creates, reads and writes to a file in the current directory +main :: IO () +main = do + progName <- getProgName + let fileName = progName ++ ".db" + e <- doesFileExist fileName + if e + then do + hr <- openFile fileName ReadMode + f <- hGetContents hr + v <- evalStateT arguments (map read $ lines f) + hClose hr -- must be called after working with contents! + hw <- openFile fileName AppendMode + mapM_ (hPutStrLn hw . show) v + hClose hw + else do + v <- evalStateT arguments [] + hw <- openFile fileName WriteMode + mapM_ (hPutStrLn hw . show) v + hClose hw diff --git a/Task/Simple-database/J/simple-database-1.j b/Task/Simple-database/J/simple-database-1.j new file mode 100644 index 0000000000..982209ee6c --- /dev/null +++ b/Task/Simple-database/J/simple-database-1.j @@ -0,0 +1,108 @@ +HELP=: 0 :0 +Commands: + +DBNAME add DATA +DBNAME display the latest entry +DBNAME display the latest entry where CATEGORY contains WORD +DBNAME display all entries +DBNAME display all entries order by CATEGORY + +1) The first add with new DBNAME assign category names. +2) lower case arguments verbatim. +3) UPPER CASE: substitute your values. + +Examples, having saved this program as a file named s : +$ jconsole s simple.db display all entries +$ jconsole s simple.db add "first field" "2nd field" +) + +Q=: '''' NB. quote character +time=: 6!:0@:('YYYY-MM-DD:hh:mm:ss.sss'"_) + +embed=: >@:{.@:[ , ] , >@:{:@:[ +assert '(x+y)' -: '()' embed 'x+y' + +Duplicate=: 1 :'#~ m&= + 1 #~ #' +assert 0 1 2 3 3 4 -: 3 Duplicate i.5 + +prepare=: LF ,~ [: }:@:; (Q;Q,';')&embed@:(Q Duplicate)&.>@:(;~ time) +assert (-: }.@:".@:}:@:prepare) 'boxed';'';'li''st';'of';'''strings''' + +categorize=: dyad define +i=. x i. y +if. (1 (~: #) i) +. i (= #) x do. + smoutput 'choose 1 of' + smoutput x + exit 1 +end. +{. i NB. "index of" frame has rank 1. +) +assert 0 -: 'abc' categorize 'a' + +loadsdb=: (<'time') (<0 0)} ".;._2@:(1!:1) + +Dispatch=: conjunction define +help +: +commands=. y +command=. {. commands +x (u`help@.(command(i.~ ;:)n)) }.commands +) + +NB. the long fork in show groups (": #~ (1 1 embed (1j1 }:@:# (1 #~ #)))) +show=: smoutput@:(": #~ 1 1 embed 1j1 }:@:# 1 #~ #) + +in=: +./@:E. +assert 'the' in'quick brown fox jumps over the lazy dog' +assert 'the'-.@:in'QUICK BROWN FOX JUMPS OVER THE LAZY DOG' + +where=: dyad define +'category contains word'=. 3 {. y +if. 'contains' -.@:-: contains do. + help'' + exit 1 +end. +i=. x ({.@:[ categorize <@:]) category +j=. {: I. ; word&in&.> i {"1 x +if. 0 (= #) j do. + smoutput 'no matches' +else. + x (show@:{~ 0&,) j +end. +) + +entry=: 4 : 0 +if. a: = y do. + show@:({. ,: {:) x +else. + x ''`where Dispatch'where' y +end. +) + +latest=: ''`entry Dispatch'entry' +the=: ''`latest Dispatch'latest' + +by=: 4 : 0 +i=. x (categorize~ {.)~ y +show ({. , (/: i&{"1)@:}.) x +) + +order=: ''`by Dispatch'by' + +entries=: 4 : 0 +if. a: = y do. + show x +else. + x ''`order Dispatch'order' y +end. +) + +all=: ''`entries Dispatch'entries' + +help=: smoutput@:(HELP"_) +add=: 1!:3~ prepare NB. minimal---no error tests +display=: (the`all Dispatch'the all'~ loadsdb)~ NB. load the simple db for some sort of display + +({. add`display Dispatch'add display' }.)@:(2&}.)ARGV + +exit 0 diff --git a/Task/Simple-database/J/simple-database-2.j b/Task/Simple-database/J/simple-database-2.j new file mode 100644 index 0000000000..804f0f00aa --- /dev/null +++ b/Task/Simple-database/J/simple-database-2.j @@ -0,0 +1,13 @@ +D='jconsole s dataflow' + +$D add name expression algebraic rank valence example explanation +$D add insert 'f/ y' 'insert f within y' infinite dyad 'sum=: +/' 'continued_fraction=:+`%/' +$D add fork '(f g h)y' 'g(f(y),h(y))' infinite monad 'average=: +/ % #' 'sum divided by tally' +$D add hook '(f g)y' 'f(y,g(y))' infinite monad '(/: 2&{"1)table' 'sort by third column' +$D add hook 'x(f g)y' 'f(x,g(y))' infinite dyad 'display verb in s' 'a reflexive dyadic hook' +$D add fork 'x(f g h)y' 'g(f(x,y),h(x,y))' infinite dyad '2j1(+ * -)9 12' 'product of sum and difference' +$D add reflexive 'f~ y' 'f(y,y)' infinite monad '^~y' 'y raised to the power of y' +$D add passive 'x f~ y' 'f(y,x)' 'ranks of f' dyad '(%~ i.@:>:) 8x' '8 intervals from 0 to 1' +$D add atop 'f@g y' 'f(g(y))' 'rank of g' monad '*:@(+/)' 'square the sum' +$D add atop 'x f@g y' 'f(g(x,y))' 'rank of g' dyad '>@{.' '(lisp) open the car' +$D add 'many more!' diff --git a/Task/Simple-database/J/simple-database-3.j b/Task/Simple-database/J/simple-database-3.j new file mode 100644 index 0000000000..1d7372964e --- /dev/null +++ b/Task/Simple-database/J/simple-database-3.j @@ -0,0 +1,76 @@ +$ . input # source the input +$ echo $D +jconsole s dataflow +$ $D display the latest entry +┌───────────────────────┬──────────┬──────────┬─────────┬────┬───────┬───────┬───────────┐ +│time │name │expression│algebraic│rank│valence│example│explanation│ +│2012-02-07:20:36:54.749│many more!│ │ │ │ │ │ │ +└───────────────────────┴──────────┴──────────┴─────────┴────┴───────┴───────┴───────────┘ +$ $D display the latest entry where 'part of speech' contains verb +choose 1 of +┌────┬────┬──────────┬─────────┬────┬───────┬───────┬───────────┐ +│time│name│expression│algebraic│rank│valence│example│explanation│ +└────┴────┴──────────┴─────────┴────┴───────┴───────┴───────────┘ +$ $D display the latest entry where example contains average +┌───────────────────────┬────┬──────────┬────────────┬────────┬───────┬────────────────┬────────────────────┐ +│time │name│expression│algebraic │rank │valence│example │explanation │ +│2012-02-07:20:36:54.564│fork│(f g h)y │g(f(y),h(y))│infinite│monad │average=: +/ % #│sum divided by tally│ +└───────────────────────┴────┴──────────┴────────────┴────────┴───────┴────────────────┴────────────────────┘ +$ $D display all entries ordre by valence # oops! transposition typo. +Commands: + +DBNAME add DATA +DBNAME display the latest entry +DBNAME display the latest entry where CATEGORY contains WORD +DBNAME display all entries +DBNAME display all entries order by CATEGORY + +1) The first add with new DBNAME assign category names. +2) lower case arguments verbatim. +3) UPPER CASE: substitute your values. + +Examples, having saved this program as a file named s : +$ jconsole s simple.db display all entries +$ jconsole s simple.db add "first field" "2nd field" + +$ $D display all entries order by valence +┌───────────────────────┬──────────┬──────────┬─────────────────┬──────────┬───────┬─────────────────┬─────────────────────────────┐ +│time │name │expression│algebraic │rank │valence│example │explanation │ +│2012-02-08:23:45:06.539│many more!│ │ │ │ │ │ │ +│2012-02-08:23:45:06.329│insert │f/ y │insert f within y│infinite │dyad │sum=: +/ │continued_fraction=:+`%/ │ +│2012-02-08:23:45:06.400│hook │x(f g)y │f(x,g(y)) │infinite │dyad │display verb in s│a reflexive dyadic hook │ +│2012-02-08:23:45:06.426│fork │x(f g h)y │g(f(x,y),h(x,y)) │infinite │dyad │2j1(+ * -)9 12 │product of sum and difference│ +│2012-02-08:23:45:06.471│passive │x f~ y │f(y,x) │ranks of f│dyad │(%~ i.@:>:) 8x │8 intervals from 0 to 1 │ +│2012-02-08:23:45:06.515│atop │x f@g y │f(g(x,y)) │rank of g │dyad │>@{. │(lisp) open the car │ +│2012-02-08:23:45:06.353│fork │(f g h)y │g(f(y),h(y)) │infinite │monad │average=: +/ % # │sum divided by tally │ +│2012-02-08:23:45:06.376│hook │(f g)y │f(y,g(y)) │infinite │monad │(/: 2&{"1)table │sort by third column │ +│2012-02-08:23:45:06.448│reflexive │f~ y │f(y,y) │infinite │monad │^~y │y raised to the power of y │ +│2012-02-08:23:45:06.493│atop │f@g y │f(g(y)) │rank of g │monad │*:@(+/) │square the sum │ +└───────────────────────┴──────────┴──────────┴─────────────────┴──────────┴───────┴─────────────────┴─────────────────────────────┘ +$ $D display all entries +┌───────────────────────┬──────────┬──────────┬─────────────────┬──────────┬───────┬─────────────────┬─────────────────────────────┐ +│time │name │expression│algebraic │rank │valence│example │explanation │ +│2012-02-08:23:45:06.329│insert │f/ y │insert f within y│infinite │dyad │sum=: +/ │continued_fraction=:+`%/ │ +│2012-02-08:23:45:06.353│fork │(f g h)y │g(f(y),h(y)) │infinite │monad │average=: +/ % # │sum divided by tally │ +│2012-02-08:23:45:06.376│hook │(f g)y │f(y,g(y)) │infinite │monad │(/: 2&{"1)table │sort by third column │ +│2012-02-08:23:45:06.400│hook │x(f g)y │f(x,g(y)) │infinite │dyad │display verb in s│a reflexive dyadic hook │ +│2012-02-08:23:45:06.426│fork │x(f g h)y │g(f(x,y),h(x,y)) │infinite │dyad │2j1(+ * -)9 12 │product of sum and difference│ +│2012-02-08:23:45:06.448│reflexive │f~ y │f(y,y) │infinite │monad │^~y │y raised to the power of y │ +│2012-02-08:23:45:06.471│passive │x f~ y │f(y,x) │ranks of f│dyad │(%~ i.@:>:) 8x │8 intervals from 0 to 1 │ +│2012-02-08:23:45:06.493│atop │f@g y │f(g(y)) │rank of g │monad │*:@(+/) │square the sum │ +│2012-02-08:23:45:06.515│atop │x f@g y │f(g(x,y)) │rank of g │dyad │>@{. │(lisp) open the car │ +│2012-02-08:23:45:06.539│many more!│ │ │ │ │ │ │ +└───────────────────────┴──────────┴──────────┴─────────────────┴──────────┴───────┴─────────────────┴─────────────────────────────┘ +$ cat dataflow +'2012-02-08:23:45:06.304';'name';'expression';'algebraic';'rank';'valence';'example';'explanation' +'2012-02-08:23:45:06.329';'insert';'f/ y';'insert f within y';'infinite';'dyad';'sum=: +/';'continued_fraction=:+`%/' +'2012-02-08:23:45:06.353';'fork';'(f g h)y';'g(f(y),h(y))';'infinite';'monad';'average=: +/ % #';'sum divided by tally' +'2012-02-08:23:45:06.376';'hook';'(f g)y';'f(y,g(y))';'infinite';'monad';'(/: 2&{"1)table';'sort by third column' +'2012-02-08:23:45:06.400';'hook';'x(f g)y';'f(x,g(y))';'infinite';'dyad';'display verb in s';'a reflexive dyadic hook' +'2012-02-08:23:45:06.426';'fork';'x(f g h)y';'g(f(x,y),h(x,y))';'infinite';'dyad';'2j1(+ * -)9 12';'product of sum and difference' +'2012-02-08:23:45:06.448';'reflexive';'f~ y';'f(y,y)';'infinite';'monad';'^~y';'y raised to the power of y' +'2012-02-08:23:45:06.471';'passive';'x f~ y';'f(y,x)';'ranks of f';'dyad';'(%~ i.@:>:) 8x';'8 intervals from 0 to 1' +'2012-02-08:23:45:06.493';'atop';'f@g y';'f(g(y))';'rank of g';'monad';'*:@(+/)';'square the sum' +'2012-02-08:23:45:06.515';'atop';'x f@g y';'f(g(x,y))';'rank of g';'dyad';'>@{.';'(lisp) open the car' +'2012-02-08:23:45:06.539';'many more!' +$ diff --git a/Task/Simple-database/PicoLisp/simple-database.l b/Task/Simple-database/PicoLisp/simple-database.l new file mode 100644 index 0000000000..f1c6cb6562 --- /dev/null +++ b/Task/Simple-database/PicoLisp/simple-database.l @@ -0,0 +1,36 @@ +#!/usr/bin/pil + +(de usage () + (prinl + "Usage:^J\ + sdb add <cat> <date> ... Add a new entry^J\ + sdb <file> get <title> Retrieve an entry^J\ + sdb <file> latest Print the latest entry^J\ + sdb <file> categories Print the latest for each cat^J\ + sdb <file> Print all, sorted by date" ) ) + +(de printEntry (E) + (apply println (cdddr E) (car E) (cadr E) (datStr (caddr E))) ) + +(ifn (setq *File (opt)) + (usage) + (case (opt) + (add + (let (Ttl (opt) Cat (opt)) + (if (strDat (opt)) + (rc *File Ttl (cons Cat @ (argv))) + (prinl "Bad date") ) ) ) + (get + (let Ttl (opt) + (when (rc *File Ttl) + (printEntry (cons Ttl @)) ) ) ) + (latest + (printEntry (maxi caddr (in *File (read)))) ) + (categories + (for Cat (by cadr group (in *File (read))) + (printEntry (maxi caddr Cat)) ) ) + (NIL + (mapc printEntry (by caddr sort (in *File (read)))) ) + (T (usage)) ) ) + +(bye) diff --git a/Task/Simple-database/Pike/simple-database.pike b/Task/Simple-database/Pike/simple-database.pike new file mode 100644 index 0000000000..03f90b0f6f --- /dev/null +++ b/Task/Simple-database/Pike/simple-database.pike @@ -0,0 +1,154 @@ +mapping db = ([]); + +mapping make_episode(string series, string title, string episode, array date) +{ + return ([ "series":series, "episode":episode, "title":title, "date":date ]); +} + +void print_episode(mapping episode) +{ + write(" %-30s %10s %-30s (%{%d.%})\n", + episode->series, episode->episode, episode->title, episode->date); +} + +void print_series(mapping series) +{ + write("%-30s %-10s\n", series->series, series->status); + map(series->episodes, print_episode); +} + +void dump_db(mapping database) +{ + foreach(database; string name; mapping series) + { + print_series(series); + } +} + +array get_latest(mapping database) +{ + array latest = ({}); + foreach(database; string name; mapping series) + { + latest += ({ series->episodes[0] }); + } + return latest; +} + +int(0..1) compare_date(array a, array b) +{ + if (!arrayp(a) && !arrayp(b)) return false; + if (!arrayp(a) || !sizeof(a)) return arrayp(b) && sizeof(b); + if (!arrayp(b) || !sizeof(b)) return arrayp(a) && sizeof(a); + if (a[0] == b[0]) return compare_date(a[1..], b[1..]); + return a[0] < b[0]; +} + +int(0..1) compare_by_date(mapping a, mapping b) +{ + return compare_date(reverse(a->date), reverse(b->date)); +} + +void watch_list(mapping database) +{ + map(Array.sort_array(get_latest(database), compare_by_date), + print_episode); +} + +string prompt_read(string prompt) +{ + write("%s: ", prompt); + return Stdio.stdin.gets(); +} + +array parse_date(string date) +{ + return (array(int))(date/"."); +} + +mapping prompt_for_episode() +{ + return make_episode(prompt_read("Series"), + prompt_read("Title"), + prompt_read("Episode"), + parse_date(prompt_read("Date watched"))); +} + +// pike offers encode_value() and decode_value() as standard ways +// to save and read data, but that is not a human readable format. +// therefore we are instead printing the structure as debug-output +// which is a readable form as long as it only contains integers, +// strings, mappings, arrays and multisets this format can be read by pike. +// to read it we are creating a class that contains the data as a value, +// which is then compiled and instantiated to allow us to pull the data out. +void save_db(string filename, mapping database) +{ + Stdio.write_file(filename, sprintf("%O", database)); +} + +void watch_save() +{ + save_db("pwatch", db); +} + +mapping load_db(string filename) +{ + if (file_stat(filename)) + return compile_string("mixed data = " + + Stdio.read_file(filename) + ";")()->data; + else return ([]); +} + +mapping get_series(string name, mapping database) +{ + return database[name]; +} + +array get_episode_list(string series, mapping database) +{ + return database[series]->episodes; +} + +void watch_new_series(string name, string status, mapping database) +{ + database[name] = (["series":name, "status":status, "episodes":({}) ]); +} + +mapping get_or_add_series(string name, mapping database) +{ + if (!database[name]) + { + string answer = prompt_read("Add new series? [y/n]: "); + if (answer == "y") + watch_new_series(name, "active", database); + } + return database[name]; +} + +void watch_add(mapping database) +{ + mapping episode = prompt_for_episode(); + string series_name = episode->series; + mapping series = get_or_add_series(series_name, database); + if (!series) + watch_add(database); + else + series->episodes = Array.unshift(series->episodes, episode); +} + +void watch_load() +{ + db = load_db("pwatch"); +} + +int main(int argc, array argv) +{ + watch_load(); + if (argc>1 && argv[1] == "add") + { + watch_add(db); + watch_save(); + } + else + watch_list(db); +} diff --git a/Task/Simple-database/Python/simple-database.py b/Task/Simple-database/Python/simple-database.py new file mode 100644 index 0000000000..11c3e9968f --- /dev/null +++ b/Task/Simple-database/Python/simple-database.py @@ -0,0 +1,108 @@ +#!/usr/bin/python3 + +'''\ +Simple database for: http://rosettacode.org/wiki/Simple_database + +''' + +import argparse +from argparse import Namespace +import datetime +import shlex + + +def parse_args(): + 'Set up, parse, and return arguments' + + parser = argparse.ArgumentParser(epilog=globals()['__doc__']) + + parser.add_argument('command', choices='add pl plc pa'.split(), + help='''\ +add: Add a new entry +pl: Print the latest entry +plc: Print the latest entry for each category/tag +pa: Print all entries sorted by a date''') + parser.add_argument('-d', '--description', + help='A description of the item. (e.g., title, name)') + parser.add_argument('-t', '--tag', + help=('''A category or tag (genre, topic, relationship ''' + '''such as “friend” or “family”)''')) + parser.add_argument('-f', '--field', nargs=2, action='append', + help='Other optional fields with value (can be repeated)') + + return parser + +def do_add(args, dbname): + 'Add a new entry' + if args.description is None: + args.description = '' + if args.tag is None: + args.tag = '' + del args.command + print('Writing record to %s' % dbname) + with open(dbname, 'a') as db: + db.write('%r\n' % args) + +def do_pl(args, dbname): + 'Print the latest entry' + print('Getting last record from %s' % dbname) + with open(dbname, 'r') as db: + for line in db: pass + record = eval(line) + del record._date + print(str(record)) + +def do_plc(args, dbname): + 'Print the latest entry for each category/tag' + print('Getting latest record for each tag from %s' % dbname) + with open(dbname, 'r') as db: + records = [eval(line) for line in db] + tags = set(record.tag for record in records) + records.reverse() + for record in records: + if record.tag in tags: + del record._date + print(str(record)) + tags.discard(record.tag) + if not tags: break + +def do_pa(args, dbname): + 'Print all entries sorted by a date' + print('Getting all records by date from %s' % dbname) + with open(dbname, 'r') as db: + records = [eval(line) for line in db] + for record in records: + del record._date + print(str(record)) + +def test(): + import time + parser = parse_args() + for cmdline in [ + """-d Book -f title 'Windy places' -f type hardback --tag DISCOUNT add""", + """-d Book -f title 'RC spammers' -f type paperback -t DISCOUNT add""", + """-d Book -f title 'Splat it' -f type hardback -f special 'first edition' -t PREMIUM add""", + """pl""", + """plc""", + ]: + args = parser.parse_args(shlex.split(cmdline)) + now = datetime.datetime.utcnow() + args._date = now.isoformat() + do_command[args.command](args, dbname) + time.sleep(0.5) + + + +do_command = dict(add=do_add, pl=do_pl, plc=do_plc, pa=do_pa) +dbname = '_simple_db_db.py' + + +if __name__ == '__main__': + if 0: + test() + else: + parser = parse_args() + args = parser.parse_args() + now = datetime.datetime.utcnow() + args._date = now.isoformat() + do_command[args.command](args, dbname) diff --git a/Task/Simple-database/Ruby/simple-database.rb b/Task/Simple-database/Ruby/simple-database.rb new file mode 100644 index 0000000000..3d4496bae9 --- /dev/null +++ b/Task/Simple-database/Ruby/simple-database.rb @@ -0,0 +1,187 @@ +require 'date' +require 'json' +require 'securerandom' + +class SimpleDatabase + def initialize(dbname, *fields) + @dbname = dbname + @filename = @dbname + ".dat" + @fields = fields + @maxl = @fields.collect {|f| f.length}.max + @data = { + 'fields' => fields, + 'items' => {}, + 'history' => [], + 'tags' => {}, + } + end + attr_reader :dbname, :fields + + def self.open(dbname) + db = new(dbname) + db.read + db + end + + def read() + if not File.exists?(@filename) + raise ArgumentError, "Database #@dbname has not been created" + end + @data = JSON.parse(File.read(@filename)) + @fields = @data['fields'] + @maxl = @fields.collect {|f| f.length}.max + end + + def write() + File.open(@filename, 'w') {|f| f.write(JSON.generate(@data))} + end + + def add(*values) + id = SecureRandom.uuid + @data['items'][id] = Hash[ @fields.zip(values) ] + @data['history'] << [Time.now.to_f, id] + id + end + + def tag(id, *tags) + tags.each do |tag| + if @data['tags'][tag].nil? + @data['tags'][tag] = [id] + else + @data['tags'][tag] << id + end + end + id + end + + def latest + @data['history'].sort_by {|val| val[0]}.last.last + end + + def get_item(id) + @data['items'][id] + end + + def tags() + @data['tags'].keys.sort + end + + def ids_for_tag(tag) + @data['tags'][tag] + end + + def tags_for_id(id) + @data['tags'].keys.inject([]) do |tags, tag| + tags << tag if @data['tags'][tag].include?(id) + tags + end + end + + def display(id) + item = get_item(id) + fmt = "%#{@maxl}s - %s\n" + puts fmt % ['id', id] + @fields.each {|f| print fmt % [f, item[f]]} + puts fmt % ['tags', tags_for_id(id).join(',')] + added = @data['history'].find {|x| x[1] == id}.first + puts fmt % ['date added', Time.at(added).ctime] + puts "" + end + + def each() + @data['history'].each {|time, id| yield id} + end + + def each_item_with_tag(tag) + @data['tags'][tag].each {|id| yield id} + end +end +def usage() + puts <<END +usage: #{$0} command args ... + +commands: + help + create dbname field ... + fields dbname + add dbname value ... + tag dbname id tag ... + tags dbname + list dbname [tag ...] + latest dbname + latest_by_tag dbname +END +end + +def open_database(args) + dbname = args.shift + begin + SimpleDatabase.open(dbname) + rescue ArgumentError => e + STDERR.puts e.message + exit 1 + end +end + +def process_command_line(command, *args) + case command + when 'help' + usage + + when 'create' + db = SimpleDatabase.new(*args) + db.write + puts "Database #{args[0]} created" + + when 'fields' + db = open_database(args) + puts "Database #{db.dbname} fields:" + puts db.fields.join(',') + + when 'add' + db = open_database(args) + id = db.add(*args) + db.write + puts "Database #{db.dbname} added id #{id}" + + when 'tag' + db = open_database(args) + id = args.shift + db.tag(id, *args) + db.write + db.display(id) + + when 'tags' + db = open_database(args) + puts "Database #{db.dbname} tags:" + puts db.tags.join(',') + + when 'list' + db = open_database(args) + if args.empty? + db.each {|id| db.display(id)} + else + args.each do |tag| + puts "Items tagged #{tag}" + db.each_item_with_tag(tag) {|id| db.display(id)} + end + end + + when 'latest' + db = open_database(args) + db.display(db.latest) + + when 'latest_by_tag' + db = open_database(args) + db.tags.each do |tag| + puts tag + db.display(db.ids_for_tag(tag).last) + end + + else + puts "Error: unknown command '#{command}'" + usage + end +end + +process_command_line *ARGV diff --git a/Task/Simple-database/Run-BASIC/simple-database.run b/Task/Simple-database/Run-BASIC/simple-database.run new file mode 100644 index 0000000000..34bc46304e --- /dev/null +++ b/Task/Simple-database/Run-BASIC/simple-database.run @@ -0,0 +1,100 @@ +sqliteconnect #sql, "f:\client.db" ' Connect to the DB + +' ------------------------------- +' show user options +' ------------------------------- +[sho] +cls ' clear screen +button #acd, "Add a new entry", [add] +button #acd, "Print the latest entry", [last] +button #acd, "Print the latest entry for each category", [lastCat] +button #acd, "Print all entries sorted by a date", [date] +button #ex, "Exit", [exit] +wait + +' ------------------------------------ +' add a new entry (user input screen) +' ------------------------------------ +[add] +cls ' clear the screen +html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 bgcolor=wheat>" +html "<TR align=center BGCOLOR=tan><TD colspan=2>Client Maintenance</TD></TR><TR>" +html "<TD bgcolor=tan align=right>Client Num</TD><TD>" + textbox #clientNum,clientNum$,5 + +html "</TD></TR><TR><TD bgcolor=tan align=right>Name</TD><TD>" + textbox #name,name$,30 + +html "</TD></TR><TR><TD bgcolor=tan align=right>Client Date</TD><TD>" + textbox #clientDate,clientDate$,19 + +html "</TD></TR><TR><TD bgcolor=tan align=right>Category</TD><TD>" + textbox #category,category$,10 + +html "</TD></TR><TR><TR bgcolor=tan><TD colspan=2 ALIGN=CENTER>" + button #acd, "Add", [addIt] + button #ex, "Exit", [sho] +html "</TD></TR></TABLE>" +wait + +' --------------------------------------------- +' Get data from the screen +' --------------------------------------------- +[addIt] +clientNum = #clientNum contents$() +name$ = trim$(#name contents$()) +clientDate$ = trim$(#clientDate contents$()) +category$ = trim$(#category contents$()) +dbVals$ = clientNum;",'";name$;"','";clientDate$;"','";category$;"'" +sql$ = "INSERT into client VALUES ("; dbVals$ ; ")" +#sql execute(sql$) +goto [sho] + +' ------------------------------------ +' Select last entry +' ------------------------------------ +[last] +sql$ = "SELECT *,client.rowid as rowid FROM client ORDER BY rowid desc LIMIT 1" +what$ = "---- Last Entry ----" +goto [shoQuery] + +' ------------------------------------ +' Select by category (Last date only) +' ------------------------------------ +[lastCat] +sql$ = "SELECT * FROM client +WHERE client.clientDate = (SELECT max(c.clientDate) +FROM client as c WHERE c.category = client.category) +ORDER BY category" +what$ = "---- Last Category Sequence ----" +goto [shoQuery] + +' ------------------------------------ +' Select by date +' ------------------------------------ +[date] +sql$ = "SELECT * FROM client ORDER BY clientDate" +what$ = "---- By Date ----" + +[shoQuery] +cls +print what$ +html "<TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0>" +html "<TR align=center bgcolor=wheat><TD>Client<br>Num</TD><TD>Name</TD><TD>Client<br>Date</TD><TD>Category</TD></TR>" ' heading +#sql execute(sql$) +WHILE #sql hasanswer() + #row = #sql #nextrow() + clientNum = #row clientNum() + name$ = #row name$() + clientDate$ = #row clientDate$() + category$ = #row category$() + + html "<TR><TD align=right>";clientNum;"</TD><TD>";name$;"</TD><TD>";clientDate$;"</TD><TD>";category$;"</TD></TR>" +WEND +html "</TABLE>" +button #c, "Continue", [sho] +wait + +' ------ the end ------- +[exit] +end diff --git a/Task/Simple-database/Tcl/simple-database-1.tcl b/Task/Simple-database/Tcl/simple-database-1.tcl new file mode 100644 index 0000000000..744e449080 --- /dev/null +++ b/Task/Simple-database/Tcl/simple-database-1.tcl @@ -0,0 +1,101 @@ +#!/usr/bin/env tclsh8.6 +package require Tcl 8.6 +namespace eval udb { + variable db {} + + proc Load {filename} { + variable db + if {[catch {set f [open $filename]}]} { + set db {} + return + } + set db [read $f] + close $f + } + proc Store {filename} { + variable db + if {[catch {set f [open $filename w]}]} return + dict for {nm inf} $db { + puts $f [list $nm $inf] + } + close $f + } + + proc add {title category {date "now"} args} { + variable db + if {$date eq "now"} { + set date [clock seconds] + } else { + set date [clock scan $date] + } + dict set db $title [list $category $date $args] + return + } + proc Rec {nm cat date xtra} { + dict create description $nm category $cat date [clock format $date] \ + {*}$xtra _names [dict keys $xtra] + } + proc latest {{category ""}} { + variable db + if {$category eq ""} { + set d [lsort -stride 2 -index {1 1} -integer -decreasing $db] + dict for {nm inf} $d break + return [list [Rec $nm {*}$inf]] + } + set latestbycat {} + dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] { + dict set latestbycat [lindex $inf 0] [list $nm {*}$inf] + } + return [list [Rec {*}[dict get $latestbycat $category]]] + } + proc latestpercategory {} { + variable db + set latestbycat {} + dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] { + dict set latestbycat [lindex $inf 0] [list $nm {*}$inf] + } + set result {} + dict for {- inf} $latestbycat { + lappend result [Rec {*}$inf] + } + return $result + } + proc bydate {} { + variable db + set result {} + dict for {nm inf} [lsort -stride 2 -index {1 1} -integer $db] { + lappend result [Rec $nm {*}$inf] + } + return $result + } + + namespace export add latest latestpercategory bydate + namespace ensemble create +} + +if {$argc < 2} { + puts stderr "wrong # args: should be \"$argv0 dbfile subcommand ?args...?\"" + exit 1 +} +udb::Load [lindex $argv 0] +set separator "" +if {[catch {udb {*}[lrange $argv 1 end]} msg]} { + puts stderr [regsub "\"udb " $msg "\"$argv0 dbfile "] + exit 1 +} +foreach row $msg { + puts -nonewline $separator + apply {row { + dict with row { + puts "Title: $description" + puts "Category: $category" + puts "Date: $date" + foreach v $_names { + puts "${v}: [dict get $row $v]" + } + } + }} $row + set separator [string repeat - 70]\n +} + +udb::Store [lindex $argv 0] diff --git a/Task/Simple-database/Tcl/simple-database-2.tcl b/Task/Simple-database/Tcl/simple-database-2.tcl new file mode 100644 index 0000000000..a9f43cfca9 --- /dev/null +++ b/Task/Simple-database/Tcl/simple-database-2.tcl @@ -0,0 +1,91 @@ +bash$ udb.tcl db +wrong # args: should be "udb.tcl dbfile subcommand ?args...?" +bash$ udb.tcl db ? +unknown or ambiguous subcommand "?": must be add, bydate, latest, or latestpercategory +bash$ udb.tcl db add +wrong # args: should be "udb.tcl dbfile add title category ?date? ?arg ...?" +bash$ udb.tcl db add "Title 1" foo +bash$ udb.tcl db add "Title 2" foo +bash$ udb.tcl db add "Title 3" bar +bash$ udb.tcl db bydate +Title: Title 1 +Category: foo +Date: Tue Nov 15 18:11:58 GMT 2011 +---------------------------------------------------------------------- +Title: Title 2 +Category: foo +Date: Tue Nov 15 18:12:01 GMT 2011 +---------------------------------------------------------------------- +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 +bash$ udb.tcl db latest +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 +bash$ udb.tcl db latest foo +Title: Title 2 +Category: foo +Date: Tue Nov 15 18:12:01 GMT 2011 +bash$ udb.tcl db latest bar +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 +bash$ udb.tcl db latestpercategory +Title: Title 2 +Category: foo +Date: Tue Nov 15 18:12:01 GMT 2011 +---------------------------------------------------------------------- +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 +bash$ udb.tcl db add "Title 4" bar "12:00 Monday last week" +bash$ udb.tcl db bydate +Title: Title 4 +Category: bar +Date: Mon Nov 14 12:00:00 GMT 2011 +---------------------------------------------------------------------- +Title: Title 1 +Category: foo +Date: Tue Nov 15 18:11:58 GMT 2011 +---------------------------------------------------------------------- +Title: Title 2 +Category: foo +Date: Tue Nov 15 18:12:01 GMT 2011 +---------------------------------------------------------------------- +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 +bash$ cat db +{Title 1} {foo 1321380718 {}} +{Title 2} {foo 1321380721 {}} +{Title 3} {bar 1321380727 {}} +{Title 4} {bar 1321272000 {}} +bash$ udb.tcl db add "Title 5" foo "12:00 Monday last week" Comment 'Wholly excellent!' +bash$ cat db +{Title 1} {foo 1321380718 {}} +{Title 2} {foo 1321380721 {}} +{Title 3} {bar 1321380727 {}} +{Title 4} {bar 1321272000 {}} +{Title 5} {foo 1321272000 {Comment {Wholly excellent!}}} +bash$ udb.tcl db bydate +Title: Title 4 +Category: bar +Date: Mon Nov 14 12:00:00 GMT 2011 +---------------------------------------------------------------------- +Title: Title 5 +Category: foo +Date: Mon Nov 14 12:00:00 GMT 2011 +Comment: Wholly excellent! +---------------------------------------------------------------------- +Title: Title 1 +Category: foo +Date: Tue Nov 15 18:11:58 GMT 2011 +---------------------------------------------------------------------- +Title: Title 2 +Category: foo +Date: Tue Nov 15 18:12:01 GMT 2011 +---------------------------------------------------------------------- +Title: Title 3 +Category: bar +Date: Tue Nov 15 18:12:07 GMT 2011 diff --git a/Task/Simple-database/UNIX-Shell/simple-database-1.sh b/Task/Simple-database/UNIX-Shell/simple-database-1.sh new file mode 100644 index 0000000000..34e921b77b --- /dev/null +++ b/Task/Simple-database/UNIX-Shell/simple-database-1.sh @@ -0,0 +1,96 @@ +#!/bin/sh + +db_create() { + mkdir ./"$1" && mkdir "./$1/.tag" && echo "Create DB \`$1'" +} + +db_delete() { + rm -r ./"$1" && echo "Delete DB \`$1'" +} + +db_show() { + if [ -z "$2" ]; then show_help; fi + for x in "./$1/$2/"*; do + echo "$x:" | sed "s/.*\///" + cat "$x" | sed "s/^/ /" + echo + done + + printf "Tags: " + ls "./$1/$2/.tag" +} + +db_tag() { + local db="$1" item="$2" + shift + shift + for tag in $@; do + mkdir "./$db/.tag/$tag" + ln -s "$PWD/$db/$item" "./$db/.tag/$tag/" + touch "./$db/$item/.tag/$tag" + done +} + +show_help() { + echo "Usage: $0 command [args]" + echo "Commands:" + cat $0 | grep ") ##" | grep -v grep | sed 's/) ## /:\t/' + exit +} + +if [ -z "$1" ]; then show_help; fi + +action=$1 it=database +shift +case $action in + create) ## db -- create $it + db_create "$@" ;; + + drop) ## db -- delete $it + db_delete "$@" ;; + + add) ## db item -- add new item to $it + mkdir -p "./$1/$2/.tag" && touch "./$1/$2/Description" ;; + + rem) ## db item -- delete item from $it + rm -r "./$1/$2" + rm "./$1/.tag/"*"/$2" + ;; + + show) ## db item -- show item + db_show "$@" ;; + + newtag) ## db new-tag-name -- create new tag name + mkdir "./$1/.tag/$2" ;; + + prop) ## db item property-name property-content -- add property to item + echo "$4" > "./$1/$2/$3" ;; + + tag) ## db item tag [more-tags...] -- mark item with tags + db_tag "$@" ;; + + last) ## db -- show latest item + ls "$1" --sort=time | tail -n 1 + ;; + + list) ## db -- list all items + ls "$1" -1 --sort=time + ;; + + last-all) ## db -- list items in each category + for x in "$1/.tag/"*; do + echo "$x" | sed 's/.*\//Tag: /' + printf " " + ls "$x" --sort=time | tail -n 1 + echo + done + ;; + + help) ## this message + show_help + ;; + + *) echo Bad DB command: $1 + show_help + ;; +esac diff --git a/Task/Simple-database/UNIX-Shell/simple-database-2.sh b/Task/Simple-database/UNIX-Shell/simple-database-2.sh new file mode 100644 index 0000000000..3766d20736 --- /dev/null +++ b/Task/Simple-database/UNIX-Shell/simple-database-2.sh @@ -0,0 +1,37 @@ +$ sdb create CDs +Create DB `CDs' +$ sdb add CDs Bookends +$ sdb prop CDs Bookends artists "Simon & Garfunkel" +$ sdb add CDs "Ode to joy" +$ sdb prop CDs "Ode to joy" artist "Beethoven" +$ sdb tag CDs Bookends rock folk # I'm not sure about this +$ sdb tag CDs "Ode to joy" classical +$ sdb show CDs Bookends +Description: + +artists: + Simon & Garfunkel + +Tags: folk rock +$ sdb prop CDs "Ode to joy" Description "Sym. No. 9" +$ sdb show CDs "Ode to joy" +Description: + Sym. No. 9 + +artist: + Beethoven + +Tags: classical +$ sdb last-all CDs +Tag: classical + Ode to joy + +Tag: folk + Bookends + +Tag: rock + Bookends + +$ sdb drop CDs +Delete DB `CDs' +$ diff --git a/Task/Simple-windowed-application/0DESCRIPTION b/Task/Simple-windowed-application/0DESCRIPTION new file mode 100644 index 0000000000..892a2d2d13 --- /dev/null +++ b/Task/Simple-windowed-application/0DESCRIPTION @@ -0,0 +1 @@ +This task asks to create a window with a label that says "There have been no clicks yet" and a button that says "click me". Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked. diff --git a/Task/Simple-windowed-application/1META.yaml b/Task/Simple-windowed-application/1META.yaml new file mode 100644 index 0000000000..04942ee47c --- /dev/null +++ b/Task/Simple-windowed-application/1META.yaml @@ -0,0 +1,6 @@ +--- +category: +- Basic language learning +note: GUI +requires: +- Graphics diff --git a/Task/Simple-windowed-application/Ada/simple-windowed-application.ada b/Task/Simple-windowed-application/Ada/simple-windowed-application.ada new file mode 100644 index 0000000000..4ac9227665 --- /dev/null +++ b/Task/Simple-windowed-application/Ada/simple-windowed-application.ada @@ -0,0 +1,67 @@ +with Gdk.Event; use Gdk.Event; +with Gtk.Button; use Gtk.Button; +with Gtk.Label; use Gtk.Label; +with Gtk.Window; use Gtk.Window; +with Gtk.Widget; use Gtk.Widget; +with Gtk.Table; use Gtk.Table; + +with Gtk.Handlers; +with Gtk.Main; + +procedure Simple_Windowed_Application is + Window : Gtk_Window; + Grid : Gtk_Table; + Button : Gtk_Button; + Label : Gtk_Label; + Count : Natural := 0; + + package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); + package Return_Handlers is + new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean); + + function Delete_Event (Widget : access Gtk_Widget_Record'Class) + return Boolean is + begin + return False; + end Delete_Event; + + procedure Destroy (Widget : access Gtk_Widget_Record'Class) is + begin + Gtk.Main.Main_Quit; + end Destroy; + + procedure Clicked (Widget : access Gtk_Widget_Record'Class) is + begin + Count := Count + 1; + Set_Text (Label, "The button clicks:" & Natural'Image (Count)); + end Clicked; + +begin + Gtk.Main.Init; + Gtk.Window.Gtk_New (Window); + Gtk_New (Grid, 1, 2, False); + Add (Window, Grid); + Gtk_New (Label, "There have been no clicks yet"); + Attach (Grid, Label, 0, 1, 0, 1); + Gtk_New (Button, "Click me"); + Attach (Grid, Button, 0, 1, 1, 2); + Return_Handlers.Connect + ( Window, + "delete_event", + Return_Handlers.To_Marshaller (Delete_Event'Access) + ); + Handlers.Connect + ( Window, + "destroy", + Handlers.To_Marshaller (Destroy'Access) + ); + Handlers.Connect + ( Button, + "clicked", + Handlers.To_Marshaller (Clicked'Access) + ); + Show_All (Grid); + Show (Window); + + Gtk.Main.Main; +end Simple_Windowed_Application; diff --git a/Task/Simple-windowed-application/AutoHotkey/simple-windowed-application.ahk b/Task/Simple-windowed-application/AutoHotkey/simple-windowed-application.ahk new file mode 100644 index 0000000000..d57618be58 --- /dev/null +++ b/Task/Simple-windowed-application/AutoHotkey/simple-windowed-application.ahk @@ -0,0 +1,14 @@ +; Create simple windowed application + Gui, Add, Text, vTextCtl, There have been no clicks yet ; add a Text-Control + Gui, Add, Button, gButtonClick xm, click me ; add a Button-Control + Gui, Show, , Simple windowed application ; show the Window +Return ; end of the auto-execute section + +ButtonClick: ; the subroutine executed each time the Button-Control is clicked + count++ ; increment the click-counting var + GuiControl, , TextCtl, %count% ; update the Text-Control with the click-counting var +Return ; end of the subroutine + +GuiClose: ; the subroutine executed when the Window is closed + ExitApp ; exit this process +Return diff --git a/Task/Simple-windowed-application/BBC-BASIC/simple-windowed-application.bbc b/Task/Simple-windowed-application/BBC-BASIC/simple-windowed-application.bbc new file mode 100644 index 0000000000..de9a6ff761 --- /dev/null +++ b/Task/Simple-windowed-application/BBC-BASIC/simple-windowed-application.bbc @@ -0,0 +1,18 @@ + INSTALL @lib$+"WINLIB2" + INSTALL @lib$+"WINLIB5" + + window% = FN_newdialog("Rosetta Code", 100, 100, 120, 52, 8, 1000) + PROC_static(window%, "There have been no clicks yet", 100, 10, 10, 100, 14, 0) + PROC_pushbutton(window%, "Click me", FN_setproc(PROCclick), 40, 30, 40, 16, 0) + PROC_showdialog(window%) + + REPEAT + WAIT 1 + UNTIL !window% = 0 + QUIT + + DEF PROCclick + PRIVATE clicks% + clicks% += 1 + SYS "SetDlgItemText", !window%, 100, "Number of clicks = " + STR$(clicks%) + ENDPROC diff --git a/Task/Simple-windowed-application/C++/simple-windowed-application-1.cpp b/Task/Simple-windowed-application/C++/simple-windowed-application-1.cpp new file mode 100644 index 0000000000..db49990198 --- /dev/null +++ b/Task/Simple-windowed-application/C++/simple-windowed-application-1.cpp @@ -0,0 +1,21 @@ +#ifndef CLICKCOUNTER_H +#define CLICKCOUNTER_H + +#include <QWidget> +class QLabel ; +class QPushButton ; +class QVBoxLayout ; + +class Counter : public QWidget { + Q_OBJECT +public : + Counter( QWidget * parent = 0 ) ; +private : + int number ; + QLabel *countLabel ; + QPushButton *clicker ; + QVBoxLayout *myLayout ; +private slots : + void countClicks( ) ; +} ; +#endif diff --git a/Task/Simple-windowed-application/C++/simple-windowed-application-2.cpp b/Task/Simple-windowed-application/C++/simple-windowed-application-2.cpp new file mode 100644 index 0000000000..30a0df9e31 --- /dev/null +++ b/Task/Simple-windowed-application/C++/simple-windowed-application-2.cpp @@ -0,0 +1,20 @@ +#include <QPushButton> +#include <QLabel> +#include <QVBoxLayout> +#include "clickcounter.h" + +Counter::Counter( QWidget * parent ) : QWidget( parent ) { + number = 0 ; + countLabel = new QLabel( "There have been no clicks yet!" ) ; + clicker = new QPushButton( "click me" ) ; + connect ( clicker , SIGNAL( clicked( ) ) , this , SLOT( countClicks( ) ) ) ; + myLayout = new QVBoxLayout ; + myLayout->addWidget( countLabel ) ; + myLayout->addWidget( clicker ) ; + setLayout( myLayout ) ; +} + +void Counter::countClicks( ) { + number++ ; + countLabel->setText( QString( "The button has been clicked %1 times!").arg( number ) ) ; +} diff --git a/Task/Simple-windowed-application/C++/simple-windowed-application-3.cpp b/Task/Simple-windowed-application/C++/simple-windowed-application-3.cpp new file mode 100644 index 0000000000..9c8bb43fd2 --- /dev/null +++ b/Task/Simple-windowed-application/C++/simple-windowed-application-3.cpp @@ -0,0 +1,9 @@ +#include <QApplication> +#include "clickcounter.h" + +int main( int argc , char *argv[ ] ) { + QApplication app( argc , argv ) ; + Counter counter ; + counter.show( ) ; + return app.exec( ) ; +} diff --git a/Task/Simple-windowed-application/C/simple-windowed-application.c b/Task/Simple-windowed-application/C/simple-windowed-application.c new file mode 100644 index 0000000000..b699af8279 --- /dev/null +++ b/Task/Simple-windowed-application/C/simple-windowed-application.c @@ -0,0 +1,40 @@ +#include <stdio.h> +#include <gtk/gtk.h> + +const gchar *clickme = "Click Me"; +guint counter = 0; + +#define MAXLEN 64 +void clickedme(GtkButton *o, gpointer d) +{ + GtkLabel *l = GTK_LABEL(d); + char nt[MAXLEN]; + + counter++; + snprintf(nt, MAXLEN, "You clicked me %d times", counter); + gtk_label_set_text(l, nt); +} + +int main(int argc, char **argv) +{ + GtkWindow *win; + GtkButton *button; + GtkLabel *label; + GtkVBox *vbox; + + gtk_init(&argc, &argv); + win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(win, clickme); + button = (GtkButton*)gtk_button_new_with_label(clickme); + label = (GtkLabel*)gtk_label_new("There have been no clicks yet"); + gtk_label_set_single_line_mode(label, TRUE); + vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1); + gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label)); + gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button)); + gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); + g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); + g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label); + gtk_widget_show_all(GTK_WIDGET(win)); + gtk_main(); + return 0; +} diff --git a/Task/Simple-windowed-application/Clojure/simple-windowed-application.clj b/Task/Simple-windowed-application/Clojure/simple-windowed-application.clj new file mode 100644 index 0000000000..535f845b42 --- /dev/null +++ b/Task/Simple-windowed-application/Clojure/simple-windowed-application.clj @@ -0,0 +1,24 @@ +(ns counter-window + (:import (javax.swing JFrame JLabel JButton))) + +(defmacro on-action [component event & body] + `(. ~component addActionListener + (proxy [java.awt.event.ActionListener] [] + (actionPerformed [~event] ~@body)))) + +(defn counter-app [] + (let [counter (atom 0) + label (JLabel. "There have been no clicks yet") + button (doto (JButton. "Click me!") + (on-action evnt + (.setText label + (str "Counter: " (swap! counter inc))))) + panel (doto (JPanel.) + (.setOpaque true) + (.add label) + (.add button))] + (doto (JFrame. "Counter App") + (.setContentPane panel) + (.setSize 300 100) + (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) + (.setVisible true)))) diff --git a/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-1.lisp b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-1.lisp new file mode 100644 index 0000000000..a0b801d24b --- /dev/null +++ b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-1.lisp @@ -0,0 +1,3 @@ +(defpackage #:rcswa + (:use #:clim #:clim-lisp)) +(in-package #:rcswa) diff --git a/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-2.lisp b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-2.lisp new file mode 100644 index 0000000000..826e5a993e --- /dev/null +++ b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-2.lisp @@ -0,0 +1,19 @@ +(define-application-frame simple-windowed-application () + ((clicks :initform 0 + :accessor clicks-of)) + (:menu-bar t) + (:pane + (make-pane 'application-pane + :width '(40 :character) + :height '(3 :character) + :display-time :command-loop + :display-function + (lambda (pane stream) + (declare (ignore pane)) + (format stream "~[There have been no clicks yet.~ + ~:;~:*There ~[have~;has~:;have~]~:* been ~R click~:P.~]" + (clicks-of *application-frame*)))))) + +(define-simple-windowed-application-command (com-click-me :menu t) + () + (incf (clicks-of *application-frame*))) diff --git a/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-3.lisp b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-3.lisp new file mode 100644 index 0000000000..03c4faf9a6 --- /dev/null +++ b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-3.lisp @@ -0,0 +1,27 @@ +(define-application-frame simple-windowed-application () + ((clicks :initform 0 + :accessor clicks-of)) + (:panes + (the-label :application + :width '(40 :character) + :height '(3 :character) + :display-time t + :display-function + (lambda (pane stream) + (declare (ignore pane)) + (format stream "~[There have been no clicks yet.~ + ~:;~:*There ~[have~;has~:;have~]~:* been ~R click~:P.~]" + (clicks-of *application-frame*)))) + (the-button :push-button + :label "Click Me" + :activate-callback + (lambda (button) + (declare (ignore button)) + (incf (clicks-of *application-frame*)) + (redisplay-frame-pane *application-frame* + (find-pane-named *application-frame* 'the-label) + :force-p t)))) + (:layouts (default + (vertically (:equalize-width nil :align-x :center) + the-label + (spacing (:thickness 10) the-button))))) diff --git a/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-4.lisp b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-4.lisp new file mode 100644 index 0000000000..b9807ae3d8 --- /dev/null +++ b/Task/Simple-windowed-application/Common-Lisp/simple-windowed-application-4.lisp @@ -0,0 +1 @@ +(run-frame-top-level (make-application-frame 'simple-windowed-application)) diff --git a/Task/Simple-windowed-application/D/simple-windowed-application-1.d b/Task/Simple-windowed-application/D/simple-windowed-application-1.d new file mode 100644 index 0000000000..30ac6712ee --- /dev/null +++ b/Task/Simple-windowed-application/D/simple-windowed-application-1.d @@ -0,0 +1,31 @@ +module winapp ; +import dfl.all ; +import std.string ; + +class MainForm: Form { + Label label ; + Button button ; + this() { + width = 240 ; + with(label = new Label) { + text = "There have been no clicks yet" ; + dock = DockStyle.TOP ; + parent = this ; + } + with(button = new Button) { + dock = DockStyle.BOTTOM ; + text = "Click Me" ; + parent = this ; + click ~= &onClickButton ; + } + height = label.height + button.height + 36 ; + } + private void onClickButton(Object sender, EventArgs ea) { + static int count = 0 ; + label.text = "You had been clicked me " ~ std.string.toString(++count) ~ " times." ; + } +} + +void main() { + Application.run(new MainForm); +} diff --git a/Task/Simple-windowed-application/D/simple-windowed-application-2.d b/Task/Simple-windowed-application/D/simple-windowed-application-2.d new file mode 100644 index 0000000000..1f3f825e36 --- /dev/null +++ b/Task/Simple-windowed-application/D/simple-windowed-application-2.d @@ -0,0 +1,36 @@ +module SimpleWindow; +import tango.text.convert.Integer; +import tango.core.Thread; // For Thread.yield + +import xf.hybrid.Hybrid; //For widgets and general API +import xf.hybrid.backend.GL; // For OpenGL Renderer + +void main() { + //load config file + scope cfg = loadHybridConfig(`./SimpleWindow.cfg`); + scope renderer = new Renderer; + auto counter = 0; + + bool programRunning = true; + while (programRunning) { + // Tell Hybrid what config to use + gui.begin(cfg); + // Exit program if user clicks the Close button + if (gui().getProperty!(bool)("main.frame.closeClicked")) { + programRunning = false; + } + // Update text on the label + if (counter != 0) + Label("main.label").text = toString(counter); + // Increment counter if the button has been clicked + if (Button("main.button").clicked) { + counter++; + } + // Finalize. Prepare to render + gui.end(); + // Render window using OpenGL Renderer + gui.render(renderer); + + Thread.yield(); + } +} diff --git a/Task/Simple-windowed-application/Delphi/simple-windowed-application.delphi b/Task/Simple-windowed-application/Delphi/simple-windowed-application.delphi new file mode 100644 index 0000000000..d4feca6813 --- /dev/null +++ b/Task/Simple-windowed-application/Delphi/simple-windowed-application.delphi @@ -0,0 +1,87 @@ +-- begin file -- + + Program SingleWinApp ; + + // This is the equivalent of the C #include + Uses Forms, Windows, Messages, Classes, Graphics, Controls, StdCtrls ; + + + type + + // The only reason for this declaration is to allow the connection of the + // on click method to the forms button object. This class declaration adds + // a procedure. + + TMainForm class(tform) + Procedure AddClicks(sender : tObject); + end; + + + // Use these globals. + var + + MainForm : tForm ; + aLabel : tLabel ; + aButton : tButton ; + i : integer = 0 ; + + + // This is the Method call that we connect to the button object + // to start counting the clicks. + Procedure tMainForm.AddClicks(sender :tObject) + begin + inc(i); + aLabel.Caption := IntToStr(i) + ' Clicks since startup' ; + end; + + + Begin + // Do all the behind the scenes stuff that sets up the Windows environment + Application.Initialize ; + + // Create the form + + // Forms can either be created with an owner, like I have done here, or with + // the owner set to Nil. In pascal (all versions of Borland) '''NIL''' is a + // reserved, (the equivalent of '''NULL''' in Ansi C) word and un-sets any pointer + // variable. Setting the owner to the application object will ensure that the form is + // freed by the application object when the application shuts down. If I had set + // the owner to NIL then i would have had to make sure I freed the form explicitly + // or it would have been orphaned, thus creating a memory leak. + + // I must direct your attention to the CreateNew constructor. This is + // a non standard usage. Normally the constructor Create() will call this + // as part of the initialization routine for the form. Normally as you drop + // various components on a form in deign mode, a DFM file is created with + // all the various initial states of the controls. This bypasses the + // DFM file altogether although all components AND the form are created + // with default values. (see the Delphi help file). + + MainForm := tMainForm.CreateNew(Application); + MainForm.Parent := Application ; + MainForm.Position := poScreenCenter ; + MainForm.Caption := 'Single Window Application' ; + + // Create the Label, set its owner as MaiaForm + aLabel := tLabel.Create(mainForm); + aLabel.Parent := MainForm; + aLabel.Caption := IntToStr(i) + ' Clicks since startup' ; + aLabel.Left := 20 ; + aLabel.Top := MainForm.ClientRect.Bottom div 2 ; + + // Create the button, set its owner to MainForm + aButton := tButton.Create(MainForm); + aButton.Parent := MainForm ; + aButton.Caption := 'Click Me!'; + aButton.Left := (MainForm.ClientRect.Right div 2)-(aButton.Width div 2 ); + aButton.Top := MainForm.ClientRect.Bottom - aButton.Height - 10 ; + aButton.OnClick := AddClicks ; + + // Show the main form, Modaly. The ONLY reason to do this is because in this + // demonstration if you only call the SHOW method, the form will appear and + // disappear in a split second. + MainForm.ShowModal ; + + Application.Run ; + + end. // Program diff --git a/Task/Simple-windowed-application/E/simple-windowed-application.e b/Task/Simple-windowed-application/E/simple-windowed-application.e new file mode 100644 index 0000000000..3de6c1a4b8 --- /dev/null +++ b/Task/Simple-windowed-application/E/simple-windowed-application.e @@ -0,0 +1,16 @@ +when (currentVat.morphInto("awt")) -> { + var clicks := 0 + def w := <swing:makeJFrame>("Rosetta Code 'Simple Windowed Application'") + w.setContentPane(JPanel` + ${def l := <swing:makeJLabel>("There have been no clicks yet.")} $\ + ${def b := <swing:makeJButton>("Click Me")} + `) + b.addActionListener(def _ { + to actionPerformed(_) { + clicks += 1 + l.setText(`Number of clicks: $clicks`) + } + }) + w.pack() + w.show() +} diff --git a/Task/Simple-windowed-application/Euphoria/simple-windowed-application.euphoria b/Task/Simple-windowed-application/Euphoria/simple-windowed-application.euphoria new file mode 100644 index 0000000000..acf3c7f4f6 --- /dev/null +++ b/Task/Simple-windowed-application/Euphoria/simple-windowed-application.euphoria @@ -0,0 +1,19 @@ +include EuWinGUI.ew + +Window("EuWinGUI - Simple windowed application",100,100,360,100) +constant Button1 = Control(Button,"Click me",250,20,80,25) +constant Label1 = Control(Label,"There have been no clicks yet",10,25,200,18) + +integer clicks +clicks = 0 + +-- Event loop +while 1 do + WaitEvent() + if EventOwner = Button1 and Event = Click then + clicks += 1 + SetText(Label1,sprintf("You clicked me %d times",clicks)) + end if +end while + +CloseApp(0) diff --git a/Task/Simple-windowed-application/Fantom/simple-windowed-application.fantom b/Task/Simple-windowed-application/Fantom/simple-windowed-application.fantom new file mode 100644 index 0000000000..340b46891a --- /dev/null +++ b/Task/Simple-windowed-application/Fantom/simple-windowed-application.fantom @@ -0,0 +1,29 @@ +using fwt +using gfx + +class SimpleApplication +{ + public static Void main () + { + Window + { + title = "Simple Window Application" + size = Size(350, 50) + clicked := 0 + label := Label + { + text = "There have been no clicks yet" + } + Button + { + text = "Click me" + onAction.add |Event e| + { + clicked += 1 + label.text = "There have been $clicked clicks" + } + }, + label, + }.open + } +} diff --git a/Task/Simple-windowed-application/Forth/simple-windowed-application-1.fth b/Task/Simple-windowed-application/Forth/simple-windowed-application-1.fth new file mode 100644 index 0000000000..b9712b8711 --- /dev/null +++ b/Task/Simple-windowed-application/Forth/simple-windowed-application-1.fth @@ -0,0 +1,11 @@ +also minos +text-label ptr click-label +Variable click# click# off +: click-win ( -- ) screen self window new window with + X" There have been no clicks yet" text-label new + dup F bind click-label + ^ S[ 1 click# +! + click# @ 0 <# #S s" Number of clicks: " holds #> + click-label assign ]S X" Click me" button new + &2 vabox new panel s" Clicks" assign show endwith ; +click-win diff --git a/Task/Simple-windowed-application/Forth/simple-windowed-application-2.fth b/Task/Simple-windowed-application/Forth/simple-windowed-application-2.fth new file mode 100644 index 0000000000..a0e5ec9464 --- /dev/null +++ b/Task/Simple-windowed-application/Forth/simple-windowed-application-2.fth @@ -0,0 +1,36 @@ +#! xbigforth +\ automatic generated code +\ do not edit + +also editor also minos also forth + +component class ccount +public: + early widget + early open + early dialog + early open-app + text-label ptr click# + ( [varstart] ) cell var clicks ( [varend] ) +how: + : open new DF[ 0 ]DF s" Click counter" open-component ; + : dialog new DF[ 0 ]DF s" Click counter" open-dialog ; + : open-app new DF[ 0 ]DF s" Click counter" open-application ; +class; + +ccount implements + ( [methodstart] ) ( [methodend] ) + : widget ( [dumpstart] ) + X" There have been no clicks yet" text-label new ^^bind click# + ^^ S[ 1 clicks +! +clicks @ 0 <# #S s" Number of clicks: " holds #> click# assign ]S ( MINOS ) X" Click me" button new + &2 vabox new panel + ( [dumpend] ) ; + : init ^>^^ assign widget 1 :: init ; +class; + +: main + ccount open-app + $1 0 ?DO stop LOOP bye ; +script? [IF] main [THEN] +previous previous previous diff --git a/Task/Simple-windowed-application/Go/simple-windowed-application.go b/Task/Simple-windowed-application/Go/simple-windowed-application.go new file mode 100644 index 0000000000..d5d5555714 --- /dev/null +++ b/Task/Simple-windowed-application/Go/simple-windowed-application.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "github.com/mattn/go-gtk/gtk" +) + +func main() { + gtk.Init(nil) + window := gtk.Window(gtk.GTK_WINDOW_TOPLEVEL) + window.SetTitle("Click me") + label := gtk.Label("There have been no clicks yet") + var clicks int + button := gtk.ButtonWithLabel("click me") + button.Clicked(func() { + clicks++ + if clicks == 1 { + label.SetLabel("Button clicked 1 time") + } else { + label.SetLabel(fmt.Sprintf("Button clicked %d times", + clicks)) + } + }) + vbox := gtk.VBox(false, 1) + vbox.Add(label) + vbox.Add(button) + window.Add(vbox) + window.Connect("destroy", func() { + gtk.MainQuit() + }) + window.ShowAll() + gtk.Main() +} diff --git a/Task/Simple-windowed-application/Groovy/simple-windowed-application-1.groovy b/Task/Simple-windowed-application/Groovy/simple-windowed-application-1.groovy new file mode 100644 index 0000000000..58a360630f --- /dev/null +++ b/Task/Simple-windowed-application/Groovy/simple-windowed-application-1.groovy @@ -0,0 +1,11 @@ +import groovy.swing.SwingBuilder + +count = 0 +new SwingBuilder().edt { + frame(title:'Click frame', pack: true, show: true) { + vbox { + countLabel = label("There have been no clicks yet.") + button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."}) + } + } +} diff --git a/Task/Simple-windowed-application/Groovy/simple-windowed-application-2.groovy b/Task/Simple-windowed-application/Groovy/simple-windowed-application-2.groovy new file mode 100644 index 0000000000..555536891a --- /dev/null +++ b/Task/Simple-windowed-application/Groovy/simple-windowed-application-2.groovy @@ -0,0 +1,16 @@ +import groovy.swing.SwingBuilder +import groovy.beans.Bindable + +@Bindable class Model { + Integer count = 0 +} +model = new Model() +new SwingBuilder().edt { + frame(title:'Click frame', pack: true, show: true) { + vbox { + label(text: bind(source: model, sourceProperty: 'count', + converter: { v -> !v ? "There have been no clicks yet." : "Clicked ${v} time(s)."})) + button('Click Me', actionPerformed: {model.count++}) + } + } +} diff --git a/Task/Simple-windowed-application/Haskell/simple-windowed-application.hs b/Task/Simple-windowed-application/Haskell/simple-windowed-application.hs new file mode 100644 index 0000000000..e998a82223 --- /dev/null +++ b/Task/Simple-windowed-application/Haskell/simple-windowed-application.hs @@ -0,0 +1,30 @@ +import Graphics.UI.Gtk +import Data.IORef + +main :: IO () +main = do + initGUI + window <- windowNew + window `onDestroy` mainQuit + windowSetTitle window "Simple Windowed App" + set window [ containerBorderWidth := 10 ] + + hbox <- hBoxNew True 5 + + set window [ containerChild := hbox ] + + lab <- labelNew (Just "There have been no clicks yet") + button <- buttonNewWithLabel "Click me" + set hbox [ containerChild := lab ] + set hbox [ containerChild := button ] + + m <- newIORef 0 + + onClicked button $ do + v <- readIORef m + writeIORef m (v+1) + set lab [ labelText := "There have been " ++ show (v+1) ++ " clicks" ] + + widgetShowAll window + + mainGUI diff --git a/Task/Simple-windowed-application/HicEst/simple-windowed-application.hicest b/Task/Simple-windowed-application/HicEst/simple-windowed-application.hicest new file mode 100644 index 0000000000..545a7ec082 --- /dev/null +++ b/Task/Simple-windowed-application/HicEst/simple-windowed-application.hicest @@ -0,0 +1,8 @@ + CHARACTER label="There have been no clicks yet" + + DO count = 1, 1E100 ! "forever" + DLG(Button="Click me", Width=3, TItle=label) ! Width=3 to display full length label + label = "Clicked " // count // "time(s)" + ENDDO + + END diff --git a/Task/Simple-windowed-application/IDL/simple-windowed-application.idl b/Task/Simple-windowed-application/IDL/simple-windowed-application.idl new file mode 100644 index 0000000000..08e20e868f --- /dev/null +++ b/Task/Simple-windowed-application/IDL/simple-windowed-application.idl @@ -0,0 +1,14 @@ +pro counter, ev + widget_control, ev.top, get_uvalue=tst + tst[1] = tst[1]+1 + widget_control, tst[0], set_value="Number of clicks: "+string(tst[1],format='(i0)') + widget_control, ev.top, set_uvalue=tst +end + +id = widget_base(title = 'Window Title',column=1) +ld = widget_label(id, value = 'There have been no clicks yet.') +widget_control, /realize, id, set_uvalue=[ld,0] +dummy = widget_button(id,value=' Click Me ',event_pro='counter') +xmanager, "Simple", Id + +end diff --git a/Task/Simple-windowed-application/J/simple-windowed-application.j b/Task/Simple-windowed-application/J/simple-windowed-application.j new file mode 100644 index 0000000000..34c3503acd --- /dev/null +++ b/Task/Simple-windowed-application/J/simple-windowed-application.j @@ -0,0 +1,22 @@ +SIMPLEAPP=: noun define +pc simpleApp; +xywh 131 11 44 12;cc inc button;cn "Click me"; +xywh 7 10 115 11;cc shownText static;cn "There have been no clicks yet."; +pas 6 6;pcenter; +rem form end; +) + +simpleApp_run=: verb define + wd SIMPLEAPP + simpleApp_accum=: 0 NB. initialize accumulator + wd 'pshow;' +) + +simpleApp_inc_button=: verb define + wd 'set shownText *','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum +) + +simpleApp_close=: wd bind 'pclose' +simpleApp_cancel=: simpleApp_close + +simpleApp_run'' diff --git a/Task/Simple-windowed-application/Java/simple-windowed-application.java b/Task/Simple-windowed-application/Java/simple-windowed-application.java new file mode 100644 index 0000000000..338142a2c9 --- /dev/null +++ b/Task/Simple-windowed-application/Java/simple-windowed-application.java @@ -0,0 +1,35 @@ +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +public class Clicks extends JFrame implements ActionListener{ + private long clicks = 0; + private JLabel label; + private JButton clicker; + private String text; + + public Clicks(){ + text = "There have been no clicks yet"; + label = new JLabel(text); + clicker = new JButton("click me"); + clicker.addActionListener(this);//listen to the button + setLayout(new BorderLayout());//handles placement of components + add(label,BorderLayout.CENTER);//add the label to the biggest section + add(clicker,BorderLayout.SOUTH);//put the button underneath it + setSize(300,200);//stretch out the window + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X" + setVisible(true);//show it + } + public static void main(String[] args){ + new Clicks();//call the constructor where all the magic happens + } + public void actionPerformed(ActionEvent arg0) { + if(arg0.getSource() == clicker){//if they clicked the button + text = "There have been " + (++clicks) + " clicks"; + label.setText(text);//change the text + } + + } +} diff --git a/Task/Simple-windowed-application/JavaFX-Script/simple-windowed-application.javafx b/Task/Simple-windowed-application/JavaFX-Script/simple-windowed-application.javafx new file mode 100644 index 0000000000..9a700d740a --- /dev/null +++ b/Task/Simple-windowed-application/JavaFX-Script/simple-windowed-application.javafx @@ -0,0 +1,25 @@ +import javafx.stage.*; +import javafx.scene.*; +import javafx.scene.layout.*; +import javafx.scene.control.*; + +Stage { + scene: Scene { + width: 300 height: 200 + content: VBox { + var clicks: Integer; + + spacing: 10 + content: [ + Label { + def varText = bind if (clicks == 0) then "no clicks yet" else "{clicks} clicks" + text : bind "There have been {varText}" + } + Button { + text: "click me" + onMouseClicked: function(e) { clicks++; } + } + ] + } + } +} diff --git a/Task/Simple-windowed-application/Liberty-BASIC/simple-windowed-application.liberty b/Task/Simple-windowed-application/Liberty-BASIC/simple-windowed-application.liberty new file mode 100644 index 0000000000..33535d3e40 --- /dev/null +++ b/Task/Simple-windowed-application/Liberty-BASIC/simple-windowed-application.liberty @@ -0,0 +1,16 @@ +nomainwin + button #demo.btn, "Click Me", [btnClick], UL, 20, 50 + statictext #demo.num, "There have been no clicks yet.", 20, 100, 240, 30 + open "Rosetta Task: Simple windowed application" for window as #demo + #demo "trapclose [quit]" + nClicks = 0 +wait + +[quit] + close #demo +end + +[btnClick] + nClicks = nClicks + 1 + #demo.num "The button has been clicked ";nClicks;" times." +wait diff --git a/Task/Simple-windowed-application/Logo/simple-windowed-application-1.logo b/Task/Simple-windowed-application/Logo/simple-windowed-application-1.logo new file mode 100644 index 0000000000..09a49a7dc3 --- /dev/null +++ b/Task/Simple-windowed-application/Logo/simple-windowed-application-1.logo @@ -0,0 +1,9 @@ +to clickwindow +windowCreate "root "clickWin [Click that button!!!] 0 0 100 100 [] +Make "i 0 +staticCreate "clickWin "clickSt [There have been no clicks yet] 0 0 100 20 +buttonCreate "clickWin "clickBtn [click me] 10 20 80 20 ~ + [Make "i :i+1 ~ + ifelse :i=1 [staticUpdate "clickSt (list "clicked :i "time)] ~ + [staticUpdate "clickSt (list "clicked :i "times)]] +end diff --git a/Task/Simple-windowed-application/Logo/simple-windowed-application-2.logo b/Task/Simple-windowed-application/Logo/simple-windowed-application-2.logo new file mode 100644 index 0000000000..3a2eaf0488 --- /dev/null +++ b/Task/Simple-windowed-application/Logo/simple-windowed-application-2.logo @@ -0,0 +1 @@ +clickwindow diff --git a/Task/Simple-windowed-application/Lua/simple-windowed-application.lua b/Task/Simple-windowed-application/Lua/simple-windowed-application.lua new file mode 100644 index 0000000000..47690ce483 --- /dev/null +++ b/Task/Simple-windowed-application/Lua/simple-windowed-application.lua @@ -0,0 +1,14 @@ +require"iuplua" +l = iup.label{title="There have been no clicks yet."} +b = iup.button{title="Click me!"} +clicks = 0 +function b:button_cb() + clicks = clicks + 1 + l.title = "There have been " .. clicks/2 .. " clicks so far." --yes, this is correct. +end +dlg = iup.dialog{iup.vbox{l, b}, title="Simple Windowed Application"} +dlg:show() + +if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then + iup.MainLoop() +end diff --git a/Task/Simple-windowed-application/MAXScript/simple-windowed-application.maxscript b/Task/Simple-windowed-application/MAXScript/simple-windowed-application.maxscript new file mode 100644 index 0000000000..5fa4dfceb0 --- /dev/null +++ b/Task/Simple-windowed-application/MAXScript/simple-windowed-application.maxscript @@ -0,0 +1,13 @@ +rollout buttonClick "Button Click" +( + label l "There have been no clicks yet" + button clickMe "Click me" + local clickCount = 0 + + on clickMe pressed do + ( + clickCount += 1 + l.text = ("Number of clicks: " + clickCount as string) + ) +) +createDialog buttonClick diff --git a/Task/Simple-windowed-application/Mathematica/simple-windowed-application.math b/Task/Simple-windowed-application/Mathematica/simple-windowed-application.math new file mode 100644 index 0000000000..c0ef7845ff --- /dev/null +++ b/Task/Simple-windowed-application/Mathematica/simple-windowed-application.math @@ -0,0 +1,4 @@ +DynamicModule[{n = 0}, + CreateDialog[{Dynamic@ + TextCell@If[n == 0, "There have been no clicks yet", n], + Button["click me", n++]}]] diff --git a/Task/Simple-windowed-application/Modula-3/simple-windowed-application.mod3 b/Task/Simple-windowed-application/Modula-3/simple-windowed-application.mod3 new file mode 100644 index 0000000000..2deb28cff7 --- /dev/null +++ b/Task/Simple-windowed-application/Modula-3/simple-windowed-application.mod3 @@ -0,0 +1,20 @@ +MODULE Click EXPORTS Main; + +IMPORT Fmt, TextVBT, ButtonVBT, VBT, Axis, HVSplit, TrestleComm, Trestle; + +VAR label := TextVBT.New("There have been no clicks yet."); + button := ButtonVBT.New(TextVBT.New("Click me!"), Clicked); + main := HVSplit.Cons(Axis.T.Ver, label, button, adjustable := FALSE); + count := 0; + +PROCEDURE Clicked(<*UNUSED*>button: ButtonVBT.T; <*UNUSED*>READONLY cd: VBT.MouseRec) = + BEGIN + INC(count); + TextVBT.Put(label, "Button pressed: " & Fmt.Int(count)); + END Clicked; + +<*FATAL TrestleComm.Failure*> +BEGIN + Trestle.Install(main); + Trestle.AwaitDelete(main); +END Click. diff --git a/Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ocaml b/Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ocaml new file mode 100644 index 0000000000..6fe09464ab --- /dev/null +++ b/Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ocaml @@ -0,0 +1,16 @@ +#directory "+labltk" +#load "labltk.cma" + +let () = + let top = Tk.openTk() in + Wm.title_set top "Tk-OCaml Example"; + let label = Label.create ~text:"There have been no clicks yet" top in + let b = + Button.create + ~text:"click me" + ~command:(fun () -> Tk.closeTk (); exit 0) + top + in + Tk.pack [Tk.coe label; Tk.coe b]; + Tk.mainLoop (); +;; diff --git a/Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ocaml b/Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ocaml new file mode 100644 index 0000000000..b102ee755d --- /dev/null +++ b/Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ocaml @@ -0,0 +1,13 @@ +open GMain + +let window = GWindow.window ~border_width:2 () +let vbox = GPack.vbox ~packing:window#add () +let label = GMisc.label ~text:"There have been no clicks yet" ~packing:vbox#pack () +let button = GButton.button ~label:"click me" ~packing:vbox#pack () + +let () = + window#event#connect#delete ~callback:(fun _ -> true); + window#connect#destroy ~callback:Main.quit; + button#connect#clicked ~callback:window#destroy; + window#show (); + Main.main () diff --git a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m new file mode 100644 index 0000000000..f7a6f90a2f --- /dev/null +++ b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-1.m @@ -0,0 +1,13 @@ +#include <Foundation/Foundation.h> +#include <AppKit/AppKit.h> + +@interface ClickMe : NSWindow +{ + NSButton *button; + NSTextField *text; + int counter; +} +- (void)applicationDidFinishLaunching: (NSNotification *)notification; +- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification; +- (void)advanceCounter: (id)sender; +@end diff --git a/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m new file mode 100644 index 0000000000..fdc6b77723 --- /dev/null +++ b/Task/Simple-windowed-application/Objective-C/simple-windowed-application-2.m @@ -0,0 +1,86 @@ +@implementation ClickMe : NSWindow +-(id) init +{ + NSRect buttonRect; + int totalWindowHeight; + + counter = 0; + button = [[NSButton alloc] init]; + [button setButtonType: NSToggleButton]; + [button setTitle: @"Click Me"]; + [button sizeToFit]; + [button setTarget: self]; + [button setAction: @selector(advanceCounter:)]; + buttonRect = [button frame]; + + text = [[NSTextField alloc] + initWithFrame: NSMakeRect(buttonRect.origin.x, buttonRect.size.height, + buttonRect.size.width, buttonRect.size.height)]; + [text setAlignment: NSCenterTextAlignment]; + [text setEditable: NO]; + [text setStringValue: @"There have been no clicks yet"]; + [text sizeToFit]; + + // reset size of button according to size of (larger...?) text + [button + setFrameSize: NSMakeSize( [text frame].size.width, buttonRect.size.height ) ]; + + totalWindowHeight = buttonRect.size.height + [text frame].size.height; + + [self + initWithContentRect: NSMakeRect(100, 100, + [text frame].size.width, totalWindowHeight) + styleMask: (NSTitledWindowMask | NSClosableWindowMask) + backing: NSBackingStoreBuffered + defer: NO]; + + [[self contentView] addSubview: text]; [text release]; + [[self contentView] addSubview: button]; [button release]; + + [self setTitle: @"Click Me!"]; + [self center]; + + return self; +} + + +-(void) dealloc +{ + [button release]; + [text release]; + [super dealloc]; +} + +- (void)applicationDidFinishLaunching: (NSNotification *)notification +{ + [self orderFront: self]; +} + +- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification +{ + return YES; +} + +- (void)advanceCounter: (id)sender +{ + counter++; + [text setStringValue: [NSString stringWithFormat: @"Clicked %d times", counter]]; +} +@end + + +int main() +{ + ClickMe *clickme; + NSAutoreleasePool *pool; + NSApplication *app; + + pool = [[NSAutoreleasePool alloc] init]; + app = [NSApplication sharedApplication]; + clickme = [[ClickMe alloc] init]; + [app setDelegate: clickme]; + [app run]; + [clickme release]; + [pool release]; + return 0; +} diff --git a/Task/Simple-windowed-application/Oz/simple-windowed-application.oz b/Task/Simple-windowed-application/Oz/simple-windowed-application.oz new file mode 100644 index 0000000000..b646e46136 --- /dev/null +++ b/Task/Simple-windowed-application/Oz/simple-windowed-application.oz @@ -0,0 +1,18 @@ +functor +import + Application + QTk at 'x-oz://system/wp/QTk.ozf' +define + Count = {NewCell 0} + Label + GUI = td(action:proc {$} {Application.exit 0} end %% exit on close + label(text:"There have been no clicks yet." handle:Label) + button(text:"Click Me" + action:proc {$} + Count := @Count + 1 + {Label set(text:"Number of clicks: "#@Count#".")} + end + )) + Window = {QTk.build GUI} + {Window show} +end diff --git a/Task/Simple-windowed-application/Pascal/simple-windowed-application.pascal b/Task/Simple-windowed-application/Pascal/simple-windowed-application.pascal new file mode 100644 index 0000000000..1b6f7740a8 --- /dev/null +++ b/Task/Simple-windowed-application/Pascal/simple-windowed-application.pascal @@ -0,0 +1,47 @@ +Program SimpleWindowApplication; + +uses + SysUtils, + glib2, + Gtk2; + +const + clickme = 'Click Me'; + MAXLEN = 64; + +var + counter: integer = 0; + +procedure clickedme(o: PGtkButton; d: pointer); cdecl; + var + nt: Pchar; + l: PGtkLabel; + begin + l := Gtk_LABEL(d); + inc(counter); + nt := Pchar('You clicked me ' + inttostr(counter) + ' times'); + Gtk_label_set_text(l, nt); + end; + +var + win: PGtkWindow; + button: PGtkButton; + Mylabel: PGtkLabel; + vbox: PGtkVBox; + +begin + Gtk_init(@argc, @argv); + win := PGtkWindow(Gtk_window_new(Gtk_WINDOW_TOPLEVEL)); + Gtk_window_set_title(win, clickme); + button := PGtkButton(Gtk_button_new_with_label(clickme)); + Mylabel := PGtkLabel(Gtk_label_new('There have been no clicks yet')); + Gtk_label_set_single_line_mode(Mylabel, TRUE); + vbox := PGtkVBox(Gtk_vbox_new(TRUE, 1)); + Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(Mylabel)); + Gtk_container_add(Gtk_CONTAINER(vbox), Gtk_WIDGET(button)); + Gtk_container_add(Gtk_CONTAINER(win), Gtk_WIDGET(vbox)); + g_signal_connect(G_OBJECT(win), 'delete-event', TGCallBack(@Gtk_main_quit), NULL); + g_signal_connect(G_OBJECT(button), 'clicked', TGCallBack(@clickedme), Mylabel); + Gtk_widget_show_all(Gtk_WIDGET(win)); + Gtk_main(); +end. diff --git a/Task/Simple-windowed-application/Perl/simple-windowed-application-1.pl b/Task/Simple-windowed-application/Perl/simple-windowed-application-1.pl new file mode 100644 index 0000000000..016f69a385 --- /dev/null +++ b/Task/Simple-windowed-application/Perl/simple-windowed-application-1.pl @@ -0,0 +1,10 @@ +use Tk; + +$main = MainWindow->new; +$l = $main->Label('-text' => 'There have been no clicks yet.')->pack; +$count = 0; +$main->Button( + -text => ' Click Me ', + -command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); }, +)->pack; +MainLoop(); diff --git a/Task/Simple-windowed-application/Perl/simple-windowed-application-2.pl b/Task/Simple-windowed-application/Perl/simple-windowed-application-2.pl new file mode 100644 index 0000000000..ae603fc2bb --- /dev/null +++ b/Task/Simple-windowed-application/Perl/simple-windowed-application-2.pl @@ -0,0 +1,27 @@ +use Gtk '-init'; + +# Window. +$window = Gtk::Window->new; +$window->signal_connect('destroy' => sub { Gtk->main_quit; }); + +# VBox. +$vbox = Gtk::VBox->new(0, 0); +$window->add($vbox); + +# Label. +$label = Gtk::Label->new('There have been no clicks yet.'); +$vbox->add($label); + +# Button. +$count = 0; +$button = Gtk::Button->new(' Click Me '); +$vbox->add($button); +$button->signal_connect('clicked', sub { + $label->set_text(++$count); +}); + +# Show. +$window->show_all; + +# Main loop. +Gtk->main; diff --git a/Task/Simple-windowed-application/Perl/simple-windowed-application-3.pl b/Task/Simple-windowed-application/Perl/simple-windowed-application-3.pl new file mode 100644 index 0000000000..86e5597146 --- /dev/null +++ b/Task/Simple-windowed-application/Perl/simple-windowed-application-3.pl @@ -0,0 +1,7 @@ +use XUL::Gui; + +display + TextBox( id=>'txt', value=>'there have been no clicks yet' ), + Button( label=>'click me', oncommand=>sub{ + $ID{txt}->value = ++$clicks + }); diff --git a/Task/Simple-windowed-application/PicoLisp/simple-windowed-application.l b/Task/Simple-windowed-application/PicoLisp/simple-windowed-application.l new file mode 100644 index 0000000000..0e642fc5cf --- /dev/null +++ b/Task/Simple-windowed-application/PicoLisp/simple-windowed-application.l @@ -0,0 +1,19 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(load "@ext.l" "@lib/http.l" "@lib/xhtml.l" "@lib/form.l") + +(zero *Count) + +(de start () + (app) + (action + (html 0 "Clicks" NIL NIL + (form NIL + (gui '(+Init +TextField) "There have been no clicks yet") + (----) + (gui '(+JS +Button) "click me" + '(set> (field -1) + (pack "Clicked " (inc '*Count) " times") ) ) ) ) ) ) + +(server 8080 "!start") +(wait) diff --git a/Task/Simple-windowed-application/Pike/simple-windowed-application.pike b/Task/Simple-windowed-application/Pike/simple-windowed-application.pike new file mode 100644 index 0000000000..c6256826f1 --- /dev/null +++ b/Task/Simple-windowed-application/Pike/simple-windowed-application.pike @@ -0,0 +1,21 @@ +GTK2.Widget mainwindow,clickcnt,clicker; +int clicks; + +void click() +{ + clickcnt->set_text("Clicks: "+(++clicks)); +} + +int main() +{ + GTK2.setup_gtk(); + mainwindow=GTK2.Window(GTK2.WindowToplevel); + mainwindow->set_title("Click counter"); + mainwindow->add(GTK2.Vbox(0,10) + ->add(clickcnt=GTK2.Label("There have been no clicks yet")) + ->add(clicker=GTK2.Button("Click me")) + )->show_all(); + mainwindow->signal_connect("delete_event",lambda() {exit(0);}); + clicker->signal_connect("clicked",click); + return -1; +} diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application.psh new file mode 100644 index 0000000000..b41a1054d2 --- /dev/null +++ b/Task/Simple-windowed-application/PowerShell/simple-windowed-application.psh @@ -0,0 +1,15 @@ +$count = 0 + +New-Window { + New-StackPanel { + New-TextBlock "There have been no clicks yet" ` + -On_Loaded { + Set-Variable tb $this + } + New-Button "Click me" ` + -On_Click { + $count++ + $tb.Text = $count + } + } +} -SizeToContent WidthAndHeight -Show diff --git a/Task/Simple-windowed-application/Prolog/simple-windowed-application.pro b/Task/Simple-windowed-application/Prolog/simple-windowed-application.pro new file mode 100644 index 0000000000..5aed181816 --- /dev/null +++ b/Task/Simple-windowed-application/Prolog/simple-windowed-application.pro @@ -0,0 +1,41 @@ +:- dynamic click/1. + +dialog('Simple windowed application', + [ object := + Simple_windowed_application, + parts := + [ Simple_windowed_application := + dialog('Simple windowed application'), + Name := + label(name, 'There have been no clicks yet'), + BtnClick := + button(button) + ], + modifications := + [ BtnClick := [ label := 'Click me !' + ] + ], + layout := + [ area(Name, + area(40, 20, 200, 18)), + area(BtnClick, + area(90, 60, 80, 24)) + ], + behaviour := + [ + BtnClick := [message := message(@prolog, btnclick, Name)] + ] + ]). + +btnclick(Label) :- + retract(click(V)), + V1 is V+1, + assert(click(V1)), + sformat(A, '~w click(s)', [V1]), + send(Label, selection, A). + +simple_windowed :- + retractall(click(_)), + assert(click(0)), + make_dialog(D, 'Simple windowed application'), + send(D, open). diff --git a/Task/Simple-windowed-application/PureBasic/simple-windowed-application.purebasic b/Task/Simple-windowed-application/PureBasic/simple-windowed-application.purebasic new file mode 100644 index 0000000000..46aee8d0e9 --- /dev/null +++ b/Task/Simple-windowed-application/PureBasic/simple-windowed-application.purebasic @@ -0,0 +1,32 @@ +Global Window_0 +Global Window_0_Text_0 +Global Window_0_Button_1 +Global Clicks, txt$ + +Procedure OpenWindow_Window_0() + Protected flags=#PB_Window_SystemMenu|#PB_Window_SizeGadget|#PB_Window_TitleBar|#PB_Window_WindowCentered + Window_0 = OpenWindow(#PB_Any, 408, 104, 280, 45, "Simple windowed application", flags) + If Window_0 + SmartWindowRefresh(Window_0, #True) + Window_0_Text_0 = TextGadget(#PB_Any, 5, 5, 165, 20, "There have been no clicks yet") + Window_0_Button_1 = ButtonGadget(#PB_Any, 190, 10, 85, 30, "Click me") + EndIf +EndProcedure + +OpenWindow_Window_0() + +Repeat + Select WaitWindowEvent() + Case #PB_Event_Gadget + Select EventGadget() + Case Window_0_Text_0 + Case Window_0_Button_1 + Clicks+1 + txt$="You Clicked "+Str(Clicks)+" time" + If Clicks>1: txt$+"s": EndIf + SetGadgetText(Window_0_Text_0,txt$) + EndSelect + Case #PB_Event_CloseWindow + End + EndSelect +ForEver diff --git a/Task/Simple-windowed-application/Python/simple-windowed-application-1.py b/Task/Simple-windowed-application/Python/simple-windowed-application-1.py new file mode 100644 index 0000000000..05fd038b19 --- /dev/null +++ b/Task/Simple-windowed-application/Python/simple-windowed-application-1.py @@ -0,0 +1,13 @@ +from Tkinter import Tk, Label, Button + +def update_label(): + global n + n += 1 + l["text"] = "Number of clicks: %d" % n + +w = Tk() +n = 0 +l = Label(w, text="There have been no clicks yet") +l.pack() +Button(w, text="click me", command=update_label).pack() +w.mainloop() diff --git a/Task/Simple-windowed-application/Python/simple-windowed-application-2.py b/Task/Simple-windowed-application/Python/simple-windowed-application-2.py new file mode 100644 index 0000000000..f632cd76b1 --- /dev/null +++ b/Task/Simple-windowed-application/Python/simple-windowed-application-2.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +from Tkinter import Button, Frame, Label, Pack + +class ClickCounter(Frame): + def click(self): + self.count += 1 + self.label['text'] = 'Number of clicks: %d' % self.count + + def createWidgets(self): + self.label = Label(self, text='here have been no clicks yet') + self.label.pack() + self.button = Button(self, text='click me', command=self.click) + self.button.pack() + + def __init__(self, master=None): + Frame.__init__(self, master) + Pack.config(self) + self.createWidgets() + self.count = 0 + +if __name__=="__main__": + ClickCounter().mainloop() diff --git a/Task/Simple-windowed-application/Python/simple-windowed-application-3.py b/Task/Simple-windowed-application/Python/simple-windowed-application-3.py new file mode 100644 index 0000000000..096076d6d6 --- /dev/null +++ b/Task/Simple-windowed-application/Python/simple-windowed-application-3.py @@ -0,0 +1,20 @@ +import sys +from qt import * + +def update_label(): + global i + i += 1 + lbl.setText("Number of clicks: %i" % i) + +i = 0 +app = QApplication(sys.argv) +win = QWidget() +win.resize(200, 100) +lbl = QLabel("There have been no clicks yet", win) +lbl.setGeometry(0, 15, 200, 25) +btn = QPushButton("click me", win) +btn.setGeometry(50, 50, 100, 25) +btn.connect(btn, SIGNAL("clicked()"), update_label) +win.show() +app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) +app.exec_loop() diff --git a/Task/Simple-windowed-application/Python/simple-windowed-application-4.py b/Task/Simple-windowed-application/Python/simple-windowed-application-4.py new file mode 100644 index 0000000000..d56881407b --- /dev/null +++ b/Task/Simple-windowed-application/Python/simple-windowed-application-4.py @@ -0,0 +1,28 @@ +import wx + +class MyApp(wx.App): + def click(self, event): + self.count += 1 + self.label.SetLabel("Count: %d" % self.count) + + def OnInit(self): + frame = wx.Frame(None, wx.ID_ANY, "Hello from wxPython") + self.count = 0 + self.button = wx.Button(frame, wx.ID_ANY, "Click me!") + self.label = wx.StaticText(frame, wx.ID_ANY, "Count: 0") + self.Bind(wx.EVT_BUTTON, self.click, self.button) + + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.sizer.Add(self.button, True, wx.EXPAND) + self.sizer.Add(self.label, True, wx.EXPAND) + frame.SetSizer(self.sizer) + frame.SetAutoLayout(True) + self.sizer.Fit(frame) + + frame.Show(True) + + self.SetTopWindow(frame) + return True + +app = MyApp(0) +app.MainLoop() diff --git a/Task/Simple-windowed-application/R/simple-windowed-application.r b/Task/Simple-windowed-application/R/simple-windowed-application.r new file mode 100644 index 0000000000..c145e94f69 --- /dev/null +++ b/Task/Simple-windowed-application/R/simple-windowed-application.r @@ -0,0 +1,10 @@ +library(gWidgets) +library(gWidgetstcltk) +win <- gwindow() +lab <- glabel("There have been no clicks yet", container=win) +btn <- gbutton("click me", container=win, handle=function(h, ...) + { + val <- as.numeric(svalue(lab)) + svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1)) + } +) diff --git a/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol b/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol new file mode 100644 index 0000000000..5f332b87b9 --- /dev/null +++ b/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol @@ -0,0 +1,29 @@ +REBOL [ + Title: "Simple Windowed Application" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/Simple_Windowed_Application +] + +clicks: 0 + +; Simple GUI's in REBOL can be defined with 'layout', a +; special-purpose language (dialect, in REBOL-speak) for specifying +; interfaces. In the example below, I describe a gradient background +; with a text label and a button. The block in the button section +; details what should happen when it's clicked on -- increment the +; number of clicks and update the label text. + +; The 'view' function paints the layout on the screen and listens for +; events. + +view layout [ + backdrop effect [gradient 0x1 black coal] + + label: vtext "There have been no clicks yet." + + button maroon "click me" [ + clicks: clicks + 1 + set-face label reform ["clicks:" clicks] + ] +] diff --git a/Task/Simple-windowed-application/Racket/simple-windowed-application.rkt b/Task/Simple-windowed-application/Racket/simple-windowed-application.rkt new file mode 100644 index 0000000000..fbd540595f --- /dev/null +++ b/Task/Simple-windowed-application/Racket/simple-windowed-application.rkt @@ -0,0 +1,11 @@ +#lang racket/gui + +(define frame (new frame% [label "There have been no clicks yet"])) + +(define num-clicks 0) +(define (cb obj me) + (set! num-clicks (add1 num-clicks)) + (send frame set-label (format "~a" num-clicks))) + +(new button% [parent frame] [label "Click me"] [callback cb]) +(send frame show #t) diff --git a/Task/Simple-windowed-application/RapidQ/simple-windowed-application.rapidq b/Task/Simple-windowed-application/RapidQ/simple-windowed-application.rapidq new file mode 100644 index 0000000000..ec63a07b43 --- /dev/null +++ b/Task/Simple-windowed-application/RapidQ/simple-windowed-application.rapidq @@ -0,0 +1,26 @@ +DECLARE SUB buttonClick + +CREATE form AS QForm + Center + Height = 120 + Width = 300 + + CREATE text AS QLabel + Caption = "There have been no clicks yet." + Left = 30: Top = 20 + END CREATE + + CREATE button1 AS QButton + Caption = "Click me" + Left = 100: Top = 50: Height = 25: Width = 100 + OnClick = buttonClick + END CREATE +END CREATE + +SUB buttonClick + STATIC count AS Integer + count = count+1 + text.Caption = "Clicked " + STR$(count) + " times." +END SUB + +form.ShowModal diff --git a/Task/Simple-windowed-application/Ruby/simple-windowed-application-1.rb b/Task/Simple-windowed-application/Ruby/simple-windowed-application-1.rb new file mode 100644 index 0000000000..b4571d1b53 --- /dev/null +++ b/Task/Simple-windowed-application/Ruby/simple-windowed-application-1.rb @@ -0,0 +1,11 @@ +require 'tk' +str = TkVariable.new("no clicks yet") +count = 0 +root = TkRoot.new +TkLabel.new(root, "textvariable" => str).pack +TkButton.new(root) do + text "click me" + command {str.value = count += 1} + pack +end +Tk.mainloop diff --git a/Task/Simple-windowed-application/Ruby/simple-windowed-application-2.rb b/Task/Simple-windowed-application/Ruby/simple-windowed-application-2.rb new file mode 100644 index 0000000000..6d47d5243c --- /dev/null +++ b/Task/Simple-windowed-application/Ruby/simple-windowed-application-2.rb @@ -0,0 +1,10 @@ +Shoes.app do + stack do + @count = 0 + @label = para "no clicks yet" + button "click me" do + @count += 1 + @label.text = "click: #@count" + end + end +end diff --git a/Task/Simple-windowed-application/Run-BASIC/simple-windowed-application.run b/Task/Simple-windowed-application/Run-BASIC/simple-windowed-application.run new file mode 100644 index 0000000000..778bae6cf6 --- /dev/null +++ b/Task/Simple-windowed-application/Run-BASIC/simple-windowed-application.run @@ -0,0 +1,10 @@ +msg$ = "There have been no clicks yet" +[loop] cls ' clear screen +print msg$ +button #c, "Click Me", [clickMe] 'create a button with handle and goto [tag] +wait + +[clickMe] +clicks = clicks + 1 +msg$ = "Button has been clicked ";clicks;" times" +goto [loop] diff --git a/Task/Simple-windowed-application/Scala/simple-windowed-application.scala b/Task/Simple-windowed-application/Scala/simple-windowed-application.scala new file mode 100644 index 0000000000..28c671b18f --- /dev/null +++ b/Task/Simple-windowed-application/Scala/simple-windowed-application.scala @@ -0,0 +1,29 @@ +import scala.swing._ +import scala.swing.event._ +import scala.swing.Swing._ + +object SimpleApp extends SimpleSwingApplication { + def top = new MainFrame { + var nClicks = 0 + + val button = new Button { + text = "click me" + } + val label = new Label { + text = "There have been no clicks yet" + } + contents = new BorderPanel { + layout(button) = BorderPanel.Position.South + layout(label) = BorderPanel.Position.Center + } + + preferredSize = ((300, 200): Dimension) + + listenTo(button) + reactions += { + case ButtonClicked(_) => + nClicks += 1 + label.text = "There have been %d clicks" format nClicks + } + } +} diff --git a/Task/Simple-windowed-application/Smalltalk/simple-windowed-application.st b/Task/Simple-windowed-application/Smalltalk/simple-windowed-application.st new file mode 100644 index 0000000000..81f2521e36 --- /dev/null +++ b/Task/Simple-windowed-application/Smalltalk/simple-windowed-application.st @@ -0,0 +1,16 @@ +|top clickCount lh button| + +clickCount := 0. +lh := ValueHolder with:'There have been no clicks yet'. + +top := StandardSystemView label:'Rosetta Simple Window'. +top extent:300@100. +top add:((Label new labelChannel:lh) origin: 0 @ 10 corner: 1.0 @ 40). +top add:((button := Button label:'Eat Me') origin: 10 @ 50 corner: 100 @ 80). + +button action:[ + clickCount := clickCount + 1. + lh value: ('number of clicks: %1' bindWith:clickCount) + ]. + +top open diff --git a/Task/Simple-windowed-application/TI-89-BASIC/simple-windowed-application.ti-89 b/Task/Simple-windowed-application/TI-89-BASIC/simple-windowed-application.ti-89 new file mode 100644 index 0000000000..3cc5e964e3 --- /dev/null +++ b/Task/Simple-windowed-application/TI-89-BASIC/simple-windowed-application.ti-89 @@ -0,0 +1,12 @@ +Prgm + Local clicks + 0 → clicks + 1 → ok © System variable also set by Dialog statement + While ok = 1 + Dialog + Title "Rosetta Code" + Text "There have been " & string(clicks) & " OKs" + EndDlog + clicks + 1 → clicks + EndWhile +EndPrgm diff --git a/Task/Simple-windowed-application/Tcl/simple-windowed-application.tcl b/Task/Simple-windowed-application/Tcl/simple-windowed-application.tcl new file mode 100644 index 0000000000..fa5e5fc431 --- /dev/null +++ b/Task/Simple-windowed-application/Tcl/simple-windowed-application.tcl @@ -0,0 +1,7 @@ +package require Tk +pack [label .l -text "There have been no clicks yet"] +set count 0 +pack [button .b -text "click me" -command upd] +proc upd {} { + .l configure -text "Number of clicks: [incr ::count]" +} diff --git a/Task/Simple-windowed-application/Unicon/simple-windowed-application.unicon b/Task/Simple-windowed-application/Unicon/simple-windowed-application.unicon new file mode 100644 index 0000000000..b38361d972 --- /dev/null +++ b/Task/Simple-windowed-application/Unicon/simple-windowed-application.unicon @@ -0,0 +1,31 @@ +import gui +$include "guih.icn" + +class SimpleApp : Dialog (label) + + # -- automatically called when the dialog is created + method component_setup() + # create and add the label + label := Label("label=There have been no clicks yet","pos=50%,33%", "align=c,c") + add (label) + + # create and add the button + button := TextButton("label=Click me", "pos=50%,66%", "align=c,c") + button.connect(self, "clicked", ACTION_EVENT) + add (button) + + # some cosmetic settings for the window + attrib("size=180,70", "bg=light gray") + end + + method clicked () + static count := 0 + count +:= 1 + label.set_label ("Clicked " || count || " times") + end +end + +procedure main() + local d := SimpleApp () + d.show_modal() +end diff --git a/Task/Simple-windowed-application/Vedit-macro-language/simple-windowed-application.vedit b/Task/Simple-windowed-application/Vedit-macro-language/simple-windowed-application.vedit new file mode 100644 index 0000000000..1b169a2139 --- /dev/null +++ b/Task/Simple-windowed-application/Vedit-macro-language/simple-windowed-application.vedit @@ -0,0 +1,13 @@ +Reg_Set(10, "There have been no clicks yet") +#1 = 0 +repeat (ALL) { + #2 = Dialog_Input_1(3, "`Simple Windowed Application`, + `|@(10)`, + `[&Click me]`,`[&Exit]`", + APP+CENTER, 0, 0) + if (#2 != 1) { break } // ESC or Exit + #1++ + Num_Str(#1, 10) + Reg_Set(10, "Clicked", INSERT) + Reg_Set(10, " times", APPEND) +} diff --git a/Task/Simple-windowed-application/Visual-Basic/simple-windowed-application.vb b/Task/Simple-windowed-application/Visual-Basic/simple-windowed-application.vb new file mode 100644 index 0000000000..76a2b93002 --- /dev/null +++ b/Task/Simple-windowed-application/Visual-Basic/simple-windowed-application.vb @@ -0,0 +1,32 @@ +VERSION 5.00 +Begin VB.Form Form2 + Caption = "There have been no clicks yet" + ClientHeight = 2940 + ClientLeft = 60 + ClientTop = 600 + ClientWidth = 8340 + LinkTopic = "Form1" + ScaleHeight = 2940 + ScaleWidth = 8340 + StartUpPosition = 3 'Windows Default + Begin VB.CommandButton Command1 + Caption = "Click me!" + Height = 495 + Left = 3600 + TabIndex = 0 + Top = 1200 + Width = 1215 + End +End +Attribute VB_Name = "Form1" +Attribute VB_GlobalNameSpace = False +Attribute VB_Creatable = False +Attribute VB_PredeclaredId = True +Attribute VB_Exposed = False +'-----user-written code begins here; everything above this line is hidden in the GUI----- +Private clicked As Long + +Private Sub Command1_Click() + clicked = clicked + 1 + Me.Caption = clicked & " clicks." +End Sub diff --git a/Task/Simple-windowed-application/XPL0/simple-windowed-application.xpl0 b/Task/Simple-windowed-application/XPL0/simple-windowed-application.xpl0 new file mode 100644 index 0000000000..658a72cd8d --- /dev/null +++ b/Task/Simple-windowed-application/XPL0/simple-windowed-application.xpl0 @@ -0,0 +1,30 @@ +include c:\cxpl\stdlib; \standard library provides mouse routines, etc. +def Ww=40, Wh=12, Wx=(80-Ww)/2, Wy=(25-Wh)/2; \window width, etc. +def Bw=11, Bh=4, Bx=Wx+(Ww-Bw)/2, By=Wy+3*(Wh-Bh)/4; \button size & position +int Clicks, Mx, My; \number of clicks and mouse coordinates + +[ShowCursor(false); \turn off flashing cursor +Attrib($1F); \bright white characters on blue +SetWind(Wx, Wy, Wx+Ww, Wy+Wh, 2, true); \blue window with no scroll +DrawBox(Wx, Wy, Wx+Ww, Wy+Wh, 3); \draw borders +Cursor(Wx+5, Wy+3); Text(6, "There have been no clicks yet."); +DrawBox(Bx, By, Bx+Bw, By+Bh, 0); \draw button +Cursor(Bx+2, By+2); Text(6, "Click me"); + +OpenMouse; +ShowMouse(true); +Clicks:= 0; +repeat if GetMouseButton(0) then \left button down + [while GetMouseButton(0) do []; \wait for release + Mx:= GetMousePosition(0) / 8; \character coordinates + My:= GetMousePosition(1) / 8; + if Mx>=Bx & Mx<=Bx+Bw & My>=By & My<=By+Bh then + [Clicks:= Clicks+1; \mouse pointer is on the button + Cursor(Wx+4, Wy+3); + Text(6, "Times button has been clicked: "); + IntOut(6, Clicks); + ]; + ]; +until ChkKey; \keystroke terminates program +SetVid(3); \turn off mouse and turn on flashing cursor +] diff --git a/Task/Simple-windowed-application/Yorick/simple-windowed-application.yorick b/Task/Simple-windowed-application/Yorick/simple-windowed-application.yorick new file mode 100644 index 0000000000..095c2f9077 --- /dev/null +++ b/Task/Simple-windowed-application/Yorick/simple-windowed-application.yorick @@ -0,0 +1,22 @@ +#include "button.i" + +window, 0; +btn_click = Button(text="click me", x=.395, y=.65, dx=0.04368, dy=0.0091); +btn_quit = Button(text="quit", x=.395, y=.6, dx=0.02184, dy=0.0091); +count = 0; +msg = "There have been no clicks yet"; +finished = 0; +do { + fma; + plt, msg, .395, .7, justify="CH"; + button_plot, btn_click; + button_plot, btn_quit; + xy = mouse(0, 0, ""); + if(button_test(btn_click, xy(1), xy(2))) { + count++; + msg = swrite(format="Number of clicks: %d", count); + } else if(button_test(btn_quit, xy(1), xy(2))) { + finished = 1; + winkill, 0; + } +} while(!finished); diff --git a/Task/Simulate-input-Keyboard/0DESCRIPTION b/Task/Simulate-input-Keyboard/0DESCRIPTION new file mode 100644 index 0000000000..59a70a86d5 --- /dev/null +++ b/Task/Simulate-input-Keyboard/0DESCRIPTION @@ -0,0 +1,2 @@ +{{Omit From|Modula-3}} +Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them). diff --git a/Task/Simulate-input-Keyboard/1META.yaml b/Task/Simulate-input-Keyboard/1META.yaml new file mode 100644 index 0000000000..b5b7d9296e --- /dev/null +++ b/Task/Simulate-input-Keyboard/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Testing +note: GUI diff --git a/Task/Simulate-input-Keyboard/AutoHotkey/simulate-input-keyboard.ahk b/Task/Simulate-input-Keyboard/AutoHotkey/simulate-input-keyboard.ahk new file mode 100644 index 0000000000..796fbe60d4 --- /dev/null +++ b/Task/Simulate-input-Keyboard/AutoHotkey/simulate-input-keyboard.ahk @@ -0,0 +1,3 @@ +run, cmd /k +WinWait, ahk_class ConsoleWindowClass +controlsend, ,hello console, ahk_class ConsoleWindowClass diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit new file mode 100644 index 0000000000..2702377cfb --- /dev/null +++ b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit @@ -0,0 +1,3 @@ +Run("notepad") +WinWaitActive("Untitled - Notepad") +Send("The answer is 42") diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit new file mode 100644 index 0000000000..88943c1e58 --- /dev/null +++ b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit @@ -0,0 +1,3 @@ +$name="type your name here" +$name = InputBox("Name","Your name please ?",$name) +MsgBox(0,"Name","Your name is: "&$name) diff --git a/Task/Simulate-input-Keyboard/C/simulate-input-keyboard.c b/Task/Simulate-input-Keyboard/C/simulate-input-keyboard.c new file mode 100644 index 0000000000..417a85acf8 --- /dev/null +++ b/Task/Simulate-input-Keyboard/C/simulate-input-keyboard.c @@ -0,0 +1,114 @@ +#include <stdio.h> +#include <stdlib.h> +#include <X11/Xlib.h> +#include <X11/Xutil.h> + +int main(int argc, char *argv[]) +{ + Display *dpy; + Window win; + GC gc; + int scr; + Atom WM_DELETE_WINDOW; + XEvent ev; + XEvent ev2; + KeySym keysym; + int loop; + + /* open connection with the server */ + dpy = XOpenDisplay(NULL); + if (dpy == NULL) { + fputs("Cannot open display", stderr); + exit(1); + } + scr = XDefaultScreen(dpy); + + /* create window */ + win = XCreateSimpleWindow(dpy, + XRootWindow(dpy, scr), + /* x, y, width, height, border_width */ + 10, 10, 300, 200, 1, + /* border, background */ + XBlackPixel(dpy, scr), XWhitePixel(dpy, scr)); + + /* set window name */ + XStoreName(dpy, win, argv[0]); + + /* select kind of events we are interested in */ + XSelectInput(dpy, win, ExposureMask | KeyPressMask | ButtonPressMask); + + /* map (show) the window */ + XMapWindow(dpy, win); + XFlush(dpy); + + /* default graphics context */ + gc = XDefaultGC(dpy, scr); + + /* connect the close button in the window handle */ + WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", True); + XSetWMProtocols(dpy, win, &WM_DELETE_WINDOW, 1); + + /* event loop */ + loop = 1; + while (loop) { + XNextEvent(dpy, &ev); + switch (ev.type) + { + case Expose: + /* draw or redraw the window */ + { + char msg1[] = "Clic in the window to generate"; + char msg2[] = "a key press event"; + XDrawString(dpy, win, gc, 10, 20, msg1, sizeof(msg1)-1); + XDrawString(dpy, win, gc, 10, 35, msg2, sizeof(msg2)-1); + } + break; + + case ButtonPress: + puts("ButtonPress event received"); + /* + printf("> button (x,y) : %d %d\n", + ev.xbutton.x, + ev.xbutton.y); + */ + ev2.type = KeyPress; + ev2.xkey.state = ShiftMask; + ev2.xkey.keycode = 24 + (rand() % 33); + ev2.xkey.same_screen = True; + XSendEvent(dpy, win, True/*propagate*/, KeyPressMask, &ev2); + break; + + case ClientMessage: + /* delete window event */ + if (ev.xclient.data.l[0] == WM_DELETE_WINDOW) + loop = 0; + break; + + case KeyPress: + /* handle key press */ + puts("KeyPress event received"); + printf("> keycode: %d\n", ev.xkey.keycode); + /* exit if q or escape are pressed */ + keysym = XLookupKeysym(&(ev.xkey), 0); + if (keysym == XK_q || + keysym == XK_Escape) { + loop = 0; + } else { + char buffer[] = " "; + int nchars = XLookupString( + &(ev.xkey), + buffer, + 2, /* buffer size */ + &keysym, + NULL ); + if (nchars == 1) + printf("> Key '%c' pressed\n", buffer[0]); + } + break; + } + } + XDestroyWindow(dpy, win); + /* close connection to server */ + XCloseDisplay(dpy); + return 1; +} diff --git a/Task/Simulate-input-Keyboard/Clojure/simulate-input-keyboard.clj b/Task/Simulate-input-Keyboard/Clojure/simulate-input-keyboard.clj new file mode 100644 index 0000000000..0cac4420e4 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Clojure/simulate-input-keyboard.clj @@ -0,0 +1,15 @@ +(import java.awt.Robot) +(import java.awt.KeyEvent) +(defn keytype [str] + (let [robot (new Robot)] + (doseq [ch str] + (if (Character/isUpperCase ch) + (doto robot + (.keyPress (. KeyEvent VK_SHIFT)) + (.keyPress (int ch)) + (.keyRelease (int ch)) + (.keyRelease (. KeyEvent VK_SHIFT))) + (let [upCh (Character/toUpperCase ch)] + (doto robot + (.keyPress (int upCh)) + (.keyRelease (int upCh)))))))) diff --git a/Task/Simulate-input-Keyboard/GUISS/simulate-input-keyboard.guiss b/Task/Simulate-input-Keyboard/GUISS/simulate-input-keyboard.guiss new file mode 100644 index 0000000000..c7d648f61a --- /dev/null +++ b/Task/Simulate-input-Keyboard/GUISS/simulate-input-keyboard.guiss @@ -0,0 +1 @@ +Start,Programs,Accessories,Notepad,Textbox,Type:Hello World[pling] diff --git a/Task/Simulate-input-Keyboard/Java/simulate-input-keyboard.java b/Task/Simulate-input-Keyboard/Java/simulate-input-keyboard.java new file mode 100644 index 0000000000..b3769d20f5 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Java/simulate-input-keyboard.java @@ -0,0 +1,16 @@ +import java.awt.Robot +public static void type(String str){ + Robot robot = new Robot(); + for(char ch:str.toCharArray()){ + if(Character.isUpperCase(ch)){ + robot.keyPress(KeyEvent.VK_SHIFT); + robot.keyPress((int)ch); + robot.keyRelease((int)ch); + robot.keyRelease(KeyEvent.VK_SHIFT); + }else{ + char upCh = Character.toUpperCase(ch); + robot.keyPress((int)upCh); + robot.keyRelease((int)upCh); + } + } +} diff --git a/Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ocaml b/Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ocaml new file mode 100644 index 0000000000..ba2ca808f5 --- /dev/null +++ b/Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ocaml @@ -0,0 +1,105 @@ +open Xlib + +let () = + (* open connection with the server *) + let d = xOpenDisplay "" in + let s = xDefaultScreen d in + + Random.self_init(); + + (* create window *) + let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 300 200 1 + (xBlackPixel d s) (xWhitePixel d s) in + + (* set window name *) + xStoreName d w Sys.argv.(0); + + (* select kind of events we are interested in *) + xSelectInput d w [ExposureMask; KeyPressMask; ButtonPressMask]; + + (* map (show) the window *) + xMapWindow d w; + xFlush d; + + let dbl = w in + let gc = xDefaultGC d s in + + (* connect the close button in the window handle *) + let wm_delete_window = xInternAtom d "WM_DELETE_WINDOW" true in + xSetWMProtocols d w wm_delete_window 1; + + (* event loop *) + let e = new_xEvent() in + try while true do + xNextEvent d e; + + (* draw or redraw the window *) + match xEventKind e with + | XExposeEvent _ -> + xDrawString d dbl gc 10 20 "Clic in the window to generate"; + xDrawString d dbl gc 10 35 "a key press event"; + + | XButtonPressedEvent event -> + let dat = xButtonEvent_datas event in + (* + Printf.printf "button x,y : %d %d\n%!" + dat.button_x + dat.button_y; + *) + let xKeyEvent_contents = { + key_serial = dat.button_serial; + key_send_event = dat.button_send_event; + key_display = dat.button_display; + key_window = dat.button_window; + key_root = dat.button_root; + key_subwindow = dat.button_subwindow; + key_time = dat.button_time; + key_x = dat.button_x; + key_y = dat.button_y; + key_x_root = dat.button_x_root; + key_y_root = dat.button_y_root; + + key_state = [ShiftMask]; + key_keycode = (24 + Random.int 33); + key_same_screen = true; + } in + let propagate = true in + let event_mask = KeyPressMask in + xSendEvent d w propagate event_mask (XKeyPressedEvCnt xKeyEvent_contents); + + (* delete window event *) + | XClientMessageEvent xclient -> + let atom = xEvent_xclient_data xclient in + if atom = wm_delete_window then + raise Exit + + (* handle key press *) + | XKeyPressedEvent event -> + print_endline "Key Pressed Event"; + begin + let d = xKeyEvent_datas event in + Printf.printf "keycode: %d\n%!" d.key_keycode; + end; + (* exit if q or escape are pressed *) + let keysym = xLookupKeysym event 0 in + if keysym = Keysym.xK_q || + keysym = Keysym.xK_Escape then + raise Exit + else + let printable, c = + let buf = " " in + let n, _ = xLookupString event buf in + if (n = 1) + then (true, buf.[0]) + else (false, '\000') + in + if printable then + Printf.printf "Key '%c' pressed\n%!" c; + + | _ -> () + done with + | Exit -> + xDestroyWindow d w; + (* close connection to server *) + xCloseDisplay d; +;; diff --git a/Task/Simulate-input-Keyboard/Oz/simulate-input-keyboard.oz b/Task/Simulate-input-Keyboard/Oz/simulate-input-keyboard.oz new file mode 100644 index 0000000000..4ac409cf2d --- /dev/null +++ b/Task/Simulate-input-Keyboard/Oz/simulate-input-keyboard.oz @@ -0,0 +1,14 @@ +declare + [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']} + Entry + Window = {QTk.build td(entry(handle:Entry))} +in + {Window show} + {Entry getFocus(force:true)} + + for C in "Hello, world!" do + Key = if C == 32 then "<space>" else [C] end + in + {Delay 100} + {Tk.send event(generate Entry Key)} + end diff --git a/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-1.pl b/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-1.pl new file mode 100644 index 0000000000..e27c09b10e --- /dev/null +++ b/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-1.pl @@ -0,0 +1,9 @@ +$target = "/dev/pts/51"; +### How to get the correct value for $TIOCSTI is discussed here : http://www.perlmonks.org/?node_id=10920 +$TIOCSTI = 0x5412 ; +open(TTY,">$target") or die "cannot open $target" ; +$b="sleep 99334 &\015"; +@c=split("",$b); +sleep(2); +foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ; +print "DONE\n"; diff --git a/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-2.pl b/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-2.pl new file mode 100644 index 0000000000..ec7ba172f1 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Perl/simulate-input-keyboard-2.pl @@ -0,0 +1 @@ +SendKeys("Hello, how are you?\n"); diff --git a/Task/Simulate-input-Keyboard/PicoLisp/simulate-input-keyboard.l b/Task/Simulate-input-Keyboard/PicoLisp/simulate-input-keyboard.l new file mode 100644 index 0000000000..e0f8ee9848 --- /dev/null +++ b/Task/Simulate-input-Keyboard/PicoLisp/simulate-input-keyboard.l @@ -0,0 +1,15 @@ +(load "@lib/http.l" "@lib/scrape.l") + +# Connect to the demo app at http://7fach.de/8080 +(scrape "7fach.de" 80 "8080") + +# Log in +(expect "'admin' logged in" + (enter 3 "admin") # Enter user name into 3rd field + (enter 4 "admin") # Enter password into 4th field + (press "login") ) # Press the "login" button + +(click "Items") # Open "Items" dialog +(click "Spare Part") # Click on "Spare Part" article +(prinl (value 8)) # Print the price (12.50) +(click "logout") # Log out diff --git a/Task/Simulate-input-Keyboard/PureBasic/simulate-input-keyboard.purebasic b/Task/Simulate-input-Keyboard/PureBasic/simulate-input-keyboard.purebasic new file mode 100644 index 0000000000..463657c938 --- /dev/null +++ b/Task/Simulate-input-Keyboard/PureBasic/simulate-input-keyboard.purebasic @@ -0,0 +1,3 @@ +If AW_WinActivate("Calc") + AW_SendKeys("123+3=") +EndIf diff --git a/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-1.tcl b/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-1.tcl new file mode 100644 index 0000000000..581e022cc9 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-1.tcl @@ -0,0 +1,2 @@ +set key "x" +event generate $target <Key-$key> diff --git a/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-2.tcl b/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-2.tcl new file mode 100644 index 0000000000..302aa675b4 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Tcl/simulate-input-keyboard-2.tcl @@ -0,0 +1,6 @@ +package require Tk +pack [text .t] +focus -force .t +foreach c [split "hello world" ""] { + event generate .t [expr {$c eq " "?"<space>": $c}] +} diff --git a/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbscript b/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbscript new file mode 100644 index 0000000000..8b17d7601f --- /dev/null +++ b/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbscript @@ -0,0 +1,5 @@ +Dim WshShell +Set WshShell = WScript.CreateObject("WScript.Shell") +WshShell.SendKeys "{Down}{F2}" +WScript.Sleep 1000 ' one-second delay +WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter diff --git a/Task/Simulate-input-Mouse/0DESCRIPTION b/Task/Simulate-input-Mouse/0DESCRIPTION new file mode 100644 index 0000000000..ba9de0d5d2 --- /dev/null +++ b/Task/Simulate-input-Mouse/0DESCRIPTION @@ -0,0 +1,2 @@ +Simulate the click of a mouse button by the user. Specify if the target GUI may be externally created. +{{Omit From|Modula-3}} diff --git a/Task/Simulate-input-Mouse/1META.yaml b/Task/Simulate-input-Mouse/1META.yaml new file mode 100644 index 0000000000..b5b7d9296e --- /dev/null +++ b/Task/Simulate-input-Mouse/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Testing +note: GUI diff --git a/Task/Simulate-input-Mouse/AutoHotkey/simulate-input-mouse.ahk b/Task/Simulate-input-Mouse/AutoHotkey/simulate-input-mouse.ahk new file mode 100644 index 0000000000..678340329c --- /dev/null +++ b/Task/Simulate-input-Mouse/AutoHotkey/simulate-input-mouse.ahk @@ -0,0 +1,6 @@ +WinActivate, ahk_class MozillaUIWindowClass +Click 200, 200 right ; relative to external window (firefox) +sleep, 2000 +WinMinimize +CoordMode, Mouse, Screen +Click 400, 400 right ; relative to top left corner of the screen. diff --git a/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-1.fantom b/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-1.fantom new file mode 100644 index 0000000000..ac817b8943 --- /dev/null +++ b/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-1.fantom @@ -0,0 +1,33 @@ +using fwt +using gfx + +class Main +{ + public static Void main () + { + button1 := Button + { + text = "don't click!" + onAction.add |Event e| + { + echo ("clicked by code") + } + } + button2 := Button + { + text = "click" + onAction.add |Event e| + { + // fire all the event listeners on button1 + button1.onAction.fire(e) + } + } + Window + { + title = "simulate mouse event" + size = Size (300, 200) + button1, + button2, + }.open + } +} diff --git a/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-2.fantom b/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-2.fantom new file mode 100644 index 0000000000..f91b0fe9ba --- /dev/null +++ b/Task/Simulate-input-Mouse/Fantom/simulate-input-mouse-2.fantom @@ -0,0 +1,28 @@ +using [java] java.awt::Robot +using [java] java.awt.event::InputEvent +using fwt +using gfx + +class Main +{ + public static Void main () + { + button := Button + { + text = "click for robot" + onAction.add |Event e| + { + robot := Robot () + robot.mouseMove (50, 50) // move to screen point 50, 50 + robot.mousePress (InputEvent.BUTTON1_MASK) // and click mouse + robot.mouseRelease (InputEvent.BUTTON1_MASK) + } + } + Window + { + title = "simulate mouse event" + size = Size (300, 200) + button, + }.open + } +} diff --git a/Task/Simulate-input-Mouse/GUISS/simulate-input-mouse.guiss b/Task/Simulate-input-Mouse/GUISS/simulate-input-mouse.guiss new file mode 100644 index 0000000000..cafb0464fc --- /dev/null +++ b/Task/Simulate-input-Mouse/GUISS/simulate-input-mouse.guiss @@ -0,0 +1,2 @@ +Start,Programs,Accessories,Notepad,Textbox,Type:Hello World[pling],Menu:File,Save, +Inputbox:filename>greetings.txt,Button:Save diff --git a/Task/Simulate-input-Mouse/Java/simulate-input-mouse-1.java b/Task/Simulate-input-Mouse/Java/simulate-input-mouse-1.java new file mode 100644 index 0000000000..3f5ecd0ddf --- /dev/null +++ b/Task/Simulate-input-Mouse/Java/simulate-input-mouse-1.java @@ -0,0 +1,6 @@ +Point p = component.getLocation(); +Robot robot = new Robot(); +robot.mouseMove(p.getX(), p.getY()); //you may want to move a few pixels closer to the center by adding to these values +robot.mousePress(InputEvent.BUTTON1_MASK); //BUTTON1_MASK is the left button, + //BUTTON2_MASK is the middle button, BUTTON3_MASK is the right button +robot.mouseRelease(InputEvent.BUTTON1_MASK); diff --git a/Task/Simulate-input-Mouse/Java/simulate-input-mouse-2.java b/Task/Simulate-input-Mouse/Java/simulate-input-mouse-2.java new file mode 100644 index 0000000000..35d83d9a18 --- /dev/null +++ b/Task/Simulate-input-Mouse/Java/simulate-input-mouse-2.java @@ -0,0 +1 @@ +button.doClick(); //optionally, give an integer argument for the number of milliseconds to hold the button down diff --git a/Task/Simulate-input-Mouse/Oz/simulate-input-mouse.oz b/Task/Simulate-input-Mouse/Oz/simulate-input-mouse.oz new file mode 100644 index 0000000000..d68a7a4f84 --- /dev/null +++ b/Task/Simulate-input-Mouse/Oz/simulate-input-mouse.oz @@ -0,0 +1,10 @@ +declare + [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']} + Button + Window = {QTk.build td(button(text:"Click me" handle:Button))} +in + {Window show} + {Delay 500} + {Tk.send event(generate Button "<ButtonPress-1>")} + {Delay 500} + {Tk.send event(generate Button "<ButtonRelease-1>")} diff --git a/Task/Simulate-input-Mouse/PicoLisp/simulate-input-mouse.l b/Task/Simulate-input-Mouse/PicoLisp/simulate-input-mouse.l new file mode 100644 index 0000000000..e0f8ee9848 --- /dev/null +++ b/Task/Simulate-input-Mouse/PicoLisp/simulate-input-mouse.l @@ -0,0 +1,15 @@ +(load "@lib/http.l" "@lib/scrape.l") + +# Connect to the demo app at http://7fach.de/8080 +(scrape "7fach.de" 80 "8080") + +# Log in +(expect "'admin' logged in" + (enter 3 "admin") # Enter user name into 3rd field + (enter 4 "admin") # Enter password into 4th field + (press "login") ) # Press the "login" button + +(click "Items") # Open "Items" dialog +(click "Spare Part") # Click on "Spare Part" article +(prinl (value 8)) # Print the price (12.50) +(click "logout") # Log out diff --git a/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-1.purebasic b/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-1.purebasic new file mode 100644 index 0000000000..a20812d1fc --- /dev/null +++ b/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-1.purebasic @@ -0,0 +1,13 @@ +Macro Click() + mouse_event_(#MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) + mouse_event_(#MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) +EndMacro + +; Click at the current location +Click() + +Delay(1000) ; Wait a second + +; Move to a new location and click it +SetCursorPos_(50, 50) +Click() diff --git a/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-2.purebasic b/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-2.purebasic new file mode 100644 index 0000000000..fe85fbc005 --- /dev/null +++ b/Task/Simulate-input-Mouse/PureBasic/simulate-input-mouse-2.purebasic @@ -0,0 +1,4 @@ +; The same function as above, but using AutoWin UserLibray +AW_MouseClick() +Delay(1000) +AW_MouseClick(#PB_MouseButton_Left, 50, 50) diff --git a/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-1.tcl b/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-1.tcl new file mode 100644 index 0000000000..48417e87b5 --- /dev/null +++ b/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-1.tcl @@ -0,0 +1,3 @@ +# Simulate a full click cycle: button down and up +event generate .okBtn <ButtonPress-1> -x 5 -y 5 +event generate .okBtn <ButtonRelease-1> -x 5 -y 5 diff --git a/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-2.tcl b/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-2.tcl new file mode 100644 index 0000000000..58c611321f --- /dev/null +++ b/Task/Simulate-input-Mouse/Tcl/simulate-input-mouse-2.tcl @@ -0,0 +1 @@ +.okBtn invoke diff --git a/Task/Singleton/0DESCRIPTION b/Task/Singleton/0DESCRIPTION new file mode 100644 index 0000000000..a8644a830c --- /dev/null +++ b/Task/Singleton/0DESCRIPTION @@ -0,0 +1 @@ +A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance. diff --git a/Task/Singleton/1META.yaml b/Task/Singleton/1META.yaml new file mode 100644 index 0000000000..43afe9a8b6 --- /dev/null +++ b/Task/Singleton/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Object oriented diff --git a/Task/Singleton/ActionScript/singleton.as b/Task/Singleton/ActionScript/singleton.as new file mode 100644 index 0000000000..2b66c3d4fd --- /dev/null +++ b/Task/Singleton/ActionScript/singleton.as @@ -0,0 +1,20 @@ +package +{ + public class Singleton + { + + private static var instance:Singleton; + + // ActionScript does not allow private or protected constructors. + public function Singleton(enforcer:SingletonEnforcer) { + + } + + public static function getInstance():Singleton { + if (instance == null) instance = new Singleton(new SingletonEnforcer()); + return instance; + } + } +} + +internal class SingletonEnforcer {} diff --git a/Task/Singleton/Ada/singleton-1.ada b/Task/Singleton/Ada/singleton-1.ada new file mode 100644 index 0000000000..26b7570502 --- /dev/null +++ b/Task/Singleton/Ada/singleton-1.ada @@ -0,0 +1,10 @@ +package Global_Singleton is + procedure Set_Data (Value : Integer); + function Get_Data return Integer; +private + type Instance_Type is record + -- Define instance data elements + Data : Integer := 0; + end record; + Instance : Instance_Type; +end Global_Singleton; diff --git a/Task/Singleton/Ada/singleton-2.ada b/Task/Singleton/Ada/singleton-2.ada new file mode 100644 index 0000000000..346b248e61 --- /dev/null +++ b/Task/Singleton/Ada/singleton-2.ada @@ -0,0 +1,21 @@ +package body Global_Singleton is + + -------------- + -- Set_Data -- + -------------- + + procedure Set_Data (Value : Integer) is + begin + Instance.Data := Value; + end Set_Data; + + -------------- + -- Get_Data -- + -------------- + + function Get_Data return Integer is + begin + return Instance.Data; + end Get_Data; + +end Global_Singleton; diff --git a/Task/Singleton/Ada/singleton-3.ada b/Task/Singleton/Ada/singleton-3.ada new file mode 100644 index 0000000000..d4d73a121b --- /dev/null +++ b/Task/Singleton/Ada/singleton-3.ada @@ -0,0 +1,11 @@ +package Protected_Singleton is + procedure Set_Data (Value : Integer); + function Get_Data return Integer; +private + protected Instance is + procedure Set(Value : Integer); + function Get return Integer; + private + Data : Integer := 0; + end Instance_Type; +end Protected_Singleton; diff --git a/Task/Singleton/Ada/singleton-4.ada b/Task/Singleton/Ada/singleton-4.ada new file mode 100644 index 0000000000..6475ab6e72 --- /dev/null +++ b/Task/Singleton/Ada/singleton-4.ada @@ -0,0 +1,47 @@ +package body Protected_Singleton is + + -------------- + -- Set_Data -- + -------------- + + procedure Set_Data (Value : Integer) is + begin + Instance.Set(Value); + end Set_Data; + + -------------- + -- Get_Data -- + -------------- + + function Get_Data return Integer is + begin + return Instance.Get; + end Get_Data; + + -------------- + -- Instance -- + -------------- + + protected body Instance is + + --------- + -- Set -- + --------- + + procedure Set (Value : Integer) is + begin + Data := Value; + end Set; + + --------- + -- Get -- + --------- + + function Get return Integer is + begin + return Data; + end Get; + + end Instance; + +end Protected_Singleton; diff --git a/Task/Singleton/AutoHotkey/singleton.ahk b/Task/Singleton/AutoHotkey/singleton.ahk new file mode 100644 index 0000000000..ef1233d726 --- /dev/null +++ b/Task/Singleton/AutoHotkey/singleton.ahk @@ -0,0 +1,28 @@ +b1 := borg() +b2 := borg() +msgbox % "b1 is b2? " . (b1 == b2) +b1.datum := 3 +msgbox % "b1.datum := 3`n...`nb1 datum: " b1.datum "`nb2 datum: " b2.datum ; is 3 also +msgbox % "b1.datum is b2.datum ? " (b1.datum == b2.datum) +return + + +borg(){ + static borg + If !borg + borg := Object("__Set", "Borg_Set" + , "__Get", "Borg_Get") + return object(1, borg, "base", borg) +} + + +Borg_Get(brg, name) +{ + Return brg[1, name] +} + +Borg_Set(brg, name, val) +{ + brg[1, name] := val + Return val +} diff --git a/Task/Singleton/C++/singleton-1.cpp b/Task/Singleton/C++/singleton-1.cpp new file mode 100644 index 0000000000..2a97fe1426 --- /dev/null +++ b/Task/Singleton/C++/singleton-1.cpp @@ -0,0 +1,38 @@ +class Singleton +{ +public: + static Singleton* Instance() + { + // We need to ensure that we don't accidentally create two Singletons + HANDLE hMutex = CreateMutex(NULL, FALSE, "MySingletonMutex"); + WaitForSingleObject(hMutex, INFINITE); + + // Create the instance of the class. + // Since it's a static variable, if the class has already been created, + // It won't be created again. + static Singleton myInstance; + + // Release our mutex so that other application threads can use this function + ReleaseMutex( hMutex ); + + // Free the handle + CloseHandle( hMutex ); + + // Return a pointer to our mutex instance. + return &myInstance; + } + + // Any other public methods + +protected: + Singleton() + { + // Constructor code goes here. + } + ~Singleton() + { + // Destructor code goes here. + } + + // And any other protected methods. +} diff --git a/Task/Singleton/C++/singleton-2.cpp b/Task/Singleton/C++/singleton-2.cpp new file mode 100644 index 0000000000..ff52ce3270 --- /dev/null +++ b/Task/Singleton/C++/singleton-2.cpp @@ -0,0 +1,27 @@ +class Singleton +{ +public: + static Singleton* Instance() + { + // Since it's a static variable, if the class has already been created, + // It won't be created again. + static Singleton myInstance; + + // Return a pointer to our mutex instance. + return &myInstance; + } + + // Any other public methods + +protected: + Singleton() + { + // Constructor code goes here. + } + ~Singleton() + { + // Destructor code goes here. + } + + // And any other protected methods. +} diff --git a/Task/Singleton/C/singleton-1.c b/Task/Singleton/C/singleton-1.c new file mode 100644 index 0000000000..22820868d2 --- /dev/null +++ b/Task/Singleton/C/singleton-1.c @@ -0,0 +1,7 @@ +#ifndef SILLY_H +#define SILLY_H + +extern void JumpOverTheDog( int numberOfTimes); +extern int PlayFetchWithDog( float weightOfStick); + +#endif diff --git a/Task/Singleton/C/singleton-2.c b/Task/Singleton/C/singleton-2.c new file mode 100644 index 0000000000..18e9019b5c --- /dev/null +++ b/Task/Singleton/C/singleton-2.c @@ -0,0 +1,25 @@ +... +#include "silly.h" + +struct sDog { + float max_stick_weight; + int isTired; + int isAnnoyed; +}; + +static struct sDog lazyDog = { 4.0, 0,0 }; + +/* define functions used by the functions in header as static */ +static int RunToStick( ) +{... +} +/* define functions declared in the header file. */ + +void JumpOverTheDog(int numberOfTimes) +{ ... + lazyDog.isAnnoyed = TRUE; +} +int PlayFetchWithDog( float weightOfStick ) +{ ... + if(weightOfStick < lazyDog.max_stick_weight){... +} diff --git a/Task/Singleton/C/singleton-3.c b/Task/Singleton/C/singleton-3.c new file mode 100644 index 0000000000..61dc8921fd --- /dev/null +++ b/Task/Singleton/C/singleton-3.c @@ -0,0 +1,7 @@ +... +#include "silly.h" +... +/* code using the dog methods */ + JumpOverTheDog( 4); + retrieved = PlayFetchWithDog( 3.1); +... diff --git a/Task/Singleton/Common-Lisp/singleton.lisp b/Task/Singleton/Common-Lisp/singleton.lisp new file mode 100644 index 0000000000..2f1514c714 --- /dev/null +++ b/Task/Singleton/Common-Lisp/singleton.lisp @@ -0,0 +1,24 @@ +(defgeneric concat (a b) + (:documentation "Concatenate two phrases.")) + +(defclass nonempty-phrase () + ((text :initarg :text :reader text))) + +(defmethod concat ((a nonempty-phrase) (b nonempty-phrase)) + (make-instance 'nonempty-phrase :text (concatenate 'string (text a) " " (text b)))) + +(defmethod concat ((a (eql 'the-empty-phrase)) b) + b) + +(defmethod concat (a (b (eql 'the-empty-phrase))) + a) + +(defun example () + (let ((before (make-instance 'nonempty-phrase :text "Jack")) + (mid (make-instance 'nonempty-phrase :text "went")) + (after (make-instance 'nonempty-phrase :text "to fetch a pail of water"))) + (dolist (p (list 'the-empty-phrase + (make-instance 'nonempty-phrase :text "and Jill"))) + (dolist (q (list 'the-empty-phrase + (make-instance 'nonempty-phrase :text "up the hill"))) + (write-line (text (reduce #'concat (list before p mid q after)))))))) diff --git a/Task/Singleton/D/singleton.d b/Task/Singleton/D/singleton.d new file mode 100644 index 0000000000..16506d0ac0 --- /dev/null +++ b/Task/Singleton/D/singleton.d @@ -0,0 +1,61 @@ +module singleton ; +import std.stdio ; +import std.thread ; +import std.random ; +import std.c.time ; + +class Dealer { + private static Dealer me ; + static Dealer Instance() { + writefln(" Calling Dealer... ") ; + if(me is null) // Double Checked Lock + synchronized // this part of code can only be executed by one thread a time + if(me is null) + me = new Dealer ; + return me ; + } + private static string[] str = ["(1)Enjoy", "(2)Rosetta", "(3)Code"] ; + private int state ; + private this() { + for(int i = 0 ; i < 3 ; i++) { + writefln("...calling Dealer... ") ; + msleep(rand() & 2047) ; + } + writefln(">>Dealer is called to come in!") ; + state = str.length - 1 ; + } + Dealer nextState() { + synchronized(this) // accessed to Object _this_ is locked ... is it necessary ??? + state = (state + 1) % str.length ; + return this ; + } + string toString() { return str[state] ; } +} + +class Coder : Thread { + private string name_ ; + Coder hasName(string name) { name_ = name ; return this ; } + override int run() { + msleep(rand() & 1023) ; + writefln(">>%s come in.", name_) ; + Dealer single = Dealer.Instance ; + msleep(rand() & 1023) ; + for(int i = 0 ; i < 3 ; i++) { + writefln("%9s got %-s", name_, single.nextState) ; + msleep(rand() & 1023) ; + } + return 0 ; + } +} + +void main() { + Coder x = new Coder ; + Coder y = new Coder ; + Coder z = new Coder ; + + x.hasName("Peter").start() ; + y.hasName("Paul").start() ; + z.hasName("Mary").start() ; + + x.wait ; y.wait ; z.wait ; +} diff --git a/Task/Singleton/Delphi/singleton.delphi b/Task/Singleton/Delphi/singleton.delphi new file mode 100644 index 0000000000..e52b0f0178 --- /dev/null +++ b/Task/Singleton/Delphi/singleton.delphi @@ -0,0 +1,40 @@ +unit Singleton; + +interface + +type + TSingleton = class + private + //Private fields and methods here... + + class var _instance: TSingleton; + protected + //Other protected methods here... + public + //Global point of access to the unique instance + class function Create: TSingleton; + + destructor Destroy; override; + + //Other public methods and properties here... + end; + +implementation + +{ TSingleton } + +class function TSingleton.Create: TSingleton; +begin + if (_instance = nil) then + _instance:= inherited Create as Self; + + result:= _instance; +end; + +destructor TSingleton.Destroy; +begin + _instance:= nil; + inherited; +end; + +end. diff --git a/Task/Singleton/E/singleton.e b/Task/Singleton/E/singleton.e new file mode 100644 index 0000000000..77e6c08eaa --- /dev/null +++ b/Task/Singleton/E/singleton.e @@ -0,0 +1,3 @@ +def aSingleton { + # ... +} diff --git a/Task/Singleton/Erlang/singleton-1.erl b/Task/Singleton/Erlang/singleton-1.erl new file mode 100644 index 0000000000..2fb3ff814f --- /dev/null +++ b/Task/Singleton/Erlang/singleton-1.erl @@ -0,0 +1,33 @@ +-module(singleton). + +-export([get/0, set/1, start/0]). + +-export([loop/1]). + +% spec singleton:get() -> {ok, Value::any()} | not_set +get() -> + ?MODULE ! {get, self()}, + receive + {ok, not_set} -> not_set; + Answer -> Answer + end. + +% spec singleton:set(Value::any()) -> ok +set(Value) -> + ?MODULE ! {set, self(), Value}, + receive + ok -> ok + end. + +start() -> + register(?MODULE, spawn(?MODULE, loop, [not_set])). + +loop(Value) -> + receive + {get, From} -> + From ! {ok, Value}, + loop(Value); + {set, From, NewValue} -> + From ! ok, + loop(NewValue) + end. diff --git a/Task/Singleton/Erlang/singleton-2.erl b/Task/Singleton/Erlang/singleton-2.erl new file mode 100644 index 0000000000..f4cf252a46 --- /dev/null +++ b/Task/Singleton/Erlang/singleton-2.erl @@ -0,0 +1,14 @@ +1> singleton:get(). +not_set +2> singleton:set(apple). +ok +3> singleton:get(). +{ok,apple} +4> singleton:set("Pear"). +ok +5> singleton:get(). +{ok,"Pear"} +6> singleton:set(42). +ok +7> singleton:get(). +{ok,42} diff --git a/Task/Singleton/Factor/singleton.factor b/Task/Singleton/Factor/singleton.factor new file mode 100644 index 0000000000..b8ff91b667 --- /dev/null +++ b/Task/Singleton/Factor/singleton.factor @@ -0,0 +1,6 @@ +USING: classes.singleton kernel io prettyprint ; +IN: singleton-demo + +SINGLETON: bar +GENERIC: foo ( obj -- ) +M: bar foo drop "Hello!" print ; diff --git a/Task/Singleton/Go/singleton-1.go b/Task/Singleton/Go/singleton-1.go new file mode 100644 index 0000000000..5e94b7c4ba --- /dev/null +++ b/Task/Singleton/Go/singleton-1.go @@ -0,0 +1,9 @@ +package singlep + +// package level data declarations serve as singleton instance variables +var X, Y int + +// package level functions serve as methods for a package-as-a-singleton +func F() int { + return Y - X +} diff --git a/Task/Singleton/Go/singleton-2.go b/Task/Singleton/Go/singleton-2.go new file mode 100644 index 0000000000..1083915911 --- /dev/null +++ b/Task/Singleton/Go/singleton-2.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "singlep" +) + +func main() { + // dot selector syntax references package variables and functions + singlep.X = 2 + singlep.Y = 3 + fmt.Println(singlep.X, singlep.Y) + fmt.Println(singlep.F()) +} diff --git a/Task/Singleton/Groovy/singleton-1.groovy b/Task/Singleton/Groovy/singleton-1.groovy new file mode 100644 index 0000000000..0bb337824d --- /dev/null +++ b/Task/Singleton/Groovy/singleton-1.groovy @@ -0,0 +1,11 @@ +@Singleton +class SingletonClass { + + def invokeMe() { + println 'invoking method of a singleton class' + } + + static void main(def args) { + SingletonClass.instance.invokeMe() + } +} diff --git a/Task/Singleton/Groovy/singleton-2.groovy b/Task/Singleton/Groovy/singleton-2.groovy new file mode 100644 index 0000000000..91474374e3 --- /dev/null +++ b/Task/Singleton/Groovy/singleton-2.groovy @@ -0,0 +1,13 @@ +class Singleton + method print() + write("Hi there.") + end + initially + write("In constructor!") + Singleton := create |self +end + +procedure main() + Singleton().print() + Singleton().print() +end diff --git a/Task/Singleton/Io/singleton.io b/Task/Singleton/Io/singleton.io new file mode 100644 index 0000000000..f5c694403f --- /dev/null +++ b/Task/Singleton/Io/singleton.io @@ -0,0 +1,2 @@ +Singleton := Object clone +Singleton clone = Singleton diff --git a/Task/Singleton/Java/singleton-1.java b/Task/Singleton/Java/singleton-1.java new file mode 100644 index 0000000000..e12dcecea3 --- /dev/null +++ b/Task/Singleton/Java/singleton-1.java @@ -0,0 +1,26 @@ +class Singleton +{ + private static Singleton myInstance; + public static Singleton getInstance() + { + if (myInstance == null) + { + synchronized(Singleton.class) + { + if (myInstance == null) + { + myInstance = new Singleton(); + } + } + } + + return myInstance; + } + + protected Singleton() + { + // Constructor code goes here. + } + + // Any other methods +} diff --git a/Task/Singleton/Java/singleton-2.java b/Task/Singleton/Java/singleton-2.java new file mode 100644 index 0000000000..988f5eef53 --- /dev/null +++ b/Task/Singleton/Java/singleton-2.java @@ -0,0 +1,20 @@ +class Singleton +{ + private static Singleton myInstance; + public static Singleton getInstance() + { + if (myInstance == null) + { + myInstance = new Singleton(); + } + + return myInstance; + } + + protected Singleton() + { + // Constructor code goes here. + } + + // Any other methods +} diff --git a/Task/Singleton/JavaScript/singleton.js b/Task/Singleton/JavaScript/singleton.js new file mode 100644 index 0000000000..220d260329 --- /dev/null +++ b/Task/Singleton/JavaScript/singleton.js @@ -0,0 +1,20 @@ +function Singleton() { + if(Singleton._instance) return Singleton._instance; + this.set(""); + Singleton._instance = this; +} + +Singleton.prototype.set = function(msg) { this.msg = msg; } +Singleton.prototype.append = function(msg) { this.msg += msg; } +Singleton.prototype.get = function() { return this.msg; } + + +var a = new Singleton(); +var b = new Singleton(); +var c = new Singleton(); + +a.set("Hello"); +b.append(" World"); +c.append("!!!"); + +document.write( (new Singleton()).get() ); diff --git a/Task/Singleton/Logtalk/singleton-1.logtalk b/Task/Singleton/Logtalk/singleton-1.logtalk new file mode 100644 index 0000000000..53fbce4b13 --- /dev/null +++ b/Task/Singleton/Logtalk/singleton-1.logtalk @@ -0,0 +1,16 @@ +:- object(singleton). + + :- public(value/1). + value(Value) :- + state(Value). + + :- public(set_value/1). + set_value(Value) :- + retract(state(_)), + assertz(state(Value)). + + :- private(state/1). + :- dynamic(state/1). + state(0). + +:- end_object. diff --git a/Task/Singleton/Logtalk/singleton-2.logtalk b/Task/Singleton/Logtalk/singleton-2.logtalk new file mode 100644 index 0000000000..bced2aaa89 --- /dev/null +++ b/Task/Singleton/Logtalk/singleton-2.logtalk @@ -0,0 +1,7 @@ +| ?- singleton::value(Value). +Value = 0 +yes + +| ?- singleton::(set_value(1), value(Value)). +Value = 1 +yes diff --git a/Task/Singleton/NetRexx/singleton.netrexx b/Task/Singleton/NetRexx/singleton.netrexx new file mode 100644 index 0000000000..d44fe1cf34 --- /dev/null +++ b/Task/Singleton/NetRexx/singleton.netrexx @@ -0,0 +1,97 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import java.util.random + +class RCSingleton public + + method main(args = String[]) public static + RCSingleton.Testcase.main(args) + return + + -- --------------------------------------------------------------------------- + class RCSingleton.Instance public + + properties private static + _instance = Instance() + + properties private + _refCount = int + _random = Random + + method Instance() private + this._refCount = 0 + this._random = Random() + return + + method getInstance public static returns RCSingleton.Instance + return _instance + + method getRandom public returns Random + return _random + + method addRef public protect + _refCount = _refCount + 1 + return + + method release public protect + if _refCount > 0 then + _refCount = _refCount - 1 + return + + method getRefCount public protect returns int + return _refCount + + -- --------------------------------------------------------------------------- + class RCSingleton.Testcase public implements Runnable + + properties private + _instance = RCSingleton.Instance + + method run public + say threadInfo'|-' + thud = Thread.currentThread + _instance = RCSingleton.Instance.getInstance + thud.yield + _instance.addRef + say threadInfo'|'_instance.getRefCount + thud.yield + do + thud.sleep(_instance.getRandom.nextInt(1000)) + catch ex = InterruptedException + ex.printStackTrace + end + _instance.release + say threadInfo'|'_instance.getRefCount + return + + method main(args = String[]) public static + threads = [ Thread - + Thread(Testcase()), Thread(Testcase()), Thread(Testcase()), - + Thread(Testcase()), Thread(Testcase()), Thread(Testcase()) ] + say threadInfo'|-' + mn = Testcase() + mn._instance = RCSingleton.Instance.getInstance + say mn.threadInfo'|'mn._instance.getRefCount + mn._instance.addRef + say mn.threadInfo'|'mn._instance.getRefCount + do + loop tr over threads + (Thread tr).start + end tr + Thread.sleep(400) + catch ex = InterruptedException + ex.printStackTrace + end + mn._instance.release + say mn.threadInfo'|'mn._instance.getRefCount + return + + method threadInfo public static returns String + trd = Thread.currentThread + tid = trd.getId + hc = trd.hashCode + info = Rexx(trd.getName).left(16, '_')':' - + || Rexx(Long.toString(tid)).right(10, 0)':' - + || '@'Rexx(Integer.toHexString(hc)).right(8, 0) + return info diff --git a/Task/Singleton/Objeck/singleton.objeck b/Task/Singleton/Objeck/singleton.objeck new file mode 100644 index 0000000000..d3814a39dc --- /dev/null +++ b/Task/Singleton/Objeck/singleton.objeck @@ -0,0 +1,18 @@ +class Singleton { + @singleton : static : Singleton; + + New : private () { + } + + function : GetInstance() ~ Singleton { + if(@singleton <> Nil) { + @singleton := Singleton->New(); + }; + + return @singleton; + } + + method : public : DoStuff() ~ Nil { + ... + } +} diff --git a/Task/Singleton/Objective-C/singleton-1.m b/Task/Singleton/Objective-C/singleton-1.m new file mode 100644 index 0000000000..28aa2a11ca --- /dev/null +++ b/Task/Singleton/Objective-C/singleton-1.m @@ -0,0 +1,9 @@ +// SomeSingleton.h +@interface SomeSingleton : NSObject +{ + // any instance variables +} + ++ (SomeSingleton*)sharedInstance; + +@end diff --git a/Task/Singleton/Objective-C/singleton-2.m b/Task/Singleton/Objective-C/singleton-2.m new file mode 100644 index 0000000000..6c8b8cf99b --- /dev/null +++ b/Task/Singleton/Objective-C/singleton-2.m @@ -0,0 +1,38 @@ +// SomeSingleton.m +@implementation SomeSingleton + ++ (SomeSingleton*) sharedInstance +{ + static sharedInstance = nil; + if(!sharedInstance) { + sharedInstance = [[SomeSingleton alloc] init]; + } + return sharedInstance; +} + +- (id)copyWithZone:(NSZone *)zone +{ + return self; +} + +- (id)retain +{ + return self; +} + +- (unsigned)retainCount +{ + return UINT_MAX; +} + +- (void)release +{ + // prevent release +} + +- (id)autorelease +{ + return self; +} + +@end diff --git a/Task/Singleton/OxygenBasic/singleton.oxy b/Task/Singleton/OxygenBasic/singleton.oxy new file mode 100644 index 0000000000..ed080f8423 --- /dev/null +++ b/Task/Singleton/OxygenBasic/singleton.oxy @@ -0,0 +1,14 @@ +class singleton +static sys a,b,c +static string s,t,u +static double x,y,z +end class + +'TEST +'==== + +singleton A +singleton B +A.c=3 +print B.c 'result 3 +print sizeof B 'result 0 diff --git a/Task/Singleton/Oz/singleton.oz b/Task/Singleton/Oz/singleton.oz new file mode 100644 index 0000000000..66e76f3a13 --- /dev/null +++ b/Task/Singleton/Oz/singleton.oz @@ -0,0 +1,19 @@ +declare + local + class Singleton + meth init + skip + end + end + L = {NewLock} + Instance + in + fun {GetInstance} + lock L then + if {IsFree Instance} then + Instance = {New Singleton init} + end + Instance + end + end + end diff --git a/Task/Singleton/PHP/singleton.php b/Task/Singleton/PHP/singleton.php new file mode 100644 index 0000000000..fd22828285 --- /dev/null +++ b/Task/Singleton/PHP/singleton.php @@ -0,0 +1,21 @@ +class Singleton { + protected static $instance = null; + public $test_var; + private function __construct(){ + //Any constructor code + } + public static function getInstance(){ + if (is_null(self::$instance)){ + self::$instance = new self(); + } + return self::$instance; + } +} + +$foo = Singleton::getInstance(); +$foo->test_var = 'One'; + +$bar = Singleton::getInstance(); +echo $bar->test_var; //Prints 'One' + +$fail = new Singleton(); //Fatal error diff --git a/Task/Singleton/Perl-6/singleton.pl6 b/Task/Singleton/Perl-6/singleton.pl6 new file mode 100644 index 0000000000..b14e1c13c9 --- /dev/null +++ b/Task/Singleton/Perl-6/singleton.pl6 @@ -0,0 +1,6 @@ +class Singleton { + # We create a lexical variable in the class block that holds our single instance. + my Singleton $instance = Singleton.bless(*); # You can add initialization arguments here. + method new {!!!} # Singleton.new dies. + method instance { $instance; } +} diff --git a/Task/Singleton/Perl/singleton.pl b/Task/Singleton/Perl/singleton.pl new file mode 100644 index 0000000000..8779f84e65 --- /dev/null +++ b/Task/Singleton/Perl/singleton.pl @@ -0,0 +1,29 @@ +package Singleton; +use strict; +use warnings; + +my $Instance; + +sub new { + my $class = shift; + $Instance ||= bless {}, $class; # initialised once only +} + +sub name { + my $self = shift; + $self->{name}; +} + +sub set_name { + my ($self, $name) = @_; + $self->{name} = $name; +} + +package main; + +my $s1 = Singleton->new; +$s1->set_name('Bob'); +printf "name: %s, ref: %s\n", $s1->name, $s1; + +my $s2 = Singleton->new; +printf "name: %s, ref: %s\n", $s2->name, $s2; diff --git a/Task/Singleton/PicoLisp/singleton.l b/Task/Singleton/PicoLisp/singleton.l new file mode 100644 index 0000000000..e45108f738 --- /dev/null +++ b/Task/Singleton/PicoLisp/singleton.l @@ -0,0 +1,7 @@ +(class +Singleton) + +(dm message1> () + (prinl "This is method 1 on " This) ) + +(dm message2> () + (prinl "This is method 2 on " This) ) diff --git a/Task/Singleton/PureBasic/singleton-1.purebasic b/Task/Singleton/PureBasic/singleton-1.purebasic new file mode 100644 index 0000000000..56fcd95777 --- /dev/null +++ b/Task/Singleton/PureBasic/singleton-1.purebasic @@ -0,0 +1,48 @@ +Global SingletonSemaphore=CreateSemaphore(1) + +Interface OO_Interface ; Interface for any value of this type + Get.i() + Set(Value.i) + Destroy() +EndInterface + +Structure OO_Structure ; The *VTable structure + Get.i + Set.i + Destroy.i +EndStructure + +Structure OO_Var + *VirtualTable.OO_Structure + Value.i +EndStructure + +Procedure OO_Get(*Self.OO_Var) + ProcedureReturn *Self\Value +EndProcedure + +Procedure OO_Set(*Self.OO_Var, n) + *Self\Value = n +EndProcedure + +Procedure CreateSingleton() + If TrySemaphore(SingletonSemaphore) + *p.OO_Var = AllocateMemory(SizeOf(OO_Var)) + If *p + *p\VirtualTable = ?VTable + EndIf + EndIf + ProcedureReturn *p +EndProcedure + +Procedure OO_Destroy(*Self.OO_Var) + FreeMemory(*Self) + SignalSemaphore(SingletonSemaphore) +EndProcedure + +DataSection + VTable: + Data.i @OO_Get() + Data.i @OO_Set() + Data.i @OO_Destroy() +EndDataSection diff --git a/Task/Singleton/PureBasic/singleton-2.purebasic b/Task/Singleton/PureBasic/singleton-2.purebasic new file mode 100644 index 0000000000..c4901c49a3 --- /dev/null +++ b/Task/Singleton/PureBasic/singleton-2.purebasic @@ -0,0 +1,23 @@ +Singleton Class Demo + BeginPrivate + Name$ + X.i + EndPrivate + + Public Method Init(Name$) + This\Name$ = Name$ + EndMethod + + Public Method GetX() + MethodReturn This\X + EndMethod + + Public Method SetX(n) + This\X = n + EndMethod + + Public Method Hello() + MessageRequester("Hello!", "I'm "+This\Name$) + EndMethod + +EndClass diff --git a/Task/Singleton/Python/singleton.py b/Task/Singleton/Python/singleton.py new file mode 100644 index 0000000000..1507d1d626 --- /dev/null +++ b/Task/Singleton/Python/singleton.py @@ -0,0 +1,19 @@ +>>> class Borg(object): + __state = {} + def __init__(self): + self.__dict__ = self.__state + # Any other class names/methods + + +>>> b1 = Borg() +>>> b2 = Borg() +>>> b1 is b2 +False +>>> b1.datum = range(5) +>>> b1.datum +[0, 1, 2, 3, 4] +>>> b2.datum +[0, 1, 2, 3, 4] +>>> b1.datum is b2.datum +True +>>> # For any datum! diff --git a/Task/Singleton/Racket/singleton.rkt b/Task/Singleton/Racket/singleton.rkt new file mode 100644 index 0000000000..80b86f4895 --- /dev/null +++ b/Task/Singleton/Racket/singleton.rkt @@ -0,0 +1,9 @@ +#lang racket + +(provide instance) + +(define singleton% + (class object% + (super-new))) + +(define instance (new singleton%)) diff --git a/Task/Singleton/Ruby/singleton.rb b/Task/Singleton/Ruby/singleton.rb new file mode 100644 index 0000000000..09a719bb21 --- /dev/null +++ b/Task/Singleton/Ruby/singleton.rb @@ -0,0 +1,9 @@ +require 'singleton' +class MySingleton + include Singleton + # constructor and/or methods go here +end + +a = MySingleton.instance # instance is only created the first time it is requested +b = MySingleton.instance +puts a.equal?(b) # outputs "true" diff --git a/Task/Singleton/Scala/singleton.scala b/Task/Singleton/Scala/singleton.scala new file mode 100644 index 0000000000..eeec68bb2b --- /dev/null +++ b/Task/Singleton/Scala/singleton.scala @@ -0,0 +1,3 @@ +object Singleton { + // any code here gets executed as if in a constructor +} diff --git a/Task/Singleton/Slate/singleton.slate b/Task/Singleton/Slate/singleton.slate new file mode 100644 index 0000000000..5c241fe077 --- /dev/null +++ b/Task/Singleton/Slate/singleton.slate @@ -0,0 +1 @@ +define: #Singleton &builder: [Oddball clone] diff --git a/Task/Singleton/Tcl/singleton-1.tcl b/Task/Singleton/Tcl/singleton-1.tcl new file mode 100644 index 0000000000..d529f559ab --- /dev/null +++ b/Task/Singleton/Tcl/singleton-1.tcl @@ -0,0 +1,21 @@ +package require TclOO + +# This is a metaclass, a class that defines the behavior of other classes +oo::class create singleton { + superclass oo::class + variable object + unexport create ;# Doesn't make sense to have named singletons + method new args { + if {![info exists object]} { + set object [next {*}$args] + } + return $object + } +} + +singleton create example { + method counter {} { + my variable count + return [incr count] + } +} diff --git a/Task/Singleton/Tcl/singleton-2.tcl b/Task/Singleton/Tcl/singleton-2.tcl new file mode 100644 index 0000000000..064cc39590 --- /dev/null +++ b/Task/Singleton/Tcl/singleton-2.tcl @@ -0,0 +1,14 @@ +% set a [example new] +::oo::Obj20 +% set b [example new] ;# note how this returns the same object name +::oo::Obj20 +% expr {$a == $b} +1 +% $a counter +1 +% $b counter +2 +% $a counter +3 +% $b counter +4 diff --git a/Task/Singly-linked-list-Element-definition/0DESCRIPTION b/Task/Singly-linked-list-Element-definition/0DESCRIPTION new file mode 100644 index 0000000000..2c6677a3d5 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/0DESCRIPTION @@ -0,0 +1 @@ +Define the data structure for a [[singly-linked list]] element. Said element should contain a data member capable of holding a numeric value, and the link to the next element should be mutable. diff --git a/Task/Singly-linked-list-Element-definition/1META.yaml b/Task/Singly-linked-list-Element-definition/1META.yaml new file mode 100644 index 0000000000..32d20151af --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Data Structures diff --git a/Task/Singly-linked-list-Element-definition/ACL2/singly-linked-list-element-definition.acl2 b/Task/Singly-linked-list-Element-definition/ACL2/singly-linked-list-element-definition.acl2 new file mode 100644 index 0000000000..ba4ddd59de --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/ACL2/singly-linked-list-element-definition.acl2 @@ -0,0 +1,3 @@ +(let ((elem 8) + (next (list 6 7 5 3 0 9))) + (cons elem next)) diff --git a/Task/Singly-linked-list-Element-definition/ALGOL-68/singly-linked-list-element-definition.alg b/Task/Singly-linked-list-Element-definition/ALGOL-68/singly-linked-list-element-definition.alg new file mode 100644 index 0000000000..0f3b11915b --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/ALGOL-68/singly-linked-list-element-definition.alg @@ -0,0 +1,6 @@ +MODE DATA = STRUCT ( ... ); + +MODE LINK = STRUCT ( + REF LINK next, + DATA value +); diff --git a/Task/Singly-linked-list-Element-definition/AWK/singly-linked-list-element-definition.awk b/Task/Singly-linked-list-Element-definition/AWK/singly-linked-list-element-definition.awk new file mode 100644 index 0000000000..df9501106c --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/AWK/singly-linked-list-element-definition.awk @@ -0,0 +1,23 @@ +BEGIN { + NIL = 0 + HEAD = 1 + LINK = 1 + VALUE = 2 + + delete list + initList() +} + +function initList() { + delete list + list[HEAD] = makeNode(NIL, NIL) +} + +function makeNode(link, value) { + return link SUBSEP value +} + +function getNode(part, nodePtr, linkAndValue) { + split(list[nodePtr], linkAndValue, SUBSEP) + return linkAndValue[part] +} diff --git a/Task/Singly-linked-list-Element-definition/ActionScript/singly-linked-list-element-definition.as b/Task/Singly-linked-list-Element-definition/ActionScript/singly-linked-list-element-definition.as new file mode 100644 index 0000000000..bddd9170cb --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/ActionScript/singly-linked-list-element-definition.as @@ -0,0 +1,13 @@ +package +{ + public class Node + { + public var data:Object = null; + public var link:Node = null; + + public function Node(obj:Object) + { + data = obj; + } + } +} diff --git a/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada b/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada new file mode 100644 index 0000000000..bb04c45935 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada @@ -0,0 +1,6 @@ +type Link; +type Link_Access is access Link; +type Link is record + Next : Link_Access := null; + Data : Integer; +end record; diff --git a/Task/Singly-linked-list-Element-definition/AutoHotkey/singly-linked-list-element-definition.ahk b/Task/Singly-linked-list-Element-definition/AutoHotkey/singly-linked-list-element-definition.ahk new file mode 100644 index 0000000000..bceafc6733 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/AutoHotkey/singly-linked-list-element-definition.ahk @@ -0,0 +1,2 @@ +element = 5 ; data +element_next = element2 ; link to next element diff --git a/Task/Singly-linked-list-Element-definition/BBC-BASIC/singly-linked-list-element-definition.bbc b/Task/Singly-linked-list-Element-definition/BBC-BASIC/singly-linked-list-element-definition.bbc new file mode 100644 index 0000000000..abcde643f7 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/BBC-BASIC/singly-linked-list-element-definition.bbc @@ -0,0 +1 @@ + DIM node{pNext%, iData%} diff --git a/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-1.bracmat b/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-1.bracmat new file mode 100644 index 0000000000..51c3977e6e --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-1.bracmat @@ -0,0 +1,3 @@ +link = + (next=) + (data=) diff --git a/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-2.bracmat b/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-2.bracmat new file mode 100644 index 0000000000..8465f8c8ad --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Bracmat/singly-linked-list-element-definition-2.bracmat @@ -0,0 +1,6 @@ + new$link:?link1 +& new$link:?link2 +& first thing:?(link1..data) +& secundus:?(link2..data) +& '$link2:(=?(link1..next)) +& !(link1..next..data) diff --git a/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-1.cpp b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-1.cpp new file mode 100644 index 0000000000..33e0a97854 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-1.cpp @@ -0,0 +1,5 @@ +struct link +{ + link* next; + int data; +}; diff --git a/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-2.cpp b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-2.cpp new file mode 100644 index 0000000000..e0cad25cc4 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-2.cpp @@ -0,0 +1,6 @@ +struct link +{ + link* next; + int data; + link(int a_data, link* a_next = 0): next(a_next), data(a_data) {} +}; diff --git a/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-3.cpp b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-3.cpp new file mode 100644 index 0000000000..a09a207ae2 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-3.cpp @@ -0,0 +1 @@ + link* small_primes = new link(2, new link(3, new link(5, new link(7)))); diff --git a/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-4.cpp b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-4.cpp new file mode 100644 index 0000000000..cb1ad86ece --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/C++/singly-linked-list-element-definition-4.cpp @@ -0,0 +1,6 @@ +template<typename T> struct link +{ + link* next; + T data; + link(T a_data, link* a_next = 0): next(a_next), data(a_data) {} +}; diff --git a/Task/Singly-linked-list-Element-definition/C/singly-linked-list-element-definition.c b/Task/Singly-linked-list-Element-definition/C/singly-linked-list-element-definition.c new file mode 100644 index 0000000000..e84892c892 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/C/singly-linked-list-element-definition.c @@ -0,0 +1,4 @@ +struct link { + struct link *next; + int data; +}; diff --git a/Task/Singly-linked-list-Element-definition/Clean/singly-linked-list-element-definition.clean b/Task/Singly-linked-list-Element-definition/Clean/singly-linked-list-element-definition.clean new file mode 100644 index 0000000000..c764f68466 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Clean/singly-linked-list-element-definition.clean @@ -0,0 +1,3 @@ +import StdMaybe + +:: Link t = { next :: Maybe (Link t), data :: t } diff --git a/Task/Singly-linked-list-Element-definition/Common-Lisp/singly-linked-list-element-definition.lisp b/Task/Singly-linked-list-Element-definition/Common-Lisp/singly-linked-list-element-definition.lisp new file mode 100644 index 0000000000..ca5a8c6206 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Common-Lisp/singly-linked-list-element-definition.lisp @@ -0,0 +1 @@ +(cons 1 (cons 2 (cons 3 nil)) => (1 2 3) diff --git a/Task/Singly-linked-list-Element-definition/D/singly-linked-list-element-definition.d b/Task/Singly-linked-list-Element-definition/D/singly-linked-list-element-definition.d new file mode 100644 index 0000000000..c8d58ce936 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/D/singly-linked-list-element-definition.d @@ -0,0 +1,9 @@ +struct SLinkedNode(T) { + T data; + typeof(this)* next; +} + +void main() { + alias SLinkedNode!int N; + N* n = new N(10); +} diff --git a/Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.delphi b/Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.delphi new file mode 100644 index 0000000000..a29c1f2719 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.delphi @@ -0,0 +1,6 @@ +Type + pOneWayList = ^OneWayList; + OneWayList = record + pData : pointer ; + Next : pOneWayList ; + end; diff --git a/Task/Singly-linked-list-Element-definition/E/singly-linked-list-element-definition.e b/Task/Singly-linked-list-Element-definition/E/singly-linked-list-element-definition.e new file mode 100644 index 0000000000..875b62f669 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/E/singly-linked-list-element-definition.e @@ -0,0 +1,13 @@ +interface LinkedList guards LinkedListStamp {} +def empty implements LinkedListStamp { + to null() { return true } +} +def makeLink(value :int, var next :LinkedList) { + def link implements LinkedListStamp { + to null() { return false } + to value() { return value } + to next() { return next } + to setNext(new) { next := new } + } + return link +} diff --git a/Task/Singly-linked-list-Element-definition/Factor/singly-linked-list-element-definition.factor b/Task/Singly-linked-list-Element-definition/Factor/singly-linked-list-element-definition.factor new file mode 100644 index 0000000000..21f8e2cc87 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Factor/singly-linked-list-element-definition.factor @@ -0,0 +1,4 @@ +TUPLE: linked-list data next ; + +: <linked-list> ( data -- linked-list ) + linked-list new swap >>data ; diff --git a/Task/Singly-linked-list-Element-definition/Fantom/singly-linked-list-element-definition.fantom b/Task/Singly-linked-list-Element-definition/Fantom/singly-linked-list-element-definition.fantom new file mode 100644 index 0000000000..62e89da280 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Fantom/singly-linked-list-element-definition.fantom @@ -0,0 +1,11 @@ +class Node +{ + const Int value // keep value fixed + Node? successor // allow successor to change, also, can be 'null', for end of list + + new make (Int value, Node? successor := null) + { + this.value = value + this.successor = successor + } +} diff --git a/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-1.fth b/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-1.fth new file mode 100644 index 0000000000..9ef7db626e --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-1.fth @@ -0,0 +1,3 @@ +0 value numbers +: push ( n -- ) + here swap numbers , , to numbers ; diff --git a/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-2.fth b/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-2.fth new file mode 100644 index 0000000000..2ef562f019 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Forth/singly-linked-list-element-definition-2.fth @@ -0,0 +1,8 @@ +: length ( list -- u ) + 0 swap begin dup while 1 under+ @ repeat drop ; + +: head ( list -- x ) + cell+ @ ; + +: .numbers ( list -- ) + begin dup while dup head . @ repeat drop ; diff --git a/Task/Singly-linked-list-Element-definition/Fortran/singly-linked-list-element-definition.f b/Task/Singly-linked-list-Element-definition/Fortran/singly-linked-list-element-definition.f new file mode 100644 index 0000000000..c1c39d68c9 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Fortran/singly-linked-list-element-definition.f @@ -0,0 +1,8 @@ +type node + real :: data + type( node ), pointer :: next => null() +end type node +! +!. . . . +! +type( node ) :: head diff --git a/Task/Singly-linked-list-Element-definition/Go/singly-linked-list-element-definition.go b/Task/Singly-linked-list-Element-definition/Go/singly-linked-list-element-definition.go new file mode 100644 index 0000000000..6510f06bce --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Go/singly-linked-list-element-definition.go @@ -0,0 +1,18 @@ +type Ele struct { + Data interface{} + Next *Ele +} + +func (e *Ele) Append(data interface{}) *Ele { + if e.Next == nil { + e.Next = &Ele{data, nil} + } else { + tmp := &Ele{data, e.Next} + e.Next = tmp + } + return e.Next +} + +func (e *Ele) String() string { + return fmt.Sprintf("Ele: %v", e.Data) +} diff --git a/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-1.groovy b/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-1.groovy new file mode 100644 index 0000000000..f008268d68 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-1.groovy @@ -0,0 +1,5 @@ +class ListNode { + Object payload + ListNode next + String toString() { "${payload} -> ${next}" } +} diff --git a/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-2.groovy b/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-2.groovy new file mode 100644 index 0000000000..f8c1ffe73b --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Groovy/singly-linked-list-element-definition-2.groovy @@ -0,0 +1,4 @@ +def n1 = new ListNode(payload:25) +n1.next = new ListNode(payload:88) + +println n1 diff --git a/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-1.hs b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-1.hs new file mode 100644 index 0000000000..d429133b95 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-1.hs @@ -0,0 +1 @@ + data List a = Nil | Cons a (List a) diff --git a/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-2.hs b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-2.hs new file mode 100644 index 0000000000..dadb3ca549 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-2.hs @@ -0,0 +1 @@ + data IntList s = Nil | Cons Integer (STRef s (IntList s)) diff --git a/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-3.hs b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-3.hs new file mode 100644 index 0000000000..74d866ba35 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-3.hs @@ -0,0 +1 @@ +record Node (value, successor) diff --git a/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-4.hs b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-4.hs new file mode 100644 index 0000000000..a810151519 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-4.hs @@ -0,0 +1,5 @@ +class Node (value, successor) + initially (value, successor) + self.value := value + self.successor := successor +end diff --git a/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-5.hs b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-5.hs new file mode 100644 index 0000000000..561bc5a435 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Haskell/singly-linked-list-element-definition-5.hs @@ -0,0 +1,5 @@ +procedure main () + n := Node(1, Node (2)) + write (n.value) + write (n.successor.value) +end diff --git a/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-1.j b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-1.j new file mode 100644 index 0000000000..232e291580 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-1.j @@ -0,0 +1,2 @@ +list=: 0 2$0 +list diff --git a/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-2.j b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-2.j new file mode 100644 index 0000000000..45c2912a96 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-2.j @@ -0,0 +1,3 @@ + list=: ,: _ 42 + list +_ 42 diff --git a/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-3.j b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-3.j new file mode 100644 index 0000000000..5413334f46 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/J/singly-linked-list-element-definition-3.j @@ -0,0 +1,7 @@ + list=: 0 2$a: NB. creates list with 0 items + list + list=: ,: (<_) , <'some text' NB. creates list with 1 item + list ++-+---------+ +|_|some text| ++-+---------+ diff --git a/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-1.java b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-1.java new file mode 100644 index 0000000000..c9a18e9897 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-1.java @@ -0,0 +1,5 @@ +class Link +{ + Link next; + int data; +} diff --git a/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-2.java b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-2.java new file mode 100644 index 0000000000..0dec7a8260 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-2.java @@ -0,0 +1,6 @@ +class Link +{ + Link next; + int data; + Link(int a_data, Link a_next) { next = a_next; data = a_data; } +} diff --git a/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-3.java b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-3.java new file mode 100644 index 0000000000..cf392f7c34 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-3.java @@ -0,0 +1 @@ + Link small_primes = new Link(2, new Link(3, new Link(5, new Link(7, null)))); diff --git a/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-4.java b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-4.java new file mode 100644 index 0000000000..083366ad69 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Java/singly-linked-list-element-definition-4.java @@ -0,0 +1,6 @@ +class Link<T> +{ + Link<T> next; + T data; + Link(T a_data, Link<T> a_next) { next = a_next; data = a_data; } +} diff --git a/Task/Singly-linked-list-Element-definition/JavaScript/singly-linked-list-element-definition.js b/Task/Singly-linked-list-Element-definition/JavaScript/singly-linked-list-element-definition.js new file mode 100644 index 0000000000..0b8e49cc8d --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/JavaScript/singly-linked-list-element-definition.js @@ -0,0 +1,30 @@ +function LinkedList(value, next) { + this._value = value; + this._next = next; +} +LinkedList.prototype.value = function() { + if (arguments.length == 1) + this._value = arguments[0]; + else + return this._value; +} +LinkedList.prototype.next = function() { + if (arguments.length == 1) + this._next = arguments[0]; + else + return this._next; +} + +// convenience function to assist the creation of linked lists. +function createLinkedListFromArray(ary) { + var head = new LinkedList(ary[0], null); + var prev = head; + for (var i = 1; i < ary.length; i++) { + var node = new LinkedList(ary[i], null); + prev.next(node); + prev = node; + } + return head; +} + +var head = createLinkedListFromArray([10,20,30,40]); diff --git a/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-1.logo b/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-1.logo new file mode 100644 index 0000000000..30884569a5 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-1.logo @@ -0,0 +1,5 @@ +fput item list ; add item to the head of a list + +first list ; get the data +butfirst list ; get the remainder +bf list ; contraction for "butfirst" diff --git a/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-2.logo b/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-2.logo new file mode 100644 index 0000000000..561fba87de --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Logo/singly-linked-list-element-definition-2.logo @@ -0,0 +1,2 @@ +.setfirst list value +.setbf list remainder diff --git a/Task/Singly-linked-list-Element-definition/Mathematica/singly-linked-list-element-definition.math b/Task/Singly-linked-list-Element-definition/Mathematica/singly-linked-list-element-definition.math new file mode 100644 index 0000000000..b7e6408e55 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Mathematica/singly-linked-list-element-definition.math @@ -0,0 +1,2 @@ +Append[{}, x] +-> {x} diff --git a/Task/Singly-linked-list-Element-definition/Modula-2/singly-linked-list-element-definition.mod2 b/Task/Singly-linked-list-Element-definition/Modula-2/singly-linked-list-element-definition.mod2 new file mode 100644 index 0000000000..3d2b8c9634 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Modula-2/singly-linked-list-element-definition.mod2 @@ -0,0 +1,6 @@ +TYPE + Link = POINTER TO LinkRcd; + LinkRcd = RECORD + Next: Link; + Data: INTEGER + END; diff --git a/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ocaml b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ocaml new file mode 100644 index 0000000000..abe4bc4ad1 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ocaml @@ -0,0 +1 @@ + type 'a list = Nil | Cons of 'a * 'a list diff --git a/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ocaml b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ocaml new file mode 100644 index 0000000000..b9da7db6dc --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ocaml @@ -0,0 +1 @@ + type int_list = Nil | Cons of int * int_list ref diff --git a/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m new file mode 100644 index 0000000000..6f6122936a --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m @@ -0,0 +1,42 @@ +#import <objc/Object.h> + +@interface RCListElement : Object +{ + RCListElement *next; + id datum; +} ++ (RCListElement *)new; +- (RCListElement *)next; +- (id)datum; +- (RCListElement *)setNext: (RCListElement *)nx; +- (void)setDatum: (id)d; +@end + +@implementation RCListElement ++ (RCListElement *)new +{ + RCListElement *m = [super new]; + [m setNext: nil]; + [m setDatum: nil]; + return m; +} +- (RCListElement *)next +{ + return next; +} +- (id)datum +{ + return datum; +} +- (RCListElement *)setNext: (RCListElement *)nx +{ + RCListElement *p; + p = next; + next = nx; + return p; +} +- (void)setDatum: (id)d +{ + datum = d; +} +@end diff --git a/Task/Singly-linked-list-Element-definition/Pascal/singly-linked-list-element-definition.pascal b/Task/Singly-linked-list-Element-definition/Pascal/singly-linked-list-element-definition.pascal new file mode 100644 index 0000000000..994cefdf44 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Pascal/singly-linked-list-element-definition.pascal @@ -0,0 +1,6 @@ +type + PLink = ^TLink; + TLink = record + FNext: PLink; + FData: integer; + end; diff --git a/Task/Singly-linked-list-Element-definition/Perl-6/singly-linked-list-element-definition.pl6 b/Task/Singly-linked-list-Element-definition/Perl-6/singly-linked-list-element-definition.pl6 new file mode 100644 index 0000000000..61a6e59b9a --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Perl-6/singly-linked-list-element-definition.pl6 @@ -0,0 +1 @@ +my $elem = 42 => $nextelem; diff --git a/Task/Singly-linked-list-Element-definition/Perl/singly-linked-list-element-definition.pl b/Task/Singly-linked-list-Element-definition/Perl/singly-linked-list-element-definition.pl new file mode 100644 index 0000000000..2f3e9bc02e --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Perl/singly-linked-list-element-definition.pl @@ -0,0 +1,5 @@ +my %node = ( + data => 'say what', + next => \%foo_node, +); +$node{next} = \%bar_node; # mutable diff --git a/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-1.pop11 b/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-1.pop11 new file mode 100644 index 0000000000..3f0cd141af --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-1.pop11 @@ -0,0 +1,15 @@ +;;; Use shorthand syntax to create list. +lvars l1 = [1 2 three 'four']; +;;; Allocate a single list node, with value field 1 and the link field +;;; pointing to empty list +lvars l2 = cons(1, []); +;;; print first element of l1 +front(l1) => +;;; print the rest of l1 +back(l1) => +;;; Use index notation to access third element +l1(3) => +;;; modify link field of l2 to point to l1 +l1 -> back(l2); +;;; Print l2 +l2 => diff --git a/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-2.pop11 b/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-2.pop11 new file mode 100644 index 0000000000..7291f7a679 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Pop11/singly-linked-list-element-definition-2.pop11 @@ -0,0 +1,16 @@ +uses objectclass; +define :class ListNode; + slot value = []; + slot next = []; +enddefine; +;;; Allocate new node and assign to l1 +newListNode() -> l1; +;;; Print it +l1 => +;;; modify value +1 -> value(l1); +l1 => +;;; Allocate new node with initialized values and assign to link field +;;; of l1 +consListNode(2, []) -> next(l1); +l1 => diff --git a/Task/Singly-linked-list-Element-definition/PureBasic/singly-linked-list-element-definition.purebasic b/Task/Singly-linked-list-Element-definition/PureBasic/singly-linked-list-element-definition.purebasic new file mode 100644 index 0000000000..dc4f67ccda --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/PureBasic/singly-linked-list-element-definition.purebasic @@ -0,0 +1,4 @@ +Structure MyData + *next.MyData + Value.i +EndStructure diff --git a/Task/Singly-linked-list-Element-definition/Python/singly-linked-list-element-definition.py b/Task/Singly-linked-list-Element-definition/Python/singly-linked-list-element-definition.py new file mode 100644 index 0000000000..24aa315ab4 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Python/singly-linked-list-element-definition.py @@ -0,0 +1,27 @@ +class LinkedList(object): + """USELESS academic/classroom example of a linked list implemented in Python. + Don't ever consider using something this crude! Use the built-in list() type! + """ + class Node(object): + def __init__(self, item): + self.value = item + self.next = None + def __init__(self, item=None): + if item is not None: + self.head = Node(item); self.tail = self.head + else: + self.head = None; self.tail = None + def append(self, item): + if not self.head: + self.head = Node(item) + self.tail = self.head + elif self.tail: + self.tail.next = Node(item) + self.tail = self.tail.next + else: + self.tail = Node(item) + def __iter__(self): + cursor = self.head + while cursor: + yield cursor.value + cursor = cursor.next diff --git a/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx b/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx new file mode 100644 index 0000000000..73d1520f29 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/REXX/singly-linked-list-element-definition.rexx @@ -0,0 +1,34 @@ +/*REXX program to show how to create and show a single-linked list. */ +@.=0 /*define a null linked list (so far). */ +call set@ ,3 /*build linked list of 12 proth primes.*/ +call set@ ,5 +call set@ ,13 +call set@ ,17 +call set@ ,41 +call set@ ,97 +call set@ ,113 +call set@ ,193 +call set@ ,241 +call set@ ,257 +call set@ ,353 +call set@ ,449 +w=length(@._last) /*use width of the last item number. */ + + do j=1 for @._last /*show all entries of the linked list.*/ + say "item" right(j,w) '=' right(@.j._value,@.max_width) + end /*j*/ +exit /*stick a fork in it, we're done. */ +/*───────────────────────────────SET@ subroutine────────────────────────*/ +set@: procedure expose @.; parse arg #,y +if arg(1,'o') then do /*if 1st arg omitted, then add to list*/ + _=@._last+1 /*bump the last ptr in the linked list*/ + @._last=_ /*define the next item in linked list.*/ + #=_ /*point to this item in linked list.*/ + end +@.#._value=y /*set the item to the value specified.*/ +@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/ +if #\==1 then do /*if not the first item, link it. */ + prev=#-1 /*figure out what the previous item is*/ + @.prev._next=# /*now, link the previous item to here.*/ + end +return /*return to the invoker of this sub. *// diff --git a/Task/Singly-linked-list-Element-definition/Ruby/singly-linked-list-element-definition.rb b/Task/Singly-linked-list-Element-definition/Ruby/singly-linked-list-element-definition.rb new file mode 100644 index 0000000000..5864280a1e --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Ruby/singly-linked-list-element-definition.rb @@ -0,0 +1,28 @@ +class ListNode + attr_accessor :value, :succ + + def initialize(value, succ=nil) + self.value = value + self.succ = succ + end + + def each(&b) + yield self + succ.each(&b) if succ + end + + include Enumerable + + def self.from_array(ary) + head = self.new(ary[0], nil) + prev = head + ary[1..-1].each do |val| + node = self.new(val, nil) + prev.succ = node + prev = node + end + head + end +end + +list = ListNode.from_array([1,2,3,4]) diff --git a/Task/Singly-linked-list-Element-definition/Run-BASIC/singly-linked-list-element-definition.run b/Task/Singly-linked-list-Element-definition/Run-BASIC/singly-linked-list-element-definition.run new file mode 100644 index 0000000000..fdddab38c9 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Run-BASIC/singly-linked-list-element-definition.run @@ -0,0 +1,3 @@ +data = 10 +link = 10 +dim node{data,link} diff --git a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust new file mode 100644 index 0000000000..1b166c7b74 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust @@ -0,0 +1,4 @@ +enum SingleLinkedList<T> { + Node(T, @mut SingleLinkedList<T>), + None +} diff --git a/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-1.scala b/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-1.scala new file mode 100644 index 0000000000..a742174df2 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-1.scala @@ -0,0 +1,4 @@ +class Node(n: Int, link: Node) { + var data = n + var next = link +} diff --git a/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-2.scala b/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-2.scala new file mode 100644 index 0000000000..60e05dfae6 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Scala/singly-linked-list-element-definition-2.scala @@ -0,0 +1,11 @@ +class Node { + var data: Int + var next = this + + def this(n: Int, link: Node) { + this() + if (next != null){ + data = n + next = link + } + } diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.ss new file mode 100644 index 0000000000..5dd545106f --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.ss @@ -0,0 +1 @@ +(cons value next) diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.ss new file mode 100644 index 0000000000..80ac961cd1 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.ss @@ -0,0 +1,2 @@ +(car my-list) ; returns the first element of the list +(cdr my-list) ; returns the remainder of the list diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.ss new file mode 100644 index 0000000000..6bf333a493 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.ss @@ -0,0 +1,2 @@ +(set-car! my-list new-elem) +(set-cdr! my-list new-next) diff --git a/Task/Singly-linked-list-Element-definition/Tcl/singly-linked-list-element-definition.tcl b/Task/Singly-linked-list-Element-definition/Tcl/singly-linked-list-element-definition.tcl new file mode 100644 index 0000000000..823bd6f6c7 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Tcl/singly-linked-list-element-definition.tcl @@ -0,0 +1,25 @@ +oo::class create List { + variable content next + constructor {value {list ""}} { + set content $value + set next $list + } + method value args { + set content {*}$args + } + method attach {list} { + set next $list + } + method detach {} { + set next "" + } + method next {} { + return $next + } + method print {} { + for {set n [self]} {$n ne ""} {set n [$n next]} { + lappend values [$n value] + } + return $values + } +} diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 new file mode 100644 index 0000000000..412ad6a103 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-1.x86 @@ -0,0 +1,4 @@ +struct link +.next: resd 1 +.data: resd 1 +endstruc diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 new file mode 100644 index 0000000000..83e1c1bd5e --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-2.x86 @@ -0,0 +1 @@ +link resb 16 diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 new file mode 100644 index 0000000000..3c3b03702b --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-3.x86 @@ -0,0 +1,4 @@ +link struct +next dd ? +data dd ? +link ends diff --git a/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 new file mode 100644 index 0000000000..14bed8e654 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/X86-Assembly/singly-linked-list-element-definition-4.x86 @@ -0,0 +1,5 @@ +struc link next,data +{ + .next dd next + .data dd data +} diff --git a/Task/Singly-linked-list-Element-definition/XPL0/singly-linked-list-element-definition.xpl0 b/Task/Singly-linked-list-Element-definition/XPL0/singly-linked-list-element-definition.xpl0 new file mode 100644 index 0000000000..80832f39b6 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/XPL0/singly-linked-list-element-definition.xpl0 @@ -0,0 +1,16 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +def IntSize=4; \number of bytes in an integer +def Size=10; \number of nodes in this linked list +int Link, List, Node; +[Link:= 0; \build linked list, starting at the end +for Node:= 0 to Size-1 do + [List:= Reserve(IntSize*2); \get some memory to hold link and data + List(0):= Link; + List(1):= Node*Node; \insert example data + Link:= List; \Link now points to newly created node + ]; +Node:= List; \traverse the linked list +repeat IntOut(0, Node(1)); CrLf(0); \display the example data + Node:= Node(0); \move to next node +until Node=0; \end of the list +] diff --git a/Task/Singly-linked-list-Element-insertion/0DESCRIPTION b/Task/Singly-linked-list-Element-insertion/0DESCRIPTION new file mode 100644 index 0000000000..78b272a057 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/0DESCRIPTION @@ -0,0 +1,3 @@ +Using the link element defined in [[Singly-Linked List (element)]], define a method to insert an element into a [[singly-linked list]] following a given element. + +Using this method, insert an element C into a list comprised of elements A->B, following element A. diff --git a/Task/Singly-linked-list-Element-insertion/1META.yaml b/Task/Singly-linked-list-Element-insertion/1META.yaml new file mode 100644 index 0000000000..32d20151af --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Data Structures diff --git a/Task/Singly-linked-list-Element-insertion/ACL2/singly-linked-list-element-insertion.acl2 b/Task/Singly-linked-list-Element-insertion/ACL2/singly-linked-list-element-insertion.acl2 new file mode 100644 index 0000000000..4b2c192553 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/ACL2/singly-linked-list-element-insertion.acl2 @@ -0,0 +1,8 @@ +(defun insert-after (x e xs) + (cond ((endp xs) + nil) + ((equal x (first xs)) + (cons (first xs) + (cons e (rest xs)))) + (t (cons (first xs) + (insert-after x e (rest xs)))))) diff --git a/Task/Singly-linked-list-Element-insertion/ALGOL-68/singly-linked-list-element-insertion.alg b/Task/Singly-linked-list-Element-insertion/ALGOL-68/singly-linked-list-element-insertion.alg new file mode 100644 index 0000000000..ed27349149 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/ALGOL-68/singly-linked-list-element-insertion.alg @@ -0,0 +1,25 @@ +MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next); + +STRINGLIST list := ("Big", + LOC STRINGLIST := ("fjords", + LOC STRINGLIST := ("vex", + LOC STRINGLIST := ("quick", + LOC STRINGLIST := ("waltz", + LOC STRINGLIST := ("nymph",NIL)))))); + +PROC insert = (REF STRINGLIST list, node)VOID: ( + next OF node := next OF list; + next OF list := node +); + +STRINGLIST very := ("VERY", NIL); + +# EXAMPLE OF INSERTION # +insert(next OF next OF list, very ); + +REF STRINGLIST node := list; +WHILE REF STRINGLIST(node) ISNT NIL DO + print((value OF node, space)); + node := next OF node +OD; +print((newline)) diff --git a/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-1.as b/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-1.as new file mode 100644 index 0000000000..1b033bdf54 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-1.as @@ -0,0 +1,14 @@ +package +{ + public class Node + { + public var data:Object = null; + public var link:Node = null; + + public function insert(node:Node):void + { + node.link = link; + link = node; + } + } +} diff --git a/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-2.as b/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-2.as new file mode 100644 index 0000000000..b729cc4986 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/ActionScript/singly-linked-list-element-insertion-2.as @@ -0,0 +1,7 @@ +import Node; + +var A:Node = new Node(1); +var B:Node = new Node(2); +var C:Node = new Node(3); +A.insert(B); +A.insert(C); diff --git a/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada b/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada new file mode 100644 index 0000000000..2c62228df8 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada @@ -0,0 +1,34 @@ +with Ada.Unchecked_Deallocation; +-- Define the link type +procedure Singly_Linked is + + type Link; + type Link_Access is access Link; + type Link is record + Data : Integer; + Next : Link_Access := null; + end record; + -- Instantiate the generic deallocator for the link type + procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access); + + -- Define the procedure + procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is + begin + if Anchor /= null and Newbie /= null then + Newbie.Next := Anchor.Next; + Anchor.Next := Newbie; + end if; + end Insert_Append; + + -- Create the link elements + A : Link_Access := new Link'(1, null); + B : Link_Access := new Link'(2, null); + C : Link_Access := new Link'(3, null); +-- Execute the program +begin + Insert_Append(A, B); + Insert_Append(A, C); + Free(A); + Free(B); + Free(C); +end Singly_Linked; diff --git a/Task/Singly-linked-list-Element-insertion/AutoHotkey/singly-linked-list-element-insertion.ahk b/Task/Singly-linked-list-Element-insertion/AutoHotkey/singly-linked-list-element-insertion.ahk new file mode 100644 index 0000000000..7e3d4ea013 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/AutoHotkey/singly-linked-list-element-insertion.ahk @@ -0,0 +1,17 @@ +a = 1 +a_next = b +b = 2 +b_next = 0 +c = 3 +insert_after("c", "a") +Listvars +msgbox +return + +insert_after(new, old) +{ + local temp + temp := %old%_next + %old%_next := new + %new%_next := temp +} diff --git a/Task/Singly-linked-list-Element-insertion/BBC-BASIC/singly-linked-list-element-insertion.bbc b/Task/Singly-linked-list-Element-insertion/BBC-BASIC/singly-linked-list-element-insertion.bbc new file mode 100644 index 0000000000..df8c9d086b --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/BBC-BASIC/singly-linked-list-element-insertion.bbc @@ -0,0 +1,15 @@ + DIM node{pNext%, iData%} + DIM a{} = node{}, b{} = node{}, c{} = node{} + + a.pNext% = b{} + a.iData% = 123 + b.iData% = 789 + c.iData% = 456 + + PROCinsert(a{}, c{}) + END + + DEF PROCinsert(here{}, new{}) + new.pNext% = here.pNext% + here.pNext% = new{} + ENDPROC diff --git a/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-1.cpp b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-1.cpp new file mode 100644 index 0000000000..ea7dba0142 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-1.cpp @@ -0,0 +1,5 @@ +template<typename T> void insert_after(link<T>* list_node, link<T>* new_node) +{ + new_node->next = list_node->next; + list_node->next = new_node; +}; diff --git a/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-2.cpp b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-2.cpp new file mode 100644 index 0000000000..dd30bab2db --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-2.cpp @@ -0,0 +1,2 @@ +link<int>* a = new link<int>('A', new link<int>('B')); +link<int>* c = new link<int>('C'); diff --git a/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-3.cpp b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-3.cpp new file mode 100644 index 0000000000..94a7c75222 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-3.cpp @@ -0,0 +1 @@ + insert_after(a, c); diff --git a/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-4.cpp b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-4.cpp new file mode 100644 index 0000000000..c1d55dae2d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C++/singly-linked-list-element-insertion-4.cpp @@ -0,0 +1,6 @@ +while (a) +{ + link<int>* tmp = a; + a = a->next; + delete tmp; +} diff --git a/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-1.c b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-1.c new file mode 100644 index 0000000000..395cdb1df3 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-1.c @@ -0,0 +1,4 @@ +void insert_append (link *anchor, link *newlink) { + newlink->next = anchor->next; + anchor->next = newlink; +} diff --git a/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-2.c b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-2.c new file mode 100644 index 0000000000..eb4cfc90cc --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-2.c @@ -0,0 +1,7 @@ +link *a, *b, *c; +a = malloc(sizeof(link)); +b = malloc(sizeof(link)); +c = malloc(sizeof(link)); +a->data = 1; +b->data = 2; +c->data = 3; diff --git a/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-3.c b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-3.c new file mode 100644 index 0000000000..4987bc5c67 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-3.c @@ -0,0 +1 @@ + insert_append (a, b); diff --git a/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-4.c b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-4.c new file mode 100644 index 0000000000..2f82d64b4f --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-4.c @@ -0,0 +1 @@ + insert_append (a, c); diff --git a/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-5.c b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-5.c new file mode 100644 index 0000000000..4cfc253dbd --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/C/singly-linked-list-element-insertion-5.c @@ -0,0 +1,3 @@ + free (a); + free (b); + free (c); diff --git a/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-1.clj b/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-1.clj new file mode 100644 index 0000000000..789256dd69 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-1.clj @@ -0,0 +1,4 @@ +(defn insert-after [new old ls] + (cond (empty? ls) ls + (= (first ls) old) (cons old (cons new (rest ls))) + :else (cons (first ls) (insert-after new old (rest ls))))) diff --git a/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-2.clj b/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-2.clj new file mode 100644 index 0000000000..0814913a3d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Clojure/singly-linked-list-element-insertion-2.clj @@ -0,0 +1,2 @@ +user=> (insert-after 'c 'a '(a b)) +(a c b) diff --git a/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-1.lisp b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-1.lisp new file mode 100644 index 0000000000..15a1d097e3 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-1.lisp @@ -0,0 +1,19 @@ +(defun insert-after (new-element old-element list &key (test 'eql)) + "Return a list like list, but with new-element appearing after the +first occurence of old-element. If old-element does not appear in +list, then a list returning just new-element is returned." + (if (endp list) (list new-element) + (do ((head (list (first list)) (cons (first tail) head)) + (tail (rest list) (rest tail))) + ((or (endp tail) (funcall test old-element (first head))) + (nreconc head (cons new-element tail)))))) + +(defun ninsert-after (new-element old-element list &key (test 'eql)) + "Like insert-after, but modifies list in place. If list is empty, a +new list containing just new-element is returned." + (if (endp list) (list new-element) + (do ((prev list next) + (next (cdr list) (cdr next))) + ((or (null next) (funcall test old-element (car prev))) + (rplacd prev (cons new-element next)) + list)))) diff --git a/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-2.lisp b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-2.lisp new file mode 100644 index 0000000000..9299ad9eb8 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-2.lisp @@ -0,0 +1,4 @@ +(defun simple-insert-after (new-element old-element list &key (test 'eql)) + (let ((tail (rest (member old-element list :test test)))) + (nconc (ldiff list tail) + (cons new-element tail)))) diff --git a/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-3.lisp b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-3.lisp new file mode 100644 index 0000000000..57bb26cfa5 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Common-Lisp/singly-linked-list-element-insertion-3.lisp @@ -0,0 +1,15 @@ +(defun insert-after (list new existing &key (test #'eql)) +"Insert item new into list, before existing, or at the end if existing +is not present. The default comparison test function is EQL. This +function destroys the original list and returns the new list." + (cond + ;; case 1: list is empty: just return list of new + ((endp list) + (list new)) + ;; case 2: existing element is first element of list + ((funcall test (car list) existing) + `(,(car list) ,new ,@(cdr list))) + ;; case 3: recurse: insert the element into the rest of the list, + ;; and make that list the new rest. + (t (rplacd list (insert-before (cdr list) new existing :test test)) + list))) diff --git a/Task/Singly-linked-list-Element-insertion/D/singly-linked-list-element-insertion.d b/Task/Singly-linked-list-Element-insertion/D/singly-linked-list-element-insertion.d new file mode 100644 index 0000000000..721ac49176 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/D/singly-linked-list-element-insertion.d @@ -0,0 +1,21 @@ +struct SLinkedNode(T) { + T data; + typeof(this)* next; +} + +void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) { + newNode.next = listNode.next; + listNode.next = newNode; +} + +void main() { + alias N = SLinkedNode!char; + + auto lh = new N('A', new N('B')); + auto c = new N('C'); + + // Inserts C after A, creating the (A C B) list: + insertAfter(lh, c); + + // The GC will collect the memory. +} diff --git a/Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.delphi b/Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.delphi new file mode 100644 index 0000000000..194a0f25f1 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.delphi @@ -0,0 +1,58 @@ +// Using the same type defs from the one way list example. + +Type + + // The pointer to the list structure + pOneWayList = ^OneWayList; + + // The list structure + OneWayList = record + pData : pointer ; + Next : pOneWayList ; + end; + +// I will illustrate a simple function that will return a pointer to the +// new node or it will return NIL. In this example I will always insert +// right, to keep the code clear. Since I am using a function all operations +// for the new node will be conducted on the functions result. This seems +// somewhat counter intuitive, but it is the simplest way to accomplish this. + +Function InsertNode(VAR CurrentNode:pOneWayList): pOneWayList +begin + + // I try not to introduce different parts of the language, and keep each + // example to just the code required. in this case it is important to use + // a try/except block. In any OS that is multi-threaded and has many apps + // running at the same time, you cannot rely on a call to check memory available + // and then attempting to allocate. In the time between the two, another + // program may have grabbed the memory you were trying to get. + + Try + // Try to allocate enough memory for a variable the size of OneWayList + GetMem(Result,SizeOf(OneWayList)); + Except + On EOutOfMemoryError do + begin + Result := NIL + exit; + end; + end; + + // Initialize the variable. + Result.Next := NIL ; + Reuslt.pdata := NIL ; + + // Ok now we will insert to the right. + + // Is the Next pointer of CurrentNode Nil? If it is we are just tacking + // on to the end of the list. + + if CurrentNode.Next = NIL then + CurrentNode.Next := Result + else + // We are inserting into the middle of this list + Begin + Result.Next := CurrentNode.Next ; + CurrentNode.Next := result ; + end; +end; diff --git a/Task/Singly-linked-list-Element-insertion/E/singly-linked-list-element-insertion.e b/Task/Singly-linked-list-Element-insertion/E/singly-linked-list-element-insertion.e new file mode 100644 index 0000000000..807de9dbe1 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/E/singly-linked-list-element-insertion.e @@ -0,0 +1,18 @@ +def insertAfter(head :LinkedList ? (!head.null()), + new :LinkedList ? (new.next().null())) { + new.setNext(head.next()) + head.setNext(new) +} + +def a := makeLink(1, empty) +def b := makeLink(2, empty) +def c := makeLink(3, empty) + +insertAfter(a, b) +insertAfter(a, c) + +var x := a +while (!x.null()) { + println(x.value()) + x := x.next() +} diff --git a/Task/Singly-linked-list-Element-insertion/Factor/singly-linked-list-element-insertion.factor b/Task/Singly-linked-list-Element-insertion/Factor/singly-linked-list-element-insertion.factor new file mode 100644 index 0000000000..5ea0b6c016 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Factor/singly-linked-list-element-insertion.factor @@ -0,0 +1,9 @@ +: list-append ( previous new -- ) + [ swap next>> >>next drop ] [ >>next drop ] 2bi ; + +SYMBOLS: A B C ; + +A <linked-list> +[ C <linked-list> list-append ] keep +[ B <linked-list> list-append ] keep +. diff --git a/Task/Singly-linked-list-Element-insertion/Fantom/singly-linked-list-element-insertion.fantom b/Task/Singly-linked-list-Element-insertion/Fantom/singly-linked-list-element-insertion.fantom new file mode 100644 index 0000000000..eae4d6194e --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Fantom/singly-linked-list-element-insertion.fantom @@ -0,0 +1,34 @@ +class Node +{ + const Int value + Node? successor // can be null, for end of series + + new make (Int value, Node? successor := null) + { + this.value = value + this.successor = successor + } + + // insert method for this problem + public Void insert (Node newNode) + { + newNode.successor = this.successor + this.successor = newNode + } +} + +// simple class to test putting 'c' between 'a' and 'b' +class Main +{ + public static Void main () + { + c := Node (2) + b := Node (3) + a := Node (1, b) + a.insert (c) + + echo (a.value) + echo (a.successor.value) + echo (a.successor.successor.value) + } +} diff --git a/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-1.fth b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-1.fth new file mode 100644 index 0000000000..710bc2030a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-1.fth @@ -0,0 +1,4 @@ +\ Create the list and some list elements +create A 0 , char A , +create B 0 , char B , +create C 0 , char C , diff --git a/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-2.fth b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-2.fth new file mode 100644 index 0000000000..a1668b1ef0 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-2.fth @@ -0,0 +1,2 @@ +B A chain +C B chain diff --git a/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-3.fth b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-3.fth new file mode 100644 index 0000000000..837d014377 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Forth/singly-linked-list-element-insertion-3.fth @@ -0,0 +1 @@ + : chain ( a b -- ) 2dup @ swap ! ! ; diff --git a/Task/Singly-linked-list-Element-insertion/Fortran/singly-linked-list-element-insertion.f b/Task/Singly-linked-list-Element-insertion/Fortran/singly-linked-list-element-insertion.f new file mode 100644 index 0000000000..1f5d8b017b --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Fortran/singly-linked-list-element-insertion.f @@ -0,0 +1,10 @@ +elemental subroutine addAfter(nodeBefore,value) + type (node), intent(inout) :: nodeBefore + real, intent(in) :: value + type (node), pointer :: newNode + + allocate(newNode) + newNode%data = value + newNode%next => nodeBefore%next + nodeBefore%next => newNode +end subroutine addAfter diff --git a/Task/Singly-linked-list-Element-insertion/Go/singly-linked-list-element-insertion.go b/Task/Singly-linked-list-Element-insertion/Go/singly-linked-list-element-insertion.go new file mode 100644 index 0000000000..c23b1c92be --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Go/singly-linked-list-element-insertion.go @@ -0,0 +1,38 @@ +package main + +import "fmt" + +type Ele struct { + Data interface{} + Next *Ele +} + +func (e *Ele) insert(data interface{}) { + if e == nil { + panic("attept to modify nil") + } + e.Next = &Ele{data, e.Next} +} + +func (e *Ele) printList() { + if e == nil { + fmt.Println(nil) + return + } + fmt.Printf("(%v", e.Data) + for { + e = e.Next + if e == nil { + fmt.Println(")") + return + } + fmt.Print(" ", e.Data) + } +} + +func main() { + h := &Ele{"A", &Ele{"B", nil}} + h.printList() + h.insert("C") + h.printList() +} diff --git a/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-1.groovy b/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-1.groovy new file mode 100644 index 0000000000..966e3e202a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-1.groovy @@ -0,0 +1,20 @@ +class NodeList { + private enum Flag { FRONT } + private ListNode head + void insert(value, insertionPoint=Flag.FRONT) { + if (insertionPoint == Flag.FRONT) { + head = new ListNode(payload: value, next: head) + } else { + def node = head + while (node.payload != insertionPoint) { + node = node.next + if (node == null) { + throw new IllegalArgumentException( + "Insertion point ${afterValue} not already contained in list") + } + } + node.next = new ListNode(payload:value, next:node.next) + } + } + String toString() { "${head}" } +} diff --git a/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-2.groovy b/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-2.groovy new file mode 100644 index 0000000000..bc401ef409 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Groovy/singly-linked-list-element-insertion-2.groovy @@ -0,0 +1,7 @@ +def list = new NodeList() +list.insert('B') +list.insert('A') +println list + +list.insert('C', 'A') +println list diff --git a/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-1.hs b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-1.hs new file mode 100644 index 0000000000..7ee5f14f23 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-1.hs @@ -0,0 +1,3 @@ +insertAfter a b (c:cs) | a==c = a : b : cs + | otherwise = c : insertAfter a b cs +insertAfter _ _ [] = error "Can't insert" diff --git a/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-2.hs b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-2.hs new file mode 100644 index 0000000000..ba11cfd179 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-2.hs @@ -0,0 +1,6 @@ +record Node (value, successor) + +procedure insert_node (node, newNode) + newNode.successor := node.successor + node.successor := newNode +end diff --git a/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-3.hs b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-3.hs new file mode 100644 index 0000000000..0496888e79 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Haskell/singly-linked-list-element-insertion-3.hs @@ -0,0 +1,11 @@ +class Node (value, successor) + + method insert (node) + node.successor := self.successor + self.successor := node + end + + initially (value, successor) + self.value := value + self.successor := successor +end diff --git a/Task/Singly-linked-list-Element-insertion/J/singly-linked-list-element-insertion.j b/Task/Singly-linked-list-Element-insertion/J/singly-linked-list-element-insertion.j new file mode 100644 index 0000000000..2588a285ad --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/J/singly-linked-list-element-insertion.j @@ -0,0 +1,11 @@ +list=: 1 65,:_ 66 +A=:0 NB. reference into list +B=:1 NB. reference into list +insertAfter=: monad define + 'localListName localListNode localNewValue'=. y + localListValue=: ".localListName + localOldLinkRef=: <localListNode,0 + localNewLinkRef=: #localListValue + localNewNode=: (localOldLinkRef { localListValue), localNewValue + (localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode +) diff --git a/Task/Singly-linked-list-Element-insertion/Java/singly-linked-list-element-insertion.java b/Task/Singly-linked-list-Element-insertion/Java/singly-linked-list-element-insertion.java new file mode 100644 index 0000000000..3c36a2dc9d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Java/singly-linked-list-element-insertion.java @@ -0,0 +1,5 @@ +void insertNode(Node<T> anchor_node, Node<T> new_node) +{ + new_node.next = anchor_node.next; + anchor_node.next = new_node; +} diff --git a/Task/Singly-linked-list-Element-insertion/JavaScript/singly-linked-list-element-insertion.js b/Task/Singly-linked-list-Element-insertion/JavaScript/singly-linked-list-element-insertion.js new file mode 100644 index 0000000000..333c115fbb --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/JavaScript/singly-linked-list-element-insertion.js @@ -0,0 +1,12 @@ +LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) { + if (this._value == searchValue) { + nodeToInsert.next(this.next()); + this.next(nodeToInsert); + } + else if (this.next() == null) + throw new Error(0, "value '" + searchValue + "' not found in linked list.") + else + this.next().insertAfter(searchValue, nodeToInsert); +} +var list = createLinkedListFromArray(['A','B']); +list.insertAfter('A', new LinkedList('C', null)); diff --git a/Task/Singly-linked-list-Element-insertion/Logo/singly-linked-list-element-insertion.logo b/Task/Singly-linked-list-Element-insertion/Logo/singly-linked-list-element-insertion.logo new file mode 100644 index 0000000000..74d75be544 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Logo/singly-linked-list-element-insertion.logo @@ -0,0 +1,7 @@ +to insert :after :list :value + localmake "tail member :after :list + if not empty? :tail [.setbf :tail fput :value bf :tail] + output :list +end + +show insert 5 [3 5 1 8] 2 diff --git a/Task/Singly-linked-list-Element-insertion/Mathematica/singly-linked-list-element-insertion.math b/Task/Singly-linked-list-Element-insertion/Mathematica/singly-linked-list-element-insertion.math new file mode 100644 index 0000000000..e1272dbc4f --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Mathematica/singly-linked-list-element-insertion.math @@ -0,0 +1,2 @@ +Append[{a, b}, c] +->{a, b, c} diff --git a/Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ocaml b/Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ocaml new file mode 100644 index 0000000000..207486f6dd --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ocaml @@ -0,0 +1,4 @@ +let rec insert_after a b = function + c :: cs when a = c -> a :: b :: cs + | c :: cs -> c :: insert_after a b cs + | [] -> raise Not_found diff --git a/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-1.pascal b/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-1.pascal new file mode 100644 index 0000000000..fb6fa68847 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-1.pascal @@ -0,0 +1,15 @@ +type + pCharNode = ^CharNode; + CharNode = record + data: char; + next: pCharNode; + end; + +(* This procedure inserts a node (newnode) directly after another node which is assumed to already be in a list. + It does not allocate a new node, but takes an already allocated node, thus allowing to use it (together with + a procedure to remove a node from a list) for splicing a node from one list to another. *) +procedure InsertAfter(listnode, newnode: pCharNode); +begin + newnode^.next := listnode^.next; + listnode^.next := newnode; +end; diff --git a/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-2.pascal b/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-2.pascal new file mode 100644 index 0000000000..fc7d45b15c --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pascal/singly-linked-list-element-insertion-2.pascal @@ -0,0 +1,27 @@ +var + A, B: pCharNode; +begin + (* build the two-component list A->C manually *) + new(A); + A^.data := 'A'; + new(A^.next); + A^.next^.data := 'C'; + A^.next^.next := nil; + + (* create the node to be inserted. The initialization of B^.next isn't strictly necessary + (it gets overwritten anyway), but it's good style not to leave any values undefined. *) + new(B); + node^.data := 'B'; + node^.next := nil; + + (* call the above procedure to insert node B after node A *) + InsertAfter(A, B); + + (* delete the list *) + while A <> nil do + begin + B := A; + A := A^.next; + dispose(B); + end +end. diff --git a/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 b/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 new file mode 100644 index 0000000000..10c0cadc03 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl-6/singly-linked-list-element-insertion.pl6 @@ -0,0 +1,13 @@ +my $letters = 'A' => 'C' => Mu; + +sub insert-after($list, $after, $new) { + loop (my $l = $list; $l; $l = $l.value) { + if $l.key eqv $after { + $l.value = $new => $l.value; + return; + } + } + die "Element $after not found"; +} + +$letters.&insert-after('A', 'B'); diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-1.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-1.pl new file mode 100644 index 0000000000..bf22a4f9bb --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-1.pl @@ -0,0 +1,2 @@ +my @l = ($A, $B); +push @l, $C, splice @l, 1; diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-2.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-2.pl new file mode 100644 index 0000000000..169e032727 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-2.pl @@ -0,0 +1,19 @@ +sub insert_after { + # first argument: node to insert after + # second argument: node to insert + $_[1]{next} = $_[0]{next}; + $_[0]{next} = $_[1]; +} + +my %B = ( + data => 3, + next => undef, # not a circular list +); +my %A = ( + data => 1, + next => \%B, +); +my %C = ( + data => 2, +); +insert_after \%A, \%C; diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-3.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-3.pl new file mode 100644 index 0000000000..4f4cc2c74e --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-3.pl @@ -0,0 +1 @@ + insert_after \%A, { data => 2 }; diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-4.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-4.pl new file mode 100644 index 0000000000..5e683e9098 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-4.pl @@ -0,0 +1,11 @@ +sub insert_after { + my $node = $_[0]; + my $next = $node->{next}; + shift; + while (defined $_[0]) { + $node->{next} = $_[0]; + $node = $node->{next}; + shift; + } + $node->{next} = $next; +} diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-5.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-5.pl new file mode 100644 index 0000000000..7c312de51d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-5.pl @@ -0,0 +1,2 @@ +my %list = ( data => 'A' ); +insert_after \%list, { data => 'B' }, { data => 'C' }; diff --git a/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-6.pl b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-6.pl new file mode 100644 index 0000000000..ea5833368c --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Perl/singly-linked-list-element-insertion-6.pl @@ -0,0 +1,10 @@ +my $list2; + +# create a new list ('A'. 'B', 'C') and store it in $list2 +insert_after $list2 = { data => 'A' }, { data => 'B' }, { data => 'C' }; + +# append two new nodes ('D', 'E') after the first element +insert_after $list2, { data => 'A2' }, { data => 'A3' }; + +# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2') +insert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' }; diff --git a/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-1.l b/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-1.l new file mode 100644 index 0000000000..d5aaa058bd --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-1.l @@ -0,0 +1,4 @@ +(de insertAfter (Item Lst New) + (when (member Item Lst) + (con @ (cons New (cdr @))) ) + Lst ) diff --git a/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-2.l b/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-2.l new file mode 100644 index 0000000000..62403f39ff --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PicoLisp/singly-linked-list-element-insertion-2.l @@ -0,0 +1,4 @@ +(de insertAfter (Item Lst New) + (if (index Item Lst) + (conc (cut @ 'Lst) (cons New Lst)) + Lst ) ) diff --git a/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-1.pop11 b/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-1.pop11 new file mode 100644 index 0000000000..23e7ac6f20 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-1.pop11 @@ -0,0 +1,8 @@ +define insert_into_list(anchor, x); + cons(x, back(anchor)) -> back(anchor); +enddefine; +;;; Build inital list +lvars l1 = cons("a", []); +insert_into_list(l1, "b"); +;;; insert c +insert_into_list(l1, "c"); diff --git a/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-2.pop11 b/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-2.pop11 new file mode 100644 index 0000000000..4d5f870d64 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pop11/singly-linked-list-element-insertion-2.pop11 @@ -0,0 +1,14 @@ +uses objectclass; +define :class ListNode; + slot value = []; + slot next = []; +enddefine; + +define insert_into_List(anchor, x); + consListNode(x, next(anchor)) -> next(anchor); +enddefine; +;;; Build inital list +lvars l2 = consListNode("a", []); +insert_into_List(l2, "b"); +;;; insert c +insert_into_List(l2, "c"); diff --git a/Task/Singly-linked-list-Element-insertion/PureBasic/singly-linked-list-element-insertion.purebasic b/Task/Singly-linked-list-Element-insertion/PureBasic/singly-linked-list-element-insertion.purebasic new file mode 100644 index 0000000000..f08e229705 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PureBasic/singly-linked-list-element-insertion.purebasic @@ -0,0 +1,18 @@ +Procedure insertAfter(Value, *node.MyData = #Null) + Protected *newNode.MyData = AllocateMemory(SizeOf(MyData)) + If *newNode + If *node + *newNode\next = *node\next + *node\next = *newNode + EndIf + *newNode\Value = Value + EndIf + ProcedureReturn *newNode ;return pointer to newnode +EndProcedure + + +Define *SL_List.MyData, a = 1, b = 2, c = 3 + +*SL_List = insertAfter(a) ;start the list +insertAfter(b, *SL_List) ;insert after head of list +insertAfter(c, *SL_List) ;insert after head of list and before tail diff --git a/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-1.py b/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-1.py new file mode 100644 index 0000000000..e4a1ae0110 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-1.py @@ -0,0 +1,12 @@ +def chain_insert(lst, at, item): + while lst is not None: + if lst[0] == at: + lst[1] = [item, lst[1]] + return + else: + lst = lst[1] + raise ValueError(str(at) + " not found") + +chain = ['A', ['B', None]] +chain_insert(chain, 'A', 'C') +print chain diff --git a/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-2.py b/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-2.py new file mode 100644 index 0000000000..820ecce32d --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Python/singly-linked-list-element-insertion-2.py @@ -0,0 +1 @@ +['A', ['C', ['B', None]]] diff --git a/Task/Singly-linked-list-Element-insertion/Ruby/singly-linked-list-element-insertion.rb b/Task/Singly-linked-list-Element-insertion/Ruby/singly-linked-list-element-insertion.rb new file mode 100644 index 0000000000..7b7d267eb5 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Ruby/singly-linked-list-element-insertion.rb @@ -0,0 +1,14 @@ +class ListNode + def insert_after(search_value, new_value) + if search_value == value + self.succ = self.class.new(new_value, succ) + elsif self.succ.nil? + raise StandardError, "value #{search_value} not found in list" + else + self.succ.insert_after(search_value, new_value) + end + end +end + +list = ListNode.new(:a, ListNode.new(:b)) +list.insert_after(:a, :c) diff --git a/Task/Singly-linked-list-Element-insertion/Scala/singly-linked-list-element-insertion.scala b/Task/Singly-linked-list-Element-insertion/Scala/singly-linked-list-element-insertion.scala new file mode 100644 index 0000000000..fe5888e084 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Scala/singly-linked-list-element-insertion.scala @@ -0,0 +1,6 @@ +object Node { + def insert(a: Node, c: Node) = { + c.next = a.next + a.next = c + } +} diff --git a/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.ss b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.ss new file mode 100644 index 0000000000..5172e24a8a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.ss @@ -0,0 +1,8 @@ +(define (insert-after a b lst) + (if (null? lst) + lst ; This should be an error, but we will just return the list untouched + (let ((c (car lst)) + (cs (cdr lst))) + (if (equal? a c) + (cons a (cons b cs)) + (cons c (insert-after a b cs)))))) diff --git a/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.ss b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.ss new file mode 100644 index 0000000000..71363a5f50 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.ss @@ -0,0 +1,4 @@ +(define (insert-after! a b lst) + (let ((pos (member a lst))) + (if pos + (set-cdr! pos (cons b (cdr pos)))))) diff --git a/Task/Singly-linked-list-Element-insertion/Tcl/singly-linked-list-element-insertion.tcl b/Task/Singly-linked-list-Element-insertion/Tcl/singly-linked-list-element-insertion.tcl new file mode 100644 index 0000000000..99de5b9368 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Tcl/singly-linked-list-element-insertion.tcl @@ -0,0 +1,8 @@ +# Assume rest of definition is already present +oo::define List method insertAfter element { + $element attach $next + set next $element +} + +set A [List new "A" [List new "B"]] +$A insertAfter [List new "C"] diff --git a/Task/Singly-linked-list-Traversal/0DESCRIPTION b/Task/Singly-linked-list-Traversal/0DESCRIPTION new file mode 100644 index 0000000000..8f1a5ded3e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/0DESCRIPTION @@ -0,0 +1 @@ +Traverse from the beginning of a singly-linked list to the end. diff --git a/Task/Singly-linked-list-Traversal/1META.yaml b/Task/Singly-linked-list-Traversal/1META.yaml new file mode 100644 index 0000000000..60e9ee5c5f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Iteration +note: Data Structures diff --git a/Task/Singly-linked-list-Traversal/ACL2/singly-linked-list-traversal.acl2 b/Task/Singly-linked-list-Traversal/ACL2/singly-linked-list-traversal.acl2 new file mode 100644 index 0000000000..9499a21fdd --- /dev/null +++ b/Task/Singly-linked-list-Traversal/ACL2/singly-linked-list-traversal.acl2 @@ -0,0 +1,5 @@ +(defun traverse (xs) + (if (endp xs) + (cw "End.~%") + (prog2$ (cw "~x0~%" (first xs)) + (traverse (rest xs))))) diff --git a/Task/Singly-linked-list-Traversal/ALGOL-68/singly-linked-list-traversal.alg b/Task/Singly-linked-list-Traversal/ALGOL-68/singly-linked-list-traversal.alg new file mode 100644 index 0000000000..a3228028a2 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/ALGOL-68/singly-linked-list-traversal.alg @@ -0,0 +1,15 @@ +MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next); + +STRINGLIST list := ("Big", + LOC STRINGLIST := ("fjords", + LOC STRINGLIST := ("vex", + LOC STRINGLIST := ("quick", + LOC STRINGLIST := ("waltz", + LOC STRINGLIST := ("nymph",NIL)))))); + +REF STRINGLIST node := list; +WHILE node ISNT REF STRINGLIST(NIL) DO + print((value OF node, space)); + node := next OF node +OD; +print(newline) diff --git a/Task/Singly-linked-list-Traversal/ActionScript/singly-linked-list-traversal.as b/Task/Singly-linked-list-Traversal/ActionScript/singly-linked-list-traversal.as new file mode 100644 index 0000000000..faf5a117c8 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/ActionScript/singly-linked-list-traversal.as @@ -0,0 +1,6 @@ +var A:Node; +//... +for(var i:Node = A; i != null; i = i.link) +{ + doStuff(i); +} diff --git a/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada b/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada new file mode 100644 index 0000000000..ae9652df0a --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada @@ -0,0 +1,18 @@ +with Ada.Containers.Doubly_Linked_Lists; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Traversal_Example is + package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); + use Int_List; + procedure Print(Position : Cursor) is + begin + Put_Line(Integer'Image(Element(Position))); + end Print; + The_List : List; +begin + for I in 1..10 loop + The_List.Append(I); + end loop; + -- Traverse the list, calling Print for each value + The_List.Iterate(Print'access); +end traversal_example; diff --git a/Task/Singly-linked-list-Traversal/AutoHotkey/singly-linked-list-traversal.ahk b/Task/Singly-linked-list-Traversal/AutoHotkey/singly-linked-list-traversal.ahk new file mode 100644 index 0000000000..ee9e317f6f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/AutoHotkey/singly-linked-list-traversal.ahk @@ -0,0 +1,20 @@ +a = 1 +a_next = b +b = 2 +b_next = c +c = 3 + +traverse("a") +return + +traverse(element) +{ + MsgBox % element . "= " . %element% + name := element . "_next" + while, %name% + { + element := %name% + msgbox % %name% . "= " . %element% + name := %name% . "_next" + } +} diff --git a/Task/Singly-linked-list-Traversal/BBC-BASIC/singly-linked-list-traversal.bbc b/Task/Singly-linked-list-Traversal/BBC-BASIC/singly-linked-list-traversal.bbc new file mode 100644 index 0000000000..a88d1aaf33 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/BBC-BASIC/singly-linked-list-traversal.bbc @@ -0,0 +1,24 @@ + DIM node{pNext%, iData%} + DIM a{} = node{}, b{} = node{}, c{} = node{} + + a.pNext% = b{} + a.iData% = 123 + b.iData% = 789 + c.iData% = 456 + + PROCinsert(a{}, c{}) + + PRINT "Traverse list:" + pnode% = a{} + REPEAT + !(^node{}+4) = pnode% + PRINT node.iData% + pnode% = node.pNext% + UNTIL pnode% = 0 + + END + + DEF PROCinsert(here{}, new{}) + new.pNext% = here.pNext% + here.pNext% = new{} + ENDPROC diff --git a/Task/Singly-linked-list-Traversal/C/singly-linked-list-traversal.c b/Task/Singly-linked-list-Traversal/C/singly-linked-list-traversal.c new file mode 100644 index 0000000000..26ccea8a9f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/C/singly-linked-list-traversal.c @@ -0,0 +1,6 @@ +struct link *first; +// ... +struct link *iter; +for(iter = first; iter != NULL; iter = iter->next) { + // access data, e.g. with iter->data +} diff --git a/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj b/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj new file mode 100644 index 0000000000..0ce2e8a5fe --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj @@ -0,0 +1 @@ +(doseq [x xs] (println x) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-1.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-1.lisp new file mode 100644 index 0000000000..80fb0c429e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-1.lisp @@ -0,0 +1,2 @@ +(dolist (x list) + (print x)) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp new file mode 100644 index 0000000000..b061b4bdfe --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp @@ -0,0 +1,3 @@ +(loop for ref = list then (rest ref) + until (null ref) + do (print (first ref))) diff --git a/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-1.d b/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-1.d new file mode 100644 index 0000000000..07db963f42 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-1.d @@ -0,0 +1,15 @@ +struct SLinkedNode(T) { + T data; + typeof(this)* next; +} + +void main() { + import std.stdio; + + alias N = SLinkedNode!int; + auto lh = new N(1, new N(2, new N(3, new N(4)))); + + for (auto p = lh; p; p = p.next) + write(p.data, " "); + writeln(); +} diff --git a/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-2.d b/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-2.d new file mode 100644 index 0000000000..5387ba61de --- /dev/null +++ b/Task/Singly-linked-list-Traversal/D/singly-linked-list-traversal-2.d @@ -0,0 +1,11 @@ +import tango.io.Stdout; +import tango.util.collection.LinkSeq; + +void main() { + auto m = new LinkSeq!(char[]); + m.append("alpha"); + m.append("bravo"); + m.append("charlie"); + foreach (val; m) + Stdout(val).newline; +} diff --git a/Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.delphi b/Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.delphi new file mode 100644 index 0000000000..53f9f49ca4 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.delphi @@ -0,0 +1,22 @@ +uses system ; + +type + + // declare the list pointer type + plist = ^List ; + + // declare the list type, a generic data pointer prev and next pointers + List = record + data : pointer ; + next : pList ; + end; + +// since this task is just showing the traversal I am not allocating the memory and setting up the root node etc. +// Note the use of the carat symbol for de-referencing the pointer. + +begin + + // beginning to end + while not (pList^.Next = NIL) do pList := pList^.Next ; + +end; diff --git a/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-1.e b/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-1.e new file mode 100644 index 0000000000..424ab71510 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-1.e @@ -0,0 +1,6 @@ +var linkedList := [1, [2, [3, [4, [5, [6, [7, null]]]]]]] + +while (linkedList =~ [value, next]) { + println(value) + linkedList := next +} diff --git a/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-2.e b/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-2.e new file mode 100644 index 0000000000..9c08e701ed --- /dev/null +++ b/Task/Singly-linked-list-Traversal/E/singly-linked-list-traversal-2.e @@ -0,0 +1,6 @@ +var linkedList := makeLink(1, makeLink(2, makeLink(3, empty))) + +while (!(linkedList.null())) { + println(linkedList.value()) + linkedList := linkedList.next() +} diff --git a/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-1.ela b/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-1.ela new file mode 100644 index 0000000000..2a9e956381 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-1.ela @@ -0,0 +1,2 @@ +traverse [] = [] +traverse (x::xs) = x :: traverse xs diff --git a/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-2.ela b/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-2.ela new file mode 100644 index 0000000000..cf7b97ba7d --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Ela/singly-linked-list-traversal-2.ela @@ -0,0 +1,3 @@ +xs = [& x \\ x <- [1..1000]]//lazy list + +traverse xs diff --git a/Task/Singly-linked-list-Traversal/Factor/singly-linked-list-traversal.factor b/Task/Singly-linked-list-Traversal/Factor/singly-linked-list-traversal.factor new file mode 100644 index 0000000000..834756becd --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Factor/singly-linked-list-traversal.factor @@ -0,0 +1,11 @@ +: list-each ( linked-list quot: ( data -- ) -- ) + [ [ data>> ] dip call ] + [ [ next>> ] dip over [ list-each ] [ 2drop ] if ] 2bi ; inline recursive + +SYMBOLS: A B C ; + +A <linked-list> +[ C <linked-list> list-insert ] keep +[ B <linked-list> list-insert ] keep + +[ . ] list-each diff --git a/Task/Singly-linked-list-Traversal/Fantom/singly-linked-list-traversal.fantom b/Task/Singly-linked-list-Traversal/Fantom/singly-linked-list-traversal.fantom new file mode 100644 index 0000000000..e340b25825 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Fantom/singly-linked-list-traversal.fantom @@ -0,0 +1,7 @@ + // traverse the linked list + Node? current := a + while (current != null) + { + echo (current.value) + current = current.successor + } diff --git a/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-1.fth b/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-1.fth new file mode 100644 index 0000000000..31a5eb3155 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-1.fth @@ -0,0 +1,2 @@ +: last ( list -- end ) + begin dup @ while @ repeat ; diff --git a/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-2.fth b/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-2.fth new file mode 100644 index 0000000000..4e9a20602d --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Forth/singly-linked-list-traversal-2.fth @@ -0,0 +1,4 @@ +: walk ( a xt -- ) + >r begin ?dup while + dup cell+ @ r@ execute + @ repeat r> drop ; diff --git a/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-1.f b/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-1.f new file mode 100644 index 0000000000..4c2d275890 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-1.f @@ -0,0 +1,14 @@ +subroutine traversal(list,proc) + type(node), target :: list + type(node), pointer :: current + interface + subroutine proc(node) + real, intent(in) :: node + end subroutine proc + end interface + current => list + do while ( associated(current) ) + call proc(current%data) + current => current%next + end do +end subroutine traversal diff --git a/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-2.f b/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-2.f new file mode 100644 index 0000000000..c234423c86 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Fortran/singly-linked-list-traversal-2.f @@ -0,0 +1,9 @@ +subroutine printNode(data) + real, intent(in) :: data + write (*,*) data +end subroutine + +subroutine printAll(list) + type(node), intent(in) :: list + call traversal(list,printNode) +end subroutine printAll diff --git a/Task/Singly-linked-list-Traversal/Go/singly-linked-list-traversal.go b/Task/Singly-linked-list-Traversal/Go/singly-linked-list-traversal.go new file mode 100644 index 0000000000..ae279db7ed --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Go/singly-linked-list-traversal.go @@ -0,0 +1,7 @@ +start := &Ele{"tacos", nil} +end := start.Append("burritos") +end = end.Append("fajitas") +end = end.Append("enchilatas") +for iter := start; iter != nil; iter = iter.Next { + fmt.Println(iter) +} diff --git a/Task/Singly-linked-list-Traversal/Haskell/singly-linked-list-traversal.hs b/Task/Singly-linked-list-Traversal/Haskell/singly-linked-list-traversal.hs new file mode 100644 index 0000000000..750d748ea1 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Haskell/singly-linked-list-traversal.hs @@ -0,0 +1,9 @@ +map (>5) [1..10] -- [False,False,False,False,False,True,True,True,True,True] + +map (++ "s") ["Apple", "Orange", "Mango", "Pear"] -- ["Apples","Oranges","Mangos","Pears"] + +foldr (+) 0 [1..10] -- prints 55 + +traverse :: [a] -> [a] +traverse list = map func list + where func a = -- ...do something with a diff --git a/Task/Singly-linked-list-Traversal/Icon/singly-linked-list-traversal.icon b/Task/Singly-linked-list-Traversal/Icon/singly-linked-list-traversal.icon new file mode 100644 index 0000000000..ca12ab7907 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Icon/singly-linked-list-traversal.icon @@ -0,0 +1,7 @@ +procedure main () + ns := Node(1, Node(2, Node (3))) + until /ns do { # repeat until ns is null + write (ns.value) + ns := ns.successor + } +end diff --git a/Task/Singly-linked-list-Traversal/J/singly-linked-list-traversal.j b/Task/Singly-linked-list-Traversal/J/singly-linked-list-traversal.j new file mode 100644 index 0000000000..baa1be41a7 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/J/singly-linked-list-traversal.j @@ -0,0 +1 @@ +foo"0 {:"1 list diff --git a/Task/Singly-linked-list-Traversal/Java/singly-linked-list-traversal.java b/Task/Singly-linked-list-Traversal/Java/singly-linked-list-traversal.java new file mode 100644 index 0000000000..792a2708f3 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Java/singly-linked-list-traversal.java @@ -0,0 +1,6 @@ +LinkedList<Type> list = new LinkedList<Type>(); + +for(Type i: list){ + //each element will be in variable "i" + System.out.println(i); +} diff --git a/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal.js b/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal.js new file mode 100644 index 0000000000..a476011d95 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal.js @@ -0,0 +1,12 @@ +LinkedList.prototype.traverse = function(func) { + func(this); + if (this.next() != null) + this.next().traverse(func); +} + +LinkedList.prototype.print = function() { + this.traverse( function(node) {print(node.value())} ); +} + +var head = createLinkedListFromArray([10,20,30,40]); +head.print(); diff --git a/Task/Singly-linked-list-Traversal/Logo/singly-linked-list-traversal.logo b/Task/Singly-linked-list-Traversal/Logo/singly-linked-list-traversal.logo new file mode 100644 index 0000000000..1e59485dbd --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Logo/singly-linked-list-traversal.logo @@ -0,0 +1,4 @@ +to last :list + if empty? bf :list [output first :list] + output last bf :list +end diff --git a/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-1.m b/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-1.m new file mode 100644 index 0000000000..3e87622fa4 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-1.m @@ -0,0 +1,4 @@ +list = 1:10; + for k=1:length(list) + printf('%i\n',list(k)) + end; diff --git a/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-2.m b/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-2.m new file mode 100644 index 0000000000..cb1603478e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/MATLAB/singly-linked-list-traversal-2.m @@ -0,0 +1 @@ + printf('%d\n', list(:)); diff --git a/Task/Singly-linked-list-Traversal/Mathematica/singly-linked-list-traversal.math b/Task/Singly-linked-list-Traversal/Mathematica/singly-linked-list-traversal.math new file mode 100644 index 0000000000..5419e18dc9 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Mathematica/singly-linked-list-traversal.math @@ -0,0 +1,7 @@ +Print /@ {"rosettacode", "kitten", "sitting", "rosettacode", "raisethysword"} +-> +rosettacode +kitten +sitting +rosettacode +raisethysword diff --git a/Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ocaml b/Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ocaml new file mode 100644 index 0000000000..20eb807c84 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ocaml @@ -0,0 +1,9 @@ +# let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in + List.iter print_endline li ;; +big +fjords +vex +quick +waltz +nymph +- : unit = () diff --git a/Task/Singly-linked-list-Traversal/Objeck/singly-linked-list-traversal.objeck b/Task/Singly-linked-list-Traversal/Objeck/singly-linked-list-traversal.objeck new file mode 100644 index 0000000000..5e1a3c1abb --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Objeck/singly-linked-list-traversal.objeck @@ -0,0 +1,3 @@ +for(node := head; node <> Nil; node := node->GetNext();) { + node->GetValue()->PrintLine(); +}; diff --git a/Task/Singly-linked-list-Traversal/Objective-C/singly-linked-list-traversal.m b/Task/Singly-linked-list-Traversal/Objective-C/singly-linked-list-traversal.m new file mode 100644 index 0000000000..a378de47f5 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Objective-C/singly-linked-list-traversal.m @@ -0,0 +1,6 @@ +RCListElement *current; +for(current=first_of_the_list; current != nil; current = [current next] ) +{ + // to get the "datum": + // id dat_obj = [current datum]; +} diff --git a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 new file mode 100644 index 0000000000..c182b358a2 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 @@ -0,0 +1,5 @@ +my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu; + +loop (my $l = $list; $l; $l = $l.value) { + say $l.key; +} diff --git a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 new file mode 100644 index 0000000000..12193eaa8b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 @@ -0,0 +1,11 @@ +use MONKEY_TYPING; +augment class Pair { + method traverse () { + gather loop (my $l = self; $l; $l = $l.value) { + take $l.key; + } + } +} + +my $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu; +say ~$list.traverse; diff --git a/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-1.l b/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-1.l new file mode 100644 index 0000000000..307d323c5e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-1.l @@ -0,0 +1 @@ +(mapc println '(a "cde" (X Y Z) 999)) diff --git a/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-2.l b/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-2.l new file mode 100644 index 0000000000..e798796108 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/PicoLisp/singly-linked-list-traversal-2.l @@ -0,0 +1,2 @@ +(for X '(a "cde" (X Y Z) 999) + (println X) ) diff --git a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium new file mode 100644 index 0000000000..b003100f7f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-1.protium @@ -0,0 +1,9 @@ +<@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@> +<@ OMT>From First to Last</@> +<@ ITEFORSZELSTLIT>public holidays| +<@ SAYLST>...</@><@ ACTMOVFWDLST>...</@> +</@> +<@ OMT>From Last to First (pointer is still at end of list)</@> +<@ ITEFORSZELSTLIT>public holidays| +<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@> +</@> diff --git a/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium new file mode 100644 index 0000000000..ca6946a25b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Protium/singly-linked-list-traversal-2.protium @@ -0,0 +1,9 @@ +<# 指定构造列表字串>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</#> +<# 忽略>From First to Last</#> +<# 迭代迭代次数结构大小列表字串>public holidays| +<# 显示列表>...</#><# 运行移位指针向前列表>...</#> +</#> +<# 忽略>From Last to First (pointer is still at end of list)</#> +<# 迭代迭代次数结构大小列表字串>public holidays| +<# 显示列表>...</#><# 运行移位指针向后列表>...</#> +</#> diff --git a/Task/Singly-linked-list-Traversal/PureBasic/singly-linked-list-traversal.purebasic b/Task/Singly-linked-list-Traversal/PureBasic/singly-linked-list-traversal.purebasic new file mode 100644 index 0000000000..f0f06fdfd6 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/PureBasic/singly-linked-list-traversal.purebasic @@ -0,0 +1,9 @@ +Procedure traverse(*node.MyData) + While *node + ;access data, i.e. PrintN(Str(*node\Value)) + *node = *node\next + Wend +EndProcedure + +;called using +traverse(*firstnode.MyData) diff --git a/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-1.py b/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-1.py new file mode 100644 index 0000000000..900af9edde --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-1.py @@ -0,0 +1,2 @@ +for node in lst: + print node.value diff --git a/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-2.py b/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-2.py new file mode 100644 index 0000000000..24e964d68d --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Python/singly-linked-list-traversal-2.py @@ -0,0 +1,23 @@ +class LinkedList(object): + """USELESS academic/classroom example of a linked list implemented in Python. + Don't ever consider using something this crude! Use the built-in list() type! + """ + def __init__(self, value, next): + self.value = value; + self.next = next + def __iter__(self): + node = self + while node != None: + yield node.value + node = node.next; + +lst = LinkedList("big", next= + LinkedList(value="fjords",next= + LinkedList(value="vex", next= + LinkedList(value="quick", next= + LinkedList(value="waltz", next= + LinkedList(value="nymph", next=None)))))); + +for value in lst: + print value,; +print diff --git a/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-1.retro b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-1.retro new file mode 100644 index 0000000000..de538f6375 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-1.retro @@ -0,0 +1 @@ +: traverse ( l- ) repeat @ 0; again ; diff --git a/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-2.retro b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-2.retro new file mode 100644 index 0000000000..91750e9bf0 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-2.retro @@ -0,0 +1 @@ +last [ drop ] ^types'LIST each@ diff --git a/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-3.retro b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-3.retro new file mode 100644 index 0000000000..1fb9bef0aa --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Retro/singly-linked-list-traversal-3.retro @@ -0,0 +1 @@ +last [ @d->name puts space ] ^types'LIST each@ diff --git a/Task/Singly-linked-list-Traversal/Ruby/singly-linked-list-traversal.rb b/Task/Singly-linked-list-Traversal/Ruby/singly-linked-list-traversal.rb new file mode 100644 index 0000000000..464d63828b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Ruby/singly-linked-list-traversal.rb @@ -0,0 +1,13 @@ +head = ListNode.new("a", ListNode.new("b", ListNode.new("c"))) +head.insertAfter("b", "b+") + +# then: +head.each {|node| print node.value, ","} +puts + +# or +current = head +begin + print current.value, "," +end while current = current.succ +puts diff --git a/Task/Singly-linked-list-Traversal/Run-BASIC/singly-linked-list-traversal.run b/Task/Singly-linked-list-Traversal/Run-BASIC/singly-linked-list-traversal.run new file mode 100644 index 0000000000..1c07505dc3 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Run-BASIC/singly-linked-list-traversal.run @@ -0,0 +1,4 @@ +list$ = "now is the time for all good men" +for lnk = 1 to 8 + print lnk;"->";word$(list$,lnk) +next lnk diff --git a/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-1.scala b/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-1.scala new file mode 100644 index 0000000000..6310d64e2e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-1.scala @@ -0,0 +1,6 @@ +def traverse1[T](xs: Seq[T]): Unit = xs match { + case s if s.isEmpty => () + case _ => { Console.println(xs.head); + traverse1(xs.tail) + } +} diff --git a/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-2.scala b/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-2.scala new file mode 100644 index 0000000000..c5e01557f8 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal-2.scala @@ -0,0 +1 @@ +def traverse2[T](xs: Seq[T]) = for (x <- xs) Console.println(x) diff --git a/Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.ss b/Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.ss new file mode 100644 index 0000000000..e5fca76ac9 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.ss @@ -0,0 +1,6 @@ +(define (traverse seq func) + (if (null? seq) + '() + (begin + (func (car seq)) + (traverse (cdr seq) func)))) diff --git a/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-1.tcl b/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-1.tcl new file mode 100644 index 0000000000..04a7014826 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-1.tcl @@ -0,0 +1,11 @@ +oo::define List { + method for {varName script} { + upvar 1 $varName var + set elem [self] + while {$elem ne ""} { + set var [$elem value] + uplevel 1 $script + set elem [$elem next] + } + } +} diff --git a/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-2.tcl b/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-2.tcl new file mode 100644 index 0000000000..367e307620 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Tcl/singly-linked-list-traversal-2.tcl @@ -0,0 +1,7 @@ +set list {} +foreach n {1 3 5 7 2 4 6 8} { + set list [List new $n $list] +} +$list for x { + puts "we have a $x in the list" +} diff --git a/Task/Singly-linked-list-Traversal/Trith/singly-linked-list-traversal.trith b/Task/Singly-linked-list-Traversal/Trith/singly-linked-list-traversal.trith new file mode 100644 index 0000000000..ee41c4c5c2 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Trith/singly-linked-list-traversal.trith @@ -0,0 +1 @@ +[1 2 3 4 5] [print] each diff --git a/Task/Singly-linked-list-Traversal/Visual-Basic-.NET/singly-linked-list-traversal.visual b/Task/Singly-linked-list-Traversal/Visual-Basic-.NET/singly-linked-list-traversal.visual new file mode 100644 index 0000000000..5c216a7296 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Visual-Basic-.NET/singly-linked-list-traversal.visual @@ -0,0 +1,6 @@ +Private Sub Iterate(ByVal list As LinkedList(Of Integer)) + Dim node = list.First + Do Until node Is Nothing + node = node.Next + Loop + End Sub diff --git a/Task/Singly-linked-list-Traversal/XPL0/singly-linked-list-traversal.xpl0 b/Task/Singly-linked-list-Traversal/XPL0/singly-linked-list-traversal.xpl0 new file mode 100644 index 0000000000..6528ee7b18 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/XPL0/singly-linked-list-traversal.xpl0 @@ -0,0 +1 @@ +repeat Node:= Node(0) until Node=0 diff --git a/Task/Sleep/0DESCRIPTION b/Task/Sleep/0DESCRIPTION new file mode 100644 index 0000000000..79f052a965 --- /dev/null +++ b/Task/Sleep/0DESCRIPTION @@ -0,0 +1,6 @@ +Write a program that does the following in this order: +* Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. +* [[Hello world/Text|Print]] "Sleeping..." +* Sleep the main [[thread]] for the given amount of time. +* Print "Awake!" +* End. diff --git a/Task/Sleep/1META.yaml b/Task/Sleep/1META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/Sleep/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/Sleep/AWK/sleep.awk b/Task/Sleep/AWK/sleep.awk new file mode 100644 index 0000000000..a730478cc0 --- /dev/null +++ b/Task/Sleep/AWK/sleep.awk @@ -0,0 +1,12 @@ +# syntax: GAWK -f SLEEP.AWK [seconds] +BEGIN { + print("Sleeping...") + loop(ARGV[1]) + print("Awake!") + exit(0) +} +function loop(seconds, t) { +# awk lacks a sleep mechanism, so simulate one by looping + t = systime() + while (systime() < t + seconds) {} +} diff --git a/Task/Sleep/Ada/sleep.ada b/Task/Sleep/Ada/sleep.ada new file mode 100644 index 0000000000..d18964f8df --- /dev/null +++ b/Task/Sleep/Ada/sleep.ada @@ -0,0 +1,11 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Float_Text_Io; use Ada.Float_Text_Io; + +procedure Sleep is + In_Val : Float; +begin + Get(In_Val); + Put_Line("Sleeping..."); + delay Duration(In_Val); + Put_Line("Awake!"); +end Sleep; diff --git a/Task/Sleep/AutoHotkey/sleep.ahk b/Task/Sleep/AutoHotkey/sleep.ahk new file mode 100644 index 0000000000..9a97ea1def --- /dev/null +++ b/Task/Sleep/AutoHotkey/sleep.ahk @@ -0,0 +1,4 @@ +TrayTip, sleeping, sleeping +sleep, 2000 ; 2 seconds +TrayTip, awake, awake +Msgbox, awake diff --git a/Task/Sleep/AutoIt/sleep.autoit b/Task/Sleep/AutoIt/sleep.autoit new file mode 100644 index 0000000000..94eda9c289 --- /dev/null +++ b/Task/Sleep/AutoIt/sleep.autoit @@ -0,0 +1,6 @@ +#AutoIt Version: 3.2.10.0 +$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0) +Dim $sleep_millisec=$sleep_me*1000 +MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec") +sleep ($sleep_millisec) +MsgBox(0,"Awake","... Awaking") diff --git a/Task/Sleep/BASIC/sleep-1.basic b/Task/Sleep/BASIC/sleep-1.basic new file mode 100644 index 0000000000..373c492718 --- /dev/null +++ b/Task/Sleep/BASIC/sleep-1.basic @@ -0,0 +1,4 @@ +INPUT sec 'the SLEEP command takes seconds +PRINT "Sleeping..." +SLEEP sec +PRINT "Awake!" diff --git a/Task/Sleep/BASIC/sleep-2.basic b/Task/Sleep/BASIC/sleep-2.basic new file mode 100644 index 0000000000..bb1a6bd5ac --- /dev/null +++ b/Task/Sleep/BASIC/sleep-2.basic @@ -0,0 +1,5 @@ +10 REM s is the number of seconds +20 LET s = 5 +30 PRINT "Sleeping" +40 PAUSE s * 50 +50 PRINT "Awake" diff --git a/Task/Sleep/BBC-BASIC/sleep.bbc b/Task/Sleep/BBC-BASIC/sleep.bbc new file mode 100644 index 0000000000..23db0d51b5 --- /dev/null +++ b/Task/Sleep/BBC-BASIC/sleep.bbc @@ -0,0 +1,4 @@ + INPUT "Enter the time to sleep in centiseconds: " sleep% + PRINT "Sleeping..." + WAIT sleep% + PRINT "Awake!" diff --git a/Task/Sleep/Batch-File/sleep-1.bat b/Task/Sleep/Batch-File/sleep-1.bat new file mode 100644 index 0000000000..73ac2ddc45 --- /dev/null +++ b/Task/Sleep/Batch-File/sleep-1.bat @@ -0,0 +1,6 @@ +@echo off +set /p Seconds=Enter the number of seconds to sleep: +set /a Seconds+=1 +echo Sleeping ... +ping -n %Seconds% localhost >nul 2>&1 +echo Awake! diff --git a/Task/Sleep/Batch-File/sleep-2.bat b/Task/Sleep/Batch-File/sleep-2.bat new file mode 100644 index 0000000000..3dc0208441 --- /dev/null +++ b/Task/Sleep/Batch-File/sleep-2.bat @@ -0,0 +1,5 @@ +@echo off +set /p MilliSeconds=Enter the number of milliseconds to sleep: +echo Sleeping ... +ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1 +echo Awake! diff --git a/Task/Sleep/Batch-File/sleep-3.bat b/Task/Sleep/Batch-File/sleep-3.bat new file mode 100644 index 0000000000..f477cd459a --- /dev/null +++ b/Task/Sleep/Batch-File/sleep-3.bat @@ -0,0 +1,5 @@ +@echo off +set /p Seconds=Enter the number of seconds to sleep: +echo Sleeping ... +timeout /t %Seconds% /nobreak >nul +echo Awake! diff --git a/Task/Sleep/C++/sleep-1.cpp b/Task/Sleep/C++/sleep-1.cpp new file mode 100644 index 0000000000..14a74c3fad --- /dev/null +++ b/Task/Sleep/C++/sleep-1.cpp @@ -0,0 +1,11 @@ +#include <iostream> +#include <thread> +#include <chrono> +int main() +{ + unsigned long microseconds; + std::cin >> microseconds; + std::cout << "Sleeping..." << std::endl; + std::this_thread::sleep_for(std::chrono::microseconds(microseconds)); + std::cout << "Awake!\n"; +} diff --git a/Task/Sleep/C++/sleep-2.cpp b/Task/Sleep/C++/sleep-2.cpp new file mode 100644 index 0000000000..99150918b5 --- /dev/null +++ b/Task/Sleep/C++/sleep-2.cpp @@ -0,0 +1,14 @@ +#include <unistd.h> +#include <iostream> + +using namespace std; + +int main(int argc, char* argv[]) +{ + useconds_t microseconds; + cin >> microseconds; + cout << "Sleeping..." << endl; + usleep(microseconds); + cout << "Awake!" << endl; + return 0; +} diff --git a/Task/Sleep/C/sleep.c b/Task/Sleep/C/sleep.c new file mode 100644 index 0000000000..5759395586 --- /dev/null +++ b/Task/Sleep/C/sleep.c @@ -0,0 +1,12 @@ +#include <stdio.h> +#include <unistd.h> + +int main() +{ + unsigned int seconds; + scanf("%u", &seconds); + printf("Sleeping...\n"); + sleep(seconds); + printf("Awake!\n"); + return 0; +} diff --git a/Task/Sleep/Clojure/sleep.clj b/Task/Sleep/Clojure/sleep.clj new file mode 100644 index 0000000000..66dc848cd2 --- /dev/null +++ b/Task/Sleep/Clojure/sleep.clj @@ -0,0 +1,6 @@ +(defn sleep [ms] ; time in milliseconds + (println "Sleeping...") + (Thread/sleep ms) + (println "Awake!")) +; call it +(sleep 1000) diff --git a/Task/Sleep/Common-Lisp/sleep.lisp b/Task/Sleep/Common-Lisp/sleep.lisp new file mode 100644 index 0000000000..9a375c0e00 --- /dev/null +++ b/Task/Sleep/Common-Lisp/sleep.lisp @@ -0,0 +1,7 @@ +(defun test-sleep () + (let ((seconds (read))) + (format t "Sleeping...~%") + (sleep seconds) + (format t "Awake!~%"))) + +(test-sleep) diff --git a/Task/Sleep/D/sleep.d b/Task/Sleep/D/sleep.d new file mode 100644 index 0000000000..faeb0a674b --- /dev/null +++ b/Task/Sleep/D/sleep.d @@ -0,0 +1,12 @@ +import std.stdio, core.thread; + +void main() { + write("Enter a time to sleep (in seconds): "); + + long secs; + readf(" %d", &secs); + + writeln("Sleeping..."); + Thread.sleep(dur!"seconds"(secs)); + writeln("Awake!"); +} diff --git a/Task/Sleep/Delphi/sleep.delphi b/Task/Sleep/Delphi/sleep.delphi new file mode 100644 index 0000000000..3d41a6b5cd --- /dev/null +++ b/Task/Sleep/Delphi/sleep.delphi @@ -0,0 +1,17 @@ +program SleepOneSecond; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +var + lTimeToSleep: Integer; +begin + if ParamCount = 0 then + lTimeToSleep := 1000 + else + lTimeToSleep := StrToInt(ParamStr(1)); + WriteLn('Sleeping...'); + Sleep(lTimeToSleep); // milliseconds + WriteLn('Awake!'); +end. diff --git a/Task/Sleep/E/sleep.e b/Task/Sleep/E/sleep.e new file mode 100644 index 0000000000..05ac24273d --- /dev/null +++ b/Task/Sleep/E/sleep.e @@ -0,0 +1,7 @@ +def sleep(milliseconds :int, nextThing) { + stdout.println("Sleeping...") + timer.whenPast(timer.now() + milliseconds, fn { + stdout.println("Awake!") + nextThing() + }) +} diff --git a/Task/Sleep/EGL/sleep.egl b/Task/Sleep/EGL/sleep.egl new file mode 100644 index 0000000000..ca81906479 --- /dev/null +++ b/Task/Sleep/EGL/sleep.egl @@ -0,0 +1,11 @@ +program Sleep type BasicProgram{} + + // Syntax: sysLib.wait(time BIN(9,2) in) + + function main() + SysLib.writeStdout("Sleeping!"); + sysLib.wait(15); // waits for 15 seconds + SysLib.writeStdout("Awake!"); + end + +end diff --git a/Task/Sleep/Eiffel/sleep.e b/Task/Sleep/Eiffel/sleep.e new file mode 100644 index 0000000000..3922e49be3 --- /dev/null +++ b/Task/Sleep/Eiffel/sleep.e @@ -0,0 +1,17 @@ +class + APPLICATION +inherit + EXECUTION_ENVIRONMENT +create + make +feature -- Initialization + make + -- Sleep for a given number of nanoseconds. + do + print ("Enter a number of nanoseconds: ") + io.read_integer_64 + print ("Sleeping...%N") + sleep (io.last_integer_64) + print ("Awake!%N") + end +end diff --git a/Task/Sleep/Erlang/sleep-1.erl b/Task/Sleep/Erlang/sleep-1.erl new file mode 100644 index 0000000000..e13f9f1375 --- /dev/null +++ b/Task/Sleep/Erlang/sleep-1.erl @@ -0,0 +1,4 @@ +main() -> + io:format("Sleeping...~n"), + timer:sleep(1000), %% in milliseconds + io:format("Awake!~n"). diff --git a/Task/Sleep/Erlang/sleep-2.erl b/Task/Sleep/Erlang/sleep-2.erl new file mode 100644 index 0000000000..328ed7f03d --- /dev/null +++ b/Task/Sleep/Erlang/sleep-2.erl @@ -0,0 +1,6 @@ +main() -> + io:format("Sleeping...~n"), + receive + after 1000 -> ok %% in milliseconds + end, + io:format("Awake!~n"). diff --git a/Task/Sleep/Factor/sleep.factor b/Task/Sleep/Factor/sleep.factor new file mode 100644 index 0000000000..78d2617095 --- /dev/null +++ b/Task/Sleep/Factor/sleep.factor @@ -0,0 +1,7 @@ +USING: calendar io math.parser threads ; + +: read-sleep ( -- ) + readln string>number seconds + "Sleeping..." print + sleep + "Awake!" print ; diff --git a/Task/Sleep/Fantom/sleep.fantom b/Task/Sleep/Fantom/sleep.fantom new file mode 100644 index 0000000000..8e1f4561b6 --- /dev/null +++ b/Task/Sleep/Fantom/sleep.fantom @@ -0,0 +1,21 @@ +using concurrent + +class Main +{ + public static Void main () + { + echo ("Enter a time to sleep: ") + input := Env.cur.in.readLine + try + { + time := Duration.fromStr (input) + echo ("sleeping ...") + Actor.sleep (time) + echo ("awake!") + } + catch + { + echo ("Invalid time entered") + } + } +} diff --git a/Task/Sleep/Forth/sleep.fth b/Task/Sleep/Forth/sleep.fth new file mode 100644 index 0000000000..169701cc3d --- /dev/null +++ b/Task/Sleep/Forth/sleep.fth @@ -0,0 +1,4 @@ +: sleep ( ms -- ) + ." Sleeping..." + ms + ." awake." cr ; diff --git a/Task/Sleep/Fortran/sleep.f b/Task/Sleep/Fortran/sleep.f new file mode 100644 index 0000000000..7e6c5aae44 --- /dev/null +++ b/Task/Sleep/Fortran/sleep.f @@ -0,0 +1,18 @@ +program test_sleep + + implicit none + integer :: iostat + integer :: seconds + character (32) :: argument + + if (iargc () == 1) then + call getarg (1, argument) + read (argument, *, iostat = iostat) seconds + if (iostat == 0) then + write (*, '(a)') 'Sleeping...' + call sleep (seconds) + write (*, '(a)') 'Awake!' + end if + end if + +end program test_sleep diff --git a/Task/Sleep/Frink/sleep.frink b/Task/Sleep/Frink/sleep.frink new file mode 100644 index 0000000000..632ff67aa7 --- /dev/null +++ b/Task/Sleep/Frink/sleep.frink @@ -0,0 +1,7 @@ +do + t = eval[input["Enter amount of time to sleep: ", "1 second"]] +while ! (t conforms time) + +println["Sleeping..."] +sleep[t] +println["Awake!"] diff --git a/Task/Sleep/Go/sleep.go b/Task/Sleep/Go/sleep.go new file mode 100644 index 0000000000..6a0ef5b130 --- /dev/null +++ b/Task/Sleep/Go/sleep.go @@ -0,0 +1,13 @@ +package main + +import "time" +import "fmt" + +func main() { + fmt.Print("Enter number of seconds to sleep: ") + var sec float64 + fmt.Scanf("%f", &sec) + fmt.Print("Sleeping…") + time.Sleep(time.Duration(sec * float64(time.Second))) + fmt.Println("\nAwake!") +} diff --git a/Task/Sleep/Groovy/sleep-1.groovy b/Task/Sleep/Groovy/sleep-1.groovy new file mode 100644 index 0000000000..85d65962c6 --- /dev/null +++ b/Task/Sleep/Groovy/sleep-1.groovy @@ -0,0 +1,5 @@ +def sleepTest = { + println("Sleeping...") + sleep(it) + println("Awake!") +} diff --git a/Task/Sleep/Groovy/sleep-2.groovy b/Task/Sleep/Groovy/sleep-2.groovy new file mode 100644 index 0000000000..0b59451904 --- /dev/null +++ b/Task/Sleep/Groovy/sleep-2.groovy @@ -0,0 +1,12 @@ +sleepTest(1000) +print ''' +Hmmm. That was... less than satisfying. +How about this instead? +''' +Thread.start { + (0..5).each { + println it + sleep(1000) + } +} +sleepTest(5000) diff --git a/Task/Sleep/Haskell/sleep.hs b/Task/Sleep/Haskell/sleep.hs new file mode 100644 index 0000000000..3edf902955 --- /dev/null +++ b/Task/Sleep/Haskell/sleep.hs @@ -0,0 +1,6 @@ +import Control.Concurrent + +main = do seconds <- readLn + putStrLn "Sleeping..." + threadDelay $ round $ seconds * 1000000 + putStrLn "Awake!" diff --git a/Task/Sleep/HicEst/sleep.hicest b/Task/Sleep/HicEst/sleep.hicest new file mode 100644 index 0000000000..4b66dd7c74 --- /dev/null +++ b/Task/Sleep/HicEst/sleep.hicest @@ -0,0 +1,4 @@ +DLG(NameEdit = milliseconds, Button = "Go to sleep") +WRITE(StatusBar) "Sleeping ... " +SYSTEM(WAIT = milliseconds) +WRITE(Messagebox) "Awake!" diff --git a/Task/Sleep/IDL/sleep.idl b/Task/Sleep/IDL/sleep.idl new file mode 100644 index 0000000000..6a74a86afa --- /dev/null +++ b/Task/Sleep/IDL/sleep.idl @@ -0,0 +1,4 @@ +read,i,prompt='Input sleep time in seconds: ' +print,'Sleeping...' +wait,i ; in seconds, but accepts floats(/fractional) as input +print,'Awake!' diff --git a/Task/Sleep/Icon/sleep.icon b/Task/Sleep/Icon/sleep.icon new file mode 100644 index 0000000000..6a5634ded4 --- /dev/null +++ b/Task/Sleep/Icon/sleep.icon @@ -0,0 +1,12 @@ +procedure main() + +repeat { + writes("Enter number of seconds to sleep :") + s := reads() + if s = ( 0 < integer(s)) then break + } + +write("\nSleeping for ",s," seconds.") +delay(1000 * s) +write("Awake!") +end diff --git a/Task/Sleep/J/sleep-1.j b/Task/Sleep/J/sleep-1.j new file mode 100644 index 0000000000..9942795a1c --- /dev/null +++ b/Task/Sleep/J/sleep-1.j @@ -0,0 +1,7 @@ +sleep =: 6!:3 + +sleeping=: monad define + smoutput 'Sleeping...' + sleep y + smoutput 'Awake!' +) diff --git a/Task/Sleep/J/sleep-2.j b/Task/Sleep/J/sleep-2.j new file mode 100644 index 0000000000..7da1ea2aa5 --- /dev/null +++ b/Task/Sleep/J/sleep-2.j @@ -0,0 +1,3 @@ + sleeping 0.500 NB. Sleep 500 milliseconds +Sleeping... +Awake! diff --git a/Task/Sleep/Java/sleep.java b/Task/Sleep/Java/sleep.java new file mode 100644 index 0000000000..502012c8b9 --- /dev/null +++ b/Task/Sleep/Java/sleep.java @@ -0,0 +1,15 @@ +import java.util.InputMismatchException; +import java.util.Scanner; + +public class Sleep { + public static void main(final String[] args) throws InterruptedException { + try { + int ms = new Scanner(System.in).nextInt(); //Java's sleep method accepts milliseconds + System.out.println("Sleeping..."); + Thread.sleep(ms); + System.out.println("Awake!"); + } catch (InputMismatchException inputMismatchException) { + System.err.println("Exception: " + inputMismatchException); + } + } +} diff --git a/Task/Sleep/JavaScript/sleep.js b/Task/Sleep/JavaScript/sleep.js new file mode 100644 index 0000000000..067888bdcb --- /dev/null +++ b/Task/Sleep/JavaScript/sleep.js @@ -0,0 +1,9 @@ +<script> + + setTimeout(function () { + document.write('Awake!') + }, prompt("Number of milliseconds to sleep")); + + document.write('Sleeping... '); + +</script> diff --git a/Task/Sleep/Liberty-BASIC/sleep.liberty b/Task/Sleep/Liberty-BASIC/sleep.liberty new file mode 100644 index 0000000000..4f8638f03d --- /dev/null +++ b/Task/Sleep/Liberty-BASIC/sleep.liberty @@ -0,0 +1,4 @@ +Input "Please input the number of milliseconds you would like to sleep. "; sleeptime +Print "Sleeping..." +CallDLL #kernel32, "Sleep", sleeptime As long, ret As void +Print "Awake!" diff --git a/Task/Sleep/Logo/sleep.logo b/Task/Sleep/Logo/sleep.logo new file mode 100644 index 0000000000..63a7f15ded --- /dev/null +++ b/Task/Sleep/Logo/sleep.logo @@ -0,0 +1,5 @@ +to sleep :n +print [Sleeping...] +wait :n ; units: 1/60th of a second +print [Awake.] +end diff --git a/Task/Sleep/MATLAB/sleep.m b/Task/Sleep/MATLAB/sleep.m new file mode 100644 index 0000000000..aca6653cfe --- /dev/null +++ b/Task/Sleep/MATLAB/sleep.m @@ -0,0 +1,9 @@ +function sleep() + + time = input('How many seconds would you like me to sleep for? '); + assert(time > .01); + disp('Sleeping...'); + pause(time); + disp('Awake!'); + +end diff --git a/Task/Sleep/Mathematica/sleep.math b/Task/Sleep/Mathematica/sleep.math new file mode 100644 index 0000000000..dfb7298523 --- /dev/null +++ b/Task/Sleep/Mathematica/sleep.math @@ -0,0 +1 @@ +Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];) diff --git a/Task/Sleep/NetRexx/sleep.netrexx b/Task/Sleep/NetRexx/sleep.netrexx new file mode 100644 index 0000000000..90a4f79fd5 --- /dev/null +++ b/Task/Sleep/NetRexx/sleep.netrexx @@ -0,0 +1,37 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method sleep(secs) public static binary + ms = (secs * 1000).format(null, 0) -- milliseconds, rounded to nearest integer + say 'Sleeping...' + do + Thread.sleep(ms) + catch ix = InterruptedException + say 'Sleep interrupted!' + ix.printStackTrace() + end + say 'Awake!' + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + secs = -1 + loop until \secs.datatype('N') + if secs > 0 then do + say 'Napping for' secs's' + say + sleep(secs) + end + say + say 'How many seconds do you want me to sleep? (enter something non-numeric to terminate)\-' + parse ask secs . + say + end + say + say 'Goodbye...' + say + return diff --git a/Task/Sleep/NewLISP/sleep.newlisp b/Task/Sleep/NewLISP/sleep.newlisp new file mode 100644 index 0000000000..bf9c6d67fd --- /dev/null +++ b/Task/Sleep/NewLISP/sleep.newlisp @@ -0,0 +1,3 @@ +(println "Sleeping..." ) +(sleep 2000) ; Wait for 2 seconds +(println "Awake!") diff --git a/Task/Sleep/Nimrod/sleep.nimrod b/Task/Sleep/Nimrod/sleep.nimrod new file mode 100644 index 0000000000..0d8ac6ff22 --- /dev/null +++ b/Task/Sleep/Nimrod/sleep.nimrod @@ -0,0 +1,7 @@ +import os, strutils + +echo("Enter how long I should sleep (in milliseconds):") +var timed = parseInt(readLine(stdin).string) +echo("Sleeping...") +sleep(timed) +echo("Awake!") diff --git a/Task/Sleep/OCaml/sleep-1.ocaml b/Task/Sleep/OCaml/sleep-1.ocaml new file mode 100644 index 0000000000..24e8cdf24c --- /dev/null +++ b/Task/Sleep/OCaml/sleep-1.ocaml @@ -0,0 +1,5 @@ +#load "unix.cma";; +let seconds = read_int ();; +print_endline "Sleeping...";; +Unix.sleep seconds;; (* number is integer in seconds *) +print_endline "Awake!";; diff --git a/Task/Sleep/OCaml/sleep-2.ocaml b/Task/Sleep/OCaml/sleep-2.ocaml new file mode 100644 index 0000000000..e71223b3a5 --- /dev/null +++ b/Task/Sleep/OCaml/sleep-2.ocaml @@ -0,0 +1,7 @@ +#load "unix.cma";; +#directory "+threads";; +#load "threads.cma";; +let seconds = read_float ();; +print_endline "Sleeping...";; +Thread.delay seconds;; (* number is in seconds ... but accepts fractions *) +print_endline "Awake!";; diff --git a/Task/Sleep/Objeck/sleep.objeck b/Task/Sleep/Objeck/sleep.objeck new file mode 100644 index 0000000000..52c10cb4b3 --- /dev/null +++ b/Task/Sleep/Objeck/sleep.objeck @@ -0,0 +1,11 @@ +bundle Default { + class Test { + function : Main(args : System.String[]) ~ Nil { + if(args->Size() = 1) { + "Sleeping..."->PrintLine(); + Thread->Sleep(args[0]->ToInt()); + "Awake!"->PrintLine(); + }; + } + } +} diff --git a/Task/Sleep/Objective-C/sleep.m b/Task/Sleep/Objective-C/sleep.m new file mode 100644 index 0000000000..b5eb337822 --- /dev/null +++ b/Task/Sleep/Objective-C/sleep.m @@ -0,0 +1,17 @@ +#import <Foundation/Foundation.h> + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSTimeInterval sleeptime; + + printf("wait time in seconds: "); + scanf("%f", &sleeptime); + + NSLog(@"sleeping..."); + [NSThread sleepForTimeInterval: sleeptime]; + NSLog(@"awakening..."); + + [pool release]; + return 0; +} diff --git a/Task/Sleep/Oz/sleep.oz b/Task/Sleep/Oz/sleep.oz new file mode 100644 index 0000000000..3c2523c718 --- /dev/null +++ b/Task/Sleep/Oz/sleep.oz @@ -0,0 +1,8 @@ +declare + class TextFile from Open.file Open.text end + StdIn = {New TextFile init(name:stdin)} + WaitTime = {String.toInt {StdIn getS($)}} +in + {System.showInfo "Sleeping..."} + {Delay WaitTime} %% in milliseconds + {System.showInfo "Awake!"} diff --git a/Task/Sleep/PARI-GP/sleep-1.pari b/Task/Sleep/PARI-GP/sleep-1.pari new file mode 100644 index 0000000000..748efc2e07 --- /dev/null +++ b/Task/Sleep/PARI-GP/sleep-1.pari @@ -0,0 +1,7 @@ +sleep(ms)={ + print("Sleeping..."); + while((ms-=gettime()) > 0,); + print("Awake!") +}; + +sleep(input()) diff --git a/Task/Sleep/PARI-GP/sleep-2.pari b/Task/Sleep/PARI-GP/sleep-2.pari new file mode 100644 index 0000000000..3110f04ed5 --- /dev/null +++ b/Task/Sleep/PARI-GP/sleep-2.pari @@ -0,0 +1,8 @@ +sleep(s)={ + print("Sleeping..."); + alarm(s); + trap(alarmer,,while(1,)); + print("Awake!") +}; + +sleep(input()) diff --git a/Task/Sleep/PHP/sleep-1.php b/Task/Sleep/PHP/sleep-1.php new file mode 100644 index 0000000000..0ab72e7d16 --- /dev/null +++ b/Task/Sleep/PHP/sleep-1.php @@ -0,0 +1,4 @@ +$seconds = 42; +echo "Sleeping...\n"; +sleep($seconds); # number is integer in seconds +echo "Awake!\n"; diff --git a/Task/Sleep/PHP/sleep-2.php b/Task/Sleep/PHP/sleep-2.php new file mode 100644 index 0000000000..e78d8f4b95 --- /dev/null +++ b/Task/Sleep/PHP/sleep-2.php @@ -0,0 +1,4 @@ +$microseconds = 42000000; +echo "Sleeping...\n"; +usleep($microseconds); # number is integer in microseconds +echo "Awake!\n"; diff --git a/Task/Sleep/PHP/sleep-3.php b/Task/Sleep/PHP/sleep-3.php new file mode 100644 index 0000000000..8dbb8b2e87 --- /dev/null +++ b/Task/Sleep/PHP/sleep-3.php @@ -0,0 +1,4 @@ +$nanoseconds = 42000000000; +echo "Sleeping...\n"; +time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds +echo "Awake!\n"; diff --git a/Task/Sleep/PL-I/sleep.pli b/Task/Sleep/PL-I/sleep.pli new file mode 100644 index 0000000000..ff2f4f1c9e --- /dev/null +++ b/Task/Sleep/PL-I/sleep.pli @@ -0,0 +1,3 @@ +put ('sleeping'); +delay (2000); /* wait for 2 seconds (=2000 milliseconds). */ +put ('awake'); diff --git a/Task/Sleep/Perl-6/sleep.pl6 b/Task/Sleep/Perl-6/sleep.pl6 new file mode 100644 index 0000000000..17931b853a --- /dev/null +++ b/Task/Sleep/Perl-6/sleep.pl6 @@ -0,0 +1,4 @@ +my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096; +say "Sleeping..."; +sleep $sec; +say "Awake!"; diff --git a/Task/Sleep/Perl/sleep-1.pl b/Task/Sleep/Perl/sleep-1.pl new file mode 100644 index 0000000000..0afc50a40c --- /dev/null +++ b/Task/Sleep/Perl/sleep-1.pl @@ -0,0 +1,4 @@ +$seconds = <>; +print "Sleeping...\n"; +sleep $seconds; # number is in seconds +print "Awake!\n"; diff --git a/Task/Sleep/Perl/sleep-2.pl b/Task/Sleep/Perl/sleep-2.pl new file mode 100644 index 0000000000..b9061fbfec --- /dev/null +++ b/Task/Sleep/Perl/sleep-2.pl @@ -0,0 +1,11 @@ +use Time::HiRes qw( usleep nanosleep ); + +$microseconds = <>; +print "Sleeping...\n"; +usleep $microseconds; +print "Awake!\n"; + +$nanoseconds = <>; +print "Sleeping...\n"; +nanosleep $nanoseconds; +print "Awake!\n"; diff --git a/Task/Sleep/PicoLisp/sleep-1.l b/Task/Sleep/PicoLisp/sleep-1.l new file mode 100644 index 0000000000..d29adc694b --- /dev/null +++ b/Task/Sleep/PicoLisp/sleep-1.l @@ -0,0 +1,3 @@ +(prinl "Sleeping..." ) +(wait 2000) # Wait for 2 seconds +(prinl "Awake!") diff --git a/Task/Sleep/PicoLisp/sleep-2.l b/Task/Sleep/PicoLisp/sleep-2.l new file mode 100644 index 0000000000..1eaa12ee86 --- /dev/null +++ b/Task/Sleep/PicoLisp/sleep-2.l @@ -0,0 +1,3 @@ +(prinl "Sleeping..." ) +(call 'sleep 2) # Wait for 2 seconds +(prinl "Awake!") diff --git a/Task/Sleep/PowerShell/sleep.psh b/Task/Sleep/PowerShell/sleep.psh new file mode 100644 index 0000000000..15dec5125e --- /dev/null +++ b/Task/Sleep/PowerShell/sleep.psh @@ -0,0 +1,4 @@ +$d = [int] (Read-Host Duration in seconds) +Write-Host Sleeping ... +Start-Sleep $d +Write-Host Awake! diff --git a/Task/Sleep/Prolog/sleep.pro b/Task/Sleep/Prolog/sleep.pro new file mode 100644 index 0000000000..b486f69eca --- /dev/null +++ b/Task/Sleep/Prolog/sleep.pro @@ -0,0 +1,4 @@ +rosetta_sleep(Time) :- + writeln('Sleeping...'), + sleep(Time), + writeln('Awake!'). diff --git a/Task/Sleep/Protium/sleep-1.protium b/Task/Sleep/Protium/sleep-1.protium new file mode 100644 index 0000000000..dfad53e3de --- /dev/null +++ b/Task/Sleep/Protium/sleep-1.protium @@ -0,0 +1,4 @@ +<@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@> +<@ SAYLIT>Sleeping</@> +<@ ACTPAUVAR>secs</@> +<@ SAYLIT>Awake</@> diff --git a/Task/Sleep/Protium/sleep-2.protium b/Task/Sleep/Protium/sleep-2.protium new file mode 100644 index 0000000000..230d2650cd --- /dev/null +++ b/Task/Sleep/Protium/sleep-2.protium @@ -0,0 +1,4 @@ +<# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#> +<# MontrezLittéralement>Sleeping</#> +<# AgissezFaireUnePauseVariable>secs</#> +<# MontrezLittéralement>Awake</#> diff --git a/Task/Sleep/Protium/sleep-3.protium b/Task/Sleep/Protium/sleep-3.protium new file mode 100644 index 0000000000..e4c71629d0 --- /dev/null +++ b/Task/Sleep/Protium/sleep-3.protium @@ -0,0 +1,4 @@ +<@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@> +<@ 显示_字串_>Sleeping</@> +<@ 运行_暂停动变量_>secs</@> +<@ 显示_字串_>Awake</@> diff --git a/Task/Sleep/PureBasic/sleep.purebasic b/Task/Sleep/PureBasic/sleep.purebasic new file mode 100644 index 0000000000..e2044244fe --- /dev/null +++ b/Task/Sleep/PureBasic/sleep.purebasic @@ -0,0 +1,11 @@ +If OpenConsole() + + Print("Enter a time(milliseconds) to sleep: ") + x.i = Val(Input()) + PrintN("Sleeping...") + Delay(x) ;in milliseconds + PrintN("Awake!") + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Sleep/Python/sleep.py b/Task/Sleep/Python/sleep.py new file mode 100644 index 0000000000..8741a86dc1 --- /dev/null +++ b/Task/Sleep/Python/sleep.py @@ -0,0 +1,6 @@ +import time + +seconds = float(raw_input()) +print "Sleeping..." +time.sleep(seconds) # number is in seconds ... but accepts fractions +print "Awake!" diff --git a/Task/Sleep/R/sleep.r b/Task/Sleep/R/sleep.r new file mode 100644 index 0000000000..12ba992a0d --- /dev/null +++ b/Task/Sleep/R/sleep.r @@ -0,0 +1,9 @@ +sleep <- function(time=1) +{ + message("Sleeping...") + flush.console() + Sys.sleep(time) + message("Awake!") +} + +sleep() diff --git a/Task/Sleep/REBOL/sleep.rebol b/Task/Sleep/REBOL/sleep.rebol new file mode 100644 index 0000000000..133d5be689 --- /dev/null +++ b/Task/Sleep/REBOL/sleep.rebol @@ -0,0 +1,11 @@ +REBOL [ + Title: "Sleep Main Thread" + Date: 2009-12-15 + Author: oofoe + URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread +] + +naptime: to-integer ask "Please enter sleep time in seconds: " +print "Sleeping..." +wait naptime +print "Awake!" diff --git a/Task/Sleep/REXX/sleep.rexx b/Task/Sleep/REXX/sleep.rexx new file mode 100644 index 0000000000..893e9906a7 --- /dev/null +++ b/Task/Sleep/REXX/sleep.rexx @@ -0,0 +1,6 @@ +/*REXX program to sleep x seconds (base in the argument). */ +parse arg secs . /*get a (possible) argument. */ +secs=word(secs 0,1) /*if not present, assume 0 (zero)*/ +say 'Sleeping' secs "seconds." /*tell 'em what's happening. */ +call delay(secs) /*snooze. Hopefully, a short nap*/ +say 'Awake!' /*and tell 'em we're running. */ diff --git a/Task/Sleep/Racket/sleep.rkt b/Task/Sleep/Racket/sleep.rkt new file mode 100644 index 0000000000..d05685e790 --- /dev/null +++ b/Task/Sleep/Racket/sleep.rkt @@ -0,0 +1,7 @@ +#lang racket +(displayln "Enter a time (in seconds): ") +(define time (read)) +(when (number? time) + (displayln "Sleeping...") + (sleep time) + (displayln "Awake!")) diff --git a/Task/Sleep/Retro/sleep.retro b/Task/Sleep/Retro/sleep.retro new file mode 100644 index 0000000000..4f46f4e9c3 --- /dev/null +++ b/Task/Sleep/Retro/sleep.retro @@ -0,0 +1,6 @@ +: sleep ( n- ) + [ time [ time over - 1 > ] until drop ] times ; + : test + "\nTime to sleep (in seconds): " puts getToken toNumber + "\nSleeping..." sleep + "\nAwake!\n" ; diff --git a/Task/Sleep/Ruby/sleep.rb b/Task/Sleep/Ruby/sleep.rb new file mode 100644 index 0000000000..f2d0e9dc47 --- /dev/null +++ b/Task/Sleep/Ruby/sleep.rb @@ -0,0 +1,5 @@ +seconds = gets.to_f +puts "Sleeping..." +sleep(seconds) # number is in seconds ... but accepts fractions +# Minimum resolution is system dependent. +puts "Awake!" diff --git a/Task/Sleep/Scala/sleep.scala b/Task/Sleep/Scala/sleep.scala new file mode 100644 index 0000000000..66cf544d4d --- /dev/null +++ b/Task/Sleep/Scala/sleep.scala @@ -0,0 +1,9 @@ +import java.util.Scanner + +object Sleeper extends Application { + val input = new Scanner(System.in) + val ms = input.nextInt + System.out.println("Sleeping...") + Thread.sleep(ms) + System.out.println("Awake!") +} diff --git a/Task/Sleep/Scheme/sleep.ss b/Task/Sleep/Scheme/sleep.ss new file mode 100644 index 0000000000..6adc7888aa --- /dev/null +++ b/Task/Sleep/Scheme/sleep.ss @@ -0,0 +1,11 @@ +(use format) +(use srfi-18) + +(format #t "Enter a time (in seconds): ") +(let ((time (read))) ; converts input to a number, if possible + (if (number? time) + (begin + (format #t "Sleeping...~&") + (thread-sleep! time) + (format #t "Awake!~&")) + (format #t "You must enter a number~&"))) diff --git a/Task/Sleep/Seed7/sleep.seed7 b/Task/Sleep/Seed7/sleep.seed7 new file mode 100644 index 0000000000..eba1d13233 --- /dev/null +++ b/Task/Sleep/Seed7/sleep.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + include "duration.s7i"; + +const proc: main is func + local + var integer: secondsToSleep is 0; + begin + write("Enter number of seconds to sleep: "); + readln(secondsToSleep); + writeln("Sleeping..."); + wait(secondsToSleep . SECONDS); + writeln("Awake!"); + end func; diff --git a/Task/Sleep/Smalltalk/sleep-1.st b/Task/Sleep/Smalltalk/sleep-1.st new file mode 100644 index 0000000000..55a033d7a3 --- /dev/null +++ b/Task/Sleep/Smalltalk/sleep-1.st @@ -0,0 +1,4 @@ +t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber. +Transcript show: 'Sleeping...'. +(Delay forSeconds: t) wait. +Transcript show: 'Awake!'. diff --git a/Task/Sleep/Smalltalk/sleep-2.st b/Task/Sleep/Smalltalk/sleep-2.st new file mode 100644 index 0000000000..42309a4ff3 --- /dev/null +++ b/Task/Sleep/Smalltalk/sleep-2.st @@ -0,0 +1,4 @@ +t := (Dialog request: 'Enter time in seconds') asNumber. +Transcript show: 'Sleeping...'. +(Delay forSeconds: t) wait. +Transcript show: 'Awake!'. diff --git a/Task/Sleep/Standard-ML/sleep.ml b/Task/Sleep/Standard-ML/sleep.ml new file mode 100644 index 0000000000..dc947357b6 --- /dev/null +++ b/Task/Sleep/Standard-ML/sleep.ml @@ -0,0 +1,8 @@ +(TextIO.print "input a number of seconds please: "; +let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in + TextIO.print "Sleeping...\n"; + OS.Process.sleep (Time.fromReal seconds); (* it takes a Time.time data structure as arg, + but in my implementation it seems to round down to the nearest second. + I dunno why; it doesn't say anything about this in the documentation *) + TextIO.print "Awake!\n" +end) diff --git a/Task/Sleep/Suneido/sleep.suneido b/Task/Sleep/Suneido/sleep.suneido new file mode 100644 index 0000000000..b2a20cf804 --- /dev/null +++ b/Task/Sleep/Suneido/sleep.suneido @@ -0,0 +1,6 @@ +function (time) + { + Print("Sleeping...") + Sleep(time) // time is in milliseconds + Print("Awake!") + } diff --git a/Task/Sleep/TUSCRIPT/sleep.tuscript b/Task/Sleep/TUSCRIPT/sleep.tuscript new file mode 100644 index 0000000000..8e2f062573 --- /dev/null +++ b/Task/Sleep/TUSCRIPT/sleep.tuscript @@ -0,0 +1,5 @@ +$$ MODE TUSCRIPT +secondsrange=2 +PRINT "Sleeping ",secondsrange," seconds " +WAIT #secondsrange +PRINT "Awake after Naping ",secondsrange, " seconds" diff --git a/Task/Sleep/Tcl/sleep-1.tcl b/Task/Sleep/Tcl/sleep-1.tcl new file mode 100644 index 0000000000..5efc5bf8de --- /dev/null +++ b/Task/Sleep/Tcl/sleep-1.tcl @@ -0,0 +1,6 @@ +puts -nonewline "Enter a number of milliseconds to sleep: " +flush stdout +set millis [gets stdin] +puts Sleeping... +after $millis +puts Awake! diff --git a/Task/Sleep/Tcl/sleep-2.tcl b/Task/Sleep/Tcl/sleep-2.tcl new file mode 100644 index 0000000000..3308d10237 --- /dev/null +++ b/Task/Sleep/Tcl/sleep-2.tcl @@ -0,0 +1,8 @@ +puts -nonewline "Enter a number of milliseconds to sleep: " +flush stdout +set millis [gets stdin] +set ::wakupflag 0 +puts Sleeping... +after $millis set ::wakeupflag 1 +vwait ::wakeupflag +puts Awake! diff --git a/Task/Sleep/UNIX-Shell/sleep.sh b/Task/Sleep/UNIX-Shell/sleep.sh new file mode 100644 index 0000000000..b38c787bf7 --- /dev/null +++ b/Task/Sleep/UNIX-Shell/sleep.sh @@ -0,0 +1,5 @@ +printf "Enter a time in seconds to sleep: " +read seconds +echo "Sleeping..." +sleep "$seconds" +echo "Awake!" diff --git a/Task/Sleep/VBScript/sleep.vbscript b/Task/Sleep/VBScript/sleep.vbscript new file mode 100644 index 0000000000..8b7fb15908 --- /dev/null +++ b/Task/Sleep/VBScript/sleep.vbscript @@ -0,0 +1,4 @@ +iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org") +WScript.Echo "Sleeping..." +WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds +WScript.Echo "Awake!" diff --git a/Task/Sleep/Vedit-macro-language/sleep.vedit b/Task/Sleep/Vedit-macro-language/sleep.vedit new file mode 100644 index 0000000000..32e82fc259 --- /dev/null +++ b/Task/Sleep/Vedit-macro-language/sleep.vedit @@ -0,0 +1,4 @@ +#1 = Get_Num("Sleep time in 1/10 seconds: ") +Message("Sleeping...\n") +Sleep(#1) +Message("Awake!\n") diff --git a/Task/Sockets/0DESCRIPTION b/Task/Sockets/0DESCRIPTION new file mode 100644 index 0000000000..7311c00940 --- /dev/null +++ b/Task/Sockets/0DESCRIPTION @@ -0,0 +1 @@ +For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required. diff --git a/Task/Sockets/1META.yaml b/Task/Sockets/1META.yaml new file mode 100644 index 0000000000..688669690e --- /dev/null +++ b/Task/Sockets/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Networking and Web Interaction diff --git a/Task/Sockets/Ada/sockets.ada b/Task/Sockets/Ada/sockets.ada new file mode 100644 index 0000000000..de016bbee9 --- /dev/null +++ b/Task/Sockets/Ada/sockets.ada @@ -0,0 +1,20 @@ +with GNAT.Sockets; use GNAT.Sockets; + +procedure SocketSend is + procedure sendData (IP : String; Msg : String) is + Client : Socket_Type; + Address : Sock_Addr_Type; + Channel : Stream_Access; + begin + Create_Socket (Client); + Address.Addr := Inet_Addr(ip); + Address.Port := 256; + Connect_Socket (Client, Address); + Channel := Stream (Client); + String'Write (Channel, Msg); + Close_Socket (Client); + end; +begin + Initialize; + sendData ("127.0.0.1","hello socket world"); +end; diff --git a/Task/Sockets/AutoHotkey/sockets.ahk b/Task/Sockets/AutoHotkey/sockets.ahk new file mode 100644 index 0000000000..b66a8ec52b --- /dev/null +++ b/Task/Sockets/AutoHotkey/sockets.ahk @@ -0,0 +1,125 @@ +Network_Port = 256 +Network_Address = 127.0.0.1 +NewData := false +DataReceived = +GoSub, Connection_Init +SendData(socket,"hello socket world") +return + +Connection_Init: +OnExit, ExitSub + +socket := ConnectToAddress(Network_Address, Network_Port) +if socket = -1 + ExitApp + +Process, Exist +DetectHiddenWindows On +ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel) +DetectHiddenWindows Off + +NotificationMsg = 0x5556 +OnMessage(NotificationMsg, "ReceiveData") + +FD_READ = 1 +FD_CLOSE = 32 +if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CLOSE) +{ + MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") + ExitApp +} + +return + + +ConnectToAddress(IPAddress, Port) +{ + VarSetCapacity(wsaData, 32) + result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) + if ErrorLevel + { + MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required. + return -1 + } + if result + { + MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") + return -1 + } + AF_INET = 2 + SOCK_STREAM = 1 + IPPROTO_TCP = 6 + socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP) + if socket = -1 + { + MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") + return -1 + } + SizeOfSocketAddress = 16 + VarSetCapacity(SocketAddress, SizeOfSocketAddress) + InsertInteger(2, SocketAddress, 0, AF_INET) + InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2) + InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4) + if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress) + { + MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?" + return -1 + } + return socket +} + +ReceiveData(wParam, lParam) +{ + global DataReceived + global NewData + socket := wParam + ReceivedDataSize = 4096 + Loop + { + VarSetCapacity(ReceivedData, ReceivedDataSize, 0) + ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0) + if ReceivedDataLength = 0 + ExitApp + if ReceivedDataLength = -1 + { + WinsockError := DllCall("Ws2_32\WSAGetLastError") + if WinsockError = 10035 + { + DataReceived = %TempDataReceived% + NewData := true + return 1 + } + if WinsockError <> 10054 + MsgBox % "recv() indicated Winsock error " . WinsockError + ExitApp + } + if (A_Index = 1) + TempDataReceived = + TempDataReceived = %TempDataReceived%%ReceivedData% + } + return 1 +} + +SendData(wParam,SendData) +{ + socket := wParam + SendDataSize := VarSetCapacity(SendData) + SendDataSize += 1 + sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0) +} + +InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4) +{ + Loop %pSize% + DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF) +} + +ReceiveProcedure: + if NewData + GuiControl, , ReceivedText, %DataReceived% + NewData := false +Return + +ExitSub: +DllCall("Ws2_32\WSACleanup") +ExitApp diff --git a/Task/Sockets/BBC-BASIC/sockets.bbc b/Task/Sockets/BBC-BASIC/sockets.bbc new file mode 100644 index 0000000000..48652367d4 --- /dev/null +++ b/Task/Sockets/BBC-BASIC/sockets.bbc @@ -0,0 +1,12 @@ + INSTALL @lib$+"SOCKLIB" + PROC_initsockets + + socket% = FN_tcpconnect("localhost", "256") + IF socket% = 0 ERROR 100, "Failed to open socket" + + REM Don't use FN_writesocket since an error is expected + msg$ = "hello socket world" + SYS `send`, socket%, !^msg$, LEN(msg$), 0 TO result% + + PROC_closesocket(socket%) + PROC_exitsockets diff --git a/Task/Sockets/C/sockets.c b/Task/Sockets/C/sockets.c new file mode 100644 index 0000000000..4d084ccb73 --- /dev/null +++ b/Task/Sockets/C/sockets.c @@ -0,0 +1,37 @@ +#include <stdio.h> +#include <string.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> + +const char *msg = "hello socket world"; + +int main() +{ + int i, sock, len, slen; + + struct addrinfo hints, *addrs; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + if (0 == getaddrinfo("localhost", "256", &hints, &addrs)) + { + sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol); + if ( sock >= 0 ) + { + if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 ) + { + const char *pm = msg; + do + { + len = strlen(pm); + slen = send(sock, pm, len, 0); + pm += slen; + } while ((0 <= slen) && (slen < len)); + } + close(sock); + } + freeaddrinfo(addrs); + } +} diff --git a/Task/Sockets/Clojure/sockets.clj b/Task/Sockets/Clojure/sockets.clj new file mode 100644 index 0000000000..254aef7c95 --- /dev/null +++ b/Task/Sockets/Clojure/sockets.clj @@ -0,0 +1,10 @@ +(ns socket-example + (:import (java.net Socket) + (java.io PrintWriter))) + +(defn send-data [host msg] + (with-open [sock (Socket. host 256) + printer (PrintWriter. (.getOutputStream sock))] + (.println printer msg))) + +(send-data "localhost" "hello socket world") diff --git a/Task/Sockets/Common-Lisp/sockets-1.lisp b/Task/Sockets/Common-Lisp/sockets-1.lisp new file mode 100644 index 0000000000..eaa8f8ac1d --- /dev/null +++ b/Task/Sockets/Common-Lisp/sockets-1.lisp @@ -0,0 +1,4 @@ +CL-USER> (usocket:with-client-socket (socket stream "localhost" 256) + (write-line "hello socket world" stream) + (values)) +; No value diff --git a/Task/Sockets/Common-Lisp/sockets-2.lisp b/Task/Sockets/Common-Lisp/sockets-2.lisp new file mode 100644 index 0000000000..77bbd335a8 --- /dev/null +++ b/Task/Sockets/Common-Lisp/sockets-2.lisp @@ -0,0 +1,2 @@ +aurora ~% sudo nc -l -p 256 +hello socket world diff --git a/Task/Sockets/D/sockets.d b/Task/Sockets/D/sockets.d new file mode 100644 index 0000000000..3af3e967aa --- /dev/null +++ b/Task/Sockets/D/sockets.d @@ -0,0 +1,13 @@ +module socket ; +import std.stdio ; +import std.socket ; +version(Win32) { + // For Win32 systems, need to link with ws2_32.lib. + pragma(lib, "ws2_32.lib") ; +} +void main() { + auto socket = new Socket(AddressFamily.INET, SocketType.STREAM) ; + socket.connect(new InternetAddress("localhost",256)) ; + writefln(socket.send(cast(void[])"hello socket world"), " bytes sent.") ; + socket.close() ; +} diff --git a/Task/Sockets/Delphi/sockets.delphi b/Task/Sockets/Delphi/sockets.delphi new file mode 100644 index 0000000000..3b35d7322f --- /dev/null +++ b/Task/Sockets/Delphi/sockets.delphi @@ -0,0 +1,19 @@ +program Sockets; + +{$APPTYPE CONSOLE} + +uses IdTCPClient; + +var + lTCPClient: TIdTCPClient; +begin + lTCPClient := TIdTCPClient.Create(nil); + try + lTCPClient.Host := '127.0.0.1'; + lTCPClient.Port := 256; + lTCPClient.Connect; + lTCPClient.IOHandler.WriteLn('hello socket world'); + finally + lTCPClient.Free; + end; +end. diff --git a/Task/Sockets/Erlang/sockets.erl b/Task/Sockets/Erlang/sockets.erl new file mode 100644 index 0000000000..28c1bc5693 --- /dev/null +++ b/Task/Sockets/Erlang/sockets.erl @@ -0,0 +1,8 @@ +-module(socket). +-export([start/0]). + +start() -> + {ok, Sock} = gen_tcp:connect("localhost", 256, + [binary, {packet, 0}]), + ok = gen_tcp:send(Sock, "hello socket world"), + ok = gen_tcp:close(Sock). diff --git a/Task/Sockets/Factor/sockets.factor b/Task/Sockets/Factor/sockets.factor new file mode 100644 index 0000000000..d5453d1f58 --- /dev/null +++ b/Task/Sockets/Factor/sockets.factor @@ -0,0 +1 @@ +"localhost" 256 <inet> utf8 [ "hello socket world" print ] with-client diff --git a/Task/Sockets/Fantom/sockets.fantom b/Task/Sockets/Fantom/sockets.fantom new file mode 100644 index 0000000000..0cba49dda8 --- /dev/null +++ b/Task/Sockets/Fantom/sockets.fantom @@ -0,0 +1,14 @@ +using inet + +class Socket +{ + public static Void main () + { + sock := TcpSocket() + sock.connect(IpAddr("localhost"), 256) + + sock.out.printLine("hello socket world") + sock.out.flush + sock.close + } +} diff --git a/Task/Sockets/Forth/sockets.fth b/Task/Sockets/Forth/sockets.fth new file mode 100644 index 0000000000..ec4d765e9d --- /dev/null +++ b/Task/Sockets/Forth/sockets.fth @@ -0,0 +1,7 @@ +include unix/socket.fs + +s" localhost" 256 open-socket + +dup s" hello socket world" rot write-socket + +close-socket diff --git a/Task/Sockets/Go/sockets.go b/Task/Sockets/Go/sockets.go new file mode 100644 index 0000000000..166fbcc285 --- /dev/null +++ b/Task/Sockets/Go/sockets.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "net" +) + +func main() { + conn, err := net.Dial("tcp", "localhost:256") + if err != nil { + fmt.Println(err) + return + } + _, err = conn.Write([]byte("hello socket world")) + if err != nil { + fmt.Println(err) + return + } + conn.Close() +} diff --git a/Task/Sockets/Groovy/sockets.groovy b/Task/Sockets/Groovy/sockets.groovy new file mode 100644 index 0000000000..b949f691b8 --- /dev/null +++ b/Task/Sockets/Groovy/sockets.groovy @@ -0,0 +1,3 @@ +s = new java.net.Socket("localhost", 256) +s << "hello socket world" +s.close() diff --git a/Task/Sockets/Haskell/sockets-1.hs b/Task/Sockets/Haskell/sockets-1.hs new file mode 100644 index 0000000000..4cdb0ca236 --- /dev/null +++ b/Task/Sockets/Haskell/sockets-1.hs @@ -0,0 +1,3 @@ +import Network + +main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world" diff --git a/Task/Sockets/Haskell/sockets-2.hs b/Task/Sockets/Haskell/sockets-2.hs new file mode 100644 index 0000000000..04e3385e8e --- /dev/null +++ b/Task/Sockets/Haskell/sockets-2.hs @@ -0,0 +1,8 @@ +link cfunc +procedure main () + hello("localhost", 1024) +end + +procedure hello (host, port) + write(tconnect(host, port) | stop("unable to connect to", host, ":", port) , "hello socket world") +end diff --git a/Task/Sockets/Haskell/sockets-3.hs b/Task/Sockets/Haskell/sockets-3.hs new file mode 100644 index 0000000000..be15c667b8 --- /dev/null +++ b/Task/Sockets/Haskell/sockets-3.hs @@ -0,0 +1,16 @@ +procedure main(arglist) #: usage socket port hostname or socket port + hello(arglist[2]|"",arglist[1]) +end + +procedure hello(host,port) + local s + /host := "" + host ||:= ":" + host ||:= 0 < 65536 > port | runerr(103,port) + if s := open(host,"n") then { + write(s, "hello socket world.") + close(s) + } + else stop("Unable to connect to ",host,":",port) + return +end diff --git a/Task/Sockets/IDL/sockets.idl b/Task/Sockets/IDL/sockets.idl new file mode 100644 index 0000000000..518b53d7ae --- /dev/null +++ b/Task/Sockets/IDL/sockets.idl @@ -0,0 +1,3 @@ +socket, unit, 'localhost',256,/get_lun +printf,unit,"hello socket world" +close, unit diff --git a/Task/Sockets/J/sockets.j b/Task/Sockets/J/sockets.j new file mode 100644 index 0000000000..265f3f9a2f --- /dev/null +++ b/Task/Sockets/J/sockets.j @@ -0,0 +1,5 @@ + coinsert'jsocket' [ require 'socket' NB. Sockets library + socket =. >{.sdcheck sdsocket'' NB. Open a socket + host =. sdcheck sdgethostbyname 'localhost' NB. Resolve host + sdcheck sdconnect socket ; host ,< 256 NB. Create connection to port 256 + sdcheck 'hello socket world' sdsend socket , 0 NB. Send msg diff --git a/Task/Sockets/Java/sockets.java b/Task/Sockets/Java/sockets.java new file mode 100644 index 0000000000..b99921043c --- /dev/null +++ b/Task/Sockets/Java/sockets.java @@ -0,0 +1,14 @@ +import java.io.IOException; +import java.net.*; +public class SocketSend { + public static void main(String args[]) throws IOException { + sendData("localhost", "hello socket world"); + } + + public static void sendData(String host, String msg) throws IOException { + Socket sock = new Socket( host, 256 ); + sock.getOutputStream().write(msg.getBytes()); + sock.getOutputStream().flush(); + sock.close(); + } +} diff --git a/Task/Sockets/Lua/sockets.lua b/Task/Sockets/Lua/sockets.lua new file mode 100644 index 0000000000..487186de05 --- /dev/null +++ b/Task/Sockets/Lua/sockets.lua @@ -0,0 +1,6 @@ +socket = require "socket" +host, port = "127.0.0.1", 256 + +sid = socket.udp() +sid:sendto( "hello socket world", host, port ) +sid:close() diff --git a/Task/Sockets/Nemerle/sockets.nemerle b/Task/Sockets/Nemerle/sockets.nemerle new file mode 100644 index 0000000000..580a9aabe4 --- /dev/null +++ b/Task/Sockets/Nemerle/sockets.nemerle @@ -0,0 +1,13 @@ +using System.Text; +using System.Net.Sockets; + +module Program +{ + Main() : void + { + def sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + sock.Connect("127.0.0.1", 1000); + _ = sock.Send(Encoding.ASCII.GetBytes("Hell, world!")); + sock.Close(); + } +} diff --git a/Task/Sockets/NetRexx/sockets.netrexx b/Task/Sockets/NetRexx/sockets.netrexx new file mode 100644 index 0000000000..dda4d89079 --- /dev/null +++ b/Task/Sockets/NetRexx/sockets.netrexx @@ -0,0 +1,28 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +import java.net. + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg host':'port':'message + if host = '' then host = 'localhost' + if port = '' then port = 256 + if message = '' then message = 'hello socket world' + sendToSocket(host, port, message) + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method sendToSocket(host, port, message) public static + do + sokt = Socket(host, port) + soks = sokt.getOutputStream() + soks.write((String message).getBytes()) + soks.flush() + sokt.close() + catch ix = IOException + ix.printStackTrace() + end + return diff --git a/Task/Sockets/OCaml/sockets-1.ocaml b/Task/Sockets/OCaml/sockets-1.ocaml new file mode 100644 index 0000000000..e46658d7a3 --- /dev/null +++ b/Task/Sockets/OCaml/sockets-1.ocaml @@ -0,0 +1,11 @@ +open Unix + +let init_socket addr port = + let inet_addr = (gethostbyname addr).h_addr_list.(0) in + let sockaddr = ADDR_INET (inet_addr, port) in + let sock = socket PF_INET SOCK_STREAM 0 in + connect sock sockaddr; + (* convert the file descriptor into high-level channels: *) + let outchan = out_channel_of_descr sock in + let inchan = in_channel_of_descr sock in + (inchan, outchan) diff --git a/Task/Sockets/OCaml/sockets-2.ocaml b/Task/Sockets/OCaml/sockets-2.ocaml new file mode 100644 index 0000000000..65fa659ca7 --- /dev/null +++ b/Task/Sockets/OCaml/sockets-2.ocaml @@ -0,0 +1,4 @@ +let () = + let ic, oc = init_socket "localhost" 256 in + output_string oc "hello socket world"; +;; diff --git a/Task/Sockets/Objeck/sockets.objeck b/Task/Sockets/Objeck/sockets.objeck new file mode 100644 index 0000000000..3ff6c76b3e --- /dev/null +++ b/Task/Sockets/Objeck/sockets.objeck @@ -0,0 +1,13 @@ +use Net; + +bundle Default { + class Socket { + function : Main(args : String[]) ~ Nil { + socket := TCPSocket->New("localhost", 256); + if(socket->IsOpen()) { + socket->WriteString("hello socket world"); + socket->Close(); + } + } + } +} diff --git a/Task/Sockets/Objective-C/sockets.m b/Task/Sockets/Objective-C/sockets.m new file mode 100644 index 0000000000..e099d64a0f --- /dev/null +++ b/Task/Sockets/Objective-C/sockets.m @@ -0,0 +1,20 @@ +// declare the class to conform to NSStreamDelegate protocol + +// in some method +NSOutputStream *oStream; +[NSStream getStreamsToHost:[NSHost hostWithName:@"localhost"] port:256 inputStream:NULL outputStream:&oStream]; +[oStream setDelegate:self]; +[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; +[oStream open]; + + +// later, in the same class: +- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent { + NSOutputStream *oStream = (NSOutputStream *)aStream; + if (streamEvent == NSStreamEventHasBytesAvailable) { + NSString *str = @"hello socket world"; + const char *rawstring = [str UTF8String]; + [oStream write:rawstring maxLength:strlen(rawstring)]; + [oStream close]; + } +} diff --git a/Task/Sockets/Oz/sockets.oz b/Task/Sockets/Oz/sockets.oz new file mode 100644 index 0000000000..ba97453d47 --- /dev/null +++ b/Task/Sockets/Oz/sockets.oz @@ -0,0 +1,6 @@ +declare + Socket = {New Open.socket init} +in + {Socket connect(port:256)} + {Socket write(vs:"hello socket world")} + {Socket close} diff --git a/Task/Sockets/PHP/sockets.php b/Task/Sockets/PHP/sockets.php new file mode 100644 index 0000000000..1360ec26b4 --- /dev/null +++ b/Task/Sockets/PHP/sockets.php @@ -0,0 +1,3 @@ +$socket = fsockopen('localhost', 256); +fputs($socket, 'hello socket world'); +fclose($socket); diff --git a/Task/Sockets/Perl-6/sockets.pl6 b/Task/Sockets/Perl-6/sockets.pl6 new file mode 100644 index 0000000000..b5d16a247f --- /dev/null +++ b/Task/Sockets/Perl-6/sockets.pl6 @@ -0,0 +1,6 @@ +my $host = '127.0.0.1'; +my $port = 256; + +my $client = IO::Socket::INET.new(:$host, :$port); +$client.send( 'hello socket world' ); +$client.close; diff --git a/Task/Sockets/Perl/sockets-1.pl b/Task/Sockets/Perl/sockets-1.pl new file mode 100644 index 0000000000..cafe99dc30 --- /dev/null +++ b/Task/Sockets/Perl/sockets-1.pl @@ -0,0 +1,9 @@ +use Socket; + +$host = gethostbyname('localhost'); +$in = sockaddr_in(256, $host); +$proto = getprotobyname('tcp'); +socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto); +connect(Socket_Handle, $in); +send(Socket_Handle, 'hello socket world', 0, $in); +close(Socket_Handle); diff --git a/Task/Sockets/Perl/sockets-2.pl b/Task/Sockets/Perl/sockets-2.pl new file mode 100644 index 0000000000..df3b95d68d --- /dev/null +++ b/Task/Sockets/Perl/sockets-2.pl @@ -0,0 +1,7 @@ +use Socket::Class; + +$sock = Socket::Class->new( + 'remote_port' => 256, +) || die Socket::Class->error; +$sock->send('hello socket world'); +$sock->free; diff --git a/Task/Sockets/PicoLisp/sockets.l b/Task/Sockets/PicoLisp/sockets.l new file mode 100644 index 0000000000..d644b957c9 --- /dev/null +++ b/Task/Sockets/PicoLisp/sockets.l @@ -0,0 +1,3 @@ +(when (connect "localhost" 256) + (out @ (prinl "hello socket world")) + (close @) ) diff --git a/Task/Sockets/Pike/sockets.pike b/Task/Sockets/Pike/sockets.pike new file mode 100644 index 0000000000..06d73311fd --- /dev/null +++ b/Task/Sockets/Pike/sockets.pike @@ -0,0 +1,8 @@ +import Stdio; + +int main(){ + object con = File(); + con->connect("127.0.0.1",256); + con->write("hello socket world"); + con->close(); +} diff --git a/Task/Sockets/PureBasic/sockets.purebasic b/Task/Sockets/PureBasic/sockets.purebasic new file mode 100644 index 0000000000..09c0e00477 --- /dev/null +++ b/Task/Sockets/PureBasic/sockets.purebasic @@ -0,0 +1,4 @@ +InitNetwork() +ConnectionID = OpenNetworkConnection("localhost", 256) +SendNetworkString(ConnectionID, "hello socket world") +CloseNetworkConnection(ConnectionID) diff --git a/Task/Sockets/Python/sockets.py b/Task/Sockets/Python/sockets.py new file mode 100644 index 0000000000..26924a6c35 --- /dev/null +++ b/Task/Sockets/Python/sockets.py @@ -0,0 +1,5 @@ +import socket +sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +sock.connect(("localhost", 256)) +sock.sendall("hello socket world") +sock.close() diff --git a/Task/Sockets/Racket/sockets.rkt b/Task/Sockets/Racket/sockets.rkt new file mode 100644 index 0000000000..9617258c11 --- /dev/null +++ b/Task/Sockets/Racket/sockets.rkt @@ -0,0 +1,4 @@ +#lang racket +(let-values ([(in out) (tcp-connect "localhost" 256)]) + (display "hello socket world\n" out) + (close-output-port out)) diff --git a/Task/Sockets/Rhope/sockets.rhope b/Task/Sockets/Rhope/sockets.rhope new file mode 100644 index 0000000000..8154d04d06 --- /dev/null +++ b/Task/Sockets/Rhope/sockets.rhope @@ -0,0 +1,4 @@ +Socket Send(0,0) +|: + [New@Net Client["localhost",256]]Put String["hello socket world"] +:| diff --git a/Task/Sockets/Ruby/sockets.rb b/Task/Sockets/Ruby/sockets.rb new file mode 100644 index 0000000000..050738be35 --- /dev/null +++ b/Task/Sockets/Ruby/sockets.rb @@ -0,0 +1,4 @@ +require 'socket' +sock = TCPSocket.open("localhost", 256) +sock.write("hello socket world") +sock.close diff --git a/Task/Sockets/Scheme/sockets.ss b/Task/Sockets/Scheme/sockets.ss new file mode 100644 index 0000000000..1a174eb056 --- /dev/null +++ b/Task/Sockets/Scheme/sockets.ss @@ -0,0 +1,3 @@ +(let ((s (socket PF_INET SOCK_STREAM 0))) + (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 256) + (display "hello socket world" s)) diff --git a/Task/Sockets/Seed7/sockets.seed7 b/Task/Sockets/Seed7/sockets.seed7 new file mode 100644 index 0000000000..e08e07f0d7 --- /dev/null +++ b/Task/Sockets/Seed7/sockets.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + include "socket.s7i"; + +const proc: main is func + local + var file: sock is STD_NULL; + begin + sock := openInetSocket(256); + writeln(sock, "hello socket world"); + close(sock); + end func; diff --git a/Task/Sockets/Slate/sockets.slate b/Task/Sockets/Slate/sockets.slate new file mode 100644 index 0000000000..232196d29d --- /dev/null +++ b/Task/Sockets/Slate/sockets.slate @@ -0,0 +1,10 @@ +[ | socket | + [ | addr stream | + addr: (Net SocketAddress newOn: '127.0.0.1:256'). + socket: (Net Socket newFor: addr domain type: Net Socket Types Stream protocol: Net Socket Protocols Default). + socket connectTo: addr. + stream: (Net SocketStream newOn: socket). + stream nextPutAll: ('hello socket world' as: ByteArray). + stream flush + ] ensure: [socket close] +] do. diff --git a/Task/Sockets/Smalltalk/sockets.st b/Task/Sockets/Smalltalk/sockets.st new file mode 100644 index 0000000000..071a3bfdf7 --- /dev/null +++ b/Task/Sockets/Smalltalk/sockets.st @@ -0,0 +1,48 @@ +PackageLoader fileInPackage: 'TCP'! + +Object subclass: #HelloSocket + instanceVariableNames: 'ss' + classVariableNames: '' + poolDictionaries: '' + category: 'SimpleEcho'! + +!HelloSocket class methodsFor: 'instance creation'! + +port: anInteger + | ses | + ses := super new. + ses init: anInteger. + ^ses +!! + +!HelloSocket methodsFor: 'instance initialization'! + +init: anInteger + ss := (TCP.ServerSocket port: anInteger). + ^self +!! + +!HelloSocket methodsFor: 'running'! + +run + | s | + [ + ss waitForConnection. + s := (ss accept). + [self handleSocket: s] fork + ] repeat +!! + +!HelloSocket methodsFor: 'handling'! + +handleSocket: s + | msg | + msg := 'hello socket world'. + msg displayOn: s. + (String with: (Character value: 10)) displayOn: s. + s flush +!! + +Smalltalk at: #helloServer put: (HelloSocket port: 2560). + +helloServer run. diff --git a/Task/Sockets/Tcl/sockets.tcl b/Task/Sockets/Tcl/sockets.tcl new file mode 100644 index 0000000000..a6d3e1e08a --- /dev/null +++ b/Task/Sockets/Tcl/sockets.tcl @@ -0,0 +1,3 @@ +set io [socket localhost 256] +puts -nonewline $io "hello socket world" +close $io diff --git a/Task/Sockets/Toka/sockets.toka b/Task/Sockets/Toka/sockets.toka new file mode 100644 index 0000000000..3b5afc3d3a --- /dev/null +++ b/Task/Sockets/Toka/sockets.toka @@ -0,0 +1,14 @@ +needs sockets + +#! A simple abstraction layer that makes writing trivial servers easy +value| server.socket server.connection server.action | +[ ( n- ) pBind to server.socket ] is server.setSocket +[ ( - ) server.socket pAccept to server.connection ] is server.acceptConnection +[ ( - ) server.connection pClose drop ] is server.closeConnection +[ ( $- ) >r server.connection r> string.getLength pWrite drop ] is server.send +[ ( an- ) server.connection -rot pRead drop ] is server.recieve +[ ( qn- ) swap to server.action server.setSocket + [ server.acceptConnection server.action invoke server.closeConnection TRUE ] whileTrue ] is server.start + +#! The actual server +[ " hello socket world" server.send ] 256 server.start diff --git a/Task/Sockets/UNIX-Shell/sockets.sh b/Task/Sockets/UNIX-Shell/sockets.sh new file mode 100644 index 0000000000..c84b95eb04 --- /dev/null +++ b/Task/Sockets/UNIX-Shell/sockets.sh @@ -0,0 +1 @@ +echo "hello socket world" | nc localhost 256 diff --git a/Task/Sockets/Visual-Basic-.NET/sockets.visual b/Task/Sockets/Visual-Basic-.NET/sockets.visual new file mode 100644 index 0000000000..49bfb0853e --- /dev/null +++ b/Task/Sockets/Visual-Basic-.NET/sockets.visual @@ -0,0 +1,15 @@ +Imports System +Imports System.IO +Imports System.Net.Sockets + +Public Class Program + Public Shared Sub Main(ByVal args As String[]) + Dim tcp As New TcpClient("localhost", 256) + Dim writer As New StreamWriter(tcp.GetStream()) + + writer.Write("hello socket world") + writer.Flush() + + tcp.Close() + End Sub +End Class diff --git a/Task/Sockets/X86-Assembly/sockets-1.x86 b/Task/Sockets/X86-Assembly/sockets-1.x86 new file mode 100644 index 0000000000..fd42b6d2fd --- /dev/null +++ b/Task/Sockets/X86-Assembly/sockets-1.x86 @@ -0,0 +1,163 @@ +;using sockets on linux with the 0x80 inturrprets. +; +;assemble +; nasm -o socket.o -f elf32 -g socket.asm +;link +; ld -o socket socket.o +; +; +;Just some assigns for better readability + +%assign SOCK_STREAM 1 +%assign AF_INET 2 +%assign SYS_socketcall 102 +%assign SYS_SOCKET 1 +%assign SYS_CONNECT 3 +%assign SYS_SEND 9 +%assign SYS_RECV 10 + +section .text + global _start + +;-------------------------------------------------- +;Functions to make things easier. :] +;-------------------------------------------------- +_socket: + mov [cArray+0], dword AF_INET + mov [cArray+4], dword SOCK_STREAM + mov [cArray+8], dword 0 + mov eax, SYS_socketcall + mov ebx, SYS_SOCKET + mov ecx, cArray + int 0x80 + ret + +_connect: + call _socket + mov dword [sock], eax + mov dx, si + mov byte [edi+3], dl + mov byte [edi+2], dh + mov [cArray+0], eax ;sock; + mov [cArray+4], edi ;&sockaddr_in; + mov edx, 16 + mov [cArray+8], edx ;sizeof(sockaddr_in); + mov eax, SYS_socketcall + mov ebx, SYS_CONNECT + mov ecx, cArray + int 0x80 + ret + +_send: + mov edx, [sock] + mov [sArray+0],edx + mov [sArray+4],eax + mov [sArray+8],ecx + mov [sArray+12], dword 0 + mov eax, SYS_socketcall + mov ebx, SYS_SEND + mov ecx, sArray + int 0x80 + ret + +_exit: + push 0x1 + mov eax, 1 + push eax + int 0x80 + +_print: + mov ebx, 1 + mov eax, 4 + int 0x80 + ret +;-------------------------------------------------- +;Main code body +;-------------------------------------------------- + +_start: + mov esi, szIp + mov edi, sockaddr_in + xor eax,eax + xor ecx,ecx + xor edx,edx + .cc: + xor ebx,ebx + .c: + lodsb + inc edx + sub al,'0' + jb .next + imul ebx,byte 10 + add ebx,eax + jmp short .c + .next: + mov [edi+ecx+4],bl + inc ecx + cmp ecx,byte 4 + jne .cc + + mov word [edi], AF_INET + mov esi, szPort + xor eax,eax + xor ebx,ebx + .nextstr1: + lodsb + test al,al + jz .ret1 + sub al,'0' + imul ebx,10 + add ebx,eax + jmp .nextstr1 + .ret1: + xchg ebx,eax + mov [sport], eax + + mov si, [sport] + call _connect + cmp eax, 0 + jnz short _fail + mov eax, msg + mov ecx, msglen + call _send + call _exit + +_fail: + mov edx, cerrlen + mov ecx, cerrmsg + call _print + call _exit + + +_recverr: + call _exit +_dced: + call _exit + +section .data +cerrmsg db 'failed to connect :(',0xa +cerrlen equ $-cerrmsg +msg db 'Hello socket world!',0xa +msglen equ $-msg + +szIp db '127.0.0.1',0 +szPort db '256',0 + +section .bss +sock resd 1 +;general 'array' for syscall_socketcall argument arg. +cArray resd 1 + resd 1 + resd 1 + resd 1 + +;send 'array'. +sArray resd 1 + resd 1 + resd 1 + resd 1 +;duh? +sockaddr_in resb 16 +;.. +sport resb 2 +buff resb 1024 diff --git a/Task/Sockets/X86-Assembly/sockets-2.x86 b/Task/Sockets/X86-Assembly/sockets-2.x86 new file mode 100644 index 0000000000..6de078630f --- /dev/null +++ b/Task/Sockets/X86-Assembly/sockets-2.x86 @@ -0,0 +1,145 @@ +.586 +.model flat,stdcall +option casemap:none + +include /masm32/include/windows.inc +include /masm32/include/user32.inc +include /masm32/include/kernel32.inc +include /masm32/include/ws2_32.inc + +includelib /masm32/lib/user32.lib +includelib /masm32/lib/kernel32.lib +includelib /masm32/lib/ws2_32.lib + +WinMain proto :DWORD,:DWORD,:DWORD,:DWORD + + +.data + ClassName db "MainWinClass",0 + AppName db "Async Sockets",0 + szSockStr db "Hello socket world!",13,10,0 + szIp db "127.0.0.1",0 + port dd 256 + + wsa WSADATA <> + sa sockaddr_in <> + +.data? + hInstance dd ? + CommandLine dd ? + sock dd ? + +.const +WM_SOCK equ WM_USER+100 + +.code +start: + invoke WSAStartup, 200h, addr wsa + .if eax!=NULL + invoke ExitProcess, eax + .else + invoke GetModuleHandle, NULL + mov hInstance,eax + invoke GetCommandLine + mov CommandLine,eax + invoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT + invoke ExitProcess,eax + .endif + +WinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD + LOCAL wc:WNDCLASSEX + LOCAL msg:MSG + LOCAL hwnd:HWND + + mov wc.cbSize,SIZEOF WNDCLASSEX + mov wc.style, CS_HREDRAW or CS_VREDRAW + mov wc.lpfnWndProc, OFFSET WndProc + mov wc.cbClsExtra,NULL + mov wc.cbWndExtra,NULL + push hInstance + pop wc.hInstance + mov wc.hbrBackground,COLOR_BTNFACE+1 + mov wc.lpszMenuName,NULL + mov wc.lpszClassName,OFFSET ClassName + + invoke LoadIcon,NULL,IDI_APPLICATION + mov wc.hIcon,eax + mov wc.hIconSm,eax + + invoke LoadCursor,NULL,IDC_ARROW + mov wc.hCursor,eax + + invoke RegisterClassEx, addr wc + INVOKE CreateWindowEx,NULL,ADDR ClassName,ADDR AppName,\ + WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,\ + CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,\ + hInst,NULL + mov hwnd,eax + + invoke ShowWindow, hwnd,SW_SHOWNORMAL + invoke UpdateWindow, hwnd + + .WHILE TRUE + invoke GetMessage, ADDR msg,NULL,0,0 + .BREAK .IF (!eax) + invoke TranslateMessage, ADDR msg + invoke DispatchMessage, ADDR msg + .ENDW + + mov eax,msg.wParam + ret +WinMain endp + +WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM + + .IF uMsg==WM_DESTROY + invoke PostQuitMessage,NULL + .ELSEIF uMsg==WM_CREATE + invoke socket, AF_INET,SOCK_STREAM, 0 + .if eax==INVALID_SOCKET + ;error + .endif + mov sock, eax + invoke WSAAsyncSelect, sock, hWnd, WM_SOCK, FD_CONNECT or FD_CLOSE + .if eax==INVALID_SOCKET + ;error! + .endif + mov sa.sin_family, AF_INET + invoke inet_addr, addr szIp + mov sa.sin_addr, eax + invoke htons, port + mov sa.sin_port, ax + invoke connect, sock, addr sa, sizeof sa + .if eax==SOCKET_ERROR + invoke WSAGetLastError + .if eax!=WSAEWOULDBLOCK + ;real error. + .endif + .endif + .elseif uMsg==WM_SOCK + mov edx, lParam + .if dx==FD_CONNECT + shr edx, 16 + .if dx==NULL + invoke lstrlen, addr szSockStr + invoke send, sock, addr szSockStr, eax, 0 + .else + ;error + .endif + .elseif dx==FD_CLOSE + shr edx, 16 + .if dx==NULL + invoke SendMessage, hWnd, WM_DESTROY, 0, 0 + .endif + .endif + .ELSE + invoke DefWindowProc,hWnd,uMsg,wParam,lParam + ret + .ENDIF + + xor eax,eax + ret +WndProc endp + + +end start diff --git a/Task/Sockets/X86-Assembly/sockets-3.x86 b/Task/Sockets/X86-Assembly/sockets-3.x86 new file mode 100644 index 0000000000..b642a08950 --- /dev/null +++ b/Task/Sockets/X86-Assembly/sockets-3.x86 @@ -0,0 +1,118 @@ +.586 +.model flat,stdcall +option casemap:none + +include /masm32/include/windows.inc +include /masm32/include/user32.inc +include /masm32/include/kernel32.inc +include /masm32/include/ws2_32.inc + +includelib /masm32/lib/user32.lib +includelib /masm32/lib/kernel32.lib +includelib /masm32/lib/ws2_32.lib + +WinMain proto :DWORD,:DWORD,:DWORD,:DWORD + + +.data + ClassName db "MainWinClass",0 + AppName db "Blocking Sockets",0 + szSockStr db "Hello socket world!",13,10,0 + szIp db "127.0.0.1",0 + port dd 256 + + wsa WSADATA <> + sa sockaddr_in <> + +.data? + hInstance dd ? + CommandLine dd ? + sock dd ? + +.code +start: + invoke WSAStartup, 200h, addr wsa + .if eax!=NULL + invoke ExitProcess, eax + .else + invoke GetModuleHandle, NULL + mov hInstance,eax + invoke GetCommandLine + mov CommandLine,eax + invoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT + invoke ExitProcess,eax + .endif + +WinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD + LOCAL wc:WNDCLASSEX + LOCAL msg:MSG + LOCAL hwnd:HWND + + mov wc.cbSize,SIZEOF WNDCLASSEX + mov wc.style, CS_HREDRAW or CS_VREDRAW + mov wc.lpfnWndProc, OFFSET WndProc + mov wc.cbClsExtra,NULL + mov wc.cbWndExtra,NULL + push hInstance + pop wc.hInstance + mov wc.hbrBackground,COLOR_BTNFACE+1 + mov wc.lpszMenuName,NULL + mov wc.lpszClassName,OFFSET ClassName + + invoke LoadIcon,NULL,IDI_APPLICATION + mov wc.hIcon,eax + mov wc.hIconSm,eax + + invoke LoadCursor,NULL,IDC_ARROW + mov wc.hCursor,eax + + invoke RegisterClassEx, addr wc + INVOKE CreateWindowEx,NULL,ADDR ClassName,ADDR AppName,\ + WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,\ + CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,\ + hInst,NULL + mov hwnd,eax + + invoke ShowWindow, hwnd,SW_SHOWNORMAL + invoke UpdateWindow, hwnd + + .WHILE TRUE + invoke GetMessage, ADDR msg,NULL,0,0 + .BREAK .IF (!eax) + invoke TranslateMessage, ADDR msg + invoke DispatchMessage, ADDR msg + .ENDW + + mov eax,msg.wParam + ret +WinMain endp + +WndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM + + .IF uMsg==WM_DESTROY + invoke PostQuitMessage,NULL + .ELSEIF uMsg==WM_CREATE + invoke socket, AF_INET,SOCK_STREAM, 0 + .if eax==INVALID_SOCKET + ;error + .endif + mov sock, eax + mov sa.sin_family, AF_INET + invoke inet_addr, addr szIp + mov sa.sin_addr, eax + invoke htons, port + mov sa.sin_port, ax + invoke connect, sock, addr sa, sizeof sa + invoke lstrlen, addr szSockStr + invoke send, sock, addr szSockStr, eax, 0 + .ELSE + invoke DefWindowProc,hWnd,uMsg,wParam,lParam + ret + .ENDIF + + xor eax,eax + ret +WndProc endp + + +end start diff --git a/Task/Sokoban/0DESCRIPTION b/Task/Sokoban/0DESCRIPTION new file mode 100644 index 0000000000..cc04063c4a --- /dev/null +++ b/Task/Sokoban/0DESCRIPTION @@ -0,0 +1,16 @@ +Demonstrate how to find a solution to a given [[wp:Sokoban|Sokoban]] level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. + +Sokoban levels are usually stored as a character array where +* ''space'' is an empty square +* # is a wall +* @ is the player +* $ is a box +* . is a goal +* + is the player on a goal +* * is a box on a goal + +Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that ('''l'''eft, '''u'''p, '''r'''ight, '''d'''own) direction and capital LURD represents a push. + +Please state if you use some other format for either the input or output, and why. + +For more information, see [http://www.sokobano.de/wiki/index.php?title=Main_Page the Sokoban wiki]. diff --git a/Task/Sokoban/1META.yaml b/Task/Sokoban/1META.yaml new file mode 100644 index 0000000000..a2413d963b --- /dev/null +++ b/Task/Sokoban/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Games diff --git a/Task/Sokoban/C++/sokoban-1.cpp b/Task/Sokoban/C++/sokoban-1.cpp new file mode 100644 index 0000000000..b876d477cf --- /dev/null +++ b/Task/Sokoban/C++/sokoban-1.cpp @@ -0,0 +1,168 @@ +#include <iostream> +#include <string> +#include <vector> +#include <queue> +#include <regex> +#include <tuple> +#include <set> +#include <array> +using namespace std; + +class Board +{ +public: + vector<vector<char>> sData, dData; + int px, py; + + Board(string b) + { + regex pattern("([^\\n]+)\\n?"); + sregex_iterator end, iter(b.begin(), b.end(), pattern); + + int w = 0; + vector<string> data; + for(; iter != end; ++iter) + { + data.push_back((*iter)[1]); + w = max(w, (*iter)[1].length()); + } + + for(int v = 0; v < data.size(); ++v) + { + vector<char> sTemp, dTemp; + for(int u = 0; u < w; ++u) + { + if(u > data[v].size()) + { + sTemp.push_back(' '); + dTemp.push_back(' '); + } + else + { + char s = ' ', d = ' ', c = data[v][u]; + + if(c == '#') + s = '#'; + else if(c == '.' || c == '*' || c == '+') + s = '.'; + + if(c == '@' || c == '+') + { + d = '@'; + px = u; + py = v; + } + else if(c == '$' || c == '*') + d = '*'; + + sTemp.push_back(s); + dTemp.push_back(d); + } + } + + sData.push_back(sTemp); + dData.push_back(dTemp); + } + } + + bool move(int x, int y, int dx, int dy, vector<vector<char>> &data) + { + if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') + return false; + + data[y][x] = ' '; + data[y+dy][x+dx] = '@'; + + return true; + } + + bool push(int x, int y, int dx, int dy, vector<vector<char>> &data) + { + if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') + return false; + + data[y][x] = ' '; + data[y+dy][x+dx] = '@'; + data[y+2*dy][x+2*dx] = '*'; + + return true; + } + + bool isSolved(const vector<vector<char>> &data) + { + for(int v = 0; v < data.size(); ++v) + for(int u = 0; u < data[v].size(); ++u) + if((sData[v][u] == '.') ^ (data[v][u] == '*')) + return false; + return true; + } + + string solve() + { + set<vector<vector<char>>> visited; + queue<tuple<vector<vector<char>>, string, int, int>> open; + + open.push(make_tuple(dData, "", px, py)); + visited.insert(dData); + + array<tuple<int, int, char, char>, 4> dirs; + dirs[0] = make_tuple(0, -1, 'u', 'U'); + dirs[1] = make_tuple(1, 0, 'r', 'R'); + dirs[2] = make_tuple(0, 1, 'd', 'D'); + dirs[3] = make_tuple(-1, 0, 'l', 'L'); + + while(open.size() > 0) + { + vector<vector<char>> temp, cur = get<0>(open.front()); + string cSol = get<1>(open.front()); + int x = get<2>(open.front()); + int y = get<3>(open.front()); + open.pop(); + + for(int i = 0; i < 4; ++i) + { + temp = cur; + int dx = get<0>(dirs[i]); + int dy = get<1>(dirs[i]); + + if(temp[y+dy][x+dx] == '*') + { + if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())) + { + if(isSolved(temp)) + return cSol + get<3>(dirs[i]); + open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); + visited.insert(temp); + } + } + else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())) + { + if(isSolved(temp)) + return cSol + get<2>(dirs[i]); + open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); + visited.insert(temp); + } + } + } + + return "No solution"; + } +}; + +int main() +{ + string level = + "#######\n" + "# #\n" + "# #\n" + "#. # #\n" + "#. $$ #\n" + "#.$$ #\n" + "#.# @#\n" + "#######"; + + Board b(level); + + cout << level << endl << endl << b.solve() << endl; + return 0; +} diff --git a/Task/Sokoban/C++/sokoban-2.cpp b/Task/Sokoban/C++/sokoban-2.cpp new file mode 100644 index 0000000000..9da34b3ba0 --- /dev/null +++ b/Task/Sokoban/C++/sokoban-2.cpp @@ -0,0 +1,140 @@ +#include <iostream> +#include <string> +#include <vector> +#include <queue> +#include <tuple> +#include <array> +#include <map> +#include <boost/algorithm/string.hpp> +#include <boost/unordered_set.hpp> + +using namespace std; + +typedef vector<char> TableRow; +typedef vector<TableRow> Table; + +struct Board { + Table sData, dData; + int px, py; + + Board(string b) { + vector<string> data; + boost::split(data, b, boost::is_any_of("\n")); + + size_t width = 0; + for (auto &row: data) + width = max(width, row.size()); + + map<char,char> maps = {{' ',' '}, {'.','.'}, {'@',' '}, + {'#','#'}, {'$',' '}}, + mapd = {{' ',' '}, {'.',' '}, {'@','@'}, + {'#',' '}, {'$','*'}}; + + for (size_t r = 0; r < data.size(); r++) { + TableRow sTemp, dTemp; + for (size_t c = 0; c < width; c++) { + char ch = c < data[r].size() ? data[r][c] : ' '; + sTemp.push_back(maps[ch]); + dTemp.push_back(mapd[ch]); + if (ch == '@') { + px = c; + py = r; + } + } + sData.push_back(sTemp); + dData.push_back(dTemp); + } + } + + bool move(int x, int y, int dx, int dy, Table &data) { + if (sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') + return false; + + data[y][x] = ' '; + data[y+dy][x+dx] = '@'; + return true; + } + + bool push(int x, int y, int dx, int dy, Table &data) { + if (sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') + return false; + + data[y][x] = ' '; + data[y+dy][x+dx] = '@'; + data[y+2*dy][x+2*dx] = '*'; + return true; + } + + bool isSolved(const Table &data) { + for (size_t r = 0; r < data.size(); r++) + for (size_t c = 0; c < data[r].size(); c++) + if ((sData[r][c] == '.') != (data[r][c] == '*')) + return false; + return true; + } + + string solve() { + boost::unordered_set<Table, boost::hash<Table>> visited; + visited.insert(dData); + + queue<tuple<Table, string, int, int>> open; + open.push(make_tuple(dData, "", px, py)); + + vector<tuple<int, int, char, char>> dirs = { + make_tuple( 0, -1, 'u', 'U'), + make_tuple( 1, 0, 'r', 'R'), + make_tuple( 0, 1, 'd', 'D'), + make_tuple(-1, 0, 'l', 'L') + }; + + while (open.size() > 0) { + Table temp, cur = get<0>(open.front()); + string cSol = get<1>(open.front()); + int x = get<2>(open.front()); + int y = get<3>(open.front()); + open.pop(); + + for (int i = 0; i < 4; ++i) { + temp = cur; + int dx = get<0>(dirs[i]); + int dy = get<1>(dirs[i]); + + if (temp[y+dy][x+dx] == '*') { + if (push(x, y, dx, dy, temp) && + visited.find(temp) == visited.end()) { + if (isSolved(temp)) + return cSol + get<3>(dirs[i]); + open.push(make_tuple(temp, cSol + get<3>(dirs[i]), + x+dx, y+dy)); + visited.insert(temp); + } + } else if (move(x, y, dx, dy, temp) && + visited.find(temp) == visited.end()) { + if (isSolved(temp)) + return cSol + get<2>(dirs[i]); + open.push(make_tuple(temp, cSol + get<2>(dirs[i]), + x+dx, y+dy)); + visited.insert(temp); + } + } + } + + return "No solution"; + } +}; + +int main() { + string level = "#######\n" + "# #\n" + "# #\n" + "#. # #\n" + "#. $$ #\n" + "#.$$ #\n" + "#.# @#\n" + "#######"; + + cout << level << endl << endl; + Board board(level); + cout << board.solve() << endl; + return 0; +} diff --git a/Task/Sokoban/C/sokoban.c b/Task/Sokoban/C/sokoban.c new file mode 100644 index 0000000000..b5dda0462f --- /dev/null +++ b/Task/Sokoban/C/sokoban.c @@ -0,0 +1,402 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <stdint.h> +#include <assert.h> +#include <stdbool.h> + +int w, h, n_boxes; +uint8_t *board, *goals, *live; + +typedef uint16_t cidx_t; +typedef uint32_t hash_t; + +/* board configuration is represented by an array of cell indices + of player and boxes */ +typedef struct state_t state_t; + +struct state_t { // variable length + hash_t h; + state_t *prev, *next, *qnext; + cidx_t c[]; +}; + +size_t state_size, block_size = 32; +state_t *block_root, *block_head; + +inline +state_t* newstate(state_t *parent) { + inline state_t* next_of(state_t *s) { + return (void*)((uint8_t*)s + state_size); + } + + state_t *ptr; + if (!block_head) { + block_size *= 2; + state_t *p = malloc(block_size * state_size); + assert(p); + p->next = block_root; + block_root = p; + ptr = (void*)((uint8_t*)p + state_size * block_size); + p = block_head = next_of(p); + state_t *q; + for (q = next_of(p); q < ptr; p = q, q = next_of(q)) + p->next = q; + p->next = NULL; + } + + ptr = block_head; + block_head = block_head->next; + + ptr->prev = parent; + ptr->h = 0; + return ptr; +} + +inline +void unnewstate(state_t *p) { + p->next = block_head; + block_head = p; +} + +enum { space, wall, player, box }; + +#define E "\033[" +const char * const glyph1[] = { " ", "#", E"31m@"E"m", E"33m$"E"m"}; +const char * const glyph2[] = { E"32m."E"m", "#", E"32m@"E"m", E"32m$"E"m"}; +#undef E + +// mark up positions where a box definitely should not be +void mark_live(const int c) +{ + const int y = c / w, x = c % w; + if (live[c]) return; + + live[c] = 1; + if (y > 1 && board[c - w] != wall && board[c - w * 2] != wall) + mark_live(c - w); + if (y < h - 2 && board[c + w] != wall && board[c + w * 2] != wall) + mark_live(c + w); + if (x > 1 && board[c - 1] != wall && board[c - 2] != wall) + mark_live(c - 1); + if (x < w - 2 && board[c + 1] != wall && board[c + 2] != wall) + mark_live(c + 1); +} + +state_t *parse_board(const int y, const int x, const char *s) +{ + w = x, h = y; + board = calloc(w * h, sizeof(uint8_t)); + assert(board); + goals = calloc(w * h, sizeof(uint8_t)); + assert(goals); + live = calloc(w * h, sizeof(uint8_t)); + assert(live); + + n_boxes = 0; + for (int i = 0; s[i]; i++) { + switch(s[i]) { + case '#': board[i] = wall; + continue; + + case '.': // fallthrough + case '+': goals[i] = 1; // fallthrough + case '@': continue; + + case '*': goals[i] = 1; // fallthrough + case '$': n_boxes++; + continue; + default: continue; + } + } + + const int is = sizeof(int); + state_size = (sizeof(state_t) + (1 + n_boxes) * sizeof(cidx_t) + is - 1) + / is * is; + + state_t *state = newstate(NULL); + + for (int i = 0, j = 0; i < w * h; i++) { + if (goals[i]) mark_live(i); + if (s[i] == '$' || s[i] == '*') + state->c[++j] = i; + else if (s[i] == '@' || s[i] == '+') + state->c[0] = i; + } + + return state; +} + +void show_board(const state_t *s) +{ + unsigned char b[w * h]; + memcpy(b, board, w * h); + + b[ s->c[0] ] = player; + for (int i = 1; i <= n_boxes; i++) + b[ s->c[i] ] = box; + + for (int i = 0; i < w * h; i++) { + printf((goals[i] ? glyph2 : glyph1)[ b[i] ]); + if (! ((1 + i) % w)) + putchar('\n'); + } +} + +// K&R hash function +inline +void hash(state_t *s) +{ + if (!s->h) { + register hash_t ha = 0; + cidx_t *p = s->c; + for (int i = 0; i <= n_boxes; i++) + ha = p[i] + 31 * ha; + s->h = ha; + } +} + +state_t **buckets; +hash_t hash_size, fill_limit, filled; + +void extend_table() +{ + int old_size = hash_size; + + if (!old_size) { + hash_size = 1024; + filled = 0; + fill_limit = hash_size * 3 / 4; // 0.75 load factor + } else { + hash_size *= 2; + fill_limit *= 2; + } + + buckets = realloc(buckets, sizeof(state_t*) * hash_size); + assert(buckets); + + // rehash + memset(buckets + old_size, 0, sizeof(state_t*) * (hash_size - old_size)); + + const hash_t bits = hash_size - 1; + for (int i = 0; i < old_size; i++) { + state_t *head = buckets[i]; + buckets[i] = NULL; + while (head) { + state_t *next = head->next; + const int j = head->h & bits; + head->next = buckets[j]; + buckets[j] = head; + head = next; + } + } +} + +state_t *lookup(state_t *s) +{ + hash(s); + state_t *f = buckets[s->h & (hash_size - 1)]; + for (; f; f = f->next) { + if (//(f->h == s->h) && + !memcmp(s->c, f->c, sizeof(cidx_t) * (1 + n_boxes))) + break; + } + + return f; +} + +bool add_to_table(state_t *s) +{ + if (lookup(s)) { + unnewstate(s); + return false; + } + + if (filled++ >= fill_limit) + extend_table(); + + hash_t i = s->h & (hash_size - 1); + + s->next = buckets[i]; + buckets[i] = s; + return true; +} + +bool success(const state_t *s) +{ + for (int i = 1; i <= n_boxes; i++) + if (!goals[s->c[i]]) return false; + return true; +} + +state_t *move_me(state_t *s, const int dy, const int dx) +{ + const int y = s->c[0] / w; + const int x = s->c[0] % w; + const int y1 = y + dy; + const int x1 = x + dx; + const int c1 = y1 * w + x1; + + if (y1 < 0 || y1 > h || x1 < 0 || x1 > w + || board[c1] == wall) + return NULL; + + int at_box = 0; + for (int i = 1; i <= n_boxes; i++) { + if (s->c[i] == c1) { + at_box = i; + break; + } + } + + int c2; + if (at_box) { + c2 = c1 + dy * w + dx; + if (board[c2] == wall || !live[c2]) + return NULL; + for (int i = 1; i <= n_boxes; i++) + if (s->c[i] == c2) return NULL; + } + + state_t *n = newstate(s); + memcpy(n->c + 1, s->c + 1, sizeof(cidx_t) * n_boxes); + + cidx_t *p = n->c; + p[0] = c1; + + if (at_box) p[at_box] = c2; + + // leet bubble sort + for (int i = n_boxes; --i; ) { + cidx_t t = 0; + for (int j = 1; j < i; j++) { + if (p[j] > p[j + 1]) + t = p[j], p[j] = p[j+1], p[j+1] = t; + } + if (!t) break; + } + + return n; +} + +state_t *next_level, *done; + +bool queue_move(state_t *s) +{ + if (!s || !add_to_table(s)) + return false; + + if (success(s)) { + puts("\nSuccess!"); + done = s; + return true; + } + + s->qnext = next_level; + next_level = s; + return false; +} + +bool do_move(state_t *s) +{ + return queue_move(move_me(s, 1, 0)) + || queue_move(move_me(s, -1, 0)) + || queue_move(move_me(s, 0, 1)) + || queue_move(move_me(s, 0, -1)); +} + +void show_moves(const state_t *s) +{ + if (s->prev) + show_moves(s->prev); + usleep(200000); + printf("\033[H"); + show_board(s); +} + +int main() +{ + state_t *s = parse_board( + +#define BIG 0 + +#if BIG == 0 + 8, 7, + "#######" + "# #" + "# #" + "#. # #" + "#. $$ #" + "#.$$ #" + "#.# @#" + "#######" + +#elif BIG == 1 + 5, 13, + "#############" + "# # #" + "# $$$$$$$ @#" + "#....... #" + "#############" + +#elif BIG == 2 + 5, 13, + "#############" + "#... # #" + "#.$$$$$$$ @#" + "#... #" + "#############" + +#else + 11, 19, + " ##### " + " # # " + " # # " + " ### #$## " + " # # " + "### #$## # ######" + "# # ## ##### .#" + "# $ $ ..#" + "##### ### #@## .#" + " # #########" + " ####### " +#endif + ); + + show_board(s); + extend_table(); + queue_move(s); + for (int i = 0; !done; i++) { + printf("depth %d\r", i); + fflush(stdout); + + state_t *head = next_level; + for (next_level = NULL; head && !done; head = head->qnext) + do_move(head); + + if (!next_level) { + puts("no solution?"); + return 1; + } + } + + printf("press any key to see moves\n"); + getchar(), puts("\033[H\033[J"); + show_moves(done); + +#if 0 + free(buckets); + free(board); + free(goals); + free(live); + + while (block_root) { + void *tmp = block_root->next; + free(block_root); + block_root = tmp; + } +#endif + + return 0; +} diff --git a/Task/Sokoban/D/sokoban-1.d b/Task/Sokoban/D/sokoban-1.d new file mode 100644 index 0000000000..02a66219e3 --- /dev/null +++ b/Task/Sokoban/D/sokoban-1.d @@ -0,0 +1,134 @@ +import std.string, std.typecons, std.exception, std.algorithm; +import queue_usage2; // No queue in DMD 2.061 Phobos. + +immutable struct Board { + private enum El : char { floor=' ', wall='#', goal='.', + box='$', player='@', boxOnGoal='*' } + private alias string CTable; + private immutable size_t ncols; + private immutable CTable sData, dData; + private immutable int playerx, playery; + + this(in string[] board) pure nothrow + in { + foreach (row; board) { + assert(row.length == board[0].length, + "Unequal board rows."); + foreach (c; row) + assert(c.inPattern(" #.$@*"), "Not valid input"); + } + } body { + immutable sMap=[' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; + immutable dMap=[' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; + ncols = board[0].length; + + foreach (r, row; board) + foreach (c, ch; row) { + sData ~= sMap[ch]; + dData ~= dMap[ch]; + if (ch == El.player) { + playerx = c; + playery = r; + } + } + } + + private bool move(in int x, in int y, in int dx, + in int dy, ref CTable data) + const pure /*nothrow*/ { + if (sData[(y+dy) * ncols + x+dx] == El.wall || + data[(y+dy) * ncols + x+dx] != El.floor) + return false; + + auto data2 = data.dup; // not nothrow + data2[y * ncols + x] = El.floor; + data2[(y+dy) * ncols + x+dx] = El.player; + data = assumeUnique(data2); // not enforced + return true; + } + + private bool push(in int x, in int y, in int dx, + in int dy, ref CTable data) + const pure /*nothrow*/ { + if (sData[(y+2*dy) * ncols + x+2*dx] == El.wall || + data[(y+2*dy) * ncols + x+2*dx] != El.floor) + return false; + + auto data2 = data.dup; // not nothrow + data2[y * ncols + x] = El.floor; + data2[(y+dy) * ncols + x+dx] = El.player; + data2[(y+2*dy) * ncols + x+2*dx] = El.boxOnGoal; + data = assumeUnique(data2); // not enforced + return true; + } + + private bool isSolved(in CTable data) const pure nothrow { + foreach (i, d; data) + if ((sData[i] == El.goal) != (d == El.boxOnGoal)) + return false; + return true; + } + + string solve() pure { + bool[immutable CTable] visitedSet = [dData: true]; + + alias Tuple!(CTable, string, int, int) Four; + GrowableCircularQueue!Four open; + open.push(Four(dData, "", playerx, playery)); + + immutable dirs = [tuple( 0, -1, 'u', 'U'), + tuple( 1, 0, 'r', 'R'), + tuple( 0, 1, 'd', 'D'), + tuple(-1, 0, 'l', 'L')]; + + while (open.length) { + //immutable (cur, cSol, x, y) = open.pop(); + immutable item = open.pop(); + immutable CTable cur = item[0]; + immutable string cSol = item[1]; + immutable int x = item[2]; + immutable int y = item[3]; + + foreach (di; dirs) { + CTable temp = cur; + //immutable (dx, dy) = di[0 .. 2]; + immutable int dx = di[0]; + immutable int dy = di[1]; + + if (temp[(y+dy) * ncols + x+dx] == El.boxOnGoal) { + if (push(x, y, dx, dy, temp) && temp !in visitedSet) { + if (isSolved(temp)) + return cSol ~ di[3]; + open.push(Four(temp, cSol ~ di[3], x+dx, y+dy)); + visitedSet[temp] = true; + } + } else if (move(x, y, dx, dy, temp) && + temp !in visitedSet) { + if (isSolved(temp)) + return cSol ~ di[2]; + open.push(Four(temp, cSol ~ di[2], x+dx, y+dy)); + visitedSet[temp] = true; + } + } + } + + return "No solution"; + } +} + +void main() { + import std.stdio, core.memory; + GC.disable(); // Uses about twice the memory + immutable level = +"####### +# # +# # +#. # # +#. $$ # +#.$$ # +#.# @# +#######"; + + immutable b = Board(level.splitLines()); + writeln(level, "\n\n", b.solve()); +} diff --git a/Task/Sokoban/D/sokoban-2.d b/Task/Sokoban/D/sokoban-2.d new file mode 100644 index 0000000000..c2d0f495b4 --- /dev/null +++ b/Task/Sokoban/D/sokoban-2.d @@ -0,0 +1,388 @@ +import core.stdc.stdio: printf, puts, fflush, stdout, putchar; +import core.stdc.stdlib: malloc, calloc, realloc, free, alloca, exit; +import core.stdc.string: memcpy, memset, memcmp; + +alias ushort cidx_t; +alias uint hash_t; + +// Board configuration is represented by an array of cell +// indices of player and boxes. +struct State { + hash_t h; + State* prev, next, qnext; + cidx_t[0] c; +} + +__gshared int w, h, n_boxes; +__gshared ubyte* board, goals, live; +__gshared size_t state_size, block_size = 32; +__gshared State* block_root, block_head; + +State* newState(State* parent) nothrow { + static State* next_of(State *s) nothrow { + return cast(State*)(cast(ubyte*)s + state_size); + } + + State *ptr; + if (!block_head) { + block_size *= 2; + State* p = cast(State*)malloc(block_size * state_size); + if (p == null) exit(1); + State* q; + p.next = block_root; + block_root = p; + ptr = cast(State*)(cast(ubyte*)p + state_size * block_size); + p = block_head = next_of(p); + for (q = next_of(p); q < ptr; p = q, q = next_of(q)) + p.next = q; + p.next = null; + } + + ptr = block_head; + block_head = block_head.next; + + ptr.prev = parent; + ptr.h = 0; + return ptr; +} + +void unNewState(State* p) nothrow { + p.next = block_head; + block_head = p; +} + +enum Cell { space, wall, player, box } + +// mark up positions where a box definitely should not be +void markLive(in int c) nothrow { + immutable int y = c / w; + immutable int x = c % w; + if (live[c]) + return; + + live[c] = 1; + if (y > 1 && board[c - w] != Cell.wall && + board[c - w * 2] != Cell.wall) + markLive(c - w); + if (y < h - 2 && board[c + w] != Cell.wall && + board[c + w * 2] != Cell.wall) + markLive(c + w); + if (x > 1 && board[c - 1] != Cell.wall && + board[c - 2] != Cell.wall) + markLive(c - 1); + if (x < w - 2 && board[c + 1] != Cell.wall && + board[c + 2] != Cell.wall) + markLive(c + 1); +} + +State* parseBoard(in int y, in int x, const char* s) nothrow { + w = x, h = y; + board = cast(ubyte*)calloc(w * h, ubyte.sizeof); + if (board == null) exit(2); + goals = cast(ubyte*)calloc(w * h, ubyte.sizeof); + if (goals == null) exit(3); + live = cast(ubyte*)calloc(w * h, ubyte.sizeof); + if (live == null) exit(4); + + n_boxes = 0; + for (int i = 0; s[i]; i++) { + switch(s[i]) { + case '#': + board[i] = Cell.wall; + continue; + case '.', '+': + goals[i] = 1; + goto case; + case '@': + continue; + case '*': + goals[i] = 1; + goto case; + case '$': + n_boxes++; + continue; + default: + continue; + } + } + + enum int int_size = int.sizeof; + state_size = (State.sizeof + + (1 + n_boxes) * cidx_t.sizeof + + int_size - 1) + / int_size * int_size; + + State* state = newState(null); + + for (cidx_t i = 0, j = 0; i < w * h; i++) { + if (goals[i]) + markLive(i); + if (s[i] == '$' || s[i] == '*') + (cast(cidx_t*)&state.c)[++j] = i; + else if (s[i] == '@' || s[i] == '+') + (cast(cidx_t*)&state.c)[0] = i; + } + + return state; +} + +void showBoard(const State* s) nothrow { + static immutable char*[] glyph1 = [" ", "#", "@", "$"]; + static immutable char*[] glyph2 = [".", "#", "@", "$"]; + + auto ptr = cast(char*)alloca(w * h * char.sizeof); + if (ptr == null) exit(5); + auto b = ptr[0 .. w * h]; + + memcpy(b.ptr, board, w * h); + + b[(cast(cidx_t*)&s.c)[0]] = Cell.player; + for (int i = 1; i <= n_boxes; i++) + b[(cast(cidx_t*)&s.c)[i]] = Cell.box; + + for (int i = 0; i < w * h; i++) { + printf((goals[i] ? glyph2 : glyph1)[b[i]]); + if (!((1 + i) % w)) + putchar('\n'); + } +} + +// K&R hash function +void hash(State* s) nothrow { + if (!s.h) { + hash_t ha = 0; + cidx_t* p = cast(cidx_t*)&s.c; + for (int i = 0; i <= n_boxes; i++) + ha = p[i] + 31 * ha; + s.h = ha; + } +} + +__gshared State** buckets; +__gshared hash_t hash_size, fill_limit, filled; + +void extendTable() nothrow { + int old_size = hash_size; + + if (!old_size) { + hash_size = 1024; + filled = 0; + fill_limit = hash_size * 3 / 4; // 0.75 load factor + } else { + hash_size *= 2; + fill_limit *= 2; + } + + buckets = cast(State**)realloc(buckets, + (State*).sizeof * hash_size); + if (buckets == null) exit(6); + + // rehash + memset(buckets + old_size, + 0, + (State*).sizeof * (hash_size - old_size)); + + immutable hash_t bits = hash_size - 1; + for (int i = 0; i < old_size; i++) { + State *head = buckets[i]; + buckets[i] = null; + while (head) { + State* next = head.next; + immutable int j = head.h & bits; + head.next = buckets[j]; + buckets[j] = head; + head = next; + } + } +} + +State* lookup(State *s) nothrow { + hash(s); + State *f = buckets[s.h & (hash_size - 1)]; + for (; f; f = f.next) { + if (!memcmp((cast(cidx_t*)&s.c), (cast(cidx_t*)&f.c), + cidx_t.sizeof * (1 + n_boxes))) + break; + } + + return f; +} + +bool addToTable(State* s) nothrow { + if (lookup(s)) { + unNewState(s); + return false; + } + + if (filled++ >= fill_limit) + extendTable(); + + immutable hash_t i = s.h & (hash_size - 1); + + s.next = buckets[i]; + buckets[i] = s; + return true; +} + +bool success(const State* s) nothrow { + for (int i = 1; i <= n_boxes; i++) + if (!goals[(cast(cidx_t*)&s.c)[i]]) + return false; + return true; +} + +State* moveMe(State* s, int dy, int dx) nothrow { + immutable int y = (cast(cidx_t*)&s.c)[0] / w; + immutable int x = (cast(cidx_t*)&s.c)[0] % w; + immutable int y1 = y + dy; + immutable int x1 = x + dx; + immutable int c1 = y1 * w + x1; + + if (y1 < 0 || y1 > h || x1 < 0 || x1 > w || board[c1] == Cell.wall) + return null; + + int at_box = 0; + for (int i = 1; i <= n_boxes; i++) { + if ((cast(cidx_t*)&s.c)[i] == c1) { + at_box = i; + break; + } + } + + int c2; + if (at_box) { + c2 = c1 + dy * w + dx; + if (board[c2] == Cell.wall || !live[c2]) + return null; + for (int i = 1; i <= n_boxes; i++) + if ((cast(cidx_t*)&s.c)[i] == c2) + return null; + } + + State* n = newState(s); + memcpy((cast(cidx_t*)&n.c) + 1, + (cast(cidx_t*)&s.c) + 1, + cidx_t.sizeof * n_boxes); + + cidx_t* p = (cast(cidx_t*)&n.c); + p[0] = cast(cidx_t)c1; + + if (at_box) + p[at_box] = cast(cidx_t)c2; + + // Bubble sort + for (int i = n_boxes; --i; ) { + cidx_t t = 0; + for (int j = 1; j < i; j++) { + if (p[j] > p[j + 1]) + t = p[j], p[j] = p[j+1], p[j+1] = t; + } + if (!t) + break; + } + + return n; +} + +__gshared State* next_level, done; + +bool queueMove(State *s) nothrow { + if (!s || !addToTable(s)) + return false; + + if (success(s)) { + puts("\nSuccess!"); + done = s; + return true; + } + + s.qnext = next_level; + next_level = s; + return false; +} + +bool do_move(State* s) nothrow { + return queueMove(moveMe(s, 1, 0)) || + queueMove(moveMe(s, -1, 0)) || + queueMove(moveMe(s, 0, 1)) || + queueMove(moveMe(s, 0, -1)); +} + +void showMoves(in State* s) nothrow { + if (s.prev) + showMoves(s.prev); + printf("\n"); + showBoard(s); +} + +int main() nothrow { + enum BIG = 0; + + static if (BIG == 0) { + State* s = parseBoard(8, 7, + "#######"~ + "# #"~ + "# #"~ + "#. # #"~ + "#. $$ #"~ + "#.$$ #"~ + "#.# @#"~ + "#######"); + + } else static if (BIG == 1) { + State* s = parseBoard(5, 13, + "#############"~ + "# # #"~ + "# $$$$$$$ @#"~ + "#....... #" + "#############"); + + } else { + State* s = parseBoard(11, 19, + " ##### "~ + " # # "~ + " # # "~ + " ### #$## "~ + " # # "~ + "### #$## # ######"~ + "# # ## ##### .#"~ + "# $ $ ..#"~ + "##### ### #@## .#"~ + " # #########"~ + " ####### "); + } + + showBoard(s); + extendTable(); + queueMove(s); + for (int i = 0; !done; i++) { + printf("depth %d\r", i); + fflush(stdout); + + State *head = next_level; + for (next_level = null; head && !done; head = head.qnext) + do_move(head); + + if (!next_level) { + puts("No solution?"); + return 1; + } + } + + showMoves(done); + + version (none) { + free(buckets); + free(board); + free(goals); + free(live); + + while (block_root) { + auto tmp = block_root.next; + free(block_root); + block_root = tmp; + } + } + + return 0; +} diff --git a/Task/Sokoban/Go/sokoban.go b/Task/Sokoban/Go/sokoban.go new file mode 100644 index 0000000000..5fec7db72e --- /dev/null +++ b/Task/Sokoban/Go/sokoban.go @@ -0,0 +1,117 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + level := ` +####### +# # +# # +#. # # +#. $$ # +#.$$ # +#.# @# +#######` + fmt.Printf("level:%s\n", level) + fmt.Printf("solution:\n%s\n", solve(level)) +} + +func solve(board string) string { + buffer = make([]byte, len(board)) + width := strings.Index(board[1:], "\n") + 1 + dirs := []struct { + move, push string + dPos int + }{ + {"u", "U", -width}, + {"r", "R", 1}, + {"d", "D", width}, + {"l", "L", -1}, + } + visited := map[string]bool{board: true} + open := []state{state{board, "", strings.Index(board, "@")}} + for len(open) > 0 { + s1 := &open[0] + open = open[1:] + for _, dir := range dirs { + var newBoard, newSol string + newPos := s1.pos + dir.dPos + switch s1.board[newPos] { + case '$', '*': + newBoard = s1.push(dir.dPos) + if newBoard == "" || visited[newBoard] { + continue + } + newSol = s1.cSol + dir.push + if strings.IndexAny(newBoard, ".+") < 0 { + return newSol + } + case ' ', '.': + newBoard = s1.move(dir.dPos) + if visited[newBoard] { + continue + } + newSol = s1.cSol + dir.move + default: + continue + } + open = append(open, state{newBoard, newSol, newPos}) + visited[newBoard] = true + } + } + return "No solution" +} + +type state struct { + board string + cSol string + pos int +} + +var buffer []byte + +func (s *state) move(dPos int) string { + copy(buffer, s.board) + if buffer[s.pos] == '@' { + buffer[s.pos] = ' ' + } else { + buffer[s.pos] = '.' + } + newPos := s.pos + dPos + if buffer[newPos] == ' ' { + buffer[newPos] = '@' + } else { + buffer[newPos] = '+' + } + return string(buffer) +} + +func (s *state) push(dPos int) string { + newPos := s.pos + dPos + boxPos := newPos + dPos + switch s.board[boxPos] { + case ' ', '.': + default: + return "" + } + copy(buffer, s.board) + if buffer[s.pos] == '@' { + buffer[s.pos] = ' ' + } else { + buffer[s.pos] = '.' + } + if buffer[newPos] == '$' { + buffer[newPos] = '@' + } else { + buffer[newPos] = '+' + } + if buffer[boxPos] == ' ' { + buffer[boxPos] = '$' + } else { + buffer[boxPos] = '*' + } + return string(buffer) +} diff --git a/Task/Sokoban/OCaml/sokoban.ocaml b/Task/Sokoban/OCaml/sokoban.ocaml new file mode 100644 index 0000000000..da8d03d7ef --- /dev/null +++ b/Task/Sokoban/OCaml/sokoban.ocaml @@ -0,0 +1,94 @@ +type dir = U | D | L | R +type move_t = Move of dir | Push of dir + +let letter = function + | Push(U) -> 'U' | Push(D) -> 'D' | Push(L) -> 'L' | Push(R) -> 'R' + | Move(U) -> 'u' | Move(D) -> 'd' | Move(L) -> 'l' | Move(R) -> 'r' + +let cols = ref 0 +let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1 + +let store = Hashtbl.create 251 +let mark t = Hashtbl.add store t true +let marked t = Hashtbl.mem store t + +let show ml = + List.iter (fun c -> print_char (letter c)) (List.rev ml); print_newline() + +let gen_moves (x,boxes) bd = + let empty i = bd.(i) = ' ' && not (List.mem i boxes) in + let check l dir = + let dx = delta dir in + let x1 = x+dx in + if List.mem x1 boxes then ( + if empty (x1+dx) then Push(dir) :: l else l + ) else ( + if bd.(x1) = ' ' then Move(dir) :: l else l + ) in + (List.fold_left check [] [U; L; R; D]) + +let do_move (x,boxes) = function + | Push(d) -> let dx = delta d in + let x1 = x+dx in let x2 = x1+dx in + let rec shift = function + | [] -> failwith "shift" + | h :: t -> if h = x1 then x2 :: t else h :: shift t in + x1, List.fast_sort compare (shift boxes) + | Move(d) -> (x+(delta d)), boxes + +let init_pos bd = + let p = ref 0 in + let q = ref [] in + let check i c = + if c = '$' || c = '*' then q := i::!q + else if c = '@' then p := i in ( + Array.iteri check bd; + (!p, List.fast_sort compare !q); + ) + +let final_box bd = + let check (i,l) c = if c = '.' || c = '*' then (i+1,i::l) else (i+1,l) in + List.fast_sort compare (snd (Array.fold_left check (0,[]) bd)) + +let array_of_input inp = + let r = List.length inp and c = String.length (List.hd inp) in + let a = Array.create (r*c) ' ' in ( + for i = 0 to pred r do + let s = List.nth inp i in + for j = 0 to pred c do a.(i*c+j) <- s.[j] done + done; + cols := c; a) + +let solve b = + let board = array_of_input b in + let targets = final_box board in + let solved pos = targets = snd pos in + let clear = Array.map (function '#' -> '#' | _ -> ' ') in + let bdc = clear board in + let q = Queue.create () in + let pos1 = init_pos board in + begin + mark pos1; + Queue.add (pos1, []) q; + while not (Queue.is_empty q) do + let curr, mhist = Queue.pop q in + let moves = gen_moves curr bdc in + let check m = + let next = do_move curr m in + if not (marked next) then + if solved next then (show (m::mhist); exit 0) + else (mark next; Queue.add (next,m::mhist) q) in + List.iter check moves + done; + print_endline "No solution" + end;; + +let level = ["#######"; + "# #"; + "# #"; + "#. # #"; + "#. $$ #"; + "#.$$ #"; + "#.# @#"; + "#######"] in +solve level diff --git a/Task/Sokoban/PicoLisp/sokoban-1.l b/Task/Sokoban/PicoLisp/sokoban-1.l new file mode 100644 index 0000000000..357957fa69 --- /dev/null +++ b/Task/Sokoban/PicoLisp/sokoban-1.l @@ -0,0 +1,82 @@ +(load "@lib/simul.l") + +# Display board +(de display () + (disp *Board NIL + '((This) + (pack + (if2 (== This *Pos) (memq This *Goals) + "+" # Player on goal + "@" # Player elsewhere + (if (: val) "*" ".") # On gloal + (or (: val) " ") ) # Elsewhere + " " ) ) ) ) + +# Initialize +(de main (Lst) + (mapc + '((B L) + (mapc + '((This C) + (case C + (" ") + ("." (push '*Goals This)) + ("@" (setq *Pos This)) + ("$" (=: val C) (push '*Boxes This)) + (T (=: val C)) ) ) + B L ) ) + (setq *Board (grid (length (car Lst)) (length Lst))) + (apply mapcar (flip (mapcar chop Lst)) list) ) + (display) ) + +# Generate possible push-moves +(de pushes () + (make + (for Box *Boxes + (unless (or (; (west Box) val) (; (east Box) val)) + (when (moves (east Box)) + (link (cons (cons Box (west Box)) *Pos "L" @)) ) + (when (moves (west Box)) + (link (cons (cons Box (east Box)) *Pos "R" @)) ) ) + (unless (or (; (south Box) val) (; (north Box) val)) + (when (moves (north Box)) + (link (cons (cons Box (south Box)) *Pos "D" @)) ) + (when (moves (south Box)) + (link (cons (cons Box (north Box)) *Pos "U" @)) ) ) ) ) ) + +# Moves of player to destination +(de moves (Dst Hist) + (or + (== Dst *Pos) + (mini length + (extract + '((Dir) + (with ((car Dir) Dst) + (cond + ((== This *Pos) (cons (cdr Dir))) + ((: val)) + ((memq This Hist)) + ((moves This (cons Dst Hist)) + (cons (cdr Dir) @) ) ) ) ) + '((west . "r") (east . "l") (south . "u") (north . "d")) ) ) ) ) + +# Find solution +(de go (Res) + (unless (idx '*Hist (sort (copy *Boxes)) T) # No repeated state + (if (find '((This) (<> "$" (: val))) *Goals) + (pick + '((Psh) + (setq # Move + *Pos (caar Psh) + *Boxes (cons (cdar Psh) (delq *Pos *Boxes)) ) + (put *Pos 'val NIL) + (put (cdar Psh) 'val "$") + (prog1 (go (append (cddr Psh) Res)) + (setq # Undo move + *Pos (cadr Psh) + *Boxes (cons (caar Psh) (delq (cdar Psh) *Boxes)) ) + (put (cdar Psh) 'val NIL) + (put (caar Psh) 'val "$") ) ) + (pushes) ) + (display) # Display solution + (pack (flip Res)) ) ) ) diff --git a/Task/Sokoban/PicoLisp/sokoban-2.l b/Task/Sokoban/PicoLisp/sokoban-2.l new file mode 100644 index 0000000000..d7143d070c --- /dev/null +++ b/Task/Sokoban/PicoLisp/sokoban-2.l @@ -0,0 +1,12 @@ +(main + (quote + "#######" + "# #" + "# #" + "#. # #" + "#. $$ #" + "#.$$ #" + "#.# @#" + "#######" ) ) +(prinl) +(go) diff --git a/Task/Sokoban/Python/sokoban.py b/Task/Sokoban/Python/sokoban.py new file mode 100644 index 0000000000..94710d9fc0 --- /dev/null +++ b/Task/Sokoban/Python/sokoban.py @@ -0,0 +1,96 @@ +from array import array +from collections import deque +import psyco + +data = [] +nrows = 0 +px = py = 0 +sdata = "" +ddata = "" + +def init(board): + global data, nrows, sdata, ddata, px, py + data = filter(None, board.splitlines()) + nrows = max(len(r) for r in data) + + maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '} + mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'} + + for r, row in enumerate(data): + for c, ch in enumerate(row): + sdata += maps[ch] + ddata += mapd[ch] + if ch == '@': + px = c + py = r + +def push(x, y, dx, dy, data): + if sdata[(y+2*dy) * nrows + x+2*dx] == '#' or \ + data[(y+2*dy) * nrows + x+2*dx] != ' ': + return None + + data2 = array("c", data) + data2[y * nrows + x] = ' ' + data2[(y+dy) * nrows + x+dx] = '@' + data2[(y+2*dy) * nrows + x+2*dx] = '*' + return data2.tostring() + +def is_solved(data): + for i in xrange(len(data)): + if (sdata[i] == '.') != (data[i] == '*'): + return False + return True + +def solve(): + open = deque([(ddata, "", px, py)]) + visited = set([ddata]) + dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), + (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')) + + lnrows = nrows + while open: + cur, csol, x, y = open.popleft() + + for di in dirs: + temp = cur + dx, dy = di[0], di[1] + + if temp[(y+dy) * lnrows + x+dx] == '*': + temp = push(x, y, dx, dy, temp) + if temp and temp not in visited: + if is_solved(temp): + return csol + di[3] + open.append((temp, csol + di[3], x+dx, y+dy)) + visited.add(temp) + else: + if sdata[(y+dy) * lnrows + x+dx] == '#' or \ + temp[(y+dy) * lnrows + x+dx] != ' ': + continue + + data2 = array("c", temp) + data2[y * lnrows + x] = ' ' + data2[(y+dy) * lnrows + x+dx] = '@' + temp = data2.tostring() + + if temp not in visited: + if is_solved(temp): + return csol + di[2] + open.append((temp, csol + di[2], x+dx, y+dy)) + visited.add(temp) + + return "No solution" + + +level = """\ +####### +# # +# # +#. # # +#. $$ # +#.$$ # +#.# @# +#######""" + +psyco.full() +init(level) +print level, "\n\n", solve() diff --git a/Task/Sokoban/Tcl/sokoban-1.tcl b/Task/Sokoban/Tcl/sokoban-1.tcl new file mode 100644 index 0000000000..1199e7eed9 --- /dev/null +++ b/Task/Sokoban/Tcl/sokoban-1.tcl @@ -0,0 +1,70 @@ +package require Tcl 8.5 + +proc solveSokoban b { + set cols [string length [lindex $b 0]] + set dxes [list [expr {-$cols}] $cols -1 1] + set i 0 + foreach c [split [join $b ""] ""] { + switch $c { + " " {lappend bdc " "} + "#" {lappend bdc "#"} + "@" {lappend bdc " ";set startplayer $i } + "$" {lappend bdc " ";lappend startbox $i} + "." {lappend bdc " "; lappend targets $i} + "+" {lappend bdc " ";set startplayer $i; lappend targets $i} + "*" {lappend bdc " ";lappend startbox $i;lappend targets $i} + } + incr i + } + set q [list [list $startplayer $startbox] {}] + set store([lindex $q 0]) {} + for {set idx 0} {$idx < [llength $q]} {incr idx 2} { + lassign [lindex $q $idx] x boxes + foreach dir {U D L R} dx $dxes { + if {[set x1 [expr {$x + $dx}]] in $boxes} { + if {[lindex $bdc [incr x1 $dx]] ne " " || $x1 in $boxes} { + continue + } + set tmpboxes $boxes + set x1 [expr {$x + $dx}] + for {set i 0} {$i < [llength $boxes]} {incr i} { + if {[lindex $boxes $i] == $x1} { + lset tmpboxes $i [expr {$x1 + $dx}] + break + } + } + if {$dx == 1 || $dx == -1} { + set next [list $x1 $tmpboxes] + } else { + set next [list $x1 [lsort -integer $tmpboxes]] + } + if {![info exists store($next)]} { + if {$targets eq [lindex $next 1]} { + foreach c [lindex $q [expr {$idx + 1}]] { + lassign $c ispush olddir + if {$ispush} { + append solution $olddir + } else { + append solution [string tolower $olddir] + } + } + return [append solution $dir] + } + set store($next) {} + set nm [lindex $q [expr {$idx + 1}]] + lappend q $next + lappend q [lappend nm [list 1 $dir]] + } + } elseif {[lindex $bdc $x1] eq " "} { + set next [list [expr {$x + $dx}] $boxes] + if {![info exists store($next)]} { + set store($next) {} + set nm [lindex $q [expr {$idx + 1}]] + lappend q $next + lappend q [lappend nm [list 0 $dir]] + } + } + } + } + error "no solution" +} diff --git a/Task/Sokoban/Tcl/sokoban-2.tcl b/Task/Sokoban/Tcl/sokoban-2.tcl new file mode 100644 index 0000000000..982e2e93dc --- /dev/null +++ b/Task/Sokoban/Tcl/sokoban-2.tcl @@ -0,0 +1,11 @@ +set level { + "#######" + "# #" + "# #" + "#. # #" + "#. $$ #" + "#.$$ #" + "#.# @#" + "#######" +} +puts [solveSokoban $level] diff --git a/Task/Solve-a-Hidato-puzzle/0DESCRIPTION b/Task/Solve-a-Hidato-puzzle/0DESCRIPTION new file mode 100644 index 0000000000..9af3630df8 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/0DESCRIPTION @@ -0,0 +1,20 @@ +The task is to write a program which solves [[wp:Hidato|Hidato puzzles]]. + +The rules are: +* You are given a grid with some numbers placed in it. The other squares in the grid will be blank. +** The grid is not necessarily rectangular. +** The grid may have holes in it. +** The grid is always connected. +** The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. +** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. +* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). +** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. +** A square may only contain one number. +* In a proper Hidato puzzle, the solution is unique. + +For example the following problem +[[File:Hidato_Start.png|center|Sample Hidato problem, from Wikipedia]] + +has the following solution, with path marked on it: + +[[File:HEnd.png|center|Solution to sample Hidato problem]] diff --git a/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c b/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c new file mode 100644 index 0000000000..95c85bf491 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/C/solve-a-hidato-puzzle.c @@ -0,0 +1,166 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +int *board, *flood, *known, top = 0, w, h; + +inline int idx(int y, int x) { return y * w + x; } + +int neighbors(int c, int *p) +/* +@c cell +@p list of neighbours +@return amount of neighbours +*/ +{ + int i, j, n = 0; + int y = c / w, x = c % w; + + for (i = y - 1; i <= y + 1; i++) { + if (i < 0 || i >= h) continue; + for (j = x - 1; j <= x + 1; j++) + if (!(j < 0 || j >= w + || (j == x && i == y) + || board[ p[n] = idx(i,j) ] == -1)) + n++; + } + + return n; +} + +void flood_fill(int c) +/* +fill all free cells around @c with “1” and write output to variable “flood” +@c cell +*/ +{ + int i, n[8], nei; + + nei = neighbors(c, n); + for (i = 0; i < nei; i++) { // for all neighbours + if (board[n[i]] || flood[n[i]]) continue; // if cell is not free, choose another neighbour + + flood[n[i]] = 1; + flood_fill(n[i]); + } +} + +/* Check all empty cells are reachable from higher known cells. + Should really do more checks to make sure cell_x and cell_x+1 + share enough reachable empty cells; I'm lazy. Will implement + if a good counter example is presented. */ +int check_connectity(int lowerbound) +{ + int c; + memset(flood, 0, sizeof(flood[0]) * w * h); + for (c = lowerbound + 1; c <= top; c++) + if (known[c]) flood_fill(known[c]); // mark all free cells around known cells + + for (c = 0; c < w * h; c++) + if (!board[c] && !flood[c]) // if there are free cells which could not be reached from flood_fill + return 0; + + return 1; +} + +void make_board(int x, int y, const char *s) +{ + int i; + + w = x, h = y; + x = w * h; + + known = calloc(sizeof(int*), x + 1); + board = calloc(sizeof(int), x); + flood = calloc(sizeof(int), x); + + while (x--) board[x] = -1; + + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) { + i = idx(y, x); + + while (isspace(*s)) s++; + + switch (*s) { + case '_': board[i] = 0; + case '.': break; + default: + known[ board[i] = strtol(s, 0, 10) ] = i; + if (board[i] > top) top = board[i]; + } + + while (*s && !isspace(*s)) s++; + } +} + +void show_board(const char *s) +{ + int i, j, c; + + printf("\n%s:\n", s); + + for (i = 0; i < h; i++, putchar('\n')) + for (j = 0; j < w; j++) { + c = board[ idx(i, j) ]; + printf(!c ? " __" : c == -1 ? " " : " %2d", c); + } +} + +int fill(int c, int n) +{ + int i, nei, p[8], ko, bo; + + if ((board[c] && board[c] != n) || (known[n] && known[n] != c)) + return 0; + + if (n == top) return 1; + + ko = known[n]; + bo = board[c]; + board[c] = n; + + if (check_connectity(n)) { + nei = neighbors(c, p); + for (i = 0; i < nei; i++) + if (fill(p[i], n + 1)) + return 1; + } + + board[c] = bo; + known[n] = ko; + return 0; +} + +int main() +{ + make_board( +#define USE_E 0 +#if (USE_E == 0) + 8,8, " __ 33 35 __ __ .. .. .." + " __ __ 24 22 __ .. .. .." + " __ __ __ 21 __ __ .. .." + " __ 26 __ 13 40 11 .. .." + " 27 __ __ __ 9 __ 1 .." + " . . __ __ 18 __ __ .." + " . .. . . __ 7 __ __" + " . .. .. .. . . 5 __" +#elif (USE_E == 1) + 3, 3, " . 4 ." + " _ 7 _" + " 1 _ _" +#else + 50, 3, + " 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74" + " . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ ." + " . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ." +#endif + ); + + show_board("Before"); + fill(known[1], 1); + show_board("After"); /* "40 lbs in two weeks!" */ + + return 0; +} diff --git a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d new file mode 100644 index 0000000000..0f3d22dd17 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-1.d @@ -0,0 +1,75 @@ +import std.stdio, std.array, std.conv, std.algorithm; + +int[][] board; +int[] given, start; + +void setup(string s) { + auto lines = s.split("\n"); + auto cols = lines[0].split().length; + auto rows = lines.length; + given.length = 0; + + board = new int[][](rows + 2, cols + 2); + foreach (i; 0 .. rows + 2) + board[i][] = -1; + + foreach (r, row; lines) { + foreach (c, cell; row.split()) { + switch (cell) { + case "__" : board[r + 1][c + 1] = 0; break; + case "." : break; + default : + int val = to!int(cell); + board[r + 1][c + 1] = val; + given ~= val; + if (val == 1) start = [r + 1, c + 1]; + } + } + } + given.sort(); +} + +bool solve(int r, int c, int n, int next = 0) { + if (n > given[$-1]) return true; + + if (board[r][c] && board[r][c] != n) + return false; + + if (board[r][c] == 0 && given[next] == n) + return false; + + int back = board[r][c]; + + board[r][c] = n; + foreach (i; -1 .. 2) + foreach (j; -1 .. 2) + if (solve(r + i, c + j, n + 1, next + (back == n))) + return true; + + board[r][c] = back; + return false; +} + +void printBoard() { + foreach (r; 0 .. board.length) { + foreach (c; board[r]) + writef(c == -1 ? " " : !c ? "__ " : "%2d ", c); + write('\n'); + } +} + +void main() { + auto hi = "__ 33 35 __ __ . . . + __ __ 24 22 __ . . . + __ __ __ 21 __ __ . . + __ 26 __ 13 40 11 . . + 27 __ __ __ 9 __ 1 . + . . __ __ 18 __ __ . + . . . . __ 7 __ __ + . . . . . . 5 __"; + + setup(hi); + printBoard(); + solve(start[0], start[1], 1); + printBoard(); +} diff --git a/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d new file mode 100644 index 0000000000..9dad5b3327 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/D/solve-a-hidato-puzzle-2.d @@ -0,0 +1,138 @@ +import std.stdio, std.string, std.conv, std.array, std.algorithm, + std.exception; + +struct Hidato { + alias Cell = int; + enum : Cell { emptyCell = -2, unknownCell = -1 } + + alias KnownT = int[2][Cell]; + immutable KnownT known; + immutable Cell boardMax; + Cell[][] board; + + this(in string input) /*pure nothrow*/ in { + assert(!input.empty); + } out { + immutable nRows = board.length; + immutable nCols = board[0].length; + assert(boardMax > 0 && boardMax <= nRows * nCols); + assert(known.length >= 2 && known.length <= nRows * nCols); + assert(1 in known && boardMax in known); + + foreach (const row; board) + foreach (immutable cell; row) + assert(cell == Hidato.emptyCell || + cell == Hidato.unknownCell || + (cell >= 1 && cell <= nRows * nCols)); + + foreach (/*immutable*/ n, immutable rc; known) { + assert(n > 0 && n <= boardMax); + assert(rc[0] >= 0 && rc[0] < nRows); + assert(rc[1] >= 0 && rc[1] < nCols); + } + } body { + bool[Cell] pathSeen; // A set. + KnownT knownMutable; + const lines = input.splitLines(); + immutable nCols = lines[0].split().length; + foreach (immutable int r, immutable row; lines) { + assert(row.split().length == nCols, + text("Wrong cols n.: ", row.split().length)); + auto boardRow = new typeof(board[0])(nCols); + foreach (immutable int c, immutable cell; row.split()) { + switch (cell) { + case ".": + boardRow[c] = Hidato.emptyCell; + break; + case "_": + boardRow[c] = Hidato.unknownCell; + break; + default: // Known. + immutable val = to!Cell(cell); + enforce(val > 0, "Path numbers must be > 0."); + enforce(val !in pathSeen, + text("Duplicated path number: ", val)); + pathSeen[val] = true; + boardRow[c] = val; + knownMutable[val] = [r, c]; + boardMax = max(boardMax, val); + } + } + board ~= boardRow; + } + + known = assumeUnique(knownMutable); // Not verified. + } + + bool solve() pure nothrow in { + assert(1 in known); + } body { + bool fill(in int r, in int c, in Cell n) pure nothrow { + if (n > boardMax) + return true; + + if (c < 0 || c >= board[0].length || + r < 0 || r >= board.length) + return false; + + if ((board[r][c] != Hidato.unknownCell && + board[r][c] != n) || + (n in known && known[n] != [r, c])) + return false; + + board[r][c] = n; + foreach (immutable i; -1 .. 2) + foreach (immutable j; -1 .. 2) + if (fill(r + i, c + j, n + 1)) + return true; + + board[r][c] = Hidato.unknownCell; + return false; + } + + return fill(known[1][0], known[1][1], 1); + } + + string toString() const { + immutable d = [Hidato.emptyCell: ".", + Hidato.unknownCell: "_"]; + immutable form = "%" ~ text(text(boardMax).length + 1) ~ "s"; + + string result; + foreach (const row; board) { + foreach (immutable c; row) + result ~= format(form, d.get(c, text(c))); + result ~= "\n"; + } + return result; + } +} + +void solveHidato(in string problem) { + auto hi = Hidato(problem); + writeln("Problem:\n", hi); + hi.solve(); + writeln("Solution:\n", hi); + writeln(); +} + +void main() { + solveHidato(" _ 33 35 _ _ . . . + _ _ 24 22 _ . . . + _ _ _ 21 _ _ . . + _ 26 _ 13 40 11 . . + 27 _ _ _ 9 _ 1 . + . . _ _ 18 _ _ . + . . . . _ 7 _ _ + . . . . . . 5 _"); + + solveHidato(". 4 . + _ 7 _ + 1 _ _"); + + solveHidato( +"1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74 + . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . + . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ." +); +} diff --git a/Task/Solve-a-Hidato-puzzle/Mathprog/solve-a-hidato-puzzle.math b/Task/Solve-a-Hidato-puzzle/Mathprog/solve-a-hidato-puzzle.math new file mode 100644 index 0000000000..554e259f74 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Mathprog/solve-a-hidato-puzzle.math @@ -0,0 +1,64 @@ +/*Hidato.mathprog, part of KuKu by Nigel Galloway + + Find a solution to a Hidato problem + + Nigel_Galloway@operamail.com + April 1st., 2011 +*/ + +param ZBLS; +param ROWS; +param COLS; +param D := 1; +set ROWSR := 1..ROWS; +set COLSR := 1..COLS; +set ROWSV := (1-D)..(ROWS+D); +set COLSV := (1-D)..(COLS+D); +param Iz{ROWSR,COLSR}, integer, default 0; +set ZBLSV := 1..(ZBLS+1); +set ZBLSR := 1..ZBLS; + +var BR{ROWSV,COLSV,ZBLSV}, binary; + +void0{r in ROWSV, z in ZBLSR,c in (1-D)..0}: BR[r,c,z] = 0; +void1{r in ROWSV, z in ZBLSR,c in (COLS+1)..(COLS+D)}: BR[r,c,z] = 0; +void2{c in COLSV, z in ZBLSR,r in (1-D)..0}: BR[r,c,z] = 0; +void3{c in COLSV, z in ZBLSR,r in (ROWS+1)..(ROWS+D)}: BR[r,c,z] = 0; +void4{r in ROWSV,c in (1-D)..0}: BR[r,c,ZBLS+1] = 1; +void5{r in ROWSV,c in (COLS+1)..(COLS+D)}: BR[r,c,ZBLS+1] = 1; +void6{c in COLSV,r in (1-D)..0}: BR[r,c,ZBLS+1] = 1; +void7{c in COLSV,r in (ROWS+1)..(ROWS+D)}: BR[r,c,ZBLS+1] = 1; + +Izfree{r in ROWSR, c in COLSR, z in ZBLSR : Iz[r,c] = -1}: BR[r,c,z] = 0; +Iz1{Izr in ROWSR, Izc in COLSR, r in ROWSR, c in COLSR, z in ZBLSR : Izr=r and Izc=c and Iz[Izr,Izc]=z}: BR[r,c,z] = 1; + +rule1{z in ZBLSR}: sum{r in ROWSR, c in COLSR} BR[r,c,z] = 1; +rule2{r in ROWSR, c in COLSR}: sum{z in ZBLSV} BR[r,c,z] = 1; +rule3{r in ROWSR, c in COLSR, z in ZBLSR}: BR[0,0,z+1] + BR[r-1,c-1,z+1] + BR[r-1,c,z+1] + BR[r-1,c+1,z+1] + BR[r,c-1,z+1] + BR[r,c+1,z+1] + BR[r+1,c-1,z+1] + BR[r+1,c,z+1] + BR[r+1,c+1,z+1] - BR[r,c,z] >= 0; + +solve; + +for {r in ROWSR} { + for {c in COLSR} { + printf " %2d", sum{z in ZBLSR} BR[r,c,z]*z; + } + printf "\n"; +} +data; + +param ROWS := 8; +param COLS := 8; +param ZBLS := 40; +param +Iz: 1 2 3 4 5 6 7 8 := + 1 . 33 35 . . -1 -1 -1 + 2 . . 24 22 . -1 -1 -1 + 3 . . . 21 . . -1 -1 + 4 . 26 . 13 40 11 -1 -1 + 5 27 . . . 9 . 1 -1 + 6 -1 -1 . . 18 . . -1 + 7 -1 -1 -1 -1 . 7 . . + 8 -1 -1 -1 -1 -1 -1 5 . + ; + + end; diff --git a/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 b/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 new file mode 100644 index 0000000000..a57ea26e7f --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 @@ -0,0 +1,72 @@ +my @grid; +my @known; + +sub show_board() { + my $width = $*max.chars; + for @grid -> $r { + say do for @$r { + when Rat { ' ' x $width } + when 0 { '_' x $width } + default { .fmt("%{$width}d") } + } + } +} + +sub neighbors($y,$x --> List) { + gather for [-1, -1], [-1, 0], [-1, 1], + [ 0, -1], [ 0, 1], + [ 1, -1], [ 1, 0], [ 1, 1] + { + my $y1 = $y + .[0]; + my $x1 = $x + .[1]; + take [$y1,$x1] if defined @grid[$y1][$x1]; + } +} + +sub try_fill($v, $coord [$y,$x] --> Bool) { + return True if $v > $*max; + + my $old = @grid[$y][$x]; + + return False if $old and $old != $v; + return False if @known[$v] and @known[$v] !eqv $coord; + + @grid[$y][$x] = $v; + print "\e[0H"; + show_board(); + + for neighbors($y, $x) { + return True if try_fill $v + 1, $_; + } + + @grid[$y][$x] = $old; + return False; +} + +sub hidato($board) { + my $*max = [max] +«$board.comb(/\d+/); + + @grid = $board.lines.map: -> $line { + [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] + } + for ^@grid -> $y { + for ^@grid[$y] -> $x { + if @grid[$y][$x] -> $v { + @known[$v] = [$y,$x]; + } + } + } + print "\e[0H\e[0J"; + try_fill 1, @known[1]; +} + +hidato q:to/END/; + __ 33 35 __ __ .. .. .. + __ __ 24 22 __ .. .. .. + __ __ __ 21 __ __ .. .. + __ 26 __ 13 40 11 .. .. + 27 __ __ __ 9 __ 1 .. + .. .. __ __ 18 __ __ .. + .. .. .. .. __ 7 __ __ + .. .. .. .. .. .. 5 __ + END diff --git a/Task/Solve-a-Hidato-puzzle/Perl/solve-a-hidato-puzzle.pl b/Task/Solve-a-Hidato-puzzle/Perl/solve-a-hidato-puzzle.pl new file mode 100644 index 0000000000..669c43f26d --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Perl/solve-a-hidato-puzzle.pl @@ -0,0 +1,84 @@ +use strict; +use List::Util 'max'; + +our (@grid, @known, $n); + +sub show_board { + for my $r (@grid) { + print map(!defined($_) ? ' ' : $_ + ? sprintf("%3d", $_) + : ' __' + , @$r), "\n" + } +} + +sub parse_board { + @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} + split "\n", shift(); + for my $y (0 .. $#grid) { + for my $x (0 .. $#{$grid[$y]}) { + $grid[$y][$x] > 0 + and $known[$grid[$y][$x]] = "$y,$x"; + } + } + $n = max(map { max @$_ } @grid); +} + +sub neighbors { + my ($y, $x) = @_; + my @out; + for ( [-1, -1], [-1, 0], [-1, 1], + [ 0, -1], [ 0, 1], + [ 1, -1], [ 1, 0], [ 1, 1]) + { + my $y1 = $y + $_->[0]; + my $x1 = $x + $_->[1]; + next if $x1 < 0 || $y1 < 0; + next unless defined $grid[$y1][$x1]; + push @out, "$y1,$x1"; + } + @out +} + +sub try_fill { + my ($v, $coord) = @_; + return 1 if $v > $n; + + my ($y, $x) = split ',', $coord; + my $old = $grid[$y][$x]; + + return if $old && $old != $v; + return if exists $known[$v] and $known[$v] ne $coord; + + $grid[$y][$x] = $v; + print "\033[0H"; + show_board(); + + try_fill($v + 1, $_) && return 1 + for neighbors($y, $x); + + $grid[$y][$x] = $old; + return +} + +parse_board +# ". 4 . +# _ 7 _ +# 1 _ _"; + +# " 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74 +# . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ +# . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ +# "; + + "__ 33 35 __ __ .. .. .. . + __ __ 24 22 __ .. .. .. . + __ __ __ 21 __ __ .. .. . + __ 26 __ 13 40 11 .. .. . + 27 __ __ __ 9 __ 1 .. . + . . __ __ 18 __ __ .. . + . .. . . __ 7 __ __ . + . .. .. .. . . 5 __ ."; + +print "\033[2J"; +try_fill(1, $known[1]); diff --git a/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-1.l b/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-1.l new file mode 100644 index 0000000000..b15e93960e --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-1.l @@ -0,0 +1,45 @@ +(load "@lib/simul.l") + +(de hidato (Lst) + (let Grid (grid (length (maxi length Lst)) (length Lst)) + (mapc + '((G L) + (mapc + '((This Val) + (nond + (Val + (with (: 0 1 1) (con (: 0 1))) # Cut off west + (with (: 0 1 -1) (set (: 0 1))) # east + (with (: 0 -1 1) (con (: 0 -1))) # south + (with (: 0 -1 -1) (set (: 0 -1))) # north + (set This) ) + ((=T Val) (=: val Val)) ) ) + G L ) ) + Grid + (apply mapcar (reverse Lst) list) ) + (let Todo + (by '((This) (: val)) sort + (mapcan '((Col) (filter '((This) (: val)) Col)) + Grid ) ) + (let N 1 + (with (pop 'Todo) + (recur (N Todo) + (unless (> (inc 'N) (; Todo 1 val)) + (find + '((Dir) + (with (Dir This) + (cond + ((= N (: val)) + (if (cdr Todo) (recurse N @) T) ) + ((not (: val)) + (=: val N) + (or (recurse N Todo) (=: val NIL)) ) ) ) ) + (quote + west east south north + ((X) (or (south (west X)) (west (south X)))) + ((X) (or (north (west X)) (west (north X)))) + ((X) (or (south (east X)) (east (south X)))) + ((X) (or (north (east X)) (east (north X)))) ) ) ) ) ) ) ) + (disp Grid 0 + '((This) + (if (: val) (align 3 @) " ") ) ) ) ) diff --git a/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-2.l b/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-2.l new file mode 100644 index 0000000000..c0aac93b3a --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/PicoLisp/solve-a-hidato-puzzle-2.l @@ -0,0 +1,10 @@ +(hidato + (quote + (T 33 35 T T) + (T T 24 22 T) + (T T T 21 T T) + (T 26 T 13 40 11) + (27 T T T 9 T 1) + (NIL NIL T T 18 T T) + (NIL NIL NIL NIL T 7 T T) + (NIL NIL NIL NIL NIL NIL 5 T) ) ) diff --git a/Task/Solve-a-Hidato-puzzle/Prolog/solve-a-hidato-puzzle.pro b/Task/Solve-a-Hidato-puzzle/Prolog/solve-a-hidato-puzzle.pro new file mode 100644 index 0000000000..80505d0b21 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Prolog/solve-a-hidato-puzzle.pro @@ -0,0 +1,100 @@ +:- use_module(library(clpfd)). + +hidato :- + init1(Li), + % skip first blank line + init2(1, 1, 10, Li), + my_write(Li). + + +init1(Li) :- + Li = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, A, 33, 35, B, C, 0, 0, 0, 0, + 0, D, E, 24, 22, F, 0, 0, 0, 0, + 0, G, H, I, 21, J, K, 0, 0, 0, + 0, L, 26, M, 13, 40, 11, 0, 0, 0, + 0, 27, N, O, P, 9, Q, 1, 0, 0, + 0, 0, 0, R, S, 18, T, U, 0, 0, + 0, 0, 0, 0, 0, V, 7, W, X, 0, + 0, 0, 0, 0, 0, 0, 0, 5, Y, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + + LV = [ A, 33, 35, B, C, + D, E, 24, 22, F, + G, H, I, 21, J, K, + L, 26, M, 13, 40, 11, + 27, N, O, P, 9, Q, 1, + R, S, 18, T, U, + V, 7, W, X, + 5, Y], + + + LV ins 1..40, + all_distinct(LV). + +% give the constraints +% Stop before the last line +init2(_N, Col, Max_Col, _L) :- + Col is Max_Col - 1. + +% skip zeros +init2(N, Lig, Col, L) :- + I is N + Lig * Col, + element(I, L, 0), + !, + V is N+1, + ( V > Col -> N1 = 1, Lig1 is Lig + 1; N1 = V, Lig1 = Lig), + init2(N1, Lig1, Col, L). + + +% skip first column +init2(1, Lig, Col, L) :- + !, + init2(2, Lig, Col, L) . + +% skip last column +init2(Col, Lig, Col, L) :- + !, + Lig1 is Lig+1, + init2(1, Lig1, Col, L). + +% V5 V3 V6 +% V1 V V2 +% V7 V4 V8 +% general case +init2(N, Lig, Col, L) :- + I is N + Lig * Col, + element(I, L, V), + + I1 is I - 1, I2 is I + 1, I3 is I - Col, I4 is I + Col, + I5 is I3 - 1, I6 is I3 + 1, I7 is I4 - 1, I8 is I4 + 1, + + maplist(compute_BI(L, V), [I1,I2,I3,I4,I5,I6,I7,I8], VI, BI), + + sum(BI, #=, SBI), + + ( ((V #= 1 #\/ V #= 40) #/\ SBI #= 1) #\/ + (V #\= 1 #/\ V #\= 40 #/\ SBI #= 2)) #<==> 1, + + labeling([ffc, enum], [V | VI]), + + N1 is N+1, + init2(N1, Lig, Col, L). + +compute_BI(L, V, I, VI, BI) :- + element(I, L, VI), + VI #= 0 #==> BI #= 0, + ( VI #\= 0 #/\ (V - VI #= 1 #\/ VI - V #= 1)) #<==> BI. + +% display the result +my_write([0, A, B, C, D, E, F, G, H, 0 | T]) :- + maplist(my_write_1, [A, B, C, D, E, F, G, H]), nl, + my_write(T). + +my_write([]). + +my_write_1(0) :- + write(' '). + +my_write_1(X) :- + writef('%3r', [X]). diff --git a/Task/Solve-a-Hidato-puzzle/Python/solve-a-hidato-puzzle.py b/Task/Solve-a-Hidato-puzzle/Python/solve-a-hidato-puzzle.py new file mode 100644 index 0000000000..2813d3e424 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Python/solve-a-hidato-puzzle.py @@ -0,0 +1,69 @@ +board = [] +given = [] +start = None + +def setup(s): + global board, given, start + lines = s.splitlines() + ncols = len(lines[0].split()) + nrows = len(lines) + board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)] + + for r, row in enumerate(lines): + for c, cell in enumerate(row.split()): + if cell == "__" : + board[r + 1][c + 1] = 0 + continue + elif cell == ".": + continue # -1 + else: + val = int(cell) + board[r + 1][c + 1] = val + given.append(val) + if val == 1: + start = (r + 1, c + 1) + given.sort() + +def solve(r, c, n, next=0): + if n > given[-1]: + return True + if board[r][c] and board[r][c] != n: + return False + if board[r][c] == 0 and given[next] == n: + return False + + back = 0 + if board[r][c] == n: + next += 1 + back = n + + board[r][c] = n + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if solve(r + i, c + j, n + 1, next): + return True + board[r][c] = back + return False + +def print_board(): + d = {-1: " ", 0: "__"} + bmax = max(max(r) for r in board) + form = "%" + str(len(str(bmax)) + 1) + "s" + for r in board[1:-1]: + print "".join(form % d.get(c, str(c)) for c in r[1:-1]) + +hi = """\ +__ 33 35 __ __ . . . +__ __ 24 22 __ . . . +__ __ __ 21 __ __ . . +__ 26 __ 13 40 11 . . +27 __ __ __ 9 __ 1 . + . . __ __ 18 __ __ . + . . . . __ 7 __ __ + . . . . . . 5 __""" + +setup(hi) +print_board() +solve(start[0], start[1], 1) +print +print_board() diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb new file mode 100644 index 0000000000..b4de67b362 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb @@ -0,0 +1,31 @@ +# Solve a Hidato Puzzle +# +# Nigel_Galloway +# May 5th., 2012. +class Cell + def initialize(row=0, col=0, value=nil) + @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] + @t = false + $zbl[value] = false unless value == nil + @value = value + end + def try(value) + return false if @value == nil + return true if value > E + return false if @t + return false if @value > 0 and @value != value + return false if @value == 0 and not $zbl[value] + @t = true + @adj.each{|x| + if (Board[x[0]][x[1]].try(value+1)) then + @value = value + return true + end + } + @t = false + return false + end + def value + return @value + end +end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb new file mode 100644 index 0000000000..0202b1d46a --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb @@ -0,0 +1,15 @@ +Rows = 3 +Cols = 3 +E = 7 +$zbl = Array.new(E+1,true) +Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new(1,2,4) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(2,1,0) ,Cell.new(2,2,7) ,Cell.new(2,3,0) ,Cell.new()], + [Cell.new(),Cell.new(3,1,1) ,Cell.new(3,2,0) ,Cell.new(3,3,0) ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] + +require 'benchmark' +puts Benchmark.measure {Board[3][1].try(1)} +(1..Rows).each{|r| + (1..Cols).each{|c| printf("%2s",Board[r][c].value)} + puts ""} diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb new file mode 100644 index 0000000000..0448776b18 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-3.rb @@ -0,0 +1,19 @@ +Rows = 8 +Cols = 8 +E = 40 +$zbl = Array.new(E+1,true) +Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(1,1,0) ,Cell.new(1,2,33) ,Cell.new(1,3,35) ,Cell.new(1,4,0) ,Cell.new(1,5,0) ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(2,1,0) ,Cell.new(2,2,0) ,Cell.new(2,3,24) ,Cell.new(2,4,22) ,Cell.new(2,5,0) ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(3,1,0) ,Cell.new(3,2,0) ,Cell.new(3,3,0) ,Cell.new(3,4,21) ,Cell.new(3,5,0) ,Cell.new(3,6,0) ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(4,1,0) ,Cell.new(4,2,26) ,Cell.new(4,3,0) ,Cell.new(4,4,13) ,Cell.new(4,5,40) ,Cell.new(4,6,11) ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(5,1,27) ,Cell.new(5,2,0) ,Cell.new(5,3,0) ,Cell.new(5,4,0) ,Cell.new(5,5,9) ,Cell.new(5,6,0) ,Cell.new(5,7,1) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(6,3,0) ,Cell.new(6,4,0) ,Cell.new(6,5,18) ,Cell.new(6,6,0) ,Cell.new(6,7,0) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(7,5,0) ,Cell.new(7,6,7) ,Cell.new(7,7,0) ,Cell.new(7,8,0) ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(8,7,5) ,Cell.new(8,8,0) ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] +require 'benchmark' +puts Benchmark.measure {Board[5][7].try(1)} +(1..Rows).each{|r| + (1..Cols).each{|c| printf("%3s",Board[r][c].value)} + puts ""} diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb new file mode 100644 index 0000000000..1cedae6782 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb @@ -0,0 +1,14 @@ +Rows = 3 +Cols = 50 +E = 74 +$zbl = Array.new(E+1,true) +Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(1,1,1) ,Cell.new(1,2,0) ,Cell.new(1,3,0) ,Cell.new() ,Cell.new() ,Cell.new(1,6,0) ,Cell.new(1,7,0) ,Cell.new() ,Cell.new() ,Cell.new(1,10,0) ,Cell.new(1,11,0) ,Cell.new() ,Cell.new() ,Cell.new(1,14,0) ,Cell.new(1,15,0) ,Cell.new() ,Cell.new() ,Cell.new(1,18,0) ,Cell.new(1,19,0) ,Cell.new() ,Cell.new() ,Cell.new(1,22,0) ,Cell.new(1,23,0) ,Cell.new() ,Cell.new() ,Cell.new(1,26,0) ,Cell.new(1,27,0) ,Cell.new() ,Cell.new() ,Cell.new(1,30,0) ,Cell.new(1,31,0) ,Cell.new() ,Cell.new() ,Cell.new(1,34,0) ,Cell.new(1,35,0) ,Cell.new() ,Cell.new() ,Cell.new(1,38,0) ,Cell.new(1,39,0) ,Cell.new() ,Cell.new() ,Cell.new(1,42,0) ,Cell.new(1,43,0) ,Cell.new() ,Cell.new() ,Cell.new(1,46,0) ,Cell.new(1,47,0) ,Cell.new() ,Cell.new() ,Cell.new(1,50,74),Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(2,3,0) ,Cell.new() ,Cell.new(2,5,0) ,Cell.new() ,Cell.new(2,7,0) ,Cell.new() ,Cell.new(2,9,0) ,Cell.new() ,Cell.new(2,11,0) ,Cell.new() ,Cell.new(2,13,0) ,Cell.new() ,Cell.new(2,15,0) ,Cell.new() ,Cell.new(2,17,0) ,Cell.new() ,Cell.new(2,19,0) ,Cell.new() ,Cell.new(2,21,0) ,Cell.new() ,Cell.new(2,23,0) ,Cell.new() ,Cell.new(2,25,0) ,Cell.new() ,Cell.new(2,27,0) ,Cell.new() ,Cell.new(2,29,0) ,Cell.new() ,Cell.new(2,31,0) ,Cell.new() ,Cell.new(2,33,0) ,Cell.new() ,Cell.new(2,35,0) ,Cell.new() ,Cell.new(2,37,0) ,Cell.new() ,Cell.new(2,39,0) ,Cell.new() ,Cell.new(2,41,0) ,Cell.new() ,Cell.new(2,43,0) ,Cell.new() ,Cell.new(2,45,0) ,Cell.new() ,Cell.new(2,47,0) ,Cell.new() ,Cell.new(2,49,0) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(3,4,0) ,Cell.new(3,5,0) ,Cell.new() ,Cell.new() ,Cell.new(3,8,0) ,Cell.new(3,9,0) ,Cell.new() ,Cell.new() ,Cell.new(3,12,0) ,Cell.new(3,13,0) ,Cell.new() ,Cell.new() ,Cell.new(3,16,0) ,Cell.new(3,17,0) ,Cell.new() ,Cell.new() ,Cell.new(3,20,0) ,Cell.new(3,21,0) ,Cell.new() ,Cell.new() ,Cell.new(3,24,0) ,Cell.new(3,25,0) ,Cell.new() ,Cell.new() ,Cell.new(3,28,0) ,Cell.new(3,29,0) ,Cell.new() ,Cell.new() ,Cell.new(3,32,0) ,Cell.new(3,33,0) ,Cell.new() ,Cell.new() ,Cell.new(3,36,0) ,Cell.new(3,37,0) ,Cell.new() ,Cell.new() ,Cell.new(3,40,0) ,Cell.new(3,41,0) ,Cell.new() ,Cell.new() ,Cell.new(3,44,0) ,Cell.new(3,45,0) ,Cell.new() ,Cell.new() ,Cell.new(3,48,0) ,Cell.new(3,49,0) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] +require 'benchmark' +puts Benchmark.measure {Board[1][1].try(1)} +(1..Rows).each{|r| + (1..Cols).each{|c| printf("%3s",Board[r][c].value)} + puts ""} diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb new file mode 100644 index 0000000000..824bd28ca9 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-5.rb @@ -0,0 +1,9 @@ +Rows = 3 +Cols = 50 +E = 74 +$zbl = Array.new(E+1,true) +Board = [[Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new(1,1,1) ,Cell.new(1,2,0) ,Cell.new(1,3,0) ,Cell.new() ,Cell.new() ,Cell.new(1,6,0) ,Cell.new(1,7,0) ,Cell.new() ,Cell.new() ,Cell.new(1,10,0) ,Cell.new(1,11,0) ,Cell.new() ,Cell.new() ,Cell.new(1,14,0) ,Cell.new(1,15,0) ,Cell.new() ,Cell.new() ,Cell.new(1,18,0) ,Cell.new(1,19,0) ,Cell.new() ,Cell.new() ,Cell.new(1,22,0) ,Cell.new(1,23,0) ,Cell.new() ,Cell.new() ,Cell.new(1,26,0) ,Cell.new(1,27,0) ,Cell.new() ,Cell.new() ,Cell.new(1,30,0) ,Cell.new(1,31,0) ,Cell.new() ,Cell.new() ,Cell.new(1,34,0) ,Cell.new(1,35,0) ,Cell.new() ,Cell.new() ,Cell.new(1,38,0) ,Cell.new(1,39,0) ,Cell.new() ,Cell.new() ,Cell.new(1,42,0) ,Cell.new(1,43,0) ,Cell.new() ,Cell.new() ,Cell.new(1,46,0) ,Cell.new(1,47,0) ,Cell.new() ,Cell.new() ,Cell.new(1,50,74),Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new(2,3,0) ,Cell.new() ,Cell.new(2,5,0) ,Cell.new() ,Cell.new(2,7,0) ,Cell.new() ,Cell.new(2,9,0) ,Cell.new() ,Cell.new(2,11,0) ,Cell.new() ,Cell.new(2,13,0) ,Cell.new() ,Cell.new(2,15,0) ,Cell.new() ,Cell.new(2,17,0) ,Cell.new() ,Cell.new(2,19,0) ,Cell.new() ,Cell.new(2,21,0) ,Cell.new() ,Cell.new(2,23,0) ,Cell.new() ,Cell.new(2,25,0) ,Cell.new() ,Cell.new(2,27,0) ,Cell.new() ,Cell.new(2,29,0) ,Cell.new() ,Cell.new(2,31,0) ,Cell.new() ,Cell.new(2,33,0) ,Cell.new() ,Cell.new(2,35,0) ,Cell.new() ,Cell.new(2,37,0) ,Cell.new() ,Cell.new(2,39,0) ,Cell.new() ,Cell.new(2,41,0) ,Cell.new() ,Cell.new(2,43,0) ,Cell.new() ,Cell.new(2,45,0) ,Cell.new() ,Cell.new(2,47,0) ,Cell.new() ,Cell.new(2,49,0) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(3,4,0) ,Cell.new(3,5,0) ,Cell.new() ,Cell.new() ,Cell.new(3,8,11) ,Cell.new(3,9,0) ,Cell.new() ,Cell.new() ,Cell.new(3,12,0) ,Cell.new(3,13,0) ,Cell.new() ,Cell.new() ,Cell.new(3,16,23) ,Cell.new(3,17,0) ,Cell.new() ,Cell.new() ,Cell.new(3,20,0) ,Cell.new(3,21,0) ,Cell.new() ,Cell.new() ,Cell.new(3,24,35) ,Cell.new(3,25,0) ,Cell.new() ,Cell.new() ,Cell.new(3,28,0) ,Cell.new(3,29,0) ,Cell.new() ,Cell.new() ,Cell.new(3,32,47) ,Cell.new(3,33,0) ,Cell.new() ,Cell.new() ,Cell.new(3,36,0) ,Cell.new(3,37,0) ,Cell.new() ,Cell.new() ,Cell.new(3,40,0) ,Cell.new(3,41,0) ,Cell.new() ,Cell.new() ,Cell.new(3,44,65) ,Cell.new(3,45,0) ,Cell.new() ,Cell.new() ,Cell.new(3,48,0) ,Cell.new(3,49,0) ,Cell.new() ,Cell.new()], + [Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new()]] diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb new file mode 100644 index 0000000000..27e7c8472d --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-6.rb @@ -0,0 +1,48 @@ +# Solve a Hidato Puzzle with Warnsdorff like logic applied +# +# Nigel_Galloway +# May 6th., 2012. +class Cell + def initialize(row=0, col=0, value=nil) + @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] + @t = false + $zbl[value] = false unless value == nil + @value = value + end + def try(value) + return false if @value == nil + return true if value > E + return false if @t + return false if @value > 0 and @value != value + return false if @value == 0 and not $zbl[value] + @t = true + h = Hash.new + n = 0 + @adj.each{|x| + h[Board[x[0]][x[1]].wdof*10+n] = Board[x[0]][x[1]] + n += 1 + } + h.sort.each{|key,cell| + if (cell.try(value+1)) then + @value = value + return true + end + } + @t = false + return false + end + def wdon + return 0 if @value == nil + return 0 if @value > 0 + return 0 if @t + return 1 + end + def wdof + res = 0 + @adj.each{|x| res += Board[x[0]][x[1]].wdon} + return res + end + def value + return @value + end +end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb new file mode 100644 index 0000000000..54ebf377a8 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-7.rb @@ -0,0 +1,44 @@ +class Cell + def initialize(row=0, col=0, value=nil) + @adj = [[row-1,col-2],[row-2,col-1],[row-2,col+1],[row-1,col+2],[row+1,col+2],[row+2,col+1],[row+2,col-1],[row+1,col-2]] + @t = false + $zbl[value] = false unless value == nil + @value = value + end + def try(value) + return false if @value == nil + return true if value > E + return false if @t + return false if @value > 0 and @value != value + return false if @value == 0 and not $zbl[value] + @t = true + h = Hash.new + n = 0 + @adj.each{|x| + h[Board[x[0]][x[1]].wdof*10+n] = Board[x[0]][x[1]] + n += 1 + } + h.sort.each{|key,cell| + if (cell.try(value+1)) then + @value = value + return true + end + } + @t = false + return false + end + def wdon + return 0 if @value == nil + return 0 if @value > 0 + return 0 if @t + return 1 + end + def wdof + res = 0 + @adj.each{|x| res += Board[x[0]][x[1]].wdon} + return res + end + def value + return @value + end +end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb new file mode 100644 index 0000000000..15ec189f25 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-8.rb @@ -0,0 +1,21 @@ +Rows = 9 +Cols = 9 +E = 64 +$zbl = Array.new(E+1,true) +Board = [[Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(2,2,0),Cell.new(2,3,0),Cell.new(2,4,0),Cell.new(2,5,0),Cell.new(2,6,0),Cell.new(2,7,0),Cell.new(2,8,0),Cell.new(2,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(3,2,0),Cell.new(3,3,0),Cell.new(3,4,0),Cell.new(3,5,0),Cell.new(3,6,0),Cell.new(3,7,0),Cell.new(3,8,0),Cell.new(3,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(4,2,0),Cell.new(4,3,0),Cell.new(4,4,0),Cell.new(4,5,0),Cell.new(4,6,0),Cell.new(4,7,0),Cell.new(4,8,0),Cell.new(4,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(5,2,0),Cell.new(5,3,1),Cell.new(5,4,0),Cell.new(5,5,0),Cell.new(5,6,0),Cell.new(5,7,0),Cell.new(5,8,0),Cell.new(5,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(6,2,0),Cell.new(6,3,0),Cell.new(6,4,0),Cell.new(6,5,0),Cell.new(6,6,0),Cell.new(6,7,0),Cell.new(6,8,0),Cell.new(6,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(7,2,0),Cell.new(7,3,0),Cell.new(7,4,0),Cell.new(7,5,0),Cell.new(7,6,0),Cell.new(7,7,0),Cell.new(7,8,0),Cell.new(7,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(8,2,0),Cell.new(8,3,0),Cell.new(8,4,0),Cell.new(8,5,0),Cell.new(8,6,0),Cell.new(8,7,0),Cell.new(8,8,0),Cell.new(8,9,0) ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new(9,2,0),Cell.new(9,3,0),Cell.new(9,4,0),Cell.new(9,5,0),Cell.new(9,6,0),Cell.new(9,7,0),Cell.new(9,8,0),Cell.new(9,9,0),Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()], + [Cell.new(),Cell.new(),Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new() ,Cell.new(),Cell.new()]] +require 'benchmark' +puts Benchmark.measure {Board[5][3].try(1)} +(1..Rows).each{|r| + (1..Cols).each{|c| printf("%3s",Board[r][c].value)} + puts ""} diff --git a/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-1.tcl b/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-1.tcl new file mode 100644 index 0000000000..700c02c091 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-1.tcl @@ -0,0 +1,110 @@ +proc init {initialConfiguration} { + global grid max filled + set max 1 + set y 0 + foreach row [split [string trim $initialConfiguration "\n"] "\n"] { + set x 0 + set rowcontents {} + foreach cell $row { + if {![string is integer -strict $cell]} {set cell -1} + lappend rowcontents $cell + set max [expr {max($max, $cell)}] + if {$cell > 0} { + dict set filled $cell [list $y $x] + } + incr x + } + lappend grid $rowcontents + incr y + } +} + +proc findseps {} { + global max filled + set result {} + for {set i 1} {$i < $max-1} {incr i} { + if {[dict exists $filled $i]} { + for {set j [expr {$i+1}]} {$j <= $max} {incr j} { + if {[dict exists $filled $j]} { + if {$j-$i > 1} { + lappend result [list $i $j [expr {$j-$i}]] + } + break + } + } + } + } + return [lsort -integer -index 2 $result] +} + +proc makepaths {sep} { + global grid filled + lassign $sep from to len + lassign [dict get $filled $from] y x + set result {} + foreach {dx dy} {-1 -1 -1 0 -1 1 0 -1 0 1 1 -1 1 0 1 1} { + discover [expr {$x+$dx}] [expr {$y+$dy}] [expr {$from+1}] $to \ + [list [list $from $x $y]] $grid + } + return $result +} +proc discover {x y n limit path model} { + global filled + # Check for illegal + if {[lindex $model $y $x] != 0} return + upvar 1 result result + lassign [dict get $filled $limit] ly lx + # Special case + if {$n == $limit-1} { + if {abs($x-$lx)<=1 && abs($y-$ly)<=1 && !($lx==$x && $ly==$y)} { + lappend result [lappend path [list $n $x $y] [list $limit $lx $ly]] + } + return + } + # Check for impossible + if {abs($x-$lx) > $limit-$n || abs($y-$ly) > $limit-$n} return + # Recursive search + lappend path [list $n $x $y] + lset model $y $x $n + incr n + foreach {dx dy} {-1 -1 -1 0 -1 1 0 -1 0 1 1 -1 1 0 1 1} { + discover [expr {$x+$dx}] [expr {$y+$dy}] $n $limit $path $model + } +} + +proc applypath {path} { + global grid filled + puts "Found unique path for [lindex $path 0 0] -> [lindex $path end 0]" + foreach cell [lrange $path 1 end-1] { + lassign $cell n x y + lset grid $y $x $n + dict set filled $n [list $y $x] + } +} + +proc printgrid {} { + global grid max + foreach row $grid { + foreach cell $row { + puts -nonewline [format " %*s" [string length $max] [expr { + $cell==-1 ? "." : $cell + }]] + } + puts "" + } +} + +proc solveHidato {initialConfiguration} { + init $initialConfiguration + set limit [llength [findseps]] + while {[llength [set seps [findseps]]] && [incr limit -1]>=0} { + foreach sep $seps { + if {[llength [set paths [makepaths $sep]]] == 1} { + applypath [lindex $paths 0] + break + } + } + } + puts "" + printgrid +} diff --git a/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-2.tcl b/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-2.tcl new file mode 100644 index 0000000000..c7cab26672 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Tcl/solve-a-hidato-puzzle-2.tcl @@ -0,0 +1,10 @@ +solveHidato " + 0 33 35 0 0 . . . + 0 0 24 22 0 . . . + 0 0 0 21 0 0 . . + 0 26 0 13 40 11 . . + 27 0 0 0 9 0 1 . + . . 0 0 18 0 0 . + . . . . 0 7 0 0 + . . . . . . 5 0 +" diff --git a/Task/Sort-an-array-of-composite-structures/0DESCRIPTION b/Task/Sort-an-array-of-composite-structures/0DESCRIPTION new file mode 100644 index 0000000000..97849fb1fb --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/0DESCRIPTION @@ -0,0 +1,13 @@ +Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudocode): + + Define structure pair such that: + name as a string + value as a string + +and an array of such pairs: + + x: array of pairs + +then define a sort routine that sorts the array ''x'' by the key ''name''. + +This task can always be accomplished with [[Sorting Using a Custom Comparator]]. If your language is not listed here, please see the other article. diff --git a/Task/Sort-an-array-of-composite-structures/1META.yaml b/Task/Sort-an-array-of-composite-structures/1META.yaml new file mode 100644 index 0000000000..556e45905d --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting diff --git a/Task/Sort-an-array-of-composite-structures/ACL2/sort-an-array-of-composite-structures.acl2 b/Task/Sort-an-array-of-composite-structures/ACL2/sort-an-array-of-composite-structures.acl2 new file mode 100644 index 0000000000..6a4095ff66 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/ACL2/sort-an-array-of-composite-structures.acl2 @@ -0,0 +1,32 @@ +(defun insert-by-key (o os key) + (cond ((endp os) (list o)) + ((< (cdr (assoc key o)) + (cdr (assoc key (first os)))) + (cons o os)) + (t (cons (first os) + (insert-by-key o (rest os) key))))) + +(defun isort-by-key (os key) + (if (endp os) + nil + (insert-by-key (first os) + (isort-by-key (rest os) key) + key))) + +(isort-by-key + '(((name . "map") + (weight . 9) + (value . 150)) + ((name . "compass") + (weight . 13) + (value . 35)) + ((name . "water") + (weight . 153) + (value . 200)) + ((name . "sandwich") + (weight . 50) + (value . 60)) + ((name . "glucose") + (weight . 15) + (value . 60))) + 'value) diff --git a/Task/Sort-an-array-of-composite-structures/ALGOL-68/sort-an-array-of-composite-structures.alg b/Task/Sort-an-array-of-composite-structures/ALGOL-68/sort-an-array-of-composite-structures.alg new file mode 100644 index 0000000000..5e9b674d18 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/ALGOL-68/sort-an-array-of-composite-structures.alg @@ -0,0 +1,9 @@ +MODE SORTSTRUCT = PERSON; +OP < = (PERSON a,b)BOOL: age OF a < age OF b; +PR READ "prelude/sort.a68" PR; + +MODE PERSON = STRUCT (STRING name, INT age); +FORMAT person repr = $"Name: "g", Age: "g(0)l$; + +[]SORTSTRUCT person = (("joe", 120), ("foo", 31), ("bar", 51)); +printf((person repr, shell sort(person), $l$)) diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada new file mode 100644 index 0000000000..d6cfc6e0b8 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada @@ -0,0 +1,41 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +with Ada.Containers.Generic_Array_Sort; + +procedure Demo_Array_Sort is + + function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + + type A_Composite is + record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + function "<" (L, R : A_Composite) return Boolean is + begin + return L.Name < R.Name; + end "<"; + + procedure Put_Line (C : A_Composite) is + begin + Put_Line (To_String (C.Name) & " " & To_String (C.Value)); + end Put_Line; + + type An_Array is array (Natural range <>) of A_Composite; + + procedure Sort is new Ada.Containers.Generic_Array_Sort (Natural, A_Composite, An_Array); + + Data : An_Array := (1 => (Name => +"Joe", Value => +"5531"), + 2 => (Name => +"Adam", Value => +"2341"), + 3 => (Name => +"Bernie", Value => +"122"), + 4 => (Name => +"Walter", Value => +"1234"), + 5 => (Name => +"David", Value => +"19")); + +begin + Sort (Data); + for I in Data'Range loop + Put_Line (Data (I)); + end loop; +end Demo_Array_Sort; diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada new file mode 100644 index 0000000000..a00776cd45 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada @@ -0,0 +1,42 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +with Ada.Containers.Ordered_Sets; + +procedure Sort_Composites is + + function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + + type A_Composite is + record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + function "<" (L, R : A_Composite) return Boolean is + begin + return L.Name < R.Name; + end "<"; + + procedure Put_Line (C : A_Composite) is + begin + Put_Line (To_String (C.Name) & " " & To_String (C.Value)); + end Put_Line; + + package Composite_Sets is new Ada.Containers.Ordered_Sets (A_Composite); + + procedure Put_Line (C : Composite_Sets.Cursor) is + begin + Put_Line (Composite_Sets.Element (C)); + end Put_Line; + + Data : Composite_Sets.Set; + +begin + Data.Insert (New_Item => (Name => +"Joe", Value => +"5531")); + Data.Insert (New_Item => (Name => +"Adam", Value => +"2341")); + Data.Insert (New_Item => (Name => +"Bernie", Value => +"122")); + Data.Insert (New_Item => (Name => +"Walter", Value => +"1234")); + Data.Insert (New_Item => (Name => +"David", Value => +"19")); + Data.Iterate (Put_Line'Access); +end Sort_Composites; diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada new file mode 100644 index 0000000000..52e1a81aac --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada @@ -0,0 +1,54 @@ +with Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + +procedure Sort_Composite is + type Composite_Record is record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + type Pairs_Array is array(Positive range <>) of Composite_Record; + + procedure Swap(Left, Right : in out Composite_Record) is + Temp : Composite_Record := Left; + begin + Left := Right; + Right := Temp; + end Swap; + + -- Sort_Names uses a bubble sort + + procedure Sort_Name(Pairs : in out Pairs_Array) is + Swap_Performed : Boolean := True; + begin + while Swap_Performed loop + Swap_Performed := False; + for I in Pairs'First..(Pairs'Last - 1) loop + if Pairs(I).Name > Pairs(I + 1).Name then + Swap (Pairs(I), Pairs(I + 1)); + Swap_Performed := True; + end if; + end loop; + end loop; + end Sort_Name; + + procedure Print(Item : Pairs_Array) is + begin + for I in Item'range loop + Ada.Text_Io.Put_Line(To_String(Item(I).Name) & ", " & + to_String(Item(I).Value)); + end loop; + end Print; + type Names is (Fred, Barney, Wilma, Betty, Pebbles); + type Values is (Home, Work, Cook, Eat, Bowl); + My_Pairs : Pairs_Array(1..5); +begin + for I in My_Pairs'range loop + My_Pairs(I).Name := To_Unbounded_String(Names'Image(Names'Val(Integer(I - 1)))); + My_Pairs(I).Value := To_Unbounded_String(Values'Image(Values'Val(Integer(I - 1)))); + end loop; + Print(My_Pairs); + Ada.Text_Io.Put_Line("========================="); + Sort_Name(My_Pairs); + Print(My_Pairs); +end Sort_Composite; diff --git a/Task/Sort-an-array-of-composite-structures/AutoHotkey/sort-an-array-of-composite-structures.ahk b/Task/Sort-an-array-of-composite-structures/AutoHotkey/sort-an-array-of-composite-structures.ahk new file mode 100644 index 0000000000..757bee389b --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/AutoHotkey/sort-an-array-of-composite-structures.ahk @@ -0,0 +1,24 @@ +start: +Gui, Add, ListView, r20 w200, 1|2 +data = +( +foo,53 +joe,34 +bar,23 +) + +Loop, parse, data, `n +{ + stringsplit, row, A_LoopField, `, + LV_Add(row, row1, row2) +} +LV_ModifyCol() ; Auto-size columns +Gui, Show +msgbox, sorting by column1 +LV_ModifyCol(1, "sort") ; sort by first column +msgbox, sorting by column2 +LV_ModifyCol(2, "sort Integer") ; sort by second column numerically +return + +GuiClose: +ExitApp diff --git a/Task/Sort-an-array-of-composite-structures/BBC-BASIC/sort-an-array-of-composite-structures.bbc b/Task/Sort-an-array-of-composite-structures/BBC-BASIC/sort-an-array-of-composite-structures.bbc new file mode 100644 index 0000000000..b439ae9a12 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/BBC-BASIC/sort-an-array-of-composite-structures.bbc @@ -0,0 +1,19 @@ + INSTALL @lib$+"SORTSALIB" + sort% = FN_sortSAinit(0,0) + + DIM pair{name$, number%} + DIM array{(10)} = pair{} + FOR i% = 1 TO DIM(array{()}, 1) + READ array{(i%)}.name$, array{(i%)}.number% + NEXT + + DATA "Eight", 8, "Two", 2, "Five", 5, "Nine", 9, "One", 1 + DATA "Three", 3, "Six", 6, "Seven", 7, "Four", 4, "Ten", 10 + + C% = DIM(array{()}, 1) + D% = 1 + CALL sort%, array{()}, array{(0)}.number%, array{(0)}.name$ + + FOR i% = 1 TO DIM(array{()}, 1) + PRINT array{(i%)}.name$, array{(i%)}.number% + NEXT diff --git a/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp b/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp new file mode 100644 index 0000000000..ab8b1867f7 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp @@ -0,0 +1,56 @@ +#include <iterator> +#include <algorithm> +#include <iostream> + +template<typename Struct, typename MemberType> class less_member +{ +public: + less_member(MemberType Struct::*m): + member(m) + { + } + bool operator()(Struct const& s1, Struct const& s2) const + { + return s1.*member < s2.*member; + } +private: + MemberType Struct::*const member; +}; + +template<typename Struct, typename MemberType> + less_member<Struct, MemberType> make_less_member(MemberType Struct::* m) +{ + return m; +} + +template<typename FwdIter, typename MemberPtrType> + void sort_for_member(FwdIter first, FwdIter last, MemberPtrType m) +{ + std::sort(first, last, make_less_member(m)); +} + +struct entry +{ + std::string name; + std::string value; +}; + +int main() +{ + entry array[] = { { "grass", "green" }, + { "snow", "white" }, + { "sky", "blue" }, + { "cherry", "red" } }; + std::cout << "before sorting:\n\n"; + for (int i = 0; i < 4; ++i) + std::cout << "index: " << i << ", name: " << array[i].name + << ", value: " << array[i].value << "\n"; + + sort_for_member(array, array+4, &entry::name); + + std::cout << "\nafter sorting:\n\n"; + for (int i = 0; i < 4; ++i) + std::cout << "index: " << i << ", name: " << array[i].name + << ", value: " << array[i].value << "\n"; + return 0; +} diff --git a/Task/Sort-an-array-of-composite-structures/C/sort-an-array-of-composite-structures.c b/Task/Sort-an-array-of-composite-structures/C/sort-an-array-of-composite-structures.c new file mode 100644 index 0000000000..5d52d8ad08 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/C/sort-an-array-of-composite-structures.c @@ -0,0 +1,97 @@ +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> + +typedef struct twoStringsStruct { + char * key, *value; +} sTwoStrings; + +int ord( char v ) +{ + static char *dgts = "012345679"; + char *cp; + for (cp=dgts; v != *cp; cp++); + return (cp-dgts); +} + +int cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2) +{ + char *p1 = s1->key; + char *p2 = s2->key; + char *mrk1, *mrk2; + while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;} + if (isdigit(*p1) && isdigit(*p2)) { + long v1, v2; + if ((*p1 == '0') ||(*p2 == '0')) { + while (p1 > s1->key) { + p1--; p2--; + if (*p1 != '0') break; + } + if (!isdigit(*p1)) { + p1++; p2++; + } + } + mrk1 = p1; mrk2 = p2; + v1 = 0; + while(isdigit(*p1)) { + v1 = 10*v1+ord(*p1); + p1++; + } + v2 = 0; + while(isdigit(*p2)) { + v2 = 10*v2+ord(*p2); + p2++; + } + if (v1 == v2) + return(p2-mrk2)-(p1-mrk1); + return v1 - v2; + } + if (tolower(*p1) != tolower(*p2)) + return (tolower(*p1) - tolower(*p2)); + for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++); + return (*p1 -*p2); +} + +int maxstrlen( char *a, char *b) +{ + int la = strlen(a); + int lb = strlen(b); + return (la>lb)? la : lb; +} + +int main() +{ + sTwoStrings toBsorted[] = { + { "Beta11a", "many" }, + { "alpha1", "This" }, + { "Betamax", "sorted." }, + { "beta3", "order" }, + { "beta11a", "strings" }, + { "beta001", "is" }, + { "beta11", "which" }, + { "beta041", "be" }, + { "beta05", "in" }, + { "beta1", "the" }, + { "beta40", "should" }, + }; +#define ASIZE (sizeof(toBsorted)/sizeof(sTwoStrings)) + int k, maxlens[ASIZE]; + char format[12]; + sTwoStrings *cp; + + qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs); + + for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) { + maxlens[k] = maxstrlen(cp->key, cp->value); + sprintf(format," %%-%ds", maxlens[k]); + printf(format, toBsorted[k].value); + } + printf("\n"); + for (k=0; k < ASIZE; k++) { + sprintf(format," %%-%ds", maxlens[k]); + printf(format, toBsorted[k].key); + } + printf("\n"); + + return 0; +} diff --git a/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-1.clj b/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-1.clj new file mode 100644 index 0000000000..d19d2fe449 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-1.clj @@ -0,0 +1,7 @@ +;; Gathered with Google Squared +(def *langs* [["Clojure" 2007] ["Common Lisp" 1984] ["Java" 1995] ["Haskell" 1990] + ["Lisp" 1958] ["Scheme" 1975]]) + +user> (sort-by second *langs*) ; using a keyfn + +(["Lisp" 1958] ["Scheme" 1975] ["Common Lisp" 1984] ["Haskell" 1990] ["Java" 1995] ["Clojure" 2007]) diff --git a/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-2.clj b/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-2.clj new file mode 100644 index 0000000000..3b27b842f1 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Clojure/sort-an-array-of-composite-structures-2.clj @@ -0,0 +1,7 @@ +user> (sort #(compare (second %1) (second %2)) *langs*) ; using a comparator + +(["Lisp" 1958] ["Scheme" 1975] ["Common Lisp" 1984] ["Haskell" 1990] ["Java" 1995] ["Clojure" 2007]) + +user> (sort-by second > *langs*) ; using a keyfn and a comparator + +(["Clojure" 2007] ["Java" 1995] ["Haskell" 1990] ["Common Lisp" 1984] ["Scheme" 1975] ["Lisp" 1958]) diff --git a/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-1.lisp b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-1.lisp new file mode 100644 index 0000000000..00fce0b75d --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-1.lisp @@ -0,0 +1,2 @@ +CL-USER> (defparameter *test-scores* '(("texas" 68.9) ("ohio" 87.8) ("california" 76.2) ("new york" 88.2)) ) +*TEST-SCORES* diff --git a/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-2.lisp b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-2.lisp new file mode 100644 index 0000000000..d59c296c39 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-2.lisp @@ -0,0 +1,2 @@ +CL-USER> (sort (copy-list *test-scores*) #'string-lessp :key #'first) +(("california" 76.2) ("new york" 88.2) ("ohio" 87.8) ("texas" 68.9)) diff --git a/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-3.lisp b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-3.lisp new file mode 100644 index 0000000000..4e643fa017 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Common-Lisp/sort-an-array-of-composite-structures-3.lisp @@ -0,0 +1,2 @@ +CL-USER> (sort (copy-list *test-scores*) #'< :key #'second) +(("texas" 68.9) ("california" 76.2) ("ohio" 87.8) ("new york" 88.2)) diff --git a/Task/Sort-an-array-of-composite-structures/D/sort-an-array-of-composite-structures.d b/Task/Sort-an-array-of-composite-structures/D/sort-an-array-of-composite-structures.d new file mode 100644 index 0000000000..90c1ff6437 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/D/sort-an-array-of-composite-structures.d @@ -0,0 +1,13 @@ +import std.stdio, std.algorithm; + +struct Pair { string name, value; } + +void main() { + Pair[] pairs = [{"Joe", "5531"}, + {"Adam", "2341"}, + {"Bernie", "122"}, + {"Walter", "1234"}, + {"David", "19"}]; + + pairs.schwartzSort!q{ a.name }.writeln; +} diff --git a/Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.delphi b/Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.delphi new file mode 100644 index 0000000000..e481ed117b --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.delphi @@ -0,0 +1,33 @@ +program SortCompositeStructures; + +{$APPTYPE CONSOLE} + +uses SysUtils, Generics.Collections, Generics.Defaults; + +type + TStructurePair = record + name: string; + value: string; + constructor Create(const aName, aValue: string); + end; + +constructor TStructurePair.Create(const aName, aValue: string); +begin + name := aName; + value := aValue; +end; + +var + lArray: array of TStructurePair; +begin + SetLength(lArray, 3); + lArray[0] := TStructurePair.Create('dog', 'rex'); + lArray[1] := TStructurePair.Create('cat', 'simba'); + lArray[2] := TStructurePair.Create('horse', 'trigger'); + + TArray.Sort<TStructurePair>(lArray , TDelegatedComparer<TStructurePair>.Construct( + function(const Left, Right: TStructurePair): Integer + begin + Result := CompareText(Left.Name, Right.Name); + end)); +end. diff --git a/Task/Sort-an-array-of-composite-structures/E/sort-an-array-of-composite-structures.e b/Task/Sort-an-array-of-composite-structures/E/sort-an-array-of-composite-structures.e new file mode 100644 index 0000000000..50ff9e3da8 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/E/sort-an-array-of-composite-structures.e @@ -0,0 +1,14 @@ +def compareBy(keyfn) { # This ought to be in the standard library + return def comparer(a, b) { + return keyfn(a).op__cmp(keyfn(b)) + } +} + +def x := [ + ["Joe",3], + ["Bill",4], + ["Alice",20], + ["Harry",3], +] + +println(x.sort(compareBy(fn [name,_] { name }))) diff --git a/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-1.erl b/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-1.erl new file mode 100644 index 0000000000..3b15cbcf40 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-1.erl @@ -0,0 +1,20 @@ +1> lists:sort([{{2006,2007},"Ducks"}, + {{2000,2001},"Avalanche"}, + {{2002,2003},"Devils"}, + {{2001,2002},"Red Wings"}, + {{2003,2004},"Lightning"}, + {{2004,2005},"N/A: lockout"}, + {{2005,2006},"Hurricanes"}, + {{1999,2000},"Devils"}, + {{2007,2008},"Red Wings"}, + {{2008,2009},"Penguins"}]). +[{{1999,2000},"Devils"}, + {{2000,2001},"Avalanche"}, + {{2001,2002},"Red Wings"}, + {{2002,2003},"Devils"}, + {{2003,2004},"Lightning"}, + {{2004,2005},"N/A: lockout"}, + {{2005,2006},"Hurricanes"}, + {{2006,2007},"Ducks"}, + {{2007,2008},"Red Wings"}, + {{2008,2009},"Penguins"}] diff --git a/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-2.erl b/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-2.erl new file mode 100644 index 0000000000..c64c23ba21 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Erlang/sort-an-array-of-composite-structures-2.erl @@ -0,0 +1,22 @@ +2> F = fun({_,X},{_,Y}) -> X < Y end. +#Fun<erl_eval.12.113037538> +3> lists:usort(F, [{{2006,2007},"Ducks"}, + {{2000,2001},"Avalanche"}, + {{2002,2003},"Devils"}, + {{2001,2002},"Red Wings"}, + {{2003,2004},"Lightning"}, + {{2004,2005},"N/A: lockout"}, + {{2005,2006},"Hurricanes"}, + {{1999,2000},"Devils"}, + {{2007,2008},"Red Wings"}, + {{2008,2009},"Penguins"}]). +[{{2000,2001},"Avalanche"}, + {{1999,2000},"Devils"}, + {{2002,2003},"Devils"}, + {{2006,2007},"Ducks"}, + {{2005,2006},"Hurricanes"}, + {{2003,2004},"Lightning"}, + {{2004,2005},"N/A: lockout"}, + {{2008,2009},"Penguins"}, + {{2007,2008},"Red Wings"}, + {{2001,2002},"Red Wings"}] diff --git a/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.euphoria b/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.euphoria new file mode 100644 index 0000000000..c8fa245a6f --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.euphoria @@ -0,0 +1,15 @@ +include sort.e +include misc.e + +constant NAME = 1 +function compare_names(sequence a, sequence b) + return compare(a[NAME],b[NAME]) +end function + +sequence s +s = { { "grass", "green" }, + { "snow", "white" }, + { "sky", "blue" }, + { "cherry", "red" } } + +pretty_print(1,custom_sort(routine_id("compare_names"),s),{2}) diff --git a/Task/Sort-an-array-of-composite-structures/Factor/sort-an-array-of-composite-structures.factor b/Task/Sort-an-array-of-composite-structures/Factor/sort-an-array-of-composite-structures.factor new file mode 100644 index 0000000000..cdbc35910a --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Factor/sort-an-array-of-composite-structures.factor @@ -0,0 +1,3 @@ +TUPLE: example-pair name value ; + +: sort-by-name ( seq -- seq' ) [ [ name>> ] compare ] sort ; diff --git a/Task/Sort-an-array-of-composite-structures/Fantom/sort-an-array-of-composite-structures.fantom b/Task/Sort-an-array-of-composite-structures/Fantom/sort-an-array-of-composite-structures.fantom new file mode 100644 index 0000000000..e5a28cc97e --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Fantom/sort-an-array-of-composite-structures.fantom @@ -0,0 +1,32 @@ +class Pair // create a composite structure +{ + Str name + Str value + new make (Str name, Str value) + { + this.name = name + this.value = value + } + + override Str toStr () + { + "(Pair: $name, $value)" + } +} + +class Main +{ + public static Void main () + { + // samples + pairs := [Pair("Fantom", "OO"), Pair("Clojure", "Functional"), Pair("Java", "OO") ] + + sorted := pairs.dup // make a copy of original list + sorted.sort |Pair a, Pair b -> Int| // sort using custom comparator + { + a.name <=> b.name + } + echo ("Started with : " + pairs.join(" ")) + echo ("Finished with: " + sorted.join(" ")) + } +} diff --git a/Task/Sort-an-array-of-composite-structures/Fortran/sort-an-array-of-composite-structures.f b/Task/Sort-an-array-of-composite-structures/Fortran/sort-an-array-of-composite-structures.f new file mode 100644 index 0000000000..d169077ff4 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Fortran/sort-an-array-of-composite-structures.f @@ -0,0 +1,35 @@ +PROGRAM EXAMPLE + IMPLICIT NONE + + TYPE Pair + CHARACTER(6) :: name + CHARACTER(1) :: value + END TYPE Pair + + TYPE(Pair) :: rcc(10), temp + INTEGER :: i, j + + rcc(1) = Pair("Black", "0") + rcc(2) = Pair("Brown", "1") + rcc(3) = Pair("Red", "2") + rcc(4) = Pair("Orange", "3") + rcc(5) = Pair("Yellow", "4") + rcc(6) = Pair("Green", "5") + rcc(7) = Pair("Blue", "6") + rcc(8) = Pair("Violet", "7") + rcc(9) = Pair("Grey", "8") + rcc(10) = Pair("White", "9") + + DO i = 2, SIZE(rcc) + j = i - 1 + temp = rcc(i) + DO WHILE (j>=1 .AND. LGT(rcc(j)%name, temp%name)) + rcc(j+1) = rcc(j) + j = j - 1 + END DO + rcc(j+1) = temp + END DO + + WRITE (*,"(2A6)") rcc + +END PROGRAM EXAMPLE diff --git a/Task/Sort-an-array-of-composite-structures/Go/sort-an-array-of-composite-structures.go b/Task/Sort-an-array-of-composite-structures/Go/sort-an-array-of-composite-structures.go new file mode 100644 index 0000000000..17c7304536 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Go/sort-an-array-of-composite-structures.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "sort" +) + +type pair struct { + name, value string +} +type csArray []pair + +// three methods satisfy sort.Interface +func (a csArray) Less(i, j int) bool { return a[i].name < a[j].name } +func (a csArray) Len() int { return len(a) } +func (a csArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] } + +var x = csArray{ + pair{"joe", "120"}, + pair{"foo", "31"}, + pair{"bar", "251"}, +} + +func main() { + sort.Sort(x) + for _, p := range x { + fmt.Printf("%5s: %s\n", p.name, p.value) + } +} diff --git a/Task/Sort-an-array-of-composite-structures/Groovy/sort-an-array-of-composite-structures.groovy b/Task/Sort-an-array-of-composite-structures/Groovy/sort-an-array-of-composite-structures.groovy new file mode 100644 index 0000000000..7b0806811e --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Groovy/sort-an-array-of-composite-structures.groovy @@ -0,0 +1,25 @@ +class Holiday { + def date + def name + Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) } + String toString() { "${format.format date}: ${name}" } + static format = new java.text.SimpleDateFormat("yyyy-MM-dd") +} + +def holidays = [ new Holiday("2009-12-25", "Christmas Day"), + new Holiday("2009-04-22", "Earth Day"), + new Holiday("2009-09-07", "Labor Day"), + new Holiday("2009-07-04", "Independence Day"), + new Holiday("2009-10-31", "Halloween"), + new Holiday("2009-05-25", "Memorial Day"), + new Holiday("2009-03-14", "PI Day"), + new Holiday("2009-01-01", "New Year's Day"), + new Holiday("2009-12-31", "New Year's Eve"), + new Holiday("2009-11-26", "Thanksgiving"), + new Holiday("2009-02-14", "St. Valentine's Day"), + new Holiday("2009-03-17", "St. Patrick's Day"), + new Holiday("2009-01-19", "Martin Luther King Day"), + new Holiday("2009-02-16", "President's Day") ] + +holidays.sort { x, y -> x.date <=> y.date } +holidays.each { println it } diff --git a/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs new file mode 100644 index 0000000000..f5ff099847 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Haskell/sort-an-array-of-composite-structures.hs @@ -0,0 +1,11 @@ +import List + +data Person = P String Int deriving Eq +instance Show Person where + show (P name val) = "Person "++name++" with value "++(show val) +instance Ord Person where + compare (P n1 _) (P n2 _) = compare n1 n2 + +people = [(P "Joe" 12), (P "Bob" 8), (P "Alice" 9), (P "Harry" 2)] +sortedPeople = sort people +sortedPeopleByVal = sortBy (\(P _ v1) (P _ v2)->compare v1 v2) people diff --git a/Task/Sort-an-array-of-composite-structures/Icon/sort-an-array-of-composite-structures.icon b/Task/Sort-an-array-of-composite-structures/Icon/sort-an-array-of-composite-structures.icon new file mode 100644 index 0000000000..d491fafbab --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Icon/sort-an-array-of-composite-structures.icon @@ -0,0 +1,12 @@ +record star(name,HIP) + +procedure main() + +Ori := [ star("Betelgeuse",27989), + star("Rigel",24436), + star("Belatrix", 25336), + star("Alnilam",26311) ] + +write("Some Orion stars by HIP#") +every write( (x := !sortf(Ori,2)).name, " HIP ",x.HIP) +end diff --git a/Task/Sort-an-array-of-composite-structures/J/sort-an-array-of-composite-structures.j b/Task/Sort-an-array-of-composite-structures/J/sort-an-array-of-composite-structures.j new file mode 100644 index 0000000000..f79ea7fa76 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/J/sort-an-array-of-composite-structures.j @@ -0,0 +1,17 @@ + names =: ;: 'Perlis Wilkes Hamming Minsky Wilkinson McCarthy' + values=: ;: 'Alan Maurice Richard Marvin James John' + pairs =: values ,. names + pairs /: names ++-------+---------+ +|Richard|Hamming | ++-------+---------+ +|John |McCarthy | ++-------+---------+ +|Marvin |Minsky | ++-------+---------+ +|Alan |Perlis | ++-------+---------+ +|Maurice|Wilkes | ++-------+---------+ +|James |Wilkinson| ++-------+---------+ diff --git a/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures.java b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures.java new file mode 100644 index 0000000000..515919cb27 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures.java @@ -0,0 +1,34 @@ +import java.util.Arrays; +import java.util.Comparator; + +public class SortComp { + public static class Pair { + public String name; + public String value; + public Pair(String n, String v) { + name = n; + value = v; + } + } + + public static void main(String[] args) { + Pair[] pairs = {new Pair("06-07", "Ducks"), new Pair("00-01", "Avalanche"), + new Pair("02-03", "Devils"), new Pair("01-02", "Red Wings"), + new Pair("03-04", "Lightning"), new Pair("04-05", "lockout"), + new Pair("05-06", "Hurricanes"), new Pair("99-00", "Devils"), + new Pair("07-08", "Red Wings"), new Pair("08-09", "Penguins")}; + + sortByName(pairs); + for (Pair p : pairs) { + System.out.println(p.name + " " + p.value); + } + } + + public static void sortByName(Pair[] pairs) { + Arrays.sort(pairs, new Comparator<Pair>() { + public int compare(Pair p1, Pair p2) { + return p1.name.compareTo(p2.name); + } + }); + } +} diff --git a/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures.js b/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures.js new file mode 100644 index 0000000000..875ab0bf04 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/JavaScript/sort-an-array-of-composite-structures.js @@ -0,0 +1,8 @@ +var arr = [ + {id: 3, value: "foo"}, + {id: 2, value: "bar"}, + {id: 4, value: "baz"}, + {id: 1, value: 42}, + {id: 5, something: "another string"} // Works with any object declaring 'id' as a number. +]; +arr = arr.sort(function(a, b) {return a.id - b.id}); // Sort with comparator checking the id. diff --git a/Task/Sort-an-array-of-composite-structures/Liberty-BASIC/sort-an-array-of-composite-structures.liberty b/Task/Sort-an-array-of-composite-structures/Liberty-BASIC/sort-an-array-of-composite-structures.liberty new file mode 100644 index 0000000000..3e8f077015 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Liberty-BASIC/sort-an-array-of-composite-structures.liberty @@ -0,0 +1,18 @@ +N =20 +dim IntArray$( N, 2) + +print "Original order" +for i =1 to N + name$ =mid$( "SortArrayOfCompositeStructures", int( 25 *rnd( 1)), 1 +int( 4 *rnd( 1))) + IntArray$( i, 1) =name$ + print name$, + t$ =str$( int( 1000 *rnd( 1))) + IntArray$( i, 2) =t$ + print t$ +next i + +sort IntArray$(), 1, N, 1 +print "Sorted by name" ' ( we specified column 1) +for i =1 to N + print IntArray$( i, 1), IntArray$( i, 2) +next i diff --git a/Task/Sort-an-array-of-composite-structures/Lua/sort-an-array-of-composite-structures.lua b/Task/Sort-an-array-of-composite-structures/Lua/sort-an-array-of-composite-structures.lua new file mode 100644 index 0000000000..01fe5682ea --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Lua/sort-an-array-of-composite-structures.lua @@ -0,0 +1,10 @@ +function sorting( a, b ) + return a[1] < b[1] +end + +tab = { {"C++", 1979}, {"Ada", 1983}, {"Ruby", 1995}, {"Eiffel", 1985} } + +table.sort( tab, sorting ) +for _, v in ipairs( tab ) do + print( unpack(v) ) +end diff --git a/Task/Sort-an-array-of-composite-structures/MAXScript/sort-an-array-of-composite-structures.maxscript b/Task/Sort-an-array-of-composite-structures/MAXScript/sort-an-array-of-composite-structures.maxscript new file mode 100644 index 0000000000..19d0d677b7 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/MAXScript/sort-an-array-of-composite-structures.maxscript @@ -0,0 +1,13 @@ +fn keyCmp comp1 comp2 = +( + case of + ( + (comp1[1] > comp2[1]): 1 + (comp1[1] < comp2[1]): -1 + default: 0 + ) +) + +people = #(#("joe", 39), #("dave", 37), #("bob", 42)) +qsort people keyCmp +print people diff --git a/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-1.math b/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-1.math new file mode 100644 index 0000000000..a6fab2c098 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-1.math @@ -0,0 +1,13 @@ +events = {{"2009-12-25", "Christmas Day"}, {"2009-04-22", + "Earth Day"}, {"2009-09-07", "Labor Day"}, {"2009-07-04", + "Independence Day"}, {"2009-10-31", "Halloween"}, {"2009-05-25", + "Memorial Day"}, {"2009-03-14", "PI Day"}, {"2009-01-01", + "New Year's Day"}, {"2009-12-31", + "New Year's Eve"}, {"2009-11-26", "Thanksgiving"}, {"2009-02-14", + "St. Valentine's Day"}, {"2009-03-17", + "St. Patrick's Day"}, {"2009-01-19", + "Martin Luther King Day"}, {"2009-02-16", "President's Day"}}; +date = 1; +name = 2; +SortBy[events, #[[name]] &] // Grid +SortBy[events, #[[date]] &] // Grid diff --git a/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-2.math b/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-2.math new file mode 100644 index 0000000000..b9d5acdb57 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Mathematica/sort-an-array-of-composite-structures-2.math @@ -0,0 +1,30 @@ +2009-12-25 Christmas Day +2009-04-22 Earth Day +2009-10-31 Halloween +2009-07-04 Independence Day +2009-09-07 Labor Day +2009-01-19 Martin Luther King Day +2009-05-25 Memorial Day +2009-01-01 New Year's Day +2009-12-31 New Year's Eve +2009-03-14 PI Day +2009-02-16 President's Day +2009-03-17 St. Patrick's Day +2009-02-14 St. Valentine's Day +2009-11-26 Thanksgiving + + +2009-01-01 New Year's Day +2009-01-19 Martin Luther King Day +2009-02-14 St. Valentine's Day +2009-02-16 President's Day +2009-03-14 PI Day +2009-03-17 St. Patrick's Day +2009-04-22 Earth Day +2009-05-25 Memorial Day +2009-07-04 Independence Day +2009-09-07 Labor Day +2009-10-31 Halloween +2009-11-26 Thanksgiving +2009-12-25 Christmas Day +2009-12-31 New Year's Eve diff --git a/Task/Sort-an-array-of-composite-structures/NetRexx/sort-an-array-of-composite-structures.netrexx b/Task/Sort-an-array-of-composite-structures/NetRexx/sort-an-array-of-composite-structures.netrexx new file mode 100644 index 0000000000..f3fcc80260 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/NetRexx/sort-an-array-of-composite-structures.netrexx @@ -0,0 +1,54 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +-- ============================================================================= +class RSortCompsiteStructure public + + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[]) public static + places = [ - + PairBean('London', 'UK'), PairBean('New York', 'US') - + , PairBean('Boston', 'US'), PairBean('Washington', 'US') - + , PairBean('Washington', 'UK'), PairBean("Birmingham", 'US') - + , PairBean("Birmingham", 'UK'), PairBean("Boston", 'UK') - + ] + say displayArray(places) + Arrays.sort(places, PairComparator()) + say displayArray(places) + return + + method displayArray(harry = PairBean[]) constant + disp = '' + loop elmt over harry + disp = disp','elmt + end elmt + return '['disp.substr(2)']' -- trim leading comma + +-- ============================================================================= +class RSortCompsiteStructure.PairBean + properties indirect + name + value + method PairBean(name_, value_) public + setName(name_) + setValue(value_) + return + method toString() public returns String + return '('getName()','getValue()')' + +-- ============================================================================= +class RSortCompsiteStructure.PairComparator implements Comparator + method compare(lft = Object, rgt = Object) public binary returns int + cRes = int + if lft <= RSortCompsiteStructure.PairBean, rgt <= RSortCompsiteStructure.PairBean then do + lName = String (RSortCompsiteStructure.PairBean lft).getName() + rName = String (RSortCompsiteStructure.PairBean rgt).getName() + cRes = lName.compareTo(rName) + if cRes == 0 then do + lVal = String (RSortCompsiteStructure.PairBean lft).getValue() + rVal = String (RSortCompsiteStructure.PairBean rgt).getValue() + cRes = lVal.compareTo(rVal) + end + end + else signal IllegalArgumentException('Arguments must be of type PairBean') + return cRes diff --git a/Task/Sort-an-array-of-composite-structures/OCaml/sort-an-array-of-composite-structures.ocaml b/Task/Sort-an-array-of-composite-structures/OCaml/sort-an-array-of-composite-structures.ocaml new file mode 100644 index 0000000000..05504882da --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/OCaml/sort-an-array-of-composite-structures.ocaml @@ -0,0 +1,6 @@ +# let people = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)];; +val people : (string * int) list = + [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)] +# let sortedPeopleByVal = List.sort (fun (_, v1) (_, v2) -> compare v1 v2) people;; +val sortedPeopleByVal : (string * int) list = + [("Harry", 2); ("Bob", 8); ("Alice", 9); ("Joe", 12)] diff --git a/Task/Sort-an-array-of-composite-structures/Objeck/sort-an-array-of-composite-structures.objeck b/Task/Sort-an-array-of-composite-structures/Objeck/sort-an-array-of-composite-structures.objeck new file mode 100644 index 0000000000..05df3e5453 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Objeck/sort-an-array-of-composite-structures.objeck @@ -0,0 +1,44 @@ +use Collection; + +class Entry implements Compare { + @name : String; + @value : Float; + + New(name : String, value : Float) { + @name := name; + @value := value; + } + + method : public : Compare(rhs : Compare) ~ Int { + return @name->Compare(rhs->As(Entry)->GetName()); + } + + method : public : GetName() ~ String { + return @name; + } + + method : public : HashID() ~ Int { + return @name->HashID(); + } + + method : public : ToString() ~ String { + return "name={$@name}, value={$@value}"; + } +} + +class Sorter { + function : Main(args : String[]) ~ Nil { + entries := CompareVector->New(); + entries->AddBack(Entry->New("Krypton", 83.798)); + entries->AddBack(Entry->New("Beryllium", 9.012182)); + entries->AddBack(Entry->New("Silicon", 28.0855)); + entries->AddBack(Entry->New("Cobalt", 58.933195)); + entries->AddBack(Entry->New("Selenium", 78.96)); + entries->AddBack(Entry->New("Germanium", 72.64)); + + entries->Sort(); + each(i : entries) { + entries->Get(i)->As(Entry)->ToString()->PrintLine(); + }; + } +} diff --git a/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m b/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m new file mode 100644 index 0000000000..30111a0286 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Objective-C/sort-an-array-of-composite-structures.m @@ -0,0 +1,64 @@ +@interface Pair : NSObject { + NSString *name; + NSString *value; +} ++(id)pairWithName:(NSString *)n value:(NSString *)v; +-(id)initWithName:(NSString *)n value:(NSString *)v; +-(NSString *)name; +-(NSString *)value; +@end + +@implementation Pair ++(id)pairWithName:(NSString *)n value:(NSString *)v { + return [[[self alloc] initWithName:n value:v] autorelease]; +} +-(id)initWithName:(NSString *)n value:(NSString *)v { + if ((self = [super init])) { + name = [n retain]; + value = [v retain]; + } + return self; +} +-(void)dealloc { + [name release]; + [value release]; + [super dealloc]; +} +-(NSString *)name { return name; } +-(NSString *)value { return value; } +-(NSString *)description { + return [NSString stringWithFormat:@"< %@ -> %@ >", name, value]; +} +@end + +int main() { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSArray *pairs = [NSArray arrayWithObjects: + [Pair pairWithName:@"06-07" value:@"Ducks"], + [Pair pairWithName:@"00-01" value:@"Avalanche"], + [Pair pairWithName:@"02-03" value:@"Devils"], + [Pair pairWithName:@"01-02" value:@"Red Wings"], + [Pair pairWithName:@"03-04" value:@"Lightning"], + [Pair pairWithName:@"04-05" value:@"lockout"], + [Pair pairWithName:@"05-06" value:@"Hurricanes"], + [Pair pairWithName:@"99-00" value:@"Devils"], + [Pair pairWithName:@"07-08" value:@"Red Wings"], + [Pair pairWithName:@"08-09" value:@"Penguins"], + nil]; + + // optional 3rd arg: you can also specify a selector to compare the keys + NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; + + // it takes an array of sort descriptors, and it will be ordered by the + // first one, then if it's a tie by the second one, etc. + NSArray *sorted = [pairs sortedArrayUsingDescriptors: + [NSArray arrayWithObject:sd]]; + NSLog(@"%@", sorted); + + [sd release]; + + [pool release]; + + return 0; +} diff --git a/Task/Sort-an-array-of-composite-structures/Oz/sort-an-array-of-composite-structures.oz b/Task/Sort-an-array-of-composite-structures/Oz/sort-an-array-of-composite-structures.oz new file mode 100644 index 0000000000..3f584611c3 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Oz/sort-an-array-of-composite-structures.oz @@ -0,0 +1,13 @@ +declare + People = [person(name:joe value:3) + person(name:bill value:4) + person(name:alice value:20) + person(name:harry value:3)] + + SortedPeople = {Sort People + fun {$ P1 P2} + P1.name < P2.name + end + } +in + {ForAll SortedPeople Show} diff --git a/Task/Sort-an-array-of-composite-structures/PARI-GP/sort-an-array-of-composite-structures.pari b/Task/Sort-an-array-of-composite-structures/PARI-GP/sort-an-array-of-composite-structures.pari new file mode 100644 index 0000000000..09f3b05090 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PARI-GP/sort-an-array-of-composite-structures.pari @@ -0,0 +1 @@ +vecsort([["name", "value"],["name2", "value2"]], 1, 2) diff --git a/Task/Sort-an-array-of-composite-structures/Perl-6/sort-an-array-of-composite-structures.pl6 b/Task/Sort-an-array-of-composite-structures/Perl-6/sort-an-array-of-composite-structures.pl6 new file mode 100644 index 0000000000..b5f06d289d --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Perl-6/sort-an-array-of-composite-structures.pl6 @@ -0,0 +1,19 @@ +my class Employee { + has Str $.name; + has Num $.wage; +} + +my $boss = Employee.new( name => "Frank Myers" , wage => 6755.85 ); +my $driver = Employee.new( name => "Aaron Fast" , wage => 2530.40 ); +my $worker = Employee.new( name => "John Dude" , wage => 2200.00 ); +my $salesman = Employee.new( name => "Frank Mileeater" , wage => 4590.12 ); + +my @team = $boss, $driver, $worker, $salesman; + +my @orderedByName = @team.sort( *.name )».name; +my @orderedByWage = @team.sort( *.wage )».name; + +say "Team ordered by name (ascending order):"; +say @orderedByName.join(' '); +say "Team ordered by wage (ascending order):"; +say @orderedByWage.join(' '); diff --git a/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-1.pl b/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-1.pl new file mode 100644 index 0000000000..99cdfdf224 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-1.pl @@ -0,0 +1,2 @@ +@people = (['joe', 120], ['foo', 31], ['bar', 51]); +@people = sort { $a->[0] cmp $b->[0] } @people; diff --git a/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-2.pl b/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-2.pl new file mode 100644 index 0000000000..1ab971ace9 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Perl/sort-an-array-of-composite-structures-2.pl @@ -0,0 +1,2 @@ +@people = (['joe', 120], ['foo', 31], ['bar', 51]); +@people = sort { $a->[1] <=> $b->[1] } @people; diff --git a/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-1.l b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-1.l new file mode 100644 index 0000000000..c80ca8915a --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-1.l @@ -0,0 +1,2 @@ +: (sort '(("def" 456) ("abc" 789) ("ghi" 123))) +-> (("abc" 789) ("def" 456) ("ghi" 123)) diff --git a/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-2.l b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-2.l new file mode 100644 index 0000000000..701ff2e1c4 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-2.l @@ -0,0 +1,2 @@ +: (by car sort '(("def" 456) ("abc" 789) ("ghi" 123))) +-> (("abc" 789) ("def" 456) ("ghi" 123)) diff --git a/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-3.l b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-3.l new file mode 100644 index 0000000000..3fd860026e --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PicoLisp/sort-an-array-of-composite-structures-3.l @@ -0,0 +1,2 @@ +: (by cadr sort '(("def" 456) ("abc" 789) ("ghi" 123))) +-> (("ghi" 123) ("def" 456) ("abc" 789)) diff --git a/Task/Sort-an-array-of-composite-structures/PureBasic/sort-an-array-of-composite-structures.purebasic b/Task/Sort-an-array-of-composite-structures/PureBasic/sort-an-array-of-composite-structures.purebasic new file mode 100644 index 0000000000..8d9548c51e --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PureBasic/sort-an-array-of-composite-structures.purebasic @@ -0,0 +1,33 @@ +Structure MyPair ; Define a structured data type + Name$ + Value.i +EndStructure + +Dim People.MyPair(2) ; Allocate some elements + +People(0)\Name$ = "John" ; Start filling them in +People(0)\Value = 100 + +People(1)\Name$ = "Emma" +People(1)\Value = 200 + +People(2)\Name$ = "Johnny" +People(2)\Value = 175 + +If OpenConsole() + Define i + ; Sort ascending by name + SortStructuredArray(People(), #PB_Sort_Ascending, OffsetOf(MyPair\Name$), #PB_Sort_String) + PrintN(#CRLF$+"Sorted ascending by name.") + For i=0 To 2 + PrintN(People(i)\Name$+" - Value: "+Str(People(i)\Value)) + Next + ; Sort descending by value + SortStructuredArray(People(), #PB_Sort_Descending, OffsetOf(MyPair\Value), #PB_Sort_Integer) + PrintN(#CRLF$+"Sorted descending by value.") + For i=0 To 2 + PrintN(People(i)\Name$+" - Value: "+Str(People(i)\Value)) + Next + ; Wait for user... + PrintN(#CRLF$+"Press ENTER to exit"):Input() +EndIf diff --git a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-1.py b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-1.py new file mode 100644 index 0000000000..397ebae5b9 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-1.py @@ -0,0 +1,2 @@ +people = [('joe', 120), ('foo', 31), ('bar', 51)] +sorted(people) diff --git a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-2.py b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-2.py new file mode 100644 index 0000000000..2e129bd3ce --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-2.py @@ -0,0 +1 @@ +[('bar', 51), ('foo', 31), ('joe', 120)] diff --git a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py new file mode 100644 index 0000000000..52985061da --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py @@ -0,0 +1,3 @@ +from operator import itemgetter +people = [(120, 'joe'), (31, 'foo'), (51, 'bar')] +people.sort(key=itemgetter(0)) diff --git a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-4.py b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-4.py new file mode 100644 index 0000000000..b8a9ca02e8 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-4.py @@ -0,0 +1 @@ +[(51, 'bar'), (31, 'foo'), (120, 'joe')] diff --git a/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-1.r b/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-1.r new file mode 100644 index 0000000000..e365439182 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-1.r @@ -0,0 +1,3 @@ +sortbyname <- function(x, ...) x[order(names(x), ...)] +x <- c(texas=68.9, ohio=87.8, california=76.2, "new york"=88.2) +sortbyname(x) diff --git a/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-2.r b/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-2.r new file mode 100644 index 0000000000..dcc174373b --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/R/sort-an-array-of-composite-structures-2.r @@ -0,0 +1 @@ +sortbyname(x, decreasing=TRUE) diff --git a/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb b/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb new file mode 100644 index 0000000000..4e8eb16efa --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb @@ -0,0 +1,6 @@ +Person = Struct.new(:name,:value) +list = [Person.new("Joe",3), + Person.new("Bill",4), + Person.new("Alice",20), + Person.new("Harry",3)] +list.sort_by{|x|x.name} diff --git a/Task/Sort-an-array-of-composite-structures/Run-BASIC/sort-an-array-of-composite-structures.run b/Task/Sort-an-array-of-composite-structures/Run-BASIC/sort-an-array-of-composite-structures.run new file mode 100644 index 0000000000..fd9147e122 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Run-BASIC/sort-an-array-of-composite-structures.run @@ -0,0 +1,17 @@ +sqliteconnect #mem, ":memory:" ' create in memory db +mem$ = "CREATE TABLE people(num integer, name text,city text)" +#mem execute(mem$) +data "1","George","Redding","2","Fred","Oregon","3","Ben","Seneca","4","Steve","Fargo","5","Frank","Houston" + +for i = 1 to 5 ' read data and place in memory DB + read num$ :read name$: read city$ + #mem execute("INSERT INTO people VALUES(";num$;",'";name$;"','";city$;"')") +next i +#mem execute("SELECT * FROM people ORDER BY name") 'sort by name order +WHILE #mem hasanswer() + #row = #mem #nextrow() + num = #row num() + name$ = #row name$() + city$ = #row city$() + print num;" ";name$;" ";city$ +WEND diff --git a/Task/Sort-an-array-of-composite-structures/Seed7/sort-an-array-of-composite-structures.seed7 b/Task/Sort-an-array-of-composite-structures/Seed7/sort-an-array-of-composite-structures.seed7 new file mode 100644 index 0000000000..5cfa4573c4 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Seed7/sort-an-array-of-composite-structures.seed7 @@ -0,0 +1,39 @@ +$ include "seed7_05.s7i"; + +const type: pair is new struct + var string: name is ""; + var string: value is ""; + end struct; + +const func integer: compare (in pair: pair1, in pair: pair2) is + return compare(pair1.name, pair2.name); + +const func string: str (in pair: aPair) is + return "(" <& aPair.name <& ", " <& aPair.value <& ")"; + +enable_output(pair); + +const func pair: pair (in string: name, in string: value) is func + result + var pair: newPair is pair.value; + begin + newPair.name := name; + newPair.value := value; + end func; + +var array pair: data is [] ( + pair("Joe", "5531"), + pair("Adam", "2341"), + pair("Bernie", "122"), + pair("Walter", "1234"), + pair("David", "19")); + +const proc: main is func + local + var pair: aPair is pair.value; + begin + data := sort(data); + for aPair range data do + writeln(aPair); + end for; + end func; diff --git a/Task/Sort-an-array-of-composite-structures/Tcl/sort-an-array-of-composite-structures.tcl b/Task/Sort-an-array-of-composite-structures/Tcl/sort-an-array-of-composite-structures.tcl new file mode 100644 index 0000000000..9d07af17df --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Tcl/sort-an-array-of-composite-structures.tcl @@ -0,0 +1,3 @@ +set people {{joe 120} {foo 31} {bar 51}} +# sort by the first element of each pair +lsort -index 0 $people diff --git a/Task/Sort-an-array-of-composite-structures/UNIX-Shell/sort-an-array-of-composite-structures.sh b/Task/Sort-an-array-of-composite-structures/UNIX-Shell/sort-an-array-of-composite-structures.sh new file mode 100644 index 0000000000..c9dbed8afb --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/UNIX-Shell/sort-an-array-of-composite-structures.sh @@ -0,0 +1,28 @@ +list="namez:order! +name space:in +name1:sort +name:Please" + +newline=" +" + +dumplist() { + ( + IFS=$newline + for pair in $list; do + ( + IFS=: + set -- $pair + echo " $1 => $2" + ) + done + ) +} + +echo "Original list:" +dumplist + +list=`IFS=$newline; printf %s "$list" | sort -t: -k1,1` + +echo "Sorted list:" +dumplist diff --git a/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-1.ursala b/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-1.ursala new file mode 100644 index 0000000000..2d9ad09618 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-1.ursala @@ -0,0 +1,9 @@ +#import std + +#cast %sWLW + +examples = + +( + -<&l <('z','a'),('x','c'),('y','b')>, # sorted by the left + -<&r <('z','a'),('x','c'),('y','b')>) # sorted by the right diff --git a/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-2.ursala b/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-2.ursala new file mode 100644 index 0000000000..4cf480cb72 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ursala/sort-an-array-of-composite-structures-2.ursala @@ -0,0 +1,14 @@ +#import std + +person :: name %s value %s + +people = + +< + person[name: 'Marilyn Monroe',value: 'priceless'], + person[name: 'Victor Hugo',value: 'millions'], + person[name: 'Johnny Carson',value: 'up there']> + +#cast _person%L + +example = (lleq+ ~name~~)-< people diff --git a/Task/Sort-an-array-of-composite-structures/XPL0/sort-an-array-of-composite-structures.xpl0 b/Task/Sort-an-array-of-composite-structures/XPL0/sort-an-array-of-composite-structures.xpl0 new file mode 100644 index 0000000000..15f753c375 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/XPL0/sort-an-array-of-composite-structures.xpl0 @@ -0,0 +1,32 @@ +include c:\cxpl\stdlib; +char Dict(10,10); +int Entries; + +proc BSort(A, N); \Bubble sort array A's key string into ascending order +char A; \address of array +int N; \number of items in array (size) +int B, I, J, T; +[B:= A; \B(I) accesses 32-bit pointers, not A(I) 8-bit bytes +for J:= N-1 downto 0 do + for I:= 0 to J-1 do + if StrCmp(A(I,1), A(I+1,1)) > 0 then + [T:= B(I); B(I):= B(I+1); B(I+1):= T]; \swap pointers +]; + +proc AddEntry(Letter, Greek); \Insert entry into associative array +char Letter, Greek; +[Dict(Entries,0):= Letter; +StrCopy(Greek, @Dict(Entries,1)); +Entries:= Entries+1; \(limit checks ignored for simplicity) +]; + +int I; +[Entries:= 0; +AddEntry(^A, "alpha"); \add items in arbitrary order +AddEntry(^D, "delta"); +AddEntry(^B, "beta"); +AddEntry(^C, "gamma"); +BSort(Dict, Entries); \sort entries by Greek name +for I:= 0 to Entries-1 do \show sorted entries + [ChOut(0, Dict(I,0)); ChOut(0, ^ ); Text(0, @Dict(I,1)); CrLf(0)]; +] diff --git a/Task/Sort-an-integer-array/0DESCRIPTION b/Task/Sort-an-integer-array/0DESCRIPTION new file mode 100644 index 0000000000..6bf7c7e9ce --- /dev/null +++ b/Task/Sort-an-integer-array/0DESCRIPTION @@ -0,0 +1 @@ +Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible. diff --git a/Task/Sort-an-integer-array/1META.yaml b/Task/Sort-an-integer-array/1META.yaml new file mode 100644 index 0000000000..556e45905d --- /dev/null +++ b/Task/Sort-an-integer-array/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting diff --git a/Task/Sort-an-integer-array/4D/sort-an-integer-array-1.4d b/Task/Sort-an-integer-array/4D/sort-an-integer-array-1.4d new file mode 100644 index 0000000000..81464b3c93 --- /dev/null +++ b/Task/Sort-an-integer-array/4D/sort-an-integer-array-1.4d @@ -0,0 +1,8 @@ +ARRAY INTEGER($nums;0) +APPEND TO ARRAY($nums;2) +APPEND TO ARRAY($nums;4) +APPEND TO ARRAY($nums;3) +APPEND TO ARRAY($nums;1) +APPEND TO ARRAY($nums;2) +SORT ARRAY($nums) ` sort in ascending order +SORT ARRAY($nums;<) ` sort in descending order diff --git a/Task/Sort-an-integer-array/4D/sort-an-integer-array-2.4d b/Task/Sort-an-integer-array/4D/sort-an-integer-array-2.4d new file mode 100644 index 0000000000..b4e40680ed --- /dev/null +++ b/Task/Sort-an-integer-array/4D/sort-an-integer-array-2.4d @@ -0,0 +1,8 @@ +TABLEAU ENTIER($nombres;0) +AJOUTER A TABLEAU($nombres;2) +AJOUTER A TABLEAU($nombres;4) +AJOUTER A TABLEAU($nombres;3) +AJOUTER A TABLEAU($nombres;1) +AJOUTER A TABLEAU($nombres;2) +TRIER TABLEAU($nombres) ` pour effectuer un tri par ordre croissant +TRIER TABLEAU($nombres;<) ` pour effectuer un tri par ordre décroissant diff --git a/Task/Sort-an-integer-array/ALGOL-68/sort-an-integer-array.alg b/Task/Sort-an-integer-array/ALGOL-68/sort-an-integer-array.alg new file mode 100644 index 0000000000..ad48fec5be --- /dev/null +++ b/Task/Sort-an-integer-array/ALGOL-68/sort-an-integer-array.alg @@ -0,0 +1,24 @@ +CO PR READ "shell_sort.a68" PR CO +MODE TYPE = INT; + +PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:( + INT inc := ( UPB seq + LWB seq + 1 ) OVER 2; + WHILE inc NE 0 DO + FOR index FROM LWB seq TO UPB seq DO + INT i := index; + TYPE el = seq[i]; + WHILE ( i - LWB seq >= inc | seq[i - inc] > el | FALSE ) DO + seq[i] := seq[i - inc]; + i -:= inc + OD; + seq[i] := el + OD; + inc := IF inc = 2 THEN 1 ELSE ENTIER(inc * 5 / 11) FI + OD; + seq +); + +PROC shell sort = ([]TYPE seq)[]TYPE: + in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq); + +print((shell sort((2, 4, 3, 1, 2)), new line)) diff --git a/Task/Sort-an-integer-array/APL/sort-an-integer-array.apl b/Task/Sort-an-integer-array/APL/sort-an-integer-array.apl new file mode 100644 index 0000000000..735c258fff --- /dev/null +++ b/Task/Sort-an-integer-array/APL/sort-an-integer-array.apl @@ -0,0 +1,3 @@ + X←63 92 51 92 39 15 43 89 36 69 + X[⍋X] +15 36 39 43 51 63 69 89 92 92 diff --git a/Task/Sort-an-integer-array/ActionScript/sort-an-integer-array.as b/Task/Sort-an-integer-array/ActionScript/sort-an-integer-array.as new file mode 100644 index 0000000000..13e76d7549 --- /dev/null +++ b/Task/Sort-an-integer-array/ActionScript/sort-an-integer-array.as @@ -0,0 +1,7 @@ +//Comparison function must returns Numbers even though it deals with integers. +function compare(x:int, y:int):Number +{ + return Number(x-y); +} +var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]); +nums.sort(compare); diff --git a/Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada b/Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada new file mode 100644 index 0000000000..62d31a1df1 --- /dev/null +++ b/Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada @@ -0,0 +1,43 @@ +with Gnat.Heap_Sort_G; + +procedure Integer_Sort is + -- Heap sort package requires data to be in index values starting at + -- 1 while index value 0 is used as temporary storage + type Int_Array is array(Natural range <>) of Integer; + Values : Int_Array := (0,1,8,2,7,3,6,4,5); + + -- define move and less than subprograms for use by the heap sort package + procedure Move_Int(From : Natural; To : Natural) is + begin + Values(To) := Values(From); + end Move_Int; + + function Lt_Int(Left, Right : Natural) return Boolean is + begin + return Values(Left) < Values (Right); + end Lt_Int; + + -- Instantiate the generic heap sort package + package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int); + +begin + Heap_Sort.Sort(8); +end Integer_Sort; + +requires an Ada05 compiler, e.g GNAT GPL 2007 +with Ada.Containers.Generic_Array_Sort; + +procedure Integer_Sort is + -- + type Int_Array is array(Natural range <>) of Integer; + Values : Int_Array := (0,1,8,2,7,3,6,4,5); + + -- Instantiate the generic sort package from the standard Ada library + procedure Sort is new Ada.Containers.Generic_Array_Sort + (Index_Type => Natural, + Element_Type => Integer, + Array_Type => Int_Array); + +begin + Sort(Values); +end Integer_Sort; diff --git a/Task/Sort-an-integer-array/AutoHotkey/sort-an-integer-array.ahk b/Task/Sort-an-integer-array/AutoHotkey/sort-an-integer-array.ahk new file mode 100644 index 0000000000..84530cd1a5 --- /dev/null +++ b/Task/Sort-an-integer-array/AutoHotkey/sort-an-integer-array.ahk @@ -0,0 +1,3 @@ +numbers = 5 4 1 2 3 +sort, numbers, N D%A_Space% +Msgbox % numbers diff --git a/Task/Sort-an-integer-array/BBC-BASIC/sort-an-integer-array.bbc b/Task/Sort-an-integer-array/BBC-BASIC/sort-an-integer-array.bbc new file mode 100644 index 0000000000..2e4c72d8f0 --- /dev/null +++ b/Task/Sort-an-integer-array/BBC-BASIC/sort-an-integer-array.bbc @@ -0,0 +1,13 @@ + INSTALL @lib$+"SORTLIB" + sort% = FN_sortinit(0,0) + + DIM array(8) + array() = 8, 2, 5, 9, 1, 3, 6, 7, 4 + + C% = DIM(array(),1) + 1 + CALL sort%, array(0) + + FOR i% = 0 TO DIM(array(),1) - 1 + PRINT ; array(i%) ", "; + NEXT + PRINT ; array(i%) diff --git a/Task/Sort-an-integer-array/Befunge/sort-an-integer-array.bf b/Task/Sort-an-integer-array/Befunge/sort-an-integer-array.bf new file mode 100644 index 0000000000..3ee3c32996 --- /dev/null +++ b/Task/Sort-an-integer-array/Befunge/sort-an-integer-array.bf @@ -0,0 +1,4 @@ +v +> 543** > :#v_ $&> :#v_ 1 > :0g > :#v_ $ 1+: 543** `! #v_ 25*,@ + ^-1p0\0:< ^-1 p0\+1 g0:&< ^-1\.:\< + ^ < diff --git a/Task/Sort-an-integer-array/Bracmat/sort-an-integer-array.bracmat b/Task/Sort-an-integer-array/Bracmat/sort-an-integer-array.bracmat new file mode 100644 index 0000000000..b4f31cdda0 --- /dev/null +++ b/Task/Sort-an-integer-array/Bracmat/sort-an-integer-array.bracmat @@ -0,0 +1,17 @@ +{sort takes a list of space-separated integers} +(sort= + sum elem sorted n +. 0:?sum + & whl + ' (!arg:%?elem ?arg&(!elem.)+!sum:?sum) + & :?sorted + & whl + ' ( !sum:?n*(?elem.)+?sum + & whl + ' ( !n+-1:~<0:?n + & !sorted !elem:?sorted + ) + ) + & !sorted); + + out$sort$(9 -2 1 2 8 0 1 2); diff --git a/Task/Sort-an-integer-array/Burlesque/sort-an-integer-array.blq b/Task/Sort-an-integer-array/Burlesque/sort-an-integer-array.blq new file mode 100644 index 0000000000..53e7dbfd0c --- /dev/null +++ b/Task/Sort-an-integer-array/Burlesque/sort-an-integer-array.blq @@ -0,0 +1 @@ +{1 3 2 5 4}>< diff --git a/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp b/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp new file mode 100644 index 0000000000..a0e37276ad --- /dev/null +++ b/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp @@ -0,0 +1,8 @@ +#include <algorithm> + +int main() +{ + int nums[] = {2,4,3,1,2}; + std::sort(nums, nums+5); + return 0; +} diff --git a/Task/Sort-an-integer-array/C++/sort-an-integer-array-2.cpp b/Task/Sort-an-integer-array/C++/sort-an-integer-array-2.cpp new file mode 100644 index 0000000000..6cf2a5b1ee --- /dev/null +++ b/Task/Sort-an-integer-array/C++/sort-an-integer-array-2.cpp @@ -0,0 +1,14 @@ +#include <algorithm> +#include <vector> + +int main() +{ + std::vector<int> nums; + nums.push_back(2); + nums.push_back(4); + nums.push_back(3); + nums.push_back(1); + nums.push_back(2); + std::sort(nums.begin(), nums.end()); + return 0; +} diff --git a/Task/Sort-an-integer-array/C++/sort-an-integer-array-3.cpp b/Task/Sort-an-integer-array/C++/sort-an-integer-array-3.cpp new file mode 100644 index 0000000000..3fdfec2017 --- /dev/null +++ b/Task/Sort-an-integer-array/C++/sort-an-integer-array-3.cpp @@ -0,0 +1,13 @@ +#include <list> + +int main() +{ + std::list<int> nums; + nums.push_back(2); + nums.push_back(4); + nums.push_back(3); + nums.push_back(1); + nums.push_back(2); + nums.sort(); + return 0; +} diff --git a/Task/Sort-an-integer-array/C/sort-an-integer-array.c b/Task/Sort-an-integer-array/C/sort-an-integer-array.c new file mode 100644 index 0000000000..fa04f1b374 --- /dev/null +++ b/Task/Sort-an-integer-array/C/sort-an-integer-array.c @@ -0,0 +1,17 @@ +#include <stdlib.h> /* qsort() */ +#include <stdio.h> /* printf() */ + +int intcmp(const void *aa, const void *bb) +{ + const int *a = aa, *b = bb; + return (*a < *b) ? -1 : (*a > *b); +} + +int main() +{ + int nums[5] = {2,4,3,1,2}; + qsort(nums, 5, sizeof(int), intcmp); + printf("result: %d %d %d %d %d\n", + nums[0], nums[1], nums[2], nums[3], nums[4]); + return 0; +} diff --git a/Task/Sort-an-integer-array/Clean/sort-an-integer-array.clean b/Task/Sort-an-integer-array/Clean/sort-an-integer-array.clean new file mode 100644 index 0000000000..ca3be0a187 --- /dev/null +++ b/Task/Sort-an-integer-array/Clean/sort-an-integer-array.clean @@ -0,0 +1,7 @@ +import StdEnv + +sortArray :: (a e) -> a e | Array a e & Ord e +sortArray array = {y \\ y <- sort [x \\ x <-: array]} + +Start :: {#Int} +Start = sortArray {2, 4, 3, 1, 2} diff --git a/Task/Sort-an-integer-array/Clojure/sort-an-integer-array.clj b/Task/Sort-an-integer-array/Clojure/sort-an-integer-array.clj new file mode 100644 index 0000000000..982894b092 --- /dev/null +++ b/Task/Sort-an-integer-array/Clojure/sort-an-integer-array.clj @@ -0,0 +1,2 @@ +(sort [5 4 3 2 1]) ; sort can also take a comparator function +(1 2 3 4 5) diff --git a/Task/Sort-an-integer-array/Common-Lisp/sort-an-integer-array.lisp b/Task/Sort-an-integer-array/Common-Lisp/sort-an-integer-array.lisp new file mode 100644 index 0000000000..8cafc03247 --- /dev/null +++ b/Task/Sort-an-integer-array/Common-Lisp/sort-an-integer-array.lisp @@ -0,0 +1,2 @@ +CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<) +#(-2 0 1 1 2 2 8 9) diff --git a/Task/Sort-an-integer-array/D/sort-an-integer-array.d b/Task/Sort-an-integer-array/D/sort-an-integer-array.d new file mode 100644 index 0000000000..5f0218c3bc --- /dev/null +++ b/Task/Sort-an-integer-array/D/sort-an-integer-array.d @@ -0,0 +1,7 @@ +import std.stdio, std.algorithm; + +void main() { + auto data = [2, 4, 3, 1, 2]; + data.sort(); // in-place + assert(data == [1, 2, 2, 3, 4]); +} diff --git a/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi b/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi new file mode 100644 index 0000000000..8621a1cd42 --- /dev/null +++ b/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi @@ -0,0 +1,7 @@ +uses Types, Generics.Collections; + +var + a: TIntegerDynArray; +begin + a := TIntegerDynArray.Create(5, 4, 3, 2, 1); + TArray.Sort<Integer>(a); diff --git a/Task/Sort-an-integer-array/E/sort-an-integer-array.e b/Task/Sort-an-integer-array/E/sort-an-integer-array.e new file mode 100644 index 0000000000..b34f10ffcf --- /dev/null +++ b/Task/Sort-an-integer-array/E/sort-an-integer-array.e @@ -0,0 +1 @@ +[2,4,3,1,2].sort() diff --git a/Task/Sort-an-integer-array/EGL/sort-an-integer-array-1.egl b/Task/Sort-an-integer-array/EGL/sort-an-integer-array-1.egl new file mode 100644 index 0000000000..0d41e1d85d --- /dev/null +++ b/Task/Sort-an-integer-array/EGL/sort-an-integer-array-1.egl @@ -0,0 +1,16 @@ +program SortExample + + function main() + test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0]; + test1.sort(sortFunction); + + for(i int from 1 to test1.getSize()) + SysLib.writeStdout(test1[i]); + end + end + + function sortFunction(a any in, b any in) returns (int) + return (a as int) - (b as int); + end + +end diff --git a/Task/Sort-an-integer-array/EGL/sort-an-integer-array-2.egl b/Task/Sort-an-integer-array/EGL/sort-an-integer-array-2.egl new file mode 100644 index 0000000000..5dc1616cbe --- /dev/null +++ b/Task/Sort-an-integer-array/EGL/sort-an-integer-array-2.egl @@ -0,0 +1,7 @@ +test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0]; +RUILib.sort(test1, sortFunction); + + +function sortFunction(a any in, b any in) returns (int) + return ((a as int) - (b as int)); +end diff --git a/Task/Sort-an-integer-array/Erlang/sort-an-integer-array.erl b/Task/Sort-an-integer-array/Erlang/sort-an-integer-array.erl new file mode 100644 index 0000000000..d7d5371efb --- /dev/null +++ b/Task/Sort-an-integer-array/Erlang/sort-an-integer-array.erl @@ -0,0 +1,2 @@ +List = [2, 4, 3, 1, 2]. +SortedList = lists:sort(List). diff --git a/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.euphoria b/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.euphoria new file mode 100644 index 0000000000..0ca4d6f97b --- /dev/null +++ b/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.euphoria @@ -0,0 +1,2 @@ +include sort.e +print(1,sort({20, 7, 65, 10, 3, 0, 8, -60})) diff --git a/Task/Sort-an-integer-array/Factor/sort-an-integer-array.factor b/Task/Sort-an-integer-array/Factor/sort-an-integer-array.factor new file mode 100644 index 0000000000..e0f26eee04 --- /dev/null +++ b/Task/Sort-an-integer-array/Factor/sort-an-integer-array.factor @@ -0,0 +1 @@ +{ 1 4 9 2 3 0 5 } natural-sort . diff --git a/Task/Sort-an-integer-array/Forth/sort-an-integer-array.fth b/Task/Sort-an-integer-array/Forth/sort-an-integer-array.fth new file mode 100644 index 0000000000..04329784f5 --- /dev/null +++ b/Task/Sort-an-integer-array/Forth/sort-an-integer-array.fth @@ -0,0 +1,2 @@ +create test-data 2 , 4 , 3 , 1 , 2 , +test-data 5 cell-sort diff --git a/Task/Sort-an-integer-array/Fortran/sort-an-integer-array.f b/Task/Sort-an-integer-array/Fortran/sort-an-integer-array.f new file mode 100644 index 0000000000..bb0f53f11f --- /dev/null +++ b/Task/Sort-an-integer-array/Fortran/sort-an-integer-array.f @@ -0,0 +1,4 @@ +CALL ISORT@(b, a, n) +! n = number of elements +! a = array to be sorted +! b = array of indices of a. b(1) 'points' to the minimum value etc. diff --git a/Task/Sort-an-integer-array/GAP/sort-an-integer-array.gap b/Task/Sort-an-integer-array/GAP/sort-an-integer-array.gap new file mode 100644 index 0000000000..743e6547cd --- /dev/null +++ b/Task/Sort-an-integer-array/GAP/sort-an-integer-array.gap @@ -0,0 +1,14 @@ +a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]; +# Make a copy (with "b := a;", b and a would point to the same list) +b := ShallowCopy(a); + +# Sort in place +Sort(a); +a; +# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] + +# Sort without changing the argument +SortedList(b); +# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] +b; +# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] diff --git a/Task/Sort-an-integer-array/Go/sort-an-integer-array.go b/Task/Sort-an-integer-array/Go/sort-an-integer-array.go new file mode 100644 index 0000000000..c0009392ec --- /dev/null +++ b/Task/Sort-an-integer-array/Go/sort-an-integer-array.go @@ -0,0 +1,9 @@ +package main +import "fmt" +import "sort" + +func main() { + nums := []int {2, 4, 3, 1, 2} + sort.Ints(nums) + fmt.Println(nums) +} diff --git a/Task/Sort-an-integer-array/Golfscript/sort-an-integer-array.golfscript b/Task/Sort-an-integer-array/Golfscript/sort-an-integer-array.golfscript new file mode 100644 index 0000000000..c61eb46eea --- /dev/null +++ b/Task/Sort-an-integer-array/Golfscript/sort-an-integer-array.golfscript @@ -0,0 +1 @@ +[2 4 3 1 2]$ diff --git a/Task/Sort-an-integer-array/Groovy/sort-an-integer-array.groovy b/Task/Sort-an-integer-array/Groovy/sort-an-integer-array.groovy new file mode 100644 index 0000000000..2701260c2e --- /dev/null +++ b/Task/Sort-an-integer-array/Groovy/sort-an-integer-array.groovy @@ -0,0 +1 @@ +println ([2,4,0,3,1,2,-12].sort()) diff --git a/Task/Sort-an-integer-array/Haskell/sort-an-integer-array.hs b/Task/Sort-an-integer-array/Haskell/sort-an-integer-array.hs new file mode 100644 index 0000000000..38d3de2318 --- /dev/null +++ b/Task/Sort-an-integer-array/Haskell/sort-an-integer-array.hs @@ -0,0 +1,2 @@ +nums = [2,4,3,1,2] :: [Int] +sorted = List.sort nums diff --git a/Task/Sort-an-integer-array/HicEst/sort-an-integer-array.hicest b/Task/Sort-an-integer-array/HicEst/sort-an-integer-array.hicest new file mode 100644 index 0000000000..2b4d3eba9e --- /dev/null +++ b/Task/Sort-an-integer-array/HicEst/sort-an-integer-array.hicest @@ -0,0 +1,4 @@ +DIMENSION array(100) + + array = INT( RAN(100) ) + SORT(Vector=array, Sorted=array) diff --git a/Task/Sort-an-integer-array/IDL/sort-an-integer-array.idl b/Task/Sort-an-integer-array/IDL/sort-an-integer-array.idl new file mode 100644 index 0000000000..6a92b45e8e --- /dev/null +++ b/Task/Sort-an-integer-array/IDL/sort-an-integer-array.idl @@ -0,0 +1 @@ +result = array[sort(array)] diff --git a/Task/Sort-an-integer-array/Icon/sort-an-integer-array.icon b/Task/Sort-an-integer-array/Icon/sort-an-integer-array.icon new file mode 100644 index 0000000000..359c4b8c90 --- /dev/null +++ b/Task/Sort-an-integer-array/Icon/sort-an-integer-array.icon @@ -0,0 +1 @@ +S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69]) # will sort a list diff --git a/Task/Sort-an-integer-array/Inform-7/sort-an-integer-array.inf b/Task/Sort-an-integer-array/Inform-7/sort-an-integer-array.inf new file mode 100644 index 0000000000..4018d38aa6 --- /dev/null +++ b/Task/Sort-an-integer-array/Inform-7/sort-an-integer-array.inf @@ -0,0 +1,2 @@ +let L be {5, 4, 7, 1, 18}; +sort L; diff --git a/Task/Sort-an-integer-array/Io/sort-an-integer-array.io b/Task/Sort-an-integer-array/Io/sort-an-integer-array.io new file mode 100644 index 0000000000..760d9783ec --- /dev/null +++ b/Task/Sort-an-integer-array/Io/sort-an-integer-array.io @@ -0,0 +1,3 @@ +mums := list(2,4,3,1,2) +sorted := nums sort # returns a new sorted array. 'nums' is unchanged +nums sortInPlace # sort 'nums' "in-place" diff --git a/Task/Sort-an-integer-array/J/sort-an-integer-array-1.j b/Task/Sort-an-integer-array/J/sort-an-integer-array-1.j new file mode 100644 index 0000000000..27e3c93786 --- /dev/null +++ b/Task/Sort-an-integer-array/J/sort-an-integer-array-1.j @@ -0,0 +1 @@ +/:~ diff --git a/Task/Sort-an-integer-array/J/sort-an-integer-array-2.j b/Task/Sort-an-integer-array/J/sort-an-integer-array-2.j new file mode 100644 index 0000000000..87424d45d5 --- /dev/null +++ b/Task/Sort-an-integer-array/J/sort-an-integer-array-2.j @@ -0,0 +1,4 @@ + ] a=: 10 ?@$ 100 NB. random vector +63 92 51 92 39 15 43 89 36 69 + /:~ a +15 36 39 43 51 63 69 89 92 92 diff --git a/Task/Sort-an-integer-array/Java/sort-an-integer-array-1.java b/Task/Sort-an-integer-array/Java/sort-an-integer-array-1.java new file mode 100644 index 0000000000..71f4d5b612 --- /dev/null +++ b/Task/Sort-an-integer-array/Java/sort-an-integer-array-1.java @@ -0,0 +1,9 @@ +import java.util.Arrays; + +public class example { + public static void main(String[] args) + { + int[] nums = {2,4,3,1,2}; + Arrays.sort(nums); + } +} diff --git a/Task/Sort-an-integer-array/Java/sort-an-integer-array-2.java b/Task/Sort-an-integer-array/Java/sort-an-integer-array-2.java new file mode 100644 index 0000000000..9c620c248d --- /dev/null +++ b/Task/Sort-an-integer-array/Java/sort-an-integer-array-2.java @@ -0,0 +1,11 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class example { + public static void main(String[] args) + { + List<Integer> nums = Arrays.asList(2,4,3,1,2); + Collections.sort(nums); + } +} diff --git a/Task/Sort-an-integer-array/JavaScript/sort-an-integer-array.js b/Task/Sort-an-integer-array/JavaScript/sort-an-integer-array.js new file mode 100644 index 0000000000..96b3da9828 --- /dev/null +++ b/Task/Sort-an-integer-array/JavaScript/sort-an-integer-array.js @@ -0,0 +1,6 @@ +function int_arr(a, b) { + return a - b; +} +var numbers = [20, 7, 65, 10, 3, 0, 8, -60]; +numbers.sort(int_arr); +document.write(numbers); diff --git a/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia b/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia new file mode 100644 index 0000000000..af1e251c8b --- /dev/null +++ b/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia @@ -0,0 +1,35 @@ +julia> a = [4,2,3,1] +4-element Int32 Array: + 4 + 2 + 3 + 1 +julia>#non-mutating sort +sort(a) +4-element Int32 Array: + 1 + 2 + 3 + 4 + +julia> a +4-element Int32 Array: + 4 + 2 + 3 + 1 + +julia>#mutating sort + sort!(a) +4-element Int32 Array: + 1 + 2 + 3 + 4 + +julia> a +4-element Int32 Array: + 1 + 2 + 3 + 4 diff --git a/Task/Sort-an-integer-array/K/sort-an-integer-array.k b/Task/Sort-an-integer-array/K/sort-an-integer-array.k new file mode 100644 index 0000000000..af20529753 --- /dev/null +++ b/Task/Sort-an-integer-array/K/sort-an-integer-array.k @@ -0,0 +1,6 @@ + num: -10?10 / Integers from 0 to 9 in random order +5 9 4 2 0 3 6 1 8 7 + + srt: {x@<x} / Generalized sort ascending + srt num +0 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sort-an-integer-array/Liberty-BASIC/sort-an-integer-array.liberty b/Task/Sort-an-integer-array/Liberty-BASIC/sort-an-integer-array.liberty new file mode 100644 index 0000000000..622f236565 --- /dev/null +++ b/Task/Sort-an-integer-array/Liberty-BASIC/sort-an-integer-array.liberty @@ -0,0 +1,16 @@ +N =20 +dim IntArray( N) + +print "Original order" +for i =1 to N + t =int( 1000 *rnd( 1)) + IntArray( i) =t + print t +next i + +sort IntArray(), 1, N + +print "Sorted oprder" +for i =1 to N + print IntArray( i) +next i diff --git a/Task/Sort-an-integer-array/Lua/sort-an-integer-array.lua b/Task/Sort-an-integer-array/Lua/sort-an-integer-array.lua new file mode 100644 index 0000000000..e35d83b071 --- /dev/null +++ b/Task/Sort-an-integer-array/Lua/sort-an-integer-array.lua @@ -0,0 +1,3 @@ +t = {4, 5, 2} +table.sort(t) +print(unpack(t)) diff --git a/Task/Sort-an-integer-array/MATLAB/sort-an-integer-array.m b/Task/Sort-an-integer-array/MATLAB/sort-an-integer-array.m new file mode 100644 index 0000000000..e9fe71d8db --- /dev/null +++ b/Task/Sort-an-integer-array/MATLAB/sort-an-integer-array.m @@ -0,0 +1,2 @@ +a = [4,3,7,-2,9,1]; b = sort(a) % b contains elements of a in ascending order +[b,idx] = sort(a) % b contains a(idx) diff --git a/Task/Sort-an-integer-array/MAXScript/sort-an-integer-array.maxscript b/Task/Sort-an-integer-array/MAXScript/sort-an-integer-array.maxscript new file mode 100644 index 0000000000..ef2c420e27 --- /dev/null +++ b/Task/Sort-an-integer-array/MAXScript/sort-an-integer-array.maxscript @@ -0,0 +1,2 @@ +arr = #(5, 4, 3, 2, 1) +arr = sort arr diff --git a/Task/Sort-an-integer-array/MUMPS/sort-an-integer-array.mumps b/Task/Sort-an-integer-array/MUMPS/sort-an-integer-array.mumps new file mode 100644 index 0000000000..390063faa6 --- /dev/null +++ b/Task/Sort-an-integer-array/MUMPS/sort-an-integer-array.mumps @@ -0,0 +1,12 @@ +SORTARRAY(X,SEP) + ;X is the list of items to sort + ;X1 is the temporary array + ;SEP is the separator string between items in the list X + ;Y is the returned list + ;This routine uses the inherent sorting of the arrays + NEW I,X1,Y + SET Y="" + FOR I=1:1:$LENGTH(X,SEP) SET X1($PIECE(X,SEP,I))="" + SET I="" FOR SET I=$O(X1(I)) Q:I="" SET Y=$SELECT($L(Y)=0:I,1:Y_SEP_I) + KILL I,X1 + QUIT Y diff --git a/Task/Sort-an-integer-array/Mathematica/sort-an-integer-array.math b/Task/Sort-an-integer-array/Mathematica/sort-an-integer-array.math new file mode 100644 index 0000000000..7fc316d8ab --- /dev/null +++ b/Task/Sort-an-integer-array/Mathematica/sort-an-integer-array.math @@ -0,0 +1 @@ +numbers = Sort[{2,4,3,1,2}] diff --git a/Task/Sort-an-integer-array/Maxima/sort-an-integer-array.maxima b/Task/Sort-an-integer-array/Maxima/sort-an-integer-array.maxima new file mode 100644 index 0000000000..d3f2b4f1b4 --- /dev/null +++ b/Task/Sort-an-integer-array/Maxima/sort-an-integer-array.maxima @@ -0,0 +1 @@ +sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]); diff --git a/Task/Sort-an-integer-array/Mercury/sort-an-integer-array.mercury b/Task/Sort-an-integer-array/Mercury/sort-an-integer-array.mercury new file mode 100644 index 0000000000..8ebf1a35ee --- /dev/null +++ b/Task/Sort-an-integer-array/Mercury/sort-an-integer-array.mercury @@ -0,0 +1,14 @@ +:- module sort_int_list. +:- interface. +:- import_module io. + +:- pred main(io::di, uo::uo) is det. + +:- implementation. +:- import_module list. + +main(!IO) :- + Nums = [2, 4, 0, 3, 1, 2], + list.sort(Nums, Sorted), + io.write(Sorted, !IO), + io.nl(!IO). diff --git a/Task/Sort-an-integer-array/Modula-3/sort-an-integer-array.mod3 b/Task/Sort-an-integer-array/Modula-3/sort-an-integer-array.mod3 new file mode 100644 index 0000000000..07fea0c1df --- /dev/null +++ b/Task/Sort-an-integer-array/Modula-3/sort-an-integer-array.mod3 @@ -0,0 +1,9 @@ +MODULE ArraySort EXPORTS Main; + +IMPORT IntArraySort; + +VAR arr := ARRAY [1..10] OF INTEGER{3, 6, 1, 2, 10, 7, 9, 4, 8, 5}; + +BEGIN + IntArraySort.Sort(arr); +END ArraySort. diff --git a/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-1.netrexx b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-1.netrexx new file mode 100644 index 0000000000..ff4f89bbcf --- /dev/null +++ b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-1.netrexx @@ -0,0 +1,22 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +ia = int[] +ia = [ 2, 4, 3, 1, 2, -1, 0, -2 ] + +display(ia) +Arrays.sort(ia) +display(ia) + +-- Display results +method display(in = int[]) public static + + sorted = Rexx('') + + loop ix = 0 for in.length + sorted = sorted || Rexx(in[ix]).right(4) + end ix + + say sorted.strip('t') + + return diff --git a/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-2.netrexx b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-2.netrexx new file mode 100644 index 0000000000..769e3e779c --- /dev/null +++ b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-2.netrexx @@ -0,0 +1,72 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols + +/*REXX program to sort an integer array.*/ + +numeric digits 20 /*handle larger numbers.*/ +a = '' +a[ 1]= 1 +a[ 2]= 0 +a[ 3]= -1 +a[ 4]= 0 +a[ 5]= 5 +a[ 6]= 0 +a[ 7]= -61 +a[ 8]= 0 +a[ 9]= 1385 +a[10]= 0 +a[11]= -50521 +a[12]= 0 +a[13]= 2702765 +a[14]= 0 +a[15]= -199360981 +a[16]= 0 +a[17]= 19391512145 +a[18]= 0 +a[19]= -2404879675441 +a[20]= 0 +a[21]= 370371188237525 + +size = 21 /*we have a list of 21 Euler numbers.*/ +tell('un-sorted', a, size) +a[0] = size +esort(a, 1) +tell(' sorted', a, size) + +return + +/*----------------------------------ESORT subroutine--------------------*/ +method esort(a, size) public static +--esort: procedure expose a.; + + h = a[0] + + loop while h > 1 + h = h % 2 + loop i = 1 for a[0] - h + j = i + k = h + i + loop while a[k] < a[j] + t = a[j] + a[j] = a[k] + a[k] = t + if h >= j then leave + j = j - h + k = k - h + end + end i + end + +return + +/*----------------------------------TELL subroutine---------------------*/ +method tell(arg, a, size) public static +--tell: + + say arg.center(40, '-') + loop j = 1 for size + say arg 'array element' j.right(size.length)'='a[j].right(25) + end j + say + + return diff --git a/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-3.netrexx b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-3.netrexx new file mode 100644 index 0000000000..33c30e4311 --- /dev/null +++ b/Task/Sort-an-integer-array/NetRexx/sort-an-integer-array-3.netrexx @@ -0,0 +1,54 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols + +/*REXX program to sort an interesting integer list.*/ + +bell = '1 1 2 5 15 52 203 877 4140 21147 115975' /*some Bell numbers.*/ +bern = '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*some Bernoulli num*/ +perrin = '3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90' /*some Perrin nums. */ +list = bell bern perrin /*combine the three.*/ + +size = list.words + +a = 0 +loop j = 1 for size + a[j] = list.word(j) + end j + +say ' as is='list +a[0] = size +esort(a, size) +bList = '' + +loop j = 1 for size + bList = bList a[j] + end j + +blist = bList.strip +say ' sorted='bList + +return + +/*----------------------------------ESORT subroutine--------------------*/ +method esort(a, size) public static +--esort: procedure expose a.; + + h = a[0] + + loop while h > 1 + h = h % 2 + loop i = 1 for a[0] - h + j = i + k = h + i + loop while a[k] < a[j] + t = a[j] + a[j] = a[k] + a[k] = t + if h >= j then leave + j = j - h + k = k - h + end + end i + end + +return diff --git a/Task/Sort-an-integer-array/Nial/sort-an-integer-array.nial b/Task/Sort-an-integer-array/Nial/sort-an-integer-array.nial new file mode 100644 index 0000000000..92e25e7d36 --- /dev/null +++ b/Task/Sort-an-integer-array/Nial/sort-an-integer-array.nial @@ -0,0 +1,2 @@ +sort >= 9 6 8 7 1 10 += 10 9 8 7 6 1 diff --git a/Task/Sort-an-integer-array/Niue/sort-an-integer-array.niue b/Task/Sort-an-integer-array/Niue/sort-an-integer-array.niue new file mode 100644 index 0000000000..8f985ab8e6 --- /dev/null +++ b/Task/Sort-an-integer-array/Niue/sort-an-integer-array.niue @@ -0,0 +1,2 @@ +2 6 1 0 3 8 sort .s +0 1 2 3 6 8 diff --git a/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-1.ocaml b/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-1.ocaml new file mode 100644 index 0000000000..ca01280298 --- /dev/null +++ b/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-1.ocaml @@ -0,0 +1,2 @@ +let nums = [|2; 4; 3; 1; 2|] +Array.sort compare nums diff --git a/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-2.ocaml b/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-2.ocaml new file mode 100644 index 0000000000..9b1703c502 --- /dev/null +++ b/Task/Sort-an-integer-array/OCaml/sort-an-integer-array-2.ocaml @@ -0,0 +1,2 @@ +let nums = [2; 4; 3; 1; 2] +let sorted = List.sort compare nums diff --git a/Task/Sort-an-integer-array/Objeck/sort-an-integer-array.objeck b/Task/Sort-an-integer-array/Objeck/sort-an-integer-array.objeck new file mode 100644 index 0000000000..a9ac790cfb --- /dev/null +++ b/Task/Sort-an-integer-array/Objeck/sort-an-integer-array.objeck @@ -0,0 +1,8 @@ +bundle Default { + class Sort { + function : Main(args : System.String[]) ~ Nil { + nums := Structure.IntVector->New([2,4,3,1,2]); + nums->Sort(); + } + } +} diff --git a/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m b/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m new file mode 100644 index 0000000000..4a7c636f01 --- /dev/null +++ b/Task/Sort-an-integer-array/Objective-C/sort-an-integer-array.m @@ -0,0 +1,12 @@ +- (void)example +{ + NSArray *nums, *sorted; + nums = [NSArray arrayWithObjects: + [NSNumber numberWithInt:2], + [NSNumber numberWithInt:4], + [NSNumber numberWithInt:3], + [NSNumber numberWithInt:1], + [NSNumber numberWithInt:2], + nil]; + sorted = [nums sortedArrayUsingSelector:@selector(compare:)]; +} diff --git a/Task/Sort-an-integer-array/Octave/sort-an-integer-array.octave b/Task/Sort-an-integer-array/Octave/sort-an-integer-array.octave new file mode 100644 index 0000000000..7d1717ade4 --- /dev/null +++ b/Task/Sort-an-integer-array/Octave/sort-an-integer-array.octave @@ -0,0 +1 @@ +sortedv = sort(v); diff --git a/Task/Sort-an-integer-array/Order/sort-an-integer-array.order b/Task/Sort-an-integer-array/Order/sort-an-integer-array.order new file mode 100644 index 0000000000..718ac56cbd --- /dev/null +++ b/Task/Sort-an-integer-array/Order/sort-an-integer-array.order @@ -0,0 +1,3 @@ +#include <order/interpreter.h> + +ORDER_PP( 8seq_sort(8less, 8seq(2, 4, 3, 1, 2)) ) diff --git a/Task/Sort-an-integer-array/Oz/sort-an-integer-array.oz b/Task/Sort-an-integer-array/Oz/sort-an-integer-array.oz new file mode 100644 index 0000000000..414c29bf40 --- /dev/null +++ b/Task/Sort-an-integer-array/Oz/sort-an-integer-array.oz @@ -0,0 +1,5 @@ +declare + Nums = [2 4 3 1 2] + Sorted = {List.sort Nums Value.'<'} +in + {Show Sorted} diff --git a/Task/Sort-an-integer-array/PARI-GP/sort-an-integer-array.pari b/Task/Sort-an-integer-array/PARI-GP/sort-an-integer-array.pari new file mode 100644 index 0000000000..d028de0442 --- /dev/null +++ b/Task/Sort-an-integer-array/PARI-GP/sort-an-integer-array.pari @@ -0,0 +1 @@ +vecsort(v) diff --git a/Task/Sort-an-integer-array/PHP/sort-an-integer-array.php b/Task/Sort-an-integer-array/PHP/sort-an-integer-array.php new file mode 100644 index 0000000000..c1aca3577e --- /dev/null +++ b/Task/Sort-an-integer-array/PHP/sort-an-integer-array.php @@ -0,0 +1,4 @@ +<?php +$nums = array(2,4,3,1,2); +sort($nums); +?> diff --git a/Task/Sort-an-integer-array/PL-I/sort-an-integer-array.pli b/Task/Sort-an-integer-array/PL-I/sort-an-integer-array.pli new file mode 100644 index 0000000000..ac03a2b1ea --- /dev/null +++ b/Task/Sort-an-integer-array/PL-I/sort-an-integer-array.pli @@ -0,0 +1,37 @@ +DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */ + +MERGE: PROCEDURE (A,LA,B,LB,C); + DECLARE (A(*),B(*),C(*)) FIXED BIN(31); + DECLARE (LA,LB) FIXED BIN(31) NONASGN; + DECLARE (I,J,K) FIXED BIN(31); + + I=1; J=1; K=1; + DO WHILE ((I <= LA) & (J <= LB)); + IF(A(I) <= B(J)) THEN + DO; C(K)=A(I); K=K+1; I=I+1; END; + ELSE + DO; C(K)=B(J); K=K+1; J=J+1; END; + END; + DO WHILE (I <= LA); + C(K)=A(I); I=I+1; K=K+1; + END; + RETURN; +END MERGE; + +MERGESORT: PROCEDURE (A,N) RECURSIVE ; + DECLARE (A(*)) FIXED BINARY(31); + DECLARE N FIXED BINARY(31) NONASGN; + DECLARE Temp FIXED BINARY; + DECLARE (M,I) FIXED BINARY; + DECLARE AMP1(N) FIXED BINARY(31) BASED(P); + DECLARE P POINTER; + IF (N=1) THEN RETURN; + M = trunc((N+1)/2); + IF (M>1) THEN CALL MERGESORT(A,M); + P=ADDR(A(M+1)); + IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M); + IF A(M) <= AMP1(1) THEN RETURN; + DO I=1 to M; T(I)=A(I); END; + CALL MERGE(T,M,AMP1,N-M,A); + RETURN; +END MERGESORT; diff --git a/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-1.pl6 b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-1.pl6 new file mode 100644 index 0000000000..c6b0abad69 --- /dev/null +++ b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-1.pl6 @@ -0,0 +1 @@ +my @sorted = sort @a; diff --git a/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-2.pl6 b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-2.pl6 new file mode 100644 index 0000000000..a5bc02cb4d --- /dev/null +++ b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-2.pl6 @@ -0,0 +1 @@ +my @sorted = sort +*, @a; diff --git a/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 new file mode 100644 index 0000000000..f748a59c49 --- /dev/null +++ b/Task/Sort-an-integer-array/Perl-6/sort-an-integer-array-3.pl6 @@ -0,0 +1 @@ +@a .= sort; diff --git a/Task/Sort-an-integer-array/Perl/sort-an-integer-array.pl b/Task/Sort-an-integer-array/Perl/sort-an-integer-array.pl new file mode 100644 index 0000000000..db49267d60 --- /dev/null +++ b/Task/Sort-an-integer-array/Perl/sort-an-integer-array.pl @@ -0,0 +1,2 @@ +@nums = (2,4,3,1,2); +@sorted = sort {$a <=> $b} @nums; diff --git a/Task/Sort-an-integer-array/PicoLisp/sort-an-integer-array.l b/Task/Sort-an-integer-array/PicoLisp/sort-an-integer-array.l new file mode 100644 index 0000000000..f641560065 --- /dev/null +++ b/Task/Sort-an-integer-array/PicoLisp/sort-an-integer-array.l @@ -0,0 +1,2 @@ +(sort (2 4 3 1 2)) +-> (1 2 2 3 4) diff --git a/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-1.pop11 b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-1.pop11 new file mode 100644 index 0000000000..9ae77564f6 --- /dev/null +++ b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-1.pop11 @@ -0,0 +1,11 @@ +lvars ar = {2 4 3 1 2}; +;;; Convert array to list. +;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were +destvector(ar); +;;; conslist uses the items left on the stack plus the integer, to make a list of those items. +lvars ls = conslist(); +;;; Sort it +sort(ls) -> ls; +;;; Convert list to array +destlist(ls); +consvector() -> ar; diff --git a/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-2.pop11 b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-2.pop11 new file mode 100644 index 0000000000..0b12e31f94 --- /dev/null +++ b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-2.pop11 @@ -0,0 +1,5 @@ +lvars ar = {2 4 3 1 2}; +consvector(destlist(sort(conslist(destvector(ar))))) -> ar; +;;; print the sorted vector: +ar => +** {1 2 2 3 4} diff --git a/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-3.pop11 b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-3.pop11 new file mode 100644 index 0000000000..87e04c9af1 --- /dev/null +++ b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-3.pop11 @@ -0,0 +1,2 @@ +lvars ar = {2 4 3 1 2}; +consvector(destlist(sort(datalist(ar)))) -> ar; diff --git a/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-4.pop11 b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-4.pop11 new file mode 100644 index 0000000000..2ffd6aa570 --- /dev/null +++ b/Task/Sort-an-integer-array/Pop11/sort-an-integer-array-4.pop11 @@ -0,0 +1,2 @@ +lvars ar = {2 4 3 1 2}; +ar.datalist.sort.destlist.consvector -> ar; diff --git a/Task/Sort-an-integer-array/PowerBASIC/sort-an-integer-array.powerbasic b/Task/Sort-an-integer-array/PowerBASIC/sort-an-integer-array.powerbasic new file mode 100644 index 0000000000..bb2e7a9bd5 --- /dev/null +++ b/Task/Sort-an-integer-array/PowerBASIC/sort-an-integer-array.powerbasic @@ -0,0 +1 @@ +ARRAY SORT x() diff --git a/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.psh b/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.psh new file mode 100644 index 0000000000..b96b0f309c --- /dev/null +++ b/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.psh @@ -0,0 +1 @@ +34,12,23,56,1,129,4,2,73 | Sort-Object diff --git a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium new file mode 100644 index 0000000000..ac9f23823e --- /dev/null +++ b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-1.protium @@ -0,0 +1,15 @@ +Construct a list of numbers +<@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> +Numbers sort as strings +<@ ACTSRTENTLST>L</@> +<@ SAYDMPLST>L</@> +<@ ACTSRTENTLSTLIT>L|__StringDescending</@> +<@ SAYDMPLST>L</@> + +Construct another list of numbers +<@ LETCNSLSTLIT>list|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> +Numbers sorted as numbers +<@ ACTSRTENTLSTLIT>list|__Numeric</@> +<@ SAYDMPLST>list</@> +<@ ACTSRTENTLSTLIT>list|__NumericDescending</@> +<@ SAYDMPLST>list</@> diff --git a/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium new file mode 100644 index 0000000000..84d8078bc9 --- /dev/null +++ b/Task/Sort-an-integer-array/Protium/sort-an-integer-array-2.protium @@ -0,0 +1,15 @@ +Construct a list of numbers + +Numbers sort as strings + +1^2^25^25^3^39^4^4^41^42^44^45^47^51^65^69^77^84^ + +84^77^69^65^51^47^45^44^42^41^4^4^39^3^25^25^2^1^ + +Construct another list of numbers + +Numbers sorted as numbers + +1^2^3^4^4^25^25^39^41^42^44^45^47^51^65^69^77^84^ + +84^77^69^65^51^47^45^44^42^41^39^25^25^4^4^3^2^1^ diff --git a/Task/Sort-an-integer-array/PureBasic/sort-an-integer-array.purebasic b/Task/Sort-an-integer-array/PureBasic/sort-an-integer-array.purebasic new file mode 100644 index 0000000000..ced5cd5726 --- /dev/null +++ b/Task/Sort-an-integer-array/PureBasic/sort-an-integer-array.purebasic @@ -0,0 +1,6 @@ +Dim numbers(20) +For i = 0 To 20 + numbers(i) = Random(1000) +Next + +SortArray(numbers(), #PB_Sort_Ascending) diff --git a/Task/Sort-an-integer-array/Python/sort-an-integer-array-1.py b/Task/Sort-an-integer-array/Python/sort-an-integer-array-1.py new file mode 100644 index 0000000000..82ff89c7df --- /dev/null +++ b/Task/Sort-an-integer-array/Python/sort-an-integer-array-1.py @@ -0,0 +1,2 @@ +nums = [2,4,3,1,2] +nums.sort() diff --git a/Task/Sort-an-integer-array/Python/sort-an-integer-array-2.py b/Task/Sort-an-integer-array/Python/sort-an-integer-array-2.py new file mode 100644 index 0000000000..e83cc753c7 --- /dev/null +++ b/Task/Sort-an-integer-array/Python/sort-an-integer-array-2.py @@ -0,0 +1 @@ +nums = sorted([2,4,3,1,2]) diff --git a/Task/Sort-an-integer-array/R/sort-an-integer-array.r b/Task/Sort-an-integer-array/R/sort-an-integer-array.r new file mode 100644 index 0000000000..4ba18bdd8b --- /dev/null +++ b/Task/Sort-an-integer-array/R/sort-an-integer-array.r @@ -0,0 +1,2 @@ +nums <- c(2,4,3,1,2) +sorted <- sort(nums) diff --git a/Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol b/Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol new file mode 100644 index 0000000000..7fe4f3be3c --- /dev/null +++ b/Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol @@ -0,0 +1 @@ +sort [2 4 3 1 2] diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx new file mode 100644 index 0000000000..5e7c7316a8 --- /dev/null +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx @@ -0,0 +1,47 @@ +/*REXX program to sort (E-sort) an array (which contains integers). */ + numeric digits 30 /*handle larger numbers.*/ + a.1= 1 + a.2= 0 + a.3= -1 + a.4= 0 + a.5= 5 + a.6= 0 + a.7= -61 + a.8= 0 + a.9= 1385 +a.10= 0 +a.11= -50521 +a.12= 0 +a.13= 2702765 +a.14= 0 +a.15= -199360981 +a.16= 0 +a.17= 19391512145 +a.18= 0 +a.19= -2404879675441 +a.20= 0 +a.21= 370371188237525 + +size=21 /*have a list of 21 Euler numbers*/ +call tell 'un-sorted' +call esort size +call tell ' sorted' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ESORT subroutine────────────────────*/ +esort: procedure expose a.; parse arg N; h=N + do while h>1; h=h%2 + do i=1 for N-h; j=i; k=h+i + do while a.k<a.j + parse value a.j a.k with a.k a.j /*swap two elements.*/ + if h>=j then leave; j=j-h; k=k-h + end /*while a.k<a.j*/ + end /*i*/ + end /*while h>1*/ +return +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: say center(arg(1),50,'─') + do j=1 for size + say arg(1) 'array element' right(j,length(size))'='right(a.j,20) + end /*j*/ +say +return diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx new file mode 100644 index 0000000000..e3553cd351 --- /dev/null +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx @@ -0,0 +1,30 @@ +/*REXX program sorts (using E-sort) a list of some interesting integers.*/ + + /*quotes aren't needed if all elements in a list are non-negative.*/ +bell= 1 1 2 5 15 52 203 877 4140 21147 115975 /*some Bell numbers.*/ +bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*some Bernoulli num*/ +perrin=3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 /*some Perrin nums. */ +list=bell bern perrin /*throw 'em───>a pot*/ +say 'original =' list /*an annoucement... */ +size=words(list) /*nice to have SIZE.*/ + do j=1 for size /*build an array, 1 */ + a.j=word(list,j) /*element at a time.*/ + end /*j*/ +call esort size /*sort the stuff. */ +bList=a.1 /*start with 1st. */ + do k=2 to size /*build a list. */ + bList=bList a.k + end /*k*/ +say ' sorted =' bList /*show & tell time. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ESORT subroutine────────────────────*/ +esort: procedure expose a.; parse arg N; h=N + do while h>1; h=h%2 + do i=1 for N-h; j=i; k=h+i + do while a.k<a.j + parse value a.j a.k with a.k a.j /*swap two elements.*/ + if h>=j then leave; j=j-h; k=k-h + end /*while a.k<a.j*/ + end /*i*/ + end /*while h>1*/ +return diff --git a/Task/Sort-an-integer-array/Rascal/sort-an-integer-array.rascal b/Task/Sort-an-integer-array/Rascal/sort-an-integer-array.rascal new file mode 100644 index 0000000000..a31ec49596 --- /dev/null +++ b/Task/Sort-an-integer-array/Rascal/sort-an-integer-array.rascal @@ -0,0 +1,11 @@ +rascal>import List; +ok + +rascal>a = [1, 4, 2, 3, 5]; +list[int]: [1,4,2,3,5] + +rascal>sort(a) +list[int]: [1,2,3,4,5] + +rascal>sort(a, bool(int a, int b){return a >= b;}) +list[int]: [5,4,3,2,1] diff --git a/Task/Sort-an-integer-array/Raven/sort-an-integer-array.raven b/Task/Sort-an-integer-array/Raven/sort-an-integer-array.raven new file mode 100644 index 0000000000..cb728363a1 --- /dev/null +++ b/Task/Sort-an-integer-array/Raven/sort-an-integer-array.raven @@ -0,0 +1 @@ +[ 2 4 3 1 2 ] sort diff --git a/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb b/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb new file mode 100644 index 0000000000..8e3a799c73 --- /dev/null +++ b/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb @@ -0,0 +1,3 @@ +nums = [2,4,3,1,2] +sorted = nums.sort # returns a new sorted array. 'nums' is unchanged +nums.sort! # sort 'nums' "in-place" diff --git a/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala b/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala new file mode 100644 index 0000000000..337bb2e7f3 --- /dev/null +++ b/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala @@ -0,0 +1,2 @@ +println(List(5,2,78,2,578,-42).sortWith(_<_)) +//--> List(-42, 2, 2, 5, 78, 578) diff --git a/Task/Sort-an-integer-array/Scheme/sort-an-integer-array.ss b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array.ss new file mode 100644 index 0000000000..c50e3f835b --- /dev/null +++ b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array.ss @@ -0,0 +1 @@ +(sort #(9 -2 1 2 8 0 1 2) #'<) diff --git a/Task/Sort-an-integer-array/Seed7/sort-an-integer-array.seed7 b/Task/Sort-an-integer-array/Seed7/sort-an-integer-array.seed7 new file mode 100644 index 0000000000..8b255fc4c3 --- /dev/null +++ b/Task/Sort-an-integer-array/Seed7/sort-an-integer-array.seed7 @@ -0,0 +1,3 @@ +var array integer: nums is [] (2, 4, 3, 1, 2); + +nums := sort(nums); diff --git a/Task/Sort-an-integer-array/Slate/sort-an-integer-array.slate b/Task/Sort-an-integer-array/Slate/sort-an-integer-array.slate new file mode 100644 index 0000000000..770093abea --- /dev/null +++ b/Task/Sort-an-integer-array/Slate/sort-an-integer-array.slate @@ -0,0 +1 @@ + #(7 5 2 9 0 -1) sort diff --git a/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-1.st b/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-1.st new file mode 100644 index 0000000000..95e052d407 --- /dev/null +++ b/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-1.st @@ -0,0 +1 @@ + #(7 5 2 9 0 -1) asSortedCollection diff --git a/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-2.st b/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-2.st new file mode 100644 index 0000000000..770093abea --- /dev/null +++ b/Task/Sort-an-integer-array/Smalltalk/sort-an-integer-array-2.st @@ -0,0 +1 @@ + #(7 5 2 9 0 -1) sort diff --git a/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-1.ml b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-1.ml new file mode 100644 index 0000000000..f12bbc11d1 --- /dev/null +++ b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-1.ml @@ -0,0 +1,6 @@ +- val nums = Array.fromList [2, 4, 3, 1, 2]; +val nums = [|2,4,3,1,2|] : int array +- ArrayQSort.sort Int.compare nums; +val it = () : unit +- nums; +val it = [|1,2,2,3,4|] : int array diff --git a/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-2.ml b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-2.ml new file mode 100644 index 0000000000..ff6d8ca487 --- /dev/null +++ b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-2.ml @@ -0,0 +1,10 @@ +- load "Arraysort"; +> val it = () : unit +- load "Int"; +> val it = () : unit +- val nums = Array.fromList [2, 4, 3, 1, 2]; +> val nums = <array> : int array +- Arraysort.sort Int.compare nums; +> val it = () : unit +- Array.foldr op:: [] nums; +> val it = [1, 2, 2, 3, 4] : int list diff --git a/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-3.ml b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-3.ml new file mode 100644 index 0000000000..c72a040db8 --- /dev/null +++ b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-3.ml @@ -0,0 +1,4 @@ +- val nums = [2, 4, 3, 1, 2]; +val nums = [2,4,3,1,2] : int list +- val sorted = ListMergeSort.sort op> nums; +val sorted = [1,2,2,3,4] : int list diff --git a/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-4.ml b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-4.ml new file mode 100644 index 0000000000..a592e45f9a --- /dev/null +++ b/Task/Sort-an-integer-array/Standard-ML/sort-an-integer-array-4.ml @@ -0,0 +1,8 @@ +- load "Listsort"; +> val it = () : unit +- load "Int"; +> val it = () : unit +- val nums = [2, 4, 3, 1, 2]; +> val nums = [2, 4, 3, 1, 2] : int list +- val sorted = Listsort.sort Int.compare nums; +> val sorted = [1, 2, 2, 3, 4] : int list diff --git a/Task/Sort-an-integer-array/Tcl/sort-an-integer-array.tcl b/Task/Sort-an-integer-array/Tcl/sort-an-integer-array.tcl new file mode 100644 index 0000000000..fa678db375 --- /dev/null +++ b/Task/Sort-an-integer-array/Tcl/sort-an-integer-array.tcl @@ -0,0 +1 @@ +set result [lsort -integer $unsorted_list] diff --git a/Task/Sort-an-integer-array/Toka/sort-an-integer-array.toka b/Task/Sort-an-integer-array/Toka/sort-an-integer-array.toka new file mode 100644 index 0000000000..2e07c37554 --- /dev/null +++ b/Task/Sort-an-integer-array/Toka/sort-an-integer-array.toka @@ -0,0 +1,2 @@ +needs bsort +arrayname number_elements bsort diff --git a/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-1.sh b/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-1.sh new file mode 100644 index 0000000000..7452e2c111 --- /dev/null +++ b/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-1.sh @@ -0,0 +1,3 @@ +nums="2 4 3 1 5" +sorted=`printf "%s\n" $nums | sort -n` +echo $sorted # prints 1 2 3 4 5 diff --git a/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-2.sh b/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-2.sh new file mode 100644 index 0000000000..cb186986ba --- /dev/null +++ b/Task/Sort-an-integer-array/UNIX-Shell/sort-an-integer-array-2.sh @@ -0,0 +1,3 @@ +set -A nums 2 4 3 1 5 +set -A sorted $(printf "%s\n" ${nums[*]} | sort -n) +echo ${sorted[*]} # prints 1 2 3 4 5 diff --git a/Task/Sort-an-integer-array/Ursala/sort-an-integer-array.ursala b/Task/Sort-an-integer-array/Ursala/sort-an-integer-array.ursala new file mode 100644 index 0000000000..d1a4c46f09 --- /dev/null +++ b/Task/Sort-an-integer-array/Ursala/sort-an-integer-array.ursala @@ -0,0 +1,5 @@ +#import nat + +#cast %nL + +example = nleq-< <39,47,40,53,14,23,88,52,78,62,41,92,88,66,5,40> diff --git a/Task/Sort-an-integer-array/XPL0/sort-an-integer-array.xpl0 b/Task/Sort-an-integer-array/XPL0/sort-an-integer-array.xpl0 new file mode 100644 index 0000000000..efc8475409 --- /dev/null +++ b/Task/Sort-an-integer-array/XPL0/sort-an-integer-array.xpl0 @@ -0,0 +1,27 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +proc SSort(A, N); \Shell sort array in ascending order +int A; \address of array +int N; \number of elements in array (size) +int I, J, Gap, JG, T; +[Gap:= N>>1; +while Gap > 0 do + [for I:= Gap to N-1 do + [J:= I - Gap; + loop [JG:= J + Gap; + if A(J) <= A(JG) then quit; + T:= A(J); A(J):= A(JG); A(JG):= T; \swap elements + J:= J - Gap; + if J < 0 then quit; + ]; + ]; + Gap:= Gap>>1; + ]; +]; \SSort + +int A, I; +[A:= [3, 1, 4, 1, 5, 9, 2, 6, 5, 4]; +SSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +CrLf(0); +] diff --git a/Task/Sort-an-integer-array/Yorick/sort-an-integer-array.yorick b/Task/Sort-an-integer-array/Yorick/sort-an-integer-array.yorick new file mode 100644 index 0000000000..6a7bb09529 --- /dev/null +++ b/Task/Sort-an-integer-array/Yorick/sort-an-integer-array.yorick @@ -0,0 +1,2 @@ +nums = [2,4,3,1,2]; +nums = nums(sort(nums)); diff --git a/Task/Sort-disjoint-sublist/0DESCRIPTION b/Task/Sort-disjoint-sublist/0DESCRIPTION new file mode 100644 index 0000000000..e3fa523ea9 --- /dev/null +++ b/Task/Sort-disjoint-sublist/0DESCRIPTION @@ -0,0 +1,10 @@ +Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted. + +Make your example work with the following list of values and set of indices: +<code> + values: [7, <b>6</b>, 5, 4, 3, 2, <b>1</b>, <b>0</b>] + indices: {6, 1, 7}</code> +Where the correct result would be: + <code>[7, <b>0</b>, 5, 4, 3, 2, <b>1</b>, <b>6</b>]</code>. + +Note that for one based, rather than the zero-based indexing above, use the <code>indices: {7, 2, 8}</code>. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. diff --git a/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada b/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada new file mode 100644 index 0000000000..42ff836abb --- /dev/null +++ b/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada @@ -0,0 +1,57 @@ +with Ada.Text_IO, GNAT.Bubble_Sort; +use Ada.Text_IO; + +procedure DisjointSort is + + package Int_Io is new Integer_IO (Integer); + + subtype Index_Range is Natural range 1 .. 8; + Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0); + + subtype Subindex_Range is Natural range 1 .. 3; + type Sub_Arrays is array (Subindex_Range) of Integer; + + Sub_Index : Sub_Arrays := (7, 2, 8); + Sub_Array : Sub_Arrays; + + -- reuse of the somehow generic GNAT.Bubble_Sort (for Ada05) + + procedure Sort (Work_Array : in out Sub_Arrays) is + procedure Exchange (Op1, Op2 : Natural) is + Temp : Integer; + begin + Temp := Work_Array (Op1); + Work_Array (Op1) := Work_Array (Op2); + Work_Array (Op2) := Temp; + end Exchange; + + function Lt (Op1, Op2 : Natural) return Boolean is + begin + return (Work_Array (Op1) < Work_Array (Op2)); + end Lt; + begin + GNAT.Bubble_Sort.Sort + (N => Subindex_Range'Last, + Xchg => Exchange'Unrestricted_Access, + Lt => Lt'Unrestricted_Access); + end Sort; + +begin + -- as the positions are not ordered, first sort the positions + Sort (Sub_Index); + -- extract the values to be sorted + for I in Subindex_Range loop + Sub_Array (I) := Input_Array (Sub_Index (I)); + end loop; + Sort (Sub_Array); + -- put the sorted values at the right place + for I in Subindex_Range loop + Input_Array (Sub_Index (I)) := Sub_Array (I); + end loop; + + for I in Index_Range loop + Int_Io.Put (Input_Array (I), Width => 2); + end loop; + New_Line; + +end DisjointSort; diff --git a/Task/Sort-disjoint-sublist/BBC-BASIC/sort-disjoint-sublist.bbc b/Task/Sort-disjoint-sublist/BBC-BASIC/sort-disjoint-sublist.bbc new file mode 100644 index 0000000000..18c715b10f --- /dev/null +++ b/Task/Sort-disjoint-sublist/BBC-BASIC/sort-disjoint-sublist.bbc @@ -0,0 +1,32 @@ + INSTALL @lib$+"SORTLIB" + Sort% = FN_sortinit(0,0) : REM Ascending + + DIM list%(7) : list%() = 7, 6, 5, 4, 3, 2, 1, 0 + DIM indices%(2) : indices%() = 6, 1, 7 + + PROCsortdisjoint(list%(), indices%()) + PRINT FNshowlist(list%()) + END + + DEF PROCsortdisjoint(l%(), i%()) + LOCAL C%, i%, n%, t%() + n% = DIM(i%(),1) + DIM t%(n%) + FOR i% = 0 TO n% + t%(i%) = l%(i%(i%)) + NEXT + C% = n% + 1 + CALL Sort%, i%(0) + CALL Sort%, t%(0) + FOR i% = 0 TO n% + l%(i%(i%)) = t%(i%) + NEXT + ENDPROC + + DEF FNshowlist(l%()) + LOCAL i%, o$ + o$ = "[" + FOR i% = 0 TO DIM(l%(),1) + o$ += STR$(l%(i%)) + ", " + NEXT + = LEFT$(LEFT$(o$)) + "]" diff --git a/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-1.cpp b/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-1.cpp new file mode 100644 index 0000000000..4af6680708 --- /dev/null +++ b/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-1.cpp @@ -0,0 +1,34 @@ +#include <algorithm> +#include <iostream> +#include <iterator> +#include <vector> + +template <typename ValueIterator, typename IndicesIterator> +void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin, + IndicesIterator indicesEnd) { + std::vector<int> temp; + + for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i) + temp.push_back(valsBegin[*i]); // extract + + std::sort(indicesBegin, indicesEnd); // sort + std::sort(temp.begin(), temp.end()); // sort a C++ container + + std::vector<int>::const_iterator j = temp.begin(); + for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j) + valsBegin[*i] = *j; // replace +} + + +int main() +{ + int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 }; + int indices[] = { 6, 1, 7 }; + + sortDisjoint(values, indices, indices+3); + + std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " ")); + std::cout << "\n"; + + return 0; +} diff --git a/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-2.cpp b/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-2.cpp new file mode 100644 index 0000000000..3213d83d69 --- /dev/null +++ b/Task/Sort-disjoint-sublist/C++/sort-disjoint-sublist-2.cpp @@ -0,0 +1,62 @@ +#include <algorithm> +#include <iostream> +#include <iterator> +#include <vector> + +template <typename ValueIterator, typename IndicesIterator> +struct DisjointSubsetIterator : + public std::iterator<std::random_access_iterator_tag, + typename std::iterator_traits<ValueIterator>::value_type> { + typedef typename std::iterator_traits<ValueIterator>::value_type V; + ValueIterator valsBegin; + IndicesIterator i; + DisjointSubsetIterator() { } + DisjointSubsetIterator(const ValueIterator &_v, IndicesIterator _i) : + valsBegin(_v), i(_i) { } + DisjointSubsetIterator& operator++() { ++i; return *this; } + DisjointSubsetIterator operator++(int) { + DisjointSubsetIterator tmp = *this; ++(*this); return tmp; } + bool operator==(const DisjointSubsetIterator& y) { return i == y.i; } + bool operator!=(const DisjointSubsetIterator& y) { return i != y.i; } + V &operator*() { return valsBegin[*i]; } + DisjointSubsetIterator& operator--() { --i; return *this; } + DisjointSubsetIterator operator--(int) { + DisjointSubsetIterator tmp = *this; --(*this); return tmp; } + DisjointSubsetIterator& operator+=(int n) { i += n; return *this; } + DisjointSubsetIterator& operator-=(int n) { i -= n; return *this; } + DisjointSubsetIterator operator+(int n) { + DisjointSubsetIterator tmp = *this; return tmp += n; } + DisjointSubsetIterator operator-(int n) { + DisjointSubsetIterator tmp = *this; return tmp -= n; } + int operator-(const DisjointSubsetIterator &y) { return i - y.i; } + V &operator[](int n) { return *(*this + n); } + bool operator<(const DisjointSubsetIterator &y) { return i < y.i; } + bool operator>(const DisjointSubsetIterator &y) { return i > y.i; } + bool operator<=(const DisjointSubsetIterator &y) { return i <= y.i; } + bool operator>=(const DisjointSubsetIterator &y) { return i >= y.i; } +}; +template <typename ValueIterator, typename IndicesIterator> +DisjointSubsetIterator<ValueIterator, IndicesIterator> +operator+(int n, const DisjointSubsetIterator<ValueIterator, IndicesIterator> &i) { + return i + n; } + +template <typename ValueIterator, typename IndicesIterator> +void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin, + IndicesIterator indicesEnd) { + std::sort(DisjointSubsetIterator<ValueIterator, IndicesIterator>(valsBegin, indicesBegin), + DisjointSubsetIterator<ValueIterator, IndicesIterator>(valsBegin, indicesEnd)); +} + + +int main() +{ + int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 }; + int indices[] = { 6, 1, 7 }; + + sortDisjoint(values, indices, indices+3); + + std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " ")); + std::cout << "\n"; + + return 0; +} diff --git a/Task/Sort-disjoint-sublist/C/sort-disjoint-sublist.c b/Task/Sort-disjoint-sublist/C/sort-disjoint-sublist.c new file mode 100644 index 0000000000..4fd8a6355f --- /dev/null +++ b/Task/Sort-disjoint-sublist/C/sort-disjoint-sublist.c @@ -0,0 +1,33 @@ +#include <stdio.h> + +/* yes, bubble sort */ +void bubble_sort(int *idx, int n_idx, int *buf) +{ + int i, j, tmp; +#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++) +#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;} + for_ij { sort(idx[j], idx[i]); } + for_ij { sort(buf[idx[j]], buf[idx[i]]);} +#undef for_ij +#undef sort +} + +int main() +{ + int values[] = {7, 6, 5, 4, 3, 2, 1, 0}; + int idx[] = {6, 1, 7}; + int i; + + printf("before sort:\n"); + for (i = 0; i < 8; i++) + printf("%d ", values[i]); + + printf("\n\nafter sort:\n"); + bubble_sort(idx, 3, values); + + for (i = 0; i < 8; i++) + printf("%d ", values[i]); + printf("\n"); + + return 0; +} diff --git a/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d new file mode 100644 index 0000000000..acd8f18b83 --- /dev/null +++ b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d @@ -0,0 +1,11 @@ +import std.algorithm, std.range, std.array; + +void main() { + auto data = [7, 6, 5, 4, 3, 2, 1, 0]; + auto indices = [6, 1, 7]; + + auto idxSet = indices.sort().uniq().array(); + data.indexed(idxSet).sort(); + + assert(data == [7, 0, 5, 4, 3, 2, 1, 6]); +} diff --git a/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-2.d b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-2.d new file mode 100644 index 0000000000..22c5a292a2 --- /dev/null +++ b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-2.d @@ -0,0 +1,41 @@ +import std.algorithm: swap; + +void disjointSort(T, U)(T[] arr, U[] indexes) +in { + if (arr.length == 0) + assert(indexes.length == 0); + else { + foreach (idx; indexes) + assert(idx >= 0 && idx < arr.length); + } +} body { + void quickSort(U* left, U* right) { + if (right > left) { + auto pivot = arr[left[(right - left) / 2]]; + auto r = right, l = left; + do { + while (arr[*l] < pivot) l++; + while (arr[*r] > pivot) r--; + if (l <= r) { + swap(arr[*l], arr[*r]); + swap(l, r); + l++; + r--; + } + } while (l <= r); + quickSort(left, r); + quickSort(l, right); + } + } + + if (arr.length == 0 || indexes.length == 0) + return; + quickSort(&indexes[0], &indexes[$-1]); +} + +void main() { + auto data = [7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0]; + auto indexes = [6, 1, 1, 7]; + disjointSort(data, indexes); + assert(data == [7.0, 0.0, 5.0, 4.0, 3.0, 2.0, 1.0, 6.0]); +} diff --git a/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-3.d b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-3.d new file mode 100644 index 0000000000..6cd28e5ec1 --- /dev/null +++ b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-3.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm; + +void main() { + auto data = [7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0]; + auto indexes = [6, 1, 1, 7]; // One duplicated added to test. + + // Remove duplicates, in place: + indexes.length -= indexes.sort().uniq().copy(indexes).length; + + foreach (i, idx; indexes) + swap(data[i], data[idx]); + + data[0 .. indexes.length].sort(); + + foreach_reverse (i, idx; indexes) + swap(data[idx], data[i]); + + assert(data == [7.0, 0.0, 5.0, 4.0, 3.0, 2.0, 1.0, 6.0]); +} diff --git a/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.euphoria b/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.euphoria new file mode 100644 index 0000000000..ba44a01256 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.euphoria @@ -0,0 +1,29 @@ +include sort.e + +function uniq(sequence s) + sequence out + out = s[1..1] + for i = 2 to length(s) do + if not find(s[i], out) then + out = append(out, s[i]) + end if + end for + return out +end function + +function disjointSort(sequence s, sequence idx) + sequence values + idx = uniq(sort(idx)) + values = repeat(0, length(idx)) + for i = 1 to length(idx) do + values[i] = s[idx[i]] + end for + values = sort(values) + for i = 1 to length(idx) do + s[idx[i]] = values[i] + end for + return s +end function + +constant data = {7, 6, 5, 4, 3, 2, 1, 0} +constant indexes = {7, 2, 8} diff --git a/Task/Sort-disjoint-sublist/Fortran/sort-disjoint-sublist.f b/Task/Sort-disjoint-sublist/Fortran/sort-disjoint-sublist.f new file mode 100644 index 0000000000..53b1f976e0 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Fortran/sort-disjoint-sublist.f @@ -0,0 +1,36 @@ +program Example + implicit none + + integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /) + integer :: indices(3) = (/ 7, 2, 8 /) + +! In order to make the output insensitive to index order +! we need to sort the indices first + call Isort(indices) + +! Should work with any sort routine as long as the dummy +! argument array has been declared as an assumed shape array +! Standard insertion sort used in this example + call Isort(array(indices)) + + write(*,*) array + +contains + +subroutine Isort(a) + integer, intent(in out) :: a(:) + integer :: temp + integer :: i, j + + do i = 2, size(a) + j = i - 1 + temp = a(i) + do while (j>=1 .and. a(j)>temp) + a(j+1) = a(j) + j = j - 1 + end do + a(j+1) = temp + end do + +end subroutine Isort +end program Example diff --git a/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-1.go b/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-1.go new file mode 100644 index 0000000000..1ab743bf56 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-1.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "sort" +) + +func main() { + // givens + values := []int{7, 6, 5, 4, 3, 2, 1, 0} + indices := map[int]int{6: 0, 1: 0, 7: 0} + + orderedValues := make([]int, len(indices)) + orderedIndices := make([]int, len(indices)) + i := 0 + for j := range indices { + // validate that indices are within list boundaries + if j < 0 || j >= len(values) { + fmt.Println("Invalid index: ", j) + return + } + // extract elements to sort + orderedValues[i] = values[j] + orderedIndices[i] = j + i++ + } + // sort + sort.Ints(orderedValues) + sort.Ints(orderedIndices) + + fmt.Println("initial:", values) + // replace sorted values + for i, v := range orderedValues { + values[orderedIndices[i]] = v + } + fmt.Println("sorted: ", values) +} diff --git a/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-2.go b/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-2.go new file mode 100644 index 0000000000..b4d480b12f --- /dev/null +++ b/Task/Sort-disjoint-sublist/Go/sort-disjoint-sublist-2.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "sort" +) + +// type and methods satisfying sort.Interface +type subListSortable struct { + values sort.Interface + indices []int +} + +func (s subListSortable) Len() int { + return len(s.indices) +} + +func (s subListSortable) Swap(i, j int) { + s.values.Swap(s.indices[i], s.indices[j]) +} + +func (s subListSortable) Less(i, j int) bool { + return s.values.Less(s.indices[i], s.indices[j]) +} + +func main() { + // givens + values := []int{7, 6, 5, 4, 3, 2, 1, 0} + indices := map[int]int{6: 0, 1: 0, 7: 0} + + // make ordered list of indices for sort methods + ordered := make([]int, len(indices)) + if len(indices) > 0 { + i := 0 + for j := range indices { + ordered[i] = j + i++ + } + sort.Ints(ordered) + + // validate that indices are within list boundaries + if ordered[0] < 0 { + fmt.Println("Invalid index: ", ordered[0]) + return + } + if ordered[len(ordered)-1] >= len(values) { + fmt.Println("Invalid index: ", ordered[len(ordered)-1]) + return + } + } + + // instantiate sortable type and sort + s := subListSortable{sort.IntSlice(values), ordered} + fmt.Println("initial:", s.values) + sort.Sort(s) + fmt.Println("sorted: ", s.values) +} diff --git a/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-1.groovy b/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-1.groovy new file mode 100644 index 0000000000..baadbd9c46 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-1.groovy @@ -0,0 +1,5 @@ +def sparseSort = { a, indices = ([] + (0..<(a.size()))) -> + indices.sort().unique() + a[indices] = a[indices].sort() + a +} diff --git a/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-2.groovy b/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-2.groovy new file mode 100644 index 0000000000..5a475afbd3 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Groovy/sort-disjoint-sublist-2.groovy @@ -0,0 +1,9 @@ +def a = [7, 6, 5, 4, 3, 2, 1, 0] + +println a +println sparseSort(a, []) // no indices to sort +println a +println sparseSort(a, [6,1,7]) // suggested sample indices +println a +println sparseSort(a) // default == sort all +println a diff --git a/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist.hs b/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist.hs new file mode 100644 index 0000000000..161674134b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Haskell/sort-disjoint-sublist.hs @@ -0,0 +1,38 @@ +import Control.Monad +import qualified Data.Array as A +import Data.Array.IArray +import Data.Array.ST +import Data.List +import Data.List.Utils + +-- Partition 'xs' according to whether their element indices are in 'is'. Sort +-- the sublist corresponding to 'is', merging the result with the remainder of +-- the list. +disSort1 :: (Ord a, Num a, Enum a, Ord b) => [b] -> [a] -> [b] +disSort1 xs is = let is' = sort is + (sub, rest) = partition ((`elem` is') . fst) $ zip [0..] xs + in map snd . merge rest . zip is' . sort $ map snd sub + +-- Convert the list to an array. Extract the sublist corresponding to the +-- indices 'is'. Sort the sublist, replacing those elments in the array. +disSort2 :: (Ord a) => [a] -> [Int] -> [a] +disSort2 xs is = let as = A.listArray (0, length xs - 1) xs + sub = zip (sort is) . sort $ map (as !) is + in elems $ as // sub + +-- Similar to disSort2, but using mutable arrays. The sublist is updated +-- "in place", rather than creating a new array. However, this is not visible +-- to a caller. +disSort3 :: [Int] -> [Int] -> [Int] +disSort3 xs is = elems . runSTUArray $ do + as <- newListArray (0, length xs - 1) xs + sub <- liftM (zip (sort is) . sort) $ mapM (readArray as) is + mapM_ (uncurry (writeArray as)) sub + return as + +main = do + let xs = [7, 6, 5, 4, 3, 2, 1, 0] + is = [6, 1, 7] + print $ disSort1 xs is + print $ disSort2 xs is + print $ disSort3 xs is diff --git a/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-1.icon b/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-1.icon new file mode 100644 index 0000000000..0c8f08fa5e --- /dev/null +++ b/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-1.icon @@ -0,0 +1,25 @@ +link sort # get the 'isort' procedure for sorting a list + +procedure sortDisjoint (items, indices) + indices := isort (indices) # sort indices into a list + result := copy (items) + values := [] + every put (values, result[!indices]) + values := isort (values) + every result[!indices] := pop (values) + return result +end + +procedure main () + # set up and do the sort + items := [7, 6, 5, 4, 3, 2, 1, 0] + indices := set(7, 2, 8) # note, Icon lists 1-based + result := sortDisjoint (items, indices) + # display result + every writes (!items || " ") + write () + every writes (!indices || " ") + write () + every writes (!result || " ") + write () +end diff --git a/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-2.icon b/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-2.icon new file mode 100644 index 0000000000..74be1802a0 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Icon/sort-disjoint-sublist-2.icon @@ -0,0 +1 @@ +every put (values, result[!indices]) diff --git a/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-1.j b/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-1.j new file mode 100644 index 0000000000..e8d4dbb45f --- /dev/null +++ b/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-1.j @@ -0,0 +1,2 @@ + 7 6 5 4 3 2 1 0 (/:~@:{`[`]}~ /:~@~.) 6 1 7 +7 0 5 4 3 2 1 6 diff --git a/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-2.j b/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-2.j new file mode 100644 index 0000000000..40ed6feec5 --- /dev/null +++ b/Task/Sort-disjoint-sublist/J/sort-disjoint-sublist-2.j @@ -0,0 +1,2 @@ + 6 1 7 /:~@:{`[`]} 7 6 5 4 3 2 1 0 +7 1 5 4 3 2 0 6 diff --git a/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-1.java b/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-1.java new file mode 100644 index 0000000000..efb2d4cdcb --- /dev/null +++ b/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-1.java @@ -0,0 +1,28 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class Disjoint { + public static <T extends Comparable<? super T>> void sortDisjoint( + List<T> array, int[] idxs) { + Arrays.sort(idxs); + List<T> disjoint = new ArrayList<T>(); + for (int idx : idxs) { + disjoint.add(array.get(idx)); + } + Collections.sort(disjoint); + int i = 0; + for (int idx : idxs) { + array.set(idx, disjoint.get(i++)); + } + } + + public static void main(String[] args) { + List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0); + int[] indices = {6, 1, 7}; + System.out.println(list); + sortDisjoint(list, indices); + System.out.println(list); + } +} diff --git a/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-2.java b/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-2.java new file mode 100644 index 0000000000..2f357c847b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Java/sort-disjoint-sublist-2.java @@ -0,0 +1,24 @@ +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.AbstractList; + +public class Disjoint { + public static <T extends Comparable<? super T>> void sortDisjoint( + final List<T> array, final int[] idxs) { + Arrays.sort(idxs); + Collections.sort(new AbstractList<T>() { + public int size() { return idxs.length; } + public T get(int i) { return array.get(idxs[i]); } + public T set(int i, T x) { return array.set(idxs[i], x); } + }); + } + + public static void main(String[] args) { + List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0); + int[] indices = {6, 1, 7}; + System.out.println(list); + sortDisjoint(list, indices); + System.out.println(list); + } +} diff --git a/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist.js b/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist.js new file mode 100644 index 0000000000..b57fb5c22d --- /dev/null +++ b/Task/Sort-disjoint-sublist/JavaScript/sort-disjoint-sublist.js @@ -0,0 +1,16 @@ +function sort_disjoint(values, indices) { + var sublist = []; + indices.sort(function(a, b) { return a > b; }); + + for (var i = 0; i < indices.length; i += 1) { + sublist.push(values[indices[i]]); + } + + sublist.sort(function(a, b) { return a < b; }); + + for (var i = 0; i < indices.length; i += 1) { + values[indices[i]] = sublist.pop(); + } + + return values; +} diff --git a/Task/Sort-disjoint-sublist/K/sort-disjoint-sublist.k b/Task/Sort-disjoint-sublist/K/sort-disjoint-sublist.k new file mode 100644 index 0000000000..ceec66e8db --- /dev/null +++ b/Task/Sort-disjoint-sublist/K/sort-disjoint-sublist.k @@ -0,0 +1,2 @@ + {@[x;y@<y;:;a@<a:x@y]}[7 6 5 4 3 2 1 0;6 1 7] +7 0 5 4 3 2 1 6 diff --git a/Task/Sort-disjoint-sublist/Lua/sort-disjoint-sublist.lua b/Task/Sort-disjoint-sublist/Lua/sort-disjoint-sublist.lua new file mode 100644 index 0000000000..8966873f59 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Lua/sort-disjoint-sublist.lua @@ -0,0 +1,34 @@ +values = { 7, 6, 5, 4, 3, 2, 1, 0 } +indices = { 6, 1, 7 } + +i = 1 -- discard duplicates +while i < #indices do + j = i + 1 + while j < #indices do + if indices[i] == indices[j] then + table.remove( indices[j] ) + end + j = j + 1 + end + i = i + 1 +end + +for i = 1, #indices do + indices[i] = indices[i] + 1 -- the tables of lua are one-based +end + +vals = {} +for i = 1, #indices do + vals[i] = values[ indices[i] ] +end + +table.sort( vals ) +table.sort( indices ) + +for i = 1, #indices do + values[ indices[i] ] = vals[i] +end + +for i = 1, #values do + io.write( values[i], " " ) +end diff --git a/Task/Sort-disjoint-sublist/Mathematica/sort-disjoint-sublist.math b/Task/Sort-disjoint-sublist/Mathematica/sort-disjoint-sublist.math new file mode 100644 index 0000000000..a04f9db9fc --- /dev/null +++ b/Task/Sort-disjoint-sublist/Mathematica/sort-disjoint-sublist.math @@ -0,0 +1,5 @@ +Values = { 7, 6, 5, 4, 3, 2, 1, 0} ; Indices = { 7, 2, 8 }; +Values[[Sort[Indices]]] = Sort[Values[[Indices]]]; + +Values +-> { 7, 0, 5, 4, 3, 2, 1, 6 } diff --git a/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ocaml b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ocaml new file mode 100644 index 0000000000..3b8c8359fc --- /dev/null +++ b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ocaml @@ -0,0 +1,12 @@ +let disjoint_sort cmp values indices = + let temp = Array.map (Array.get values) indices in + Array.sort cmp temp; + Array.sort compare indices; + Array.iteri (fun i j -> values.(j) <- temp.(i)) indices + +let () = + let values = [| 7; 6; 5; 4; 3; 2; 1; 0 |] + and indices = [| 6; 1; 7 |] in + disjoint_sort compare values indices; + Array.iter (Printf.printf " %d") values; + print_newline() diff --git a/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ocaml b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ocaml new file mode 100644 index 0000000000..76c92b7dda --- /dev/null +++ b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ocaml @@ -0,0 +1,31 @@ +let disjoint_sort cmp values indices = + let indices = List.sort compare indices in + let rec aux acc j = function + | (i::iq), (v::vq) when i = j -> + aux (v::acc) (succ j) (iq, vq) + | [], _ -> acc + | il, (_::vq) -> + aux acc (succ j) (il, vq) + | _, [] -> + invalid_arg "index out of bounds" + in + let temp = aux [] 0 (indices, values) in + let temp = List.sort cmp temp in + let rec aux acc j = function + | (i::iq), (_::vq), (r::rq) when i = j -> + aux (r::acc) (succ j) (iq, vq, rq) + | [], vl, _ -> + List.rev_append acc vl + | il, (v::vq), rl -> + aux (v::acc) (succ j) (il, vq, rl) + | (_::_, [], _) -> + assert false + in + aux [] 0 (indices, values, temp) + +let () = + let values = [ 7; 6; 5; 4; 3; 2; 1; 0 ] + and indices = [ 6; 1; 7 ] in + let res = disjoint_sort compare values indices in + List.iter (Printf.printf " %d") res; + print_newline() diff --git a/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m b/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m new file mode 100644 index 0000000000..4b8dd6c7c7 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Objective-C/sort-disjoint-sublist.m @@ -0,0 +1,64 @@ +#import <Foundation/Foundation.h> + +@interface DisjointSublistView : NSMutableArray { + NSMutableArray *array; + int *indexes; + int num_indexes; +} +- (id)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind; +@end + +@implementation DisjointSublistView +- (id)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind { + if ((self = [super init])) { + array = [a retain]; + num_indexes = [ind count]; + indexes = malloc(num_indexes * sizeof(int)); + for (NSUInteger i = [ind firstIndex], j = 0; i != NSNotFound; i = [ind indexGreaterThanIndex:i], j++) + indexes[j] = i; + } + return self; +} +- (void)dealloc { + [array release]; + free(indexes); + [super dealloc]; +} +- (NSUInteger)count { return num_indexes; } +- (id)objectAtIndex:(NSUInteger)i { return [array objectAtIndex:indexes[i]]; } +- (void)replaceObjectAtIndex:(NSUInteger)i withObject:(id)x { + return [array replaceObjectAtIndex:indexes[i] withObject:x]; } +@end + +@interface NSMutableArray (SortDisjoint) +- (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator; +@end +@implementation NSMutableArray (SortDisjoint) +- (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator { + DisjointSublistView *d = [[DisjointSublistView alloc] initWithArray:self andIndexes:indexes]; + [d sortUsingSelector:comparator]; + [d release]; +} +@end + +int main(int argc, const char *argv[]) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSMutableArray *a = [NSMutableArray arrayWithObjects: + [NSNumber numberWithInt:7], + [NSNumber numberWithInt:6], + [NSNumber numberWithInt:5], + [NSNumber numberWithInt:4], + [NSNumber numberWithInt:3], + [NSNumber numberWithInt:2], + [NSNumber numberWithInt:1], + [NSNumber numberWithInt:0], + nil]; + NSMutableIndexSet *ind = [NSMutableIndexSet indexSet]; + [ind addIndex:6]; [ind addIndex:1]; [ind addIndex:7]; + [a sortDisjointSublist:ind usingSelector:@selector(compare:)]; + NSLog(@"%@", a); + + [pool release]; + return 0; +} diff --git a/Task/Sort-disjoint-sublist/Order/sort-disjoint-sublist.order b/Task/Sort-disjoint-sublist/Order/sort-disjoint-sublist.order new file mode 100644 index 0000000000..63b17de268 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Order/sort-disjoint-sublist.order @@ -0,0 +1,19 @@ +#include <order/interpreter.h> + +#define ORDER_PP_DEF_8sort_disjoint_sublist ORDER_PP_FN( \ +8fn(8L, 8I, \ + 8lets((8I, 8seq_sort(8less, 8tuple_to_seq(8I))) \ + (8J, \ + 8seq_sort(8less, 8seq_map(8fn(8X, 8seq_at(8X, 8L)), 8I))), \ + 8replace(8L, 8I, 8J))) ) + +#define ORDER_PP_DEF_8replace ORDER_PP_FN( \ +8fn(8L, 8I, 8V, \ + 8if(8is_nil(8I), \ + 8L, \ + 8replace(8seq_set(8seq_head(8I), 8L, 8seq_head(8V)), \ + 8seq_tail(8I), 8seq_tail(8V)))) ) + +ORDER_PP( + 8sort_disjoint_sublist(8seq(7, 6, 5, 4, 3, 2, 1, 0), 8tuple(6, 1, 7)) +) diff --git a/Task/Sort-disjoint-sublist/PARI-GP/sort-disjoint-sublist.pari b/Task/Sort-disjoint-sublist/PARI-GP/sort-disjoint-sublist.pari new file mode 100644 index 0000000000..547992b09c --- /dev/null +++ b/Task/Sort-disjoint-sublist/PARI-GP/sort-disjoint-sublist.pari @@ -0,0 +1,7 @@ +sortsome(v,which)={ + my(x=sum(i=1,#which,1<<(which[i]-1)),u=vecextract(v,x)); + u=vecsort(u); + which=vecsort(which); + for(i=1,#which,v[which[i]]=u[i]); + v +}; diff --git a/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-1.pl6 b/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-1.pl6 new file mode 100644 index 0000000000..6c6f37bdcb --- /dev/null +++ b/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-1.pl6 @@ -0,0 +1,6 @@ +my @values = 7, 6, 5, 4, 3, 2, 1, 0; +my @indices = 6, 1, 7; + +@values[ @indices.sort ] .= sort; + +@values.perl.say; diff --git a/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-2.pl6 b/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-2.pl6 new file mode 100644 index 0000000000..aa84a08fd9 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Perl-6/sort-disjoint-sublist-2.pl6 @@ -0,0 +1,12 @@ +sub disjointSort( @values is rw , @indices is rw --> List ) { + my @sortedValues = @values[ @indices ].sort ; + for @indices.sort -> $insert { + @values[ $insert ] = @sortedValues.shift ; + } + return @values ; +} + +my @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ; +my @indices = ( 6 , 1 , 7 ) ; +my @sortedValues = disjointSort( @values , @indices ) ; +@sortedValues.perl.say ; diff --git a/Task/Sort-disjoint-sublist/Perl/sort-disjoint-sublist.pl b/Task/Sort-disjoint-sublist/Perl/sort-disjoint-sublist.pl new file mode 100644 index 0000000000..1dfbbee35b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Perl/sort-disjoint-sublist.pl @@ -0,0 +1,14 @@ +#!/usr/bin/perl -w +use strict ; + +# this function sorts the array in place +sub disjointSort { + my ( $values , @indices ) = @_ ; + + @{$values}[ sort @indices ] = sort @{$values}[ @indices ] ; +} + +my @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ; +my @indices = ( 6 , 1 , 7 ) ; +disjointSort( \@values , @indices ) ; +print "[@values]\n" ; diff --git a/Task/Sort-disjoint-sublist/PicoLisp/sort-disjoint-sublist.l b/Task/Sort-disjoint-sublist/PicoLisp/sort-disjoint-sublist.l new file mode 100644 index 0000000000..fe610acd8e --- /dev/null +++ b/Task/Sort-disjoint-sublist/PicoLisp/sort-disjoint-sublist.l @@ -0,0 +1,6 @@ +(let (Values (7 6 5 4 3 2 1 0) Indices (7 2 8)) + (mapc + '((V I) (set (nth Values I) V)) + (sort (mapcar '((N) (get Values N)) Indices)) + (sort Indices) ) + Values ) diff --git a/Task/Sort-disjoint-sublist/PureBasic/sort-disjoint-sublist.purebasic b/Task/Sort-disjoint-sublist/PureBasic/sort-disjoint-sublist.purebasic new file mode 100644 index 0000000000..4b46dfff46 --- /dev/null +++ b/Task/Sort-disjoint-sublist/PureBasic/sort-disjoint-sublist.purebasic @@ -0,0 +1,40 @@ +Procedure Bubble_sort(Array idx(1), n, Array buf(1)) + Protected i, j + SortArray(idx(),#PB_Sort_Ascending) + For i=0 To n + For j=i+1 To n + If buf(idx(j)) < buf(idx(i)) + Swap buf(idx(j)), buf(idx(i)) + EndIf + Next + Next +EndProcedure + +Procedure main() + DataSection + values: Data.i 7, 6, 5, 4, 3, 2, 1, 0 + indices:Data.i 6, 1, 7 + EndDataSection + + Dim values.i(7) :CopyMemory(?values, @values(), SizeOf(Integer)*8) + Dim indices.i(2):CopyMemory(?indices,@indices(),SizeOf(Integer)*3) + + If OpenConsole() + Protected i + PrintN("Before sort:") + For i=0 To ArraySize(values()) + Print(Str(values(i))+" ") + Next + + PrintN(#CRLF$+#CRLF$+"After sort:") + Bubble_sort(indices(), ArraySize(indices()), values()) + For i=0 To ArraySize(values()) + Print(Str(values(i))+" ") + Next + + Print(#CRLF$+#CRLF$+"Press ENTER to exit") + Input() + EndIf +EndProcedure + +main() diff --git a/Task/Sort-disjoint-sublist/Python/sort-disjoint-sublist.py b/Task/Sort-disjoint-sublist/Python/sort-disjoint-sublist.py new file mode 100644 index 0000000000..e6b569b4de --- /dev/null +++ b/Task/Sort-disjoint-sublist/Python/sort-disjoint-sublist.py @@ -0,0 +1,18 @@ +>>> def sort_disjoint_sublist(data, indices): + indices = sorted(indices) + values = sorted(data[i] for i in indices) + for index, value in zip(indices, values): + data[index] = value + + +>>> d = [7, 6, 5, 4, 3, 2, 1, 0] +>>> i = set([6, 1, 7]) +>>> sort_disjoint_sublist(d, i) +>>> d +[7, 0, 5, 4, 3, 2, 1, 6] +>>> # Which could be more cryptically written as: +>>> def sort_disjoint_sublist(data, indices): + for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value + + +>>> diff --git a/Task/Sort-disjoint-sublist/R/sort-disjoint-sublist.r b/Task/Sort-disjoint-sublist/R/sort-disjoint-sublist.r new file mode 100644 index 0000000000..fcd9f1dc29 --- /dev/null +++ b/Task/Sort-disjoint-sublist/R/sort-disjoint-sublist.r @@ -0,0 +1,4 @@ + values=c(7,6,5,4,3,2,1,0) + indices=c(7,2,8) + values[sort(indices)]=sort(values[indices]) + print(values) diff --git a/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx new file mode 100644 index 0000000000..ae91e06894 --- /dev/null +++ b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx @@ -0,0 +1,29 @@ +/*REXX program uses a strand sort to sort a random list of words | nums.*/ +parse arg old ',' idx /*get options from command line. */ +if old='' then old=7 6 5 4 3 2 1 0 /*no list? Then use the default.*/ +if idx='' then idx=7 2 8 /*no idxs? " " " " */ +old=space(old) /*remove any extraneous blanks. */ +say 'list of indices:' idx +idx=sortL(idx) /*ensure the index list is sorted*/ +say +say ' unsorted list:' old + new=disjoint_sort(old,idx) /*sort it.*/ +say ' sorted list:' new +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────DISJOINT_SORT subroutine────────────*/ +disjoint_sort: procedure; parse arg x,indL; y=; z=; p=0 + do i=1 for words(indL) /*extract indexed values from X.*/ + z=z word(x,word(indL,i)) + end /*j*/ +z=sortL(z) /*sort extracted (indexed) values*/ + do m=1 for words(x) /*re-build (re-populate) X list.*/ + if wordpos(m,indL)==0 then y=y word(x,m) /*same | new?*/ + else do; p=p+1; y=y word(z,p); end + end /*m*/ +return strip(y) +/*──────────────────────────────────SORTL subroutine────────────────────*/ +sortL: procedure; parse arg L; n=words(L); do j=1 for n; @.j=word(L,j); end + do k=1 to n-1 /*sort index list the slow way. */ + do m=k+1 to n; if @.m<@.k then parse value @.k @.m with @.m @.k; end + end /*k*/ +s=@.1; do j=2 to n; s=s @.j; end; return s diff --git a/Task/Sort-disjoint-sublist/Ruby/sort-disjoint-sublist.rb b/Task/Sort-disjoint-sublist/Ruby/sort-disjoint-sublist.rb new file mode 100644 index 0000000000..c12337d335 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Ruby/sort-disjoint-sublist.rb @@ -0,0 +1,9 @@ +def sort_disjoint_sublist!(ar, indices) + values = ar.values_at(*indices).sort + indices.sort.zip(values).each{ |i,v| ar[i] = v } + ar +end + +values = [7, 6, 5, 4, 3, 2, 1, 0] +indices = [6, 1, 7] +p sort_disjoint_sublist!(values, indices) diff --git a/Task/Sort-disjoint-sublist/Run-BASIC/sort-disjoint-sublist.run b/Task/Sort-disjoint-sublist/Run-BASIC/sort-disjoint-sublist.run new file mode 100644 index 0000000000..a071ea9dbb --- /dev/null +++ b/Task/Sort-disjoint-sublist/Run-BASIC/sort-disjoint-sublist.run @@ -0,0 +1,30 @@ +sortData$ = "7, 6, 5, 4, 3, 2, 1, 0" +sortIdx$ = "7, 2, 8" + +numSort = 8 +dim sortData(numSort) +for i = 1 to numSort + sortData(i) = val(word$(sortData$,i,",")) +next i + +while word$(sortIdx$,s + 1) <> "" + s = s + 1 + idx = val(word$(sortIdx$,s)) + gosub [bubbleSort] +wend +end + +[bubbleSort] +sortSw = 1 +while sortSw = 1 + sortSw = 0 + for i = idx to numSort - 1 ' start sorting at idx + if sortData(i) > sortData(i+1) then + sortSw = 1 + sortHold = sortData(i) + sortData(i) = sortData(i+1) + sortData(i+1) = sortHold + end if + next i +wend +RETURN diff --git a/Task/Sort-disjoint-sublist/TUSCRIPT/sort-disjoint-sublist.tuscript b/Task/Sort-disjoint-sublist/TUSCRIPT/sort-disjoint-sublist.tuscript new file mode 100644 index 0000000000..fe222f8fd6 --- /dev/null +++ b/Task/Sort-disjoint-sublist/TUSCRIPT/sort-disjoint-sublist.tuscript @@ -0,0 +1,10 @@ +$$ MODE TUSCRIPT +values="7'6'5'4'3'2'1'0" +indices="7'2'8" +v_unsorted=SELECT (values,#indices) +v_sort=DIGIT_SORT (v_unsorted) +i_sort=DIGIT_SORT (indices) +LOOP i=i_sort,v=v_sort +values=REPLACE (values,#i,v) +ENDLOOP +PRINT values diff --git a/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-1.tcl b/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-1.tcl new file mode 100644 index 0000000000..245576c941 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-1.tcl @@ -0,0 +1,15 @@ +package require Tcl 8.5 +proc disjointSort {values indices args} { + # Ensure that we have a unique list of integers, in order + # We assume there are no end-relative indices + set indices [lsort -integer -unique $indices] + # Map from those indices to the values to sort + set selected {} + foreach i $indices {lappend selected [lindex $values $i]} + # Sort the values (using any extra options) and write back to the list + foreach i $indices v [lsort {*}$args $selected] { + lset values $i $v + } + # The updated list is the result + return $values +} diff --git a/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-2.tcl b/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-2.tcl new file mode 100644 index 0000000000..102e2439a3 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Tcl/sort-disjoint-sublist-2.tcl @@ -0,0 +1,3 @@ +set values {7 6 5 4 3 2 1 0} +set indices {6 1 7} +puts \[[join [disjointSort $values $indices] ", "]\] diff --git a/Task/Sort-disjoint-sublist/Ursala/sort-disjoint-sublist.ursala b/Task/Sort-disjoint-sublist/Ursala/sort-disjoint-sublist.ursala new file mode 100644 index 0000000000..56ea0da6d6 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Ursala/sort-disjoint-sublist.ursala @@ -0,0 +1,8 @@ +#import std +#import nat + +disjoint_sort = ^|(~&,num); ("i","v"). (-:(-:)"v"@p nleq-<~~lSrSX ~&rlPlw~|/"i" "v")*lS "v" + +#cast %nL + +t = disjoint_sort({6,1,7},<7,6,5,4,3,2,1,0>) diff --git a/Task/Sort-stability/0DESCRIPTION b/Task/Sort-stability/0DESCRIPTION new file mode 100644 index 0000000000..031855accf --- /dev/null +++ b/Task/Sort-stability/0DESCRIPTION @@ -0,0 +1,14 @@ +When sorting records in a table by a particular column or field, a [[wp:Stable_sort#Stability|stable sort]] will always retain the relative order of records that have the same key. + +For example, in this table of countries and cities, a stable sort on the '''second''' column, the cities, would keep the US Birmingham above the UK Birmingham. (Although an unstable sort ''might'', in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would ''guarantee'' it). +<pre>UK London +US New York +US Birmingham +UK Birmingham</pre> +Similarly, stable sorting on just the first column would generate “UK London” as the first item and “US Birmingham” as the last item (since the order of the elements having the same first word – “UK” or “US” – would be maintained). + +#Examine the documentation on any in-built sort routines supplied by a language. +#Indicate if an in-built routine is supplied +#If supplied, indicate whether or not the in-built routine is stable. + +(This [[wp:Stable_sort#Comparison_of_algorithms|Wikipedia table]] shows the stability of some common sort routines). diff --git a/Task/Sort-stability/1META.yaml b/Task/Sort-stability/1META.yaml new file mode 100644 index 0000000000..556e45905d --- /dev/null +++ b/Task/Sort-stability/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting diff --git a/Task/Sort-stability/AutoHotkey/sort-stability.ahk b/Task/Sort-stability/AutoHotkey/sort-stability.ahk new file mode 100644 index 0000000000..c74c5efdbc --- /dev/null +++ b/Task/Sort-stability/AutoHotkey/sort-stability.ahk @@ -0,0 +1,40 @@ +Table = +( +UK, London +US, New York +US, Birmingham +UK, Birmingham +) + +Gui, Margin, 6 +Gui, -MinimizeBox +Gui, Add, ListView, r5 w260 Grid, Orig.Position|Country|City +Loop, Parse, Table, `n, `r +{ + StringSplit, out, A_LoopField, `,, %A_Space% + LV_Add("", A_Index, out1, out2) +} +LV_ModifyCol(1, "77 Center") +LV_ModifyCol(2, "100 Center") +LV_ModifyCol(3, 79) +Gui, Add, Button, w80, Restore Order +Gui, Add, Button, x+10 wp, Sort Countries +Gui, Add, Button, x+10 wp, Sort Cities +Gui, Show,, Sort stability +Return + +GuiClose: +GuiEscape: +ExitApp + +ButtonRestoreOrder: + LV_ModifyCol(1, "Sort") +Return + +ButtonSortCountries: + LV_ModifyCol(2, "Sort") +Return + +ButtonSortCities: + LV_ModifyCol(3, "Sort") +Return diff --git a/Task/Sort-stability/GAP/sort-stability.gap b/Task/Sort-stability/GAP/sort-stability.gap new file mode 100644 index 0000000000..3dbf445c4c --- /dev/null +++ b/Task/Sort-stability/GAP/sort-stability.gap @@ -0,0 +1,17 @@ +# According to section 21.18 of the reference manual, Sort is not stable (it's a Shell sort). +# However, SortingPerm is stable. We will see it on an example, showing indexes of elements after the sort. + +n := 20; +L := List([1 .. n], i -> Random("AB")); +# "AABABBBABBABAABABBAB" + + +p := SortingPerm(L); +# (3,10,15,17,18,19,9,14,7,13,6,12,16,8,4)(5,11) + +a := Permuted(L, p);; +b := Permuted([1 .. n], p);; + +PrintArray(TransposedMat(List([1 .. n], i -> [a[i], b[i]]))); +# [ [ 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B' ], +# [ 1, 2, 4, 8, 11, 13, 14, 16, 19, 3, 5, 6, 7, 9, 10, 12, 15, 17, 18, 20 ] ] diff --git a/Task/Sort-stability/Groovy/sort-stability.groovy b/Task/Sort-stability/Groovy/sort-stability.groovy new file mode 100644 index 0000000000..8b45eb2b1e --- /dev/null +++ b/Task/Sort-stability/Groovy/sort-stability.groovy @@ -0,0 +1,10 @@ +def cityList = ['UK London', 'US New York', 'US Birmingham', 'UK Birmingham',].asImmutable() +[ + 'Sort by city': { city -> city[4..-1] }, + 'Sort by country': { city -> city[0..3] }, +].each{ String label, Closure orderBy -> + println "\n\nBefore ${label}" + cityList.each { println it } + println "\nAfter ${label}" + cityList.sort(false, orderBy).each{ println it } +} diff --git a/Task/Sort-stability/Java/sort-stability.java b/Task/Sort-stability/Java/sort-stability.java new file mode 100644 index 0000000000..37978e5e98 --- /dev/null +++ b/Task/Sort-stability/Java/sort-stability.java @@ -0,0 +1,47 @@ +import java.util.Arrays; +import java.util.Comparator; + +public class RJSortStability { + + public static void main(String[] args) { + String[] cityList = { "UK London", "US New York", "US Birmingham", "UK Birmingham", }; + + String[] cn = cityList.clone(); + System.out.println("\nBefore sort:"); + for (String city : cn) { + System.out.println(city); + } + + // sort by city + Arrays.sort(cn, new Comparator<String>() { + public int compare(String lft, String rgt) { + return lft.substring(4).compareTo(rgt.substring(4)); + } + }); + + System.out.println("\nAfter sort on city:"); + for (String city : cn) { + System.out.println(city); + } + + cn = cityList.clone(); + System.out.println("\nBefore sort:"); + for (String city : cn) { + System.out.println(city); + } + + // sort by country + Arrays.sort(cn, new Comparator<String>() { + public int compare(String lft, String rgt) { + return lft.substring(0, 2).compareTo(rgt.substring(0, 2)); + } + }); + + System.out.println("\nAfter sort on country:"); + for (String city : cn) { + System.out.println(city); + } + + System.out.println(); + } +} diff --git a/Task/Sort-stability/JavaScript/sort-stability.js b/Task/Sort-stability/JavaScript/sort-stability.js new file mode 100644 index 0000000000..d869c9277e --- /dev/null +++ b/Task/Sort-stability/JavaScript/sort-stability.js @@ -0,0 +1,7 @@ +ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] +print(ary); + +ary.sort(function(a,b){return (a[1]<b[1] ? -1 : (a[1]>b[1] ? 1 : 0))}); +print(ary); + +/* a stable sort will output ["US", "Birmingham"] before ["UK", "Birmingham"] */ diff --git a/Task/Sort-stability/Mathematica/sort-stability-1.math b/Task/Sort-stability/Mathematica/sort-stability-1.math new file mode 100644 index 0000000000..bdebb757be --- /dev/null +++ b/Task/Sort-stability/Mathematica/sort-stability-1.math @@ -0,0 +1,3 @@ +mylist = {{1, 2, 3}, {4, 5, 6}, {5, 4, 3}, {9, 5, 1}}; +Sort[mylist, (#1[[2]] < #2[[2]]) &] +#[[Ordering[#[[All, 2]]]]] &[mylist] diff --git a/Task/Sort-stability/Mathematica/sort-stability-2.math b/Task/Sort-stability/Mathematica/sort-stability-2.math new file mode 100644 index 0000000000..ddc2b8da58 --- /dev/null +++ b/Task/Sort-stability/Mathematica/sort-stability-2.math @@ -0,0 +1,2 @@ +{{1, 2, 3}, {5, 4, 3}, {9, 5, 1}, {4, 5, 6}} +{{1, 2, 3}, {5, 4, 3}, {4, 5, 6}, {9, 5, 1}} diff --git a/Task/Sort-stability/NetRexx/sort-stability.netrexx b/Task/Sort-stability/NetRexx/sort-stability.netrexx new file mode 100644 index 0000000000..b7b82a7baf --- /dev/null +++ b/Task/Sort-stability/NetRexx/sort-stability.netrexx @@ -0,0 +1,55 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols nobinary + +class RCSortStability + +method main(args = String[]) public constant + + cityList = [String "UK London", "US New York", "US Birmingham", "UK Birmingham"] + + cn = String[cityList.length] + + say + say "Before sort:" + System.arraycopy(cityList, 0, cn, 0, cityList.length) + loop city = 0 to cn.length - 1 + say cn[city] + end city + + cCompNm = Comparator CityComparator() + Arrays.sort(cn, cCompNm) + + say + say "After sort on city:" + loop city = 0 to cn.length - 1 + say cn[city] + end city + + say + say "Before sort:" + System.arraycopy(cityList, 0, cn, 0, cityList.length) + loop city = 0 to cn.length - 1 + say cn[city] + end city + + cCompCtry = Comparator CountryComparator() + Arrays.sort(cn, cCompCtry) + + say + say "After sort on country:" + loop city = 0 to cn.length - 1 + say cn[city] + end city + say + + return + +class RCSortStability.CityComparator implements Comparator + +method compare(lft = Object, rgt = Object) public binary returns int + return (String lft).substring(4).compareTo((String rgt).substring(4)) + +class RCSortStability.CountryComparator implements Comparator + +method compare(lft = Object, rgt = Object) public binary returns int + return (String lft).substring(0, 2).compareTo((String rgt).substring(0, 2)) diff --git a/Task/Sort-stability/OpenEdge-Progress/sort-stability.openedge b/Task/Sort-stability/OpenEdge-Progress/sort-stability.openedge new file mode 100644 index 0000000000..c56f183efa --- /dev/null +++ b/Task/Sort-stability/OpenEdge-Progress/sort-stability.openedge @@ -0,0 +1,25 @@ +DEFINE TEMP-TABLE tt + FIELD country AS CHAR FORMAT 'x(2)' + FIELD city AS CHAR FORMAT 'x(16)' + . + +DEFINE VARIABLE cc AS CHARACTER EXTENT 2. + +CREATE tt. ASSIGN tt.country = 'UK' tt.city = 'London'. +CREATE tt. ASSIGN tt.country = 'US' tt.city = 'New York'. +CREATE tt. ASSIGN tt.country = 'US' tt.city = 'Birmingham'. +CREATE tt. ASSIGN tt.country = 'UK' tt.city = 'Birmingham'. + +cc[1] = 'by country~n~n'. +FOR EACH tt BY tt.country BY ROWID( tt ): + cc[1] = cc[1] + tt.country + '~t' + tt.city + '~n'. +END. + +cc[2] = 'by city~n~n'. +FOR EACH tt BY tt.city BY ROWID( tt ): + cc[2] = cc[2] + tt.country + '~t' + tt.city + '~n'. +END. + +MESSAGE + cc[1] SKIP(1) cc[2] +VIEW-AS ALERT-BOX. diff --git a/Task/Sort-stability/Oz/sort-stability.oz b/Task/Sort-stability/Oz/sort-stability.oz new file mode 100644 index 0000000000..8d06207b33 --- /dev/null +++ b/Task/Sort-stability/Oz/sort-stability.oz @@ -0,0 +1,11 @@ +declare + Cities = ['UK'#'London' + 'US'#'New York' + 'US'#'Birmingham' + 'UK'#'Birmingham'] +in + %% sort by city; stable because '=<' is reflexiv + {Show {Sort Cities fun {$ A B} A.2 =< B.2 end}} + + %% sort by country; NOT stable because '<' is not reflexiv + {Show {Sort Cities fun {$ A B} A.1 < B.1 end}} diff --git a/Task/Sort-stability/Perl-6/sort-stability.pl6 b/Task/Sort-stability/Perl-6/sort-stability.pl6 new file mode 100644 index 0000000000..d7075bdf8d --- /dev/null +++ b/Task/Sort-stability/Perl-6/sort-stability.pl6 @@ -0,0 +1,9 @@ +use v6; +my @cities = + ['UK', 'London'], + ['US', 'New York'], + ['US', 'Birmingham'], + ['UK', 'Birmingham'], + ; + +.say for @cities.sort: { .[1] }; diff --git a/Task/Sort-stability/Perl/sort-stability.pl b/Task/Sort-stability/Perl/sort-stability.pl new file mode 100644 index 0000000000..555f7fdb61 --- /dev/null +++ b/Task/Sort-stability/Perl/sort-stability.pl @@ -0,0 +1 @@ +use sort 'stable'; diff --git a/Task/Sort-stability/R/sort-stability.r b/Task/Sort-stability/R/sort-stability.r new file mode 100644 index 0000000000..26e119d96d --- /dev/null +++ b/Task/Sort-stability/R/sort-stability.r @@ -0,0 +1,22 @@ +# First, define a bernoulli sample, of length 26. +x <- sample(c(0, 1), 26, replace=T) + +x +# [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0 + +# Give names to the entries. "letters" is a builtin value +names(x) <- letters + +x +# a b c d e f g h i j k l m n o p q r s t u v w x y z +# 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0 + +# The unstable one, see how "a" appears after "l" now +sort(x, method="quick") +# z h s u e q x n j r t v w y p o m l a i g f d c b k +# 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 + +# The stable sort, letters are ordered in each section +sort(x, method="shell") +# e h j n q s u x z a b c d f g i k l m o p r t v w y +# 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 diff --git a/Task/Sort-stability/REBOL/sort-stability.rebol b/Task/Sort-stability/REBOL/sort-stability.rebol new file mode 100644 index 0000000000..e351b9de83 --- /dev/null +++ b/Task/Sort-stability/REBOL/sort-stability.rebol @@ -0,0 +1,18 @@ +; REBOL's sort function is not stable by default. You need to use a custom comparator to make it so. + +blk: [ + [UK London] + [US New-York] + [US Birmingham] + [UK Birmingham] +] +sort/compare blk func [a b] [either a/2 < b/2 [-1] [either a/2 > b/2 [1] [0]]] + +; Note that you can also do a stable sort without nested blocks. +blk: [ + UK London + US New-York + US Birmingham + UK Birmingham +] +sort/skip/compare blk 2 func [a b] [either a < b [-1] [either a > b [1] [0]]] diff --git a/Task/Sort-stability/Ruby/sort-stability-1.rb b/Task/Sort-stability/Ruby/sort-stability-1.rb new file mode 100644 index 0000000000..c1c03e0e2b --- /dev/null +++ b/Task/Sort-stability/Ruby/sort-stability-1.rb @@ -0,0 +1,7 @@ +ary = [["UK", "London"], + ["US", "New York"], + ["US", "Birmingham"], + ["UK", "Birmingham"]] +p ary.sort {|a,b| a[1] <=> b[1]} +# MRI reverses the Birminghams: +# => [["UK", "Birmingham"], ["US", "Birmingham"], ["UK", "London"], ["US", "New York"]] diff --git a/Task/Sort-stability/Ruby/sort-stability-2.rb b/Task/Sort-stability/Ruby/sort-stability-2.rb new file mode 100644 index 0000000000..77c5cd98dc --- /dev/null +++ b/Task/Sort-stability/Ruby/sort-stability-2.rb @@ -0,0 +1,20 @@ +class Array + def stable_sort + n = -1 + if block_given? + collect {|x| n += 1; [x, n] + }.sort! {|a, b| + c = yield a[0], b[0] + if c.nonzero? then c else a[1] <=> b[1] end + }.collect! {|x| x[0]} + else + sort_by {|x| n += 1; [x, n]} + end + end + + def stable_sort_by + block_given? or return enum_for(:stable_sort_by) + n = -1 + sort_by {|x| n += 1; [(yield x), n]} + end +end diff --git a/Task/Sort-stability/Ruby/sort-stability-3.rb b/Task/Sort-stability/Ruby/sort-stability-3.rb new file mode 100644 index 0000000000..409237469d --- /dev/null +++ b/Task/Sort-stability/Ruby/sort-stability-3.rb @@ -0,0 +1,8 @@ +ary = [["UK", "London"], + ["US", "New York"], + ["US", "Birmingham"], + ["UK", "Birmingham"]] +p ary.stable_sort {|a, b| a[1] <=> b[1]} +# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]] +p ary.stable_sort_by {|x| x[1]} +# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]] diff --git a/Task/Sort-stability/Scala/sort-stability-1.scala b/Task/Sort-stability/Scala/sort-stability-1.scala new file mode 100644 index 0000000000..bdcb33ebb8 --- /dev/null +++ b/Task/Sort-stability/Scala/sort-stability-1.scala @@ -0,0 +1,19 @@ +scala> val list = List((1, 'c'), (1, 'b'), (2, 'a')) +list: List[(Int, Char)] = List((1,c), (1,b), (2,a)) + +scala> val srt1 = list.sortWith(_._2 < _._2) +srt1: List[(Int, Char)] = List((2,a), (1,b), (1,c)) + +scala> val srt2 = srt1.sortBy(_._1) // Ordering[Int] is implicitly defined +srt2: List[(Int, Char)] = List((1,b), (1,c), (2,a)) + +scala> val cities = """ + | |UK London + | |US New York + | |US Birmingham + | |UK Birmingham + | |""".stripMargin.lines.filterNot(_ isEmpty).toSeq +cities: Seq[String] = ArrayBuffer(UK London, US New York, US Birmingham, UK Birmingham) + +scala> cities.sortBy(_ substring 4) +res47: Seq[String] = ArrayBuffer(US Birmingham, UK Birmingham, UK London, US New York) diff --git a/Task/Sort-stability/Scala/sort-stability-2.scala b/Task/Sort-stability/Scala/sort-stability-2.scala new file mode 100644 index 0000000000..f5b016258c --- /dev/null +++ b/Task/Sort-stability/Scala/sort-stability-2.scala @@ -0,0 +1,7 @@ +scala> val cityArray = cities.toArray +cityArray: Array[String] = Array(UK London, US New York, US Birmingham, UK Birmingham) + +scala> scala.util.Sorting.stableSort(cityArray, (_: String).substring(4) < (_: String).substring(4)) + +scala> cityArray +res56: Array[String] = Array(US Birmingham, UK Birmingham, UK London, US New York) diff --git a/Task/Sort-using-a-custom-comparator/0DESCRIPTION b/Task/Sort-using-a-custom-comparator/0DESCRIPTION new file mode 100644 index 0000000000..ba874d5a10 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/0DESCRIPTION @@ -0,0 +1,4 @@ +{{omit from|BBC BASIC}} +Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. + +'''Note:''' Lexicographic order is case-insensitive. diff --git a/Task/Sort-using-a-custom-comparator/1META.yaml b/Task/Sort-using-a-custom-comparator/1META.yaml new file mode 100644 index 0000000000..556e45905d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting diff --git a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-1.ada b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-1.ada new file mode 100644 index 0000000000..d9846c6c08 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-1.ada @@ -0,0 +1,108 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Gnat.Heap_Sort_G; + +procedure Custom_Compare is + + type StringArrayType is array (Natural range <>) of Unbounded_String; + + Strings : StringArrayType := (Null_Unbounded_String, + To_Unbounded_String("this"), + To_Unbounded_String("is"), + To_Unbounded_String("a"), + To_Unbounded_String("set"), + To_Unbounded_String("of"), + To_Unbounded_String("strings"), + To_Unbounded_String("to"), + To_Unbounded_String("sort"), + To_Unbounded_String("This"), + To_Unbounded_String("Is"), + To_Unbounded_String("A"), + To_Unbounded_String("Set"), + To_Unbounded_String("Of"), + To_Unbounded_String("Strings"), + To_Unbounded_String("To"), + To_Unbounded_String("Sort")); + + procedure Move (From, To : in Natural) is + + begin + Strings(To) := Strings(From); + end Move; + + function UpCase (Char : in Character) return Character is + Temp : Character; + begin + if Char >= 'a' and Char <= 'z' then + Temp := Character'Val(Character'Pos(Char) + - Character'Pos('a') + + Character'Pos('A')); + else + Temp := Char; + end if; + return Temp; + end UpCase; + + function Lt (Op1, Op2 : Natural) + return Boolean is + Temp, Len : Natural; + begin + Len := Length(Strings(Op1)); + Temp := Length(Strings(Op2)); + if Len < Temp then + return False; + elsif Len > Temp then + return True; + end if; + + declare + S1, S2 : String(1..Len); + begin + S1 := To_String(Strings(Op1)); + S2 := To_String(Strings(Op2)); + Put("Same size: "); + Put(S1); + Put(" "); + Put(S2); + Put(" "); + for I in S1'Range loop + Put(UpCase(S1(I))); + Put(UpCase(S2(I))); + if UpCase(S1(I)) = UpCase(S2(I)) then + null; + elsif UpCase(S1(I)) < UpCase(S2(I)) then + Put(" LT"); + New_Line; + return True; + else + return False; + end if; + end loop; + Put(" GTE"); + New_Line; + return False; + end; + end Lt; + + procedure Put (Arr : in StringArrayType) is + begin + for I in 1..Arr'Length-1 loop + Put(To_String(Arr(I))); + New_Line; + end loop; + end Put; + + package Heap is new Gnat.Heap_Sort_G(Move, + Lt); + use Heap; + + +begin + Put_Line("Unsorted list:"); + Put(Strings); + New_Line; + Sort(16); + New_Line; + Put_Line("Sorted list:"); + Put(Strings); +end Custom_Compare; diff --git a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada new file mode 100644 index 0000000000..99f5706d8e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator-2.ada @@ -0,0 +1,35 @@ +Unsorted list: +this +is +a +set +of +strings +to +sort +This +Is +A +Set +Of +Strings +To +Sort + +Sorted list: +strings +Strings +sort +Sort +this +This +Set +set +is +Is +Of +of +to +To +a +A diff --git a/Task/Sort-using-a-custom-comparator/AutoHotkey/sort-using-a-custom-comparator.ahk b/Task/Sort-using-a-custom-comparator/AutoHotkey/sort-using-a-custom-comparator.ahk new file mode 100644 index 0000000000..ac4bc4fca0 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/AutoHotkey/sort-using-a-custom-comparator.ahk @@ -0,0 +1,14 @@ +numbers = 5,3,7,9,1,13,999,-4 +strings = Here,are,some,sample,strings,to,be,sorted +Sort, numbers, F IntegerSort D, +Sort, strings, F StringLengthSort D, +msgbox % numbers +msgbox % strings + +IntegerSort(a1, a2) { +return a2 - a1 +} + +StringLengthSort(a1, a2){ +return strlen(a1) - strlen(a2) +} diff --git a/Task/Sort-using-a-custom-comparator/Burlesque/sort-using-a-custom-comparator.blq b/Task/Sort-using-a-custom-comparator/Burlesque/sort-using-a-custom-comparator.blq new file mode 100644 index 0000000000..012d9271ef --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Burlesque/sort-using-a-custom-comparator.blq @@ -0,0 +1,4 @@ +blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}>< +{"ADD" "Abc" "Acb" "acb" "acc"} +blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb +{"Abc" "acb" "Acb" "acc" "ADD"} diff --git a/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp b/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp new file mode 100644 index 0000000000..53e0dd3a33 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/C++/sort-using-a-custom-comparator.cpp @@ -0,0 +1,28 @@ +#include <algorithm> +#include <string> +#include <cctype> + +// compare character case-insensitive +bool icompare_char(char c1, char c2) +{ + return std::toupper(c1) < std::toupper(c2); +} + +// return true if s1 comes before s2 +bool compare(std::string const& s1, std::string const& s2) +{ + if (s1.length() > s2.length()) + return true; + if (s1.length() < s2.length()) + return false; + return std::lexicographical_compare(s1.begin(), s1.end(), + s2.begin(), s2.end(), + icompare_char); +} + +int main() +{ + std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; + std::sort(strings, strings+8, compare); + return 0; +} diff --git a/Task/Sort-using-a-custom-comparator/C/sort-using-a-custom-comparator.c b/Task/Sort-using-a-custom-comparator/C/sort-using-a-custom-comparator.c new file mode 100644 index 0000000000..ea84973309 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/C/sort-using-a-custom-comparator.c @@ -0,0 +1,22 @@ +#include <stdlib.h> /* for qsort */ +#include <string.h> /* for strlen */ +#include <strings.h> /* for strcasecmp */ + +int mycmp(const void *s1, const void *s2) +{ + const char *l = *(const char **)s1, *r = *(const char **)s2; + size_t ll = strlen(l), lr = strlen(r); + + if (ll > lr) return -1; + if (ll < lr) return 1; + return strcasecmp(l, r); +} + +int main() +{ + const char *strings[] = { + "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }; + + qsort(strings, sizeof(strings)/sizeof(*strings), sizeof(*strings), mycmp); + return 0; +} diff --git a/Task/Sort-using-a-custom-comparator/Clean/sort-using-a-custom-comparator.clean b/Task/Sort-using-a-custom-comparator/Clean/sort-using-a-custom-comparator.clean new file mode 100644 index 0000000000..f0bcefa705 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Clean/sort-using-a-custom-comparator.clean @@ -0,0 +1,11 @@ +import StdEnv + +less s1 s2 + | size s1 > size s2 = True + | size s1 < size s2 = False + | otherwise = lower s1 < lower s2 +where + lower :: String -> String + lower s = {toLower c \\ c <-: s} + +Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"] diff --git a/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-1.clj b/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-1.clj new file mode 100644 index 0000000000..3f8e9e4748 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-1.clj @@ -0,0 +1,9 @@ +(defn rosetta-compare [s1 s2] + (let [len1 (count s1), len2 (count s2)] + (if (= len1 len2) + (compare (.toLowerCase s1) (.toLowerCase s2)) + (- len2 len1)))) + +(println + (sort rosetta-compare + ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"])) diff --git a/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-2.clj b/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-2.clj new file mode 100644 index 0000000000..578b31198d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Clojure/sort-using-a-custom-comparator-2.clj @@ -0,0 +1,2 @@ +(sort-by (juxt (comp - count) #(.toLowerCase %)) + ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]) diff --git a/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-1.lisp b/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-1.lisp new file mode 100644 index 0000000000..77e6ae6111 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-1.lisp @@ -0,0 +1,6 @@ +CL-USER> (defvar *strings* + '("Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter")) +*STRINGS* +CL-USER> (sort *strings* #'string-lessp) +("Actor" "Adam" "add" "apple" "base" "butter" "Cat" "Level" "quit" "Xmas" +"zero") diff --git a/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-2.lisp b/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-2.lisp new file mode 100644 index 0000000000..4a00687f6c --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Common-Lisp/sort-using-a-custom-comparator-2.lisp @@ -0,0 +1,6 @@ +CL-USER> (defvar *strings* + '("Cat" "apple" "Adam" "zero" "Xmas" "quit" "Level" "add" "Actor" "base" "butter")) +*STRINGS* +CL-USER> (sort *strings* #'> :key #'length) +("butter" "apple" "Level" "Actor" "Adam" "zero" "Xmas" "quit" "base" + "Cat" "add") 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 new file mode 100644 index 0000000000..6e90221c97 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator.d @@ -0,0 +1,7 @@ +import std.stdio, std.string, std.algorithm, std.typecons; + +void main() { + auto data = "here are Some sample strings to be sorted".split(); + data.schwartzSort!(s => tuple(-s.length, s.toUpper()))(); + writeln(data); +} diff --git a/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi b/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi new file mode 100644 index 0000000000..ba00b6d057 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Delphi/sort-using-a-custom-comparator.delphi @@ -0,0 +1,17 @@ +program SortWithCustomComparator; + +{$APPTYPE CONSOLE} + +uses SysUtils, Types, Generics.Collections, Generics.Defaults; + +var + lArray: TStringDynArray; +begin + lArray := TStringDynArray.Create('Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted'); + + TArray.Sort<string>(lArray , TDelegatedComparer<string>.Construct( + function(const Left, Right: string): Integer + begin + Result := Length(Right) - Length(Left); + end)); +end. diff --git a/Task/Sort-using-a-custom-comparator/E/sort-using-a-custom-comparator.e b/Task/Sort-using-a-custom-comparator/E/sort-using-a-custom-comparator.e new file mode 100644 index 0000000000..b49ca7750d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/E/sort-using-a-custom-comparator.e @@ -0,0 +1,8 @@ +/** returns a if it is nonzero, otherwise b() */ +def nonzeroOr(a, b) { return if (a.isZero()) { b() } else { a } } + +["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] \ + .sort(fn a, b { + nonzeroOr(b.size().op__cmp(a.size()), + fn { a.compareToIgnoreCase(b) }) + }) diff --git a/Task/Sort-using-a-custom-comparator/EGL/sort-using-a-custom-comparator.egl b/Task/Sort-using-a-custom-comparator/EGL/sort-using-a-custom-comparator.egl new file mode 100644 index 0000000000..802a824687 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/EGL/sort-using-a-custom-comparator.egl @@ -0,0 +1,37 @@ +program SortExample + + function main() + test1 string[] = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; + test1.sort(sortFunction); + + SysLib.writeStdout("Test 1:"); + for(i int from 1 to test1.getSize()) + SysLib.writeStdout(test1[i]); + end + + test2 string[] = ["Cat", "apple", "Adam", "zero", "Xmas", "quit", "Level", "add", "Actor", "base", "butter"]; + test2.sort(sortFunction); + + SysLib.writeStdout("Test 2:"); + for(i int from 1 to test2.getSize()) + SysLib.writeStdout(test2[i]); + end + end + + function sortFunction(a any in, b any in) returns (int) + result int = (b as string).length() - (a as string).length(); + if (result == 0) + case + when ((a as string).toLowerCase() > (b as string).toLowerCase()) + result = 1; + when ((a as string).toLowerCase() < (b as string).toLowerCase()) + result = -1; + otherwise + result = 0; + end + end + + return result; + end + +end diff --git a/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.euphoria b/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.euphoria new file mode 100644 index 0000000000..fc889cc54f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.euphoria @@ -0,0 +1,20 @@ +include sort.e +include wildcard.e +include misc.e + +function my_compare(sequence a, sequence b) + if length(a)!=length(b) then + return -compare(length(a),length(b)) + else + return compare(lower(a),lower(b)) + end if +end function + +sequence strings +strings = reverse({ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }) + +puts(1,"Unsorted:\n") +pretty_print(1,strings,{2}) + +puts(1,"\n\nSorted:\n") +pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2}) diff --git a/Task/Sort-using-a-custom-comparator/Factor/sort-using-a-custom-comparator.factor b/Task/Sort-using-a-custom-comparator/Factor/sort-using-a-custom-comparator.factor new file mode 100644 index 0000000000..2955d5eaa9 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Factor/sort-using-a-custom-comparator.factor @@ -0,0 +1,5 @@ +: my-compare ( s1 s2 -- <=> ) + 2dup [ length ] compare invert-comparison + dup +eq+ = [ drop [ >lower ] compare ] [ 2nip ] if ; + +{ "this" "is" "a" "set" "of" "strings" "to" "sort" } [ my-compare ] sort diff --git a/Task/Sort-using-a-custom-comparator/Fantom/sort-using-a-custom-comparator.fantom b/Task/Sort-using-a-custom-comparator/Fantom/sort-using-a-custom-comparator.fantom new file mode 100644 index 0000000000..7ac2ee3de2 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Fantom/sort-using-a-custom-comparator.fantom @@ -0,0 +1,20 @@ +class Main +{ + public static Void main () + { + // sample strings from Lisp example + strs := ["Cat", "apple", "Adam", "zero", "Xmas", "quit", + "Level", "add", "Actor", "base", "butter"] + + sorted := strs.dup // make a copy of original list + sorted.sort |Str a, Str b -> Int| // sort using custom comparator + { + if (b.size == a.size) // if size is same + return a.compareIgnoreCase(b) // then sort in ascending lexicographic order, ignoring case + else + return b.size <=> a.size // else sort in descending size order + } + echo ("Started with : " + strs.join(" ")) + echo ("Finished with: " + sorted.join(" ")) + } +} diff --git a/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-1.f b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-1.f new file mode 100644 index 0000000000..a1ae645768 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-1.f @@ -0,0 +1,33 @@ +module sorts_with_custom_comparator + implicit none +contains + subroutine a_sort(a, cc) + character(len=*), dimension(:), intent(inout) :: a + interface + integer function cc(a, b) + character(len=*), intent(in) :: a, b + end function cc + end interface + + integer :: i, j, increment + character(len=max(len(a), 10)) :: temp + + increment = size(a) / 2 + do while ( increment > 0 ) + do i = increment+1, size(a) + j = i + temp = a(i) + do while ( j >= increment+1 .and. cc(a(j-increment), temp) > 0) + a(j) = a(j-increment) + j = j - increment + end do + a(j) = temp + end do + if ( increment == 2 ) then + increment = 1 + else + increment = increment * 5 / 11 + end if + end do + end subroutine a_sort +end module sorts_with_custom_comparator diff --git a/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-2.f b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-2.f new file mode 100644 index 0000000000..054ca8c9c4 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-2.f @@ -0,0 +1,26 @@ +module comparators + implicit none +contains + integer function my_compare(a, b) + character(len=*), intent(in) :: a, b + + character(len=max(len(a),len(b))) :: a1, b1 + + a1 = a + b1 = b + call to_lower(b1) + call to_lower(a1) + + if ( len(trim(a)) > len(trim(b)) ) then + my_compare = -1 + elseif ( len(trim(a)) == len(trim(b)) ) then + if ( a1 > b1 ) then + my_compare = 1 + else + my_compare = -1 + end if + else + my_compare = 1 + end if + end function my_compare +end module comparators diff --git a/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-3.f b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-3.f new file mode 100644 index 0000000000..f7cab591d4 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Fortran/sort-using-a-custom-comparator-3.f @@ -0,0 +1,15 @@ +program CustomComparator + use comparators + use sorts_with_custom_comparator + implicit none + + character(len=100), dimension(8) :: str + integer :: i + + str = (/ "this", "is", "an", "array", "of", "strings", "to", "sort" /) + call a_sort(str, my_compare) + + do i = 1, size(str) + print *, trim(str(i)) + end do +end program CustomComparator diff --git a/Task/Sort-using-a-custom-comparator/Go/sort-using-a-custom-comparator.go b/Task/Sort-using-a-custom-comparator/Go/sort-using-a-custom-comparator.go new file mode 100644 index 0000000000..17f2e614bd --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Go/sort-using-a-custom-comparator.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "sort" + "strings" +) + +type sortable []string + +func (s sortable) Len() int { return len(s) } +func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s sortable) Less(i, j int) bool { + a, b := s[i], s[j] + if len(a) != len(b) { + return len(a) > len(b) + } + return strings.ToLower(a) < strings.ToLower(b) +} + +func main() { + var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") + fmt.Println(s, "(original)") + + sort.Sort(s) + fmt.Println(s, "(sorted)") +} diff --git a/Task/Sort-using-a-custom-comparator/Groovy/sort-using-a-custom-comparator.groovy b/Task/Sort-using-a-custom-comparator/Groovy/sort-using-a-custom-comparator.groovy new file mode 100644 index 0000000000..820f2bdc12 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Groovy/sort-using-a-custom-comparator.groovy @@ -0,0 +1,5 @@ +def strings = "Here are some sample strings to be sorted".split() +strings.sort { x, y -> + y.length() <=> x.length() ?: x.compareToIgnoreCase(y) +} +println strings diff --git a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs new file mode 100644 index 0000000000..4b46448ce4 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-1.hs @@ -0,0 +1,9 @@ +import List +import Char + +mycmp s1 s2 = case compare (length s2) (length s1) of + EQ -> compare (map toLower s1) (map toLower s2) + x -> x + +strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] +sorted = sortBy mycmp strings diff --git a/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs new file mode 100644 index 0000000000..bdd1e1e659 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Haskell/sort-using-a-custom-comparator-2.hs @@ -0,0 +1,3 @@ +import Data.Monoid +mycmp s1 s2 = mappend (compare (length s2) (length s1)) + (compare (map toLower s1) (map toLower s2)) diff --git a/Task/Sort-using-a-custom-comparator/Icon/sort-using-a-custom-comparator.icon b/Task/Sort-using-a-custom-comparator/Icon/sort-using-a-custom-comparator.icon new file mode 100644 index 0000000000..f974d32c08 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Icon/sort-using-a-custom-comparator.icon @@ -0,0 +1,13 @@ +procedure main() #: demonstrate various ways to sort a list and string + write("Sorting Demo for custom comparator") + L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] + write(" Unsorted Input : ") + every write(" ",image(!L)) + shellsort(L,cmptask) # most of the RC sorts will work here + write(" Sorted Output : ") + every write(" ",image(!L)) +end + +procedure cmptask(a,b) # sort by descending length and ascending lexicographic order for strings of equal length +if (*a > *b) | ((*a = *b) & (map(a) << map(b))) then return b +end diff --git a/Task/Sort-using-a-custom-comparator/J/sort-using-a-custom-comparator.j b/Task/Sort-using-a-custom-comparator/J/sort-using-a-custom-comparator.j new file mode 100644 index 0000000000..6b1d3cc048 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/J/sort-using-a-custom-comparator.j @@ -0,0 +1,7 @@ + mycmp=: 1 :'/:u' + length_and_lex =: (-@:# ; lower)&> + strings=: 'Here';'are';'some';'sample';'strings';'to';'be';'sorted' + length_and_lex mycmp strings ++-------+------+------+----+----+---+--+--+ +|strings|sample|sorted|Here|some|are|be|to| ++-------+------+------+----+----+---+--+--+ diff --git a/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-1.java b/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-1.java new file mode 100644 index 0000000000..a3237bd60f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-1.java @@ -0,0 +1,20 @@ +import java.util.Comparator; +import java.util.Arrays; + +public class Test { + public static void main(String[] args) { + String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; + + Arrays.sort(strings, new Comparator<String>() { + public int compare(String s1, String s2) { + int c = s2.length() - s1.length(); + if (c == 0) + c = s1.compareToIgnoreCase(s2); + return c; + } + }); + + for (String s: strings) + System.out.print(s + " "); + } +} diff --git a/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-2.java b/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-2.java new file mode 100644 index 0000000000..8c13afa958 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Java/sort-using-a-custom-comparator-2.java @@ -0,0 +1,18 @@ +import java.util.Comparator; +import java.util.Arrays; + +public class ComparatorTest { + public static void main(String[] args) { + String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; + + Arrays.sort(strings, (s1, s2) -> { + int c = s2.length() - s1.length(); + if (c == 0) + c = s1.compareToIgnoreCase(s2); + return c; + }); + + for (String s: strings) + System.out.print(s + " "); + } +} diff --git a/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator.js b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator.js new file mode 100644 index 0000000000..401dfab2d7 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/JavaScript/sort-using-a-custom-comparator.js @@ -0,0 +1,10 @@ +function lengthSorter(a, b) { + var result = b.length - a.length; + if (result == 0) + result = a.localeCompare(b); + return result; +} + +var test = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; +test.sort(lengthSorter); +alert( test.join(' ') ); // strings sample sorted Here some are be to diff --git a/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua b/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua new file mode 100644 index 0000000000..2210d8fc72 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua @@ -0,0 +1,7 @@ +function pair(a, b) return a[1] < b[1] end + +t = { +{2, 5}, {1, 6}, {4, 8}, {3, 2} +} +table.sort(t, pair) +for i, v in ipairs(t) do print(unpack(v)) end diff --git a/Task/Sort-using-a-custom-comparator/MAXScript/sort-using-a-custom-comparator.maxscript b/Task/Sort-using-a-custom-comparator/MAXScript/sort-using-a-custom-comparator.maxscript new file mode 100644 index 0000000000..011c5a8dbe --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/MAXScript/sort-using-a-custom-comparator.maxscript @@ -0,0 +1,23 @@ +fn myCmp str1 str2 = +( + case of + ( + (str1.count < str2.count): 1 + (str1.count > str2.count): -1 + default:( + -- String compare is case sensitive, name compare isn't. Hence... + str1 = str1 as name + str2 = str2 as name + case of + ( + (str1 > str2): 1 + (str1 < str2): -1 + default: 0 + ) + ) + ) +) + +strList = #("Here", "are", "some", "sample", "strings", "to", "be", "sorted") +qSort strList myCmp +print strList diff --git a/Task/Sort-using-a-custom-comparator/Mathematica/sort-using-a-custom-comparator.math b/Task/Sort-using-a-custom-comparator/Mathematica/sort-using-a-custom-comparator.math new file mode 100644 index 0000000000..4d26210113 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Mathematica/sort-using-a-custom-comparator.math @@ -0,0 +1,7 @@ +StringOrderQ[x_String, y_String] := + If[StringLength[x] == StringLength[y], + OrderedQ[{x, y}], + StringLength[x] >StringLength[y] + ] +words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"}; +Sort[words,StringOrderQ] diff --git a/Task/Sort-using-a-custom-comparator/Maxima/sort-using-a-custom-comparator.maxima b/Task/Sort-using-a-custom-comparator/Maxima/sort-using-a-custom-comparator.maxima new file mode 100644 index 0000000000..509f22e4b5 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Maxima/sort-using-a-custom-comparator.maxima @@ -0,0 +1,8 @@ +strangeorderp(a, b) := slength(a) > slength(b) or (slength(a) = slength(b) and orderlessp(a, b))$ +s: tokens("Lorem ipsum dolor sit amet consectetur adipiscing elit Sed non risus Suspendisse\ + lectus tortor dignissim sit amet adipiscing nec ultricies sed dolor")$ + +sort(s, strangeorderp); +["Suspendisse", "consectetur", "adipiscing", "adipiscing", "dignissim", "ultricies", +"lectus", "tortor", "Lorem", "dolor", "dolor", "ipsum", "risus", "amet", "amet", +"elit", "Sed", "nec", "non", "sed", "sit", "sit"] diff --git a/Task/Sort-using-a-custom-comparator/NetRexx/sort-using-a-custom-comparator.netrexx b/Task/Sort-using-a-custom-comparator/NetRexx/sort-using-a-custom-comparator.netrexx new file mode 100644 index 0000000000..b49018824f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/NetRexx/sort-using-a-custom-comparator.netrexx @@ -0,0 +1,32 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +-- ============================================================================= +class RSortCustomComparator public + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method main(args = String[]) public static + sample = [String 'Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted'] + say displayArray(sample) + Arrays.sort(sample, LengthComparator()) + say displayArray(sample) + return + +method displayArray(harry = String[]) constant + disp = '' + loop elmt over harry + disp = disp','elmt + end elmt + return '['disp.substr(2)']' -- trim leading comma + +-- ============================================================================= +class RSortCustomComparator.LengthComparator implements Comparator + +method compare(lft = Object, rgt = Object) public binary returns int + cRes = int + if lft <= String, rgt <= String then do + cRes = (String rgt).length - (String lft).length + if cRes == 0 then cRes = (String lft).compareToIgnoreCase(String rgt) + end + else signal IllegalArgumentException('Arguments must be Strings') + return cRes diff --git a/Task/Sort-using-a-custom-comparator/Nial/sort-using-a-custom-comparator.nial b/Task/Sort-using-a-custom-comparator/Nial/sort-using-a-custom-comparator.nial new file mode 100644 index 0000000000..2bbd74409f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Nial/sort-using-a-custom-comparator.nial @@ -0,0 +1,4 @@ +sort fork [=[tally first,tally last],up, >= [tally first,tally last]] ['Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted'] +=+-------+------+------+----+----+---+--+--+ +=|strings|sample|sorted|Here|some|are|be|to| +=+-------+------+------+----+----+---+--+--+ diff --git a/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-1.ocaml b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-1.ocaml new file mode 100644 index 0000000000..2c753e55f6 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-1.ocaml @@ -0,0 +1,5 @@ +let mycmp s1 s2 = + if String.length s1 <> String.length s2 then + compare (String.length s2) (String.length s1) + else + String.compare (String.lowercase s1) (String.lowercase s2) diff --git a/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-2.ocaml b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-2.ocaml new file mode 100644 index 0000000000..842319c0bb --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-2.ocaml @@ -0,0 +1,6 @@ +# let strings = ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"];; +val strings : string list = + ["Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"] +# List.sort mycmp strings;; +- : string list = +["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"] diff --git a/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-3.ocaml b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-3.ocaml new file mode 100644 index 0000000000..ec1de5daf8 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/OCaml/sort-using-a-custom-comparator-3.ocaml @@ -0,0 +1,8 @@ +# let strings = [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|];; +val strings : string array = + [|"Here"; "are"; "some"; "sample"; "strings"; "to"; "be"; "sorted"|] +# Array.sort mycmp strings;; +- : unit = () +# strings;; +- : string array = +[|"strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"|] diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m new file mode 100644 index 0000000000..2139172286 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-1.m @@ -0,0 +1,28 @@ +#import <Foundation/Foundation.h> + +#define esign(X) (((X)>0)?1:(((X)<0)?-1:0)) + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSMutableArray *arr = + [NSMutableArray + arrayWithArray: [@"this is a set of strings to sort" + componentsSeparatedByString: @" "] + ]; + + [arr sortUsingComparator: ^NSComparisonResult(id obj1, id obj2){ + NSComparisonResult l = esign((int)([obj1 length] - [obj2 length])); + return l ? -l // reverse the ordering + : [obj1 caseInsensitiveCompare: obj2]; + }]; + + for( NSString *str in arr ) + { + NSLog(@"%@", str); + } + + [pool release]; + return EXIT_SUCCESS; +} diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m new file mode 100644 index 0000000000..7f785c63d6 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-2.m @@ -0,0 +1,38 @@ +#import <Foundation/Foundation.h> + +@interface NSString (CustomComp) +- (NSComparisonResult)my_compare: (id)obj; +@end + +#define esign(X) (((X)>0)?1:(((X)<0)?-1:0)) +@implementation NSString (CustomComp) +- (NSComparisonResult)my_compare: (id)obj +{ + NSComparisonResult l = esign((int)([self length] - [obj length])); + return l ? -l // reverse the ordering + : [self caseInsensitiveCompare: obj]; +} +@end + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSMutableArray *arr = + [NSMutableArray + arrayWithArray: [@"this is a set of strings to sort" + componentsSeparatedByString: @" "] + ]; + + [arr sortUsingSelector: @selector(my_compare:)]; + + NSEnumerator *iter = [arr objectEnumerator]; + NSString *str; + while( (str = [iter nextObject]) != nil ) + { + NSLog(@"%@", str); + } + + [pool release]; + return EXIT_SUCCESS; +} diff --git a/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m new file mode 100644 index 0000000000..788f0774db --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Objective-C/sort-using-a-custom-comparator-3.m @@ -0,0 +1,22 @@ +#import <Foundation/Foundation.h> + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + NSArray *strings = [@"Here are some sample strings to be sorted" componentsSeparatedByString:@" "]; + + NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]; + NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"lowercaseString" ascending:YES]; + + NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil]; + [sd1 release]; + [sd2 release]; + + NSArray *sorted = [strings sortedArrayUsingDescriptors:sortDescriptors]; + NSLog(@"%@", sorted); + + [pool release]; + + return 0; +} diff --git a/Task/Sort-using-a-custom-comparator/Oz/sort-using-a-custom-comparator.oz b/Task/Sort-using-a-custom-comparator/Oz/sort-using-a-custom-comparator.oz new file mode 100644 index 0000000000..3eb3a9048e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Oz/sort-using-a-custom-comparator.oz @@ -0,0 +1,21 @@ +declare + fun {LexicographicLessThan Xs Ys} + for + X in {Map Xs Char.toLower} + Y in {Map Ys Char.toLower} + return:Return + default:{Length Xs}<{Length Ys} + do + if X < Y then {Return true} end + end + end + + fun {LessThan Xs Ys} + {Length Xs} > {Length Ys} + orelse + {Length Xs} == {Length Ys} andthen {LexicographicLessThan Xs Ys} + end + + Strings = ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"] +in + {ForAll {Sort Strings LessThan} System.showInfo} diff --git a/Task/Sort-using-a-custom-comparator/PARI-GP/sort-using-a-custom-comparator.pari b/Task/Sort-using-a-custom-comparator/PARI-GP/sort-using-a-custom-comparator.pari new file mode 100644 index 0000000000..91cb93a3f2 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PARI-GP/sort-using-a-custom-comparator.pari @@ -0,0 +1,2 @@ +cmp(a,b)=if(#a<#b,1,if(#a>#b,-1,lex(a,b))); +vecsort(v,cmp) diff --git a/Task/Sort-using-a-custom-comparator/PHP/sort-using-a-custom-comparator.php b/Task/Sort-using-a-custom-comparator/PHP/sort-using-a-custom-comparator.php new file mode 100644 index 0000000000..ff76466602 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PHP/sort-using-a-custom-comparator.php @@ -0,0 +1,11 @@ +<?php +function mycmp($s1, $s2) +{ + if ($d = strlen($s2) - strlen($s1)) + return $d; + return strcasecmp($s1, $s2); +} + +$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); +usort($strings, "mycmp"); +?> diff --git a/Task/Sort-using-a-custom-comparator/PL-I/sort-using-a-custom-comparator.pli b/Task/Sort-using-a-custom-comparator/PL-I/sort-using-a-custom-comparator.pli new file mode 100644 index 0000000000..207202fe9e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PL-I/sort-using-a-custom-comparator.pli @@ -0,0 +1,70 @@ +MRGEPKG: package exports(MERGESORT,MERGE,RMERGE); + +DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */ + +MERGE: PROCEDURE (A,LA,B,LB,C,CMPFN); + DECLARE (A(*),B(*),C(*)) CHAR(*) VAR; + DECLARE (LA,LB) FIXED BIN(31) NONASGN; + DECLARE (I,J,K) FIXED BIN(31); + DECLARE CMPFN ENTRY( + NONASGN CHAR(*) VAR, + NONASGN CHAR(*) VAR) + RETURNS (FIXED bin(31)); + + I=1; J=1; K=1; + DO WHILE ((I <= LA) & (J <= LB)); + IF CMPFN(A(I),B(J)) <= 0 THEN + DO; C(K)=A(I); K=K+1; I=I+1; END; + ELSE + DO; C(K)=B(J); K=K+1; J=J+1; END; + END; + DO WHILE (I <= LA); + C(K)=A(I); I=I+1; K=K+1; + END; + return; +END MERGE; + +MERGESORT: PROCEDURE (A,N,CMPFN) RECURSIVE ; + DECLARE (A(*)) CHAR(*) VAR; + DECLARE N FIXED BINARY(31) NONASGN; + DECLARE CMPFN ENTRY( + NONASGN CHAR(*) VAR, + NONASGN CHAR(*) VAR) + RETURNS (FIXED bin(31)); + DECLARE (M,I) FIXED BINARY; + DECLARE AMP1(N) CHAR(20) VAR BASED(P); + DECLARE P POINTER; + + IF (N=1) THEN RETURN; + M = trunc((N+1)/2); + IF M > 1 THEN CALL MERGESORT(A,M,CMPFN); + P=ADDR(A(M+1)); + IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M,CMPFN); + IF CMPFN(A(M),AMP1(1)) <= 0 THEN RETURN; + DO I=1 to M; T(I)=A(I); END; + CALL MERGE(T,M,AMP1,N-M,A,CMPFN); +END MERGESORT; + +RMERGE: PROC OPTIONS(MAIN); +DCL I FIXED BIN(31); +DCL A(8) CHAR(20) VAR INIT("this","is","a","set","of","strings","to","sort"); + +MyCMP: PROCEDURE(A,B) RETURNS (FIXED BIN(31)); + DCL (A,B) CHAR(*) VAR NONASGN; + DCL (I,J) FIXED BIN(31); + + I = length(trim(A)); J = length(trim(B)); + IF I < J THEN RETURN(+1); + IF I > J THEN RETURN(-1); + IF lowercase(A) < lowercase(B) THEN RETURN(-1); + IF lowercase(A) > lowercase(B) THEN RETURN(+1); + RETURN (0); +END MyCMP; + +CALL MERGESORT(A,8,MyCMP); +DO I=1 TO 8; + put edit (I,A(I)) (F(5),X(2),A(10)) skip; +END; + +put skip; +END RMERGE; diff --git a/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-1.pl6 b/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-1.pl6 new file mode 100644 index 0000000000..0d6ae4c895 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-1.pl6 @@ -0,0 +1,3 @@ +my @strings = <Here are some sample strings to be sorted>; +my @sorted_strings = sort { $^a.chars <=> $^b.chars or $^a.lc cmp $^b.lc }, @strings; +.say for @sorted_strings; diff --git a/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-2.pl6 b/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-2.pl6 new file mode 100644 index 0000000000..28a0cf482b --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator-2.pl6 @@ -0,0 +1 @@ +my @sorted_strings = sort -> $x { [ $x.chars, $x.lc ] }, @strings; diff --git a/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-1.pl b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-1.pl new file mode 100644 index 0000000000..5385d10e9e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-1.pl @@ -0,0 +1,4 @@ +sub mycmp { length $b <=> length $a || lc $a cmp lc $b } + +my @strings = ("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); +my @sorted = sort mycmp @strings; diff --git a/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-2.pl b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-2.pl new file mode 100644 index 0000000000..14fb1a7568 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-2.pl @@ -0,0 +1,2 @@ +my @strings = qw/here are some sample strings to be sorted/; +my @sorted = sort {length $b <=> length $a || lc $a cmp lc $b} @strings diff --git a/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-3.pl b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-3.pl new file mode 100644 index 0000000000..cccf2bc28a --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Perl/sort-using-a-custom-comparator-3.pl @@ -0,0 +1,5 @@ +my @strings = qw/here are some sample strings to be sorted/; +my @sorted = map { $_->[0] } + sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] } + map { [ $_, length, lc ] } + @strings; diff --git a/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-1.l b/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-1.l new file mode 100644 index 0000000000..0c61e90984 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-1.l @@ -0,0 +1,2 @@ +: (sort '("def" "abc" "ghi") >) +-> ("ghi" "def" "abc") diff --git a/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-2.l b/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-2.l new file mode 100644 index 0000000000..fa15a032bc --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PicoLisp/sort-using-a-custom-comparator-2.l @@ -0,0 +1,2 @@ +: (flip (sort '("def" "abc" "ghi"))) +-> ("ghi" "def" "abc") diff --git a/Task/Sort-using-a-custom-comparator/Pop11/sort-using-a-custom-comparator.pop11 b/Task/Sort-using-a-custom-comparator/Pop11/sort-using-a-custom-comparator.pop11 new file mode 100644 index 0000000000..4db6ca7a64 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Pop11/sort-using-a-custom-comparator.pop11 @@ -0,0 +1,21 @@ +lvars ls = ['Here' 'are' 'some' 'sample' 'strings' 'to' 'be' 'sorted']; +define compare(s1, s2); +lvars k = length(s2) - length(s1); +if k < 0 then + return(true); +elseif k > 0 then + return(false); +else + return (alphabefore(uppertolower(s1), uppertolower(s2))); +endif; +enddefine; + +syssort(ls, compare) -> ls; + +NOTE: The definition of compare can also be written thus: +define compare(s1, s2); + lvars + l1 = length(s1), + l2 = length(s2); + l1 > l2 or (l1 == l2 and alphabefore(uppertolower(s1), uppertolower(s2))) +enddefine; diff --git a/Task/Sort-using-a-custom-comparator/PowerBASIC/sort-using-a-custom-comparator.powerbasic b/Task/Sort-using-a-custom-comparator/PowerBASIC/sort-using-a-custom-comparator.powerbasic new file mode 100644 index 0000000000..df03b795d6 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PowerBASIC/sort-using-a-custom-comparator.powerbasic @@ -0,0 +1,26 @@ +FUNCTION Sorter(p1 AS STRING, p2 AS STRING) AS LONG + 'if p1 should be first, returns -1 + 'if p2 should be first, returns 1 + ' if they're equal, returns 0 + IF LEN(p1) > LEN(p2) THEN + FUNCTION = -1 + ELSEIF LEN(p2) > LEN(p1) THEN + FUNCTION = 1 + ELSEIF UCASE$(p1) > UCASE$(p2) THEN + 'if we get here, they're of equal length, + 'so now we're doing a "normal" string comparison + FUNCTION = -1 + ELSEIF UCASE$(p2) > UCASE$(p1) THEN + FUNCTION = 1 + ELSE + FUNCTION = 0 + END IF +END FUNCTION + +FUNCTION PBMAIN() + DIM x(7) AS STRING + ARRAY ASSIGN x() = "Here", "are", "some", "sample", "strings", "to", "be", "sorted" + + 'pb's built-in sorting; "USING" tells it to use our custom comparator + ARRAY SORT x(), USING Sorter() +END FUNCTION diff --git a/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.psh b/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.psh new file mode 100644 index 0000000000..b4e63cb3c3 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.psh @@ -0,0 +1,2 @@ +$list = "Here", "are", "some", "sample", "strings", "to", "be", "sorted" +$list | Sort-Object {-$_.Length},{$_} diff --git a/Task/Sort-using-a-custom-comparator/Prolog/sort-using-a-custom-comparator.pro b/Task/Sort-using-a-custom-comparator/Prolog/sort-using-a-custom-comparator.pro new file mode 100644 index 0000000000..757b6a486f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Prolog/sort-using-a-custom-comparator.pro @@ -0,0 +1,18 @@ +rosetta_sort :- + L = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted" ], + predsort(my_comp, L, L1), + writeln('Input list :'), + maplist(my_write, L), nl,nl, + writeln('Sorted list :'), + maplist(my_write, L1). + + +my_comp(Comp, W1, W2) :- + length(W1,L1), + length(W2, L2), + ( L1 < L2 -> Comp = '>' + ; L1 > L2 -> Comp = '<' + ; compare(Comp, W1, W2)). + +my_write(W) :- + format('~s ', [W]). diff --git a/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-1.py b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-1.py new file mode 100644 index 0000000000..b37005fdac --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-1.py @@ -0,0 +1,6 @@ +strings = "here are Some sample strings to be sorted".split() + +def mykey(x): + return -len(x), x.upper() + +print sorted(strings, key=mykey) diff --git a/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-2.py b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-2.py new file mode 100644 index 0000000000..548999193f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-2.py @@ -0,0 +1 @@ +['strings', 'sample', 'sorted', 'here', 'Some', 'are', 'be', 'to'] diff --git a/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-3.py b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-3.py new file mode 100644 index 0000000000..d52ac3573d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Python/sort-using-a-custom-comparator-3.py @@ -0,0 +1,4 @@ +def mycmp(s1, s2): + return cmp(len(s2), len(s1)) or cmp(s1.upper(), s2.upper()) + +print sorted(strings, cmp=mycmp) diff --git a/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-1.rb b/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-1.rb new file mode 100644 index 0000000000..846f6b64b2 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-1.rb @@ -0,0 +1,2 @@ +words = %w(Here are some sample strings to be sorted) +p words.sort_by {|word| [-word.size, word.downcase]} diff --git a/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-2.rb b/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-2.rb new file mode 100644 index 0000000000..1580ad82b9 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ruby/sort-using-a-custom-comparator-2.rb @@ -0,0 +1,2 @@ +p words.sort {|a, b| d = b.size <=> a.size + d != 0 ? d : a.upcase <=> b.upcase} diff --git a/Task/Sort-using-a-custom-comparator/Sather/sort-using-a-custom-comparator.sa b/Task/Sort-using-a-custom-comparator/Sather/sort-using-a-custom-comparator.sa new file mode 100644 index 0000000000..9fa8547a9e --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Sather/sort-using-a-custom-comparator.sa @@ -0,0 +1,15 @@ +class MAIN is + + custom_comp(a, b:STR):BOOL is + l ::= a.length - b.length; + if l = 0 then return a.lower < b.lower; end; + return l > 0; + end; + + main is + s:ARRAY{STR} := |"this", "is", "an", "array", "of", "strings", "to", "sort"|; + + s.insertion_sort_by(bind(custom_comp(_,_))); + loop #OUT + s.elt! + "\n"; end; + end; +end; diff --git a/Task/Sort-using-a-custom-comparator/Scala/sort-using-a-custom-comparator.scala b/Task/Sort-using-a-custom-comparator/Scala/sort-using-a-custom-comparator.scala new file mode 100644 index 0000000000..c28281ce14 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Scala/sort-using-a-custom-comparator.scala @@ -0,0 +1,4 @@ +List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) => + val cmp=a.size-b.size + (if (cmp==0) -a.compareTo(b) else cmp) > 0 +} diff --git a/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss new file mode 100644 index 0000000000..e210478a19 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-1.ss @@ -0,0 +1,10 @@ +(use srfi-13);;Syntax for module inclusion depends on implementation, +;;as does the presence of a sort function. +(define (mypred? a b) + (let ((len-a (string-length a)) + (len-b (string-length b))) + (if (= len-a len-b) + (string>? (string-downcase b) (string-downcase a)) + (> len-a len-b)))) + +(sort '("sorted" "here" "strings" "sample" "Some" "are" "be" "to") mypred?) diff --git a/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-2.ss b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-2.ss new file mode 100644 index 0000000000..5b29de2d7a --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-2.ss @@ -0,0 +1 @@ +("strings" "sample" "sorted" "here" "Some" "are" "be" "to") diff --git a/Task/Sort-using-a-custom-comparator/Slate/sort-using-a-custom-comparator.slate b/Task/Sort-using-a-custom-comparator/Slate/sort-using-a-custom-comparator.slate new file mode 100644 index 0000000000..5e216bb8a3 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Slate/sort-using-a-custom-comparator.slate @@ -0,0 +1,2 @@ +define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)'). +words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative] diff --git a/Task/Sort-using-a-custom-comparator/Smalltalk/sort-using-a-custom-comparator.st b/Task/Sort-using-a-custom-comparator/Smalltalk/sort-using-a-custom-comparator.st new file mode 100644 index 0000000000..214adb257d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Smalltalk/sort-using-a-custom-comparator.st @@ -0,0 +1,5 @@ +#('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)' ) asSortedCollection + sortBlock: + [:first :second | (second size = first size) + ifFalse: [second size < first size] + ifTrue: [first < second]] diff --git a/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-1.ml b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-1.ml new file mode 100644 index 0000000000..7567b33a0d --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-1.ml @@ -0,0 +1,5 @@ +fun mygt (s1, s2) = + if size s1 <> size s2 then + size s2 > size s1 + else + String.map Char.toLower s1 > String.map Char.toLower s2 diff --git a/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-2.ml b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-2.ml new file mode 100644 index 0000000000..1a80c5ebf4 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-2.ml @@ -0,0 +1,6 @@ +- val strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; +val strings = ["Here","are","some","sample","strings","to","be","sorted"] + : string list +- ListMergeSort.sort mygt strings; +val it = ["strings","sample","sorted","Here","some","are","be","to"] + : string list diff --git a/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-3.ml b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-3.ml new file mode 100644 index 0000000000..789e325f75 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-3.ml @@ -0,0 +1,5 @@ +fun mycmp (s1, s2) = + if size s1 <> size s2 then + Int.compare (size s2, size s1) + else + String.compare (String.map Char.toLower s1, String.map Char.toLower s2) diff --git a/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-4.ml b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-4.ml new file mode 100644 index 0000000000..e10228fb35 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Standard-ML/sort-using-a-custom-comparator-4.ml @@ -0,0 +1,8 @@ +- val strings = Array.fromList ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; +val strings = [|"Here","are","some","sample","strings","to","be","sorted"|] + : string array +- ArrayQSort.sort mycmp strings; +val it = () : unit +- strings; +val it = [|"strings","sample","sorted","Here","some","are","be","to"|] + : string array diff --git a/Task/Sort-using-a-custom-comparator/TUSCRIPT/sort-using-a-custom-comparator.tuscript b/Task/Sort-using-a-custom-comparator/TUSCRIPT/sort-using-a-custom-comparator.tuscript new file mode 100644 index 0000000000..13e1072904 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/TUSCRIPT/sort-using-a-custom-comparator.tuscript @@ -0,0 +1,13 @@ +$$ MODE TUSCRIPT +setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort" +unsorted=SPLIT (setofstrings,": :") +PRINT "1. setofstrings unsorted" +index="" +LOOP l=unsorted +PRINT l +length=LENGTH (l),index=APPEND(index,length) +ENDLOOP +index =DIGIT_INDEX (index) +sorted=INDEX_SORT (unsorted,index) +PRINT "2. setofstrings sorted" +*{sorted} diff --git a/Task/Sort-using-a-custom-comparator/Tcl/sort-using-a-custom-comparator.tcl b/Task/Sort-using-a-custom-comparator/Tcl/sort-using-a-custom-comparator.tcl new file mode 100644 index 0000000000..8d7ab18e49 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Tcl/sort-using-a-custom-comparator.tcl @@ -0,0 +1,13 @@ +proc sorter {a b} { + set la [string length $a] + set lb [string length $b] + if {$la < $lb} { + return 1 + } elseif {$la > $lb} { + return -1 + } + return [string compare [string tolower $a] [string tolower $b]] +} + +set strings {here are Some sample strings to be sorted} +lsort -command sorter $strings ;# ==> strings sample sorted here Some are be to diff --git a/Task/Sort-using-a-custom-comparator/Ursala/sort-using-a-custom-comparator.ursala b/Task/Sort-using-a-custom-comparator/Ursala/sort-using-a-custom-comparator.ursala new file mode 100644 index 0000000000..d1d1f2dd86 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ursala/sort-using-a-custom-comparator.ursala @@ -0,0 +1,6 @@ +#import std +#show+ + +data = <'this','is','a','list','of','strings','to','be','sorted'> + +example = psort<not leql,lleq+ ~* ~&K31K30piK26 letters> data diff --git a/Task/Sort-using-a-custom-comparator/Visual-Basic-.NET/sort-using-a-custom-comparator.visual b/Task/Sort-using-a-custom-comparator/Visual-Basic-.NET/sort-using-a-custom-comparator.visual new file mode 100644 index 0000000000..2ee79bccae --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Visual-Basic-.NET/sort-using-a-custom-comparator.visual @@ -0,0 +1,18 @@ +Imports System + +Module Sorting_Using_a_Custom_Comparator + Function CustomComparator(ByVal x As String, ByVal y As String) As Integer + Dim result As Integer + result = y.Length - x.Length + If result = 0 Then + result = String.Compare(x, y, True) + End If + Return result + End Function + + Sub Main() + Dim strings As String() = {"test", "Zoom", "strings", "a"} + + Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator)) + End Sub +End Module diff --git a/Task/Sorting-algorithms-Bead-sort/0DESCRIPTION b/Task/Sorting-algorithms-Bead-sort/0DESCRIPTION new file mode 100644 index 0000000000..df3edab475 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/0DESCRIPTION @@ -0,0 +1,4 @@ +{{Sorting Algorithm}} +In this task, the goal is to sort an array of positive integers using the [[wp:Bead_sort|Bead Sort Algorithm]]. + +Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations. diff --git a/Task/Sorting-algorithms-Bead-sort/1META.yaml b/Task/Sorting-algorithms-Bead-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Bead-sort/C++/sorting-algorithms-bead-sort.cpp b/Task/Sorting-algorithms-Bead-sort/C++/sorting-algorithms-bead-sort.cpp new file mode 100644 index 0000000000..d9c51fdb54 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/C++/sorting-algorithms-bead-sort.cpp @@ -0,0 +1,49 @@ +//this algorithm only works with positive, whole numbers. +//O(2n) time complexity where n is the summation of the whole list to be sorted. +//O(3n) space complexity. + +#include <iostream> +#include <vector> + +using std::cout; +using std::vector; + +void distribute(int dist, vector<int> &List) { + //*beads* go down into different buckets using gravity (addition). + if (dist > List.size() ) + List.resize(dist); //resize if too big for current vector + + for (int i=0; i < dist; i++) + List[i]++; +} + +vector<int> beadSort(int *myints, int n) { + vector<int> list, list2, fifth (myints, myints + n); + + cout << "#1 Beads falling down: "; + for (int i=0; i < fifth.size(); i++) + distribute (fifth[i], list); + cout << '\n'; + + cout << "\nBeads on their sides: "; + for (int i=0; i < list.size(); i++) + cout << " " << list[i]; + cout << '\n'; + + //second part + + cout << "#2 Beads right side up: "; + for (int i=0; i < list.size(); i++) + distribute (list[i], list2); + cout << '\n'; + + return list2; +} + +int main() { + int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; + vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); + cout << "Sorted list/array: "; + for(unsigned int i=0; i<sorted.size(); i++) + cout << sorted[i] << ' '; +} diff --git a/Task/Sorting-algorithms-Bead-sort/C/sorting-algorithms-bead-sort.c b/Task/Sorting-algorithms-Bead-sort/C/sorting-algorithms-bead-sort.c new file mode 100644 index 0000000000..3b00801dd1 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/C/sorting-algorithms-bead-sort.c @@ -0,0 +1,47 @@ +#include <stdio.h> +#include <stdlib.h> + +void bead_sort(int *a, int len) +{ + int i, j, max, sum; + unsigned char *beads; +# define BEAD(i, j) beads[i * max + j] + + for (i = 1, max = a[0]; i < len; i++) + if (a[i] > max) max = a[i]; + + beads = calloc(1, max * len); + + /* mark the beads */ + for (i = 0; i < len; i++) + for (j = 0; j < a[i]; j++) + BEAD(i, j) = 1; + + for (j = 0; j < max; j++) { + /* count how many beads are on each post */ + for (sum = i = 0; i < len; i++) { + sum += BEAD(i, j); + BEAD(i, j) = 0; + } + /* mark bottom sum beads */ + for (i = len - sum; i < len; i++) BEAD(i, j) = 1; + } + + for (i = 0; i < len; i++) { + for (j = 0; j < max && BEAD(i, j); j++); + a[i] = j; + } + free(beads); +} + +int main() +{ + int i, x[] = {5, 3, 1, 7, 4, 1, 1, 20}; + int len = sizeof(x)/sizeof(x[0]); + + bead_sort(x, len); + for (i = 0; i < len; i++) + printf("%d\n", x[i]); + + return 0; +} diff --git a/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj b/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj new file mode 100644 index 0000000000..1daa5d308f --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Clojure/sorting-algorithms-bead-sort.clj @@ -0,0 +1,14 @@ +(defn transpose [xs] + (loop [transposed [], remaining xs] + (if (empty? remaining) + transposed + (recur + (conj transposed (map #(first %) remaining)) + (filter #(not-empty %) (map #(rest %) remaining)))) )) + +(defn bead-sort [xs] + (map #(reduce + %) + (transpose + (transpose (map #(replicate % 1) xs))))) + +(println (bead-sort [5 2 4 1 3 3 9])) diff --git a/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d b/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d new file mode 100644 index 0000000000..02d80945c1 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d @@ -0,0 +1,20 @@ +import std.stdio, std.algorithm, std.range, std.array, std.functional; + +alias repeat0 = curry!(repeat, 0); + +// Currenty std.range.transposed doesn't work. +auto columns(R)(R m) /*pure nothrow*/ { + return m + .map!walkLength + .reduce!max + .iota + .map!(i => m.filter!(s => s.length > i).walkLength.repeat0); +} + +auto beadSort(in uint[] data) /*pure nothrow*/ { + return data.map!repeat0.columns.columns.map!walkLength; +} + +void main() { + [5, 3, 1, 7, 4, 1, 1].beadSort.writeln; +} diff --git a/Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.delphi b/Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.delphi new file mode 100644 index 0000000000..d3d7b410e8 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.delphi @@ -0,0 +1,66 @@ +program BeadSortTest; + +{$APPTYPE CONSOLE} + +uses + SysUtils; + +procedure BeadSort(var a : array of integer); +var + i, j, max, sum : integer; + beads : array of array of integer; +begin + max := a[Low(a)]; + for i := Low(a) + 1 to High(a) do + if a[i] > max then + max := a[i]; + + SetLength(beads, High(a) - Low(a) + 1, max); + + // mark the beads + + for i := Low(a) to High(a) do + for j := 0 to a[i] - 1 do + beads[i, j] := 1; + + for j := 0 to max - 1 do + begin + // count how many beads are on each post + sum := 0; + for i := Low(a) to High(a) do + begin + sum := sum + beads[i, j]; + beads[i, j] := 0; + end; + //mark bottom sum beads + for i := High(a) + 1 - sum to High(a) do + beads[i, j] := 1; + end; + + for i := Low(a) to High(a) do + begin + j := 0; + while (j < max) and (beads[i, j] <> 0) do + inc(j); + a[i] := j; + end; + + SetLength(beads, 0, 0); +end; + +const + N = 8; +var + i : integer; + x : array[1..N] of integer = (5, 3, 1, 7, 4, 1, 1, 20); +begin + for i := 1 to N do + writeln(Format('x[%d] = %d', [i, x[i]])); + + BeadSort(x); + + for i := 1 to N do + writeln(Format('x[%d] = %d', [i, x[i]])); + + readln; +end. diff --git a/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-1.factor b/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-1.factor new file mode 100644 index 0000000000..39365f79ab --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-1.factor @@ -0,0 +1,9 @@ +USING: kernel math math.order math.vectors sequences ; +: fill ( seq len -- newseq ) [ dup length ] dip swap - 0 <repetition> append ; + +: bead ( seq -- newseq ) +dup 0 [ max ] reduce +[ swap 1 <repetition> swap fill ] curry map +[ ] [ v+ ] map-reduce ; + +: beadsort ( seq -- newseq ) bead bead ; diff --git a/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-2.factor b/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-2.factor new file mode 100644 index 0000000000..727f40b7c7 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Factor/sorting-algorithms-bead-sort-2.factor @@ -0,0 +1,2 @@ +( scratchpad ) { 5 2 4 1 3 3 9 } beadsort . +{ 9 5 4 3 3 2 1 } diff --git a/Task/Sorting-algorithms-Bead-sort/Fortran/sorting-algorithms-bead-sort.f b/Task/Sorting-algorithms-Bead-sort/Fortran/sorting-algorithms-bead-sort.f new file mode 100644 index 0000000000..d2fd2a3b7d --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Fortran/sorting-algorithms-bead-sort.f @@ -0,0 +1,41 @@ +program BeadSortTest + use iso_fortran_env + ! for ERROR_UNIT; to make this a F95 code, + ! remove prev. line and declare ERROR_UNIT as an + ! integer parameter matching the unit associated with + ! standard error + + integer, dimension(7) :: a = (/ 7, 3, 5, 1, 2, 1, 20 /) + + call beadsort(a) + print *, a + +contains + + subroutine beadsort(a) + integer, dimension(:), intent(inout) :: a + + integer, dimension(maxval(a), maxval(a)) :: t + integer, dimension(maxval(a)) :: s + integer :: i, m + + m = maxval(a) + + if ( any(a < 0) ) then + write(ERROR_UNIT,*) "can't sort" + return + end if + + t = 0 + forall(i=1:size(a)) t(i, 1:a(i)) = 1 ! set up abacus + forall(i=1:m) ! let beads "fall"; instead of + s(i) = sum(t(:, i)) ! moving them one by one, we just + t(:, i) = 0 ! count how many should be at bottom, + t(1:s(i), i) = 1 ! and then "reset" and set only those + end forall + + forall(i=1:size(a)) a(i) = sum(t(i,:)) + + end subroutine beadsort + +end program BeadSortTest diff --git a/Task/Sorting-algorithms-Bead-sort/Go/sorting-algorithms-bead-sort.go b/Task/Sorting-algorithms-Bead-sort/Go/sorting-algorithms-bead-sort.go new file mode 100644 index 0000000000..7556b28168 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Go/sorting-algorithms-bead-sort.go @@ -0,0 +1,74 @@ +package main + +import ( + "fmt" + "sync" +) + +var a = []int{170, 45, 75, 90, 802, 24, 2, 66} +var aMax = 1000 + +const bead = 'o' + +func main() { + fmt.Println("before:", a) + beadSort() + fmt.Println("after: ", a) +} + +func beadSort() { + // All space in the abacus = aMax poles x len(a) rows. + all := make([]byte, aMax*len(a)) + // Slice up space by pole. (The space could be sliced by row instead, + // but slicing by pole seemed a more intuitive model of a physical abacus.) + abacus := make([][]byte, aMax) + for pole, space := 0, all; pole < aMax; pole++ { + abacus[pole] = space[:len(a)] + space = space[len(a):] + } + // Use a sync.Waitgroup as the checkpoint mechanism. + var wg sync.WaitGroup + // Place beads for each number concurrently. (Presumably beads can be + // "snapped on" to the middle of a pole without disturbing neighboring + // beads.) Also note 'row' here is a row of the abacus. + wg.Add(len(a)) + for row, n := range a { + go func(row, n int) { + for pole := 0; pole < n; pole++ { + abacus[pole][row] = bead + } + wg.Done() + }(row, n) + } + wg.Wait() + // Now tip the abacus, letting beads fall on each pole concurrently. + wg.Add(aMax) + for _, pole := range abacus { + go func(pole []byte) { + // Track the top of the stack of beads that have already fallen. + top := 0 + for row, space := range pole { + if space == bead { + // Move each bead individually, but move it from its + // starting row to the top of stack in a single operation. + // (More physical simulation such as discovering the top + // of stack by inspection, or modeling gravity, are + // possible, but didn't seem called for by the task. + pole[row] = 0 + pole[top] = bead + top++ + } + } + wg.Done() + }(pole) + } + wg.Wait() + // Read out sorted numbers by row. + for row := range a { + x := 0 + for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ { + x++ + } + a[len(a)-1-row] = x + } +} diff --git a/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-1.groovy b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-1.groovy new file mode 100644 index 0000000000..209abc11f5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-1.groovy @@ -0,0 +1,12 @@ +def beadSort = { list -> + final nPoles = list.max() + list.collect { + print "." + ([true] * it) + ([false] * (nPoles - it)) + }.transpose().collect { pole -> + print "." + pole.findAll { ! it } + pole.findAll { it } + }.transpose().collect{ beadTally -> + beadTally.findAll{ it }.size() + } +} diff --git a/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-2.groovy b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-2.groovy new file mode 100644 index 0000000000..2b291dda8b --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-2.groovy @@ -0,0 +1,19 @@ +def beadSortVerbose = { list -> + final nPoles = list.max() + // each row is a number tally-arrayed across the abacus + def beadTallies = list.collect { number -> + print "." + // true == bead, false == no bead + ([true] * number) + ([false] * (nPoles - number)) + } + // each row is an abacus pole + def abacusPoles = beadTallies.transpose() + def abacusPolesDrop = abacusPoles.collect { pole -> + print "." + // beads drop to the BOTTOM of the pole + pole.findAll { ! it } + pole.findAll { it } + } + // each row is a number again + def beadTalliesDrop = abacusPolesDrop.transpose() + beadTalliesDrop.collect{ beadTally -> beadTally.findAll{ it }.size() } +} diff --git a/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-3.groovy b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-3.groovy new file mode 100644 index 0000000000..486133bb6f --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Groovy/sorting-algorithms-bead-sort-3.groovy @@ -0,0 +1,2 @@ +println beadSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]) +println beadSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]) diff --git a/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-1.hs b/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-1.hs new file mode 100644 index 0000000000..e27e162be2 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-1.hs @@ -0,0 +1,4 @@ +import Data.List + +beadSort :: [Int] -> [Int] +beadSort = map sum. transpose. transpose. map (flip replicate 1) diff --git a/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-2.hs b/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-2.hs new file mode 100644 index 0000000000..1cf447e5e2 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Haskell/sorting-algorithms-bead-sort-2.hs @@ -0,0 +1,2 @@ +*Main> beadSort [2,4,1,3,3] +[4,3,3,2,1] diff --git a/Task/Sorting-algorithms-Bead-sort/Icon/sorting-algorithms-bead-sort.icon b/Task/Sorting-algorithms-Bead-sort/Icon/sorting-algorithms-bead-sort.icon new file mode 100644 index 0000000000..60bcd879ba --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Icon/sorting-algorithms-bead-sort.icon @@ -0,0 +1,25 @@ +procedure main() #: demonstrate various ways to sort a list and string + write("Sorting Demo using ",image(beadsort)) + writes(" on list : ") + writex(UL := [3, 14, 1, 5, 9, 2, 6, 3]) + displaysort(beadsort,copy(UL)) +end + +procedure beadsort(X) #: return sorted list ascending(or descending) +local base,i,j,x # handles negatives and zeros, may also reduce storage + + poles := list(max!X-(base := min!X -1),0) # set up poles, we will track sums not individual beads + every x := !X do { # each item in the list + if integer(x) ~= x then runerr(101,x) # ... must be an integer + every poles[1 to x - base] +:= 1 # ... beads "fall" into the sum for that pole + } + + + every (X[j := *X to 1 by -1] := base) & + (i := 1 to *poles) do # read from the bottom of the poles + if poles[i] > 0 then { # if there's a bead on the pole ... + poles[i] -:= 1 # ... remove it + X[j] +:= 1 # ... and add it in place + } + return X +end diff --git a/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-1.j b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-1.j new file mode 100644 index 0000000000..f6dd0297fe --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-1.j @@ -0,0 +1 @@ +bead=: [: +/ #"0&1 diff --git a/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-2.j b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-2.j new file mode 100644 index 0000000000..2aa94c8dca --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-2.j @@ -0,0 +1,4 @@ + bead bead 2 4 1 3 3 +4 3 3 2 1 + bead bead 5 3 1 7 4 1 1 +7 5 4 3 1 1 1 diff --git a/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-3.j b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-3.j new file mode 100644 index 0000000000..0bcc012098 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-3.j @@ -0,0 +1 @@ +bball=: ] (] + [: bead^:2 -) <./ - 1: diff --git a/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-4.j b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-4.j new file mode 100644 index 0000000000..fe5dfcd213 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/J/sorting-algorithms-bead-sort-4.j @@ -0,0 +1,2 @@ + bball 2 0 _1 3 1 _2 _3 0 +3 2 1 0 0 _1 _2 _3 diff --git a/Task/Sorting-algorithms-Bead-sort/Mathematica/sorting-algorithms-bead-sort.math b/Task/Sorting-algorithms-Bead-sort/Mathematica/sorting-algorithms-bead-sort.math new file mode 100644 index 0000000000..3af5cd6706 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Mathematica/sorting-algorithms-bead-sort.math @@ -0,0 +1,12 @@ +beadsort[ a ] := Module[ { m, sorted, s ,t }, + +sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ]; +If[ Min[a] < 0, Print["can't sort"]]; +For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ] + +For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]]; +t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ] + +For[ i=1,i<=Length[a],i++, sorted[[i]] = Total[t[[i,;;]]]; ] +Print[sorted]; +] diff --git a/Task/Sorting-algorithms-Bead-sort/NetRexx/sorting-algorithms-bead-sort.netrexx b/Task/Sorting-algorithms-Bead-sort/NetRexx/sorting-algorithms-bead-sort.netrexx new file mode 100644 index 0000000000..2738c44533 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/NetRexx/sorting-algorithms-bead-sort.netrexx @@ -0,0 +1,48 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method bead_sort(harry = Rexx[]) public static binary returns Rexx[] + MIN_ = 'MIN' + MAX_ = 'MAX' + beads = Rexx 0 + beads[MIN_] = 0 + beads[MAX_] = 0 + + loop val over harry + -- collect occurences of beads in indexed string indexed on value + if val < beads[MIN_] then beads[MIN_] = val -- keep track of min value + if val > beads[MAX_] then beads[MAX_] = val -- keep track of max value + beads[val] = beads[val] + 1 + end val + + harry_sorted = Rexx[harry.length] + bi = 0 + loop xx = beads[MIN_] to beads[MAX_] + -- extract beads in value order and insert in result array + if beads[xx] == 0 then iterate xx + loop for beads[xx] + harry_sorted[bi] = xx + bi = bi + 1 + end + end xx + + return harry_sorted + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + unsorted = [734, 3, 1, 24, 324, -1024, -666, -1, 0, 324, 32, 0, 432, 42, 3, 4, 1, 1] + sorted = bead_sort(unsorted) + say arrayToString(unsorted) + say arrayToString(sorted) + return +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method arrayToString(harry = Rexx[]) private static + list = Rexx '' + loop vv over harry + list = list vv + end vv + return '['list.space(1, ',')']' diff --git a/Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ocaml b/Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ocaml new file mode 100644 index 0000000000..52d732bb17 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ocaml @@ -0,0 +1,9 @@ +let rec columns l = + match List.filter ((<>) []) l with + [] -> [] + | l -> List.map List.hd l :: columns (List.map List.tl l) + +let replicate n x = Array.to_list (Array.make n x) + +let bead_sort l = + List.map List.length (columns (columns (List.map (fun e -> replicate e 1) l))) diff --git a/Task/Sorting-algorithms-Bead-sort/Octave/sorting-algorithms-bead-sort.octave b/Task/Sorting-algorithms-Bead-sort/Octave/sorting-algorithms-bead-sort.octave new file mode 100644 index 0000000000..adfc578b6e --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Octave/sorting-algorithms-bead-sort.octave @@ -0,0 +1,21 @@ +function sorted = beadsort(a) + sorted = a; + m = max(a); + if ( any(a < 0) ) + error("can't sort"); + endif + t = zeros(m, m); + for i = 1:numel(a) + t(i, 1:a(i)) = 1; + endfor + for i = 1:m + s = sum(t(:, i)); + t(:, i) = 0; + t(1:s, i) = 1; + endfor + for i = 1:numel(a) + sorted(i) = sum(t(i, :)); + endfor +endfunction + +beadsort([5, 7, 1, 3, 1, 1, 20]) diff --git a/Task/Sorting-algorithms-Bead-sort/OpenEdge-Progress/sorting-algorithms-bead-sort.openedge b/Task/Sorting-algorithms-Bead-sort/OpenEdge-Progress/sorting-algorithms-bead-sort.openedge new file mode 100644 index 0000000000..06e6420115 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/OpenEdge-Progress/sorting-algorithms-bead-sort.openedge @@ -0,0 +1,51 @@ +FUNCTION beadSort RETURNS CHAR ( + i_c AS CHAR +): + + DEF VAR cresult AS CHAR. + DEF VAR ii AS INT. + DEF VAR inumbers AS INT. + DEF VAR irod AS INT. + DEF VAR irods AS INT. + DEF VAR crod AS CHAR. + DEF VAR cbeads AS CHAR EXTENT. + + inumbers = NUM-ENTRIES( i_c ). + + /* determine number of rods needed */ + DO ii = 1 TO inumbers: + irods = MAXIMUM( irods, INTEGER( ENTRY( ii, i_c ) ) ). + END. + + /* put beads on rods */ + EXTENT( cbeads ) = inumbers. + DO ii = 1 TO inumbers: + cbeads[ ii ] = FILL( "X", INTEGER( ENTRY( ii, i_c ) ) ). + END. + + /* drop beads on each rod */ + DO irod = 1 TO irods: + crod = "". + DO ii = 1 TO inumbers: + crod = crod + SUBSTRING( cbeads[ ii ], irod, 1 ). + END. + crod = REPLACE( crod, " ", "" ). + DO ii = 1 TO inumbers. + SUBSTRING( cbeads[ ii ], irod, 1 ) = STRING( ii <= LENGTH( crod ), "X/ " ). + END. + END. + + /* get beads from rods */ + DO ii = 1 TO inumbers: + cresult = cresult + "," + STRING( LENGTH( REPLACE( cbeads[ ii ], " ", "" ) ) ). + END. + + RETURN SUBSTRING( cresult, 2 ). + +END FUNCTION. /* beadSort */ + +MESSAGE + "5,2,4,1,3,3,9 -> " beadSort( "5,2,4,1,3,3,9" ) SKIP + "5,3,1,7,4,1,1 -> " beadSort( "5,3,1,7,4,1,1" ) SKIP(1) + beadSort( "88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1" ) +VIEW-AS ALERT-BOX. diff --git a/Task/Sorting-algorithms-Bead-sort/PARI-GP/sorting-algorithms-bead-sort.pari b/Task/Sorting-algorithms-Bead-sort/PARI-GP/sorting-algorithms-bead-sort.pari new file mode 100644 index 0000000000..3c04b0a7ee --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PARI-GP/sorting-algorithms-bead-sort.pari @@ -0,0 +1,24 @@ +beadsort(v)={ + my(sz=vecmax(v),M=matrix(#v,sz,i,j,v[i]>=j)); \\ Set up beads + for(i=1,sz,M[,i]=countingSort(M[,i],0,1)~); \\ Let them fall + vector(#v,i,value(M[i,])) \\ Convert back to numbers +}; + +countingSort(v,mn,mx)={ + my(u=vector(#v),i=0); + for(n=mn,mx, + for(j=1,#v,if(v[j]==n,u[i++]=n)) + ); + u +}; + +value(v)={ + if(#v==0 || !v[1], return(0)); + if(v[#v], return(#v)); + my(left=1, right=#v, mid); + while (right - left > 1, + mid=(right+left)\2; + if(v[mid], left=mid, right=mid) + ); + left +}; diff --git a/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php b/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php new file mode 100644 index 0000000000..18732beea8 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php @@ -0,0 +1,21 @@ +<?php +function columns($arr) { + if (count($m) == 0) + return array(); + else if (count($m) == 1) + return array_chunk($m[0], 1); + + array_unshift($arr, NULL); + // array_map(NULL, $arr[0], $arr[1], ...) + $transpose = call_user_func_array('array_map', $arr); + return array_map('array_filter', $transpose); +} + +function beadsort($arr) { + foreach ($arr as $e) + $poles []= array_fill(0, $e, 1); + return array_map('count', columns(columns($poles))); +} + +print_r(beadsort(array(5,3,1,7,4,1,1))); +?> diff --git a/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort.pli b/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort.pli new file mode 100644 index 0000000000..00e81c065a --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort.pli @@ -0,0 +1,73 @@ +/* Handles both negative and positive values. */ + +maxval: procedure (z) returns (fixed binary); + declare z(*) fixed binary; + declare (maxv initial (0), i) fixed binary; + do i = lbound(z,1) to hbound(z,1); + maxv = max(z(i), maxv); + end; + put skip data (maxv); put skip; + return (maxv); +end maxval; +minval: procedure (z) returns (fixed binary); + declare z(*) fixed binary; + declare (minv initial (0), i) fixed binary; + + do i = lbound(z,1) to hbound(z,1); + if z(i) < 0 then minv = min(z(i), minv); + end; + put skip data (minv); put skip; + return (minv); +end minval; + +/* To deal with negative values, array elements are incremented */ +/* by the greatest (in magnitude) negative value, thus making */ +/* them positive. The resultant values are stored in an */ +/* unsigned array (PL/I provides both signed and unsigned data */ +/* types). At procedure end, the array values are restored to */ +/* original values. */ + +(subrg, fofl, size, stringrange, stringsize): +beadsort: procedure (z); /* 8-1-2010 */ + declare (z(*)) fixed binary; + declare b(maxval(z)-minval(z)+1) bit (maxval(z)-minval(z)+1) aligned; + declare (i, j, k, m, n) fixed binary; + declare a(hbound(z,1)) fixed binary unsigned; + declare offset fixed binary initial (minval(z)); + + PUT SKIP LIST('CHECKPOINT A'); PUT SKIP; + n = hbound(z,1); + m = hbound(b,1); + + if offset < 0 then + a = z - offset; + else + a = z; + + b = '0'b; + + do i = 1 to n; + substr(b(i), 1, a(i)) = copy('1'b, a(i)); + end; + do j = 1 to m; put skip list (b(j)); end; + + do j = 1 to m; + k = 0; + do i =1 to n; + if substr(b(i), j, 1) then k = k + 1; + end; + do i = 1 to n; + substr(b(i), j, 1) = (i <= k); + end; + end; + put skip; + do j = 1 to m; put skip list (b(j)); end; + + do i = 1 to n; + k = 0; + do j = 1 to m; k = k + substr(b(i), j, 1); end; + a(i) = k; + end; + if offset < 0 then z = a + offset; else z = a; + +end beadsort; diff --git a/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-1.pl6 b/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-1.pl6 new file mode 100644 index 0000000000..253f609287 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-1.pl6 @@ -0,0 +1,8 @@ +use List::Utils; + +sub beadsort(@l) { + (transpose(transpose(map {[1 xx $_]}, @l))).map(*.elems); +} + +my @list = 2,1,3,5; +say beadsort(@list).perl; diff --git a/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-2.pl6 b/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-2.pl6 new file mode 100644 index 0000000000..ba0fab6fc9 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Perl-6/sorting-algorithms-bead-sort-2.pl6 @@ -0,0 +1,9 @@ +sub beadsort(*@list) { + my @rods; + for ^«@list -> $x { @rods[$x].push(1) } + gather for ^@rods[0] -> $y { + take [+] @rods.map: { .[$y] // last } + } +} + +say beadsort 2,1,3,5; diff --git a/Task/Sorting-algorithms-Bead-sort/Perl/sorting-algorithms-bead-sort.pl b/Task/Sorting-algorithms-Bead-sort/Perl/sorting-algorithms-bead-sort.pl new file mode 100644 index 0000000000..9c7a9def69 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Perl/sorting-algorithms-bead-sort.pl @@ -0,0 +1,16 @@ +sub beadsort { + my @data = @_; + + my @columns; + my @rows; + + for my $datum (@data) { + for my $column ( 0 .. $datum-1 ) { + ++ $rows[ $columns[$column]++ ]; + } + } + + return reverse @rows; +} + +beadsort 5, 7, 1, 3, 1, 1, 20; diff --git a/Task/Sorting-algorithms-Bead-sort/PicoLisp/sorting-algorithms-bead-sort.l b/Task/Sorting-algorithms-Bead-sort/PicoLisp/sorting-algorithms-bead-sort.l new file mode 100644 index 0000000000..b825f38a00 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PicoLisp/sorting-algorithms-bead-sort.l @@ -0,0 +1,9 @@ +(de beadSort (Lst) + (let Abacus (cons NIL) + (for N Lst # Thread beads on poles + (for (L Abacus (ge0 (dec 'N)) (cdr L)) + (or (cdr L) (queue 'L (cons))) + (push (cadr L) T) ) ) + (make + (while (gt0 (cnt pop (cdr Abacus))) # Drop and count beads + (link @) ) ) ) ) diff --git a/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.psh b/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.psh new file mode 100644 index 0000000000..f37bb2a524 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.psh @@ -0,0 +1,40 @@ +Function BeadSort ( [Int64[]] $indata ) +{ + if( $indata.length -gt 1 ) + { + $min = $indata[ 0 ] + $max = $indata[ 0 ] + for( $i = 1; $i -lt $indata.length; $i++ ) + { + if( $indata[ $i ] -lt $min ) + { + $min = $indata[ $i ] + } + if( $indata[ $i ] -gt $max ) { + $max = $indata[ $i ] + } + } #Find the min & max + $poles = New-Object 'UInt64[]' ( $max - $min + 1 ) + $indata | ForEach-Object { + $min..$_ | ForEach-Object { + $poles[ $_ - $min ] += 1 + } + } #Add Beads to the poles, already moved to the bottom + $min..( $max - 1 ) | ForEach-Object { + $i = $_ - $min + if( $poles[ $i ] -gt $poles[ $i + 1 ] ) + { #No special case needed for min, since there will always be at least 1 = min + ( $poles[ $i ] )..( $poles[ $i + 1 ] + 1 ) | ForEach-Object { + Write-Output ( $i + $min ) + } + } + } #Output the results in pipeline fashion + 1..( $poles[ $max - $min ] ) | ForEach-Object { + Write-Output $max #No special case needed for max, since there will always be at least 1 = max + } + } else { + Write-Output $indata + } +} + +$l = 100; BeadSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Bead-sort/PureBasic/sorting-algorithms-bead-sort.purebasic b/Task/Sorting-algorithms-Bead-sort/PureBasic/sorting-algorithms-bead-sort.purebasic new file mode 100644 index 0000000000..0aeaa13cbb --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PureBasic/sorting-algorithms-bead-sort.purebasic @@ -0,0 +1,72 @@ +#MAXNUM=100 + +Dim MyData(Random(15)+5) +Global Dim Abacus(0,0) + +Declare BeadSort(Array InData(1)) +Declare PresentData(Array InData(1)) + +If OpenConsole() + Define i + ;- Generate a random array + For i=0 To ArraySize(MyData()) + MyData(i)=Random(#MAXNUM) + Next i + PresentData(MyData()) + ; + ;- Sort the array + BeadSort(MyData()) + PresentData(MyData()) + ; + Print("Press ENTER to exit"): Input() +EndIf + +Procedure LetFallDown(x) + Protected y=ArraySize(Abacus(),2)-1 + Protected ylim=y + While y>=0 + If Abacus(x,y) And Not Abacus(x,y+1) + Swap Abacus(x,y), Abacus(x,y+1) + If y<ylim: y+1: Continue: EndIf + Else + y-1 + EndIf + Wend +EndProcedure + +Procedure BeadSort(Array n(1)) + Protected i, j, k + NewList T() + Dim Abacus(#MAXNUM,ArraySize(N())) + ;- Set up the abacus + For i=0 To ArraySize(Abacus(),2) + For j=1 To N(i) + Abacus(j,i)=#True + Next + Next + ;- sort it in threads to simulate free beads falling down + For i=0 To #MAXNUM + AddElement(T()): T()=CreateThread(@LetFallDown(),i) + Next + ForEach T() + WaitThread(T()) + Next + ;- send it back to a normal array + For j=0 To ArraySize(Abacus(),2) + k=0 + For i=0 To ArraySize(Abacus()) + k+Abacus(i,j) + Next + N(j)=k + Next +EndProcedure + +Procedure PresentData(Array InData(1)) + Protected n, m, sum + PrintN(#CRLF$+"The array is;") + For n=0 To ArraySize(InData()) + m=InData(n): sum+m + Print(Str(m)+" ") + Next + PrintN(#CRLF$+"And its sum= "+Str(sum)) +EndProcedure diff --git a/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py b/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py new file mode 100644 index 0000000000..1a2a2626af --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Python/sorting-algorithms-bead-sort.py @@ -0,0 +1,16 @@ +try: + from itertools import zip_longest +except: + try: + from itertools import izip_longest + except: + zip_longest = lambda *args: map(None, *args) + +def beadsort(l): + return map(len, columns(columns([[1] * e for e in l]))) + +def columns(l): + return [filter(None, x) for x in zip_longest(*l)] + +# Demonstration code: +beadsort([5,3,1,7,4,1,1]) diff --git a/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx new file mode 100644 index 0000000000..557421447d --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx @@ -0,0 +1,62 @@ +/*REXX program sorts a list of integers using a bead sort algorithm. */ + /*get some grassHopper numbers. */ +grasshopper=, +1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 + + /*GreeenGrocer numbers are also called hexagonal pyramidal */ + /* numbers. */ +greengrocer=, +0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560 + + /*get some Bernoulli numerator numbers. */ +bernN='1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0 854513' + + /*Psi is also called the Reduced Totient function, and */ + /* is also called Carmichale lambda, or LAMBDA function.*/ +psi=, +1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 + +list=grasshopper greengrocer bernN psi /*combine the four lists into one*/ + +call showL 'before sort',list /*show the list before sorting. */ +$=beadSort(list) /*invoke the bead sort. */ +call showL ' after sort',$ /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +beadSort: procedure expose @.; parse arg z +$= /*this'll be the sorted list. */ +low=999999999; high=-low /*define the low and high numbers*/ +@.=0 /*define all beads to zero. */ + + do j=1 until z=='' /*pick the meat off the bone. */ + parse var z x z + if \datatype(x,'Whole') then do + say; say '*** error! ***'; say + say 'element' j "in list isn't numeric:" x + say + exit 13 + end + x=x/1 /*normalize number, it could be: */ + /* +4 007 5. 2e3 etc.*/ + @.x=@.x+1 /*indicate this bead has a number*/ + low=min(low,x) /*keep track of the lowest number*/ + high=max(high,x) /* " " " " highest " */ + end /*j*/ + /*now, collect the beads and */ + do m=low to high /*let them fall (to zero). */ + if @.m==0 then iterate /*No bead here? Then keep looking*/ + do n=1 for @.m /*let the beads fall to 0. */ + $=$ m /*add it to the sorted list. */ + end /*n*/ + end /*m*/ + +return $ +/*──────────────────────────────────SHOWL subroutine────────────────────*/ +showL: widthH=length(words(arg(2))) /*maximum width of the index. */ + + do j=1 for words(arg(2)) + say 'element' right(j,widthH) arg(1)":" right(word(arg(2),j),10) + end /*j*/ + +say copies('─',79) /*show a separator line. */ +return diff --git a/Task/Sorting-algorithms-Bead-sort/Racket/sorting-algorithms-bead-sort.rkt b/Task/Sorting-algorithms-Bead-sort/Racket/sorting-algorithms-bead-sort.rkt new file mode 100644 index 0000000000..45e1744941 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Racket/sorting-algorithms-bead-sort.rkt @@ -0,0 +1,15 @@ +#lang racket +(require rackunit) + +(define (columns lst) + (match (filter (λ (l) (not (empty? l))) lst) + ['() '()] + [l (cons (map car l) (columns (map cdr l)))])) + +(define (bead-sort lst) + (map length (columns (columns (map (λ (n) (make-list n 1)) lst))))) + +;; unit test +(check-equal? + (bead-sort '(5 3 1 7 4 1 1)) + '(7 5 4 3 1 1 1)) diff --git a/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb new file mode 100644 index 0000000000..b50dd015a4 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb @@ -0,0 +1,19 @@ +class Array + def beadsort + self.map {|e| [1] * e}.columns.columns.map {|e| e.length} + end + + def columns + y = self.length + x = self.map {|l| l.length}.max + + Array.new(x) do |row| + Array.new(y) { |column| + self[column][row] + }.compact # Remove nulls. + end + end +end + +# Demonstration code: +[5,3,1,7,4,1,1].beadsort diff --git a/Task/Sorting-algorithms-Bead-sort/Standard-ML/sorting-algorithms-bead-sort.ml b/Task/Sorting-algorithms-Bead-sort/Standard-ML/sorting-algorithms-bead-sort.ml new file mode 100644 index 0000000000..dd189fe5b5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Standard-ML/sorting-algorithms-bead-sort.ml @@ -0,0 +1,9 @@ +fun columns l = + case List.filter (not o null) l of + [] => [] + | l => map hd l :: columns (map tl l) + +fun replicate (n, x) = List.tabulate (n, fn _ => x) + +fun bead_sort l = + map length (columns (columns (map (fn e => replicate (e, 1)) l))) diff --git a/Task/Sorting-algorithms-Bead-sort/Tcl/sorting-algorithms-bead-sort.tcl b/Task/Sorting-algorithms-Bead-sort/Tcl/sorting-algorithms-bead-sort.tcl new file mode 100644 index 0000000000..7237a18cc5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Tcl/sorting-algorithms-bead-sort.tcl @@ -0,0 +1,23 @@ +package require Tcl 8.5 + +proc beadsort numList { + # Special case: empty list is empty when sorted. + if {![llength $numList]} return + # Set up the abacus... + foreach n $numList { + for {set i 0} {$i<$n} {incr i} { + dict incr vals $i + } + } + # Make the beads fall... + foreach n [dict values $vals] { + for {set i 0} {$i<$n} {incr i} { + dict incr result $i + } + } + # And the result is... + dict values $result +} + +# Demonstration code +puts [beadsort {5 3 1 7 4 1 1}] diff --git a/Task/Sorting-algorithms-Bead-sort/XPL0/sorting-algorithms-bead-sort.xpl0 b/Task/Sorting-algorithms-Bead-sort/XPL0/sorting-algorithms-bead-sort.xpl0 new file mode 100644 index 0000000000..745dc9c02a --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/XPL0/sorting-algorithms-bead-sort.xpl0 @@ -0,0 +1,27 @@ +include c:\cxpl\codes; + +proc BeadSort(Array, Length); \Sort Array into increasing order +int Array, Length; \Array contents range 0..31; number of items +int Row, I, J, T, C; +[Row:= Reserve(Length*4); \each Row has room for 32 beads +for I:= 0 to Length-1 do \each Row gets Array(I) number of beads + Row(I):= ~-1<<Array(I); \(beware for 80186..Pentium <<32 doesn't shift) +for J:= 1 to Length-1 do + for I:= Length-1 downto J do + [T:= Row(I-1) & ~Row(I); \up to 31 beads fall in a single pass + Row(I-1):= Row(I-1) | T; \(|=xor, !=or) + Row(I):= Row(I) | T; + ]; +for I:= 0 to Length-1 do \count beads in each Row + [C:= 0; T:= Row(I); + while T do + [if T&1 then C:= C+1; T:= T>>1]; + Array(I):= C; \count provides sorted order + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, 25, 9, 2, 6, 5, 0]; +BeadSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Bogosort/0DESCRIPTION b/Task/Sorting-algorithms-Bogosort/0DESCRIPTION new file mode 100644 index 0000000000..6cf7feb777 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/0DESCRIPTION @@ -0,0 +1,11 @@ +{{Sorting Algorithm}} +[[wp:Bogosort|Bogosort]] a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. + +"Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in ''n'' factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is O(n) since a single pass through the elements may suffice to order them. + +Pseudocode: + '''while not''' InOrder(list) '''do''' + Shuffle(list) + '''done''' + +The [[Knuth shuffle]] may be used to implement the shuffle part of this algorithm. diff --git a/Task/Sorting-algorithms-Bogosort/1META.yaml b/Task/Sorting-algorithms-Bogosort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Bogosort/ALGOL-68/sorting-algorithms-bogosort.alg b/Task/Sorting-algorithms-Bogosort/ALGOL-68/sorting-algorithms-bogosort.alg new file mode 100644 index 0000000000..cca115b521 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/ALGOL-68/sorting-algorithms-bogosort.alg @@ -0,0 +1,37 @@ +MODE TYPE = INT; + +PROC random shuffle = (REF[]TYPE l)VOID: ( + INT range = UPB l - LWB l + 1; + FOR index FROM LWB l TO UPB l DO + TYPE tmp := l[index]; + INT other := ENTIER (LWB l + random * range); + l[index] := l[other]; + l[other] := tmp + OD +); + +PROC in order = (REF[]TYPE l)BOOL: ( + IF LWB l >= UPB l THEN + TRUE + ELSE + TYPE last := l[LWB l]; + FOR index FROM LWB l + 1 TO UPB l DO + IF l[index] < last THEN + GO TO return false + FI; + last := l[index] + OD; + TRUE EXIT + return false: FALSE + FI +); + +PROC bogo sort = (REF[]TYPE l)REF[]TYPE: ( + WHILE NOT in order(l) DO + random shuffle(l) + OD; + l +); + +[6]TYPE sample := (61, 52, 63, 94, 46, 18); +print((bogo sort(sample), new line)) diff --git a/Task/Sorting-algorithms-Bogosort/AWK/sorting-algorithms-bogosort.awk b/Task/Sorting-algorithms-Bogosort/AWK/sorting-algorithms-bogosort.awk new file mode 100644 index 0000000000..ab6d543f1c --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/AWK/sorting-algorithms-bogosort.awk @@ -0,0 +1,30 @@ +function randint(n) +{ + return int(n * rand()) +} + +function sorted(sa, sn) +{ + for(si=1; si < sn; si++) { + if ( sa[si] > sa[si+1] ) return 0; + } + return 1 +} + +{ + line[NR] = $0 +} +END { # sort it with bogo sort + while ( sorted(line, NR) == 0 ) { + for(i=1; i <= NR; i++) { + r = randint(NR) + 1 + t = line[i] + line[i] = line[r] + line[r] = t + } + } + #print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Bogosort/ActionScript/sorting-algorithms-bogosort.as b/Task/Sorting-algorithms-Bogosort/ActionScript/sorting-algorithms-bogosort.as new file mode 100644 index 0000000000..1f9afd9df5 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/ActionScript/sorting-algorithms-bogosort.as @@ -0,0 +1,37 @@ +public function bogoSort(arr:Array):Array +{ + while (!sorted(arr)) + { + shuffle(arr); + } + + return arr; +} + +public function shuffle(arr:Array):void +{ + for (var i:int = 0; i < arr.length; i++) + { + var rand:int = Math.floor(Math.random() * arr.length); + var tmp:* = arr[i]; + arr[i] = arr[rand]; + arr[rand] = tmp; + } +} + +public function sorted(arr:Array):Boolean +{ + var last:int = arr[0]; + + for (var i:int = 1; i < arr.length; i++) + { + if (arr[i] < last) + { + return false; + } + + last = arr[i]; + } + + return true; +} diff --git a/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.ada b/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.ada new file mode 100644 index 0000000000..46f938f8ee --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.ada @@ -0,0 +1,50 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Discrete_Random; + +procedure Test_Bogosort is + generic + type Ordered is private; + type List is array (Positive range <>) of Ordered; + with function "<" (L, R : Ordered) return Boolean is <>; + procedure Bogosort (Data : in out List); + + procedure Bogosort (Data : in out List) is + function Sorted return Boolean is + begin + for I in Data'First..Data'Last - 1 loop + if not (Data (I) < Data (I + 1)) then + return False; + end if; + end loop; + return True; + end Sorted; + subtype Index is Integer range Data'Range; + package Dices is new Ada.Numerics.Discrete_Random (Index); + use Dices; + Dice : Generator; + procedure Shuffle is + J : Index; + Temp : Ordered; + begin + for I in Data'Range loop + J := Random (Dice); + Temp := Data (I); + Data (I) := Data (J); + Data (J) := Temp; + end loop; + end Shuffle; + begin + while not Sorted loop + Shuffle; + end loop; + end Bogosort; + + type List is array (Positive range <>) of Integer; + procedure Integer_Bogosort is new Bogosort (Integer, List); + Sequence : List := (7,6,3,9); +begin + Integer_Bogosort (Sequence); + for I in Sequence'Range loop + Put (Integer'Image (Sequence (I))); + end loop; +end Test_Bogosort; diff --git a/Task/Sorting-algorithms-Bogosort/AutoHotkey/sorting-algorithms-bogosort.ahk b/Task/Sorting-algorithms-Bogosort/AutoHotkey/sorting-algorithms-bogosort.ahk new file mode 100644 index 0000000000..2c9351e620 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/AutoHotkey/sorting-algorithms-bogosort.ahk @@ -0,0 +1,34 @@ +MsgBox % Bogosort("987654") +MsgBox % Bogosort("319208") +MsgBox % Bogosort("fedcba") +MsgBox % Bogosort("gikhjl") + +Bogosort(sequence) { + While !Sorted(sequence) + sequence := Shuffle(sequence) + Return sequence +} + +Sorted(sequence) { + Loop, Parse, sequence + { + current := A_LoopField + rest := SubStr(sequence, A_Index) + Loop, Parse, rest + { + If (current > A_LoopField) + Return false + } + } + Return true +} + +Shuffle(sequence) { + Max := StrLen(sequence) + 1 + Loop % StrLen(sequence) { + Random, Num, 1, % Max - A_Index + Found .= SubStr(sequence, Num, 1) + sequence := SubStr(sequence, 1, Num-1) . SubStr(sequence, Num+1) + } + Return Found +} diff --git a/Task/Sorting-algorithms-Bogosort/BBC-BASIC/sorting-algorithms-bogosort.bbc b/Task/Sorting-algorithms-Bogosort/BBC-BASIC/sorting-algorithms-bogosort.bbc new file mode 100644 index 0000000000..9a69fdddb6 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/BBC-BASIC/sorting-algorithms-bogosort.bbc @@ -0,0 +1,24 @@ + DIM test(9) + test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1 + + shuffles% = 0 + WHILE NOT FNsorted(test()) + shuffles% += 1 + PROCshuffle(test()) + ENDWHILE + PRINT ;shuffles% " shuffles required to sort "; DIM(test(),1)+1 " items." + END + + DEF PROCshuffle(d()) + LOCAL I% + FOR I% = DIM(d(),1)+1 TO 2 STEP -1 + SWAP d(I%-1), d(RND(I%)-1) + NEXT + ENDPROC + + DEF FNsorted(d()) + LOCAL I% + FOR I% = 1 TO DIM(d(),1) + IF d(I%) < d(I%-1) THEN = FALSE + NEXT + = TRUE diff --git a/Task/Sorting-algorithms-Bogosort/Brat/sorting-algorithms-bogosort.brat b/Task/Sorting-algorithms-Bogosort/Brat/sorting-algorithms-bogosort.brat new file mode 100644 index 0000000000..63e679c87a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Brat/sorting-algorithms-bogosort.brat @@ -0,0 +1,7 @@ +bogosort = { list | + sorted = list.sort #Kinda cheating here + while { list != sorted } { list.shuffle! } + list +} + +p bogosort [15 6 2 9 1 3 41 19] diff --git a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp new file mode 100644 index 0000000000..6ebd033aa0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-1.cpp @@ -0,0 +1,12 @@ +#include <iterator> +#include <algorithm> + +template<typename ForwardIterator> + void bogosort(ForwardIterator begin, ForwardIterator end) +{ + typedef std::iterator_traits<ForwardIterator>::value_type value_type; + + // if we find two adjacent values where the first is greater than the second, the sequence isn't sorted. + while (std::adjacent_find(begin, end, std::greater<value_type>()) != end) + std::random_shuffle(begin, end); +} diff --git a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp new file mode 100644 index 0000000000..009708b88a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort-2.cpp @@ -0,0 +1,9 @@ +#include <algorithm> +#include <ext/algorithm> + +template<typename ForwardIterator> + void bogosort(ForwardIterator begin, ForwardIterator end) +{ + while (!__gnu_cxx::is_sorted(begin, end)) + std::random_shuffle(begin, end); +} diff --git a/Task/Sorting-algorithms-Bogosort/C/sorting-algorithms-bogosort.c b/Task/Sorting-algorithms-Bogosort/C/sorting-algorithms-bogosort.c new file mode 100644 index 0000000000..9e73a13c3c --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/C/sorting-algorithms-bogosort.c @@ -0,0 +1,37 @@ +#include <stdio.h> +#include <stdlib.h> +#include <stdbool.h> + +bool is_sorted(int *a, int n) +{ + while ( --n >= 1 ) { + if ( a[n] < a[n-1] ) return false; + } + return true; +} + +void shuffle(int *a, int n) +{ + int i, t, r; + for(i=0; i < n; i++) { + t = a[i]; + r = rand() % n; + a[i] = a[r]; + a[r] = t; + } +} + +void bogosort(int *a, int n) +{ + while ( !is_sorted(a, n) ) shuffle(a, n); +} + +int main() +{ + int numbers[] = { 1, 10, 9, 7, 3, 0 }; + int i; + + bogosort(numbers, 6); + for (i=0; i < 6; i++) printf("%d ", numbers[i]); + printf("\n"); +} diff --git a/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj b/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj new file mode 100644 index 0000000000..1454754a52 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj @@ -0,0 +1,17 @@ +(ns bogosort + (:use [clojure.contrib.seq-utils :only (shuffle)])) + +(defn in-order? [less xs] + (or (empty? xs) + (empty? (next xs)) + (and (less (first xs) (second xs)) + (recur less (next xs))))) + +(defn bogosort + ([xs] + (bogosort < xs)) + ([less xs] + (if (in-order? less xs) xs + (recur less (shuffle xs))))) + +(println (bogosort [7,5,12,1,4,2,23,18])) diff --git a/Task/Sorting-algorithms-Bogosort/Common-Lisp/sorting-algorithms-bogosort.lisp b/Task/Sorting-algorithms-Bogosort/Common-Lisp/sorting-algorithms-bogosort.lisp new file mode 100644 index 0000000000..483a7d90e6 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Common-Lisp/sorting-algorithms-bogosort.lisp @@ -0,0 +1,12 @@ +(defun nshuffle (sequence) + (loop for i from (length sequence) downto 2 + do (rotatef (elt sequence (random i)) + (elt sequence (1- i )))) + sequence) + +(defun sortedp (list predicate) + (every predicate list (rest list))) + +(defun bogosort (list predicate) + (do ((list list (nshuffle list))) + ((sortedp list predicate) list))) diff --git a/Task/Sorting-algorithms-Bogosort/D/sorting-algorithms-bogosort.d b/Task/Sorting-algorithms-Bogosort/D/sorting-algorithms-bogosort.d new file mode 100644 index 0000000000..b05ddfa169 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/D/sorting-algorithms-bogosort.d @@ -0,0 +1,12 @@ +import std.stdio, std.algorithm, std.random; + +void bogoSort(T)(T[] data) { + while (!isSorted(data)) + randomShuffle(data); +} + +void main() { + auto array = [2, 7, 41, 11, 3, 1, 6, 5, 8]; + bogoSort(array); + writeln(array); +} diff --git a/Task/Sorting-algorithms-Bogosort/E/sorting-algorithms-bogosort.e b/Task/Sorting-algorithms-Bogosort/E/sorting-algorithms-bogosort.e new file mode 100644 index 0000000000..be889ab929 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/E/sorting-algorithms-bogosort.e @@ -0,0 +1,16 @@ +def isSorted(list) { + if (list.size() == 0) { return true } + var a := list[0] + for i in 1..!(list.size()) { + var b := list[i] + if (a > b) { return false } + a := b + } + return true +} + +def bogosort(list, random) { + while (!isSorted(list)) { + shuffle(list, random) + } +} diff --git a/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.euphoria b/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.euphoria new file mode 100644 index 0000000000..cc02012539 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.euphoria @@ -0,0 +1,32 @@ +function shuffle(sequence s) + object temp + integer j + for i = length(s) to 1 by -1 do + j = rand(i) + if i != j then + temp = s[i] + s[i] = s[j] + s[j] = temp + end if + end for + return s +end function + +function inOrder(sequence s) + for i = 1 to length(s)-1 do + if compare(s[i],s[i+1]) > 0 then + return 0 + end if + end for + return 1 +end function + +function bogosort(sequence s) + while not inOrder(s) do + ? s + s = shuffle(s) + end while + return s +end function + +? bogosort(shuffle({1,2,3,4,5,6})) diff --git a/Task/Sorting-algorithms-Bogosort/Factor/sorting-algorithms-bogosort.factor b/Task/Sorting-algorithms-Bogosort/Factor/sorting-algorithms-bogosort.factor new file mode 100644 index 0000000000..d4b229dd8a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Factor/sorting-algorithms-bogosort.factor @@ -0,0 +1,4 @@ +USING: grouping kernel math random sequences ; + +: sorted? ( seq -- ? ) 2 <clumps> [ first2 <= ] all? ; +: bogosort ( seq -- newseq ) [ dup sorted? ] [ randomize ] until ; diff --git a/Task/Sorting-algorithms-Bogosort/Fantom/sorting-algorithms-bogosort.fantom b/Task/Sorting-algorithms-Bogosort/Fantom/sorting-algorithms-bogosort.fantom new file mode 100644 index 0000000000..0d71984585 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Fantom/sorting-algorithms-bogosort.fantom @@ -0,0 +1,25 @@ +class Main +{ + Bool in_order (Int[] items) + { + (0..<(items.size-1)).toList.all |Int i -> Bool| + { + items[i] <= items[i+1] + } + } + + Int[] bogosort (Int[] items) + { + while (!in_order(items)) + { + items.shuffle + } + return items + } + + Void main () + { + // example + echo ("Sorting [3,4,2,1] gives " + bogosort ([3,4,2,1])) + } +} diff --git a/Task/Sorting-algorithms-Bogosort/Fortran/sorting-algorithms-bogosort.f b/Task/Sorting-algorithms-Bogosort/Fortran/sorting-algorithms-bogosort.f new file mode 100644 index 0000000000..d0f3527f88 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Fortran/sorting-algorithms-bogosort.f @@ -0,0 +1,49 @@ +MODULE BOGO +IMPLICIT NONE +CONTAINS + FUNCTION Sorted(a) + LOGICAL :: Sorted + INTEGER, INTENT(IN) :: a(:) + INTEGER :: i + + Sorted = .TRUE. + DO i = 1, SIZE(a)-1 + IF(a(i) > a(i+1)) THEN + Sorted = .FALSE. + EXIT + END IF + END DO + END FUNCTION Sorted + + SUBROUTINE SHUFFLE(a) + INTEGER, INTENT(IN OUT) :: a(:) + INTEGER :: i, rand, temp + REAL :: x + + DO i = SIZE(a), 1, -1 + CALL RANDOM_NUMBER(x) + rand = INT(x * i) + 1 + temp = a(rand) + a(rand) = a(i) + a(i) = temp + END DO + END SUBROUTINE +END MODULE + +PROGRAM BOGOSORT + + USE BOGO + IMPLICIT NONE + INTEGER :: iter = 0 + INTEGER :: array(8) = (/2, 7, 5, 3, 4, 8, 6, 1/) + LOGICAL :: s + + DO + s = Sorted(array) + IF (s) EXIT + CALL SHUFFLE(array) + iter = iter + 1 + END DO + WRITE (*,*) "Array required", iter, " shuffles to sort" + +END PROGRAM BOGOSORT diff --git a/Task/Sorting-algorithms-Bogosort/Go/sorting-algorithms-bogosort.go b/Task/Sorting-algorithms-Bogosort/Go/sorting-algorithms-bogosort.go new file mode 100644 index 0000000000..1a8348c4e8 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Go/sorting-algorithms-bogosort.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "math/rand" + "sort" + "time" +) + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + rand.Seed(time.Now().UnixNano()) + fmt.Println("unsorted:", list) + temp := make([]int, len(list)) + copy(temp, list) + for !sort.IntsAreSorted(temp) { + for i, v := range rand.Perm(len(list)) { + temp[i] = list[v] + } + } + fmt.Println("sorted! ", temp) +} diff --git a/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-1.groovy b/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-1.groovy new file mode 100644 index 0000000000..196a5443bb --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-1.groovy @@ -0,0 +1,8 @@ +def bogosort = { list -> + def n = list.size() + while (n > 1 && (1..<n).any{ list[it-1] > list[it] }) { + print '.'*n + Collections.shuffle(list) + } + list +} diff --git a/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-2.groovy b/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-2.groovy new file mode 100644 index 0000000000..2e4d7f4962 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Groovy/sorting-algorithms-bogosort-2.groovy @@ -0,0 +1 @@ +println (bogosort([3,1,2])) diff --git a/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs b/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs new file mode 100644 index 0000000000..ffcfd7539d --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Haskell/sorting-algorithms-bogosort.hs @@ -0,0 +1,26 @@ +import System.Random +import Data.Array.IO +import Control.Monad + +isSorted :: (Ord a) => [a] -> Bool +isSorted (e1:e2:r) = e1 <= e2 && isSorted (e2:r) +isSorted _ = True + +-- from http://www.haskell.org/haskellwiki/Random_shuffle +shuffle :: [a] -> IO [a] +shuffle xs = do + ar <- newArray n xs + forM [1..n] $ \i -> do + j <- randomRIO (i,n) + vi <- readArray ar i + vj <- readArray ar j + writeArray ar j vi + return vj + where + n = length xs + newArray :: Int -> [a] -> IO (IOArray Int a) + newArray n xs = newListArray (1,n) xs + +bogosort :: (Ord a) => [a] -> IO [a] +bogosort li | isSorted li = return li + | otherwise = shuffle li >>= bogosort diff --git a/Task/Sorting-algorithms-Bogosort/Icon/sorting-algorithms-bogosort.icon b/Task/Sorting-algorithms-Bogosort/Icon/sorting-algorithms-bogosort.icon new file mode 100644 index 0000000000..c0fd152e1c --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Icon/sorting-algorithms-bogosort.icon @@ -0,0 +1,17 @@ +procedure shuffle(l) + repeat { + !l :=: ?l + suspend l + } +end + +procedure sorted(l) + local i + if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1 +end + +procedure main() + local l + l := [6,3,4,5,1] + |( shuffle(l) & sorted(l)) \1 & every writes(" ",!l) +end diff --git a/Task/Sorting-algorithms-Bogosort/Inform-6/sorting-algorithms-bogosort.inf b/Task/Sorting-algorithms-Bogosort/Inform-6/sorting-algorithms-bogosort.inf new file mode 100644 index 0000000000..dc4440e20d --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Inform-6/sorting-algorithms-bogosort.inf @@ -0,0 +1,26 @@ +[ shuffle a n i j tmp; + for(i = n - 1: i > 0: i--) + { + j = random(i + 1) - 1; + + tmp = a->j; + a->j = a->i; + a->i = tmp; + } +]; + +[ is_sorted a n i; + for(i = 0: i < n - 1: i++) + { + if(a->i > a->(i + 1)) rfalse; + } + + rtrue; +]; + +[ bogosort a n; + while(~~is_sorted(a, n)) + { + shuffle(a, n); + } +]; diff --git a/Task/Sorting-algorithms-Bogosort/Io/sorting-algorithms-bogosort.io b/Task/Sorting-algorithms-Bogosort/Io/sorting-algorithms-bogosort.io new file mode 100644 index 0000000000..f0db467910 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Io/sorting-algorithms-bogosort.io @@ -0,0 +1,17 @@ +List do( + isSorted := method( + slice(1) foreach(i, x, + if (x < at(i), return false) + ) + return true; + ) + + bogoSortInPlace := method( + while(isSorted not, + shuffleInPlace() + ) + ) +) + +lst := list(2, 1, 4, 3) +lst bogoSortInPlace println # ==> list(1, 2, 3, 4), hopefully :) diff --git a/Task/Sorting-algorithms-Bogosort/J/sorting-algorithms-bogosort.j b/Task/Sorting-algorithms-Bogosort/J/sorting-algorithms-bogosort.j new file mode 100644 index 0000000000..5c75609e22 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/J/sorting-algorithms-bogosort.j @@ -0,0 +1,3 @@ +bogo=: monad define + whilst. +./ 2 >/\ Ry do. Ry=. (A.~ ?@!@#) y end. Ry +) diff --git a/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java new file mode 100644 index 0000000000..15e0f2f869 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java @@ -0,0 +1,24 @@ +import java.util.Collections; +import java.util.List; +import java.util.Iterator; + +public class Bogosort { + private static <T extends Comparable<? super T>> boolean isSorted(List<T> list) { + if (list.isEmpty()) + return true; + Iterator<T> 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 <T extends Comparable<? super T>> void bogoSort(List<T> list) { + while (!isSorted(list)) + Collections.shuffle(list); + } +} diff --git a/Task/Sorting-algorithms-Bogosort/JavaScript/sorting-algorithms-bogosort.js b/Task/Sorting-algorithms-Bogosort/JavaScript/sorting-algorithms-bogosort.js new file mode 100644 index 0000000000..f109d7036e --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/JavaScript/sorting-algorithms-bogosort.js @@ -0,0 +1,20 @@ +shuffle = function(v) { + for(var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x); + return v; +}; + +isSorted = function(v){ + for(var i=1; i<v.length; i++) { + if (v[i-1] > v[i]) { return false; } + } + return true; +} + +bogosort = function(v){ + var sorted = false; + while(sorted == false){ + v = shuffle(v); + sorted = isSorted(v); + } + return v; +} diff --git a/Task/Sorting-algorithms-Bogosort/Lua/sorting-algorithms-bogosort.lua b/Task/Sorting-algorithms-Bogosort/Lua/sorting-algorithms-bogosort.lua new file mode 100644 index 0000000000..15c0a0d139 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Lua/sorting-algorithms-bogosort.lua @@ -0,0 +1,26 @@ +function bogosort (list) + if type (list) ~= 'table' then return list end + + -- Fisher-Yates Knuth shuffle + local function shuffle () + local rand = math.random(1,#list) + for i=1,#list do + list[i],list[rand] = list[rand],list[i] + rand = math.random(1,#list) + end + end + + -- Returns true only if list is now sorted + local function in_order () + local last = list[1] + for i,v in next,list do + if v < last then return false end + last = v + end + return true + end + + while not in_order() do shuffle() end + + return list +end diff --git a/Task/Sorting-algorithms-Bogosort/M4/sorting-algorithms-bogosort.m4 b/Task/Sorting-algorithms-Bogosort/M4/sorting-algorithms-bogosort.m4 new file mode 100644 index 0000000000..cfa9323f72 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/M4/sorting-algorithms-bogosort.m4 @@ -0,0 +1,40 @@ +divert(-1) +define(`randSeed',141592653) +define(`setRand', + `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') +define(`rand_t',`eval(randSeed^(randSeed>>13))') +define(`random', + `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') +define(`for', + `ifelse($#,0,``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') +define(`set',`define(`$1[$2]',`$3')') +define(`new',`set($1,size,0)') +define(`get',`defn($1[$2])') +define(`append', + `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)') +define(`deck', + `new($1)for(`x',1,$2, + `append(`$1',random)')') +define(`show', + `for(`x',1,get($1,size),`get($1,x)`'ifelse(x,get($1,size),`',`, ')')') +define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)') +define(`shuffle', + `for(`x',1,get($1,size), + `swap($1,x,get($1,x),eval(1+random%get($1,size)))')') +define(`inordern', + `ifelse(eval($2>=get($1,size)),1, + 1, + `ifelse(eval(get($1,$2)>get($1,incr($2))),1, + 0, + `inordern(`$1',incr($2))')')') +define(`inorder',`inordern($1,1)') +define(`bogosort', + `ifelse(inorder(`$1'),0,`nope shuffle(`$1')`'bogosort(`$1')')') +divert + +deck(`b',6) +show(`b') +bogosort(`b') +show(`b') diff --git a/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-1.m b/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-1.m new file mode 100644 index 0000000000..f54d7cf714 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-1.m @@ -0,0 +1,5 @@ +function list = bogoSort(list) + while( ~issorted(list) ) %Check to see if it is sorted + list = list( randperm(numel(list)) ); %Randomly sort the list + end +end diff --git a/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-2.m b/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-2.m new file mode 100644 index 0000000000..4c46f9770e --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/MATLAB/sorting-algorithms-bogosort-2.m @@ -0,0 +1,5 @@ +bogoSort([5 3 8 4 9 7 6 2 1]) + +ans = + + 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Bogosort/MAXScript/sorting-algorithms-bogosort.maxscript b/Task/Sorting-algorithms-Bogosort/MAXScript/sorting-algorithms-bogosort.maxscript new file mode 100644 index 0000000000..52a278f274 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/MAXScript/sorting-algorithms-bogosort.maxscript @@ -0,0 +1,36 @@ +fn notSorted arr = +( + if arr.count > 0 then + ( + local current = arr[1] + for i in 2 to arr.count do + ( + if current > arr[i] then + ( + return true + ) + current = arr[i] + ) + ) + false +) + +fn randSort x y = +( + random -1 1 +) + +fn shuffle arr = +( + qsort arr randSort + arr +) + +fn bogosort arr = +( + while notSorted arr do + ( + arr = shuffle arr + ) + arr +) diff --git a/Task/Sorting-algorithms-Bogosort/Mathematica/sorting-algorithms-bogosort.math b/Task/Sorting-algorithms-Bogosort/Mathematica/sorting-algorithms-bogosort.math new file mode 100644 index 0000000000..cdc8b397f8 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Mathematica/sorting-algorithms-bogosort.math @@ -0,0 +1,4 @@ +Bogosort[x_List] := Block[{t=x},While[!OrderedQ[t],t=RandomSample[x]]; t] + +Bogosort[{1, 2, 6, 4, 0, -1, Pi, 3, 5}] +=> {-1, 0, 1, 2, 3, Pi, 4, 5, 6} diff --git a/Task/Sorting-algorithms-Bogosort/Modula-3/sorting-algorithms-bogosort.mod3 b/Task/Sorting-algorithms-Bogosort/Modula-3/sorting-algorithms-bogosort.mod3 new file mode 100644 index 0000000000..a846246652 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Modula-3/sorting-algorithms-bogosort.mod3 @@ -0,0 +1,46 @@ +MODULE Bogo EXPORTS Main; + +IMPORT IO, Fmt, Random; + +VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5}; + count := 0; + +PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER) = + VAR temp: INTEGER; + BEGIN + WITH rand = NEW(Random.Default).init() DO + FOR i := FIRST(a) TO LAST(a) - 1 DO + WITH j = rand.integer(i, LAST(a)) DO + temp := a[i]; + a[i] := a[j]; + a[j] := temp; + END; + END; + END; + END Shuffle; + +PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN = + BEGIN + IF NUMBER(a) <= 1 THEN + RETURN TRUE; + END; + FOR i := FIRST(a) + 1 TO LAST(a) DO + IF (a[i] < a[i - 1]) THEN + RETURN FALSE; + END; + END; + RETURN TRUE; + END Sorted; + +BEGIN + Shuffle(a); + WHILE NOT Sorted(a) DO + Shuffle(a); + INC(count); + END; + FOR i := FIRST(a) TO LAST(a) DO + IO.PutInt(a[i]); + IO.Put(" "); + END; + IO.Put("\nRequired " & Fmt.Int(count) & " shuffles\n"); +END Bogo. diff --git a/Task/Sorting-algorithms-Bogosort/Nemerle/sorting-algorithms-bogosort.nemerle b/Task/Sorting-algorithms-Bogosort/Nemerle/sorting-algorithms-bogosort.nemerle new file mode 100644 index 0000000000..0c8e1a266a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Nemerle/sorting-algorithms-bogosort.nemerle @@ -0,0 +1,39 @@ +using System; +using System.Console; +using Nemerle.Imperative; + +module Bogosort +{ + public static Bogosort[T] (this x : array[T]) : void + where T : IComparable + { + def rnd = Random(); + def shuffle(a) + { + foreach (i in [0 .. (a.Length - 2)]) + a[i] <-> a[(rnd.Next(i, a.Length))]; + } + + def isSorted(b) + { + when (b.Length <= 1) return true; + foreach (i in [1 .. (b.Length - 1)]) + when (b[i].CompareTo(b[i - 1]) < 0) return false; + true; + } + + def loop() + { + unless (isSorted(x)) {shuffle(x); loop();}; + } + + loop() + } + + Main() : void + { + def sortme = array[1, 5, 3, 6, 7, 3, 8, -2]; + sortme.Bogosort(); + foreach (i in sortme) Write($"$i "); + } +} diff --git a/Task/Sorting-algorithms-Bogosort/NetRexx/sorting-algorithms-bogosort.netrexx b/Task/Sorting-algorithms-Bogosort/NetRexx/sorting-algorithms-bogosort.netrexx new file mode 100644 index 0000000000..d22464d2b1 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/NetRexx/sorting-algorithms-bogosort.netrexx @@ -0,0 +1,46 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols nobinary + +import java.util.List + +method isSorted(list = List) private static returns boolean + + if list.isEmpty then + return isTrue + + it = list.iterator + last = Comparable it.next + loop label i_ while it.hasNext + current = Comparable it.next + if last.compareTo(current) > 0 then + return isFalse + last = current + end i_ + + return isTrue + +method bogoSort(list = List) private static + loop label s_ while \isSorted(list) + Collections.shuffle(list) + end s_ + + return + +method main(args = String[]) public constant + samples = [int 31, 41, 59, 26, 53, 58, 97, 93, 23, 84] + alst = ArrayList(samples.length) + loop iv = 0 to samples.length - 1 + alst.add(Integer(samples[iv])) + end iv + + say 'unsorted:' alst.toString + bogoSort(alst) + say 'sorted: ' alst.toString + + return + +method isTrue public static returns boolean + return 1 == 1 + +method isFalse public static returns boolean + return \isTrue diff --git a/Task/Sorting-algorithms-Bogosort/OCaml/sorting-algorithms-bogosort.ocaml b/Task/Sorting-algorithms-Bogosort/OCaml/sorting-algorithms-bogosort.ocaml new file mode 100644 index 0000000000..adc9e3ad7d --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/OCaml/sorting-algorithms-bogosort.ocaml @@ -0,0 +1,20 @@ +let rec is_sorted comp = function + | e1 :: e2 :: r -> comp e1 e2 <= 0 && is_sorted comp (e2 :: r) + | _ -> true + +(* Fisher-Yates shuffle on lists; uses temp array *) +let shuffle l = + let ar = Array.of_list l in + for n = Array.length ar - 1 downto 1 do + let k = Random.int (n+1) in + let temp = ar.(k) in (* swap ar.(k) and ar.(n) *) + ar.(k) <- ar.(n); + ar.(n) <- temp + done; + Array.to_list ar + +let rec bogosort li = + if is_sorted compare li then + li + else + bogosort (shuffle li) diff --git a/Task/Sorting-algorithms-Bogosort/Oberon-2/sorting-algorithms-bogosort.oberon-2 b/Task/Sorting-algorithms-Bogosort/Oberon-2/sorting-algorithms-bogosort.oberon-2 new file mode 100644 index 0000000000..3c3bb875b0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Oberon-2/sorting-algorithms-bogosort.oberon-2 @@ -0,0 +1,51 @@ +MODULE Bogo; + + IMPORT Out, Random; + + VAR a: ARRAY 10 OF INTEGER; + + PROCEDURE Init; + VAR i: INTEGER; + BEGIN + FOR i := 0 TO LEN(a) - 1 DO + a[i] := i + 1; + END; + END Init; + + PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN; + VAR i: INTEGER; + BEGIN + IF LEN(a) <= 1 THEN + RETURN TRUE; + END; + FOR i := 1 TO LEN(a) - 1 DO + IF (a[i] < a[i - 1]) THEN + RETURN FALSE; + END; + END; + RETURN TRUE; + END Sorted; + + PROCEDURE Shuffle*(VAR a: ARRAY OF INTEGER); + VAR n, t, r: INTEGER; + BEGIN + FOR n := 0 TO LEN(a) - 1 DO + r := Random.Roll(n); + t := a[n]; + a[n] := a[r]; + a[r] := t; + END; + END Shuffle; + +BEGIN + Init; + Shuffle(a); + WHILE ~Sorted(a) DO + Shuffle(a); + END; + FOR i := 0 TO LEN(a) - 1 DO + Out.Int(a[i], 0); + Out.String(" "); + END; + Out.Ln; +END Bogo. diff --git a/Task/Sorting-algorithms-Bogosort/Oz/sorting-algorithms-bogosort.oz b/Task/Sorting-algorithms-Bogosort/Oz/sorting-algorithms-bogosort.oz new file mode 100644 index 0000000000..e410464ae5 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Oz/sorting-algorithms-bogosort.oz @@ -0,0 +1,32 @@ +declare + proc {BogoSort Arr} + for while:{Not {InOrder Arr}} do + {Shuffle Arr} + end + end + + fun {InOrder Arr} + for I in {Array.low Arr}+1..{Array.high Arr} + return:Return default:true + do + if Arr.(I-1) > Arr.I then {Return false} end + end + end + + proc {Shuffle Arr} + Low = {Array.low Arr} + High = {Array.high Arr} + in + for I in High..Low;~1 do + J = Low + {OS.rand} mod (I - Low + 1) + OldI = Arr.I + in + Arr.I := Arr.J + Arr.J := OldI + end + end + + X = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} +in + {BogoSort X} + {Show {Array.toRecord unit X}} diff --git a/Task/Sorting-algorithms-Bogosort/PARI-GP/sorting-algorithms-bogosort.pari b/Task/Sorting-algorithms-Bogosort/PARI-GP/sorting-algorithms-bogosort.pari new file mode 100644 index 0000000000..d156975b77 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PARI-GP/sorting-algorithms-bogosort.pari @@ -0,0 +1,7 @@ +bogosort(v)={ + while(1, + my(u=vecextract(v,numtoperm(#v,random((#v)!)))); + for(i=2,#v,if(u[i]<u[i-1], next(2))); + return(u) + ); +}; diff --git a/Task/Sorting-algorithms-Bogosort/PHP/sorting-algorithms-bogosort.php b/Task/Sorting-algorithms-Bogosort/PHP/sorting-algorithms-bogosort.php new file mode 100644 index 0000000000..2f479b551c --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PHP/sorting-algorithms-bogosort.php @@ -0,0 +1,12 @@ +function bogosort($l) { + while (!in_order($l)) + shuffle($l); + return $l; +} + +function in_order($l) { + for ($i = 1; $i < count($l); $i++) + if ($l[$i] < $l[$i-1]) + return FALSE; + return TRUE; +} diff --git a/Task/Sorting-algorithms-Bogosort/Pascal/sorting-algorithms-bogosort.pascal b/Task/Sorting-algorithms-Bogosort/Pascal/sorting-algorithms-bogosort.pascal new file mode 100644 index 0000000000..0fe6c9194e --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Pascal/sorting-algorithms-bogosort.pascal @@ -0,0 +1,65 @@ +program bogosort; + +const + max = 5; +type + list = array [1..max] of integer; + +{ Print a list } +procedure printa(a: list); +var + i: integer; +begin + for i := 1 to max do + write(a[i], ' '); + writeln +end; + +{ Knuth shuffle } +procedure shuffle(var a: list); +var + i,k,tmp: integer; +begin + for i := max downto 2 do begin + k := random(i) + 1; + if (a[i] <> a[k]) then begin + tmp := a[i]; a[i] := a[k]; a[k] := tmp + end + end +end; + +{ Check for sorted list } +function sorted(a: list): boolean; +var + i: integer; +begin + sorted := True; + for i := 2 to max do + if (a[i - 1] > a[i]) then begin + sorted := False; exit + end +end; + +{ Bogosort } +procedure bogo(var a: list); +var + i: integer; +begin + i := 1; randomize; + write(i,': '); printa(a); + while not sorted(a) do begin + shuffle(a); + i := i + 1; write(i,': '); printa(a) + end +end; + +{ Test and display } +var + a: list; + i: integer; + +begin + for i := 1 to max do + a[i] := (max + 1) - i; + bogo(a); +end. diff --git a/Task/Sorting-algorithms-Bogosort/Perl-6/sorting-algorithms-bogosort.pl6 b/Task/Sorting-algorithms-Bogosort/Perl-6/sorting-algorithms-bogosort.pl6 new file mode 100644 index 0000000000..b8944766a3 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Perl-6/sorting-algorithms-bogosort.pl6 @@ -0,0 +1,7 @@ +sub bogosort (@list is copy) { + @list .= pick(*) until [<=] @list; + return @list; +} + +my @nums = (^5).map: { rand }; +say @nums.sort.Str eq @nums.&bogosort.Str ?? 'ok' !! 'not ok'; diff --git a/Task/Sorting-algorithms-Bogosort/Perl/sorting-algorithms-bogosort.pl b/Task/Sorting-algorithms-Bogosort/Perl/sorting-algorithms-bogosort.pl new file mode 100644 index 0000000000..15ae7fdef7 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Perl/sorting-algorithms-bogosort.pl @@ -0,0 +1,13 @@ +use List::Util qw(shuffle); + +sub bogosort + {my @l = @_; + @l = shuffle(@l) until in_order(@l); + return @l;} + +sub in_order + {my $last = shift; + foreach (@_) + {$_ >= $last or return 0; + $last = $_;} + return 1;} diff --git a/Task/Sorting-algorithms-Bogosort/PicoLisp/sorting-algorithms-bogosort.l b/Task/Sorting-algorithms-Bogosort/PicoLisp/sorting-algorithms-bogosort.l new file mode 100644 index 0000000000..d341a7cbb2 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PicoLisp/sorting-algorithms-bogosort.l @@ -0,0 +1,6 @@ +(de bogosort (Lst) + (loop + (map + '((L) (rot L (rand 1 (length L)))) + Lst ) + (T (apply <= Lst) Lst) ) ) diff --git a/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.psh b/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.psh new file mode 100644 index 0000000000..a7332933b0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.psh @@ -0,0 +1,29 @@ +function shuffle ($a) { + $c = $a.Clone() # make copy to avoid clobbering $a + 1..($c.Length - 1) | ForEach-Object { + $i = Get-Random -Minimum $_ -Maximum $c.Length + $c[$_-1],$c[$i] = $c[$i],$c[$_-1] + $c[$_-1] # return newly-shuffled value + } + $c[-1] # last value +} + +function isSorted( [Array] $data ) +{ + $sorted = $true + for( $i = 1; ( $i -lt $data.length ) -and $sorted; $i++ ) + { + $sorted = $data[ $i - 1 ] -le $data[ $i ] + } + $sorted +} + +function BogoSort ( [Array] $indata ) { + $data = $indata.Clone() + while( -not ( isSorted $data ) ) { + $data = shuffle $indata + } + $data +} + +$l = 7; BogoSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Bogosort/PureBasic/sorting-algorithms-bogosort.purebasic b/Task/Sorting-algorithms-Bogosort/PureBasic/sorting-algorithms-bogosort.purebasic new file mode 100644 index 0000000000..9ff769bd52 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PureBasic/sorting-algorithms-bogosort.purebasic @@ -0,0 +1,33 @@ +Procedure KnuthShuffle (Array a(1)) + Protected i, Size = ArraySize(a()) + For i = 0 To Size + Swap a(i), a(Random(Size)) + Next +EndProcedure + +Procedure isSorted(Array a(1)) + Protected i, Size = ArraySize(a()) + For i = 1 To Size + If a(i) < a(i - 1) + ProcedureReturn #False + EndIf + Next + ProcedureReturn #True +EndProcedure + +Procedure BogoSort(Array a(1)) + Protected Size = ArraySize(a()) + 1, iter + + While Not isSorted(a()) + iter + 1 + KnuthShuffle(a()) + Wend + MessageRequester("Results","Array of " + Str(Size) + " integers required " + Str(iter) + " shuffles To SORT.") +EndProcedure + +Dim b(10) +For i = 0 To 10 + b(i) = Random(100) +Next + +BogoSort(b()) diff --git a/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-1.py b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-1.py new file mode 100644 index 0000000000..4025251788 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-1.py @@ -0,0 +1,16 @@ +import random + +def bogosort(l): + while not in_order(l): + random.shuffle(l) + return l + +def in_order(l): + if not l: + return True + last = l[0] + for x in l[1:]: + if x < last: + return False + last = x + return True diff --git a/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-2.py b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-2.py new file mode 100644 index 0000000000..0cb9fae449 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-2.py @@ -0,0 +1,2 @@ +def in_order(l): + return all( l[i] <= l[i+1] for i in xrange(0,len(l)-1)) diff --git a/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-3.py b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-3.py new file mode 100644 index 0000000000..0695391a11 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-3.py @@ -0,0 +1,6 @@ +import random +def bogosort(lst): + random.shuffle(lst) # must shuffle it first or it's a bug if lst was pre-sorted! :) + while lst != sorted(lst): + random.shuffle(lst) + return lst diff --git a/Task/Sorting-algorithms-Bogosort/Qi/sorting-algorithms-bogosort.qi b/Task/Sorting-algorithms-Bogosort/Qi/sorting-algorithms-bogosort.qi new file mode 100644 index 0000000000..568716dd5c --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Qi/sorting-algorithms-bogosort.qi @@ -0,0 +1,23 @@ +(define remove-element + 0 [_ | R] -> R + Pos [A | R] -> [A | (remove-element (1- Pos) R)]) + +(define get-element + Pos R -> (nth (1+ Pos) R)) + +(define shuffle-0 + Pos R -> [(get-element Pos R) | (shuffle (remove-element Pos R))]) + +(define shuffle + [] -> [] + R -> (shuffle-0 (RANDOM (length R)) R)) + +(define in-order? + [] -> true + [A] -> true + [A B | R] -> (in-order? [B | R]) where (<= A B) + _ -> false) + +(define bogosort + Suggestion -> Suggestion where (in-order? Suggestion) + Suggestion -> (bogosort (shuffle Suggestion))) diff --git a/Task/Sorting-algorithms-Bogosort/R/sorting-algorithms-bogosort.r b/Task/Sorting-algorithms-Bogosort/R/sorting-algorithms-bogosort.r new file mode 100644 index 0000000000..8887b22d26 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/R/sorting-algorithms-bogosort.r @@ -0,0 +1,9 @@ +bogosort <- function(x) +{ + is.sorted <- function(x) all(diff(x) >= 0) + while(!is.sorted(x)) x <- sample(x) + x +} + +n <- c(1, 10, 9, 7, 3, 0) +print(bogosort(n)) diff --git a/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx new file mode 100644 index 0000000000..6eaeb26696 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx @@ -0,0 +1,46 @@ +/*REXX program;to perform a type of bogo sort on an array. */ + /*a.1 is really the 0th Berstel number... */ +a.1 = 0 ; a.11= -64 ; a.21= 4096 ; a.31= 6291456 +a.2 = 0 ; a.12= 64 ; a.22= 40960 ; a.32= 5242880 +a.3 = 1 ; a.13= 256 ; a.23= 16384 ; a.33= -15728640 +a.4 = 2 ; a.14= 0 ; a.24= -114688 ; a.34= -27262976 +a.5 = 0 ; a.15= -768 ; a.25= -131072 ; a.35= 29360128 +a.6 = -4 ; a.16= -512 ; a.26= 262144 ; a.36= 104857600 +a.7 = 0 ; a.17= 2048 ; a.27= 589824 ; a.37= -16777216 +a.8 = 16 ; a.18= 3072 ; a.28= -393216 ; a.38= -335544320 +a.9 = 16 ; a.19= -4096 ; a.29= -2097152 ; a.39= -184549376 +a.10= -32 ; a.20= -12288 ; a.30= -262144 ; a.40= 905969664 + +size=40 /*we have a list of two score Berstel numbers.*/ +call tell 'un-bogoed' + + do bogo=1 + + do j=1 for size + _=a.j + + do k=j+1 to size + if a.k>=_ then iterate + n=random(j,k) /*we have an num out of order.get rand*/ + do forever; m=random(j,k) /*get another random number.*/ + if m\==n then leave /*ensure we're not swapping the same #*/ + end /*forever*/ + parse value a.n a.m with a.m a.n /*swap 2 random nums*/ + iterate bogo + end /*k*/ + end /*j*/ + + leave + end /*bogo*/ + +say 'number of bogo sorts performed =' bogo-1 +call tell ' bogoed' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: say; say center(arg(1),40,'─') + + do j=1 to size + say arg(1) 'element'right(j,length(size))'='right(a.j,20) + end /*j*/ +say +return diff --git a/Task/Sorting-algorithms-Bogosort/Racket/sorting-algorithms-bogosort.rkt b/Task/Sorting-algorithms-Bogosort/Racket/sorting-algorithms-bogosort.rkt new file mode 100644 index 0000000000..be3854385a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Racket/sorting-algorithms-bogosort.rkt @@ -0,0 +1,10 @@ +#lang racket +(define (bogo-sort l) (if (apply <= l) l (bogo-sort (shuffle l)))) + +(require rackunit) +(check-equal? (bogo-sort '(6 5 4 3 2 1)) '(1 2 3 4 5 6)) +(check-equal? (bogo-sort (shuffle '(1 1 1 2 2 2))) '(1 1 1 2 2 2)) + +(let ((unsorted (for/list ((i 10)) (random 1000)))) + (displayln unsorted) + (displayln (bogo-sort unsorted))) diff --git a/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-1.rb b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-1.rb new file mode 100644 index 0000000000..532327b864 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-1.rb @@ -0,0 +1,12 @@ +def shuffle(l) + l.sort_by { rand } +end + +def bogosort(l) + l = shuffle(l) until in_order(l) + l +end + +def in_order(l) + (0..l.length-2).all? {|i| l[i] <= l[i+1] } +end diff --git a/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-2.rb b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-2.rb new file mode 100644 index 0000000000..abe8e95dc9 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-2.rb @@ -0,0 +1,8 @@ +def shuffle(l) + l.sort_by { rand } +end + +def bogosort(l) + l = shuffle(l) until l == l.sort + l +end diff --git a/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-3.rb b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-3.rb new file mode 100644 index 0000000000..7d64216e9e --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ruby/sorting-algorithms-bogosort-3.rb @@ -0,0 +1,8 @@ +def in_order(l) + (0..l.length-2).all? {|i| l[i] <= l[i+1] } +end + +def bogosort(l) + l.shuffle! until in_order(l) + l +end diff --git a/Task/Sorting-algorithms-Bogosort/SNOBOL4/sorting-algorithms-bogosort.sno b/Task/Sorting-algorithms-Bogosort/SNOBOL4/sorting-algorithms-bogosort.sno new file mode 100644 index 0000000000..1be01ec331 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/SNOBOL4/sorting-algorithms-bogosort.sno @@ -0,0 +1,41 @@ +* Library for random() +-include 'Random.sno' + +* # String -> array + define('s2a(str,n)i') :(s2a_end) +s2a s2a = array(n); str = str ' ' +sa1 str break(' ') . s2a<i = i + 1> span(' ') = :s(sa1)f(return) +s2a_end + +* # Array -> string + define('a2s(a)i') :(a2s_end) +a2s a2s = a2s a<i = i + 1> ' ' :s(a2s)f(return) +a2s_end + +* # Knuth shuffle in-place + define('shuffle(a)alen,n,k,tmp') :(shuffle_end) +shuffle n = alen = prototype(a); +sh1 k = convert(random() * alen,'integer') + 1 + eq(a<n>,a<k>) :s(sh2) + tmp = a<n>; a<n> = a<k>; a<k> = tmp +sh2 n = gt(n,1) n - 1 :s(sh1) + shuffle = a :(return) +shuffle_end + +* # sorted( ) predicate -> Succeed/Fail + define('sorted(a)alen,i') :(sorted_end) +sorted alen = prototype(a); i = 1 +std1 i = lt(i,alen) i + 1 :f(return) + gt(a<i - 1>,a<i>) :s(freturn)f(std1) +sorted_end + +* # Bogosort + define('bogo(a)') :(bogo_end) +bogo output = (i = i + 1) ': ' a2s(a) + bogo = sorted(a) a :s(return) + shuffle(a) :(bogo) +bogo_end + +* # Test and display + bogo(s2a('5 4 3 2 1',5)) +end diff --git a/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala b/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala new file mode 100644 index 0000000000..aa54bb6ff3 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala @@ -0,0 +1,2 @@ +def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head < s.last) +def bogosort(l: List[Int]): List[Int] = if (isSorted(l)) l else bogosort(scala.util.Random.shuffle(l)) diff --git a/Task/Sorting-algorithms-Bogosort/Smalltalk/sorting-algorithms-bogosort.st b/Task/Sorting-algorithms-Bogosort/Smalltalk/sorting-algorithms-bogosort.st new file mode 100644 index 0000000000..7dfc1452be --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Smalltalk/sorting-algorithms-bogosort.st @@ -0,0 +1,24 @@ +Smalltalk at: #isItSorted put: [ :c | + |isit| + isit := false. + (2 to: (c size)) detect: [ :i | + ( (c at: ( i - 1 )) > (c at: i) ) + ] ifNone: [ isit := true ]. + isit +]. +Smalltalk at: #bogosort put: [ :c | + [ isItSorted value: c ] whileFalse: [ + 1 to: (c size) do: [ :i | + |r t| + r := (Random between: 1 and: (c size)). + t := (c at: i). + c at: i put: (c at: r). + c at: r put: t + ] + ] +]. + +|tobesorted| +tobesorted := { 2 . 7 . 5 . 3 . 4 . 8 . 6 . 1 }. +bogosort value: tobesorted. +tobesorted displayNl. diff --git a/Task/Sorting-algorithms-Bogosort/Tcl/sorting-algorithms-bogosort.tcl b/Task/Sorting-algorithms-Bogosort/Tcl/sorting-algorithms-bogosort.tcl new file mode 100644 index 0000000000..2a54f79553 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Tcl/sorting-algorithms-bogosort.tcl @@ -0,0 +1,30 @@ +package require Tcl 8.5 + +proc shuffleInPlace {listName} { + upvar 1 $listName list + set len [set len2 [llength $list]] + for {set i 0} {$i < $len-1} {incr i; incr len2 -1} { + # Pick cell to swap with + set n [expr {int($i + $len2 * rand())}] + # Perform swap + set temp [lindex $list $i] + lset list $i [lindex $list $n] + lset list $n $temp + } +} +proc inOrder {list} { + set prev [lindex $list 0] + foreach item [lrange $list 1 end] { + if {$prev > $item} { + return false + } + set prev $item + } + return true +} +proc bogosort {list} { + while { ! [inOrder $list]} { + shuffleInPlace list + } + return $list +} diff --git a/Task/Sorting-algorithms-Bogosort/Ursala/sorting-algorithms-bogosort.ursala b/Task/Sorting-algorithms-Bogosort/Ursala/sorting-algorithms-bogosort.ursala new file mode 100644 index 0000000000..929e8b3a4a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ursala/sorting-algorithms-bogosort.ursala @@ -0,0 +1,10 @@ +#import std +#import nat + +shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC + +bogosort = (not ordered nleq)-> shuffle + +#cast %nL + +example = bogosort <8,50,0,12,47,51> diff --git a/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbscript b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbscript new file mode 100644 index 0000000000..17f2e3921f --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbscript @@ -0,0 +1,30 @@ +sub swap( byref a, byref b ) + dim tmp + tmp = a + a = b + b = tmp +end sub + +'knuth shuffle (I think) +function shuffle( a ) + dim i + dim r + randomize timer + for i = lbound( a ) to ubound( a ) + r = int( rnd * ( ubound( a ) + 1 ) ) + if r <> i then + swap a(i), a(r) + end if + next + shuffle = a +end function + +function inOrder( a ) + dim res + dim i + for i = 0 to ubound( a ) - 1 + res = ( a(i) <= a(i+1) ) + if res = false then exit for + next + inOrder = res +end function diff --git a/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbscript b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbscript new file mode 100644 index 0000000000..c40320164b --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbscript @@ -0,0 +1,10 @@ +dim a +a = array(11, 1, 2, 3, 4, 4, 6, 7, 8) + +dim t +t = timer +while not inorder( a ) + shuffle a +wend +wscript.echo timer-t, "seconds" +wscript.echo join( a, ", " ) diff --git a/Task/Sorting-algorithms-Bogosort/XPL0/sorting-algorithms-bogosort.xpl0 b/Task/Sorting-algorithms-Bogosort/XPL0/sorting-algorithms-bogosort.xpl0 new file mode 100644 index 0000000000..6535a02c48 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/XPL0/sorting-algorithms-bogosort.xpl0 @@ -0,0 +1,20 @@ +code Ran=1, ChOut=8, IntOut=11; + +proc BogoSort(A, L); \Sort array A of length L +int A, L; +int I, J, T; +[loop [I:= 0; + loop [if A(I) > A(I+1) then quit; + I:= I+1; + if I >= L-1 then return; + ]; + I:= Ran(L); J:= Ran(L); + T:= A(I); A(I):= A(J); A(J):= T; + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +BogoSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Bubble-sort/0DESCRIPTION b/Task/Sorting-algorithms-Bubble-sort/0DESCRIPTION new file mode 100644 index 0000000000..81ec113000 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/0DESCRIPTION @@ -0,0 +1,20 @@ +{{Sorting Algorithm}} +In this task, the goal is to sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers. + +The bubble sort is generally considered to be the simplest sorting algorithm. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n<sup>2</sup>) performance, it is not used often for large (or even medium-sized) datasets. + +The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them). Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. + +This can be expressed in pseudocode as follows (assuming 1-based indexing): + '''repeat''' + hasChanged := false + '''decrement''' itemCount + '''repeat with''' index '''from''' 1 '''to''' itemCount + '''if''' (item '''at''' index) > (item '''at''' (index + 1)) + swap (item '''at''' index) with (item '''at''' (index + 1)) + hasChanged := true + '''until''' hasChanged = '''false''' + +;References: +* The article on [[wp:Bubble_sort|Wikipedia]]. +* Dance [http://www.youtube.com/watch?v=lyZQPjUT5B4&feature=youtu.be interpretation]. diff --git a/Task/Sorting-algorithms-Bubble-sort/1META.yaml b/Task/Sorting-algorithms-Bubble-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Bubble-sort/ACL2/sorting-algorithms-bubble-sort.acl2 b/Task/Sorting-algorithms-Bubble-sort/ACL2/sorting-algorithms-bubble-sort.acl2 new file mode 100644 index 0000000000..62969afc78 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/ACL2/sorting-algorithms-bubble-sort.acl2 @@ -0,0 +1,26 @@ +(defun bubble (xs) + (if (endp (rest xs)) + (mv nil xs) + (let ((x1 (first xs)) + (x2 (second xs))) + (if (> x1 x2) + (mv-let (_ ys) + (bubble (cons x1 (rest (rest xs)))) + (declare (ignore _)) + (mv t (cons x2 ys))) + (mv-let (has-changed ys) + (bubble (rest xs)) + (mv has-changed (cons x1 ys))))))) + +(defun bsort-r (xs limit) + (declare (xargs :measure (nfix limit))) + (if (zp limit) + xs + (mv-let (has-changed ys) + (bubble xs) + (if has-changed + (bsort-r ys (1- limit)) + ys)))) + +(defun bsort (xs) + (bsort-r xs (len xs))) diff --git a/Task/Sorting-algorithms-Bubble-sort/ALGOL-68/sorting-algorithms-bubble-sort.alg b/Task/Sorting-algorithms-Bubble-sort/ALGOL-68/sorting-algorithms-bubble-sort.alg new file mode 100644 index 0000000000..787f5c8d93 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/ALGOL-68/sorting-algorithms-bubble-sort.alg @@ -0,0 +1,32 @@ +MODE DATA = INT; +PROC swap = (REF[]DATA slice)VOID: +( + DATA tmp = slice[1]; + slice[1] := slice[2]; + slice[2] := tmp +); + +PROC sort = (REF[]DATA array)VOID: +( + BOOL sorted; + INT shrinkage := 0; + FOR size FROM UPB array - 1 BY -1 WHILE + sorted := TRUE; + shrinkage +:= 1; + FOR i FROM LWB array TO size DO + IF array[i+1] < array[i] THEN + swap(array[i:i+1]); + sorted := FALSE + FI + OD; + NOT sorted + DO SKIP OD +); + +main:( + [10]INT random := (1,6,3,5,2,9,8,4,7,0); + + printf(($"Before: "10(g(3))l$,random)); + sort(random); + printf(($"After: "10(g(3))l$,random)) +) diff --git a/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort.awk b/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort.awk new file mode 100644 index 0000000000..88fc7e0d65 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/AWK/sorting-algorithms-bubble-sort.awk @@ -0,0 +1,20 @@ +{ # read every line into an array + line[NR] = $0 +} +END { # sort it with bubble sort + do { + haschanged = 0 + for(i=1; i < NR; i++) { + if ( line[i] > line[i+1] ) { + t = line[i] + line[i] = line[i+1] + line[i+1] = t + haschanged = 1 + } + } + } while ( haschanged == 1 ) + # print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/ActionScript/sorting-algorithms-bubble-sort.as b/Task/Sorting-algorithms-Bubble-sort/ActionScript/sorting-algorithms-bubble-sort.as new file mode 100644 index 0000000000..218cc190da --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/ActionScript/sorting-algorithms-bubble-sort.as @@ -0,0 +1,23 @@ +public function bubbleSort(toSort:Array):Array +{ + var changed:Boolean = false; + + while (!changed) + { + changed = true; + + for (var i:int = 0; i < toSort.length - 1; i++) + { + if (toSort[i] > toSort[i + 1]) + { + var tmp:int = toSort[i]; + toSort[i] = toSort[i + 1]; + toSort[i + 1] = tmp; + + changed = false; + } + } + } + + return toSort; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.ada b/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.ada new file mode 100644 index 0000000000..fb60bad2d8 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.ada @@ -0,0 +1,44 @@ +generic + type Element is private; + with function "=" (E1, E2 : Element) return Boolean is <>; + with function "<" (E1, E2 : Element) return Boolean is <>; + type Index is (<>); + type Arr is array (Index range <>) of Element; +procedure Bubble_Sort (A : in out Arr); + +procedure Bubble_Sort (A : in out Arr) is + Finished : Boolean; + Temp : Element; +begin + loop + Finished := True; + for J in A'First .. Index'Pred (A'Last) loop + if A (Index'Succ (J)) < A (J) then + Finished := False; + Temp := A (Index'Succ (J)); + A (Index'Succ (J)) := A (J); + A (J) := Temp; + end if; + end loop; + exit when Finished; + end loop; +end Bubble_Sort; + +-- Example of usage: +with Ada.Text_IO; use Ada.Text_IO; +with Bubble_Sort; +procedure Main is + type Arr is array (Positive range <>) of Integer; + procedure Sort is new + Bubble_Sort + (Element => Integer, + Index => Positive, + Arr => Arr); + A : Arr := (1, 3, 256, 0, 3, 4, -1); +begin + Sort (A); + for J in A'Range loop + Put (Integer'Image (A (J))); + end loop; + New_Line; +end Main; diff --git a/Task/Sorting-algorithms-Bubble-sort/AutoHotkey/sorting-algorithms-bubble-sort.ahk b/Task/Sorting-algorithms-Bubble-sort/AutoHotkey/sorting-algorithms-bubble-sort.ahk new file mode 100644 index 0000000000..7d37c284ac --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/AutoHotkey/sorting-algorithms-bubble-sort.ahk @@ -0,0 +1,35 @@ +var = +( +dog +cat +pile +abc +) +MsgBox % bubblesort(var) + +bubblesort(var) ; each line of var is an element of the array +{ + StringSplit, array, var, `n + hasChanged = 1 + size := array0 + While hasChanged + { + hasChanged = 0 + Loop, % (size - 1) + { + i := array%A_Index% + aj := A_Index + 1 + j := array%aj% + If (j < i) + { + temp := array%A_Index% + array%A_Index% := array%aj% + array%aj% := temp + hasChanged = 1 + } + } + } + Loop, % size + sorted .= array%A_Index% . "`n" + Return sorted +} diff --git a/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort.basic b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort.basic new file mode 100644 index 0000000000..07b6387788 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/BASIC/sorting-algorithms-bubble-sort.basic @@ -0,0 +1,11 @@ +DO + changed = 0 + FOR I = 1 to size -1 + IF nums(I) > nums(I + 1) THEN + tmp = nums(I) + nums(I) = nums(I + 1) + nums(I + 1) = tmp + changed = 1 + END IF + NEXT +LOOP WHILE(NOT changed) diff --git a/Task/Sorting-algorithms-Bubble-sort/BASIC256/sorting-algorithms-bubble-sort.basic256 b/Task/Sorting-algorithms-Bubble-sort/BASIC256/sorting-algorithms-bubble-sort.basic256 new file mode 100644 index 0000000000..ffd7b036be --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/BASIC256/sorting-algorithms-bubble-sort.basic256 @@ -0,0 +1,24 @@ +Dim a(11): ordered=false +print "Original set" +For n = 0 to 9 +a[n]=int(rand*20+1) +print a[n]+", "; +next n +#algorithm +while ordered=false + ordered=true + For n = 0 to 9 + if a[n]> a[n+1] then + x=a[n] + a[n]=a[n+1] + a[n+1]=x + ordered=false + end if + next n +end while + +print +print "Ordered set" +For n = 1 to 10 +print a[n]+", "; +next n diff --git a/Task/Sorting-algorithms-Bubble-sort/BBC-BASIC/sorting-algorithms-bubble-sort.bbc b/Task/Sorting-algorithms-Bubble-sort/BBC-BASIC/sorting-algorithms-bubble-sort.bbc new file mode 100644 index 0000000000..71eb280b70 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/BBC-BASIC/sorting-algorithms-bubble-sort.bbc @@ -0,0 +1,22 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCbubblesort(test(), 10) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCbubblesort(a(), n%) + LOCAL i%, l% + REPEAT + l% = 0 + FOR i% = 1 TO n%-1 + IF a(i%-1) > a(i%) THEN + SWAP a(i%-1),a(i%) + l% = i% + ENDIF + NEXT + n% = l% + UNTIL l% = 0 + ENDPROC diff --git a/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp b/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp new file mode 100644 index 0000000000..7097064050 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp @@ -0,0 +1,42 @@ +#include <iostream> +#include <algorithm> + +template< typename ARRAY_TYPE, typename INDEX_TYPE > +void bubble_sort(ARRAY_TYPE array[], INDEX_TYPE size) +{ + bool done = false; + + while ( ! done) + { + done = true; + for (INDEX_TYPE i = 0 ; i < size-1 ; i++) + { + if (array[i] > array[i+1]) + { + done = false; + std::swap(array[i], array[i+1]); + } + } + size--; + } +} + +template< typename TYPE > +void print(TYPE val) +{ + std::cout << val << " "; +} + +int main() +{ + int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; + bubble_sort(array, 10); + std::for_each (&array[0], &array[10], print<int>); + std::cout << std::endl; + + //But in real life... + int data[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; + std::sort(data, data+10); + std::for_each (data, data+10, print<int>); + std::cout << std::endl; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c b/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c new file mode 100644 index 0000000000..009ff225e7 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c @@ -0,0 +1,16 @@ +void bubble_sort(int *a, int n) { + int j, t = 1; + while (n-- && t) + for (j = t = 0; j < n; j++) { + if (a[j] <= a[j + 1]) continue; + t = a[j], a[j] = a[j + 1], a[j + 1] = t; + t=1; + } +} + +int main(void) { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + bubble_sort(a, sizeof(a) / sizeof(a[0])); + + return 0; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-1.cmake b/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-1.cmake new file mode 100644 index 0000000000..c4ac90925a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-1.cmake @@ -0,0 +1,26 @@ +# bubble_sort(var [value1 value2...]) sorts a list of integers. +function(bubble_sort var) + math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last]. + set(again YES) + while(again) + set(again NO) + math(EXPR last "${last} - 1") # Decrement last index. + foreach(index RANGE 1 ${last}) # Loop for each index. + math(EXPR index_plus_1 "${index} + 1") + set(a "${ARGV${index}}") # a = ARGV[index] + set(b "${ARGV${index_plus_1}}") # b = ARGV[index + 1] + if(a GREATER "${b}") # If a > b... + set(ARGV${index} "${b}") # ...then swap a, b + set(ARGV${index_plus_1} "${a}") # inside ARGV. + set(again YES) + endif() + endforeach(index) + endwhile() + + set(answer) + math(EXPR last "${ARGC} - 1") + foreach(index RANGE 1 "${last}") + list(APPEND answer "${ARGV${index}}") + endforeach(index) + set("${var}" "${answer}" PARENT_SCOPE) +endfunction(bubble_sort) diff --git a/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-2.cmake b/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-2.cmake new file mode 100644 index 0000000000..7ccc7366fa --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/CMake/sorting-algorithms-bubble-sort-2.cmake @@ -0,0 +1,2 @@ +bubble_sort(result 33 11 44 22 66 55) +message(STATUS "${result}") diff --git a/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol new file mode 100644 index 0000000000..8944734d50 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol @@ -0,0 +1,145 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. BUBBLESORT. + AUTHOR. DAVE STRATFORD. + DATE-WRITTEN. MARCH 2010. + INSTALLATION. HEXAGON SYSTEMS LIMITED. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + SOURCE-COMPUTER. ICL VME. + OBJECT-COMPUTER. ICL VME. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT FA-INPUT-FILE ASSIGN FL01. + SELECT FB-OUTPUT-FILE ASSIGN FL02. + + DATA DIVISION. + FILE SECTION. + + FD FA-INPUT-FILE. + 01 FA-INPUT-REC. + 03 FA-DATA PIC S9(6). + + FD FB-OUTPUT-FILE. + 01 FB-OUTPUT-REC PIC S9(6). + + WORKING-STORAGE SECTION. + 01 WA-IDENTITY. + 03 WA-PROGNAME PIC X(10) VALUE "BUBBLESORT". + 03 WA-VERSION PIC X(6) VALUE "000001". + + 01 WB-TABLE. + 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 + INDEXED BY WB-IX-1. + + 01 WC-VARS. + 03 WC-SIZE PIC S9(8) COMP SYNC. + 03 WC-TEMP PIC S9(8) COMP SYNC. + 03 WC-END PIC S9(8) COMP SYNC. + 03 WC-LAST-CHANGE PIC S9(8) COMP SYNC. + + 01 WF-CONDITION-FLAGS. + 03 WF-EOF-FLAG PIC X. + 88 END-OF-FILE VALUE "Y". + 03 WF-EMPTY-FILE-FLAG PIC X. + 88 EMPTY-FILE VALUE "Y". + + PROCEDURE DIVISION. + A-MAIN SECTION. + A-000. + PERFORM B-INITIALISE. + IF NOT EMPTY-FILE + PERFORM C-SORT. + PERFORM D-FINISH. + + A-999. + STOP RUN. + + B-INITIALISE SECTION. + B-000. + DISPLAY "*** " WA-PROGNAME " VERSION " + WA-VERSION " STARTING ***". + + MOVE ALL "N" TO WF-CONDITION-FLAGS. + OPEN INPUT FA-INPUT-FILE. + SET WB-IX-1 TO 0. + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG + WF-EMPTY-FILE-FLAG. + + PERFORM BA-READ-INPUT UNTIL END-OF-FILE. + + CLOSE FA-INPUT-FILE. + + SET WC-SIZE TO WB-IX-1. + + B-999. + EXIT. + + BA-READ-INPUT SECTION. + BA-000. + SET WB-IX-1 UP BY 1. + MOVE FA-DATA TO WB-ENTRY(WB-IX-1). + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG. + + BA-999. + EXIT. + + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE WC-SIZE TO WC-END. + PERFORM E-BUBBLE UNTIL WC-END = 1. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + D-FINISH SECTION. + D-000. + OPEN OUTPUT FB-OUTPUT-FILE. + SET WB-IX-1 TO 1. + + PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE. + + CLOSE FB-OUTPUT-FILE. + + DISPLAY "*** " WA-PROGNAME " FINISHED ***". + + D-999. + EXIT. + + DA-WRITE-OUTPUT SECTION. + DA-000. + WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). + SET WB-IX-1 UP BY 1. + + DA-999. + EXIT. + + E-BUBBLE SECTION. + E-000. + MOVE 1 TO WC-LAST-CHANGE. + + PERFORM F-PASS VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 = WC-END. + + MOVE WC-LAST-CHANGE TO WC-END. + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-1) > WB-ENTRY(WB-IX-1 + 1) + SET WC-LAST-CHANGE TO WB-IX-1 + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1 + 1) TO WB-ENTRY(WB-IX-1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1 + 1). + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-1.clean b/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-1.clean new file mode 100644 index 0000000000..6ef9525851 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-1.clean @@ -0,0 +1,14 @@ +import StdEnv + +bsort :: *(a e) -> *(a e) | Array a e & < e +bsort array + # (done, array) = sweep 1 True array + = if done array (bsort array) +where + sweep :: !Int !Bool !*(a e) -> (!Bool, !*(a e)) | Array a e & < e + sweep i done array + | i >= size array = (done, array) + # (e1, array) = array![i - 1] + (e2, array) = array![i] + | e1 > e2 = sweep (i + 1) False {array & [i - 1] = e2, [i] = e1} + = sweep (i + 1) done array diff --git a/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean b/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean new file mode 100644 index 0000000000..d28e355c67 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Clean/sorting-algorithms-bubble-sort-2.clean @@ -0,0 +1,2 @@ +Start :: {Int} +Start = bsort {x \\ x <- [100,99..1]} diff --git a/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-1.clj b/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-1.clj new file mode 100644 index 0000000000..741021efd9 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-1.clj @@ -0,0 +1,27 @@ +(ns bubblesort + (:import java.util.ArrayList)) + +(defn bubble-sort + "Sort in-place. + arr must implement the Java List interface and should support + random access, e.g. an ArrayList." + ([arr] (bubble-sort compare arr)) + ([cmp arr] + (letfn [(swap! [i j] + (let [t (.get arr i)] + (doto arr + (.set i (.get arr j)) + (.set j t)))) + (sorter [stop-i] + (let [changed (atom false)] + (doseq [i (range stop-i)] + (if (pos? (cmp (.get arr i) (.get arr (inc i)))) + (do + (swap! i (inc i)) + (reset! changed true)))) + @changed))] + (doseq [stop-i (range (dec (.size arr)) -1 -1) + :while (sorter stop-i)]) + arr))) + +(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1]))) diff --git a/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-2.clj b/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-2.clj new file mode 100644 index 0000000000..9636929418 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Clojure/sorting-algorithms-bubble-sort-2.clj @@ -0,0 +1,27 @@ +(defn- bubble-step + "was-changed: whether any elements prior to the current first element + were swapped; + returns a two-element vector [partially-sorted-sequence is-sorted]" + [less? xs was-changed] + (if (< (count xs) 2) + [xs (not was-changed)] + (let [[x1 x2 & xr] xs + first-is-smaller (less? x1 x2) + is-changed (or was-changed (not first-is-smaller)) + [smaller larger] (if first-is-smaller [x1 x2] [x2 x1]) + [result is-sorted] (bubble-step + less? (cons larger xr) is-changed)] + [(cons smaller result) is-sorted]))) + +(defn bubble-sort + "Takes an optional less-than predicate and a sequence. + Returns the sorted sequence. + Very inefficient (O(n²))" + ([xs] (bubble-sort <= xs)) + ([less? xs] + (let [[result is-sorted] (bubble-step less? xs false)] + (if is-sorted + result + (recur less? result))))) + +(println (bubble-sort [10 9 8 7 6 5 4 3 2 1])) diff --git a/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-1.lisp b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-1.lisp new file mode 100644 index 0000000000..3bce9c1d8b --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-1.lisp @@ -0,0 +1,10 @@ +(defun bubble-sort (sequence &optional (compare #'<)) + "sort a sequence (array or list) with an optional comparison function (cl:< is the default)" + (loop with sorted = nil until sorted do + (setf sorted t) + (loop for a below (1- (length sequence)) do + (unless (funcall compare (elt sequence a) + (elt sequence (1+ a))) + (rotatef (elt sequence a) + (elt sequence (1+ a))) + (setf sorted nil))))) diff --git a/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-2.lisp b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-2.lisp new file mode 100644 index 0000000000..c61cc6dcbf --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-2.lisp @@ -0,0 +1 @@ +(bubble-sort (list 5 4 3 2 1)) diff --git a/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-3.lisp b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-3.lisp new file mode 100644 index 0000000000..f5fe7991ab --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Common-Lisp/sorting-algorithms-bubble-sort-3.lisp @@ -0,0 +1,20 @@ +(defun bubble-sort-vector (vector predicate &aux (len (1- (length vector)))) + (do ((swapped t)) ((not swapped) vector) + (setf swapped nil) + (do ((i (min 0 len) (1+ i))) ((eql i len)) + (when (funcall predicate (aref vector (1+ i)) (aref vector i)) + (rotatef (aref vector i) (aref vector (1+ i))) + (setf swapped t))))) + +(defun bubble-sort-list (list predicate) + (do ((swapped t)) ((not swapped) list) + (setf swapped nil) + (do ((list list (rest list))) ((endp (rest list))) + (when (funcall predicate (second list) (first list)) + (rotatef (first list) (second list)) + (setf swapped t))))) + +(defun bubble-sort (sequence predicate) + (etypecase sequence + (list (bubble-sort-list sequence predicate)) + (vector (bubble-sort-vector sequence predicate)))) diff --git a/Task/Sorting-algorithms-Bubble-sort/D/sorting-algorithms-bubble-sort.d b/Task/Sorting-algorithms-Bubble-sort/D/sorting-algorithms-bubble-sort.d new file mode 100644 index 0000000000..eb02d776dc --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/D/sorting-algorithms-bubble-sort.d @@ -0,0 +1,22 @@ +import std.stdio, std.algorithm; + +void bubbleSort(T)(T[] data) pure nothrow { + auto itemCount = data.length; + bool hasChanged = false; + + do { + hasChanged = false; + itemCount--; + foreach (immutable i; 0 .. itemCount) + if (data[i] > data[i + 1]) { + swap(data[i], data[i + 1]); + hasChanged = true; + } + } while (hasChanged); +} + +void main() { + auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; + array.bubbleSort(); + writeln(array); +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Delphi/sorting-algorithms-bubble-sort.delphi b/Task/Sorting-algorithms-Bubble-sort/Delphi/sorting-algorithms-bubble-sort.delphi new file mode 100644 index 0000000000..e28562c4de --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Delphi/sorting-algorithms-bubble-sort.delphi @@ -0,0 +1,54 @@ +program TestBubbleSort; + +{$APPTYPE CONSOLE} + +{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array + +type + TItem = Integer; // declare ordinal type for array item +{$IFDEF DYNARRAY} + TArray = array of TItem; // dynamic array +{$ELSE} + TArray = array[0..15] of TItem; // static array +{$ENDIF} + +procedure BubbleSort(var A: TArray); +var + Item: TItem; + K, L, J: Integer; + +begin + L:= Low(A) + 1; + repeat + K:= High(A); + for J:= High(A) downto L do begin + if A[J - 1] > A[J] then begin + Item:= A[J - 1]; + A[J - 1]:= A[J]; + A[J]:= Item; + K:= J; + end; + end; + L:= K + 1; + until L > High(A); +end; + +var + A: TArray; + I: Integer; + +begin +{$IFDEF DYNARRAY} + SetLength(A, 16); +{$ENDIF} + for I:= Low(A) to High(A) do + A[I]:= Random(100); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + BubbleSort(A); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + Readln; +end. diff --git a/Task/Sorting-algorithms-Bubble-sort/E/sorting-algorithms-bubble-sort.e b/Task/Sorting-algorithms-Bubble-sort/E/sorting-algorithms-bubble-sort.e new file mode 100644 index 0000000000..dbe350c645 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/E/sorting-algorithms-bubble-sort.e @@ -0,0 +1,13 @@ +def bubbleSort(target) { + __loop(fn { + var changed := false + for i in 0..(target.size() - 2) { + def [a, b] := target(i, i + 2) + if (a > b) { + target(i, i + 2) := [b, a] + changed := true + } + } + changed + }) +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-1.e b/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-1.e new file mode 100644 index 0000000000..cb329cde29 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-1.e @@ -0,0 +1,30 @@ +class + APPLICATION +create + make + +feature + make + -- Create and print sorted set + do + create my_set.make + my_set.put_front (2) + my_set.put_front (6) + my_set.put_front (1) + my_set.put_front (5) + my_set.put_front (3) + my_set.put_front (9) + my_set.put_front (8) + my_set.put_front (4) + my_set.put_front (10) + my_set.put_front (7) + print ("Before: ") + across my_set as ic loop print (ic.item.out + " ") end + print ("%NAfter : ") + my_set.sort + across my_set as ic loop print (ic.item.out + " ") end + end + + my_set: MY_SORTED_SET [INTEGER] + -- Set to be sorted +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-2.e b/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-2.e new file mode 100644 index 0000000000..7fb8cf22d7 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Eiffel/sorting-algorithms-bubble-sort-2.e @@ -0,0 +1,36 @@ +class + MY_SORTED_SET [G -> COMPARABLE] +inherit + TWO_WAY_SORTED_SET [G] + redefine + sort + end +create + make + +feature + sort + -- Sort with bubble sort + local + l_unchanged: BOOLEAN + l_item_count: INTEGER + l_temp: G + do + from + l_item_count := count + until + l_unchanged + loop + l_unchanged := True + l_item_count := l_item_count - 1 + across 1 |..| l_item_count as ic loop + if Current [ic.item] > Current [ic.item + 1] then + l_temp := Current [ic.item] + Current [ic.item] := Current [ic.item + 1] + Current [ic.item + 1] := l_temp + l_unchanged := False + end + end + end + end +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.euphoria b/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.euphoria new file mode 100644 index 0000000000..f9ff6454ad --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.euphoria @@ -0,0 +1,27 @@ +function bubble_sort(sequence s) + object tmp + integer changed + for j = length(s) to 1 by -1 do + changed = 0 + for i = 1 to j-1 do + if compare(s[i], s[i+1]) > 0 then + tmp = s[i] + s[i] = s[i+1] + s[i+1] = tmp + changed = 1 + end if + end for + if not changed then + exit + end if + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,bubble_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-1.factor b/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-1.factor new file mode 100644 index 0000000000..e7b349de50 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-1.factor @@ -0,0 +1,23 @@ +USING: fry kernel locals math math.order sequences +sequences.private ; +IN: rosetta.bubble + +<PRIVATE + +:: ?exchange ( i seq quot -- ? ) + i i 1 + [ seq nth-unsafe ] bi@ quot call +gt+ = :> doit? + doit? [ i i 1 + seq exchange ] when + doit? ; inline + +: 1pass ( seq quot -- ? ) + [ [ length 1 - iota ] keep ] dip + '[ _ _ ?exchange ] [ or ] map-reduce ; inline + +PRIVATE> + +: sort! ( seq quot -- ) + over empty? + [ 2drop ] [ '[ _ _ 1pass ] loop ] if ; inline + +: natural-sort! ( seq -- ) + [ <=> ] sort! ; diff --git a/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-2.factor b/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-2.factor new file mode 100644 index 0000000000..9d471e4f06 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Factor/sorting-algorithms-bubble-sort-2.factor @@ -0,0 +1,4 @@ +10 [ 10000 random ] replicate +[ "Before: " write . ] +[ "Natural: " write [ natural-sort! ] keep . ] +[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri diff --git a/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-1.fth b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-1.fth new file mode 100644 index 0000000000..84f3cb8d3a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-1.fth @@ -0,0 +1,9 @@ +defer bubble-test +' > is bubble-test + +: bubble { addr cnt -- } + cnt 1 do + addr cnt i - cells bounds do + i 2@ bubble-test if i 2@ swap i 2! then + cell +loop + loop ; diff --git a/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-2.fth b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-2.fth new file mode 100644 index 0000000000..47cc1d0376 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-2.fth @@ -0,0 +1,6 @@ +: bubble ( addr cnt -- ) + dup 1 do + 2dup i - cells bounds do + i 2@ bubble-test if i 2@ swap i 2! then + cell +loop + loop ; diff --git a/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-3.fth b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-3.fth new file mode 100644 index 0000000000..5838d36a64 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Forth/sorting-algorithms-bubble-sort-3.fth @@ -0,0 +1,10 @@ +: bubble ( addr len -- ) + begin + 1- 2dup true -rot ( sorted addr len-1 ) + cells bounds ?do + i 2@ bubble-test if + i 2@ swap i 2! + drop false ( mark unsorted ) + then + cell +loop ( sorted ) + until 2drop ; diff --git a/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f b/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f new file mode 100644 index 0000000000..c15ef80f14 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f @@ -0,0 +1,19 @@ +SUBROUTINE Bubble_Sort(a) + REAL, INTENT(in out), DIMENSION(:) :: a + REAL :: temp + INTEGER :: i, j + LOGICAL :: swapped = .TRUE. + + DO j = SIZE(a)-1, 1, -1 + swapped = .FALSE. + DO i = 1, j + IF (a(i) > a(i+1)) THEN + temp = a(i) + a(i) = a(i+1) + a(i+1) = temp + swapped = .TRUE. + END IF + END DO + IF (.NOT. swapped) EXIT + END DO +END SUBROUTINE Bubble_Sort diff --git a/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-1.go b/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-1.go new file mode 100644 index 0000000000..50c24ca4b2 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-1.go @@ -0,0 +1,26 @@ +package main + +import "fmt" + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + bubblesort(list) + fmt.Println("sorted! ", list) +} + +func bubblesort(a []int) { + for itemCount := len(a) - 1; ; itemCount-- { + hasChanged := false + for index := 0; index < itemCount; index++ { + if a[index] > a[index+1] { + a[index], a[index+1] = a[index+1], a[index] + hasChanged = true + } + } + if hasChanged == false { + break + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-2.go b/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-2.go new file mode 100644 index 0000000000..2395db4c9c --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Go/sorting-algorithms-bubble-sort-2.go @@ -0,0 +1,29 @@ +package main + +import ( + "sort" + "fmt" +) + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + bubblesort(sort.IntSlice(list)) + fmt.Println("sorted! ", list) +} + +func bubblesort(a sort.Interface) { + for itemCount := a.Len() - 1; ; itemCount-- { + hasChanged := false + for index := 0; index < itemCount; index++ { + if a.Less(index+1, index) { + a.Swap(index, index+1) + hasChanged = true + } + } + if !hasChanged { + break + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-1.groovy b/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-1.groovy new file mode 100644 index 0000000000..20a535bff8 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-1.groovy @@ -0,0 +1,9 @@ +def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] } + +def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } + +def bubbleSort = { list -> + boolean swapped = true + while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } + list +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-2.groovy b/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-2.groovy new file mode 100644 index 0000000000..2f6538976c --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Groovy/sorting-algorithms-bubble-sort-2.groovy @@ -0,0 +1,2 @@ +println bubbleSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]) +println bubbleSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]) diff --git a/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-1.hs b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-1.hs new file mode 100644 index 0000000000..d78cbddf9b --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-1.hs @@ -0,0 +1,7 @@ +bsort :: Ord a => [a] -> [a] +bsort s = case _bsort s of + t | t == s -> t + | otherwise -> bsort t + where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) + | otherwise = x:(_bsort (x2:xs)) + _bsort s = s diff --git a/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-2.hs b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-2.hs new file mode 100644 index 0000000000..540473df41 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-2.hs @@ -0,0 +1,9 @@ +import Data.Maybe (fromMaybe) +import Control.Monad + +bsort :: Ord a => [a] -> [a] +bsort s = maybe s bsort $ _bsort s + where _bsort (x:x2:xs) = if x > x2 + then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs) + else liftM (x:) $ _bsort (x2:xs) + _bsort _ = Nothing diff --git a/Task/Sorting-algorithms-Bubble-sort/HicEst/sorting-algorithms-bubble-sort.hicest b/Task/Sorting-algorithms-Bubble-sort/HicEst/sorting-algorithms-bubble-sort.hicest new file mode 100644 index 0000000000..f6c25cadea --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/HicEst/sorting-algorithms-bubble-sort.hicest @@ -0,0 +1,16 @@ +SUBROUTINE Bubble_Sort(a) + REAL :: a(1) + + DO j = LEN(a)-1, 1, -1 + swapped = 0 + DO i = 1, j + IF (a(i) > a(i+1)) THEN + temp = a(i) + a(i) = a(i+1) + a(i+1) = temp + swapped = 1 + ENDIF + ENDDO + IF (swapped == 0) RETURN + ENDDO +END diff --git a/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-1.icon b/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-1.icon new file mode 100644 index 0000000000..84c84ec257 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-1.icon @@ -0,0 +1,16 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure bubblesort(X,op) #: return sorted list +local i,swapped + + op := sortop(op,X) # select how and what we sort + + swapped := 1 + while \swapped := &null do # the sort + every i := 2 to *X do + if op(X[i],X[i-1]) then + X[i-1] :=: X[swapped := i] + return X +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-2.icon b/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-2.icon new file mode 100644 index 0000000000..c8629f3dda --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Icon/sorting-algorithms-bubble-sort-2.icon @@ -0,0 +1,59 @@ +invocable all # for op + +procedure sortop(op,X) #: select how to sort + + op := case op of { + "string": "<<" + "numeric": "<" + &null: if type(!X) == "string" then "<<" else "<" + default: op + } +return proc(op, 2) | runerr(123, image(op)) +end + +procedure cmp(a,b) #: example custom comparison procedure + return a < b # Imagine a complex comparison test here! +end + +procedure demosort(sortproc,L,s) # demonstrate sort on L and s + + write("Sorting Demo using ",image(sortproc)) + writes(" on list : ") + writex(L) + displaysort(sortproc,L) # default string sort + displaysort(sortproc,L,"numeric") # explicit numeric sort + displaysort(sortproc,L,"string") # explicit string sort + displaysort(sortproc,L,">>") # descending string sort + displaysort(sortproc,L,">") # descending numeric sort + displaysort(sortproc,L,cmp) # ascending custom comparison + displaysort(sortproc,L,"cmp") # ascending custom comparison + + writes(" on string : ") + writex(s) + displaysort(sortproc,s) # sort characters in a string + write() + return +end + +procedure displaysort(sortproc,X,op) #: helper to show sort behavior +local t,SX + writes(" with op = ",left(image(op)||":",15)) + X := copy(X) + t := &time + SX := sortproc(X,op) + writex(SX," (",&time - t," ms)") + return +end + +procedure writex(X,suf[]) #: helper for displaysort + if type(X) == "string" then + writes(image(X)) + else { + writes("[") + every writes(" ",image(!X)) + writes(" ]") + } + every writes(!suf) + write() +return +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Io/sorting-algorithms-bubble-sort.io b/Task/Sorting-algorithms-Bubble-sort/Io/sorting-algorithms-bubble-sort.io new file mode 100644 index 0000000000..4577127920 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Io/sorting-algorithms-bubble-sort.io @@ -0,0 +1,15 @@ +List do( + bubblesort := method( + t := true + while( t, + t := false + for( j, 0, self size - 2, + if( self at( j ) start > self at( j+1 ) start, + self swapIndices( j,j+1 ) + t := true + ) + ) + ) + return( self ) + ) +) diff --git a/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-1.j b/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-1.j new file mode 100644 index 0000000000..82a70e9e81 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-1.j @@ -0,0 +1 @@ +bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_ diff --git a/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-2.j b/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-2.j new file mode 100644 index 0000000000..19653cb794 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/J/sorting-algorithms-bubble-sort-2.j @@ -0,0 +1,4 @@ + ?. 10 $ 10 +4 6 8 6 5 8 6 6 6 9 + bubbleSort ?. 10 $ 10 +4 5 6 6 6 6 6 8 8 9 diff --git a/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-1.java b/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-1.java new file mode 100644 index 0000000000..05570bc6f3 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-1.java @@ -0,0 +1,14 @@ +public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { + boolean changed = false; + do { + changed = false; + for (int a = 0; a < comparable.length - 1; a++) { + if (comparable[a].compareTo(comparable[a + 1]) > 0) { + E tmp = comparable[a]; + comparable[a] = comparable[a + 1]; + comparable[a + 1] = tmp; + changed = true; + } + } + } while (changed); +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-2.java b/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-2.java new file mode 100644 index 0000000000..6cf0b5703f --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Java/sorting-algorithms-bubble-sort-2.java @@ -0,0 +1,3 @@ +if (comparable[a].compareTo(comparable[b]) < 0){ + //same swap code as before +} diff --git a/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-1.js b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-1.js new file mode 100644 index 0000000000..31ffc6dc66 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-1.js @@ -0,0 +1,13 @@ +Array.prototype.bubblesort = function() { + var done = false; + while (!done) { + done = true; + for (var i = 1; i<this.length; i++) { + if (this[i-1] > this[i]) { + done = false; + [this[i-1], this[i]] = [this[i], this[i-1]] + } + } + } + return this; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-2.js b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-2.js new file mode 100644 index 0000000000..f6c8517bbf --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-2.js @@ -0,0 +1,15 @@ +Array.prototype.bubblesort = function() { + var done = false; + while (! done) { + done = true; + for (var i = 1; i < this.length; i++) { + if (this[i - 1] > this[i]) { + done = false; + var tmp = this[i - 1]; + this[i - 1] = this[i]; + this[i] = tmp; + } + } + } + return this; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-3.js b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-3.js new file mode 100644 index 0000000000..76ca26bda8 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/JavaScript/sorting-algorithms-bubble-sort-3.js @@ -0,0 +1,3 @@ +var my_arr = ["G", "F", "C", "A", "B", "E", "D"]; +my_arr.bubblesort(); +print(my_arr); diff --git a/Task/Sorting-algorithms-Bubble-sort/Liberty-BASIC/sorting-algorithms-bubble-sort.liberty b/Task/Sorting-algorithms-Bubble-sort/Liberty-BASIC/sorting-algorithms-bubble-sort.liberty new file mode 100644 index 0000000000..891571db44 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Liberty-BASIC/sorting-algorithms-bubble-sort.liberty @@ -0,0 +1,28 @@ + itemCount = 20 + dim item(itemCount) + for i = 1 to itemCount + item(i) = int(rnd(1) * 100) + next i + print "Before Sort" + for i = 1 to itemCount + print item(i) + next i + print: print + counter = itemCount + do + hasChanged = 0 + for i = 1 to counter - 1 + if item(i) > item(i + 1) then + temp = item(i) + item(i) = item(i + 1) + item(i + 1) = temp + hasChanged = 1 + end if + next i + counter =counter -1 + loop while hasChanged = 1 + print "After Sort" + for i = 1 to itemCount + print item(i) + next i +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Lisaac/sorting-algorithms-bubble-sort.lisaac b/Task/Sorting-algorithms-Bubble-sort/Lisaac/sorting-algorithms-bubble-sort.lisaac new file mode 100644 index 0000000000..5551d41925 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Lisaac/sorting-algorithms-bubble-sort.lisaac @@ -0,0 +1,43 @@ +Section Header + ++ name := BUBBLE_SORT; + +- external := `#include <time.h>`; + +Section Public + +- main <- ( + + a : ARRAY(INTEGER); + + a := ARRAY(INTEGER).create 0 to 100; + `srand(time(NULL))`; + 0.to 100 do { i : INTEGER; + a.put `rand()`:INTEGER to i; + }; + + bubble a; + + a.foreach { item : INTEGER; + item.print; + '\n'.print; + }; +); + +- bubble a : ARRAY(INTEGER) <- ( + + lower, size, t : INTEGER; + + sorted : BOOLEAN; + lower := a.lower; + size := a.upper - lower + 1; + { + sorted := TRUE; + size := size - 1; + 0.to (size - 1) do { i : INTEGER; + (a.item(lower + i + 1) < a.item(lower + i)).if { + t := a.item(lower + i + 1); + a.put (a.item(lower + i)) to (lower + i + 1); + a.put t to (lower + i); + sorted := FALSE; + }; + }; + }.do_while {!sorted}; +); diff --git a/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-1.lua b/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-1.lua new file mode 100644 index 0000000000..728283e9fa --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-1.lua @@ -0,0 +1,14 @@ +function bubbleSort(A) + local itemCount=#A + local hasChanged + repeat + hasChanged = false + itemCount=itemCount - 1 + for i = 1, itemCount do + if A[i] > A[i + 1] then + A[i], A[i + 1] = A[i + 1], A[i] + hasChanged = true + end + end + until hasChanged == false +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-2.lua b/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-2.lua new file mode 100644 index 0000000000..90264d7f4d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Lua/sorting-algorithms-bubble-sort-2.lua @@ -0,0 +1,5 @@ +list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 } +bubbleSort(list) +for i, j in pairs(list) do + print(j) +end diff --git a/Task/Sorting-algorithms-Bubble-sort/Lucid/sorting-algorithms-bubble-sort.lucid b/Task/Sorting-algorithms-Bubble-sort/Lucid/sorting-algorithms-bubble-sort.lucid new file mode 100644 index 0000000000..ee7958d648 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Lucid/sorting-algorithms-bubble-sort.lucid @@ -0,0 +1,16 @@ +bsort(a) = if iseod(first a) then a else + follow(bsort(allbutlast(b)),last(b)) fi + where + b = bubble(a); + bubble(a) = smaller(max, next a) + where + max = first a fby larger(max, next a); + larger(x,y) = if iseod(y) then y elseif x + end; + follow(x,y) = if xdone then y upon xdone else x fi + where + xdone = iseod x fby xdone or iseod x; + end; + last(x) = (x asa iseod next x) fby eod; + allbutlast(x) = if not iseod(next x) then x else eod fi; + end diff --git a/Task/Sorting-algorithms-Bubble-sort/M4/sorting-algorithms-bubble-sort.m4 b/Task/Sorting-algorithms-Bubble-sort/M4/sorting-algorithms-bubble-sort.m4 new file mode 100644 index 0000000000..636d5e7ca9 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/M4/sorting-algorithms-bubble-sort.m4 @@ -0,0 +1,45 @@ +divert(-1) + +define(`randSeed',141592653) +define(`setRand', + `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') +define(`rand_t',`eval(randSeed^(randSeed>>13))') +define(`random', + `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') + +define(`set',`define(`$1[$2]',`$3')') +define(`get',`defn(`$1[$2]')') +define(`new',`set($1,size,0)') +dnl for the heap calculations, it's easier if origin is 0, so set value first +define(`append', + `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)') + +dnl swap(<name>,<j>,<name>[<j>],<k>) using arg stack for the temporary +define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)') + +define(`deck', + `new($1)for(`x',1,$2, + `append(`$1',eval(random%100))')') +define(`show', + `for(`x',1,get($1,size),`get($1,x) ')') +define(`for', + `ifelse($#,0,``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') + +define(`bubbleonce', + `for(`x',1,$2, + `ifelse(eval(get($1,x)>get($1,incr(x))),1, + `swap($1,x,get($1,x),incr(x))`'1')')0') +define(`bubbleupto', + `ifelse(bubbleonce($1,$2),0, + `', + `bubbleupto($1,decr($2))')') +define(`bubblesort', + `bubbleupto($1,decr(get($1,size)))') + +divert +deck(`a',10) +show(`a') +bubblesort(`a') +show(`a') diff --git a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m new file mode 100644 index 0000000000..2598b65718 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-1.m @@ -0,0 +1,20 @@ +function list = bubbleSort(list) + + hasChanged = true; + itemCount = numel(list); + + while(hasChanged) + + hasChanged = false; + itemCount = itemCount - 1; + + for index = (1:itemCount) + + if(list(index) > list(index+1)) + list([index index+1]) = list([index+1 index]); %swap + hasChanged = true; + end %if + + end %for + end %while +end %bubbleSort diff --git a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m new file mode 100644 index 0000000000..63d5d587e9 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort-2.m @@ -0,0 +1,5 @@ +bubbleSort([5 3 8 4 9 7 6 2 1]) + +ans = + + 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-1.maxscript b/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-1.maxscript new file mode 100644 index 0000000000..9851dac2dc --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-1.maxscript @@ -0,0 +1,17 @@ +fn bubbleSort arr = +( + while true do + ( + changed = false + for i in 1 to (arr.count - 1) do + ( + if arr[i] > arr[i+1] then + ( + swap arr[i] arr[i+1] + changed = true + ) + ) + if not changed then exit + ) + arr +) diff --git a/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-2.maxscript b/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-2.maxscript new file mode 100644 index 0000000000..6531cd733e --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MAXScript/sorting-algorithms-bubble-sort-2.maxscript @@ -0,0 +1,2 @@ +myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1) +myArr = bubbleSort myArr diff --git a/Task/Sorting-algorithms-Bubble-sort/MMIX/sorting-algorithms-bubble-sort.mmix b/Task/Sorting-algorithms-Bubble-sort/MMIX/sorting-algorithms-bubble-sort.mmix new file mode 100644 index 0000000000..4d077dffe2 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MMIX/sorting-algorithms-bubble-sort.mmix @@ -0,0 +1,80 @@ +Ja IS $127 + + LOC Data_Segment +DataSeg GREG @ +Array IS @-Data_Segment + OCTA 999,200,125,1,1020,40,4,5,60,100 +ArrayLen IS (@-Array-Data_Segment)/8 + +NL IS @-Data_Segment + BYTE #a,0 + LOC @+(8-@)&7 + +Buffer IS @-Data_Segment + + + LOC #1000 + GREG @ +sorted IS $5 +i IS $6 +size IS $1 +a IS $0 +t IS $20 +t1 IS $21 +t2 IS $22 +% Input: $0 ptr to array, $1 its length (in octabyte) +% Trashed: $5, $6, $1, $20, $21, $22 +BubbleSort SETL sorted,1 % sorted = true + SUB size,size,1 % size-- + SETL i,0 % i = 0 +3H CMP t,i,size % i < size ? + BNN t,1F % if false, end for loop + 8ADDU $12,i,a % compute addresses of the + ADDU t,i,1 % octas a[i] and a[i+1] + 8ADDU $11,t,a + LDO t1,$12,0 % get their values + LDO t2,$11,0 + CMP t,t1,t2 % compare + BN t,2F % if t1<t2, next + STO t1,$11,0 % else swap them + STO t2,$12,0 + SETL sorted,0 % sorted = false +2H INCL i,1 % i++ + JMP 3B % next (for loop) +1H PBZ sorted,BubbleSort % while sorted is false, loop + GO Ja,Ja,0 + +% Help function (Print an octabyte) +% Input: $0 (the octabyte) +BufSize IS 64 + GREG @ +PrintInt8 ADDU t,DataSeg,Buffer % get buffer address + ADDU t,t,BufSize % end of buffer + SETL t1,0 % final 0 for Fputs + STB t1,t,0 +1H SUB t,t,1 % t-- + DIV $0,$0,10 % ($0,rR) = divmod($0,10) + GET t1,rR % get reminder + INCL t1,'0' % turn it into ascii digit + STB t1,t,0 % store it + PBNZ $0,1B % if $0 /= 0, loop + OR $255,t,0 % $255 = t + TRAP 0,Fputs,StdOut + GO Ja,Ja,0 % print and return + + +Main ADDU $0,DataSeg,Array % $0 = Array address + SETL $1,ArrayLen % $1 = Array Len + GO Ja,BubbleSort % BubbleSort it + SETL $4,ArrayLen % $4 = ArrayLen + ADDU $3,DataSeg,Array % $3 = Array address +2H BZ $4,1F % if $4 == 0, break + LDO $0,$3,0 % $0 = * ($3 + 0) + GO Ja,PrintInt8 % print the octa + ADDU $255,DataSeg,NL % add a trailing newline + TRAP 0,Fputs,StdOut + ADDU $3,$3,8 % next octa + SUB $4,$4,1 % $4-- + JMP 2B % loop +1H XOR $255,$255,$255 + TRAP 0,Halt,0 % exit(0) diff --git a/Task/Sorting-algorithms-Bubble-sort/Mathematica/sorting-algorithms-bubble-sort.math b/Task/Sorting-algorithms-Bubble-sort/Mathematica/sorting-algorithms-bubble-sort.math new file mode 100644 index 0000000000..35ec5f8e0b --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Mathematica/sorting-algorithms-bubble-sort.math @@ -0,0 +1,2 @@ +bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}] +bubbleSort[sortedList_] := sortedList diff --git a/Task/Sorting-algorithms-Bubble-sort/Modula-2/sorting-algorithms-bubble-sort.mod2 b/Task/Sorting-algorithms-Bubble-sort/Modula-2/sorting-algorithms-bubble-sort.mod2 new file mode 100644 index 0000000000..5abef9c8f7 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Modula-2/sorting-algorithms-bubble-sort.mod2 @@ -0,0 +1,19 @@ +PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER); + VAR + changed: BOOLEAN; + temp, count, i: INTEGER; +BEGIN + count := HIGH(a); + REPEAT + changed := FALSE; + DEC(count); + FOR i := 0 TO count DO + IF a[i] > a[i+1] THEN + temp := a[i]; + a[i] := a[i+1]; + a[i+1] := temp; + changed := TRUE + END + END + UNTIL NOT changed +END BubbleSort; diff --git a/Task/Sorting-algorithms-Bubble-sort/Modula-3/sorting-algorithms-bubble-sort.mod3 b/Task/Sorting-algorithms-Bubble-sort/Modula-3/sorting-algorithms-bubble-sort.mod3 new file mode 100644 index 0000000000..c037c8f8a4 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Modula-3/sorting-algorithms-bubble-sort.mod3 @@ -0,0 +1,20 @@ +MODULE Bubble; + +PROCEDURE Sort(VAR a: ARRAY OF INTEGER) = + VAR sorted: BOOLEAN; + temp, len: INTEGER := LAST(a); + BEGIN + WHILE NOT sorted DO + sorted := TRUE; + DEC(len); + FOR i := FIRST(a) TO len DO + IF a[i+1] < a[i] THEN + temp := a[i]; + a[i] := a[i + 1]; + a[i + 1] := temp; + sorted := FALSE; + END; + END; + END; + END Sort; +END Bubble. diff --git a/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-1.nemerle b/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-1.nemerle new file mode 100644 index 0000000000..c815e10bab --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-1.nemerle @@ -0,0 +1,43 @@ +using System; +using System.Console; + +module Bubblesort +{ + Bubblesort[T] (x : list[T]) : list[T] + where T : IComparable + { + def isSorted(y) + { + |[_] => true + |y1::y2::ys => (y1.CompareTo(y2) < 0) && isSorted(y2::ys) + } + + def sort(y) + { + |[y] => [y] + |y1::y2::ys => if (y1.CompareTo(y2) < 0) y1::sort(y2::ys) + else y2::sort(y1::ys) + } + + def loop(y) + { + if (isSorted(y)) y else {def z = sort(y); loop(z)} + } + + match(x) + { + |[] => [] + |_ => loop(x) + } + } + + Main() : void + { + def empty = []; + def single = [2]; + def several = [2, 6, 1, 7, 3, 9, 4]; + WriteLine(Bubblesort(empty)); + WriteLine(Bubblesort(single)); + WriteLine(Bubblesort(several)); + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-2.nemerle b/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-2.nemerle new file mode 100644 index 0000000000..3d624512e2 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Nemerle/sorting-algorithms-bubble-sort-2.nemerle @@ -0,0 +1,33 @@ +using System; +using System.Console; + +module Bubblesort +{ + public static Bubblesort[T](this x : array[T]) : void + where T : IComparable + { + mutable changed = false; + def ln = x.Length; + + do + { + changed = false; + foreach (i in [0 .. (ln - 2)]) + { + when (x[i].CompareTo(x[i + 1]) > 0) + { + x[i] <-> x[i + 1]; + changed = true; + } + } + } while (changed); + } + + Main() : void + { + def several = array[2, 6, 1, 7, 3, 9, 4]; + several.Bubblesort(); + foreach (i in several) + Write($"$i "); + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-1.netrexx b/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-1.netrexx new file mode 100644 index 0000000000..806a38a442 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-1.netrexx @@ -0,0 +1,36 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +placesList = [String - + "UK London", "US New York" - + , "US Boston", "US Washington" - + , "UK Washington", "US Birmingham" - + , "UK Birmingham", "UK Boston" - +] +sortedList = bubbleSort(String[] Arrays.copyOf(placesList, placesList.length)) + +lists = [placesList, sortedList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method bubbleSort(list = String[]) public constant binary returns String[] + +listLen = list.length +loop i_ = 0 to listLen - 1 + loop j_ = i_ + 1 to listLen - 1 + if list[i_].compareTo(list[j_]) > 0 then do + tmpstor = list[j_] + list[j_] = list[i_] + list[i_] = tmpstor + end + end j_ + end i_ + +return list diff --git a/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-2.netrexx b/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-2.netrexx new file mode 100644 index 0000000000..504ef39124 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/NetRexx/sorting-algorithms-bubble-sort-2.netrexx @@ -0,0 +1,46 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +placesList = [String - + "UK London", "US New York" - + , "US Boston", "US Washington" - + , "UK Washington", "US Birmingham" - + , "UK Birmingham", "UK Boston" - +] +sortedList = bubbleSort(String[] Arrays.copyOf(placesList, placesList.length)) + +lists = [placesList, sortedList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method bubbleSort(item = String[]) public constant binary returns String[] + +hasChanged = boolean +itemCount = item.length +loop label h_ until \hasChanged + hasChanged = isFalse + itemCount = itemCount - 1 + loop index = 0 to itemCount - 1 + if item[index].compareTo(item[index + 1]) > 0 then do + swap = item[index] + item[index] = item[index + 1] + item[index + 1] = swap + hasChanged = isTrue + end + end index + end h_ + +return item + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue diff --git a/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-1.ocaml b/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-1.ocaml new file mode 100644 index 0000000000..0fe5993a65 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-1.ocaml @@ -0,0 +1,11 @@ +let rec bsort s = + let rec _bsort = function + | x :: x2 :: xs when x > x2 -> + x2 :: _bsort (x :: xs) + | x :: x2 :: xs -> + x :: _bsort (x2 :: xs) + | s -> s + in + let t = _bsort s in + if t = s then t + else bsort t diff --git a/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-2.ocaml b/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-2.ocaml new file mode 100644 index 0000000000..f424e86cd1 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/OCaml/sorting-algorithms-bubble-sort-2.ocaml @@ -0,0 +1,17 @@ +let rec bsort s = + let rec _bsort = function + | x :: x2 :: xs when x > x2 -> begin + match _bsort (x :: xs) with + | None -> Some (x2 :: x :: xs) + | Some xs2 -> Some (x2 :: xs2) + end + | x :: x2 :: xs -> begin + match _bsort (x2 :: xs) with + | None -> None + | Some xs2 -> Some (x :: xs2) + end + | _ -> None + in + match _bsort s with + | None -> s + | Some s2 -> bsort s2 diff --git a/Task/Sorting-algorithms-Bubble-sort/Objeck/sorting-algorithms-bubble-sort.objeck b/Task/Sorting-algorithms-Bubble-sort/Objeck/sorting-algorithms-bubble-sort.objeck new file mode 100644 index 0000000000..efa32dc572 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Objeck/sorting-algorithms-bubble-sort.objeck @@ -0,0 +1,19 @@ +function : Swap(p : Int[]) ~ Nil { + t := p[0]; + p[0] := p[1]; + p[1] := t; +} + +function : Sort(a : Int[]) ~ Nil { + do { + sorted := true; + size -= 1; + for (i:=0; i<a->Size(); i+=1;) { + if (a[i+1] < a[i]) { + swap(a+i); + sorted := 0; + }; + }; + } + while (sorted = false); +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-1.octave b/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-1.octave new file mode 100644 index 0000000000..cddbafcd47 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-1.octave @@ -0,0 +1,14 @@ +function s = bubblesort(v) + itemCount = length(v); + do + hasChanged = false; + itemCount--; + for i = 1:itemCount + if ( v(i) > v(i+1) ) + v([i,i+1]) = v([i+1,i]); % swap + hasChanged = true; + endif + endfor + until(hasChanged == false) + s = v; +endfunction diff --git a/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-2.octave b/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-2.octave new file mode 100644 index 0000000000..eec2cb110a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Octave/sorting-algorithms-bubble-sort-2.octave @@ -0,0 +1,2 @@ +v = [9,8,7,3,1,100]; +disp(bubblesort(v)); diff --git a/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-1.oz b/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-1.oz new file mode 100644 index 0000000000..0ce9fd927d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-1.oz @@ -0,0 +1,23 @@ +declare + proc {BubbleSort Arr} + proc {Swap I J} + Arr.J := (Arr.I := Arr.J) %% assignment returns the old value + end + IsSorted = {NewCell false} + MaxItem = {NewCell {Array.high Arr}-1} + in + for until:@IsSorted do + IsSorted := true + for I in {Array.low Arr}..@MaxItem do + if Arr.I > Arr.(I+1) then + IsSorted := false + {Swap I I+1} + end + end + MaxItem := @MaxItem - 1 + end + end + Arr = {Tuple.toArray unit(10 9 8 7 6 5 4 3 2 1)} +in + {BubbleSort Arr} + {Inspect Arr} diff --git a/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-2.oz b/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-2.oz new file mode 100644 index 0000000000..bf086d8580 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Oz/sorting-algorithms-bubble-sort-2.oz @@ -0,0 +1,25 @@ +declare + local + fun {Loop Xs Changed ?IsSorted} + case Xs + of X1|X2|Xr andthen X1 > X2 then + X2|{Loop X1|Xr true IsSorted} + [] X|Xr then + X|{Loop Xr Changed IsSorted} + [] nil then + IsSorted = {Not Changed} + nil + end + end + in + fun {BubbleSort Xs} + IsSorted + Result = {Loop Xs false ?IsSorted} + in + if IsSorted then Result + else {BubbleSort Result} + end + end + end +in + {Show {BubbleSort [3 1 4 1 5 9 2 6 5]}} diff --git a/Task/Sorting-algorithms-Bubble-sort/PARI-GP/sorting-algorithms-bubble-sort.pari b/Task/Sorting-algorithms-Bubble-sort/PARI-GP/sorting-algorithms-bubble-sort.pari new file mode 100644 index 0000000000..b0c263e0ce --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PARI-GP/sorting-algorithms-bubble-sort.pari @@ -0,0 +1,12 @@ +bubbleSort(v)={ + for(i=1,#v-1, + for(j=i+1,#v, + if(v[j]<v[i], + my(t=v[j]); + v[j]=v[i]; + v[i]=t + ) + ) + ); + v +}; diff --git a/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php b/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php new file mode 100644 index 0000000000..d007ea2603 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PHP/sorting-algorithms-bubble-sort.php @@ -0,0 +1,17 @@ +function bubbleSort( array &$array ) +{ + do + { + $swapped = false; + for( $i = 0, $c = count( $array ) - 1; $i < $c; $i++ ) + { + if( $array[$i] > $array[$i + 1] ) + { + list( $array[$i + 1], $array[$i] ) = + array( $array[$i], $array[$i + 1] ); + $swapped = true; + } + } + } + while( $swapped ); +} diff --git a/Task/Sorting-algorithms-Bubble-sort/PL-I/sorting-algorithms-bubble-sort.pli b/Task/Sorting-algorithms-Bubble-sort/PL-I/sorting-algorithms-bubble-sort.pli new file mode 100644 index 0000000000..22eac3ca93 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PL-I/sorting-algorithms-bubble-sort.pli @@ -0,0 +1,16 @@ +/* A primitive bubble sort */ +bubble_sort: procedure (A); + declare A(*) fixed binary; + declare temp fixed binary; + declare i fixed binary, no_more_swaps bit (1) aligned; + + do until (no_more_swaps); + no_more_swaps = true; + do i = lbound(A,1) to hbound(A,1)-1; + if A(i) > A(i+1) then + do; temp = A(i); A(i) = A(i+1); A(i+1) = temp; + no_more_swaps = false; + end; + end; + end; +end bubble_sort; diff --git a/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-1.pascal b/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-1.pascal new file mode 100644 index 0000000000..9cc425f9e3 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-1.pascal @@ -0,0 +1,15 @@ +procedure bubble_sort(var list: array of real); +var + i, j, n: integer; + t: real; +begin + n := length(list); + for i := n downto 2 do + for j := 0 to i - 1 do + if list[j] > list[j + 1] then + begin + t := list[j]; + list[j] := list[j + 1]; + list[j + 1] := t; + end; +end; diff --git a/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-2.pascal b/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-2.pascal new file mode 100644 index 0000000000..a986761549 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Pascal/sorting-algorithms-bubble-sort-2.pascal @@ -0,0 +1,4 @@ +var + list: array[0 .. 9] of real; +// ... +bubble_sort(list); diff --git a/Task/Sorting-algorithms-Bubble-sort/Perl-6/sorting-algorithms-bubble-sort.pl6 b/Task/Sorting-algorithms-Bubble-sort/Perl-6/sorting-algorithms-bubble-sort.pl6 new file mode 100644 index 0000000000..fc265f8d86 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Perl-6/sorting-algorithms-bubble-sort.pl6 @@ -0,0 +1,7 @@ +sub bubble_sort (@a is rw) { + for ^@a -> $i { + for $i ^..^ @a -> $j { + @a[$j] < @a[$i] and @a[$i, $j] = @a[$j, $i]; + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-1.pl b/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-1.pl new file mode 100644 index 0000000000..4e6429f686 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-1.pl @@ -0,0 +1,8 @@ +# Sorts an array in place +sub bubble_sort { + for my $i (0 .. $#_){ + for my $j ($i + 1 .. $#_){ + $_[$j] < $_[$i] and @_[$i, $j] = @_[$j, $i]; + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-2.pl b/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-2.pl new file mode 100644 index 0000000000..bafc684190 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Perl/sorting-algorithms-bubble-sort-2.pl @@ -0,0 +1,2 @@ +my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38); +bubble_sort(@a); diff --git a/Task/Sorting-algorithms-Bubble-sort/PicoLisp/sorting-algorithms-bubble-sort.l b/Task/Sorting-algorithms-Bubble-sort/PicoLisp/sorting-algorithms-bubble-sort.l new file mode 100644 index 0000000000..31685a2b5f --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PicoLisp/sorting-algorithms-bubble-sort.l @@ -0,0 +1,9 @@ +(de bubbleSort (Lst) + (use Chg + (loop + (off Chg) + (for (L Lst (cdr L) (cdr L)) + (when (> (car L) (cadr L)) + (xchg L (cdr L)) + (on Chg) ) ) + (NIL Chg Lst) ) ) ) diff --git a/Task/Sorting-algorithms-Bubble-sort/Pop11/sorting-algorithms-bubble-sort.pop11 b/Task/Sorting-algorithms-Bubble-sort/Pop11/sorting-algorithms-bubble-sort.pop11 new file mode 100644 index 0000000000..a915e6acde --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Pop11/sorting-algorithms-bubble-sort.pop11 @@ -0,0 +1,19 @@ +define bubble_sort(v); +lvars n=length(v), done=false, i; +while not(done) do + true -> done; + n - 1 -> n; + for i from 1 to n do + if v(i) > v(i+1) then + false -> done; + ;;; Swap using multiple assignment + (v(i+1), v(i)) -> (v(i), v(i+1)); + endif; + endfor; +endwhile; +enddefine; + +;;; Test it +vars ar = { 10 8 6 4 2 1 3 5 7 9}; +bubble_sort(ar); +ar => diff --git a/Task/Sorting-algorithms-Bubble-sort/PostScript/sorting-algorithms-bubble-sort.ps b/Task/Sorting-algorithms-Bubble-sort/PostScript/sorting-algorithms-bubble-sort.ps new file mode 100644 index 0000000000..fba75d4bda --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PostScript/sorting-algorithms-bubble-sort.ps @@ -0,0 +1,21 @@ +/bubblesort{ +/x exch def +/temp x x length 1 sub get def +/i x length 1 sub def +/j i 1 sub def + +x length 1 sub{ +i 1 sub{ +x j 1 sub get x j get lt +{ +/temp x j 1 sub get def +x j 1 sub x j get put +x j temp put +}if +/j j 1 sub def +}repeat +/i i 1 sub def +/j i 1 sub def +}repeat +x pstack +}def diff --git a/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.psh b/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.psh new file mode 100644 index 0000000000..b9ab2c724d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.psh @@ -0,0 +1,14 @@ +function bubblesort ($a) { + $l = $a.Length + $hasChanged = $true + while ($hasChanged) { + $hasChanged = $false + $l-- + for ($i = 0; $i -lt $l; $i++) { + if ($a[$i] -gt $a[$i+1]) { + $a[$i], $a[$i+1] = $a[$i+1], $a[$i] + $hasChanged = $true + } + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/PureBasic/sorting-algorithms-bubble-sort.purebasic b/Task/Sorting-algorithms-Bubble-sort/PureBasic/sorting-algorithms-bubble-sort.purebasic new file mode 100644 index 0000000000..0b05d3dd07 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PureBasic/sorting-algorithms-bubble-sort.purebasic @@ -0,0 +1,15 @@ +Procedure bubbleSort(Array a(1)) + Protected i, itemCount, hasChanged + + itemCount = ArraySize(a()) + Repeat + hasChanged = #False + itemCount - 1 + For i = 0 To itemCount + If a(i) > a(i + 1) + Swap a(i), a(i + 1) + hasChanged = #True + EndIf + Next + Until hasChanged = #False +EndProcedure diff --git a/Task/Sorting-algorithms-Bubble-sort/Python/sorting-algorithms-bubble-sort.py b/Task/Sorting-algorithms-Bubble-sort/Python/sorting-algorithms-bubble-sort.py new file mode 100644 index 0000000000..5030daa77d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Python/sorting-algorithms-bubble-sort.py @@ -0,0 +1,26 @@ +def bubble_sort(seq): + """Inefficiently sort the mutable sequence (list) in place. + seq MUST BE A MUTABLE SEQUENCE. + + As with list.sort() and random.shuffle this does NOT return + """ + changed = True + while changed: + changed = False + for i in xrange(len(seq) - 1): + if seq[i] > seq[i+1]: + seq[i], seq[i+1] = seq[i+1], seq[i] + changed = True + return None + +if __name__ == "__main__": + """Sample usage and simple test suite""" + + from random import shuffle + + testset = range(100) + testcase = testset[:] # make a copy + shuffle(testcase) + assert testcase != testset # we've shuffled it + bubble_sort(testcase) + assert testcase == testset # we've unshuffled it back into a copy diff --git a/Task/Sorting-algorithms-Bubble-sort/Qi/sorting-algorithms-bubble-sort.qi b/Task/Sorting-algorithms-Bubble-sort/Qi/sorting-algorithms-bubble-sort.qi new file mode 100644 index 0000000000..0275a5942a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Qi/sorting-algorithms-bubble-sort.qi @@ -0,0 +1,9 @@ +(define bubble-shot + [A] -> [A] + [A B|R] -> [B|(bubble-shot [A|R])] where (> A B) + [A |R] -> [A|(bubble-shot R)]) + +(define bubble-sort + X -> (fix bubble-shot X)) + +(bubble-sort [6 8 5 9 3 2 2 1 4 7]) diff --git a/Task/Sorting-algorithms-Bubble-sort/R/sorting-algorithms-bubble-sort.r b/Task/Sorting-algorithms-Bubble-sort/R/sorting-algorithms-bubble-sort.r new file mode 100644 index 0000000000..a3e9562e32 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/R/sorting-algorithms-bubble-sort.r @@ -0,0 +1,20 @@ +bubblesort <- function(v) { + itemCount <- length(v) + repeat { + hasChanged <- FALSE + itemCount <- itemCount - 1 + for(i in 1:itemCount) { + if ( v[i] > v[i+1] ) { + t <- v[i] + v[i] <- v[i+1] + v[i+1] <- t + hasChanged <- TRUE + } + } + if ( !hasChanged ) break; + } + v +} + +v <- c(9,8,7,3,1,100) +print(bubblesort(v)) diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx new file mode 100644 index 0000000000..4242bf1835 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx @@ -0,0 +1,50 @@ +/*REXX program sorts an array using the bubble-sort method. */ + +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call bubbleSort highItem /*invoke the bubble sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────BUBBLESORT subroutine───────────────*/ +bubbleSort: procedure expose @.; parse arg n /* n = number of items. */ + /*diminish # items each time. */ + do until done /*sort until it's done. */ + done=1 /*assume it's done (1 = true). */ + do j=1 for n-1 /*sort M items this time. */ + k=j+1 /*point to the next item. */ + if @.j>@.k then do /*is it out of order ? */ + _=@.j /*assign to a temp variable. */ + @.j=@.k /*swap current with next. */ + @.k=_ /*... and next with _ */ + done=0 /*indicate it's not done. */ + end /* 1=true 0=false */ + end /*j*/ + end /*until done*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign some default values. */ +@.1 ='---letters of the Hebrew alphabet---' ; @.13='kaph [kaf]' +@.2 ='====================================' ; @.14='lamed' +@.3 ='aleph [alef]' ; @.15='mem' +@.4 ='beth [bet]' ; @.16='nun' +@.5 ='gimel' ; @.17='samekh' +@.6 ='daleth [dalet]' ; @.18='ayin' +@.7 ='he' ; @.19='pe' +@.8 ='waw [vav]' ; @.20='sadhe [tsadi]' +@.9 ='zayin' ; @.21='qoph [qof]' +@.10='heth [het]' ; @.22='resh' +@.11='teth [tet]' ; @.23='shin' +@.12='yod' ; @.24='taw [tav]' + + 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 +say copies('-',80) /*show a separator line. */ +return diff --git a/Task/Sorting-algorithms-Bubble-sort/Ruby/sorting-algorithms-bubble-sort.rb b/Task/Sorting-algorithms-Bubble-sort/Ruby/sorting-algorithms-bubble-sort.rb new file mode 100644 index 0000000000..5d92265f7b --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Ruby/sorting-algorithms-bubble-sort.rb @@ -0,0 +1,24 @@ +class Array + def bubblesort1! + length.times do |j| + for i in 1...(length - j) + if self[i] < self[i - 1] + self[i], self[i - 1] = self[i - 1], self[i] + end + end + end + self + end + def bubblesort2! + each_index do |index| + (length - 1).downto( index ) do |i| + self[i-1], self[i] = self[i], self[i-1] if self[i-1] < self[i] + end + end + self + end +end +ary = [3, 78, 4, 23, 6, 8, 6] +ary.bubblesort1! +p ary +# => [3, 4, 6, 6, 8, 23, 78] diff --git a/Task/Sorting-algorithms-Bubble-sort/Run-BASIC/sorting-algorithms-bubble-sort.run b/Task/Sorting-algorithms-Bubble-sort/Run-BASIC/sorting-algorithms-bubble-sort.run new file mode 100644 index 0000000000..ab6c4385da --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Run-BASIC/sorting-algorithms-bubble-sort.run @@ -0,0 +1,15 @@ +siz = 100 +dim data$(siz) +unSorted = 1 + +WHILE unSorted + unSorted = 0 + FOR i = 1 TO siz -1 + IF data$(i) > data$(i + 1) THEN + tmp = data$(i) + data$(i) = data$(i + 1) + data$(i + 1) = tmp + unSorted = 1 + END IF + NEXT +WEND diff --git a/Task/Sorting-algorithms-Bubble-sort/SNOBOL4/sorting-algorithms-bubble-sort.sno b/Task/Sorting-algorithms-Bubble-sort/SNOBOL4/sorting-algorithms-bubble-sort.sno new file mode 100644 index 0000000000..57b9b1e6e5 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/SNOBOL4/sorting-algorithms-bubble-sort.sno @@ -0,0 +1,24 @@ +* # Sort array in place, return array + define('bubble(a,alen)i,j,ub,tmp') :(bubble_end) +bubble i = 1; ub = alen +outer gt(ub,1) :f(bdone) + j = 1 +inner le(a<j>, a<j + 1>) :s(incrj) + tmp = a<j> + a<j> = a<j + 1> + a<j + 1> = tmp +incrj j = lt(j + 1,ub) j + 1 :s(inner) + ub = ub - 1 :(outer) +bdone bubble = a :(return) +bubble_end + +* # Fill array with test data + str = '33 99 15 54 1 20 88 47 68 72' + output = str; arr = array(10) +floop i = i + 1; str span('0123456789') . arr<i> = :s(floop) + +* # Test and display + bubble(arr,10); str = '' +sloop j = j + 1; str = str arr<j> ' ' :s(sloop) + output = trim(str) +end diff --git a/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-1.spark b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-1.spark new file mode 100644 index 0000000000..114ca5d6c6 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-1.spark @@ -0,0 +1,36 @@ +package Bubble +is + + type Arr is array(Integer range <>) of Integer; + + procedure Sort (A : in out Arr); + --# derives A from *; + +end Bubble; + + +package body Bubble +is + procedure Sort (A : in out Arr) + is + Finished : Boolean; + Temp : Integer; + begin + if A'Last /= A'First then + loop + Finished := True; + for J in Integer range A'First .. A'Last - 1 loop + if A (J + 1) < A (J) then + Finished := False; + Temp := A (J + 1); + A (J + 1) := A (J); + A (J) := Temp; + end if; + end loop; + --# assert A'Last /= A'First; + exit when Finished; + end loop; + end if; + end Sort; + +end Bubble; diff --git a/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-2.spark b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-2.spark new file mode 100644 index 0000000000..f4306338a6 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-2.spark @@ -0,0 +1,49 @@ +package Bubble +is + + type Arr is array(Integer range <>) of Integer; + + -- Sorted is a proof function with the definition: + -- Sorted(A, From_I, To_I) + -- <-> + -- (for all I in Integer range From_I .. To_I - 1 => + -- (A(I) <= A(I + 1))) . + -- + --# function Sorted (A : Arr; + --# From_I, To_I : Integer) return Boolean; + + procedure Sort (A : in out Arr); + --# derives A from *; + --# post Sorted(A, A'First, A'Last); + +end Bubble; + + +package body Bubble +is + procedure Sort (A : in out Arr) + is + Finished : Boolean; + Temp : Integer; + begin + if A'Last > A'First then + loop + Finished := True; + for J in Integer range A'First .. A'Last - 1 + --# assert Finished -> Sorted(A, A'First, J); + loop + if A (J + 1) < A (J) then + Finished := False; + Temp := A (J + 1); + A (J + 1) := A (J); + A (J) := Temp; + end if; + end loop; + --# assert A'Last /= A'First + --# and (Finished -> Sorted(A, A'First, A'Last)); + exit when Finished; + end loop; + end if; + end Sort; + +end Bubble; diff --git a/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-3.spark b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-3.spark new file mode 100644 index 0000000000..746241235a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/SPARK/sorting-algorithms-bubble-sort-3.spark @@ -0,0 +1,63 @@ +package body Bubble +is + procedure Sort (A : in out Arr) + is + Finished : Boolean; + + -- In_Position is a proof function with the definition: + -- In_Position(A, A_Start, A_I, A_End) + -- <-> + -- ((for all K in Integer range A_Start .. A_I - 1 => + -- (A(K) <= A(A_I))) + -- and + -- Sorted(A, A_I, A_End) . + -- + --# function In_Position (A : Arr; + --# A_Start, A_I, A_End : Integer) return Boolean; + + -- Swapped is a proof function with the definition: + -- Swapped(A_In, A_Out, I1, I2) + -- <-> + -- (A_Out = A_In[I1 => A_In(I2); I2 => A_In(I1)]). + -- + --# function Swapped (A_In, A_Out : Arr; + --# I1, I2 : Integer) return Boolean; + + procedure Swap (A : in out Arr; + I1 : in Integer; + I2 : in Integer) + --# derives A from *, I1, I2; + --# pre I1 in A'First .. A'Last + --# and I2 in A'First .. A'Last; + --# post Swapped(A~, A, I1, I2); + is + Temp : Integer; + begin + Temp := A(I2); + A(I2) := A(I1); + A(I1) := Temp; + end Swap; + pragma Inline (Swap); + + begin + if A'Last > A'First then + for I in reverse Integer range A'First + 1 .. A'Last loop + Finished := True; + for J in Integer range A'First .. I - 1 loop + if A (J + 1) < A (J) then + Finished := False; + Swap (A, J, J + 1); + end if; + --# assert I% = I -- I is unchanged by execution of the loop + --# and (for all K in Integer range A'First .. J => + --# (A(K) <= A(J + 1))) + --# and (I < A'Last -> In_Position(A, A'First, I + 1, A'Last)) + --# and (Finished -> Sorted(A, A'First, J + 1)); + end loop; + exit when Finished; + --# assert In_Position(A, A'First, I, A'Last); + end loop; + end if; + end Sort; + +end Bubble; diff --git a/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-1.sa b/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-1.sa new file mode 100644 index 0000000000..a671bca43a --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-1.sa @@ -0,0 +1,21 @@ +class SORT{T < $IS_LT{T}} is + private swap(inout a, inout b:T) is + temp ::= a; + a := b; + b := temp; + end; + bubble_sort(inout a:ARRAY{T}) is + i:INT; + if a.size < 2 then return; end; + loop + sorted ::= true; + loop i := 0.upto!(a.size - 2); + if a[i+1] < a[i] then + swap(inout a[i+1], inout a[i]); + sorted := false; + end; + end; + until!(sorted); + end; + end; +end; diff --git a/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-2.sa b/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-2.sa new file mode 100644 index 0000000000..6dd70e9d3e --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Sather/sorting-algorithms-bubble-sort-2.sa @@ -0,0 +1,7 @@ +class MAIN is + main is + a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|; + SORT{INT}::bubble_sort(inout a); + #OUT + a + "\n"; + end; +end; diff --git a/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort.scala b/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort.scala new file mode 100644 index 0000000000..95162b2b60 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort.scala @@ -0,0 +1,16 @@ +def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) { + import o._ + val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped + var hasChanged = true + do { + hasChanged = false + consecutiveIndices foreach { (i1, i2) => + if (arr(i1) > arr(i2)) { + hasChanged = true + val tmp = arr(i1) + arr(i1) = arr(i2) + arr(i2) = tmp + } + } + } while(hasChanged) +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-1.ss b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-1.ss new file mode 100644 index 0000000000..be47f1cbf0 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-1.ss @@ -0,0 +1,15 @@ +(define (bubble-sort x gt?) + (letrec + ((fix (lambda (f i) + (if (equal? i (f i)) + i + (fix f (f i))))) + + (sort-step (lambda (l) + (if (or (null? l) (null? (cdr l))) + l + (if (gt? (car l) (cadr l)) + (cons (cadr l) (sort-step (cons (car l) (cddr l)))) + (cons (car l) (sort-step (cdr l)))))))) + + (fix sort-step x))) diff --git a/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-2.ss b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-2.ss new file mode 100644 index 0000000000..d678ee91d0 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-2.ss @@ -0,0 +1,2 @@ +(bubble-sort (list 1 3 5 9 8 6 4 2) >) +(bubble-sort (string->list "Monkey") char<?) diff --git a/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-3.ss b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-3.ss new file mode 100644 index 0000000000..38b4d4e1b7 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-3.ss @@ -0,0 +1,12 @@ +(define (bsort l gt?) + (define (dosort l) + (cond ((null? (cdr l)) + l) + ((gt? (car l) (cadr l)) + (cons (cadr l) (dosort (cons (car l) (cddr l))))) + (else + (cons (car l) (dosort (cdr l)))))) + (let ((try (dosort l))) + (if (equal? l try) + l + (bsort try gt?)))) diff --git a/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-4.ss b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-4.ss new file mode 100644 index 0000000000..2e8ad87e1c --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scheme/sorting-algorithms-bubble-sort-4.ss @@ -0,0 +1,2 @@ +(bsort > '(2 4 6 2)) +(1 2 3) diff --git a/Task/Sorting-algorithms-Bubble-sort/Seed7/sorting-algorithms-bubble-sort.seed7 b/Task/Sorting-algorithms-Bubble-sort/Seed7/sorting-algorithms-bubble-sort.seed7 new file mode 100644 index 0000000000..23eab21fad --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Seed7/sorting-algorithms-bubble-sort.seed7 @@ -0,0 +1,18 @@ +const proc: bubbleSort (inout array elemType: arr) is func + local + var boolean: swapped is FALSE; + var integer: i is 0; + var elemType: help is elemType.value; + begin + repeat + swapped := FALSE; + for i range 1 to length(arr) - 1 do + if arr[i] > arr[i + 1] then + help := arr[i]; + arr[i] := arr[i + 1]; + arr[i + 1] := help; + swapped := TRUE; + end if; + end for; + until not swapped; + end func; diff --git a/Task/Sorting-algorithms-Bubble-sort/Smalltalk/sorting-algorithms-bubble-sort.st b/Task/Sorting-algorithms-Bubble-sort/Smalltalk/sorting-algorithms-bubble-sort.st new file mode 100644 index 0000000000..60426cabc7 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Smalltalk/sorting-algorithms-bubble-sort.st @@ -0,0 +1,18 @@ +|item swap itemCount hasChanged| +item := #(1 4 5 6 10 8 7 61 0 -3) copy. +swap := + [:indexOne :indexTwo| + |temp| + temp := item at: indexOne. + item at: indexOne put: (item at: indexTwo). + item at: indexTwo put: temp]. + +itemCount := item size. +[hasChanged := false. +itemCount := itemCount - 1. +1 to: itemCount do: + [:index | + (item at: index) > (item at: index + 1) ifTrue: + [swap value: index value: index + 1. + hasChanged := true]]. +hasChanged] whileTrue. diff --git a/Task/Sorting-algorithms-Bubble-sort/Tcl/sorting-algorithms-bubble-sort.tcl b/Task/Sorting-algorithms-Bubble-sort/Tcl/sorting-algorithms-bubble-sort.tcl new file mode 100644 index 0000000000..39e96cdea8 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Tcl/sorting-algorithms-bubble-sort.tcl @@ -0,0 +1,21 @@ +package require Tcl 8.5 +package require struct::list + +proc bubblesort {A} { + set len [llength $A] + set swapped true + while {$swapped} { + set swapped false + for {set i 0} {$i < $len - 1} {incr i} { + set j [expr {$i + 1}] + if {[lindex $A $i] > [lindex $A $j]} { + struct::list swap A $i $j + set swapped true + } + } + incr len -1 + } + return $A +} + +puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Bubble-sort/Toka/sorting-algorithms-bubble-sort.toka b/Task/Sorting-algorithms-Bubble-sort/Toka/sorting-algorithms-bubble-sort.toka new file mode 100644 index 0000000000..9c9d9c1823 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Toka/sorting-algorithms-bubble-sort.toka @@ -0,0 +1,38 @@ +#! A simple Bubble Sort function +value| array count changed | +[ ( address count -- ) + to count to array + count 0 + [ count 0 + [ i array array.get i 1 + array array.get 2dup > + [ i array array.put i 1 + array array.put ] + [ 2drop ] ifTrueFalse + ] countedLoop + count 1 - to count + ] countedLoop +] is bsort + +#! Code to display an array +[ ( array count -- ) + 0 swap [ dup i swap array.get . ] countedLoop drop cr +] is .array + +#! Create a 10-cell array +10 cells is-array foo + +#! Fill it with random values + 20 1 foo array.put + 50 2 foo array.put + 650 3 foo array.put + 120 4 foo array.put + 110 5 foo array.put + 101 6 foo array.put +1321 7 foo array.put +1310 8 foo array.put + 987 9 foo array.put + 10 10 foo array.put + +#! Display the array, sort it, and display it again +foo 10 .array +foo 10 bsort +foo 10 .array diff --git a/Task/Sorting-algorithms-Bubble-sort/UnixPipes/sorting-algorithms-bubble-sort.unixpipes b/Task/Sorting-algorithms-Bubble-sort/UnixPipes/sorting-algorithms-bubble-sort.unixpipes new file mode 100644 index 0000000000..5c2b938bbe --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/UnixPipes/sorting-algorithms-bubble-sort.unixpipes @@ -0,0 +1,23 @@ +rm -f _sortpass + +reset() { + test -f _tosort || mv _sortpass _tosort +} + +bpass() { + (read a; read b + test -n "$b" -a "$a" && ( + test $a -gt $b && (reset; echo $b; (echo $a ; cat) | bpass ) || (echo $a; (echo $b ; cat) | bpass ) + ) || echo $a) +} + +bubblesort() { + cat > _tosort + while test -f _tosort + do + cat _tosort | (rm _tosort;cat) |bpass > _sortpass + done + cat _sortpass +} + +cat to.sort | bubblesort diff --git a/Task/Sorting-algorithms-Bubble-sort/Ursala/sorting-algorithms-bubble-sort.ursala b/Task/Sorting-algorithms-Bubble-sort/Ursala/sorting-algorithms-bubble-sort.ursala new file mode 100644 index 0000000000..9cdf42c879 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Ursala/sorting-algorithms-bubble-sort.ursala @@ -0,0 +1,7 @@ +#import nat + +bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC + +#cast %nL + +example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315> diff --git a/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbscript b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbscript new file mode 100644 index 0000000000..0d42fe27d6 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbscript @@ -0,0 +1,31 @@ +sub decr( byref n ) + n = n - 1 +end sub + +sub incr( byref n ) + n = n + 1 +end sub + +sub swap( byref a, byref b) + dim tmp + tmp = a + a = b + b = tmp +end sub + +function bubbleSort( a ) + dim changed + dim itemCount + itemCount = ubound(a) + do + changed = false + decr itemCount + for i = 0 to itemCount + if a(i) > a(i+1) then + swap a(i), a(i+1) + changed = true + end if + next + loop until not changed + bubbleSort = a +end function diff --git a/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbscript b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbscript new file mode 100644 index 0000000000..20e2e5ac96 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbscript @@ -0,0 +1,5 @@ +dim a +a = array( "great eastern", "roe", "stirling", "albany", "leach") +wscript.echo join(a,", ") +bubbleSort a +wscript.echo join(a,", ") diff --git a/Task/Sorting-algorithms-Bubble-sort/Visual-Basic-.NET/sorting-algorithms-bubble-sort.visual b/Task/Sorting-algorithms-Bubble-sort/Visual-Basic-.NET/sorting-algorithms-bubble-sort.visual new file mode 100644 index 0000000000..c1606266c4 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Visual-Basic-.NET/sorting-algorithms-bubble-sort.visual @@ -0,0 +1,12 @@ +Do Until NoMoreSwaps = True + NoMoreSwaps = True + For Counter = 1 To (NumberOfItems - 1) + If List(Counter) > List(Counter + 1) Then + NoMoreSwaps = False + Temp = List(Counter) + List(Counter) = List(Counter + 1) + List(Counter + 1) = Temp + End If + Next + NumberOfItems = NumberOfItems - 1 +Loop diff --git a/Task/Sorting-algorithms-Bubble-sort/X86-Assembly/sorting-algorithms-bubble-sort.x86 b/Task/Sorting-algorithms-Bubble-sort/X86-Assembly/sorting-algorithms-bubble-sort.x86 new file mode 100644 index 0000000000..666197286f --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/X86-Assembly/sorting-algorithms-bubble-sort.x86 @@ -0,0 +1,30 @@ + .model tiny + .code + .486 + org 100h +start: mov si, offset array + mov ax, 40 ;length of array (not including $) + call bsort + mov dx, si ;point to array + mov ah, 09h ;display it as a string + int 21h + ret +array db "Pack my box with five dozen liquor jugs.$" + +;Bubble sort: si = array addrsss, ax = number of bytes +bsort: pusha + xchg cx, ax ;get size of array N + dec cx ;for J:= N-1 downto 0 +bs10: xor bx, bx ;for I:= 0 to J-1 +bs20: mov ax, [bx+si] + cmp al, ah ;if A(I) > A(I+1) then + jbe bs30 + xchg al, ah ; swap bytes + mov [bx+si], ax +bs30: inc bx ;next I + cmp bx, cx + jb bs20 + loop bs10 + popa + ret + end start diff --git a/Task/Sorting-algorithms-Bubble-sort/XPL0/sorting-algorithms-bubble-sort.xpl0 b/Task/Sorting-algorithms-Bubble-sort/XPL0/sorting-algorithms-bubble-sort.xpl0 new file mode 100644 index 0000000000..d0d4665b94 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/XPL0/sorting-algorithms-bubble-sort.xpl0 @@ -0,0 +1,24 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated strings + +proc BSort(A, N); \Bubble sort array in ascending order +char A; \address of array +int N; \number of items in array (size) +int I, J, T; +[for J:= N-1 downto 0 do + for I:= 0 to J-1 do + if A(I) > A(I+1) then + [T:= A(I); A(I):= A(I+1); A(I+1):= T]; \swap items +]; \BSort + +func StrLen(Str); \Return number of characters in an ASCIIZ string +char Str; +int I; +for I:= 0 to -1>>1-1 do + if Str(I) = 0 then return I; + +char Str; +[Str:= "Pack my box with five dozen liquor jugs."; +BSort(Str, StrLen(Str)); +Text(0, Str); CrLf(0); +] diff --git a/Task/Sorting-algorithms-Bubble-sort/Yorick/sorting-algorithms-bubble-sort.yorick b/Task/Sorting-algorithms-Bubble-sort/Yorick/sorting-algorithms-bubble-sort.yorick new file mode 100644 index 0000000000..33ea7d1800 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Yorick/sorting-algorithms-bubble-sort.yorick @@ -0,0 +1,13 @@ +func bubblesort(&items) { + itemCount = numberof(items); + do { + hasChanged = 0; + itemCount--; + for(index = 1; index <= itemCount; index++) { + if(items(index) > items(index+1)) { + items([index,index+1]) = items([index+1,index]); + hasChanged = 1; + } + } + } while(hasChanged); +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/0DESCRIPTION b/Task/Sorting-algorithms-Cocktail-sort/0DESCRIPTION new file mode 100644 index 0000000000..227d415668 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/0DESCRIPTION @@ -0,0 +1,22 @@ +{{Sorting Algorithm}}{{wikipedia|Cocktail sort}} +The cocktail shaker sort is an improvement on the [[Bubble Sort]]. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from [[wp:Cocktail sort|wikipedia]]): + '''function''' ''cocktailSort''( A : list of sortable items ) + '''do''' + swapped := false + '''for each''' i '''in''' 0 '''to''' length( A ) - 2 '''do''' + '''if''' A[ i ] > A[ i+1 ] '''then''' ''// test whether the two'' + ''// elements are in the wrong'' + ''// order'' + swap( A[ i ], A[ i+1 ] ) ''// let the two elements'' + ''// change places'' + swapped := true; + '''if''' swapped = false '''then''' + ''// we can exit the outer loop here if no swaps occurred.'' + '''break do-while loop'''; + swapped := false + '''for each''' i '''in''' length( A ) - 2 '''down to''' 0 '''do''' + '''if''' A[ i ] > A[ i+1 ] '''then''' + swap( A[ i ], A[ i+1 ] ) + swapped := true; + '''while''' swapped; ''// if no elements have been swapped,'' + ''// then the list is sorted'' diff --git a/Task/Sorting-algorithms-Cocktail-sort/1META.yaml b/Task/Sorting-algorithms-Cocktail-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-1.alg b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-1.alg new file mode 100644 index 0000000000..0ae5ebbbc3 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-1.alg @@ -0,0 +1,33 @@ +MODE DATA = CHAR; +PROC swap = (REF DATA a,b)VOID:( + DATA tmp:=a; a:=b; b:=tmp +); + +PROC cocktail sort = (REF[]DATA a)VOID: ( + WHILE + BOOL swapped := FALSE; + FOR i FROM LWB a TO UPB a - 1 DO + IF a[ i ] > a[ i + 1 ] THEN # test whether the two elements are in the wrong order # + swap( a[ i ], a[ i + 1 ] ); # let the two elements change places # + swapped := TRUE + FI + OD; + IF NOT swapped THEN + # we can exit the outer loop here if no swaps occurred. # + break do while loop + FI; + swapped := FALSE; + FOR i FROM UPB a - 1 TO LWB a DO + IF a[ i ] > a[ i + 1 ] THEN + swap( a[ i ], a[ i + 1 ] ); + swapped := TRUE + FI + OD; +# WHILE # swapped # if no elements have been swapped, then the list is sorted # + DO SKIP OD; + break do while loop: SKIP +); + +[32]CHAR data := "big fjords vex quick waltz nymph"; +cocktail sort(data); +print(data) diff --git a/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-2.alg b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-2.alg new file mode 100644 index 0000000000..0e28abf506 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-2.alg @@ -0,0 +1,12 @@ +MODE DATA = REF CHAR; +PROC swap = (REF DATA a,b)VOID:( + DATA tmp:=a; a:=b; b:=tmp +); + +PROC (REF[]DATA a)VOID cocktail sort; + +[32]CHAR data := "big fjords vex quick waltz nymph"; +[UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD; +cocktail sort(ref data); +FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); +print((data)) diff --git a/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-3.alg b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-3.alg new file mode 100644 index 0000000000..a983533a74 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-68/sorting-algorithms-cocktail-sort-3.alg @@ -0,0 +1,23 @@ +PROC odd even sort = (REF []DATA a)VOID: ( + FOR offset FROM 0 DO + BOOL swapped := FALSE; + FOR i FROM LWB a + offset TO UPB a - 1 - offset DO + IF a[ i ] > a[ i + 1 ] THEN # test whether the two elements are in the wrong order # + swap( a[ i ], a[ i + 1 ] ); # let the two elements change places # + swapped := TRUE + FI + OD; + # we can exit the outer loop here if no swaps occurred. # + IF NOT swapped THEN break do od loop FI; + swapped := FALSE; + FOR i FROM UPB a - 1 - offset - 1 BY - 1 TO LWB a + offset DO + IF a[ i ] > a[ i + 1 ] THEN + swap( a[ i ], a[ i + 1 ] ); + swapped := TRUE + FI + OD; + # if no elements have been swapped, then the list is sorted # + IF NOT swapped THEN break do od loop FI; + OD; + break do od loop: SKIP +); diff --git a/Task/Sorting-algorithms-Cocktail-sort/AWK/sorting-algorithms-cocktail-sort.awk b/Task/Sorting-algorithms-Cocktail-sort/AWK/sorting-algorithms-cocktail-sort.awk new file mode 100644 index 0000000000..9507514672 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/AWK/sorting-algorithms-cocktail-sort.awk @@ -0,0 +1,30 @@ +{ + line[NR] = $0 +} +END { # sort it with cocktail sort + swapped = 0 + do { + for(i=1; i < NR; i++) { + if ( line[i] > line[i+1] ) { + t = line[i] + line[i] = line[i+1] + line[i+1] = t + swapped = 1 + } + } + if ( swapped == 0 ) break + swapped = 0 + for(i=NR-1; i >= 1; i--) { + if ( line[i] > line[i+1] ) { + t = line[i] + line[i] = line[i+1] + line[i+1] = t + swapped = 1 + } + } + } while ( swapped == 1 ) + #print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/ActionScript/sorting-algorithms-cocktail-sort.as b/Task/Sorting-algorithms-Cocktail-sort/ActionScript/sorting-algorithms-cocktail-sort.as new file mode 100644 index 0000000000..7e9d8ce9aa --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/ActionScript/sorting-algorithms-cocktail-sort.as @@ -0,0 +1,25 @@ +function cocktailSort(input:Array):Array { + do { + var swapped:Boolean=false; + for (var i:uint = 0; i < input.length-1; i++) { + if (input[i]>input[i+1]) { + var tmp=input[i]; + input[i]=input[i+1]; + input[i+1]=tmp; + swapped=true; + } + } + if (! swapped) { + break; + } + for (i = input.length -2; i >= 0; i--) { + if (input[i]>input[i+1]) { + tmp=input[i]; + input[i]=input[i+1]; + input[i+1]=tmp; + swapped=true; + } + } + } while (swapped); + return input; +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.ada b/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.ada new file mode 100644 index 0000000000..bd33bcc41c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.ada @@ -0,0 +1,37 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Cocktail_Sort_Test is + procedure Cocktail_Sort (Item : in out String) is + procedure Swap(Left, Right : in out Character) is + Temp : Character := Left; + begin + Left := Right; + Right := Temp; + end Swap; + Swapped : Boolean := False; + begin + loop + for I in 1..Item'Last - 1 loop + if Item(I) > Item(I + 1) then + Swap(Item(I), Item(I + 1)); + Swapped := True; + end if; + end loop; + if not Swapped then + for I in reverse 1..Item'Last - 1 loop + if Item(I) > Item(I + 1) then + Swap(Item(I), Item(I + 1)); + Swapped := True; + end if; + end loop; + end if; + exit when not Swapped; + Swapped := False; + end loop; + end Cocktail_Sort; + Data : String := "big fjords vex quick waltz nymph"; +begin + Put_Line(Data); + Cocktail_Sort(Data); + Put_Line(Data); +end Cocktail_Sort_Test; diff --git a/Task/Sorting-algorithms-Cocktail-sort/AutoHotkey/sorting-algorithms-cocktail-sort.ahk b/Task/Sorting-algorithms-Cocktail-sort/AutoHotkey/sorting-algorithms-cocktail-sort.ahk new file mode 100644 index 0000000000..8cd759af68 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/AutoHotkey/sorting-algorithms-cocktail-sort.ahk @@ -0,0 +1,32 @@ +MsgBox % CocktailSort("") +MsgBox % CocktailSort("xxx") +MsgBox % CocktailSort("3,2,1") +MsgBox % CocktailSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") + +CocktailSort(var) { ; SORT COMMA SEPARATED LIST + StringSplit array, var, `, ; make array + i0 := 1, i1 := array0 ; start, end + + Loop { ; break when sorted + Changed = + Loop % i1-- -i0 { ; last entry will be in place + j := i0+A_Index, i := j-1 + If (array%j% < array%i%) ; swap? + t := array%i%, array%i% := array%j%, array%j% := t + ,Changed = 1 ; change has happened + } + IfEqual Changed,, Break + + Loop % i1-i0++ { ; first entry will be in place + i := i1-A_Index, j := i+1 + If (array%j% < array%i%) ; swap? + t := array%i%, array%i% := array%j%, array%j% := t + ,Changed = 1 ; change has happened + } + IfEqual Changed,, Break + } + + Loop % array0 ; construct string from sorted array + sorted .= "," . array%A_Index% + Return SubStr(sorted,2) ; drop leading comma +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/BBC-BASIC/sorting-algorithms-cocktail-sort.bbc b/Task/Sorting-algorithms-Cocktail-sort/BBC-BASIC/sorting-algorithms-cocktail-sort.bbc new file mode 100644 index 0000000000..fb86e01d54 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/BBC-BASIC/sorting-algorithms-cocktail-sort.bbc @@ -0,0 +1,19 @@ +DEF PROC_ShakerSort(Size%) + +Start%=2 +End%=Size% +Direction%=1 +LastChange%=1 +REPEAT + FOR J% = Start% TO End% STEP Direction% + IF data%(J%-1) > data%(J%) THEN + SWAP data%(J%-1),data%(J%) + LastChange% = J% + ENDIF + NEXT J% + End% = Start% + Start% = LastChange% - Direction% + Direction% = Direction% * -1 +UNTIL ( ( End% * Direction% ) < ( Start% * Direction% ) ) + +ENDPROC diff --git a/Task/Sorting-algorithms-Cocktail-sort/C/sorting-algorithms-cocktail-sort.c b/Task/Sorting-algorithms-Cocktail-sort/C/sorting-algorithms-cocktail-sort.c new file mode 100644 index 0000000000..d917b09b1a --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/C/sorting-algorithms-cocktail-sort.c @@ -0,0 +1,26 @@ +#include <stdio.h> + +#define try_swap { if (a[i] < a[i - 1])\ + { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; t = 0;} } + +void cocktailsort(int *a, size_t len) +{ + size_t i; + int t = 0; + while (!t) { + for (i = 1, t = 1; i < len; i++) try_swap; + if (t) break; + for (i = len - 1, t = 1; i; i--) try_swap; + } +} + +int main() +{ + int x[] = { 5, -1, 101, -4, 0, 1, 8, 6, 2, 3 }; + size_t i, len = sizeof(x)/sizeof(x[0]); + + cocktailsort(x, len); + for (i = 0; i < len; i++) + printf("%d\n", x[i]); + return 0; +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cobol b/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cobol new file mode 100644 index 0000000000..2570807cb1 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cobol @@ -0,0 +1,38 @@ + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE 2 TO WC-START + MOVE WC-SIZE TO WC-END. + MOVE 1 TO WC-DIRECTION + WC-LAST-CHANGE. + PERFORM E-SHAKER UNTIL WC-END * WC-DIRECTION < + WC-START * WC-DIRECTION. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-SHAKER SECTION. + E-000. + PERFORM F-PASS VARYING WB-IX-1 FROM WC-START BY WC-DIRECTION + UNTIL WB-IX-1 = WC-END + WC-DIRECTION. + + MOVE WC-START TO WC-END. + SUBTRACT WC-DIRECTION FROM WC-LAST-CHANGE GIVING WC-START. + MULTIPLY WC-DIRECTION BY -1 GIVING WC-DIRECTION. + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-1 - 1) > WB-ENTRY(WB-IX-1) + SET WC-LAST-CHANGE TO WB-IX-1 + MOVE WB-ENTRY(WB-IX-1 - 1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WB-IX-1 - 1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1). + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Common-Lisp/sorting-algorithms-cocktail-sort.lisp b/Task/Sorting-algorithms-Cocktail-sort/Common-Lisp/sorting-algorithms-cocktail-sort.lisp new file mode 100644 index 0000000000..7b15c61c4a --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Common-Lisp/sorting-algorithms-cocktail-sort.lisp @@ -0,0 +1,19 @@ +(defun cocktail-sort-vector (vector predicate &aux (len (length vector))) + (labels ((scan (start step &aux swapped) + (loop for i = start then (+ i step) while (< 0 i len) do + (when (funcall predicate (aref vector i) + (aref vector (1- i))) + (rotatef (aref vector i) + (aref vector (1- i))) + (setf swapped t))) + swapped)) + (loop while (and (scan 1 1) + (scan (1- len) -1)))) + vector) + +(defun cocktail-sort (sequence predicate) + (etypecase sequence + (vector (cocktail-sort-vector sequence predicate)) + (list (map-into sequence 'identity + (cocktail-sort-vector (coerce sequence 'vector) + predicate))))) diff --git a/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d new file mode 100644 index 0000000000..54f03b84e4 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d @@ -0,0 +1,26 @@ +import std.stdio, std.algorithm; + +void cocktailSort(Range)(Range data) { + bool swapped = false; + do { + foreach (i; 0 .. data.length - 1) + if (data[i] > data[i + 1]) { + swap(data[i], data[i + 1]); + swapped = true; + } + if (!swapped) + break; + swapped = false; + foreach_reverse (i; 0 .. data.length - 1) + if (data[i] > data[i + 1]) { + swap(data[i], data[i + 1]); + swapped = true; + } + } while(swapped); +} + +void main() { + auto array = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]; + cocktailSort(array); + writeln(array); +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Delphi/sorting-algorithms-cocktail-sort.delphi b/Task/Sorting-algorithms-Cocktail-sort/Delphi/sorting-algorithms-cocktail-sort.delphi new file mode 100644 index 0000000000..c7abc589f9 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Delphi/sorting-algorithms-cocktail-sort.delphi @@ -0,0 +1,64 @@ +program TestShakerSort; + +{$APPTYPE CONSOLE} + +{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array + +type + TItem = Integer; // declare ordinal type for array item +{$IFDEF DYNARRAY} + TArray = array of TItem; // dynamic array +{$ELSE} + TArray = array[0..15] of TItem; // static array +{$ENDIF} + +procedure ShakerSort(var A: TArray); +var + Item: TItem; + K, L, R, J: Integer; + +begin + L:= Low(A) + 1; + R:= High(A); + K:= High(A); + repeat + for J:= R downto L do begin + if A[J - 1] > A[J] then begin + Item:= A[J - 1]; + A[J - 1]:= A[J]; + A[J]:= Item; + K:= J; + end; + end; + L:= K + 1; + for J:= L to R do begin + if A[J - 1] > A[J] then begin + Item:= A[J - 1]; + A[J - 1]:= A[J]; + A[J]:= Item; + K:= J; + end; + end; + R:= K - 1; + until L > R; +end; + +var + A: TArray; + I: Integer; + +begin +{$IFDEF DYNARRAY} + SetLength(A, 16); +{$ENDIF} + for I:= Low(A) to High(A) do + A[I]:= Random(100); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + ShakerSort(A); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + Readln; +end. diff --git a/Task/Sorting-algorithms-Cocktail-sort/E/sorting-algorithms-cocktail-sort.e b/Task/Sorting-algorithms-Cocktail-sort/E/sorting-algorithms-cocktail-sort.e new file mode 100644 index 0000000000..f185bdfeb8 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/E/sorting-algorithms-cocktail-sort.e @@ -0,0 +1,17 @@ +/** Cocktail sort (in-place) */ +def cocktailSort(array) { + def swapIndexes := 0..(array.size() - 2) + def directions := [swapIndexes, swapIndexes.descending()] + while (true) { + for direction in directions { + var swapped := false + for a ? (array[a] > array[def b := a + 1]) in direction { + def t := array[a] + array[a] := array[b] + array[b] := t + swapped := true + } + if (!swapped) { return } + } + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.euphoria b/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.euphoria new file mode 100644 index 0000000000..4f66fcf1e2 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.euphoria @@ -0,0 +1,25 @@ +function cocktail_sort(sequence s) + integer swapped, d + object temp + sequence fromto + fromto = {1,length(s)-1} + swapped = 1 + d = 1 + while swapped do + swapped = 0 + for i = fromto[(1-d)/2+1] to fromto[(1+d)/2+1] by d do + if compare(s[i],s[i+1])>0 then + temp = s[i] + s[i] = s[i+1] + s[i+1] = temp + swapped = 1 + end if + end for + d = -d + end while + return s +end function + +constant s = rand(repeat(1000,10)) +? s +? cocktail_sort(s) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-1.fth b/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-1.fth new file mode 100644 index 0000000000..8585a27d26 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-1.fth @@ -0,0 +1,19 @@ +defer precedes ( addr addr -- flag ) + \ e.g. ' < is precedes +: sort ( a n --) + 1- cells bounds 2>r false + begin + 0= dup + while + 2r@ ?do + i cell+ @ i @ over over precedes ( mark unsorted ) + if i cell+ ! i ! dup xor else drop drop then + 1 cells +loop + 0= dup + while + 2r@ swap 1 cells - ?do + i cell+ @ i @ over over precedes ( mark unsorted ) + if i cell+ ! i ! dup xor else drop drop then + -1 cells +loop + repeat then drop 2r> 2drop +; diff --git a/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-2.fth b/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-2.fth new file mode 100644 index 0000000000..0c3d62cfa9 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Forth/sorting-algorithms-cocktail-sort-2.fth @@ -0,0 +1,12 @@ +: sort + 1- cells bounds 1 + begin + >r over over r@ -rot true -rot + r> 0< if 1 cells - then + ?do + i cell+ @ i @ over over precedes ( mark unsorted ) + if i cell+ ! i ! dup xor else drop drop then + over cells +loop + >r negate >r swap r@ cells + r> r> + until drop drop drop +; diff --git a/Task/Sorting-algorithms-Cocktail-sort/Fortran/sorting-algorithms-cocktail-sort.f b/Task/Sorting-algorithms-Cocktail-sort/Fortran/sorting-algorithms-cocktail-sort.f new file mode 100644 index 0000000000..e24c8b1ed9 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Fortran/sorting-algorithms-cocktail-sort.f @@ -0,0 +1,44 @@ +PROGRAM COCKTAIL + IMPLICIT NONE + + INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /) + + WRITE(*,"(A,10I5)") "Unsorted array:", intArray + CALL Cocktail_sort(intArray) + WRITE(*,"(A,10I5)") "Sorted array :", intArray + +CONTAINS + + SUBROUTINE Cocktail_sort(a) + INTEGER, INTENT(IN OUT) :: a(:) + INTEGER :: i, bottom, top, temp + LOGICAL :: swapped + + bottom = 1 + top = SIZE(a) - 1 + DO WHILE (bottom < top ) + swapped = .FALSE. + DO i = bottom, top + IF (array(i) > array(i+1)) THEN + temp = array(i) + array(i) = array(i+1) + array(i+1) = temp + swapped = .TRUE. + END IF + END DO + IF (.NOT. swapped) EXIT + DO i = top, bottom + 1, -1 + IF (array(i) < array(i-1)) THEN + temp = array(i) + array(i) = array(i-1) + array(i-1) = temp + swapped = .TRUE. + END IF + END DO + IF (.NOT. swapped) EXIT + bottom = bottom + 1 + top = top - 1 + END DO + END SUBROUTINE Cocktail_sort + +END PROGRAM COCKTAIL diff --git a/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-1.go b/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-1.go new file mode 100644 index 0000000000..533351de02 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-1.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + cocktailSort(a) + fmt.Println("after: ", a) +} + +func cocktailSort(a []int) { + last := len(a) - 1 + for { + swapped := false + for i := 0; i < last; i++ { + if a[i] > a[i+1] { + a[i], a[i+1] = a[i+1], a[i] + swapped = true + } + } + if !swapped { + return + } + swapped = false + for i := last - 1; i >= 0; i-- { + if a[i] > a[i+1] { + a[i], a[i+1] = a[i+1], a[i] + swapped = true + } + } + if !swapped { + return + } + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-2.go b/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-2.go new file mode 100644 index 0000000000..4d31e4fab8 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Go/sorting-algorithms-cocktail-sort-2.go @@ -0,0 +1,39 @@ +package main + +import ( + "sort" + "fmt" +) + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + cocktailSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} + +func cocktailSort(a sort.Interface) { + last := a.Len() - 1 + for { + swapped := false + for i := 0; i < last; i++ { + if a.Less(i+1, i) { + a.Swap(i, i+1) + swapped = true + } + } + if !swapped { + return + } + swapped = false + for i := last - 1; i >= 0; i-- { + if a.Less(i+1, i) { + a.Swap(i, i+1) + swapped = true + } + } + if !swapped { + return + } + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-1.groovy b/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-1.groovy new file mode 100644 index 0000000000..d9b8e3d309 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-1.groovy @@ -0,0 +1,14 @@ +def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] } + +def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find{ it }.each { makeSwap(a, i, j) } } + +def cocktailSort = { list -> + if (list == null || list.size() < 2) return list + def n = list.size() + def swap = checkSwap.curry(list) + while (true) { + def swapped = (0..(n-2)).any(swap) && ((-2)..(-n)).any(swap) + if ( ! swapped ) break + } + list +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-2.groovy b/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-2.groovy new file mode 100644 index 0000000000..8572528c4c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Groovy/sorting-algorithms-cocktail-sort-2.groovy @@ -0,0 +1,6 @@ +println cocktailSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]) +println cocktailSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]) + +println cocktailSort([ 3, 14, 1, 5, 9, 2, 6, 3 ]) +println cocktailSort([ 3, 14 ]) +println cocktailSort([ 33, 14 ]) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Haskell/sorting-algorithms-cocktail-sort.hs b/Task/Sorting-algorithms-Cocktail-sort/Haskell/sorting-algorithms-cocktail-sort.hs new file mode 100644 index 0000000000..d35f07755e --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Haskell/sorting-algorithms-cocktail-sort.hs @@ -0,0 +1,14 @@ +cocktailSort :: Ord a => [a] -> [a] +cocktailSort l + | not swapped1 = l + | not swapped2 = reverse $ l1 + | otherwise = cocktailSort l2 + where (swapped1, l1) = swappingPass (>) (False, []) l + (swapped2, l2) = swappingPass (<) (False, []) l1 + + swappingPass :: Ord a => (a -> a -> Bool) -> (Bool, [a]) -> [a] -> (Bool, [a]) + swappingPass op (swapped, l) (x1 : x2 : xs) + | op x1 x2 = swappingPass op (True, x2 : l) (x1 : xs) + | otherwise = swappingPass op (swapped, x1 : l) (x2 : xs) + swappingPass _ (swapped, l) [x] = (swapped, x : l) + swappingPass _ pair [] = pair diff --git a/Task/Sorting-algorithms-Cocktail-sort/Icon/sorting-algorithms-cocktail-sort.icon b/Task/Sorting-algorithms-Cocktail-sort/Icon/sorting-algorithms-cocktail-sort.icon new file mode 100644 index 0000000000..1ad3e53b6f --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Icon/sorting-algorithms-cocktail-sort.icon @@ -0,0 +1,17 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(cocktailsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure cocktailsort(X,op) #: return sorted list +local i,swapped + + op := sortop(op,X) # select how and what we sort + + swapped := 1 + repeat # translation of pseudo code. Contractions used to eliminate second loop. + every (if /swapped then break break else swapped := &null & next) | ( i := 1 to *X-1) | + (if /swapped then break break else swapped := &null & next) | ( i := *X-1 to 1 by -1) do + if op(X[i+1],X[i]) then + X[i+1] :=: X[swapped := i] + return X +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Io/sorting-algorithms-cocktail-sort.io b/Task/Sorting-algorithms-Cocktail-sort/Io/sorting-algorithms-cocktail-sort.io new file mode 100644 index 0000000000..0d1a34c5e1 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Io/sorting-algorithms-cocktail-sort.io @@ -0,0 +1,31 @@ +List do ( + cocktailSortInPlace := method( + start := 0 + end := size - 2 + + loop( + swapped := false + + for(idx, start, end, + if(at(idx) > at(idx + 1), + swapped := true + swapIndices(idx, idx + 1) + ) + ) + + if(swapped not, break, end := end - 1) + + for (idx, end, start, -1, + if(at(idx) > at(idx + 1), + swapped := true + swapIndices(idx, idx + 1) + ) + ) + + if(swapped not, break, start := start + 1) + ) + self) +) + +l := list(2, 3, 4, 5, 1) +l cocktailSortInPlace println # ==> list(1, 2, 3, 4, 5) diff --git a/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-1.j b/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-1.j new file mode 100644 index 0000000000..080aaf2727 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-1.j @@ -0,0 +1,3 @@ +bigToLeft=: (([ (>. , <.) {.@]) , }.@])/ +smallToLeft=: (([ (<. , >.) {.@]) , }.@])/ +cocktailSort=: |. @: (|. @: smallToLeft @: |. @: bigToLeft ^:_) diff --git a/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-2.j b/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-2.j new file mode 100644 index 0000000000..af813c279d --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/J/sorting-algorithms-cocktail-sort-2.j @@ -0,0 +1,4 @@ + ?. 10 $ 10 +4 6 8 6 5 8 6 6 6 9 + cocktailSort ?. 10 $ 10 +4 5 6 6 6 6 6 8 8 9 diff --git a/Task/Sorting-algorithms-Cocktail-sort/Java/sorting-algorithms-cocktail-sort.java b/Task/Sorting-algorithms-Cocktail-sort/Java/sorting-algorithms-cocktail-sort.java new file mode 100644 index 0000000000..8984bd2af6 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Java/sorting-algorithms-cocktail-sort.java @@ -0,0 +1,29 @@ +public static void cocktailSort( int[] A ){ + boolean swapped; + do { + swapped = false; + for (int i =0; i<= A.length - 2;i++) { + if (A[ i ] > A[ i + 1 ]) { + //test whether the two elements are in the wrong order + int temp = A[i]; + A[i] = A[i+1]; + A[i+1]=temp; + swapped = true; + } + } + if (!swapped) { + //we can exit the outer loop here if no swaps occurred. + break; + } + swapped = false; + for (int i= A.length - 2;i>=0;i--) { + if (A[ i ] > A[ i + 1 ]) { + int temp = A[i]; + A[i] = A[i+1]; + A[i+1]=temp; + swapped = true; + } + } + //if no elements have been swapped, then the list is sorted + } while (swapped); +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua b/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua new file mode 100644 index 0000000000..1b78ee0a21 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-1.lua @@ -0,0 +1,23 @@ +function cocktailSort( A ) + local swapped + repeat + swapped = false + for i = 1, #A - 1 do + if A[ i ] > A[ i+1 ] then + A[ i ], A[ i+1 ] = A[ i+1 ] ,A[i] + swapped=true + end + end + if swapped == false then + break -- repeatd loop; + end + + for i = #A - 1,1,-1 do + if A[ i ] > A[ i+1 ] then + A[ i ], A[ i+1 ] = A[ i+1 ] , A[ i ] + swapped=true + end + end + + until swapped==false +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-2.lua b/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-2.lua new file mode 100644 index 0000000000..6ce25a3df0 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Lua/sorting-algorithms-cocktail-sort-2.lua @@ -0,0 +1,5 @@ +list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 } +cocktailSort(list) +for i=1,#list do + print(list[i]j) +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-1.m b/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-1.m new file mode 100644 index 0000000000..2be2268495 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-1.m @@ -0,0 +1,30 @@ +function list = cocktailSort(list) + + %We have to do this because the do...while loop doesn't exist in MATLAB + swapped = true; + + while swapped + + %Bubble sort down the list + swapped = false; + for i = (1:numel(list)-1) + if( list(i) > list(i+1) ) + list([i i+1]) = list([i+1 i]); %swap + swapped = true; + end + end + + if ~swapped + break + end + + %Bubble sort up the list + swapped = false; + for i = (numel(list)-1:-1:1) + if( list(i) > list(i+1) ) + list([i i+1]) = list([i+1 i]); %swap + swapped = true; + end %if + end %for + end %while +end %cocktail sort diff --git a/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-2.m b/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-2.m new file mode 100644 index 0000000000..4fa5413287 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/MATLAB/sorting-algorithms-cocktail-sort-2.m @@ -0,0 +1,5 @@ +cocktailSort([6 3 7 8 5 1 2 4 9]) + +ans = + + 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Cocktail-sort/MAXScript/sorting-algorithms-cocktail-sort.maxscript b/Task/Sorting-algorithms-Cocktail-sort/MAXScript/sorting-algorithms-cocktail-sort.maxscript new file mode 100644 index 0000000000..fd648f528c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/MAXScript/sorting-algorithms-cocktail-sort.maxscript @@ -0,0 +1,26 @@ +fn cocktailSort arr = +( + local swapped = true + while swapped do + ( + swapped = false + for i in 1 to (arr.count-1) do + ( + if arr[i] > arr[i+1] then + ( + swap arr[i] arr[i+1] + swapped = true + ) + ) + if not swapped then exit + for i in (arr.count-1) to 1 by -1 do + ( + if arr[i] > arr[i+1] then + ( + swap arr[i] arr[i+1] + swapped = true + ) + ) + ) + return arr +) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Mathematica/sorting-algorithms-cocktail-sort.math b/Task/Sorting-algorithms-Cocktail-sort/Mathematica/sorting-algorithms-cocktail-sort.math new file mode 100644 index 0000000000..1dbdcff94b --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Mathematica/sorting-algorithms-cocktail-sort.math @@ -0,0 +1,11 @@ +cocktailSort[A_List] := Module[ { swapped = True }, +While[ swapped == True, + swapped=False; + For[ i = 1, i< Length[A]-1,i++, + If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped=True;] + ]; +If[swapped == False, Break[]]; +swapped=False; +For [ i= Length[A]-1, i > 0, i--, + If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped = True;] + ]]] diff --git a/Task/Sorting-algorithms-Cocktail-sort/NetRexx/sorting-algorithms-cocktail-sort.netrexx b/Task/Sorting-algorithms-Cocktail-sort/NetRexx/sorting-algorithms-cocktail-sort.netrexx new file mode 100644 index 0000000000..9efec66b8a --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/NetRexx/sorting-algorithms-cocktail-sort.netrexx @@ -0,0 +1,57 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +placesList = [String - + "UK London", "US New York" - + , "US Boston", "US Washington" - + , "UK Washington", "US Birmingham" - + , "UK Birmingham", "UK Boston" - +] +sortedList = cocktailSort(String[] Arrays.copyOf(placesList, placesList.length)) + +lists = [placesList, sortedList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method cocktailSort(A = String[]) public constant binary returns String[] + + Alength = A.length + swapped = isFalse + loop label swapped until \swapped + swapped = isFalse + loop i_ = 0 to Alength - 2 + if A[i_].compareTo(A[i_ + 1]) > 0 then do + swap = A[i_ + 1] + A[i_ + 1] = A[i_] + A[i_] = swap + swapped = isTrue + end + end i_ + if \swapped then do + leave swapped + end + swapped = isFalse + loop i_ = Alength - 2 to 0 by -1 + if A[i_].compareTo(A[i_ + 1]) > 0 then do + swap = A[i_ + 1] + A[i_ + 1] = A[i_] + A[i_] = swap + swapped = isTrue + end + end i_ + end swapped + + return A + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue diff --git a/Task/Sorting-algorithms-Cocktail-sort/OCaml/sorting-algorithms-cocktail-sort.ocaml b/Task/Sorting-algorithms-Cocktail-sort/OCaml/sorting-algorithms-cocktail-sort.ocaml new file mode 100644 index 0000000000..900b75f590 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/OCaml/sorting-algorithms-cocktail-sort.ocaml @@ -0,0 +1,37 @@ +let swap a i j = + let tmp = a.(i) in + a.(i) <- a.(j); + a.(j) <- tmp; +;; + +let cocktail_sort a = + let begin_ = ref(-1) + and end_ = ref(Array.length a - 2) in + let swapped = ref true in + try while !swapped do + swapped := false; + incr begin_; + for i = !begin_ to !end_ do + if a.(i) > a.(i+1) then begin + swap a (i) (i+1); + swapped := true; + end; + done; + if !swapped = false then raise Exit; + swapped := false; + decr end_; + for i = !end_ downto !begin_ do + if a.(i) > a.(i+1) then begin + swap a (i) (i+1); + swapped := true + end; + done; + done with Exit -> () +;; + +let () = + let a = [| 3; 7; 4; 9; 6; 1; 8; 5; 2; |] in + cocktail_sort a; + Array.iter (Printf.printf " %d") a; + print_newline(); +;; diff --git a/Task/Sorting-algorithms-Cocktail-sort/Objeck/sorting-algorithms-cocktail-sort.objeck b/Task/Sorting-algorithms-Cocktail-sort/Objeck/sorting-algorithms-cocktail-sort.objeck new file mode 100644 index 0000000000..f09f46bced --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Objeck/sorting-algorithms-cocktail-sort.objeck @@ -0,0 +1,42 @@ +bundle Default { + class Cocktail { + function : Main(args : String[]) ~ Nil { + values := [5, -1, 101, -4, 0, 1, 8, 6, 2, 3 ]; + CocktailSort(values); + each(i : values) { + values[i]->PrintLine(); + }; + } + + function : CocktailSort(a : Int[]) ~ Nil { + swapped : Bool; + do { + swapped := false; + continue := true; + for (i := 0; i <= a->Size() - 2 & continue; i += 1;) { + if(a[i] > a[i + 1]) { + temp := a[i]; + a[i] := a[i+1]; + a[i+1] := temp; + swapped := true; + }; + }; + + if(swapped <> true) { + continue := false; + }; + + swapped := false; + for(i := a->Size() - 2; i >= 0; i -= 1;){ + if(a[i] > a[i + 1]) { + temp := a[i]; + a[i] := a[i+1]; + a[i + 1] := temp; + swapped := true; + }; + }; + } + while(swapped); + } + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-1.octave b/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-1.octave new file mode 100644 index 0000000000..3bc6777cc8 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-1.octave @@ -0,0 +1,27 @@ +function sl = cocktailsort(l) + swapped = true; + while(swapped) + swapped = false; + for i = 1:(length(l)-1) + if ( l(i) > l(i+1) ) + t = l(i); + l(i) = l(i+1); + l(i+1) = t; + swapped = true; + endif + endfor + if ( !swapped ) + break; + endif + swapped = false; + for i = (length(l)-1):-1:1 + if ( l(i) > l(i+1) ) + t = l(i); + l(i) = l(i+1); + l(i+1) = t; + swapped = true; + endif + endfor + endwhile + sl = l; +endfunction diff --git a/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-2.octave b/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-2.octave new file mode 100644 index 0000000000..c29ffa8f93 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Octave/sorting-algorithms-cocktail-sort-2.octave @@ -0,0 +1,3 @@ +s = cocktailsort([5, -1, 101, -4, 0, \ + 1, 8, 6, 2, 3 ]); +disp(s); diff --git a/Task/Sorting-algorithms-Cocktail-sort/Oz/sorting-algorithms-cocktail-sort.oz b/Task/Sorting-algorithms-Cocktail-sort/Oz/sorting-algorithms-cocktail-sort.oz new file mode 100644 index 0000000000..4b51991148 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Oz/sorting-algorithms-cocktail-sort.oz @@ -0,0 +1,26 @@ +declare + proc {CocktailSort Arr} + proc {Swap I J} + Arr.J := (Arr.I := Arr.J) %% assignment returns the old value + end + IsSorted = {NewCell false} + Up = {List.number {Array.low Arr} {Array.high Arr}-1 1} + Down = {Reverse Up} + in + for until:@IsSorted break:Break do + for Range in [Up Down] do + IsSorted := true + for I in Range do + if Arr.I > Arr.(I+1) then + IsSorted := false + {Swap I I+1} + end + end + if @IsSorted then {Break} end + end + end + end + Arr = {Tuple.toArray unit(10 9 8 7 6 5 4 3 2 1)} +in + {CocktailSort Arr} + {Inspect Arr} diff --git a/Task/Sorting-algorithms-Cocktail-sort/PARI-GP/sorting-algorithms-cocktail-sort.pari b/Task/Sorting-algorithms-Cocktail-sort/PARI-GP/sorting-algorithms-cocktail-sort.pari new file mode 100644 index 0000000000..a98bb82f0a --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PARI-GP/sorting-algorithms-cocktail-sort.pari @@ -0,0 +1,24 @@ +cocktailSort(v)={ + while(1, + my(done=1); + for(i=2,#v, + if(v[i-1]>v[i], + my(t=v[i-1]); + v[i-1]=v[i]; + v[i]=t; + done=0 + ) + ); + if(done, return(v)); + done=1; + forstep(i=#v,2,-1, + if(v[i-1]>v[i], + my(t=v[i-1]); + v[i-1]=v[i]; + v[i]=t; + done=0 + ) + ); + if(done, return(v)) + ) +}; diff --git a/Task/Sorting-algorithms-Cocktail-sort/PHP/sorting-algorithms-cocktail-sort.php b/Task/Sorting-algorithms-Cocktail-sort/PHP/sorting-algorithms-cocktail-sort.php new file mode 100644 index 0000000000..329a9173cd --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PHP/sorting-algorithms-cocktail-sort.php @@ -0,0 +1,38 @@ +function cocktailSort($arr){ + if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr)); + + do{ + $swapped = false; + for($i=0;$i<count($arr);$i++){ + if(isset($arr[$i+1])){ + if($arr[$i] > $arr[$i+1]){ + list($arr[$i], $arr[$i+1]) = array($arr[$i+1], $arr[$i]); + $swapped = true; + } + } + } + + if ($swapped == false) break; + + $swapped = false; + for($i=count($arr)-1;$i>=0;$i--){ + if(isset($arr[$i-1])){ + if($arr[$i] < $arr[$i-1]) { + list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); + $swapped = true; + } + } + } + }while($swapped); + + return $arr; +} +$arr = array(5, 1, 7, 3, 6, 4, 2); +$arr2 = array("John", "Kate", "Alice", "Joe", "Jane"); +$strg = "big fjords vex quick waltz nymph"; +$arr = cocktailSort($arr); +$arr2 = cocktailSort($arr2); +$strg = cocktailSort($strg); +echo implode(',',$arr) . '<br>'; +echo implode(',',$arr2) . '<br>'; +echo implode('',$strg) . '<br>'; diff --git a/Task/Sorting-algorithms-Cocktail-sort/PL-I/sorting-algorithms-cocktail-sort.pli b/Task/Sorting-algorithms-Cocktail-sort/PL-I/sorting-algorithms-cocktail-sort.pli new file mode 100644 index 0000000000..19b659a91c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PL-I/sorting-algorithms-cocktail-sort.pli @@ -0,0 +1,17 @@ +cocktail: procedure (A); + declare A(*) fixed; + declare t fixed; + declare stable bit (1); + declare (i, n) fixed binary (31); + + n = hbound(A,1); + do until (stable); + stable = '1'b; + do i = 1 to n-1, n-1 to 1 by -1; + if A(i) > A(i+1) then + do; stable = '0'b; /* still unsorted, so set false. */ + t = A(i); A(i) = A(i+1); A(i+1) = t; + end; + end; + end; +end cocktail; diff --git a/Task/Sorting-algorithms-Cocktail-sort/Perl-6/sorting-algorithms-cocktail-sort.pl6 b/Task/Sorting-algorithms-Cocktail-sort/Perl-6/sorting-algorithms-cocktail-sort.pl6 new file mode 100644 index 0000000000..6a3bd4d860 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Perl-6/sorting-algorithms-cocktail-sort.pl6 @@ -0,0 +1,26 @@ +sub cocktail_sort ( @a ) { + my $range = 0 ..^ @a.end; + loop { + my $swapped_forward = 0; + for $range.list -> $i { + if @a[$i] > @a[$i+1] { + @a[ $i, $i+1 ] .= reverse; + $swapped_forward = 1; + } + } + last if not $swapped_forward; + + my $swapped_backward = 0; + for $range.reverse -> $i { + if @a[$i] > @a[$i+1] { + @a[ $i, $i+1 ] .= reverse; + $swapped_backward = 1; + } + } + last if not $swapped_backward; + } + return @a; +} + +my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) }; +say @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok'; diff --git a/Task/Sorting-algorithms-Cocktail-sort/Perl/sorting-algorithms-cocktail-sort.pl b/Task/Sorting-algorithms-Cocktail-sort/Perl/sorting-algorithms-cocktail-sort.pl new file mode 100644 index 0000000000..8732e67b19 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Perl/sorting-algorithms-cocktail-sort.pl @@ -0,0 +1,45 @@ +use strict; +use warnings; + +my @B=qw(t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g); +print "@B\n"; +my @C=cocktailSort(@B); +print "@C\n"; +################### cocktailSort ##################### +sub cocktailSort { #( A : list of sortable items ) defined as: + my @A = @_; + my $swapped = 1; + while ($swapped == 1) { + $swapped = 0; + for (my $i=0; $i<($#A-1); $i+=1) { + + if ($A[$i] gt $A[$i+1]) { # test whether the two + # elements are in the wrong + # order + + ($A[$i+1], $A[$i])=($A[$i], $A[$i+1]); # let the two elements + # change places + $swapped = 1; + } + } + if ($swapped == 0) { + # we can exit the outer loop here if no swaps occurred. + print "no more swaps"; + } + else { + $swapped = 0; + for (my $i=($#A-1); $i>0 ; $i-=1) { + + if($A[$i] gt $A[$i+1]) { + + ($A[$i+1], $A[$i])=($A[$i], $A[$i+1]); + $swapped = 1; + } + } + } +# if no elements have been swapped, +# then the list is sorted + } +return (@A); +#end sub +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/PicoLisp/sorting-algorithms-cocktail-sort.l b/Task/Sorting-algorithms-Cocktail-sort/PicoLisp/sorting-algorithms-cocktail-sort.l new file mode 100644 index 0000000000..9c79344d55 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PicoLisp/sorting-algorithms-cocktail-sort.l @@ -0,0 +1,19 @@ +(de cocktailSort (Lst) + (use (Swapped L) + (loop + (off Swapped) + (setq L Lst) + (while (cdr L) + (when (> (car L) (cadr L)) + (xchg L (cdr L)) + (on Swapped) ) + (pop 'L) ) + (NIL Swapped Lst) + (off Swapped) + (loop + (setq L (prior L Lst)) # Not recommended (inefficient) + (when (> (car L) (cadr L)) + (xchg L (cdr L)) + (on Swapped) ) + (T (== Lst L)) ) + (NIL Swapped Lst) ) ) ) diff --git a/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.psh b/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.psh new file mode 100644 index 0000000000..85140cd374 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.psh @@ -0,0 +1,32 @@ +function CocktailSort ($a) { + $l = $a.Length + $m = 0 + if( $l -gt 1 ) + { + $hasChanged = $true + :outer while ($hasChanged) { + $hasChanged = $false + $l-- + for ($i = $m; $i -lt $l; $i++) { + if ($a[$i] -gt $a[$i+1]) { + $a[$i], $a[$i+1] = $a[$i+1], $a[$i] + $hasChanged = $true + } + } + if(-not $hasChanged) { + break outer + } + $hasChanged = $false + for ($i = $l; $i -gt $m; $i--) { + if ($a[$i-1] -gt $a[$i]) { + $a[$i-1], $a[$i] = $a[$i], $a[$i-1] + $hasChanged = $true + } + } + $m++ + } + } + $a +} + +$l = 10; CocktailSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Cocktail-sort/PureBasic/sorting-algorithms-cocktail-sort.purebasic b/Task/Sorting-algorithms-Cocktail-sort/PureBasic/sorting-algorithms-cocktail-sort.purebasic new file mode 100644 index 0000000000..f09c712408 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PureBasic/sorting-algorithms-cocktail-sort.purebasic @@ -0,0 +1,31 @@ +;sorts an array of integers +Procedure cocktailSort(Array a(1)) + Protected index, hasChanged, low, high + + low = 0 + high = ArraySize(a()) - 1 + Repeat + hasChanged = #False + For index = low To high + If a(index) > a(index + 1) + Swap a(index), a(index + 1) + hasChanged = #True + EndIf + Next + high - 1 + + If hasChanged = #False + Break ;we can exit the outer loop here if no changes were made + EndIf + + + hasChanged = #False + For index = high To low Step -1 + If a(index) > a(index + 1) + Swap a(index), a(index + 1) + hasChanged = #True + EndIf + Next + low + 1 + Until hasChanged = #False ;if no elements have been changed, then the array is sorted +EndProcedure diff --git a/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-1.py b/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-1.py new file mode 100644 index 0000000000..30de360b87 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-1.py @@ -0,0 +1,11 @@ +def cocktailSort(A): + up = range(len(A)-1) + while True: + for indices in (up, reversed(up)): + swapped = False + for i in indices: + if A[i] > A[i+1]: + A[i], A[i+1] = A[i+1], A[i] + swapped = True + if not swapped: + return diff --git a/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-2.py b/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-2.py new file mode 100644 index 0000000000..08f298bb9f --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Python/sorting-algorithms-cocktail-sort-2.py @@ -0,0 +1,9 @@ +test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] +cocktailSort(test1) +print test1 +#>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +test2=list('big fjords vex quick waltz nymph') +cocktailSort(test2) +print ''.join(test2) +#>>> abcdefghiijklmnopqrstuvwxyz diff --git a/Task/Sorting-algorithms-Cocktail-sort/R/sorting-algorithms-cocktail-sort.r b/Task/Sorting-algorithms-Cocktail-sort/R/sorting-algorithms-cocktail-sort.r new file mode 100644 index 0000000000..3eb5fe454c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/R/sorting-algorithms-cocktail-sort.r @@ -0,0 +1,35 @@ +cocktailsort <- function(x) +{ + lenx <- length(x) + repeat + { + swapped <- FALSE + for(i in 1:(lenx-1)) + { + if(x[i] > x[i+1]) + { + temp <- x[i] + x[i] <- x[i+1] + x[i+1] <- temp + swapped <- TRUE + } + } + if(!swapped) break + + swapped <- FALSE + for(i in (lenx-1):1) + { + if(x[i] > x[i+1]) + { + temp <- x[i] + x[i] <- x[i+1] + x[i+1] <- temp + swapped <- TRUE + } + } + if(!swapped) break + } + x +} + +print(cocktailsort(c(5, -1, 101, -4, 0, 1, 8, 6, 2, 3))) diff --git a/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-1.rexx b/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-1.rexx new file mode 100644 index 0000000000..f57dea8b9b --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-1.rexx @@ -0,0 +1,71 @@ +/*REXX program sorts an array using the cocktail-sort method, a.k.a.: */ + /* bidirectional bubble sort, */ + /* cocktail shaker sort, */ + /* a selection sort variation,*/ + /* ripple sort, */ + /* shuffle sort, */ + /* shuttle sort, */ + /* happy hour sort, */ + /* a bubble sort variation. */ + +call gen@ /*generate some array elements. */ +call show@ 'before sort' /*show unsorted array elements.*/ +call cocktailSort highItem /*invoke cocktail sort subroutine*/ +call show@ ' after sort' /*show sorted array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────COCKTAILSORT subroutine─────────────*/ +cocktailSort: procedure expose @.; parse arg N /*N=# of items.*/ + + do until done; done=1 + + do j=1 for N-1; jp=j+1 + if @.j>@.jp then do; done=0; _=@.j; @.j=@.jp; @.jp=_; end + end /*j*/ + + if done then leave /*No swaps done? Then we're done*/ + + do k=N-1 for N-1 by -1; kp=k+1 + if @.k>@.kp then do; done=0; _=@.k; @.k=@.kp; @.kp=_; end + end /*k*/ + + end /*until*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.='' /*assign default value for stem. */ +@.1 ='---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---' +@.2 ='==========symbol====================pip======================================' +@.3 ='the juggler ◄─── I' +@.4 ='the high priestess [Popess] ◄─── II' +@.5 ='the empress ◄─── III' +@.6 ='the emperor ◄─── IV' +@.7 ='the hierophant [Pope] ◄─── V' +@.8 ='the lovers ◄─── VI' +@.9 ='the chariot ◄─── VII' +@.10='justice ◄─── VIII' +@.11='the hermit ◄─── IX' +@.12='fortune [the wheel of] ◄─── X' +@.13='strength ◄─── XI' +@.14='the hanging man ◄─── XII' +@.15='death [often unlabeled] ◄─── XIII' +@.16='temperance ◄─── XIV' +@.17='the devil ◄─── XV' +@.18='lightning [the tower] ◄─── XVI' +@.18='the stars ◄─── XVII' +@.20='the moon ◄─── XVIII' +@.21='the sun ◄─── XIX' +@.22='judgment ◄─── XX' +@.23='the world ◄─── XXI' +@.24='the fool [often unnumbered] ◄─── XXII' + + do i=1 while @.i\==''; end /*find how many entries in array.*/ + +highItem=i-1 /*adjust for DO loop advancement.*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(highItem) /*the maximum width of any line. */ + + do j=1 for highItem + say 'element' right(j,widthH) arg(1)":" @.j + end +say copies('─',79) /*show a separator line or fence.*/ +return diff --git a/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-2.rexx b/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-2.rexx new file mode 100644 index 0000000000..27fa0cead4 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/REXX/sorting-algorithms-cocktail-sort-2.rexx @@ -0,0 +1,17 @@ +/*──────────────────────────────────COCKTAILSORT2 subroutine────────────*/ +cocktailSort2: procedure expose @.; parse arg N /*N=# of items.*/ + /*array items may not contain blanks*/ + do until done; done=1 + + do j=1 for N-1; jp=j+1 + if @.j>@.jp then parse value 0 @.j @.jp with done @.jp @.j + end /*j*/ + + if done then leave /*No swaps done? Then we're done*/ + + do k=N-1 for N-1 by -1; kp=k+1 + if @.k>@.kp then parse value 0 @.k @.kp with done @.kp @.k + end /*k*/ + + end /*until*/ +return diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb new file mode 100644 index 0000000000..147e1049e7 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ruby/sorting-algorithms-cocktail-sort.rb @@ -0,0 +1,26 @@ +class Array + def cocktailsort! + begin + swapped = false + 0.upto(length - 2) do |i| + if self[i] > self[i + 1] + self[i], self[i + 1] = self[i + 1], self[i] + swapped = true + end + end + break if not swapped + + swapped = false + (length - 2).downto(0) do |i| + if self[i] > self[i + 1] + self[i], self[i + 1] = self[i + 1], self[i] + swapped = true + end + end + end while swapped + self + end +end +ary = [7,6,5,9,8,4,3,1,2,0] +ary.cocktailsort! +# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Cocktail-sort/Run-BASIC/sorting-algorithms-cocktail-sort.run b/Task/Sorting-algorithms-Cocktail-sort/Run-BASIC/sorting-algorithms-cocktail-sort.run new file mode 100644 index 0000000000..bc070cadd1 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Run-BASIC/sorting-algorithms-cocktail-sort.run @@ -0,0 +1,27 @@ +for i = 1 to 100 ' fill array + a(i) = rnd(0) * 100 +next i +' ------- sort ------- +beg = 2 +siz = 100 +whatWay = 1 +changed = 1 +while changed +changed = 0 + FOR i = beg TO siz STEP whatWay + IF a(i-1) > a(i) THEN + hold = a(i) + a(i) = a(i-1) + a(i-1) = hold + changed = i + end if + NEXT i + siz = beg + beg = changed - whatWay + whatWay = 0 - whatWay +wend +' ------ print result -------- +for i = 1 to 100 + print i;" ";a(i) +next i +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-1.slate b/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-1.slate new file mode 100644 index 0000000000..27b9bc5d56 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-1.slate @@ -0,0 +1,10 @@ +s@(Sequence traits) cocktailSort +[ |swapped| + swapped: False. + s size <= 1 ifTrue: [^ s]. + [{0 to: s size - 2. s size - 2 downTo: 0} + do: [|:range| range do: [|:index| (s at: index) > (s at: index + 1) ifTrue: [s swap: index with: index + 1. swapped: True]]. + swapped ifFalse: [^ s]. + swapped: False]. + ] loop +]. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-2.slate b/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-2.slate new file mode 100644 index 0000000000..13561d6b9f --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Slate/sorting-algorithms-cocktail-sort-2.slate @@ -0,0 +1,2 @@ +slate[1]> #( 10 9 8 7 6 0 -5) cocktailSort. +{-5. 0. 6. 7. 8. 9. 10} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-1.st b/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-1.st new file mode 100644 index 0000000000..b1e598f62d --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-1.st @@ -0,0 +1,30 @@ +OrderedCollection extend [ + swap: indexA and: indexB [ + |t| + t := self at: indexA. + self at: indexA put: (self at: indexB). + self at: indexB put: t + ] + cocktailSort [ + |swapped| + [ + swapped := false. + 1 to: (self size - 1) do: [ :i | + (self at: i) > (self at: (i+1)) ifTrue: [ + self swap: i and: (i+1). + swapped := true + ] + ]. + swapped ifFalse: [ ^ self ]. + swapped := false. + (self size - 1) to: 1 by: -1 do: [ :i | + (self at: i) > (self at: (i+1)) ifTrue: [ + self swap: i and: (i+1). + swapped := true + ] + ]. + swapped + ] whileTrue: [ ]. + ^ self + ] +]. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-2.st b/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-2.st new file mode 100644 index 0000000000..1a8684c3b6 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Smalltalk/sorting-algorithms-cocktail-sort-2.st @@ -0,0 +1 @@ +(#( 10 9 8 7 6 0 -5) asOrderedCollection cocktailSort) printNl. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-1.tcl b/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-1.tcl new file mode 100644 index 0000000000..9b26c02805 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-1.tcl @@ -0,0 +1,29 @@ +package require Tcl 8.5 +package require struct::list + +proc cocktailsort {A} { + set len [llength $A] + set swapped true + while {$swapped} { + set swapped false + for {set i 0} {$i < $len - 1} {incr i} { + set j [expr {$i + 1}] + if {[lindex $A $i] > [lindex $A $j]} { + struct::list swap A $i $j + set swapped true + } + } + if { ! $swapped} { + break + } + set swapped false + for {set i [expr {$len - 2}]} {$i >= 0} {incr i -1} { + set j [expr {$i + 1}] + if {[lindex $A $i] > [lindex $A $j]} { + struct::list swap A $i $j + set swapped true + } + } + } + return $A +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-2.tcl b/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-2.tcl new file mode 100644 index 0000000000..7adf46169c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Tcl/sorting-algorithms-cocktail-sort-2.tcl @@ -0,0 +1 @@ +puts [cocktailsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-1.ursala b/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-1.ursala new file mode 100644 index 0000000000..5a020ac1ea --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-1.ursala @@ -0,0 +1,3 @@ +#import std + +ctsort = ^=+ +^|(==?/~&l+ @r+ ~&x++ @x,^/~&)+ ("p". =><> ~&r?\~&C "p"?lrhPX/~&C ~&rhPlrtPCC)^~/not ~& diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-2.ursala b/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-2.ursala new file mode 100644 index 0000000000..7cfefee43c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ursala/sorting-algorithms-cocktail-sort-2.ursala @@ -0,0 +1,3 @@ +#cast %s + +test = ctsort(lleq) 'mdfdguldxisgbxjtqkadfkslakwkyioukdledbig' diff --git a/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbscript b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbscript new file mode 100644 index 0000000000..c37a58f85e --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbscript @@ -0,0 +1,30 @@ +function cocktailSort( a ) + dim swapped + dim i + do + swapped = false + for i = 0 to ubound( a ) - 1 + if a(i) > a(i+1) then + swap a(i), a(i+1) + swapped = true + end if + next + if not swapped then exit do + swapped = false + for i = ubound( a ) - 1 to 0 step -1 + if a(i) > a( i+1) then + swap a(i), a(i+1) + swapped = true + end if + next + if not swapped then exit do + loop + cocktailSort = a +end function + +sub swap( byref a, byref b) + dim tmp + tmp = a + a = b + b = tmp +end sub diff --git a/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbscript b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbscript new file mode 100644 index 0000000000..f2e232b4ef --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbscript @@ -0,0 +1,7 @@ +dim a +a = array( "portcullis", "redoubt", "palissade", "turret", "collins", "the parapet", "the quarterdeck") +wscript.echo join( a, ", ") + +dim b +b = cocktailSort( a ) +wscript.echo join( b, ", ") diff --git a/Task/Sorting-algorithms-Cocktail-sort/XPL0/sorting-algorithms-cocktail-sort.xpl0 b/Task/Sorting-algorithms-Cocktail-sort/XPL0/sorting-algorithms-cocktail-sort.xpl0 new file mode 100644 index 0000000000..dd7758bde5 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/XPL0/sorting-algorithms-cocktail-sort.xpl0 @@ -0,0 +1,28 @@ +code ChOut=8, IntOut=11; + +proc CocktailSort(A, L); \Sort array A of length L +int A, L; +int Swapped, I, T; +[loop [Swapped:= false; + for I:= 0 to L-2 do + if A(I) > A(I+1) then \test if elements are in wrong order + [T:= A(I); A(I):= A(I+1); A(I+1):= T; \elements change places + Swapped:= true; + ]; + if Swapped = false then quit; \exit outer loop if no swaps occurred + Swapped:= false; + for I:= L-2 downto 0 do + if A(I) > A(I+1) then + [T:= A(I); A(I):= A(I+1); A(I+1):= T; + Swapped:= true; + ]; + \if no elements have been swapped then the list is sorted + if not Swapped then quit; + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +CocktailSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Comb-sort/0DESCRIPTION b/Task/Sorting-algorithms-Comb-sort/0DESCRIPTION new file mode 100644 index 0000000000..858f441a35 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/0DESCRIPTION @@ -0,0 +1,30 @@ +{{Sorting Algorithm}} + +The '''Comb Sort''' is a variant of the [[Bubble Sort]]. Like the [[Shell sort]], the Comb Sort increases the gap used in comparisons and exchanges (dividing the gap by <math>(1-e^{-\varphi})^{-1} \approx 1.247330950103979</math> works best, but 1.3 may be more practical). Some implementations use the insertion sort once the gap is less than a certain amount. See the [[wp:Comb sort|article on Wikipedia]]. +Variants: +*Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings +*Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small). Comb sort with a low gap isn't much better than the Bubble Sort. + +Pseudocode: + '''function''' combsort('''array''' input) + gap := input'''.size''' ''//initialize gap size'' + '''loop until''' gap = 1 '''and''' swaps = 0 + ''//update the gap value for a next comb. Below is an example'' + gap := int(gap / 1.25) + '''if''' gap < 1 + ''//minimum gap is 1'' + gap := 1 + '''end if''' + i := 0 + swaps := 0 ''//see [[Bubble Sort]] for an explanation'' + ''//a single "comb" over the input list'' + '''loop until''' i + gap >= input'''.size''' ''//see [[Shell sort]] for similar idea'' + '''if''' input[i] > input[i+gap] + '''swap'''(input[i], input[i+gap]) + swaps := 1 ''// Flag a swap has occurred, so the'' + ''// list is not guaranteed sorted'' + '''end if''' + i := i + 1 + '''end loop''' + '''end loop''' + '''end function''' diff --git a/Task/Sorting-algorithms-Comb-sort/1META.yaml b/Task/Sorting-algorithms-Comb-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Comb-sort/AWK/sorting-algorithms-comb-sort.awk b/Task/Sorting-algorithms-Comb-sort/AWK/sorting-algorithms-comb-sort.awk new file mode 100644 index 0000000000..6dc23caef6 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/AWK/sorting-algorithms-comb-sort.awk @@ -0,0 +1,38 @@ +function combsort( a, len, gap, igap, swap, swaps, i ) +{ + gap = len + swaps = 1 + + while( gap > 1 || swaps ) + { + gap /= 1.2473; + if ( gap < 1 ) gap = 1 + i = swaps = 0 + while( i + gap < len ) + { + igap = i + int(gap) + if ( a[i] > a[igap] ) + { + swap = a[i] + a[i] = a[igap] + a[igap] = swap + swaps = 1 + } + i++; + } + } +} + +BEGIN { + a[0] = 5 + a[1] = 2 + a[2] = 7 + a[3] = -11 + a[4] = 6 + a[5] = 1 + + combsort( a, length(a) ) + + for( i=0; i<length(a); i++ ) + print a[i] +} diff --git a/Task/Sorting-algorithms-Comb-sort/ActionScript/sorting-algorithms-comb-sort.as b/Task/Sorting-algorithms-Comb-sort/ActionScript/sorting-algorithms-comb-sort.as new file mode 100644 index 0000000000..9040c30cd8 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/ActionScript/sorting-algorithms-comb-sort.as @@ -0,0 +1,21 @@ +function combSort(input:Array) +{ + var gap:uint = input.length; + var swapped:Boolean = false; + while(gap > 1 || swapped) + { + gap /= 1.25; + swapped = false; + for(var i:uint = 0; i + gap < input.length; i++) + { + if(input[i] > input[i+gap]) + { + var tmp = input[i]; + input[i] = input[i+gap]; + input[i+gap]=tmp; + swapped = true; + } + } + } + return input; +} diff --git a/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.ada b/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.ada new file mode 100644 index 0000000000..36c60270b0 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.ada @@ -0,0 +1,47 @@ +with Ada.Text_IO; +procedure Comb_Sort is + generic + type Element_Type is private; + type Index_Type is range <>; + type Array_Type is array (Index_Type range <>) of Element_Type; + with function ">" (Left, Right : Element_Type) return Boolean is <>; + with function "+" (Left : Index_Type; Right : Natural) return Index_Type is <>; + with function "-" (Left : Index_Type; Right : Natural) return Index_Type is <>; + procedure Comb_Sort (Data: in out Array_Type); + + procedure Comb_Sort (Data: in out Array_Type) is + procedure Swap (Left, Right : in Index_Type) is + Temp : Element_Type := Data(Left); + begin + Data(Left) := Data(Right); + Data(Right) := Temp; + end Swap; + Gap : Natural := Data'Length; + Swap_Occured : Boolean; + begin + loop + Gap := Natural (Float(Gap) / 1.25 - 0.5); + if Gap < 1 then + Gap := 1; + end if; + Swap_Occured := False; + for I in Data'First .. Data'Last - Gap loop + if Data (I) > Data (I+Gap) then + Swap (I, I+Gap); + Swap_Occured := True; + end if; + end loop; + exit when Gap = 1 and not Swap_Occured; + end loop; + end Comb_Sort; + + type Integer_Array is array (Positive range <>) of Integer; + procedure Int_Comb_Sort is new Comb_Sort (Integer, Positive, Integer_Array); + Test_Array : Integer_Array := (1, 3, 256, 0, 3, 4, -1); +begin + Int_Comb_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Comb_Sort; diff --git a/Task/Sorting-algorithms-Comb-sort/AutoHotkey/sorting-algorithms-comb-sort.ahk b/Task/Sorting-algorithms-Comb-sort/AutoHotkey/sorting-algorithms-comb-sort.ahk new file mode 100644 index 0000000000..996ac2dc9a --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/AutoHotkey/sorting-algorithms-comb-sort.ahk @@ -0,0 +1,48 @@ +List1 = 23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78 +List2 = 88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70 + +List2Array(List1, "MyArray") +CombSort("MyArray") +MsgBox, % List1 "`n" Array2List("MyArray") + +List2Array(List2, "MyArray") +CombSort("MyArray") +MsgBox, % List2 "`n" Array2List("MyArray") + + + +;--------------------------------------------------------------------------- +CombSort(Array) { ; CombSort of Array %Array%, length = %Array%0 +;--------------------------------------------------------------------------- + Gap := %Array%0 + While Gap > 1 Or Swaps { + If (Gap > 1) + Gap := 4 * Gap // 5 + i := Swaps := False + While (j := ++i + Gap) <= %Array%0 { + If (%Array%%i% > %Array%%j%) { + Swaps := True + %Array%%i% := (%Array%%j% "", %Array%%j% := %Array%%i%) + } + } + } +} + + + +;--------------------------------------------------------------------------- +List2Array(List, Array) { ; creates an array from a comma separated list +;--------------------------------------------------------------------------- + global + StringSplit, %Array%, List, `, +} + + + +;--------------------------------------------------------------------------- +Array2List(Array) { ; returns a comma separated list from an array +;--------------------------------------------------------------------------- + Loop, % %Array%0 + List .= (A_Index = 1 ? "" : ",") %Array%%A_Index% + Return, List +} diff --git a/Task/Sorting-algorithms-Comb-sort/BBC-BASIC/sorting-algorithms-comb-sort.bbc b/Task/Sorting-algorithms-Comb-sort/BBC-BASIC/sorting-algorithms-comb-sort.bbc new file mode 100644 index 0000000000..4fb00d8553 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/BBC-BASIC/sorting-algorithms-comb-sort.bbc @@ -0,0 +1,20 @@ +DEF PROC_CombSort11(Size%) + +gap%=Size% +REPEAT + IF gap% > 1 THEN + gap%=gap% / 1.3 + IF gap%=9 OR gap%=10 gap%=11 + ENDIF + I% = 1 + Finished%=TRUE + REPEAT + IF data%(I%) > data%(I%+gap%) THEN + SWAP data%(I%),data%(I%+gap%) + Finished% = FALSE + ENDIF + I%+=1 + UNTIL I%+gap% > Size% +UNTIL gap%=1 AND Finished% + +ENDPROC diff --git a/Task/Sorting-algorithms-Comb-sort/C++/sorting-algorithms-comb-sort.cpp b/Task/Sorting-algorithms-Comb-sort/C++/sorting-algorithms-comb-sort.cpp new file mode 100644 index 0000000000..6fcdf720c2 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/C++/sorting-algorithms-comb-sort.cpp @@ -0,0 +1,24 @@ +template<class ForwardIterator> +void combsort ( ForwardIterator first, ForwardIterator last ) +{ + static const double shrink_factor = 1.247330950103979; + typedef typename std::iterator_traits<ForwardIterator>::difference_type difference_type; + difference_type gap = std::distance(first, last); + bool swaps = true; + + while ( (gap > 1) || (swaps == true) ){ + if (gap > 1) + gap = static_cast<difference_type>(gap/shrink_factor); + + swaps = false; + ForwardIterator itLeft(first); + ForwardIterator itRight(first); std::advance(itRight, gap); + + for ( ; itRight!=last; ++itLeft, ++itRight ){ + if ( (*itRight) < (*itLeft) ){ + std::iter_swap(itLeft, itRight); + swaps = true; + } + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/C/sorting-algorithms-comb-sort.c b/Task/Sorting-algorithms-Comb-sort/C/sorting-algorithms-comb-sort.c new file mode 100644 index 0000000000..f31149b507 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/C/sorting-algorithms-comb-sort.c @@ -0,0 +1,24 @@ +void Combsort11(double a[], int nElements) +{ + int i, j, gap, swapped = 1; + double temp; + + gap = nElements; + while (gap > 1 || swapped == 1) + { + gap = gap * 10 / 13; + if (gap == 9 || gap == 10) gap = 11; + if (gap < 1) gap = 1; + swapped = 0; + for (i = 0, j = gap; j < nElements; i++, j++) + { + if (a[i] > a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + swapped = 1; + } + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cobol b/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cobol new file mode 100644 index 0000000000..73cd5b516b --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cobol @@ -0,0 +1,41 @@ + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE WC-SIZE TO WC-GAP. + + PERFORM E-COMB UNTIL WC-GAP = 1 AND FINISHED. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-COMB SECTION. + E-000. + IF WC-GAP > 1 + DIVIDE WC-GAP BY 1.3 GIVING WC-GAP + IF WC-GAP = 9 OR 10 + MOVE 11 TO WC-GAP. + + MOVE 1 TO WC-SUB-1. + MOVE "Y" TO WF-FINISHED. + + PERFORM F-SCAN UNTIL WC-SUB-1 + WC-GAP > WC-SIZE. + + E-999. + EXIT. + + F-SCAN SECTION. + F-000. + ADD WC-SUB-1 WC-GAP GIVING WC-SUB-2. + IF WB-ENTRY(WC-SUB-1) > WB-ENTRY(WC-SUB-2) + MOVE WB-ENTRY(WC-SUB-1) TO WC-TEMP + MOVE WB-ENTRY(WC-SUB-2) TO WB-ENTRY(WC-SUB-1) + MOVE WC-TEMP TO WB-ENTRY(WC-SUB-2) + MOVE "N" TO WF-FINISHED. + + ADD 1 TO WC-SUB-1. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d b/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d new file mode 100644 index 0000000000..d8cdd6271e --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d @@ -0,0 +1,22 @@ +import std.stdio, std.algorithm; + +void combSort(T)(T[] input) { + int gap = input.length; + bool swaps = true; + + while (gap > 1 || swaps) { + gap = max(1, cast(int)(gap / 1.2473)); + swaps = false; + foreach (i; 0 .. input.length - gap) + if (input[i] > input[i + gap]) { + swap(input[i], input[i + gap]); + swaps = true; + } + } +} + +void main() { + auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; + combSort(array); + writeln(array); +} diff --git a/Task/Sorting-algorithms-Comb-sort/Forth/sorting-algorithms-comb-sort.fth b/Task/Sorting-algorithms-Comb-sort/Forth/sorting-algorithms-comb-sort.fth new file mode 100644 index 0000000000..02fc4e3cb7 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Forth/sorting-algorithms-comb-sort.fth @@ -0,0 +1,47 @@ +defer precedes +defer exchange + +: gnomesort ( a n) + swap >r 1 ( n c) + begin ( n c) + over over > ( n c f) + while ( n c) + dup if ( n c) + dup dup 1- over over r@ precedes + if r@ exchange 1- else drop drop 1+ then + else 1+ then ( n c) + repeat drop drop r> drop ( --) +; + +: combsort ( a n --) + dup begin ( a n g) + 10 13 */ tuck >r >r 0 ( a g 0) + begin ( a g 0) + over r@ < ( a g 0 f) + while ( a g 0) + rot >r over over r@ precedes ( g 0 f) + if over over r@ exchange then ( g 0) + r> rot 1+ rot 1+ ( a g 0) + repeat drop drop r> r> ( a n g) + dup 9 < ( a n g f) + until drop gnomesort ( --) +; + +create example + 8 93 69 52 50 79 33 52 19 77 , , , , , , , , , , + 72 85 11 61 64 80 64 76 47 65 , , , , , , , , , , + 13 47 23 40 87 45 2 48 22 69 , , , , , , , , , , + 1 53 33 60 57 14 76 32 59 12 , , , , , , , , , , + 74 38 39 22 87 28 37 93 71 88 , , , , , , , , , , + 56 35 48 99 21 35 26 28 58 85 , , , , , , , , , , + 27 16 54 88 82 18 45 64 45 87 , , , , , , , , , , + 98 97 60 77 43 1 64 0 32 89 , , , , , , , , , , + 77 90 68 83 9 76 10 10 95 12 , , , , , , , , , , + 99 23 74 58 54 25 50 9 94 1 , , , , , , , , , , + +:noname >r cells r@ + @ swap cells r> + @ swap < ; is precedes +:noname >r cells r@ + swap cells r> + over @ over @ swap rot ! swap ! ; is exchange + +: .array 100 0 do example i cells + ? loop cr ; + +.array example 100 combsort .array diff --git a/Task/Sorting-algorithms-Comb-sort/Fortran/sorting-algorithms-comb-sort.f b/Task/Sorting-algorithms-Comb-sort/Fortran/sorting-algorithms-comb-sort.f new file mode 100644 index 0000000000..143d8d82fb --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Fortran/sorting-algorithms-comb-sort.f @@ -0,0 +1,42 @@ +program Combsort_Demo + implicit none + + integer, parameter :: num = 20 + real :: array(num) + + call random_seed + call random_number(array) + write(*,*) "Unsorted array:-" + write(*,*) array + write(*,*) + call combsort(array) + write(*,*) "Sorted array:-" + write(*,*) array + +contains + + subroutine combsort(a) + + real, intent(in out) :: a(:) + real :: temp + integer :: i, gap + logical :: swapped = .true. + + gap = size(a) + do while (gap > 1 .or. swapped) + gap = gap / 1.3 + if (gap < 1) gap = 1 + swapped = .false. + do i = 1, size(a)-gap + if (a(i) > a(i+gap)) then + temp = a(i) + a(i) = a(i+gap) + a(i+gap) = temp; + swapped = .true. + end if + end do + end do + + end subroutine combsort + +end program Combsort_Demo diff --git a/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-1.go b/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-1.go new file mode 100644 index 0000000000..ebef8f5615 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-1.go @@ -0,0 +1,35 @@ +package main + +import "fmt" + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + combSort(a) + fmt.Println("after: ", a) +} + +func combSort(a []int) { + if len(a) < 2 { + return + } + for gap := len(a); ; { + if gap > 1 { + gap = gap * 4 / 5 + } + swapped := false + for i := 0; ; { + if a[i] > a[i+gap] { + a[i], a[i+gap] = a[i+gap], a[i] + swapped = true + } + i++ + if i+gap >= len(a) { + break + } + } + if gap == 1 && !swapped { + break + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-2.go b/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-2.go new file mode 100644 index 0000000000..3dad9fa66c --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Go/sorting-algorithms-comb-sort-2.go @@ -0,0 +1,38 @@ +package main + +import ( + "sort" + "fmt" +) + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + combSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} + +func combSort(a sort.Interface) { + if a.Len() < 2 { + return + } + for gap := a.Len(); ; { + if gap > 1 { + gap = gap * 4 / 5 + } + swapped := false + for i := 0; ; { + if a.Less(i+gap, i) { + a.Swap(i, i+gap) + swapped = true + } + i++ + if i+gap >= a.Len() { + break + } + } + if gap == 1 && !swapped { + break + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-1.groovy b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-1.groovy new file mode 100644 index 0000000000..ddcf2dd11c --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-1.groovy @@ -0,0 +1,16 @@ +def makeSwap = { a, i, j -> print "."; a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j] } + +def checkSwap = { a, i, j -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } + +def combSort = { input -> + def swap = checkSwap.curry(input) + def size = input.size() + def gap = size + def swapped = true + while (gap != 1 || swapped) { + gap = (gap / 1.247330950103979) as int + gap = (gap < 1) ? 1 : gap + swapped = (0..<(size-gap)).any { swap(it, it + gap) } + } + input +} diff --git a/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-2.groovy b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-2.groovy new file mode 100644 index 0000000000..5b89a1bd11 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-2.groovy @@ -0,0 +1,12 @@ +def combSort11 = { input -> + def swap = checkSwap.curry(input) + def size = input.size() + def gap = size + def swapped = true + while (gap != 1 || swapped) { + gap = (gap / 1.247330950103979) as int + gap = ((gap < 1) ? 1 : ([10,9].contains(gap) ? 11 : gap)) + swapped = (0..<(size-gap)).any { swap(it, it + gap) } + } + input +} diff --git a/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-3.groovy b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-3.groovy new file mode 100644 index 0000000000..c022cd13f3 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Groovy/sorting-algorithms-comb-sort-3.groovy @@ -0,0 +1,5 @@ +println (combSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (combSort11([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println () +println (combSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (combSort11([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) diff --git a/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-1.hs b/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-1.hs new file mode 100644 index 0000000000..2ab4215540 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-1.hs @@ -0,0 +1,13 @@ +import Data.List +import Control.Arrow +import Control.Monad + +flgInsert x xs = ((x:xs==) &&& id)$ insert x xs + +gapSwapping k = (and *** concat. transpose). unzip + . map (foldr (\x (b,xs) -> first (b &&)$ flgInsert x xs) (True,[])) + . transpose. takeWhile (not.null). unfoldr (Just. splitAt k) + +combSort xs = (snd. fst) $ until (\((b,_),g)-> b && g==1) + (\((_,xs),g) ->(gapSwapping g xs, fg g)) ((False,xs), fg $ length xs) + where fg = max 1. truncate. (/1.25). fromIntegral diff --git a/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-2.hs b/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-2.hs new file mode 100644 index 0000000000..c50b71e608 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Haskell/sorting-algorithms-comb-sort-2.hs @@ -0,0 +1,2 @@ +*Main> combSort [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78] +[12,14,23,24,24,31,35,38,46,51,57,57,58,76,78,89,92,95,97,99] diff --git a/Task/Sorting-algorithms-Comb-sort/Icon/sorting-algorithms-comb-sort.icon b/Task/Sorting-algorithms-Comb-sort/Icon/sorting-algorithms-comb-sort.icon new file mode 100644 index 0000000000..e51c576983 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Icon/sorting-algorithms-comb-sort.icon @@ -0,0 +1,22 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(combsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure combsort(X,op) #: return sorted X +local gap,swapped,i + + op := sortop(op,X) # select how and what we sort + + swappped := gap := *X # initialize gap size and say swapped + until /swapped & gap = 1 do { + gap := integer(gap / 1.25) # update the gap value for a next comb + gap <:= 1 # minimum gap of 1 + swapped := &null + + i := 0 + until (i +:= 1) + gap > *X do # a single "comb" over the input list + if op(X[i+gap],X[i]) then + X[i+1] :=: X[swapped := i] # swap and flag as unsorted + } + return X +end diff --git a/Task/Sorting-algorithms-Comb-sort/Io/sorting-algorithms-comb-sort.io b/Task/Sorting-algorithms-Comb-sort/Io/sorting-algorithms-comb-sort.io new file mode 100644 index 0000000000..641fc9a272 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Io/sorting-algorithms-comb-sort.io @@ -0,0 +1,21 @@ +List do( + combSortInPlace := method( + gap := size + swap := true + + while(gap > 1 or swap, + swap = false + gap = (gap / 1.25) floor + + for(i, 0, size - gap, + if(at(i) > at(i + gap), + swap = true + swapIndices(i, i + gap) + ) + ) + ) + self) +) + +lst := list(23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78) +lst combSortInPlace println # ==> list(12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99) diff --git a/Task/Sorting-algorithms-Comb-sort/J/sorting-algorithms-comb-sort.j b/Task/Sorting-algorithms-Comb-sort/J/sorting-algorithms-comb-sort.j new file mode 100644 index 0000000000..832632bd05 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/J/sorting-algorithms-comb-sort.j @@ -0,0 +1,13 @@ +combSort=:3 :0 + gap=. #y + whilst.1 < gap+swaps do. + swaps=. 0 + i=. i.2,gap=. 1 >. <.gap%1.25 + while.{:$i=.i #"1~ ({: i) < #y do. + swaps=.swaps+#{:k=.i #"1~b=. >/ i{y + i=. i+gap + y=.((|.k){y) k} y + end. + end. + y +) diff --git a/Task/Sorting-algorithms-Comb-sort/Java/sorting-algorithms-comb-sort.java b/Task/Sorting-algorithms-Comb-sort/Java/sorting-algorithms-comb-sort.java new file mode 100644 index 0000000000..4e2f13a9c8 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Java/sorting-algorithms-comb-sort.java @@ -0,0 +1,18 @@ +public static <E extends Comparable<? super E>> void sort(E[] input) { + int gap = input.length; + boolean swapped = true; + while (gap > 1 || swapped) { + if (gap > 1) { + gap = (int) (gap / 1.3); + } + swapped = false; + for (int i = 0; i + gap < input.length; i++) { + if (input[i].compareTo(input[i + gap]) > 0) { + E t = input[i]; + input[i] = input[i + gap]; + input[i + gap] = t; + swapped = true; + } + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/Lua/sorting-algorithms-comb-sort.lua b/Task/Sorting-algorithms-Comb-sort/Lua/sorting-algorithms-comb-sort.lua new file mode 100644 index 0000000000..25fdc18212 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Lua/sorting-algorithms-comb-sort.lua @@ -0,0 +1,16 @@ +function combsort(t) + local gapd, gap, swaps = 1.2473, #t, 0 + while gap + swaps > 1 do + local k = 0 + swaps = 0 + if gap > 1 then gap = math.floor(gap / gapd) end + for k = 1, #t - gap do + if t[k] > t[k + gap] then + t[k], t[k + gap], swaps = t[k + gap], t[k], swaps + 1 + end + end + end + return t +end + +print(unpack(combsort{3,5,1,2,7,4,8,3,6,4,1})) diff --git a/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-1.m b/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-1.m new file mode 100644 index 0000000000..5b8fa32818 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-1.m @@ -0,0 +1,30 @@ +function list = combSort(list) + + listSize = numel(list); + gap = int32(listSize); %Coerce gap to an int so we can use the idivide function + swaps = true; %Swap flag + + while not((gap <= 1) && (swaps == false)) + + gap = idivide(gap,1.25,'floor'); %Int divide, floor the resulting operation + + if gap < 1 + gap = 1; + end + + i = 1; %i equals 1 because all arrays are 1 based in MATLAB + swaps = false; + + %i + gap must be subtracted by 1 because the pseudo-code was writen + %for 0 based arrays + while not((i + gap - 1) >= listSize) + + if (list(i) > list(i+gap)) + list([i i+gap]) = list([i+gap i]); %swap + swaps = true; + end + i = i + 1; + + end %while + end %while +end %combSort diff --git a/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-2.m b/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-2.m new file mode 100644 index 0000000000..133f1381d5 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/MATLAB/sorting-algorithms-comb-sort-2.m @@ -0,0 +1,5 @@ +>> combSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Comb-sort/Mathematica/sorting-algorithms-comb-sort.math b/Task/Sorting-algorithms-Comb-sort/Mathematica/sorting-algorithms-comb-sort.math new file mode 100644 index 0000000000..593fe51641 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Mathematica/sorting-algorithms-comb-sort.math @@ -0,0 +1,15 @@ +combSort[list_] := Module[{ gap = 0, listSize = 0, swaps = True}, + gap = listSize = Length[list]; + While[ !((gap <= 1) && (swaps == False)), + + gap = Floor@Divide[gap, 1.25]; + If[ gap < 1, gap = 1]; i = 1; swaps = False; + + While[ ! ((i + gap - 1) >= listSize), + If[ list[[i]] > list[[i + gap]], swaps = True; + list[[i ;; i + gap]] = list[[i + gap ;; i ;; -1]]; + ]; + i++; + ] + ] +] diff --git a/Task/Sorting-algorithms-Comb-sort/NetRexx/sorting-algorithms-comb-sort.netrexx b/Task/Sorting-algorithms-Comb-sort/NetRexx/sorting-algorithms-comb-sort.netrexx new file mode 100644 index 0000000000..e10b0f66b0 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/NetRexx/sorting-algorithms-comb-sort.netrexx @@ -0,0 +1,51 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +placesList = [String - + "UK London", "US New York" - + , "US Boston", "US Washington" - + , "UK Washington", "US Birmingham" - + , "UK Birmingham", "UK Boston" - +] +sortedList = combSort(String[] Arrays.copyOf(placesList, placesList.length)) + +lists = [placesList, sortedList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method combSort(input = String[]) public constant binary returns String[] + + swaps = isTrue + gap = input.length + loop label comb until gap = 1 & \swaps + gap = int gap / 1.25 + if gap < 1 then + gap = 1 + i_ = 0 + swaps = isFalse + loop label swaps until i_ + gap >= input.length + if input[i_].compareTo(input[i_ + gap]) > 0 then do + swap = input[i_] + input[i_] = input[i_ + gap] + input[i_ + gap] = swap + swaps = isTrue + end + i_ = i_ + 1 + end swaps + end comb + + return input + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue diff --git a/Task/Sorting-algorithms-Comb-sort/OCaml/sorting-algorithms-comb-sort.ocaml b/Task/Sorting-algorithms-Comb-sort/OCaml/sorting-algorithms-comb-sort.ocaml new file mode 100644 index 0000000000..a5a86fa6f5 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/OCaml/sorting-algorithms-comb-sort.ocaml @@ -0,0 +1,19 @@ +let comb_sort ~input = + let input_length = Array.length input in + let gap = ref(input_length) in + let swapped = ref true in + while (!gap > 1 || !swapped) do + if (!gap > 1) then + gap := int_of_float (float !gap /. 1.3); + + swapped := false; + for i = 0 to input_length - !gap do + if input.(i) > input.(i + !gap) then begin + let tmp = input.(i) in + input.(i) <- input.(i + !gap); + input.(i + !gap) <- tmp; + swapped := true; + end + done + done +;; diff --git a/Task/Sorting-algorithms-Comb-sort/Objeck/sorting-algorithms-comb-sort.objeck b/Task/Sorting-algorithms-Comb-sort/Objeck/sorting-algorithms-comb-sort.objeck new file mode 100644 index 0000000000..b3b996a9ff --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Objeck/sorting-algorithms-comb-sort.objeck @@ -0,0 +1,33 @@ +bundle Default { + class Stooge { + function : Main(args : String[]) ~ Nil { + nums := [3, 5, 1, 9, 7, 6, 8, 2, 4]; + CombSort(nums); + each(i : nums) { + IO.Console->Print(nums[i])->Print(","); + }; + IO.Console->PrintLine(); + } + + function : CombSort(input : Int[]) ~ Nil { + gap : Float := input->Size(); + swaps := true; + while(gap > 1 | swaps) { + gap /= 1.247330950103979; + if(gap < 1) { gap := 1; }; + i : Int := 0; + swaps := false; + while(i + gap < input->Size()) { + igap : Int := i + gap->As(Int); + if (input[i] > input[igap]) { + swap : Int := input[i]; + input[i] := input[igap]; + input[igap] := swap; + swaps := true; + }; + i += 1; + }; + }; + } + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/Oz/sorting-algorithms-comb-sort.oz b/Task/Sorting-algorithms-Comb-sort/Oz/sorting-algorithms-comb-sort.oz new file mode 100644 index 0000000000..f06dec272f --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Oz/sorting-algorithms-comb-sort.oz @@ -0,0 +1,28 @@ +declare + proc {CombSort Arr} + Low = {Array.low Arr} + High = {Array.high Arr} + Size = High - Low + 1 + Gap = {NewCell Size} + Swapped = {NewCell true} + proc {Swap I J} + Arr.J := (Arr.I := Arr.J) + end + in + for while:@Gap>1 orelse @Swapped do + if @Gap > 1 then + Gap := {Float.toInt {Floor {Int.toFloat @Gap} / 1.3}} + end + Swapped := false + for I in Low..High-@Gap do + if Arr.I > Arr.(I+@Gap) then + {Swap I I+@Gap} + Swapped := true + end + end + end + end + Arr = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} +in + {CombSort Arr} + {Show {Array.toRecord unit Arr}} diff --git a/Task/Sorting-algorithms-Comb-sort/PARI-GP/sorting-algorithms-comb-sort.pari b/Task/Sorting-algorithms-Comb-sort/PARI-GP/sorting-algorithms-comb-sort.pari new file mode 100644 index 0000000000..639fc3c82f --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PARI-GP/sorting-algorithms-comb-sort.pari @@ -0,0 +1,16 @@ +combSort(v)={ + my(phi=(1+sqrt(5))/2,magic=1/(1-exp(-phi)),g=#v,swaps); + while(g>1 | swaps, + if(g>1, g\=magic); + swaps=0; + for(i=1,#v-g, + if(v[i]>v[i+g], + my(t=v[i]); + v[i]=v[i+g]; + v[i+g]=t; + swaps++ + ) + ) + ); + v +}; diff --git a/Task/Sorting-algorithms-Comb-sort/PHP/sorting-algorithms-comb-sort.php b/Task/Sorting-algorithms-Comb-sort/PHP/sorting-algorithms-comb-sort.php new file mode 100644 index 0000000000..4073c624a5 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PHP/sorting-algorithms-comb-sort.php @@ -0,0 +1,18 @@ +function combSort($arr){ + $gap = count($arr); + $swap = true; + while ($gap > 1 || $swap){ + if($gap > 1) $gap /= 1.25; + + $swap = false; + $i = 0; + while($i+$gap < count($arr)){ + if($arr[$i] > $arr[$i+$gap]){ + list($arr[$i], $arr[$i+$gap]) = array($arr[$i+$gap],$arr[$i]); + $swap = true; + } + $i++; + } + } + return $arr; +} diff --git a/Task/Sorting-algorithms-Comb-sort/PL-I/sorting-algorithms-comb-sort.pli b/Task/Sorting-algorithms-Comb-sort/PL-I/sorting-algorithms-comb-sort.pli new file mode 100644 index 0000000000..b47dedb547 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PL-I/sorting-algorithms-comb-sort.pli @@ -0,0 +1,25 @@ +/* From the pseudocode. */ +comb_sort: procedure (A); + declare A(*) fixed; + declare t fixed; + declare (i, gap) fixed binary (31); + declare swaps bit (1) aligned; + + gap = hbound(A,1) - lbound(A,1); /* initialize the gap size. */ + do until (gap <= 1 & swaps); + /* update the gap value for a next comb. */ + put skip data (gap); + gap = gap / 1.25e0; + put skip data (gap); + swaps = '1'b; + /* a single "comb" over the array. */ + do i = lbound(A,1) by 1 until (i + gap >= hbound(A,1)); + if A(i) > A(i+gap) then + do; + t = A(i); A(i) = A(i+gap); A(i+gap) = t; + swaps = '0'b; /* Flag a swap has occurred, so */ + /* the list is not guaranteed sorted. */ + end; + end; + end; +end comb_sort; diff --git a/Task/Sorting-algorithms-Comb-sort/Pascal/sorting-algorithms-comb-sort.pascal b/Task/Sorting-algorithms-Comb-sort/Pascal/sorting-algorithms-comb-sort.pascal new file mode 100644 index 0000000000..f917f87882 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Pascal/sorting-algorithms-comb-sort.pascal @@ -0,0 +1,50 @@ +program CombSortDemo; + +type + TIntArray = array[1..40] of integer; + +var + data: TIntArray; + i: integer; + +procedure combSort(var a: TIntArray); + var + i, gap, temp: integer; + swapped: boolean; + begin + gap := length(a); + swapped := true; + while (gap > 1) or swapped do + begin + gap := trunc(gap / 1.3); + if (gap < 1) then + gap := 1; + swapped := false; + for i := 1 to length(a) - gap do + if a[i] > a[i+gap] then + begin + temp := a[i]; + a[i] := a[i+gap]; + a[i+gap] := temp; + swapped := true; + end; + end; + end; + +begin + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + combSort(data); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Comb-sort/Perl-6/sorting-algorithms-comb-sort.pl6 b/Task/Sorting-algorithms-Comb-sort/Perl-6/sorting-algorithms-comb-sort.pl6 new file mode 100644 index 0000000000..709b6b8f5d --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Perl-6/sorting-algorithms-comb-sort.pl6 @@ -0,0 +1,20 @@ +sub comb_sort ( @a is copy ) { + my $gap = +@a; + my $swaps = 1; + while $gap > 1 or $swaps { + $gap = ( ($gap * 4) div 5 ) || 1 if $gap > 1; + + $swaps = 0; + for ^(+@a - $gap) -> $i { + my $j = $i + $gap; + if @a[$i] > @a[$j] { + @a[$i, $j] .= reverse; + $swaps = 1; + } + } + } + return @a; +} + +my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) }; +say @weights.sort.Str eq @weights.&comb_sort.Str ?? 'ok' !! 'not ok'; diff --git a/Task/Sorting-algorithms-Comb-sort/Perl/sorting-algorithms-comb-sort.pl b/Task/Sorting-algorithms-Comb-sort/Perl/sorting-algorithms-comb-sort.pl new file mode 100644 index 0000000000..b8bb973cfe --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Perl/sorting-algorithms-comb-sort.pl @@ -0,0 +1,16 @@ +sub combSort { + my @arr = @_; + my $gap = @arr; + my $swaps = 1; + while ($gap > 1 || $swaps) { + $gap /= 1.25 if $gap > 1; + $swaps = 0; + foreach my $i (0 .. $#arr - $gap) { + if ($arr[$i] > $arr[$i+$gap]) { + @arr[$i, $i+$gap] = @arr[$i+$gap, $i]; + $swaps = 1; + } + } + } + return @arr; +} diff --git a/Task/Sorting-algorithms-Comb-sort/PicoLisp/sorting-algorithms-comb-sort.l b/Task/Sorting-algorithms-Comb-sort/PicoLisp/sorting-algorithms-comb-sort.l new file mode 100644 index 0000000000..fc573292b7 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PicoLisp/sorting-algorithms-comb-sort.l @@ -0,0 +1,12 @@ +(de combSort (Lst) + (let (Gap (length Lst) Swaps NIL) + (while (or (> Gap 1) Swaps) + (setq Gap (max 1 (/ (* Gap 4) 5))) + (off Swaps) + (use Lst + (for (G (cdr (nth Lst Gap)) G (cdr G)) + (when (> (car Lst) (car G)) + (xchg Lst G) + (on Swaps) ) + (pop 'Lst) ) ) ) ) + Lst ) diff --git a/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.psh b/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.psh new file mode 100644 index 0000000000..11f8cd92b8 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.psh @@ -0,0 +1,31 @@ +function CombSort ($a) { + $l = $a.Length + $gap = 11 + while( $gap -lt $l ) + { + $gap = [Math]::Floor( $gap*1.3 ) + } + if( $l -gt 1 ) + { + $hasChanged = $true + :outer while ($hasChanged -or ( $gap -gt 1 ) ) { + $count = 0 + $hasChanged = $false + if( $gap -gt 1 ) { + $gap = [Math]::Floor( $gap/1.3 ) + } else { + $l-- + } + for ($i = 0; $i -lt ( $l - $gap ); $i++) { + if ($a[$i] -gt $a[$i+$gap]) { + $a[$i], $a[$i+$gap] = $a[$i+$gap], $a[$i] + $hasChanged = $true + $count++ + } + } + } + } + $a +} + +$l = 100; CombSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-1.purebasic b/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-1.purebasic new file mode 100644 index 0000000000..dcad2ee01b --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-1.purebasic @@ -0,0 +1,22 @@ +;sorts an array of integers +Procedure combSort11(Array a(1)) + Protected i, gap, swaps = 1 + Protected nElements = ArraySize(a()) + + gap = nElements + While (gap > 1) Or (swapped = 1) + gap * 10 / 13 + If gap = 9 Or gap = 10: gap = 11: EndIf + If gap < 1: gap = 1: EndIf + + i = 0 + swaps = 0 + While (i + gap) <= nElements + If a(i) > a(i + gap) + Swap a(i), a(i + gap) + swaps = 1 + EndIf + i + 1 + Wend + Wend +EndProcedure diff --git a/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-2.purebasic b/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-2.purebasic new file mode 100644 index 0000000000..c0c666e280 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PureBasic/sorting-algorithms-comb-sort-2.purebasic @@ -0,0 +1,20 @@ +;sorts an array of integers +Procedure combSort(Array a(1)) + Protected i, gap, swaps = 1 + Protected nElements = ArraySize(a()) + + gap = nElements + While (gap > 1) Or (swaps = 1) + gap = Int(gap / 1.25) + + i = 0 + swaps = 0 + While (i + gap) <= nElements + If a(i) > a(i + gap) + Swap a(i), a(i + gap) + swaps = 1 + EndIf + i + 1 + Wend + Wend +EndProcedure diff --git a/Task/Sorting-algorithms-Comb-sort/Python/sorting-algorithms-comb-sort.py b/Task/Sorting-algorithms-Comb-sort/Python/sorting-algorithms-comb-sort.py new file mode 100644 index 0000000000..57936796a4 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Python/sorting-algorithms-comb-sort.py @@ -0,0 +1,19 @@ +>>> def combsort(input): + gap = len(input) + swaps = True + while gap > 1 or swaps: + gap = max(1, int(gap / 1.25)) # minimum gap is 1 + swaps = False + for i in range(len(input) - gap): + j = i+gap + if input[i] > input[j]: + input[i], input[j] = input[j], input[i] + swaps = True + + +>>> y = [88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70] +>>> combsort(y) +>>> assert y == sorted(y) +>>> y +[0, 4, 5, 8, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88] +>>> diff --git a/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx new file mode 100644 index 0000000000..58ec22c33b --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx @@ -0,0 +1,44 @@ +/*REXX program sorts an array using the comb-sort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call combSort highItem /*invoke the comb sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────COMBSORT subroutine─────────────────*/ +combSort: procedure expose @.; parse arg n +s=n-1 /*S = spread between COMBs. */ + + do until s<=1 & done + s=trunc(s*.8) /* ÷ is slow, * is better. */ + done=1 + do j=1 until j+s>=n + jps=j+s + if @.j>@.jps then do; _=@.j; @.j=@.jps; @.jps=_; done=0; end + end /*j*/ + end /*until*/ + +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign the default value. */ +@.1 ='--- polygon sides' +@.2 ='============== =====' +@.3 ='triangle 3' +@.4 ='quadrilateral 4' +@.5 ='pentagon 5' +@.6 ='hexagon 6' +@.7 ='heptagon 7' +@.8 ='octagon 8' +@.9 ='nonagon 9' +@.10='decagon 10' +@.11='dodecagon 12' + do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ + end +highItem=highItem-1 /*adjust highItem slightly. */ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(highItem) /*the maximum width of any line. */ + do j=1 for highItem + say 'element' right(j,widthH) arg(1)":" @.j + end +say copies('─',79) /*show a nice separator line. */ +return diff --git a/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb b/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb new file mode 100644 index 0000000000..199f52faac --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Ruby/sorting-algorithms-comb-sort.rb @@ -0,0 +1,19 @@ +class Array + def combsort! + gap = size + swaps = true + until gap <= 1 and swaps + gap = (gap / 1.25).to_int + swaps = false + 0.upto(size - gap - 1) do |i| + if self[i] > self[i+gap] + self[i], self[i+gap] = self[i+gap], self[i] + swaps = true + end + end + end + self + end +end + +p [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78].combsort! diff --git a/Task/Sorting-algorithms-Comb-sort/Sather/sorting-algorithms-comb-sort.sa b/Task/Sorting-algorithms-Comb-sort/Sather/sorting-algorithms-comb-sort.sa new file mode 100644 index 0000000000..e96496cd39 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Sather/sorting-algorithms-comb-sort.sa @@ -0,0 +1,37 @@ +class SORT{T < $IS_LT{T}} is + + private swap(inout a, inout b:T) is + temp ::= a; + a := b; + b := temp; + end; + +-- --------------------------------------------------------------------------------- + comb_sort(inout a:ARRAY{T}) is + gap ::= a.size; + swapped ::= true; + loop until!(gap <= 1 and ~swapped); + if gap > 1 then + gap := (gap.flt / 1.25).int; + end; + i ::= 0; + swapped := false; + loop until! ( (i + gap) >= a.size ); + if (a[i] > a[i+gap]) then + swap(inout a[i], inout a[i+gap]); + swapped := true; + end; + i := i + 1; + end; + end; + end; +end; + +class MAIN is + main is + a:ARRAY{INT} := |88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70|; + b ::= a.copy; + SORT{INT}::comb_sort(inout b); + #OUT + b + "\n"; + end; +end; diff --git a/Task/Sorting-algorithms-Comb-sort/Tcl/sorting-algorithms-comb-sort.tcl b/Task/Sorting-algorithms-Comb-sort/Tcl/sorting-algorithms-comb-sort.tcl new file mode 100644 index 0000000000..9a6e1be99d --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Tcl/sorting-algorithms-comb-sort.tcl @@ -0,0 +1,21 @@ +proc combsort {input} { + set gap [llength $input] + while 1 { + set gap [expr {int(floor($gap / 1.3))}] + set swaps 0 + for {set i 0} {$i+$gap < [llength $input]} {incr i} { + set j [expr {$i+$gap}] + if {[lindex $input $i] > [lindex $input $j]} { + set tmp [lindex $input $i] + lset input $i [lindex $input $j] + lset input $j $tmp + incr swaps + } + } + if {$gap <= 1 && !$swaps} break + } + return $input +} + +set data {23 76 99 58 97 57 35 89 51 38 95 92 24 46 31 24 14 12 57 78} +puts [combsort $data] diff --git a/Task/Sorting-algorithms-Counting-sort/0DESCRIPTION b/Task/Sorting-algorithms-Counting-sort/0DESCRIPTION new file mode 100644 index 0000000000..d02836b588 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/0DESCRIPTION @@ -0,0 +1,23 @@ +{{Sorting Algorithm}} +{{Wikipedia|Counting sort}} +Implement the [[wp:Counting sort|Counting sort]]. This is a way of sorting integers when the minimum and maximum value are known. + +Pseudocode: + '''function''' ''countingSort''(array, min, max): + count: '''array of''' (max - min + 1) '''elements''' + '''initialize''' count '''with''' 0 + '''for each''' number '''in''' array '''do''' + count[number - min] := count[number - min] + 1 + '''done''' + z := 0 + '''for''' i '''from''' min '''to''' max '''do''' + '''while''' ( count[i - min] > 0 ) '''do''' + array[z] := i + z := z+1 + count[i - min] := count[i - min] - 1 + '''done''' + '''done''' + +The ''min'' and ''max'' can be computed apart, or be known ''a priori''. + +'''Note''': we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array of 32 bit integers, we see that in order to hold the counts, we need an array of 2<sup>32</sup> elements, i.e., we need, to hold a count value up to 2<sup>32</sup>-1, more or less 4 Gbytes. So the counting sort is more practical when the range is (very) limited and minimum and maximum values are known ''a priori''. (Anyway sparse arrays may limit the impact of the memory usage) diff --git a/Task/Sorting-algorithms-Counting-sort/1META.yaml b/Task/Sorting-algorithms-Counting-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Counting-sort/ALGOL-68/sorting-algorithms-counting-sort.alg b/Task/Sorting-algorithms-Counting-sort/ALGOL-68/sorting-algorithms-counting-sort.alg new file mode 100644 index 0000000000..ac6c271a58 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/ALGOL-68/sorting-algorithms-counting-sort.alg @@ -0,0 +1,40 @@ +PROC counting sort mm = (REF[]INT array, INT min, max)VOID: +( + INT z := LWB array - 1; + [min:max]INT count; + + FOR i FROM LWB count TO UPB count DO count[i] := 0 OD; + FOR i TO UPB array DO count[ array[i] ]+:=1 OD; + + FOR i FROM LWB count TO UPB count DO + FOR j TO count[i] DO array[z+:=1] := i OD + OD +); + +PROC counting sort = (REF[]INT array)VOID: +( + INT min, max; + min := max := array[LWB array]; + + FOR i FROM LWB array + 1 TO UPB array DO + IF array[i] < min THEN + min := array[i] + ELIF array[i] > max THEN + max := array[i] + FI + OD +); + +# Testing (we suppose the oldest human being is less than 140 years old). # + +INT n = 100; +INT min age = 0, max age = 140; +main: +( + [n]INT ages; + + FOR i TO UPB ages DO ages[i] := ENTIER (random * ( max age + 1 ) ) OD; + counting sort mm(ages, min age, max age); + FOR i TO UPB ages DO print((" ", whole(ages[i],0))) OD; + print(new line) +) diff --git a/Task/Sorting-algorithms-Counting-sort/ActionScript/sorting-algorithms-counting-sort.as b/Task/Sorting-algorithms-Counting-sort/ActionScript/sorting-algorithms-counting-sort.as new file mode 100644 index 0000000000..dab45aa8a0 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/ActionScript/sorting-algorithms-counting-sort.as @@ -0,0 +1,16 @@ +function countingSort(array:Array, min:int, max:int) +{ + var count:Array = new Array(array.length); + for(var i:int = 0; i < count.length;i++)count[i]=0; + for(i = 0; i < array.length; i++) + { + count[array[i]-min] ++; + } + var j:uint = 0; + for(i = min; i <= max; i++) + { + for(; count[i-min] > 0; count[i-min]--) + array[j++] = i; + } + return array; +} diff --git a/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada new file mode 100644 index 0000000000..a9eae3558e --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada @@ -0,0 +1,18 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Counting_Sort is + type Data is array (Integer range <>) of Natural; + procedure Sort(Item : out Data) is + begin + for I in Item'range loop + Item(I) := I; + end loop; + end Sort; + Stuff : Data(1..140); +begin + Sort(Stuff); + for I in Stuff'range loop + Put(Natural'Image(Stuff(I))); + end loop; + New_Line; +end Counting_Sort; diff --git a/Task/Sorting-algorithms-Counting-sort/AutoHotkey/sorting-algorithms-counting-sort.ahk b/Task/Sorting-algorithms-Counting-sort/AutoHotkey/sorting-algorithms-counting-sort.ahk new file mode 100644 index 0000000000..fd2ba00277 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/AutoHotkey/sorting-algorithms-counting-sort.ahk @@ -0,0 +1,14 @@ +MsgBox % CountingSort("-1,1,1,0,-1",-1,1) + +CountingSort(ints,min,max) { + Loop % max-min+1 + i := A_Index-1, a%i% := 0 + Loop Parse, ints, `, %A_Space%%A_Tab% + i := A_LoopField-min, a%i%++ + Loop % max-min+1 { + i := A_Index-1, v := i+min + Loop % a%i% + t .= "," v + } + Return SubStr(t,2) +} diff --git a/Task/Sorting-algorithms-Counting-sort/BBC-BASIC/sorting-algorithms-counting-sort.bbc b/Task/Sorting-algorithms-Counting-sort/BBC-BASIC/sorting-algorithms-counting-sort.bbc new file mode 100644 index 0000000000..3bbedf4650 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/BBC-BASIC/sorting-algorithms-counting-sort.bbc @@ -0,0 +1,23 @@ + DIM test%(9) + test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCcountingsort(test%(), -31, 782) + FOR i% = 0 TO 9 + PRINT test%(i%) ; + NEXT + PRINT + END + + DEF PROCcountingsort(a%(), l%, h%) + LOCAL i%, z%, c%() + DIM c%(h% - l%) + FOR i% = 0 TO DIM(a%(),1) + c%(a%(i%) - l%) += 1 + NEXT + FOR i% = l% TO h% + WHILE c%(i% - l%) + a%(z%) = i% + z% += 1 + c%(i% - l%) -= 1 + ENDWHILE + NEXT + ENDPROC diff --git a/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-1.c b/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-1.c new file mode 100644 index 0000000000..b81c0c1313 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-1.c @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <stdlib.h> + +void counting_sort_mm(int *array, int n, int min, int max) +{ + int i, j, z; + + int range = max - min + 1; + int *count = malloc(range * sizeof(*array)); + + for(i = 0; i < range; i++) count[i] = 0; + for(i = 0; i < n; i++) count[ array[i] - min ]++; + + for(i = min, z = 0; i <= max; i++) { + for(j = 0; j < count[i - min]; j++) { + array[z++] = i; + } + } + + free(count); +} + +void counting_sort(int *array, int n) +{ + int i, min, max; + + min = max = array[0]; + for(i=1; i < n; i++) { + if ( array[i] < min ) { + min = array[i]; + } else if ( array[i] > max ) { + max = array[i]; + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-2.c b/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-2.c new file mode 100644 index 0000000000..02285b2dab --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/C/sorting-algorithms-counting-sort-2.c @@ -0,0 +1,11 @@ +#define N 100 +#define MAX_AGE 140 +int main() +{ + int ages[N], i; + + for(i=0; i < N; i++) ages[i] = rand()%MAX_AGE; + counting_sort_mm(ages, N, 0, MAX_AGE); + for(i=0; i < N; i++) printf("%d\n", ages[i]); + return EXIT_SUCCESS; +} diff --git a/Task/Sorting-algorithms-Counting-sort/Common-Lisp/sorting-algorithms-counting-sort.lisp b/Task/Sorting-algorithms-Counting-sort/Common-Lisp/sorting-algorithms-counting-sort.lisp new file mode 100644 index 0000000000..73ea160700 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Common-Lisp/sorting-algorithms-counting-sort.lisp @@ -0,0 +1,12 @@ +(defun counting-sort (sequence &optional (min (reduce #'min sequence)) + (max (reduce #'max sequence))) + (let ((i 0) + (counts (make-array (1+ (- max min)) :initial-element 0 + :element-type `(integer 0 ,(length sequence))))) + (declare (dynamic-extent counts)) + (map nil (lambda (n) (incf (aref counts (- n min)))) sequence) + (map-into sequence (lambda () + (do () ((plusp (aref counts i))) + (incf i)) + (decf (aref counts i)) + (+ i min))))) diff --git a/Task/Sorting-algorithms-Counting-sort/D/sorting-algorithms-counting-sort.d b/Task/Sorting-algorithms-Counting-sort/D/sorting-algorithms-counting-sort.d new file mode 100644 index 0000000000..b44c95cfdb --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/D/sorting-algorithms-counting-sort.d @@ -0,0 +1,27 @@ +import std.stdio, std.algorithm; + +void countingSort(int[] array, in size_t min, in size_t max) +pure nothrow { + auto count = new int[max - min + 1]; + foreach (number; array) + count[number - min]++; + + size_t z = 0; + foreach (i; min .. max + 1) + while (count[i - min] > 0) { + array[z] = i; + z++; + count[i - min]--; + } +} + +void main() { + auto data = [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10, 2, 1, 3, 8, + 7, 3, 9, 5, 8, 5, 1, 6, 3, 7, 5, 4, 6, 9, 9, 6, 6, + 10, 2, 4, 5, 2, 8, 2, 2, 5, 2, 9, 3, 3, 5, 7, 8, 4]; + + int dataMin = reduce!min(data); + int dataMax = reduce!max(data); + countingSort(data, dataMin, dataMax); + assert(isSorted(data)); +} diff --git a/Task/Sorting-algorithms-Counting-sort/E/sorting-algorithms-counting-sort.e b/Task/Sorting-algorithms-Counting-sort/E/sorting-algorithms-counting-sort.e new file mode 100644 index 0000000000..d287cb9753 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/E/sorting-algorithms-counting-sort.e @@ -0,0 +1,13 @@ +def countingSort(array, min, max) { + def counts := ([0] * (max - min + 1)).diverge() + for elem in array { + counts[elem - min] += 1 + } + var i := -1 + for offset => count in counts { + def elem := min + offset + for _ in 1..count { + array[i += 1] := elem + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-1.f b/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-1.f new file mode 100644 index 0000000000..fe50a4e5e0 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-1.f @@ -0,0 +1,39 @@ +module CountingSort + implicit none + + interface counting_sort + module procedure counting_sort_mm, counting_sort_a + end interface + +contains + + subroutine counting_sort_a(array) + integer, dimension(:), intent(inout) :: array + + call counting_sort_mm(array, minval(array), maxval(array)) + + end subroutine counting_sort_a + + subroutine counting_sort_mm(array, tmin, tmax) + integer, dimension(:), intent(inout) :: array + integer, intent(in) :: tmin, tmax + + integer, dimension(tmin:tmax) :: cnt + integer :: i, z + + forall(i=tmin:tmax) + cnt(i) = count(array == i) + end forall + + z = 1 + do i = tmin, tmax + do while ( cnt(i) > 0 ) + array(z) = i + z = z + 1 + cnt(i) = cnt(i) - 1 + end do + end do + + end subroutine counting_sort_mm + +end module CountingSort diff --git a/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-2.f b/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-2.f new file mode 100644 index 0000000000..00a8dee5ad --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Fortran/sorting-algorithms-counting-sort-2.f @@ -0,0 +1,17 @@ +program test + use CountingSort + implicit none + + integer, parameter :: n = 100, max_age = 140 + + real, dimension(n) :: t + integer, dimension(n) :: ages + + call random_number(t) + ages = floor(t * max_age) + + call counting_sort(ages, 0, max_age) + + write(*,'(I4)') ages + +end program test diff --git a/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-1.go b/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-1.go new file mode 100644 index 0000000000..418987a9e0 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-1.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "runtime" + "strings" +) + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} +var aMin, aMax = -1000, 1000 + +func main() { + fmt.Println("before:", a) + countingSort(a, aMin, aMax) + fmt.Println("after: ", a) +} + +func countingSort(a []int, aMin, aMax int) { + defer func() { + if x := recover(); x != nil { + // one error we'll handle and print a little nicer message + if _, ok := x.(runtime.Error); ok && + strings.HasSuffix(x.(error).Error(), "index out of range") { + fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax) + return + } + // anything else, we re-panic + panic(x) + } + }() + + count := make([]int, aMax-aMin+1) + for _, x := range a { + count[x-aMin]++ + } + z := 0 + // optimization over task pseudocode: variable c is used instead of + // count[i-min]. This saves some unneccessary calculations. + for i, c := range count { + for ; c > 0; c-- { + a[z] = i + aMin + z++ + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-2.go b/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-2.go new file mode 100644 index 0000000000..2da371e9ce --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Go/sorting-algorithms-counting-sort-2.go @@ -0,0 +1,50 @@ +package main + +import ( + "fmt" + "runtime" + "strings" +) + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} +var aMin, aMax = -1000, 1000 + +func main() { + fmt.Println("before:", a) + countingSort(a, aMin, aMax) + fmt.Println("after: ", a) +} + +func countingSort(a []int, aMin, aMax int) { + defer func() { + if x := recover(); x != nil { + // one error we'll handle and print a little nicer message + if _, ok := x.(runtime.Error); ok && + strings.HasSuffix(x.(error).Error(), "index out of range") { + fmt.Printf("data value out of range (%d..%d)\n", aMin, aMax) + return + } + // anything else, we re-panic + panic(x) + } + }() + + // WP algorithm + k := aMax - aMin // k is maximum key value. keys range 0..k + count := make([]int, k+1) + key := func(v int) int { return v - aMin } + for _, x := range a { + count[key(x)]++ + } + total := 0 + for i, c := range count { + count[i] = total + total += c + } + output := make([]int, len(a)) + for _, x := range a { + output[count[key(x)]] = x + count[key(x)]++ + } + copy(a, output) +} diff --git a/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-1.groovy b/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-1.groovy new file mode 100644 index 0000000000..9d3a2b76f9 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-1.groovy @@ -0,0 +1,8 @@ +def countingSort = { array -> + def max = array.max() + def min = array.min() + // this list size allows use of Groovy's natural negative indexing + def count = [0] * (max + 1 + [0, -min].max()) + array.each { count[it] ++ } + (min..max).findAll{ count[it] }.collect{ [it]*count[it] }.flatten() +} diff --git a/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-2.groovy b/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-2.groovy new file mode 100644 index 0000000000..c21221478f --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Groovy/sorting-algorithms-counting-sort-2.groovy @@ -0,0 +1,7 @@ +println countingSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]) +println countingSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]) + +println countingSort([15,-3,0,-1,5,4,5,20,-8]) +println countingSort([34,6,8,7,4,3,56,7,8,4,3,5,7,8,6,4,4,67,9,0,0,76,467,453,34,435,37,4,34,234,435,3,2,7,4,634,534,-735,5,4,6,78,4]) +// slo-o-o-o-ow due to unnecessarily large counting array +println countingSort([10000033,10000006,10000008,10000009,10000013,10000031,10000013,10000032,10000023,10000023,10000011,10000012,10000021]) diff --git a/Task/Sorting-algorithms-Counting-sort/Haskell/sorting-algorithms-counting-sort.hs b/Task/Sorting-algorithms-Counting-sort/Haskell/sorting-algorithms-counting-sort.hs new file mode 100644 index 0000000000..b1922b69ac --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Haskell/sorting-algorithms-counting-sort.hs @@ -0,0 +1,5 @@ +import Data.Array + +countingSort :: (Ix n) => [n] -> n -> n -> [n] +countingSort l lo hi = concatMap (uncurry $ flip replicate) count + where count = assocs . accumArray (+) 0 (lo, hi) . map (\i -> (i, 1)) $ l diff --git a/Task/Sorting-algorithms-Counting-sort/Icon/sorting-algorithms-counting-sort.icon b/Task/Sorting-algorithms-Counting-sort/Icon/sorting-algorithms-counting-sort.icon new file mode 100644 index 0000000000..57aea150c6 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Icon/sorting-algorithms-counting-sort.icon @@ -0,0 +1,23 @@ +procedure main() #: demonstrate various ways to sort a list and string + write("Sorting Demo using ",image(countingsort)) + writes(" on list : ") + writex(UL) + displaysort(countingsort,copy(UL)) +end + +procedure countingsort(X) #: return sorted list (integers only) +local T,lower,upper + + T := table(0) # hash table as sparse array + lower := upper := X[1] + + every x := !X do { + if not ( integer(x) = x ) then runerr(x,101) # must be integer + lower >:= x # minimum + upper <:= x # maximum + T[x] +:= 1 # record x's and duplicates + } + + every put(X := [],( 1 to T[i := lower to upper], i) ) # reconstitute with correct order and count + return X +end diff --git a/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-1.io b/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-1.io new file mode 100644 index 0000000000..d910f7af6e --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-1.io @@ -0,0 +1,24 @@ +List do( + countingSort := method(min, max, + count := list() setSize(max - min + 1) mapInPlace(0) + foreach(x, + count atPut(x - min, count at(x - min) + 1) + ) + + j := 0 + for(i, min, max, + while(count at(i - min) > 0, + atPut(j, i) + count atPut(i - min, at(i - min) - 1) + j = j + 1 + ) + ) + self) + + countingSortInPlace := method( + countingSort(min, max) + ) +) + +l := list(2, 3, -4, 5, 1) +l countingSortInPlace println # ==> list(-4, 1, 2, 3, 5) diff --git a/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-2.io b/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-2.io new file mode 100644 index 0000000000..0981e7ec74 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Io/sorting-algorithms-counting-sort-2.io @@ -0,0 +1,23 @@ +List do( + fill := method(x, size, + /* Resizes list to a given size and fills it with a given value. */ + setSize(size) mapInPlace(x) + ) + + countingSort := method(min, max, + count := list() fill(0, max - min + 1) + foreach(x, + count atPut(x - min, count at(x - min) + 1) + ) + + return count map(i, x, list() fill(i + min, x)) \ + prepend(list()) reduce(xs, x, xs appendSeq(x)) + ) + + countingSortInPlace := method( + copy(countingSort(min, max)) + ) +) + +l := list(2, 3, -4, 5, 1) +l countingSortInPlace println # ==> list(-4, 1, 2, 3, 5) diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-1.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-1.j new file mode 100644 index 0000000000..bb78752dd6 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-1.j @@ -0,0 +1,8 @@ +csort =: monad define + min =. <./y + cnt =. 0 $~ 1+(>./y)-min + for_a. y do. + cnt =. cnt >:@{`[`]}~ a-min + end. + cnt # min+i.#cnt +) diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-2.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-2.j new file mode 100644 index 0000000000..34187770ec --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-2.j @@ -0,0 +1 @@ +csort=: (+/@(=/) # ]) >./ (] + 1 i.@+ -) <./ diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-3.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-3.j new file mode 100644 index 0000000000..bc43ed59f7 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-3.j @@ -0,0 +1,5 @@ + ] a =. _3 + 20 ?@$ 10 +_2 _2 6 _1 1 6 _1 4 4 1 4 4 5 _3 5 3 0 _1 3 4 + + csort a +_3 _2 _2 _1 _1 _1 0 1 1 3 3 4 4 4 4 4 5 5 6 6 diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-4.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-4.j new file mode 100644 index 0000000000..3708c36187 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-4.j @@ -0,0 +1,3 @@ +csrt=:2 :0 + (m+i.n-m) (+/@(=/)~ # [) ] +) diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-5.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-5.j new file mode 100644 index 0000000000..dd7bf5cd5b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-5.j @@ -0,0 +1,3 @@ +csrt=:2 :0 + (+/@(=/) # ])&(m+i.n-m) +) diff --git a/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-6.j b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-6.j new file mode 100644 index 0000000000..749a41ac54 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/J/sorting-algorithms-counting-sort-6.j @@ -0,0 +1,2 @@ + (_3 csrt 17) a +_3 _2 _2 _1 _1 _1 0 1 1 3 3 4 4 4 4 4 5 5 6 6 diff --git a/Task/Sorting-algorithms-Counting-sort/Java/sorting-algorithms-counting-sort.java b/Task/Sorting-algorithms-Counting-sort/Java/sorting-algorithms-counting-sort.java new file mode 100644 index 0000000000..6ceb0c186d --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Java/sorting-algorithms-counting-sort.java @@ -0,0 +1,14 @@ +public static void countingSort(int[] array, int min, int max){ + int[] count= new int[max - min + 1]; + for(int number : array){ + count[number - min]++; + } + int z= 0; + for(int i= min;i <= max;i++){ + while(count[i - min] > 0){ + array[z]= i; + z++; + count[i - min]--; + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-1.js b/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-1.js new file mode 100644 index 0000000000..67c93cf984 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-1.js @@ -0,0 +1,18 @@ +var countSort = function(arr, min, max) { + var i, z = 0, count = []; + + for (i = min; i <= max; i++) { + count[i] = 0; + } + + for (i=0; i < arr.length; i++) { + count[arr[i]]++; + } + + for (i = min; i <= max; i++) { + while (count[i]-- > 0) { + arr[z++] = i; + } + } + +} diff --git a/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-2.js b/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-2.js new file mode 100644 index 0000000000..815589db81 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/JavaScript/sorting-algorithms-counting-sort-2.js @@ -0,0 +1,13 @@ +// Line breaks are in HTML + +var i, ages = []; + +for (i = 0; i < 100; i++) { + ages.push(Math.floor(Math.random() * (141))); +} + +countSort(ages, 0, 140); + +for (i = 0; i < 100; i++) { + document.write(ages[i] + "<br />"); +} diff --git a/Task/Sorting-algorithms-Counting-sort/Lua/sorting-algorithms-counting-sort.lua b/Task/Sorting-algorithms-Counting-sort/Lua/sorting-algorithms-counting-sort.lua new file mode 100644 index 0000000000..cf77cbcd8c --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Lua/sorting-algorithms-counting-sort.lua @@ -0,0 +1,30 @@ +function CountingSort( f ) + local min, max = math.min( unpack(f) ), math.max( unpack(f) ) + local count = {} + for i = min, max do + count[i] = 0 + end + + for i = 1, #f do + count[ f[i] ] = count[ f[i] ] + 1 + end + + local z = 1 + for i = min, max do + while count[i] > 0 do + f[z] = i + z = z + 1 + count[i] = count[i] - 1 + end + end + +end + + +f = { 15, -3, 0, -1, 5, 4, 5, 20, -8 } + +CountingSort( f ) + +for i in next, f do + print( f[i] ) +end diff --git a/Task/Sorting-algorithms-Counting-sort/M4/sorting-algorithms-counting-sort.m4 b/Task/Sorting-algorithms-Counting-sort/M4/sorting-algorithms-counting-sort.m4 new file mode 100644 index 0000000000..d25b96b6fd --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/M4/sorting-algorithms-counting-sort.m4 @@ -0,0 +1,36 @@ +divert(-1) + +define(`randSeed',141592653) +define(`setRand', + `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') +define(`rand_t',`eval(randSeed^(randSeed>>13))') +define(`random', + `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') + +define(`set',`define(`$1[$2]',`$3')') +define(`get',`defn(`$1[$2]')') +define(`new',`set($1,size,0)') +define(`append', + `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)') +define(`deck', + `new($1)for(`x',1,$2, + `append(`$1',eval(random%$3))')') +define(`for', + `ifelse($#,0,``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') +define(`show', + `for(`x',1,get($1,size),`get($1,x) ')') + +define(`countingsort', + `for(`x',$2,$3,`set(count,x,0)')`'for(`x',1,get($1,size), + `set(count,get($1,x),incr(get(count,get($1,x))))')`'define(`z', + 1)`'for(`x',$2,$3, + `for(`y',1,get(count,x), + `set($1,z,x)`'define(`z',incr(z))')')') + +divert +deck(`a',10,100) +show(`a') +countingsort(`a',0,99) +show(`a') diff --git a/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-1.m b/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-1.m new file mode 100644 index 0000000000..757e3730ca --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-1.m @@ -0,0 +1,22 @@ +function list = countingSort(list) + + minElem = min(list); + maxElem = max(list); + + count = zeros((maxElem-minElem+1),1); + + for number = list + count(number - minElem + 1) = count(number - minElem + 1) + 1; + end + + z = 1; + + for i = (minElem:maxElem) + while( count(i-minElem +1) > 0) + list(z) = i; + z = z+1; + count(i - minElem + 1) = count(i - minElem + 1) - 1; + end + end + +end %countingSort diff --git a/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-2.m b/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-2.m new file mode 100644 index 0000000000..7bbded16c7 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/MATLAB/sorting-algorithms-counting-sort-2.m @@ -0,0 +1,5 @@ +>> countingSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Counting-sort/Mathematica/sorting-algorithms-counting-sort.math b/Task/Sorting-algorithms-Counting-sort/Mathematica/sorting-algorithms-counting-sort.math new file mode 100644 index 0000000000..dda17e7b09 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Mathematica/sorting-algorithms-counting-sort.math @@ -0,0 +1,12 @@ +countingSort[list_] := Module[{minElem, maxElem, count, z, number}, + minElem = Min[list]; maxElem = Max[list]; + count = ConstantArray[0, (maxElem - minElem + 1)]; + For[number = 1, number < Length[list], number++, + count[[number - minElem + 1]] = count[[number - minElem + 1]] + 1;] ; + z = 1; + For[i = minElem, i < maxElem, i++, + While[count[[i - minElem + 1]] > 0, + list[[z]] = i; z++; + count[[i - minElem + 1]] = count[[i - minElem + 1]] - 1;] + ]; + ] diff --git a/Task/Sorting-algorithms-Counting-sort/Modula-3/sorting-algorithms-counting-sort.mod3 b/Task/Sorting-algorithms-Counting-sort/Modula-3/sorting-algorithms-counting-sort.mod3 new file mode 100644 index 0000000000..0d754f5b9a --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Modula-3/sorting-algorithms-counting-sort.mod3 @@ -0,0 +1,41 @@ +MODULE Counting EXPORTS Main; + +IMPORT IO, Fmt; + +VAR test := ARRAY [1..8] OF INTEGER {80, 10, 40, 60, 50, 30, 20, 70}; + +PROCEDURE Sort(VAR a: ARRAY OF INTEGER; min, max: INTEGER) = + VAR range := max - min + 1; + count := NEW(REF ARRAY OF INTEGER, range); + z := 0; + BEGIN + FOR i := FIRST(count^) TO LAST(count^) DO + count[i] := 0; + END; + + FOR i := FIRST(a) TO LAST(a) DO + INC(count[a[i] - min]); + END; + + FOR i := min TO max DO + WHILE (count[i - min] > 0) DO + a[z] := i; + INC(z); + DEC(count[i - min]); + END; + END; + END Sort; + +BEGIN + IO.Put("Unsorted: "); + FOR i := FIRST(test) TO LAST(test) DO + IO.Put(Fmt.Int(test[i]) & " "); + END; + IO.Put("\n"); + Sort(test, 10, 80); + IO.Put("Sorted: "); + FOR i := FIRST(test) TO LAST(test) DO + IO.Put(Fmt.Int(test[i]) & " "); + END; + IO.Put("\n"); +END Counting. 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 new file mode 100644 index 0000000000..9765394601 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort.netrexx @@ -0,0 +1,69 @@ +/* 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-Counting-sort/OCaml/sorting-algorithms-counting-sort.ocaml b/Task/Sorting-algorithms-Counting-sort/OCaml/sorting-algorithms-counting-sort.ocaml new file mode 100644 index 0000000000..ce6427636e --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/OCaml/sorting-algorithms-counting-sort.ocaml @@ -0,0 +1,4 @@ +let counting_sort_array arr lo hi = + let count = Array.make (hi-lo+1) 0 in + Array.iter (fun i -> count.(i-lo) <- count.(i-lo) + 1) arr; + Array.concat (Array.to_list (Array.mapi (fun i x -> Array.make x (lo+i)) count)) diff --git a/Task/Sorting-algorithms-Counting-sort/Objeck/sorting-algorithms-counting-sort.objeck b/Task/Sorting-algorithms-Counting-sort/Objeck/sorting-algorithms-counting-sort.objeck new file mode 100644 index 0000000000..9cb497762b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Objeck/sorting-algorithms-counting-sort.objeck @@ -0,0 +1,30 @@ +bundle Default { + class Cocktail { + function : Main(args : String[]) ~ Nil { + values := [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10]; + CountingSort(values, 2, 10); + each(i : values) { + values[i]->PrintLine(); + }; + } + + function : CountingSort(array : Int[], min : Int, max : Int) ~ Nil { + count := Int->New[max - min + 1]; + each(i : array) { + number := array[i]; + v := count[number - min]; + count[number - min] := v + 1; + }; + + z := 0; + for(i := min; i <= max; i += 1;) { + while(count[i - min] > 0) { + array[z] := i; + z += 1; + v := count[i - min] + count[i - min] := v - 1; + }; + }; + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-1.octave b/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-1.octave new file mode 100644 index 0000000000..5e6208f437 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-1.octave @@ -0,0 +1,10 @@ +function r = counting_sort(arr, minval, maxval) + r = arr; + z = 1; + for i = minval:maxval + cnt = sum(arr == i); + while( cnt-- > 0 ) + r(z++) = i; + endwhile + endfor +endfunction diff --git a/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-2.octave b/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-2.octave new file mode 100644 index 0000000000..3e5456d118 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Octave/sorting-algorithms-counting-sort-2.octave @@ -0,0 +1,3 @@ +ages = unidrnd(140, 100, 1); +sorted = counting_sort(ages, 0, 140); +disp(sorted); diff --git a/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-1.oz b/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-1.oz new file mode 100644 index 0000000000..4b76a87464 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-1.oz @@ -0,0 +1,24 @@ +declare + proc {CountingSort Arr Min Max} + Count = {Array.new Min Max 0} + Z = {NewCell {Array.low Arr}} + in + %% fill frequency array + for J in {Array.low Arr}..{Array.high Arr} do + Number = Arr.J + in + Count.Number := Count.Number + 1 + end + %% recreate array from frequencies + for I in Min..Max do + for C in 1..Count.I do + Arr.(@Z) := I + Z := @Z + 1 + end + end + end + + A = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} +in + {CountingSort A 1 9} + {Show {Array.toRecord unit A}} diff --git a/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-2.oz b/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-2.oz new file mode 100644 index 0000000000..2ae319c1f0 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Oz/sorting-algorithms-counting-sort-2.oz @@ -0,0 +1,21 @@ +declare + fun {CountingSort Xs} + Count = {Dictionary.new} + in + for X in Xs do + Count.X := {CondSelect Count X 0} + 1 + end + {Concat {Map {Dictionary.entries Count} Repeat}} + end + + fun {Repeat Val#Count} + if Count == 0 then nil + else Val|{Repeat Val#Count-1} + end + end + + fun {Concat Xs} + {FoldR Xs Append nil} + end +in + {Show {CountingSort [3 1 4 1 5 9 2 6 5]}} diff --git a/Task/Sorting-algorithms-Counting-sort/PARI-GP/sorting-algorithms-counting-sort.pari b/Task/Sorting-algorithms-Counting-sort/PARI-GP/sorting-algorithms-counting-sort.pari new file mode 100644 index 0000000000..352a3be513 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PARI-GP/sorting-algorithms-counting-sort.pari @@ -0,0 +1,7 @@ +countingSort(v,mn,mx)={ + my(u=vector(#v),i=0); + for(n=mn,mx, + for(j=1,#v,if(v[j]==n,u[i++]=n)) + ); + u +}; diff --git a/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-1.php b/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-1.php new file mode 100644 index 0000000000..5fb5927e77 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-1.php @@ -0,0 +1,21 @@ +<?php + +function counting_sort($arr, $min, $max) +{ + $count = array(); + for($i = $min; $i <= $max; $i++) + { + $count[$i] = 0; + } + + foreach($arr as $number) + { + $count[$number]++; + } + $z = 0; + for($i = $min; $i <= $max; $i++) { + while( $count[$i]-- > 0 ) { + $arr[$z++] = $i; + } + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-2.php b/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-2.php new file mode 100644 index 0000000000..dfa813a763 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PHP/sorting-algorithms-counting-sort-2.php @@ -0,0 +1,10 @@ +$ages = array(); +for($i=0; $i < 100; $i++) { + array_push($ages, rand(0, 140)); +} +counting_sort(&$ages, 0, 140); + +for($i=0; $i < 100; $i++) { + echo $ages[$i] . "\n"; +} +?> diff --git a/Task/Sorting-algorithms-Counting-sort/PL-I/sorting-algorithms-counting-sort.pli b/Task/Sorting-algorithms-Counting-sort/PL-I/sorting-algorithms-counting-sort.pli new file mode 100644 index 0000000000..62599f003e --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PL-I/sorting-algorithms-counting-sort.pli @@ -0,0 +1,29 @@ +count_sort: procedure (A); + declare A(*) fixed; + declare (min, max) fixed; + declare i fixed binary; + + max, min = A(lbound(A,1)); + do i = 1 to hbound(A,1); + if max < A(i) then max = A(i); + if min > A(i) then min = A(i); + end; + + begin; + declare t(min:max) fixed; + declare (i, j, k) fixed binary (31); + t = 0; + do i = 1 to hbound(A,1); + j = A(i); + t(j) = t(j) + 1; + end; + k = lbound(A,1); + do i = min to max; + if t(i) ^= 0 then + do j = 1 to t(i); + A(k) = i; + k = k + 1; + end; + end; + end; +end count_sort; diff --git a/Task/Sorting-algorithms-Counting-sort/Pascal/sorting-algorithms-counting-sort.pascal b/Task/Sorting-algorithms-Counting-sort/Pascal/sorting-algorithms-counting-sort.pascal new file mode 100644 index 0000000000..ee480b93a7 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Pascal/sorting-algorithms-counting-sort.pascal @@ -0,0 +1,32 @@ +program CountingSort; + +procedure counting_sort(var arr : Array of Integer; n, min, max : Integer); +var + count : Array of Integer; + i, j, z : Integer; +begin + SetLength(count, max-min); + for i := 0 to (max-min) do + count[i] := 0; + for i := 0 to (n-1) do + count[ arr[i] - min ] := count[ arr[i] - min ] + 1; + z := 0; + for i := min to max do + for j := 0 to (count[i - min] - 1) do begin + arr[z] := i; + z := z + 1 + end +end; + +var + ages : Array[0..99] of Integer; + i : Integer; + +begin + { testing } + for i := 0 to 99 do + ages[i] := 139 - i; + counting_sort(ages, 100, 0, 140); + for i := 0 to 99 do + writeln(ages[i]); +end. diff --git a/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-1.pl6 b/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-1.pl6 new file mode 100644 index 0000000000..4bdc5c3e59 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-1.pl6 @@ -0,0 +1,5 @@ +sub counting-sort (@ints) { + my $off = @ints.min; + (my @counts)[$_ - $off]++ for @ints; + @counts.kv.map: { ($^k + $off) xx ($^v // 0) } +} diff --git a/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-2.pl6 b/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-2.pl6 new file mode 100644 index 0000000000..2d778b8fee --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort-2.pl6 @@ -0,0 +1,3 @@ +constant @age-range = 2 .. 102; +my @ages = @age-range.roll(50); +say @ages.&counting-sort ~~ @ages.sort ?? 'ok' !! 'not ok'; diff --git a/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-1.pl b/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-1.pl new file mode 100644 index 0000000000..1933f10365 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-1.pl @@ -0,0 +1,13 @@ +#! /usr/bin/perl +use strict; + +sub counting_sort +{ + my ($a, $min, $max) = @_; + + my @cnt = (0) x ($max - $min + 1); + $cnt[$_ - $min]++ foreach @$a; + + my $i = $min; + @$a = map {($i++) x $_} @cnt; +} diff --git a/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-2.pl b/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-2.pl new file mode 100644 index 0000000000..ab9382343b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Perl/sorting-algorithms-counting-sort-2.pl @@ -0,0 +1,4 @@ +my @ages = map {int(rand(140))} 1 .. 100; + +counting_sort(\@ages, 0, 140); +print join("\n", @ages), "\n"; diff --git a/Task/Sorting-algorithms-Counting-sort/PicoLisp/sorting-algorithms-counting-sort.l b/Task/Sorting-algorithms-Counting-sort/PicoLisp/sorting-algorithms-counting-sort.l new file mode 100644 index 0000000000..943cf6bf84 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PicoLisp/sorting-algorithms-counting-sort.l @@ -0,0 +1,10 @@ +(de countingSort (Lst Min Max) + (let Count (need (- Max Min -1) 0) + (for N Lst + (inc (nth Count (- N Min -1))) ) + (make + (map + '((C I) + (do (car C) (link (car I))) ) + Count + (range Min Max) ) ) ) ) diff --git a/Task/Sorting-algorithms-Counting-sort/PureBasic/sorting-algorithms-counting-sort.purebasic b/Task/Sorting-algorithms-Counting-sort/PureBasic/sorting-algorithms-counting-sort.purebasic new file mode 100644 index 0000000000..5aa275bdaf --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PureBasic/sorting-algorithms-counting-sort.purebasic @@ -0,0 +1,16 @@ +Procedure Counting_sort(Array data_array(1), min, max) + Define i, j + Dim c(max - min) + + For i = 0 To ArraySize(data_array()) + c(data_array(i) - min) + 1 + Next + + For i = 0 To ArraySize(c()) + While c(i) + data_array(j) = i + min + j + 1 + c(i) - 1 + Wend + Next +EndProcedure diff --git a/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-1.py b/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-1.py new file mode 100644 index 0000000000..f4f5d7d6b1 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-1.py @@ -0,0 +1,14 @@ +>>> from collections import defaultdict +>>> def countingSort(array, mn, mx): + count = defaultdict(int) + for i in array: + count[i] += 1 + result = [] + for j in range(mn,mx+1): + result += [j]* count[j] + return result + +>>> data = [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10, 2, 1, 3, 8, 7, 3, 9, 5, 8, 5, 1, 6, 3, 7, 5, 4, 6, 9, 9, 6, 6, 10, 2, 4, 5, 2, 8, 2, 2, 5, 2, 9, 3, 3, 5, 7, 8, 4] +>>> mini,maxi = 1,10 +>>> countingSort(data, mini, maxi) == sorted(data) +True diff --git a/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-2.py b/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-2.py new file mode 100644 index 0000000000..d404941946 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Python/sorting-algorithms-counting-sort-2.py @@ -0,0 +1,7 @@ +def countingSort(a, min, max): + cnt = [0] * (max - min + 1) + for x in a: + cnt[x - min] += 1 + + return [x for x, n in enumerate(cnt, start=min) + for i in xrange(n)] diff --git a/Task/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.r b/Task/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.r new file mode 100644 index 0000000000..f5970ba46c --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/R/sorting-algorithms-counting-sort.r @@ -0,0 +1,20 @@ +counting_sort <- function(arr, minval, maxval) { + r <- arr + z <- 1 + for(i in minval:maxval) { + cnt = sum(arr == i) + while(cnt > 0) { + r[z] = i + z <- z + 1 + cnt <- cnt - 1 + } + } + r +} + +# 140+1 instead of 140, since random numbers generated +# by runif are always less than the given maximum; +# floor(a number at most 140.9999...) is 140 +ages <- floor(runif(100, 0, 140+1)) +sorted <- counting_sort(ages, 0, 140) +print(sorted) diff --git a/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx new file mode 100644 index 0000000000..7a5f74d9fd --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx @@ -0,0 +1,41 @@ +/*REXX program sorts an array using the count-sort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call countSort N /*sort N entries of the @. array.*/ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────countSort subroutine────────────────*/ +countSort: procedure expose @.; parse arg N; h=@.1; L=h + + do i=2 to N; L=min(L,@.i); h=max(h,@.i) + end /*i*/ + +_.=0; do j=1 for N; x=@.j; _.x=_.x+1 + end /*j*/ + +#=1; do k=L to h; if _.k\==0 then do #=# for _.k + @.#=k + end /*#*/ + end /*k*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign 40 Recaman numbers. */ +@.1 = 1 ; @.9 = 21 ; @.17= 25 ; @.25= 17 ; @.33= 79 +@.2 = 3 ; @.10= 11 ; @.18= 43 ; @.26= 43 ; @.34= 113 +@.3 = 6 ; @.11= 22 ; @.19= 62 ; @.27= 16 ; @.35= 78 +@.4 = 2 ; @.12= 10 ; @.20= 42 ; @.28= 44 ; @.36= 114 +@.5 = 7 ; @.13= 23 ; @.21= 63 ; @.29= 15 ; @.37= 77 +@.6 = 13 ; @.14= 9 ; @.22= 41 ; @.30= 45 ; @.38= 39 +@.7 = 20 ; @.15= 24 ; @.23= 18 ; @.31= 14 ; @.39= 78 +@.8 = 12 ; @.16= 8 ; @.24= 42 ; @.32= 46 ; @.40= 38 + + do N=1 while @.N\==''; end /*determine the number of entries*/ +N=N-1 /*adjust highItem slightly. */ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(N) /*max width of any element number*/ +pad=left('',9); do s=1 for N + say pad 'element' right(s,widthH) arg(1)": " @.s + end /*s*/ +say copies('─',40) /*show a pretty separator line. */ +return diff --git a/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb b/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb new file mode 100644 index 0000000000..63fa198f38 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Ruby/sorting-algorithms-counting-sort.rb @@ -0,0 +1,24 @@ +class Array + def countingsort! + do_countingsort!(min, max) + end + + protected + def do_countingsort!(min, max) + count = Array.new(max - min + 1, 0) + each {|number| count[number - min] += 1} + z = 0 + min.upto(max) do |i| + while count[i - min] > 0 + self[z] = i + z += 1 + count[i - min] -= 1 + end + end + self + end +end + +ary = [9,7,10,2,9,7,4,3,10,2,7,10,2,1,3,8,7,3,9,5,8,5,1,6,3,7,5,4,6,9,9,6,6,10,2,4,5,2,8,2,2,5,2,9,3,3,5,7,8,4] +ary.countingsort!.join(",") +# => "1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5,5,6,6,6,6,7,7,7,7,7,7,8,8,8,8,9,9,9,9,9,9,10,10,10,10" diff --git a/Task/Sorting-algorithms-Counting-sort/Scala/sorting-algorithms-counting-sort.scala b/Task/Sorting-algorithms-Counting-sort/Scala/sorting-algorithms-counting-sort.scala new file mode 100644 index 0000000000..0b987f995a --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Scala/sorting-algorithms-counting-sort.scala @@ -0,0 +1,7 @@ +def countSort(input: List[Int], min: Int, max: Int): List[Int] = + input.foldLeft(Array.fill(max - min + 1)(0)) { (arr, n) => + arr(n - min) += 1 + arr + }.zipWithIndex.foldLeft(List[Int]()) { + case (lst, (cnt, ndx)) => List.fill(cnt)(ndx + min) ::: lst + }.reverse diff --git a/Task/Sorting-algorithms-Counting-sort/Slate/sorting-algorithms-counting-sort.slate b/Task/Sorting-algorithms-Counting-sort/Slate/sorting-algorithms-counting-sort.slate new file mode 100644 index 0000000000..c7dc3708af --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Slate/sorting-algorithms-counting-sort.slate @@ -0,0 +1,16 @@ +s@(Sequence traits) countingSort &min: min &max: max +[| counts index | + min `defaultsTo: (s reduce: #min: `er). + max `defaultsTo: (s reduce: #max: `er). + counts: ((0 to: max - min) project: [| :_ | 0]). + s do: [| :value | counts at: value - min infect: [| :count | count + 1]]. + index: 0. + min to: max do: [| :value | + [(counts at: value - min) isPositive] + whileTrue: + [s at: index put: value. + index: index + 1. + counts at: value - min infect: [| :val | val - 1]] + ]. + s +]. diff --git a/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-1.st b/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-1.st new file mode 100644 index 0000000000..a4354508f1 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-1.st @@ -0,0 +1,17 @@ +OrderedCollection extend [ + countingSortWithMin: min andMax: max [ + |oc z| + oc := OrderedCollection new. + 1 to: (max - min + 1) do: [ :n| oc add: 0 ]. + self do: [ :v | + oc at: (v - min + 1) put: ( (oc at: (v - min + 1)) + 1) + ]. + z := 1. + min to: max do: [ :i | + 1 to: (oc at: (i - min + 1)) do: [ :k | + self at: z put: i. + z := z + 1. + ] + ] + ] +]. diff --git a/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-2.st b/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-2.st new file mode 100644 index 0000000000..4ba04ac887 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Smalltalk/sorting-algorithms-counting-sort-2.st @@ -0,0 +1,10 @@ +|ages| + +ages := OrderedCollection new. + +1 to: 100 do: [ :n | + ages add: (Random between: 0 and: 140) +]. + +ages countingSortWithMin: 0 andMax: 140. +ages printNl. diff --git a/Task/Sorting-algorithms-Counting-sort/Tcl/sorting-algorithms-counting-sort.tcl b/Task/Sorting-algorithms-Counting-sort/Tcl/sorting-algorithms-counting-sort.tcl new file mode 100644 index 0000000000..893e5ba263 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Tcl/sorting-algorithms-counting-sort.tcl @@ -0,0 +1,41 @@ +proc countingsort {a {min ""} {max ""}} { + # If either of min or max weren't given, compute them now + if {$min eq ""} { + set min [::tcl::mathfunc::min $a] + } + if {$max eq ""} { + set max [::tcl::mathfunc::max $a] + } + + # Make the "array" of counters + set count [lrepeat [expr {$max - $min + 1}] 0] + + # Count the values in the input list + foreach n $a { + set idx [expr {$n - $min}] + lincr count $idx + } + + # Build the output list + set z 0 + for {set i $min} {$i <= $max} {incr i} { + set idx [expr {$i - $min}] + while {[lindex $count $idx] > 0} { + lset a $z $i + incr z + lincr count $idx -1 + } + } + return $a +} + +# Helper that will increment an existing element of a list +proc lincr {listname idx {value 1}} { + upvar 1 $listname list + lset list $idx [expr {[lindex $list $idx] + $value}] +} + +# Demo code +for {set i 0} {$i < 50} {incr i} {lappend a [expr {1+ int(rand()*10)}]} +puts $a +puts [countingsort $a] diff --git a/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbscript b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbscript new file mode 100644 index 0000000000..64fbb3f7ef --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbscript @@ -0,0 +1,42 @@ +function findMax( a ) + dim num + dim max + max = 0 + for each num in a + if num > max then max = num + next + findMax = max +end function + +function findMin( a ) + dim num + dim min + min = 0 + for each num in a + if num < min then min = num + next + findMin = min +end function + +'the function returns the sorted array, but the fact is that VBScript passes the array by reference anyway +function countingSort( a ) + dim count() + dim min, max + min = findMin(a) + max = findMax(a) + redim count( max - min + 1 ) + dim i + dim z + for i = 0 to ubound( a ) + count( a(i) - min ) = count( a( i ) - min ) + 1 + next + z = 0 + for i = min to max + while count( i - min) > 0 + a(z) = i + z = z + 1 + count( i - min ) = count( i - min ) - 1 + wend + next + countingSort = a +end function diff --git a/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbscript b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbscript new file mode 100644 index 0000000000..0cfb7c0c15 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbscript @@ -0,0 +1,5 @@ +dim a +a = array(300, 1, -2, 3, -4, 5, -6, 7, -8, 100, 11 ) +wscript.echo join( a, ", " ) +countingSort a +wscript.echo join( a, ", " ) diff --git a/Task/Sorting-algorithms-Counting-sort/XPL0/sorting-algorithms-counting-sort.xpl0 b/Task/Sorting-algorithms-Counting-sort/XPL0/sorting-algorithms-counting-sort.xpl0 new file mode 100644 index 0000000000..d00c02480b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/XPL0/sorting-algorithms-counting-sort.xpl0 @@ -0,0 +1,23 @@ +include c:\cxpl\codes; + +proc CountingSort(Array, Min, Max, Size); \Sort Array +int Array, Min, Max, Size; \minimum, maximum values, number of elements +int Count, I, Z; +[Count:= Reserve((Max-Min+1)*4); \Reserve Count with 4 bytes per integer +for I:= 0 to Max-Min do Count(I):= 0; \initialize Count with 0 +for I:= 0 to Size-1 do \for each number count its occurrences + Count(Array(I)-Min):= Count(Array(I)-Min) + 1; +Z:= 0; +for I:= Min to Max do + while Count(I-Min) > 0 do + [Array(Z):= I; + Z:= Z+1; + Count(I-Min):= Count(I-Min) - 1; + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +CountingSort(A, -5, 9, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Gnome-sort/0DESCRIPTION b/Task/Sorting-algorithms-Gnome-sort/0DESCRIPTION new file mode 100644 index 0000000000..a2f6c92e81 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/0DESCRIPTION @@ -0,0 +1,24 @@ +{{Sorting Algorithm}} +{{Wikipedia|Gnome sort}} +Gnome sort is a sorting algorithm which is similar to [[Insertion sort]], except that moving an element to its proper place is accomplished by a series of swaps, as in [[Bubble Sort]]. + +The pseudocode for the algorithm is: + '''function''' ''gnomeSort''(a[0..size-1]) + i := 1 + j := 2 + '''while''' i < size '''do''' + '''if''' a[i-1] <= a[i] '''then''' + ''// for descending sort, use >= for comparison'' + i := j + j := j + 1 + '''else''' + '''swap''' a[i-1] '''and''' a[i] + i := i - 1 + '''if''' i = 0 '''then''' + i := j + j := j + 1 + '''endif''' + '''endif''' + '''done''' + +'''Task''': implement the Gnome sort in your language to sort an array (or list) of numbers. diff --git a/Task/Sorting-algorithms-Gnome-sort/1META.yaml b/Task/Sorting-algorithms-Gnome-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Gnome-sort/ALGOL-68/sorting-algorithms-gnome-sort.alg b/Task/Sorting-algorithms-Gnome-sort/ALGOL-68/sorting-algorithms-gnome-sort.alg new file mode 100644 index 0000000000..325b459fed --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/ALGOL-68/sorting-algorithms-gnome-sort.alg @@ -0,0 +1,22 @@ +MODE SORTSTRUCT = CHAR; + +PROC inplace gnome sort = (REF[]SORTSTRUCT list)REF[]SORTSTRUCT: +BEGIN + INT i:=LWB list + 1, j:=LWB list + 2; + WHILE i <= UPB list DO + IF list[i-1] <= list[i] THEN + i := j; j+:=1 + ELSE + SORTSTRUCT swap = list[i-1]; list[i-1]:= list[i]; list[i]:= swap; + i-:=1; + IF i=LWB list THEN i:=j; j+:=1 FI + FI + OD; + list +END; + +PROC gnome sort = ([]SORTSTRUCT seq)[]SORTSTRUCT: + in place gnome sort(LOC[LWB seq: UPB seq]SORTSTRUCT:=seq); + +[]SORTSTRUCT char array data = "big fjords vex quick waltz nymph"; +print((gnome sort(char array data), new line)) diff --git a/Task/Sorting-algorithms-Gnome-sort/AWK/sorting-algorithms-gnome-sort.awk b/Task/Sorting-algorithms-Gnome-sort/AWK/sorting-algorithms-gnome-sort.awk new file mode 100644 index 0000000000..c908daba95 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/AWK/sorting-algorithms-gnome-sort.awk @@ -0,0 +1,38 @@ +#!/usr/bin/awk -f + +BEGIN { + d[1] = 3.0 + d[2] = 4.0 + d[3] = 1.0 + d[4] = -8.4 + d[5] = 7.2 + d[6] = 4.0 + d[7] = 1.0 + d[8] = 1.2 + showD("Before: ") + gnomeSortD() + showD("Sorted: ") + exit +} + +function gnomeSortD( i) { + for (i = 2; i <= length(d); i++) { + if (d[i] < d[i-1]) gnomeSortBackD(i) + } +} + +function gnomeSortBackD(i, t) { + for (; i > 1 && d[i] < d[i-1]; i--) { + t = d[i] + d[i] = d[i-1] + d[i-1] = t + } +} + +function showD(p, i) { + printf p + for (i = 1; i <= length(d); i++) { + printf d[i] " " + } + print "" +} diff --git a/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as b/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as new file mode 100644 index 0000000000..29b9fa5799 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as @@ -0,0 +1,17 @@ +function gnomeSort(array:Array) +{ + var pos:uint = 0; + while(pos < array.length) + { + if(pos == 0 || array[pos] >= array[pos-1]) + pos++; + else + { + var tmp = array[pos]; + array[pos] = array[pos-1]; + array[pos-1] = tmp; + pos--; + } + } + return array; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.ada b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.ada new file mode 100644 index 0000000000..67dd45795e --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.ada @@ -0,0 +1,6 @@ +generic + type Element_Type is private; + type Index is (<>); + type Collection is array(Index) of Element_Type; + with function "<=" (Left, Right : Element_Type) return Boolean is <>; +procedure Gnome_Sort(Item : in out Collection); diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.ada b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.ada new file mode 100644 index 0000000000..17a41086e2 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.ada @@ -0,0 +1,25 @@ +procedure Gnome_Sort(Item : in out Collection) is + procedure Swap(Left, Right : in out Element_Type) is + Temp : Element_Type := Left; + begin + Left := Right; + Right := Temp; + end Swap; + + I : Integer := Index'Pos(Index'Succ(Index'First)); + J : Integer := I + 1; +begin + while I <= Index'Pos(Index'Last) loop + if Item(Index'Val(I - 1)) <= Item(Index'Val(I)) then + I := J; + J := J + 1; + else + Swap(Item(Index'Val(I - 1)), Item(Index'Val(I))); + I := I - 1; + if I = Index'Pos(Index'First) then + I := J; + J := J + 1; + end if; + end if; + end loop; +end Gnome_Sort; diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.ada b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.ada new file mode 100644 index 0000000000..f0a95d6bdf --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.ada @@ -0,0 +1,19 @@ +with Gnome_Sort; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Gnome_Sort_Test is + type Index is range 0..9; + type Buf is array(Index) of Integer; + procedure Sort is new Gnome_Sort(Integer, Index, Buf); + A : Buf := (900, 700, 800, 600, 400, 500, 200, 100, 300, 0); +begin + for I in A'range loop + Put(Integer'Image(A(I))); + end loop; + New_Line; + Sort(A); + for I in A'range loop + Put(Integer'Image(A(I))); + end loop; + New_Line; +end Gnome_Sort_Test; diff --git a/Task/Sorting-algorithms-Gnome-sort/AutoHotkey/sorting-algorithms-gnome-sort.ahk b/Task/Sorting-algorithms-Gnome-sort/AutoHotkey/sorting-algorithms-gnome-sort.ahk new file mode 100644 index 0000000000..6afb785ace --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/AutoHotkey/sorting-algorithms-gnome-sort.ahk @@ -0,0 +1,22 @@ +MsgBox % GnomeSort("") +MsgBox % GnomeSort("xxx") +MsgBox % GnomeSort("3,2,1") +MsgBox % GnomeSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") + +GnomeSort(var) { ; SORT COMMA SEPARATED LIST + StringSplit a, var, `, ; make array, size = a0 + i := 2, j := 3 + While i <= a0 { ; stop when sorted + u := i-1 + If (a%u% < a%i%) ; search for pairs to swap + i := j, j := j+1 + Else { ; swap + t := a%u%, a%u% := a%i%, a%i% := t + If (--i = 1) ; restart search + i := j, j++ + } + } + Loop % a0 ; construct string from sorted array + sorted .= "," . a%A_Index% + Return SubStr(sorted,2) ; drop leading comma +} diff --git a/Task/Sorting-algorithms-Gnome-sort/BASIC/sorting-algorithms-gnome-sort.basic b/Task/Sorting-algorithms-Gnome-sort/BASIC/sorting-algorithms-gnome-sort.basic new file mode 100644 index 0000000000..bd1e3ed0fc --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/BASIC/sorting-algorithms-gnome-sort.basic @@ -0,0 +1,19 @@ +dim a(0 to n-1) as integer +'...more code... +sort: +i = 1 +j = 2 + +while(i < ubound(a) - lbound(a)) + if a(i-1) <= a(i) then + i = j + j = j + 1 + else + swap a(i-1), a(i) + i = i - 1 + if i = 0 then + i = j + j = j + 1 + end if + end if +wend diff --git a/Task/Sorting-algorithms-Gnome-sort/BBC-BASIC/sorting-algorithms-gnome-sort.bbc b/Task/Sorting-algorithms-Gnome-sort/BBC-BASIC/sorting-algorithms-gnome-sort.bbc new file mode 100644 index 0000000000..68d9322ca1 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/BBC-BASIC/sorting-algorithms-gnome-sort.bbc @@ -0,0 +1,17 @@ +DEF PROC_GnomeSort1(Size%) +I%=2 +J%=2 +REPEAT + IF data%(J%-1) <=data%(J%) THEN + I%+=1 + J%=I% + ELSE + SWAP data%(J%-1),data%(J%) + J%-=1 + IF J%=1 THEN + I%+=1 + J%=I% + ENDIF + ENDIF +UNTIL I%>Size% +ENDPROC diff --git a/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp b/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp new file mode 100644 index 0000000000..02c28adf66 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp @@ -0,0 +1,22 @@ +#include <algorithm> +#include <iterator> + +template<typename RandomAccessIterator> +void gnomeSort(RandomAccessIterator begin, RandomAccessIterator end) { + RandomAccessIterator i = begin + 1; + RandomAccessIterator j = begin + 2; + + while(i < end) { + if(*(i - 1) <= *i) { + i = j; + ++j; + } else { + std::iter_swap(i - 1, i); + --i; + if(i == begin) { + i = j; + ++j; + } + } + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/C/sorting-algorithms-gnome-sort.c b/Task/Sorting-algorithms-Gnome-sort/C/sorting-algorithms-gnome-sort.c new file mode 100644 index 0000000000..a78b2784f7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/C/sorting-algorithms-gnome-sort.c @@ -0,0 +1,13 @@ +void gnome_sort(int *a, int n) +{ + int i=1, j=2, t; +# define swap(i, j) { t = a[i]; a[i] = a[j]; a[j] = t; } + while(i < n) { + if (a[i - 1] > a[i]) { + swap(i - 1, i); + if (--i) continue; + } + i = j++; + } +# undef swap +} diff --git a/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cobol b/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cobol new file mode 100644 index 0000000000..c81cf91821 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cobol @@ -0,0 +1,30 @@ + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + SET WB-IX-1 TO 2. + MOVE 1 TO WC-NEXT-POSN. + + PERFORM E-GNOME UNTIL WC-NEXT-POSN > WC-SIZE. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-GNOME SECTION. + E-000. + IF WB-ENTRY(WB-IX-1 - 1) NOT > WB-ENTRY(WB-IX-1) + ADD 1 TO WC-NEXT-POSN + SET WB-IX-1 TO WC-NEXT-POSN + ELSE + MOVE WB-ENTRY(WB-IX-1 - 1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WB-IX-1 - 1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1) + SET WB-IX-1 DOWN BY 1 + IF WB-IX-1 = 1 + ADD 1 TO WC-NEXT-POSN + SET WB-IX-1 TO WC-NEXT-POSN. + + E-999. + EXIT. diff --git a/Task/Sorting-algorithms-Gnome-sort/Clojure/sorting-algorithms-gnome-sort.clj b/Task/Sorting-algorithms-Gnome-sort/Clojure/sorting-algorithms-gnome-sort.clj new file mode 100644 index 0000000000..5154a17252 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Clojure/sorting-algorithms-gnome-sort.clj @@ -0,0 +1,12 @@ +(defn gnomesort + ([c] (gnomesort c <)) + ([c pred] + (loop [x [] [y1 & ys :as y] (seq c)] + (cond (empty? y) x + (empty? x) (recur (list y1) ys) + true (let [zx (last x)] + (if (pred y1 zx) + (recur (butlast x) (concat (list y1 zx) ys)) + (recur (concat x (list y1)) ys))))))) + +(println (gnomesort [3 1 4 1 5 9 2 6 5])) diff --git a/Task/Sorting-algorithms-Gnome-sort/Common-Lisp/sorting-algorithms-gnome-sort.lisp b/Task/Sorting-algorithms-Gnome-sort/Common-Lisp/sorting-algorithms-gnome-sort.lisp new file mode 100644 index 0000000000..387ad325b7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Common-Lisp/sorting-algorithms-gnome-sort.lisp @@ -0,0 +1,13 @@ +(defun gnome-sort (array predicate &aux (length (length array))) + (do ((position (min 1 length))) + ((eql length position) array) + (cond + ((eql 0 position) + (incf position)) + ((funcall predicate + (aref array position) + (aref array (1- position))) + (rotatef (aref array position) + (aref array (1- position))) + (decf position)) + (t (incf position))))) diff --git a/Task/Sorting-algorithms-Gnome-sort/D/sorting-algorithms-gnome-sort.d b/Task/Sorting-algorithms-Gnome-sort/D/sorting-algorithms-gnome-sort.d new file mode 100644 index 0000000000..9c87350628 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/D/sorting-algorithms-gnome-sort.d @@ -0,0 +1,24 @@ +import std.stdio, std.algorithm; + +void gnomeSort(T)(T arr) { + int i = 1, j = 2; + while (i < arr.length) { + if (arr[i-1] <= arr[i]) { + i = j; + j++; + } else { + swap(arr[i-1], arr[i]); + i--; + if (i == 0) { + i = j; + j++; + } + } + } +} + +void main() { + auto a = [3,4,2,5,1,6]; + gnomeSort(a); + writeln(a); +} diff --git a/Task/Sorting-algorithms-Gnome-sort/DWScript/sorting-algorithms-gnome-sort.dwscript b/Task/Sorting-algorithms-Gnome-sort/DWScript/sorting-algorithms-gnome-sort.dwscript new file mode 100644 index 0000000000..1c3afcaa09 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/DWScript/sorting-algorithms-gnome-sort.dwscript @@ -0,0 +1,37 @@ +procedure GnomeSort(a : array of Integer); +var + i, j : Integer; +begin + i := 1; + j := 2; + while i < a.Length do begin + if a[i-1] <= a[i] then begin + i := j; + j := j + 1; + end else begin + a.Swap(i-1, i); + i := i - 1; + if i = 0 then begin + i := j; + j := j + 1; + end; + end; + end; +end; + +var i : Integer; +var a := new Integer[16]; + +Print('{'); +for i := 0 to a.High do begin + a[i] := i xor 5; + Print(Format('%3d ', [a[i]])); +end; +PrintLn('}'); + +GnomeSort(a); + +Print('{'); +for i := 0 to a.High do + Print(Format('%3d ', [a[i]])); +PrintLn('}'); diff --git a/Task/Sorting-algorithms-Gnome-sort/Delphi/sorting-algorithms-gnome-sort.delphi b/Task/Sorting-algorithms-Gnome-sort/Delphi/sorting-algorithms-gnome-sort.delphi new file mode 100644 index 0000000000..5f9fc2f7cc --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Delphi/sorting-algorithms-gnome-sort.delphi @@ -0,0 +1,59 @@ +program TestGnomeSort; + +{$APPTYPE CONSOLE} + +{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array + +type + TItem = Integer; // declare ordinal type for array item +{$IFDEF DYNARRAY} + TArray = array of TItem; // dynamic array +{$ELSE} + TArray = array[0..15] of TItem; // static array +{$ENDIF} + +procedure GnomeSort(var A: TArray); +var + Item: TItem; + I, J: Integer; + +begin + I:= Low(A) + 1; + J:= Low(A) + 2; + while I <= High(A) do begin + if A[I - 1] <= A[I] then begin + I:= J; + J:= J + 1; + end + else begin + Item:= A[I - 1]; + A[I - 1]:= A[I]; + A[I]:= Item; + I:= I - 1; + if I = Low(A) then begin + I:= J; + J:= J + 1; + end; + end; + end; +end; + +var + A: TArray; + I: Integer; + +begin +{$IFDEF DYNARRAY} + SetLength(A, 16); +{$ENDIF} + for I:= Low(A) to High(A) do + A[I]:= Random(100); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + GnomeSort(A); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + Readln; +end. diff --git a/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-1.e b/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-1.e new file mode 100644 index 0000000000..21519b66f1 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-1.e @@ -0,0 +1,20 @@ +def gnomeSort(array) { + var size := array.size() + var i := 1 + var j := 2 + while (i < size) { + if (array[i-1] <= array[i]) { + i := j + j += 1 + } else { + def t := array[i-1] + array[i-1] := array[i] + array[i] := t + i -= 1 + if (i <=> 0) { + i := j + j += 1 + } + } + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-2.e b/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-2.e new file mode 100644 index 0000000000..f4b5ded1ce --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/E/sorting-algorithms-gnome-sort-2.e @@ -0,0 +1,6 @@ +? def a := [7,9,4,2,1,3,6,5,0,8].diverge() +# value: [7, 9, 4, 2, 1, 3, 6, 5, 0, 8].diverge() + +? gnomeSort(a) +? a +# value: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].diverge() diff --git a/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl new file mode 100644 index 0000000000..65797e854e --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl @@ -0,0 +1,9 @@ +-module(gnome_sort). +-export([gnome/1]). + +gnome(L, []) -> L; +gnome([Prev|P], [Next|N]) when Next > Prev -> + gnome(P, [Next|[Prev|N]]); +gnome(P, [Next|N]) -> + gnome([Next|P], N). +gnome([H|T]) -> gnome([H], T). diff --git a/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-2.erl b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-2.erl new file mode 100644 index 0000000000..4c5e57d718 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-2.erl @@ -0,0 +1,6 @@ +Eshell V5.7.3 (abort with ^G) +1> c(gnome_sort). +{ok,gnome_sort} +2> gnome_sort:gnome([8,3,9,1,3,2,6]). +[1,2,3,3,6,8,9] +3> diff --git a/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.euphoria b/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.euphoria new file mode 100644 index 0000000000..17ddf7876a --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.euphoria @@ -0,0 +1,22 @@ +function gnomeSort(sequence s) + integer i,j + object temp + i = 1 + j = 2 + while i < length(s) do + if compare(s[i], s[i+1]) <= 0 then + i = j + j += 1 + else + temp = s[i] + s[i] = s[i+1] + s[i+1] = temp + i -= 1 + if i = 0 then + i = j + j += 1 + end if + end if + end while + return s +end function diff --git a/Task/Sorting-algorithms-Gnome-sort/Fantom/sorting-algorithms-gnome-sort.fantom b/Task/Sorting-algorithms-Gnome-sort/Fantom/sorting-algorithms-gnome-sort.fantom new file mode 100644 index 0000000000..69b9562a99 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Fantom/sorting-algorithms-gnome-sort.fantom @@ -0,0 +1,34 @@ +class Main +{ + Int[] gnomesort (Int[] list) + { + i := 1 + j := 2 + while (i < list.size) + { + if (list[i-1] <= list[i]) + { + i = j + j += 1 + } + else + { + list.swap(i-1, i) + i -= 1 + if (i == 0) + { + i = j + j += 1 + } + } + } + + return list + } + + Void main () + { + list := [4,1,5,8,2,1,5,7] + echo ("" + list + " sorted is " + gnomesort (list)) + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-1.fth b/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-1.fth new file mode 100644 index 0000000000..7825997336 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-1.fth @@ -0,0 +1,24 @@ +defer precedes +defer exchange + +: gnomesort ( a n) + swap >r 1 ( n c) + begin ( n c) + over over > ( n c f) + while ( n c) + dup if ( n c) + dup dup 1- over over r@ precedes + if r@ exchange 1- else drop drop 1+ then + else 1+ then ( n c) + repeat drop drop r> drop ( --) +; + +create example + 8 93 69 52 50 79 33 52 19 77 , , , , , , , , , , + +:noname >r cells r@ + @ swap cells r> + @ swap < ; is precedes +:noname >r cells r@ + swap cells r> + over @ over @ swap rot ! swap ! ; is exchange + +: .array 10 0 do example i cells + ? loop cr ; + +.array example 10 gnomesort .array diff --git a/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-2.fth b/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-2.fth new file mode 100644 index 0000000000..798eda71f2 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Forth/sorting-algorithms-gnome-sort-2.fth @@ -0,0 +1,11 @@ +: gnomesort+ ( a n) + swap >r 2 tuck 1- ( c2 n c1) + begin ( c2 n c1) + over over > ( c2 n c1 f) + while ( c2 n c1) + dup if ( c2 n c1) + dup dup 1- over over r@ precedes + if r@ exchange 1- else drop drop drop >r dup 1+ swap r> swap then + else drop >r dup 1+ swap r> swap then + repeat drop drop drop r> drop +; ( --) diff --git a/Task/Sorting-algorithms-Gnome-sort/Fortran/sorting-algorithms-gnome-sort.f b/Task/Sorting-algorithms-Gnome-sort/Fortran/sorting-algorithms-gnome-sort.f new file mode 100644 index 0000000000..41f7cfbdb7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Fortran/sorting-algorithms-gnome-sort.f @@ -0,0 +1,37 @@ +program example + + implicit none + + integer :: array(8) = (/ 2, 8, 6, 1, 3, 5, 4, 7 /) + + call Gnomesort(array) + write(*,*) array + +contains + +subroutine Gnomesort(a) + + integer, intent(in out) :: a(:) + integer :: i, j, temp + + i = 2 + j = 3 + do while (i <= size(a)) + if (a(i-1) <= a(i)) then + i = j + j = j + 1 + else + temp = a(i-1) + a(i-1) = a(i) + a(i) = temp + i = i - 1 + if (i == 1) then + i = j + j = j + 1 + end if + end if + end do + +end subroutine Gnomesort + +end program example diff --git a/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-1.go b/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-1.go new file mode 100644 index 0000000000..3fa187cd4b --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-1.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + gnomeSort(a) + fmt.Println("after: ", a) +} + +func gnomeSort(a []int) { + for i, j := 1, 2; i < len(a); { + if a[i-1] > a[i] { + a[i-1], a[i] = a[i], a[i-1] + i-- + if i > 0 { + continue + } + } + i = j + j++ + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-2.go b/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-2.go new file mode 100644 index 0000000000..6b75c1a00e --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Go/sorting-algorithms-gnome-sort-2.go @@ -0,0 +1,27 @@ +package main + +import ( + "sort" + "fmt" +) + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + gnomeSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} + +func gnomeSort(a sort.Interface) { + for i, j := 1, 2; i < a.Len(); { + if a.Less(i, i-1) { + a.Swap(i-1, i) + i-- + if i > 0 { + continue + } + } + i = j + j++ + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-1.groovy b/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-1.groovy new file mode 100644 index 0000000000..3bfcd9fbc6 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-1.groovy @@ -0,0 +1,12 @@ +def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] } + +def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } } + +def gnomeSort = { input -> + def swap = checkSwap.curry(input) + def index = 1 + while (index < input.size()) { + index += (swap(index-1) && index > 1) ? -1 : 1 + } + input +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-2.groovy b/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-2.groovy new file mode 100644 index 0000000000..9f8c5de37e --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Groovy/sorting-algorithms-gnome-sort-2.groovy @@ -0,0 +1,2 @@ +println (gnomeSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (gnomeSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) diff --git a/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs b/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs new file mode 100644 index 0000000000..16334bd5d1 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs @@ -0,0 +1,9 @@ +gnomeSort [] = [] +gnomeSort (x:xs) = gs [x] xs + where + gs vv@(v:vs) (w:ws) + | v<=w = gs (w:vv) ws + | otherwise = gs vs (w:v:ws) + gs [] (y:ys) = gs [y] ys + gs xs [] = reverse xs +-- keeping the first argument of gs in reverse order avoids the deterioration into cubic behaviour diff --git a/Task/Sorting-algorithms-Gnome-sort/Icon/sorting-algorithms-gnome-sort.icon b/Task/Sorting-algorithms-Gnome-sort/Icon/sorting-algorithms-gnome-sort.icon new file mode 100644 index 0000000000..3f1798ab40 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Icon/sorting-algorithms-gnome-sort.icon @@ -0,0 +1,19 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(gnomesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure gnomesort(X,op) #: return sorted list +local i,j + + op := sortop(op,X) # select how and what we sort + + j := (i := 2) + 1 # translation of pseudo code + while i <= *X do { + if op(X[i],X[i-1]) then { + X[i] :=: X[i -:= 1] + if i > 1 then next + } + j := (i := j) + 1 + } + return X +end diff --git a/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-1.io b/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-1.io new file mode 100644 index 0000000000..a879009590 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-1.io @@ -0,0 +1,16 @@ +List do( + gnomeSortInPlace := method( + idx := 1 + while(idx <= size, + if(idx == 0 or at(idx) > at(idx - 1)) then( + idx = idx + 1 + ) else( + swapIndices(idx, idx - 1) + idx = idx - 1 + ) + ) + self) +) + +lst := list(5, -1, -4, 2, 9) +lst gnomeSortInPlace println # ==> list(-4, -1, 2, 5, 9) diff --git a/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-2.io b/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-2.io new file mode 100644 index 0000000000..cf5cfc2d79 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Io/sorting-algorithms-gnome-sort-2.io @@ -0,0 +1,19 @@ +List do( + gnomeSortInPlace := method( + idx1 := 1 + idx2 := 2 + + while(idx1 <= size, + if(idx1 == 0 or at(idx1) > at(idx1 - 1)) then( + idx1 = idx2 + idx2 = idx2 + 1 + ) else( + swapIndices(idx1, idx1 - 1) + idx1 = idx1 - 1 + ) + ) + self) +) + +lst := list(5, -1, -4, 2, 9) +lst gnomeSortInPlace println # ==> list(-4, -1, 2, 5, 9) diff --git a/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-1.j b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-1.j new file mode 100644 index 0000000000..a03b53016f --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-1.j @@ -0,0 +1,4 @@ +position=: 0 {.@I.@, [ +swap=: ] A.~ *@position * #@[ !@- <:@position +gnome=: swap~ 2 >/\ ] +gnomes=: gnome^:_ diff --git a/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-2.j b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-2.j new file mode 100644 index 0000000000..b1d4e93f96 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-2.j @@ -0,0 +1 @@ +swap=: position (] {~ _1 0 + [)`(0 _1 + [)`]}^:(*@[) ] diff --git a/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-3.j b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-3.j new file mode 100644 index 0000000000..75e77bc557 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-3.j @@ -0,0 +1,2 @@ +gt=: -.@(-: /:~)@,&< +gnome=: swap~ 2 gt/\ ] diff --git a/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-4.j b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-4.j new file mode 100644 index 0000000000..d5498ce818 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-4.j @@ -0,0 +1 @@ +gnomeps=: gnome^:a: diff --git a/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-5.j b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-5.j new file mode 100644 index 0000000000..00896308d7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/J/sorting-algorithms-gnome-sort-5.j @@ -0,0 +1 @@ +2 ~:/\ gnomeps diff --git a/Task/Sorting-algorithms-Gnome-sort/Java/sorting-algorithms-gnome-sort.java b/Task/Sorting-algorithms-Gnome-sort/Java/sorting-algorithms-gnome-sort.java new file mode 100644 index 0000000000..3922ff4392 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Java/sorting-algorithms-gnome-sort.java @@ -0,0 +1,16 @@ +public static void gnomeSort(int[] a) +{ + int i=1; + int j=2; + + while(i < a.length) { + if ( a[i-1] <= a[i] ) { + i = j; j++; + } else { + int tmp = a[i-1]; + a[i-1] = a[i]; + a[i--] = tmp; + i = (i==0) ? j++ : i; + } + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/JavaScript/sorting-algorithms-gnome-sort.js b/Task/Sorting-algorithms-Gnome-sort/JavaScript/sorting-algorithms-gnome-sort.js new file mode 100644 index 0000000000..541d6245fe --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/JavaScript/sorting-algorithms-gnome-sort.js @@ -0,0 +1,13 @@ +function gnomeSort(a) { + function moveBack(i) { + for( ; i > 0 && a[i-1] > a[i]; i--) { + var t = a[i]; + a[i] = a[i-1]; + a[i-1] = t; + } + } + for (var i = 1; i < a.length; i++) { + if (a[i-1] > a[i]) moveBack(i); + } + return a; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-1.lua b/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-1.lua new file mode 100644 index 0000000000..936d8d6636 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-1.lua @@ -0,0 +1,17 @@ +function gnomeSort(a) + local i, j = 2, 3 + + while i < #a do + if a[i-1] <= a[i] then + i = j + j = j + 1 + else + a[i-1], a[i] = a[i], a[i-1] -- swap + i = i - 1 + if i == 1 then -- 1 instead of 0 + i = j + j = j + 1 + end + end + end +end diff --git a/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-2.lua b/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-2.lua new file mode 100644 index 0000000000..0bb61d7d39 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Lua/sorting-algorithms-gnome-sort-2.lua @@ -0,0 +1,5 @@ +list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 } +gnomeSort(list) +for i, j in pairs(list) do + print(j) +end diff --git a/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-1.m b/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-1.m new file mode 100644 index 0000000000..eb4d3eb3e3 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-1.m @@ -0,0 +1,21 @@ +function list = gnomeSort(list) + + i = 2; + j = 3; + + while i <= numel(list) + + if list(i-1) <= list(i) + i = j; + j = j+1; + else + list([i-1 i]) = list([i i-1]); %Swap + i = i-1; + if i == 1 + i = j; + j = j+1; + end + end %if + + end %while +end %gnomeSort diff --git a/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-2.m b/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-2.m new file mode 100644 index 0000000000..3210afe059 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/MATLAB/sorting-algorithms-gnome-sort-2.m @@ -0,0 +1,5 @@ +>> gnomeSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Gnome-sort/Mathematica/sorting-algorithms-gnome-sort.math b/Task/Sorting-algorithms-Gnome-sort/Mathematica/sorting-algorithms-gnome-sort.math new file mode 100644 index 0000000000..a3c106e9ef --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Mathematica/sorting-algorithms-gnome-sort.math @@ -0,0 +1,7 @@ +gnomeSort[list_]:=Module[{i=2,j=3}, +While[ i<=Length[[list]], +If[ list[[i-1]]<=list[[i]], + i=j; j++;, + list[[i-1;;i]]=list[[i;;i-1]];i--;]; +If[i==1,i=j;j++;] +]] diff --git a/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-1.metafont b/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-1.metafont new file mode 100644 index 0000000000..5181e53ecf --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-1.metafont @@ -0,0 +1,15 @@ +def gnomesort(suffix v)(expr n) = +begingroup save i, j, t; + i := 1; j := 2; + forever: exitif not (i < n); + if v[i-1] <= v[i]: + i := j; j := j + 1; + else: + t := v[i-1]; + v[i-1] := v[i]; + v[i] := t; + i := i - 1; + i := if i=0: j; j := j + 1 else: i fi; + fi + endfor +endgroup enddef; diff --git a/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-2.metafont b/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-2.metafont new file mode 100644 index 0000000000..ba58400efc --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Metafont/sorting-algorithms-gnome-sort-2.metafont @@ -0,0 +1,7 @@ +numeric a[]; +for i = 0 upto 9: a[i] := uniformdeviate(40); message decimal a[i]; endfor +message char10; + +gnomesort(a, 10); +for i = 0 upto 9: message decimal a[i]; endfor +end diff --git a/Task/Sorting-algorithms-Gnome-sort/NetRexx/sorting-algorithms-gnome-sort.netrexx b/Task/Sorting-algorithms-Gnome-sort/NetRexx/sorting-algorithms-gnome-sort.netrexx new file mode 100644 index 0000000000..522a2fccec --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/NetRexx/sorting-algorithms-gnome-sort.netrexx @@ -0,0 +1,50 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +i1 = ArrayList(Arrays.asList([Integer(3), Integer(3), Integer(1), Integer(2), Integer(4), Integer(3), Integer(5), Integer(6)])) +say i1.toString +say gnomeSort(i1).toString + +return + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue + +method gnomeSort(a = String[], sAsc = isTrue) public constant binary returns String[] + + rl = String[a.length] + al = List gnomeSort(Arrays.asList(a), sAsc) + al.toArray(rl) + + return rl + +method gnomeSort(a = List, sAsc = isTrue) public constant binary returns ArrayList + + sDsc = \sAsc -- Ascending/descending switches + ra = ArrayList(a) + i_ = 1 + j_ = 2 + loop label i_ while i_ < ra.size + ctx = (Comparable ra.get(i_ - 1)).compareTo(Comparable ra.get(i_)) + if (sAsc & ctx <= 0) | (sDsc & ctx >= 0) then do + i_ = j_ + j_ = j_ + 1 + end + else do + swap = ra.get(i_) + ra.set(i_, ra.get(i_ - 1)) + ra.set(i_ - 1, swap) + i_ = i_ - 1 + if i_ = 0 then do + i_ = j_ + j_ = j_ + 1 + end + end + end i_ + + return ra diff --git a/Task/Sorting-algorithms-Gnome-sort/OCaml/sorting-algorithms-gnome-sort.ocaml b/Task/Sorting-algorithms-Gnome-sort/OCaml/sorting-algorithms-gnome-sort.ocaml new file mode 100644 index 0000000000..813f3e88c7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/OCaml/sorting-algorithms-gnome-sort.ocaml @@ -0,0 +1,28 @@ +# let gnome_sort a = + let i = ref 1 + and j = ref 2 in + while !i < Array.length a do + if a.(!i-1) <= a.(!i) then + begin + i := !j; + j := !j + 1; + end else begin + swap a (!i-1) (!i); + i := !i - 1; + if !i = 0 then begin + i := !j; + j := !j + 1; + end; + end; + done; + ;; +val gnome_sort : 'a array -> unit = <fun> + +# let a = [| 7; 9; 4; 2; 1; 3; 6; 5; 0; 8; |] ;; +val a : int array = [|7; 9; 4; 2; 1; 3; 6; 5; 0; 8|] + +# gnome_sort a ;; +- : unit = () + +# a ;; +- : int array = [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9|] diff --git a/Task/Sorting-algorithms-Gnome-sort/Objeck/sorting-algorithms-gnome-sort.objeck b/Task/Sorting-algorithms-Gnome-sort/Objeck/sorting-algorithms-gnome-sort.objeck new file mode 100644 index 0000000000..bb5bcdad6d --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Objeck/sorting-algorithms-gnome-sort.objeck @@ -0,0 +1,21 @@ +function : GnomeSort(a : Int[]) { + i := 1; + j := 2; +  + while(i < a->Size()) { + if (a[i-1] <= a[i]) { + i := j; + j += 1; + } + else { + tmp := a[i-1]; + a[i-1] := a[i]; + a[i] := tmp; + i -= 1; + if(i = 0) { + i := j; + j += 1; + }; + }; + }; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave new file mode 100644 index 0000000000..ea6e2489f7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave @@ -0,0 +1,19 @@ +function s = gnomesort(v) + i = 2; j = 3; + while ( i <= length(v) ) + if ( v(i-1) <= v(i) ) + i = j; + j++; + else + t = v(i-1); + v(i-1) = v(i); + v(i) = t; + i--; + if ( i == 1 ) + i = j; + j++; + endif + endif + endwhile + s = v; +endfunction diff --git a/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-2.octave b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-2.octave new file mode 100644 index 0000000000..347c76df8d --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-2.octave @@ -0,0 +1,2 @@ +v = [7, 9, 4, 2, 1, 3, 6, 5, 0, 8]; +disp(gnomesort(v)); diff --git a/Task/Sorting-algorithms-Gnome-sort/Oz/sorting-algorithms-gnome-sort.oz b/Task/Sorting-algorithms-Gnome-sort/Oz/sorting-algorithms-gnome-sort.oz new file mode 100644 index 0000000000..672af23be6 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Oz/sorting-algorithms-gnome-sort.oz @@ -0,0 +1,17 @@ +declare + fun {GnomeSort Xs} + case Xs of nil then nil + [] X|Xr then {Loop [X] Xr} + end + end + + fun {Loop Vs Ws} + case [Vs Ws] + of [V|_ W|Wr] andthen V =< W then {Loop W|Vs Wr} + [] [V|Vr W|Wr] then {Loop Vr W|V|Wr} + [] [nil W|Wr] then {Loop [W] Wr} + [] [Vs nil ] then {Reverse Vs} + end + end +in + {Show {GnomeSort [3 1 4 1 5 9 2 6 5]}} diff --git a/Task/Sorting-algorithms-Gnome-sort/PARI-GP/sorting-algorithms-gnome-sort.pari b/Task/Sorting-algorithms-Gnome-sort/PARI-GP/sorting-algorithms-gnome-sort.pari new file mode 100644 index 0000000000..d559bc0ecf --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PARI-GP/sorting-algorithms-gnome-sort.pari @@ -0,0 +1,15 @@ +gnomeSort(v)={ + my(i=2,j=3,n=#v,t); + while(i<=n, + if(v[i-1]>v[i], + t=v[i]; + v[i]=v[i-1]; + v[i--]=t; + if(i==1, i=j; j++); + , + i=j; + j++ + ) + ); + v +}; diff --git a/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php b/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php new file mode 100644 index 0000000000..aad8d19c92 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php @@ -0,0 +1,20 @@ +function gnomeSort($arr){ + $i = 1; + $j = 2; + while($i < count($arr)){ + if ($arr[$i-1] <= $arr[$i]){ + $i = $j; + $j++; + }else{ + list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); + $i--; + if($i == 0){ + $i = $j; + $j++; + } + } + } + return $arr; +} +$arr = array(3,1,6,2,9,4,7,8,5); +echo implode(',',gnomeSort($arr)); diff --git a/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pascal b/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pascal new file mode 100644 index 0000000000..03af33f9b8 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pascal @@ -0,0 +1,24 @@ +procedure gnomesort(var arr : Array of Integer; size : Integer); +var + i, j, t : Integer; +begin + i := 1; + j := 2; + while i < size do begin + if arr[i-1] <= arr[i] then + begin + i := j; + j := j + 1 + end + else begin + t := arr[i-1]; + arr[i-1] := arr[i]; + arr[i] := t; + i := i - 1; + if i = 0 then begin + i := j; + j := j + 1 + end + end + end; +end; diff --git a/Task/Sorting-algorithms-Gnome-sort/Perl-6/sorting-algorithms-gnome-sort.pl6 b/Task/Sorting-algorithms-Gnome-sort/Perl-6/sorting-algorithms-gnome-sort.pl6 new file mode 100644 index 0000000000..581fa2fc1a --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Perl-6/sorting-algorithms-gnome-sort.pl6 @@ -0,0 +1,12 @@ +sub gnome_sort (@a is rw) { + my ($i, $j) = 1, 2; + while $i < @a { + if @a[$i - 1] <= @a[$i] { + ($i, $j) = $j, $j + 1; + } + else { + (@a[$i - 1], @a[$i]) = @a[$i], @a[$i - 1]; + --$i or ($i, $j) = $j, $j + 1; + } + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl new file mode 100644 index 0000000000..61f1b5d675 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl @@ -0,0 +1,24 @@ +use strict; + +sub gnome_sort +{ + my @a = @_; + + my $size = scalar(@a); + my $i = 1; + my $j = 2; + while($i < $size) { + if ( $a[$i-1] <= $a[$i] ) { + $i = $j; + $j++; + } else { + @a[$i, $i-1] = @a[$i-1, $i]; + $i--; + if ($i == 0) { + $i = $j; + $j++; + } + } + } + return @a; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-2.pl b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-2.pl new file mode 100644 index 0000000000..73345e4c2d --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-2.pl @@ -0,0 +1,2 @@ +my @arr = ( 10, 9, 8, 5, 2, 1, 1, 0, 50, -2 ); +print "$_\n" foreach gnome_sort( @arr ); diff --git a/Task/Sorting-algorithms-Gnome-sort/PicoLisp/sorting-algorithms-gnome-sort.l b/Task/Sorting-algorithms-Gnome-sort/PicoLisp/sorting-algorithms-gnome-sort.l new file mode 100644 index 0000000000..e89a1fb457 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PicoLisp/sorting-algorithms-gnome-sort.l @@ -0,0 +1,10 @@ +(de gnomeSort (Lst) + (let J (cdr Lst) + (for (I Lst (cdr I)) + (if (>= (cadr I) (car I)) + (setq I J J (cdr J)) + (xchg I (cdr I)) + (if (== I Lst) + (setq I J J (cdr J)) + (setq I (prior I Lst)) ) ) ) ) + Lst ) diff --git a/Task/Sorting-algorithms-Gnome-sort/PowerBASIC/sorting-algorithms-gnome-sort.powerbasic b/Task/Sorting-algorithms-Gnome-sort/PowerBASIC/sorting-algorithms-gnome-sort.powerbasic new file mode 100644 index 0000000000..3b838b07eb --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PowerBASIC/sorting-algorithms-gnome-sort.powerbasic @@ -0,0 +1,34 @@ +SUB gnomeSort (a() AS LONG) + DIM i AS LONG, j AS LONG + i = 1 + j = 2 + WHILE (i < UBOUND(a) + 1) + IF (a(i - 1) <= a(i)) THEN + i = j + INCR j + ELSE + SWAP a(i - 1), a(i) + DECR i + IF 0 = i THEN + i = j + INCR j + END IF + END IF + WEND +END SUB + +FUNCTION PBMAIN () AS LONG + DIM n(9) AS LONG, x AS LONG + RANDOMIZE TIMER + OPEN "output.txt" FOR OUTPUT AS 1 + FOR x = 0 TO 9 + n(x) = INT(RND * 9999) + PRINT #1, n(x); ","; + NEXT + PRINT #1, + gnomeSort n() + FOR x = 0 TO 9 + PRINT #1, n(x); ","; + NEXT + CLOSE 1 +END FUNCTION diff --git a/Task/Sorting-algorithms-Gnome-sort/PureBasic/sorting-algorithms-gnome-sort.purebasic b/Task/Sorting-algorithms-Gnome-sort/PureBasic/sorting-algorithms-gnome-sort.purebasic new file mode 100644 index 0000000000..d46052a9d1 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PureBasic/sorting-algorithms-gnome-sort.purebasic @@ -0,0 +1,19 @@ +Procedure GnomeSort(Array a(1)) + Protected Size = ArraySize(a()) + 1 + Protected i = 1, j = 2 + + While i < Size + If a(i - 1) <= a(i) + ;for descending SORT, use >= for comparison + i = j + j + 1 + Else + Swap a(i - 1), a(i) + i - 1 + If i = 0 + i = j + j + 1 + EndIf + EndIf + Wend +EndProcedure diff --git a/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py b/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py new file mode 100644 index 0000000000..accd86a4b7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py @@ -0,0 +1,15 @@ +>>> def gnomesort(a): + i,j,size = 1,2,len(a) + while i < size: + if a[i-1] <= a[i]: + i,j = j, j+1 + else: + a[i-1],a[i] = a[i],a[i-1] + i -= 1 + if i == 0: + i,j = j, j+1 + return a + +>>> gnomesort([3,4,2,5,1,6]) +[1, 2, 3, 4, 5, 6] +>>> diff --git a/Task/Sorting-algorithms-Gnome-sort/R/sorting-algorithms-gnome-sort.r b/Task/Sorting-algorithms-Gnome-sort/R/sorting-algorithms-gnome-sort.r new file mode 100644 index 0000000000..6e7c07e87c --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/R/sorting-algorithms-gnome-sort.r @@ -0,0 +1,26 @@ +gnomesort <- function(x) +{ + i <- 1 + j <- 1 + while(i < length(x)) + { + if(x[i] <= x[i+1]) + { + i <- j + j <- j+1 + } else + { + temp <- x[i] + x[i] <- x[i+1] + x[i+1] <- temp + i <- i - 1 + if(i == 0) + { + i <- j + j <- j+1 + } + } + } + x +} +gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782 diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx new file mode 100644 index 0000000000..2b1178bb79 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx @@ -0,0 +1,41 @@ +/*REXX program sorts an array using the gnome-sort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show "before" array elements.*/ +call gnomeSort highItem /*invoke the infamous gnome sort.*/ +call show@ ' after sort' /*show "after" array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────────gnomeSORT subroutine─────────────*/ +gnomeSort: procedure expose @.; parse arg n; k=2 + + do j=3 while k<=n; km=k-1 + if @.km<=@.k then k=j + else do + _=@.km /*swap two entries in the array. */ + @.km=@.k + @.k=_ + k=k-1; if k==1 then k=j + end + end /*j*/ +return +/*─────────────────────────────────────GEN@ subroutine──────────────────*/ +gen@: @.= /*assign a default value (null). */ +@.1='---the seven virtues---' +@.2='=======================' +@.3='Faith' +@.4='Hope' +@.5='Charity [Love]' +@.6='Fortitude' +@.7='Justice' +@.8='Prudence' +@.9='Temperance' + do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ + end /*not much of a DO loop, eh? */ +highItem=highItem-1 /*because of DO, adjust highItem.*/ +return +/*─────────────────────────────────────SHOW@ subroutine─────────────────*/ +show@: widthH=length(highItem) /*the maximum width of any line. */ + do j=1 for highItem /*show and tell time for array. */ + say 'element' right(j,widthH) arg(1)":" @.j /*make it pretty.*/ + end /*j*/ +say copies('─',60) /*show a separator line that fits*/ +return diff --git a/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal new file mode 100644 index 0000000000..c63813d26d --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal @@ -0,0 +1,19 @@ +import List; + +public list[int] gnomeSort(a){ + i = 1; + j = 2; + while(i < size(a)){ + if(a[i-1] <= a[i]){ + i = j; + j += 1;} + else{ + temp = a[i-1]; + a[i-1] = a[i]; + a[i] = temp; + i = i - 1; + if(i == 0){ + i = j; + j += 1;}}} + return a; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-2.rascal b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-2.rascal new file mode 100644 index 0000000000..7be8da51a7 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-2.rascal @@ -0,0 +1,2 @@ +gnomeSort([4, 65, 2, -31, 0, 99, 83, 782, 1]) +list[int]: [-31,0,1,2,4,65,83,99,782] diff --git a/Task/Sorting-algorithms-Gnome-sort/Ruby/sorting-algorithms-gnome-sort.rb b/Task/Sorting-algorithms-Gnome-sort/Ruby/sorting-algorithms-gnome-sort.rb new file mode 100644 index 0000000000..b95d0e5305 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ruby/sorting-algorithms-gnome-sort.rb @@ -0,0 +1,20 @@ +class Array + def gnomesort! + i, j = 1, 2 + while i < length + if self[i-1] <= self[i] + i, j = j, j+1 + else + self[i-1], self[i] = self[i], self[i-1] + i -= 1 + if i == 0 + i, j = j, j+1 + end + end + end + self + end +end +ary = [7,6,5,9,8,4,3,1,2,0] +ary.gnomesort! +# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Gnome-sort/Scheme/sorting-algorithms-gnome-sort.ss b/Task/Sorting-algorithms-Gnome-sort/Scheme/sorting-algorithms-gnome-sort.ss new file mode 100644 index 0000000000..12c9cef07b --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Scheme/sorting-algorithms-gnome-sort.ss @@ -0,0 +1,21 @@ +; supply comparison function, which returns true if first and second +; arguments are in order or equal. +(define (gnome-sort-compar in-order input-list) + (let gnome ((p (list (car input-list))) + (n (cdr input-list))) + (if (null? n) ; no more flowerpots? + p ; we're done + (let ((prev-pot (car p)) + (next-pot (car n))) + (if (in-order next-pot prev-pot) + ; if the pots are in order, step forwards. + ; otherwise, exchange the two pots, and step backwards. + (gnome (cons next-pot p) ; Prev list grows + (cdr n)) ; Next list shorter by one + (if (null? (cdr p)) ; are we at the beginning? + (gnome ; if so, we can't step back + (list next-pot) ; simply exchange the pots without + (cons prev-pot (cdr n))) ; changing lengths of lists + (gnome + (cdr p) ; Prev list shorter by one + (cons next-pot (cons prev-pot (cdr n)))))))))) diff --git a/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-1.st b/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-1.st new file mode 100644 index 0000000000..6b5856e056 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-1.st @@ -0,0 +1,33 @@ +Smalltalk at: #gnomesort put: nil. + +"Utility" +OrderedCollection extend [ + swap: a with: b [ |t| + t := self at: a. + self at: a put: b. + self at: b put: t + ] +]. + +"Gnome sort as block closure" +gnomesort := [ :c | + |i j| + i := 2. j := 3. + [ i <= (c size) ] + whileTrue: [ + (c at: (i-1)) <= (c at: i) + ifTrue: [ + i := j copy. + j := j + 1. + ] + ifFalse: [ + c swap: (i-1) with: i. + i := i - 1. + i == 1 + ifTrue: [ + i := j copy. + j := j + 1 + ] + ] + ] +]. diff --git a/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-2.st b/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-2.st new file mode 100644 index 0000000000..939660aa77 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Smalltalk/sorting-algorithms-gnome-sort-2.st @@ -0,0 +1,9 @@ +|r o| +r := Random new. +o := OrderedCollection new. + +1 to: 10 do: [ :i | o add: (r between: 0 and: 50) ]. + +gnomesort value: o. + +1 to: 10 do: [ :i | (o at: i) displayNl ]. diff --git a/Task/Sorting-algorithms-Gnome-sort/Tcl/sorting-algorithms-gnome-sort.tcl b/Task/Sorting-algorithms-Gnome-sort/Tcl/sorting-algorithms-gnome-sort.tcl new file mode 100644 index 0000000000..b2ef1830dd --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Tcl/sorting-algorithms-gnome-sort.tcl @@ -0,0 +1,24 @@ +package require Tcl 8.5 +package require struct::list + +proc gnomesort {a} { + set i 1 + set j 2 + set size [llength $a] + while {$i < $size} { + if {[lindex $a [expr {$i - 1}]] <= [lindex $a $i]} { + set i $j + incr j + } else { + struct::list swap a [expr {$i - 1}] $i + incr i -1 + if {$i == 0} { + set i $j + incr j + } + } + } + return $a +} + +puts [gnomesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-1.ursala b/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-1.ursala new file mode 100644 index 0000000000..04a4b44ee8 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-1.ursala @@ -0,0 +1,5 @@ +gnome_sort "p" = + +@NiX ^=lx -+ # iteration + ~&r?\~& @lNXrX ->llx2rhPlrPCTxPrtPX~&lltPlhPrCXPrX ~&ll&& @llPrXh not "p", # backward bubble + ->~&rhPlCrtPX ~&r&& ~&lZ!| @bh "p"+- # forward scan diff --git a/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-2.ursala b/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-2.ursala new file mode 100644 index 0000000000..5ac9dec7e1 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ursala/sorting-algorithms-gnome-sort-2.ursala @@ -0,0 +1,4 @@ +#import std +#cast %s + +t = gnome_sort(lleq) 'dfijhkwlawfkjnksdjnoqwjefgflkdsgioi' diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbscript b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbscript new file mode 100644 index 0000000000..dcd8c4b3a2 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbscript @@ -0,0 +1,27 @@ +function gnomeSort( a ) + dim i + dim j + i = 1 + j = 2 + do while i < ubound( a ) + 1 + if a(i-1) <= a(i) then + i = j + j = j + 1 + else + swap a(i-1), a(i) + i = i - 1 + if i = 0 then + i = j + j = j + 1 + end if + end if + loop + gnomeSort = a +end function + +sub swap( byref x, byref y ) + dim temp + temp = x + x = y + y = temp +end sub diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbscript b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbscript new file mode 100644 index 0000000000..85d3386c21 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbscript @@ -0,0 +1,22 @@ +dim a +dim b + +a = array( "zanzibar", "aardvark","ampicillin","zulu","gogodala", "wolverhampton") +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( 234,567,345,568,2345,89,547,23,649,5769,456,456,567) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( true, false, true, true, false, false, true, false) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( 1,2,2,4,67789,-3,-45.99) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( now(), now()-1,now()+2) +b = gnomeSort( a ) +wscript.echo join(a, ", ") diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbscript b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbscript new file mode 100644 index 0000000000..fd68203cfb --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbscript @@ -0,0 +1,5 @@ +aardvark, ampicillin, gogodala, wolverhampton, zanzibar, zulu +23, 89, 234, 345, 456, 456, 547, 567, 567, 568, 649, 2345, 5769 +True, True, True, True, False, False, False, False +-45.99, -3, 1, 2, 2, 4, 67789 +2/02/2010 10:19:51 AM, 3/02/2010 10:19:51 AM, 5/02/2010 10:19:51 AM diff --git a/Task/Sorting-algorithms-Gnome-sort/XPL0/sorting-algorithms-gnome-sort.xpl0 b/Task/Sorting-algorithms-Gnome-sort/XPL0/sorting-algorithms-gnome-sort.xpl0 new file mode 100644 index 0000000000..4ea875e7c4 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/XPL0/sorting-algorithms-gnome-sort.xpl0 @@ -0,0 +1,28 @@ +code ChOut=8, IntOut=11; + +proc GnomeSort(A(0..Size-1)); \Sort array A +int A, Size; +int I, J, T; +[I:= 1; +J:= 2; +while I < Size do + if A(I-1) <= A(I) then + [\ for descending sort, use >= for comparison + I:= J; + J:= J+1; + ] + else + [T:= A(I-1); A(I-1):= A(I); A(I):= T; \swap + I:= I-1; + if I = 0 then + [I:= J; + J:= J+1; + ]; + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +GnomeSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Heapsort/0DESCRIPTION b/Task/Sorting-algorithms-Heapsort/0DESCRIPTION new file mode 100644 index 0000000000..c4a0b76ef6 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/0DESCRIPTION @@ -0,0 +1,48 @@ +{{Sorting Algorithm}}{{wikipedia|Heapsort}}[[wp:Heapsort|Heapsort]] is an in-place sorting algorithm with worst case and average complexity of <span style="font-family: serif">O(''n'' log''n'')</span>. The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. Heapsort requires random access, so can only be used on an array-like data structure. + +Pseudocode: + '''function''' heapSort(a, count) '''is''' + '''input:''' an unordered array ''a'' of length ''count'' + + <span style="color: grey">''(first place a in max-heap order)''</span> + heapify(a, count) + + end := count - 1 + '''while''' end > 0 '''do''' + <span style="color: grey">''(swap the root(maximum value) of the heap with the'' + ''last element of the heap)''</span> + swap(a[end], a[0]) + <span style="color: grey">''(decrement the size of the heap so that the previous'' + ''max value will stay in its proper place)''</span> + end := end - 1 + <span style="color: grey">''(put the heap back in max-heap order)''</span> + siftDown(a, 0, end) + + + '''function''' heapify(a,count) '''is''' + <span style="color: grey">''(start is assigned the index in ''a'' of the last parent node)''</span> + start := (count - 2) / 2 + + '''while''' start ≥ 0 '''do''' + <span style="color: grey">''(sift down the node at index start to the proper place'' + ''such that all nodes below the start index are in heap'' + ''order)''</span> + siftDown(a, start, count-1) + start := start - 1 + <span style="color: grey">''(after sifting down the root all nodes/elements are in heap order)''</span> + + '''function''' siftDown(a, start, end) '''is''' + <span style="color: grey">''(''end'' represents the limit of how far down the heap to sift)''</span> + root := start + + '''while''' root * 2 + 1 ≤ end '''do''' <span style="color: grey">''(While the root has at least one child)''</span> + child := root * 2 + 1 <span style="color: grey">''(root*2+1 points to the left child)''</span> + <span style="color: grey">''(If the child has a sibling and the child's value is less than its sibling's...)''</span> + '''if''' child + 1 ≤ end '''and''' a[child] < a[child + 1] '''then''' + child := child + 1 <span style="color: grey">''(... then point to the right child instead)''</span> + '''if''' a[root] < a[child] '''then''' <span style="color: grey">''(out of max-heap order)''</span> + swap(a[root], a[child]) + root := child <span style="color: grey">''(repeat to continue sifting down the child now)''</span> + '''else''' + '''return''' +Write a function to sort a collection of integers using heapsort. diff --git a/Task/Sorting-algorithms-Heapsort/1META.yaml b/Task/Sorting-algorithms-Heapsort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Heapsort/ActionScript/sorting-algorithms-heapsort.as b/Task/Sorting-algorithms-Heapsort/ActionScript/sorting-algorithms-heapsort.as new file mode 100644 index 0000000000..5d850641ce --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/ActionScript/sorting-algorithms-heapsort.as @@ -0,0 +1,29 @@ +function heapSort(data:Vector.<int>):Vector.<int> { + for (var start:int = (data.length-2)/2; start >= 0; start--) { + siftDown(data, start, data.length); + } + for (var end:int = data.length - 1; end > 0; end--) { + var tmp:int=data[0]; + data[0]=data[end]; + data[end]=tmp; + siftDown(data, 0, end); + } + return data; +} +function siftDown(data:Vector.<int>, start:int, end:int):void { + var heapRoot:int=start; + while (heapRoot * 2+1 < end) { + var child:int=heapRoot*2+1; + if (child+1<end&&data[child]<data[child+1]) { + child++; + } + if (data[heapRoot]<data[child]) { + var tmp:int=data[heapRoot]; + data[heapRoot]=data[child]; + data[child]=tmp; + heapRoot=child; + } else { + return; + } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.ada b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.ada new file mode 100644 index 0000000000..4812e25a02 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.ada @@ -0,0 +1,6 @@ +generic + type Element_Type is private; + type Index_Type is (<>); + type Collection is array(Index_Type range <>) of Element_Type; + with function "<" (Left, right : element_type) return boolean is <>; +procedure Generic_Heapsort(Item : in out Collection); diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.ada b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.ada new file mode 100644 index 0000000000..a2e5bf62df --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.ada @@ -0,0 +1,50 @@ +procedure Generic_Heapsort(Item : in out Collection) is + procedure Swap(Left : in out Element_Type; Right : in out Element_Type) is + Temp : Element_Type := Left; + begin + Left := Right; + Right := Temp; + end Swap; + procedure Sift_Down(Item : in out Collection) is + Root : Integer := Index_Type'Pos(Item'First); + Child : Integer := Index_Type'Pos(Item'Last); + Last : Integer := Index_Type'Pos(Item'Last); + begin + while Root * 2 + 1 <= Last loop + Child := Root * 2 + 1; + if Child + 1 <= Last and then Item(index_Type'Val(Child)) < Item(Index_Type'Val(Child + 1)) then + Child := Child + 1; + end if; + if Item(Index_Type'Val(Root)) < Item(Index_Type'Val(Child)) then + Swap(Item(Index_Type'Val(Root)), Item(Index_Type'Val(Child))); + Root := Child; + else + exit; + end if; + end loop; + end Sift_Down; + + procedure Heapify(Item : in out Collection) is + First_Pos : Integer := Index_Type'Pos(Index_Type'First); + Last_Pos : Integer := Index_Type'Pos(Index_type'Last); + Start : Index_type := Index_Type'Val((Last_Pos - First_Pos + 1) / 2); + begin + loop + Sift_Down(Item(Start..Item'Last)); + if Start > Index_Type'First then + Start := Index_Type'Pred(Start); + else + exit; + end if; + end loop; + end Heapify; + Last_Index : Index_Type := Index_Type'Last; +begin + Heapify(Item); + while Last_Index > Index_Type'First loop + Swap(Item(Last_Index), Item(Item'First)); + Last_Index := Index_Type'Pred(Last_Index); + Sift_Down(Item(Item'First..Last_Index)); + end loop; + +end Generic_Heapsort; diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.ada b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.ada new file mode 100644 index 0000000000..33ab0c550c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.ada @@ -0,0 +1,19 @@ +with Generic_Heapsort; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Test_Generic_Heapsort is + type Days is (Sun, Mon, Tue, Wed, Thu, Fri, Sat); + type Days_Col is array(Days range <>) of Natural; + procedure Sort is new Generic_Heapsort(Natural, Days, Days_Col); + Week : Days_Col := (5, 2, 7, 3, 4, 9, 1); +begin + for I in Week'range loop + Put(Days'Image(I) & ":" & Natural'Image(Week(I)) & " "); + end loop; + New_Line; + Sort(Week); + for I in Week'range loop + Put(Days'Image(I) & ":" & Natural'Image(Week(I))& " "); + end loop; + New_Line; +end Test_Generic_Heapsort; diff --git a/Task/Sorting-algorithms-Heapsort/AutoHotkey/sorting-algorithms-heapsort.ahk b/Task/Sorting-algorithms-Heapsort/AutoHotkey/sorting-algorithms-heapsort.ahk new file mode 100644 index 0000000000..dfe4eff0ff --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/AutoHotkey/sorting-algorithms-heapsort.ahk @@ -0,0 +1,34 @@ +heapSort(a) { + Local end + end := %a%0 + heapify(a,end) + While end > 1 + %a%%end% := (%a%1 "", %a%1 := %a%%end%) + ,siftDown(a, 1, --end) +} + +heapify(a, count) { + Local start + start := count // 2 + While start + siftDown(a, start--, count) +} + +siftDown(a, start, end) { + Local child, c1 + While start*2 <= end { + c1 := 1 + child := start*2 + If (c1 <= end && %a%%child% < %a%%c1%) + child := c1 + If (%a%%start% < %a%%child%) + %a%%start% := (%a%%child% "", %a%%child% := %a%%start%) + ,start := child + Else Return + } +} + +a = 1,5,2,7,3,4,6,8,1 ; ----- test ----- +StringSplit a, a, `, +heapSort("a") +ListVars +MsgBox diff --git a/Task/Sorting-algorithms-Heapsort/BBC-BASIC/sorting-algorithms-heapsort.bbc b/Task/Sorting-algorithms-Heapsort/BBC-BASIC/sorting-algorithms-heapsort.bbc new file mode 100644 index 0000000000..94a010a8c4 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/BBC-BASIC/sorting-algorithms-heapsort.bbc @@ -0,0 +1,35 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCheapsort(test()) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCheapsort(a()) + LOCAL e% + PROCheapify(a()) + FOR e% = DIM(a(),1) TO 1 STEP -1 + SWAP a(e%), a(0) + PROCsiftdown(a(), 0, e%-1) + NEXT + ENDPROC + + DEF PROCheapify(a()) + LOCAL s%, m% + m% = DIM(a(),1) + FOR s% = (m% - 1) / 2 TO 0 STEP -1 + PROCsiftdown(a(), s%, m%) + NEXT + ENDPROC + + DEF PROCsiftdown(a(), s%, e%) + LOCAL c%, r% + r% = s% + WHILE r% * 2 + 1 <= e% + c% = r% * 2 + 1 + IF c% + 1 <= e% IF a(c%) < a(c% + 1) c% += 1 + IF a(r%) < a(c%) SWAP a(r%), a(c%) : r% = c% ELSE ENDPROC + ENDWHILE + ENDPROC diff --git a/Task/Sorting-algorithms-Heapsort/BCPL/sorting-algorithms-heapsort.bcpl b/Task/Sorting-algorithms-Heapsort/BCPL/sorting-algorithms-heapsort.bcpl new file mode 100644 index 0000000000..573dbadd24 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/BCPL/sorting-algorithms-heapsort.bcpl @@ -0,0 +1,42 @@ +// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10. + +GET "libhdr.h" + +LET heapify(v, k, i, last) BE +{ LET j = i+i // If there is a son (or two), j = subscript of first. + AND x = k // x will hold the larger of the sons if any. + + IF j<=last DO x := v!j // j, x = subscript and key of first son. + IF j< last DO + { LET y = v!(j+1) // y = key of the other son. + IF x<y DO x,j := y, j+1 // j, x = subscript and key of larger son. + } + + IF k>=x DO + { v!i := k // k is not lower than larger son if any. + RETURN + } + v!i := x + i := j +} REPEAT + +AND heapsort(v, upb) BE +{ FOR i = upb/2 TO 1 BY -1 DO heapify(v, v!i, i, upb) + + FOR i = upb TO 2 BY -1 DO + { LET k = v!i + v!i := v!1 + heapify(v, k, 1, i-1) + } +} + +LET start() = VALOF { + LET v = VEC 1000 + FOR i = 1 TO 1000 DO v!i := randno(1_000_000) + heapsort(v, 1000) + FOR i = 1 TO 1000 DO + { IF i MOD 10 = 0 DO newline() + writef(" %i6", v!i) + } + newline() +} diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp new file mode 100644 index 0000000000..d9cde9cd98 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp @@ -0,0 +1,21 @@ +#include <iostream> +#include <algorithm> // for std::make_heap, std::sort_heap + +template <typename Iterator> +void heapsort(Iterator begin, Iterator end) +{ + std::make_heap(begin, end); + std::sort_heap(begin, end); +} + +int main() +{ + double valsToSort[] = { + 1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17, + -18.0, 88.1, 30.44, -37.2, 3012.0, 49.2}; + const int VSIZE = sizeof(valsToSort)/sizeof(*valsToSort); + + heapsort(valsToSort, valsToSort+VSIZE); + for (int ix=0; ix<VSIZE; ix++) std::cout << valsToSort[ix] << std::endl; + return 0; +} diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp new file mode 100644 index 0000000000..052df60528 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp @@ -0,0 +1,10 @@ +#include <iostream> +#include <algorithm> // for std::make_heap, std::pop_heap + +template <typename Iterator> +void heapsort(Iterator begin, Iterator end) +{ + std::make_heap(begin, end); + while (begin != end) + std::pop_heap(begin, end--); +} diff --git a/Task/Sorting-algorithms-Heapsort/C/sorting-algorithms-heapsort.c b/Task/Sorting-algorithms-Heapsort/C/sorting-algorithms-heapsort.c new file mode 100644 index 0000000000..2333565200 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/C/sorting-algorithms-heapsort.c @@ -0,0 +1,58 @@ +#include <stdio.h> +#include <stdlib.h> + +#define ValType double +#define IS_LESS(v1, v2) (v1 < v2) + +void siftDown( ValType *a, int start, int count); + +#define SWAP(r,s) do{ValType t=r; r=s; s=t; } while(0) + +void heapsort( ValType *a, int count) +{ + int start, end; + + /* heapify */ + for (start = (count-2)/2; start >=0; start--) { + siftDown( a, start, count); + } + + for (end=count-1; end > 0; end--) { + SWAP(a[end],a[0]); + siftDown(a, 0, end); + } +} + +void siftDown( ValType *a, int start, int end) +{ + int root = start; + + while ( root*2+1 < end ) { + int child = 2*root + 1; + if ((child + 1 < end) && IS_LESS(a[child],a[child+1])) { + child += 1; + } + if (IS_LESS(a[root], a[child])) { + SWAP( a[child], a[root] ); + root = child; + } + else + return; + } +} + + +int main() +{ + int ix; + double valsToSort[] = { + 1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17, + -18.0, 88.1, 30.44, -37.2, 3012.0, 49.2}; +#define VSIZE (sizeof(valsToSort)/sizeof(valsToSort[0])) + + heapsort(valsToSort, VSIZE); + printf("{"); + for (ix=0; ix<VSIZE; ix++) printf(" %.3f ", valsToSort[ix]); + printf("}\n"); + return 0; +} diff --git a/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-1.clj b/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-1.clj new file mode 100644 index 0000000000..f83a2a483a --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-1.clj @@ -0,0 +1,27 @@ +(defn- swap [a i j] + (assoc a i (nth a j) j (nth a i))) + +(defn- sift [a pred k l] + (loop [a a x k y (inc (* 2 k))] + (if (< (inc (* 2 x)) l) + (let [ch (if (and (< y (dec l)) (pred (nth a y) (nth a (inc y)))) + (inc y) + y)] + (if (pred (nth a x) (nth a ch)) + (recur (swap a x ch) ch (inc (* 2 ch))) + a)) + a))) + +(defn- heapify[pred a len] + (reduce (fn [c term] (sift (swap c term 0) pred 0 term)) + (reduce (fn [c i] (sift c pred i len)) + (vec a) + (range (dec (int (/ len 2))) -1 -1)) + (range (dec len) 0 -1))) + +(defn heap-sort + ([a pred] + (let [len (count a)] + (heapify pred a len))) + ([a] + (heap-sort a <))) diff --git a/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-2.clj b/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-2.clj new file mode 100644 index 0000000000..b39ed787cd --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Clojure/sorting-algorithms-heapsort-2.clj @@ -0,0 +1,6 @@ +user> (heapsort [1 2 4 6 2 3 6]) +[1 2 2 3 4 6 6] +user> (heapsort [1 2 4 6 2 3 6] >) +[6 6 4 3 2 2 1] +user> (heapsort (list 1 2 4 6 2 3 6)) +[1 2 2 3 4 6 6] diff --git a/Task/Sorting-algorithms-Heapsort/CoffeeScript/sorting-algorithms-heapsort.coffeescript b/Task/Sorting-algorithms-Heapsort/CoffeeScript/sorting-algorithms-heapsort.coffeescript new file mode 100644 index 0000000000..9c0c4a788d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/CoffeeScript/sorting-algorithms-heapsort.coffeescript @@ -0,0 +1,33 @@ +# Do an in-place heap sort. +heap_sort = (arr) -> + put_array_in_heap_order(arr) + end = arr.length - 1 + while end > 0 + [arr[0], arr[end]] = [arr[end], arr[0]] + sift_element_down_heap arr, 0, end + end -= 1 + +put_array_in_heap_order = (arr) -> + i = arr.length / 2 - 1 + i = Math.floor i + while i >= 0 + sift_element_down_heap arr, i, arr.length + i -= 1 + +sift_element_down_heap = (heap, i, max) -> + while i < max + i_big = i + c1 = 2*i + 1 + c2 = c1 + 1 + if c1 < max and heap[c1] > heap[i_big] + i_big = c1 + if c2 < max and heap[c2] > heap[i_big] + i_big = c2 + return if i_big is i + [heap[i], heap[i_big]] = [heap[i_big], heap[i]] + i = i_big + +do -> + arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8] + heap_sort arr + console.log arr diff --git a/Task/Sorting-algorithms-Heapsort/Common-Lisp/sorting-algorithms-heapsort.lisp b/Task/Sorting-algorithms-Heapsort/Common-Lisp/sorting-algorithms-heapsort.lisp new file mode 100644 index 0000000000..2f8a336caf --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Common-Lisp/sorting-algorithms-heapsort.lisp @@ -0,0 +1,73 @@ +(defun make-heap (&optional (length 7)) + (make-array length :adjustable t :fill-pointer 0)) + +(defun left-index (index) + (1- (* 2 (1+ index)))) + +(defun right-index (index) + (* 2 (1+ index))) + +(defun parent-index (index) + (floor (1- index) 2)) + +(defun percolate-up (heap index predicate) + (if (zerop index) heap + (do* ((element (aref heap index)) + (index index pindex) + (pindex (parent-index index) + (parent-index index))) + ((zerop index) heap) + (if (funcall predicate element (aref heap pindex)) + (rotatef (aref heap index) (aref heap pindex)) + (return-from percolate-up heap))))) + +(defun heap-insert (heap element predicate) + (let ((index (vector-push-extend element heap 2))) + (percolate-up heap index predicate))) + +(defun percolate-down (heap index predicate) + (let ((length (length heap)) + (element (aref heap index))) + (flet ((maybe-element (index) + "return the element at index or nil, and a boolean + indicating whether there was an element." + (if (< index length) + (values (aref heap index) t) + (values nil nil)))) + (do ((index index swap-index) + (lindex (left-index index) (left-index index)) + (rindex (right-index index) (right-index index)) + (swap-index nil) (swap-child nil)) + (nil) + ;; Extact the left child if there is one. If there is not, + ;; return the heap. Set the left child as the swap-child. + (multiple-value-bind (lchild lp) (maybe-element lindex) + (if (not lp) (return-from percolate-down heap) + (setf swap-child lchild + swap-index lindex)) + ;; Extract the right child, if any, and when better than the + ;; current swap-child, update the swap-child. + (multiple-value-bind (rchild rp) (maybe-element rindex) + (when (and rp (funcall predicate rchild lchild)) + (setf swap-child rchild + swap-index rindex)) + ;; If the swap-child is better than element, rotate them, + ;; and continue percolating down, else return heap. + (if (not (funcall predicate swap-child element)) + (return-from percolate-down heap) + (rotatef (aref heap index) (aref heap swap-index))))))))) + +(defun heap-empty-p (heap) + (eql (length heap) 0)) + +(defun heap-delete-min (heap predicate) + (assert (not (heap-empty-p heap)) () "Can't pop from empty heap.") + (prog1 (aref heap 0) + (setf (aref heap 0) (vector-pop heap)) + (unless (heap-empty-p heap) + (percolate-down heap 0 predicate)))) + +(defun heapsort (sequence predicate) + (let ((h (make-heap (length sequence)))) + (map nil #'(lambda (e) (heap-insert h e predicate)) sequence) + (map-into sequence #'(lambda () (heap-delete-min h predicate))))) diff --git a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d new file mode 100644 index 0000000000..69cfd7288c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d @@ -0,0 +1,32 @@ +import std.stdio, std.algorithm; + +void inplaceHeapSort(R)(R seq) pure nothrow { + static void siftDown(R seq, in size_t start, + in size_t end) pure nothrow { + for (size_t root = start; root * 2 + 1 <= end; ) { + auto child = root * 2 + 1; + if (child + 1 <= end && seq[child] < seq[child + 1]) + child++; + if (seq[root] < seq[child]) { + swap(seq[root], seq[child]); + root = child; + } else + break; + } + } + + if (seq.length > 1) + foreach_reverse (start; 1 .. (seq.length - 2) / 2 + 2) + siftDown(seq, start - 1, seq.length - 1); + + foreach_reverse (end; 1 .. seq.length) { + swap(seq[end], seq[0]); + siftDown(seq, 0, end - 1); + } +} + +void main() { + auto arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; + inplaceHeapSort(arr); + writeln(arr); +} diff --git a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d new file mode 100644 index 0000000000..c9ea491acb --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d @@ -0,0 +1,13 @@ +import std.stdio, std.container; + +void inplaceHeapSort(T)(T[] data) { + auto h = heapify(data); + while (!h.empty) + h.removeFront(); +} + +void main() { + auto arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; + inplaceHeapSort(arr); + writeln(arr); +} diff --git a/Task/Sorting-algorithms-Heapsort/Dart/sorting-algorithms-heapsort.dart b/Task/Sorting-algorithms-Heapsort/Dart/sorting-algorithms-heapsort.dart new file mode 100644 index 0000000000..e71011fc72 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Dart/sorting-algorithms-heapsort.dart @@ -0,0 +1,69 @@ +void heapSort(List a) { + int count = a.length; + + // first place 'a' in max-heap order + heapify(a, count); + + int end = count - 1; + while (end > 0) { + // swap the root (maximum value) of the heap with the + // last element of the heap + int tmp = a[end]; + a[end] = a[0]; + a[0] = tmp; + + // put the heap back in max-heap order + siftDown(a, 0, end - 1); + + // decrement the size of the heap so that the previous + // max value will stay in its proper place + end--; + } +} + + + +void heapify(List a, int count) { + // start is assigned the index in 'a' of the last parent node + int start = ((count - 2)/2).toInt(); // binary heap + + while (start >= 0) { + // sift down the node at index 'start' to the proper place + // such that all nodes below the 'start' index are in heap + // order + siftDown(a, start, count - 1); + start--; + } +} + +void siftDown(List a, int start, int end) { + // end represents the limit of how far down the heap to shift + int root = start; + + while ((root*2 + 1) <= end) { // While the root has at least one child + int child = root*2 + 1; // root*2+1 points to the left child + // if the child has a sibling and the child's value is less than its sibling's... + if (child + 1 <= end && a[child] < a[child + 1]) { + child = child+1; // .. then point to the right child instead + } + + if (a[root] < a[child]) { // out of max-heap order + int tmp = a[root]; + a[root] = a[child]; + a[child] = tmp; + root = child; // repeat to continue shifting down the child now + } else { + return; + } + } + +} + +void main() { + var arr=[1,5,2,7,3,9,4,6,8]; + print("Before sort"); + arr.forEach((var i)=>print("$i")); + heapSort(arr); + print("After sort"); + arr.forEach((var i)=>print("$i")); +} diff --git a/Task/Sorting-algorithms-Heapsort/E/sorting-algorithms-heapsort.e b/Task/Sorting-algorithms-Heapsort/E/sorting-algorithms-heapsort.e new file mode 100644 index 0000000000..33a2722f62 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/E/sorting-algorithms-heapsort.e @@ -0,0 +1,37 @@ +def heapsort := { + def cswap(c, a, b) { + def t := c[a] + c[a] := c[b] + c[b] := t + # println(c) + } + + def siftDown(array, start, finish) { + var root := start + while (var child := root * 2 + 1 + child <= finish) { + if (child + 1 <= finish && array[child] < array[child + 1]) { + child += 1 + } + if (array[root] < array[child]) { + cswap(array, root, child) + root := child + } else { + break + } + } + } + + /** Heapsort (in-place). */ + def heapsort(array) { + # in pseudo-code, heapify only called once, so inline it here + for start in (0..((array.size()-2)//2)).descending() { + siftDown(array, start, array.size()-1) + } + + for finish in (0..(array.size()-1)).descending() { + cswap(array, 0, finish) + siftDown(array, 0, finish - 1) + } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort.fth b/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort.fth new file mode 100644 index 0000000000..8cc1362c58 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort.fth @@ -0,0 +1,51 @@ +create example + 70 , 61 , 63 , 37 , 63 , 25 , 46 , 92 , 38 , 87 , + +[UNDEFINED] r'@ [IF] +: r'@ r> r> r@ swap >r swap >r ; +[THEN] + +defer precedes ( n1 n2 a -- f) +defer exchange ( n1 n2 a --) + +: siftDown ( a e s -- a e s) + swap >r swap >r dup ( s r) + begin ( s r) + dup 2* 1+ dup r'@ < ( s r c f) + while ( s r c) + dup 1+ dup r'@ < ( s r c c+1 f) + if ( s r c c+1) + over over r@ precedes if swap then + then drop ( s r c) + over over r@ precedes ( s r c f) + while ( s r c) + tuck r@ exchange ( s r) + repeat then ( s r) + drop drop r> swap r> swap ( a e s) +; + +: heapsort ( a n --) + over >r ( a n) + dup 1- 1- 2/ ( a c s) + begin ( a c s) + dup 0< 0= ( a c s f) + while ( a c s) + siftDown 1- ( a c s) + repeat drop ( a c) + + 1- 0 ( a e 0) + begin ( a e 0) + over 0> ( a e 0 f) + while ( a e 0) + over over r@ exchange ( a e 0) + siftDown swap 1- swap ( a e 0) + repeat ( a e 0) + drop drop drop r> drop +; + +:noname >r cells r@ + @ swap cells r> + @ swap < ; is precedes +:noname >r cells r@ + swap cells r> + over @ over @ swap rot ! swap ! ; is exchange + +: .array 10 0 do example i cells + ? loop cr ; + +.array example 10 heapsort .array diff --git a/Task/Sorting-algorithms-Heapsort/Fortran/sorting-algorithms-heapsort.f b/Task/Sorting-algorithms-Heapsort/Fortran/sorting-algorithms-heapsort.f new file mode 100644 index 0000000000..843b4fe97d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Fortran/sorting-algorithms-heapsort.f @@ -0,0 +1,65 @@ +program Heapsort_Demo + implicit none + + integer, parameter :: num = 20 + real :: array(num) + + call random_seed + call random_number(array) + write(*,*) "Unsorted array:-" + write(*,*) array + write(*,*) + call heapsort(array) + write(*,*) "Sorted array:-" + write(*,*) array + +contains + +subroutine heapsort(a) + + real, intent(in out) :: a(0:) + integer :: start, n, bottom + real :: temp + + n = size(a) + do start = (n - 2) / 2, 0, -1 + call siftdown(a, start, n); + end do + + do bottom = n - 1, 1, -1 + temp = a(0) + a(0) = a(bottom) + a(bottom) = temp; + call siftdown(a, 0, bottom) + end do + +end subroutine heapsort + +subroutine siftdown(a, start, bottom) + + real, intent(in out) :: a(0:) + integer, intent(in) :: start, bottom + integer :: child, root + real :: temp + + root = start + do while(root*2 + 1 < bottom) + child = root * 2 + 1 + + if (child + 1 < bottom) then + if (a(child) < a(child+1)) child = child + 1 + end if + + if (a(root) < a(child)) then + temp = a(child) + a(child) = a (root) + a(root) = temp + root = child + else + return + end if + end do + +end subroutine siftdown + +end program Heapsort_Demo diff --git a/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-1.go b/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-1.go new file mode 100644 index 0000000000..8970319a87 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-1.go @@ -0,0 +1,38 @@ +package main + +import ( + "sort" + "container/heap" + "fmt" +) + +type HeapHelper struct { + container sort.Interface + length int +} + +func (self HeapHelper) Len() int { return self.length } +// We want a max-heap, hence reverse the comparison +func (self HeapHelper) Less(i, j int) bool { return self.container.Less(j, i) } +func (self HeapHelper) Swap(i, j int) { self.container.Swap(i, j) } +// this should not be called +func (self *HeapHelper) Push(x interface{}) { panic("impossible") } +func (self *HeapHelper) Pop() interface{} { + self.length-- + return nil // return value not used +} + +func heapSort(a sort.Interface) { + helper := HeapHelper{ a, a.Len() } + heap.Init(&helper) + for helper.length > 0 { + heap.Pop(&helper) + } +} + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + heapSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} diff --git a/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-2.go b/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-2.go new file mode 100644 index 0000000000..50538624ed --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Go/sorting-algorithms-heapsort-2.go @@ -0,0 +1,38 @@ +package main + +import ( + "sort" + "fmt" +) + +func main() { + a := []int{170, 45, 75, -90, -802, 24, 2, 66} + fmt.Println("before:", a) + heapSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} + +func heapSort(a sort.Interface) { + for start := (a.Len() - 2) / 2; start >= 0; start-- { + siftDown(a, start, a.Len()-1) + } + for end := a.Len() - 1; end > 0; end-- { + a.Swap(0, end) + siftDown(a, 0, end-1) + } +} + + +func siftDown(a sort.Interface, start, end int) { + for root := start; root*2+1 <= end; { + child := root*2 + 1 + if child+1 <= end && a.Less(child, child+1) { + child++ + } + if !a.Less(root, child) { + return + } + a.Swap(root, child) + root = child + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-1.groovy b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-1.groovy new file mode 100644 index 0000000000..ea3ddc5965 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-1.groovy @@ -0,0 +1,25 @@ +def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] } + +def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } } + +def siftDown = { a, start, end -> + def p = start + while (p*2 < end) { + def c = p*2 + ((p*2 + 1 < end && a[p*2 + 2] > a[p*2 + 1]) ? 2 : 1) + if (checkSwap(a, c, p)) { p = c } + else { return } + } +} + +def heapify = { + (((it.size()-2).intdiv(2))..0).each { start -> siftDown(it, start, it.size()-1) } +} + +def heapSort = { list -> + heapify(list) + (0..<(list.size())).reverse().each { end -> + makeSwap(list, 0, end) + siftDown(list, 0, end-1) + } + list +} diff --git a/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy new file mode 100644 index 0000000000..0e577fd5c3 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy @@ -0,0 +1,2 @@ +println (heapSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (heapSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) diff --git a/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-1.hs b/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-1.hs new file mode 100644 index 0000000000..7cc366f325 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-1.hs @@ -0,0 +1,15 @@ +import Data.Graph.Inductive.Internal.Heap( + Heap(..),insert,findMin,deleteMin) + +-- heapsort is added in this module as an example application + +build :: Ord a => [(a,b)] -> Heap a b +build = foldr insert Empty + +toList :: Ord a => Heap a b -> [(a,b)] +toList Empty = [] +toList h = x:toList r + where (x,r) = (findMin h,deleteMin h) + +heapsort :: Ord a => [a] -> [a] +heapsort = (map fst) . toList . build . map (\x->(x,x)) diff --git a/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-2.hs b/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-2.hs new file mode 100644 index 0000000000..ad5847a1d5 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Haskell/sorting-algorithms-heapsort-2.hs @@ -0,0 +1,2 @@ +*Main> heapsort [[6,9],[2,13],[6,8,14,9],[10,7],[5]] +[[2,13],[5],[6,8,14,9],[6,9],[10,7]] diff --git a/Task/Sorting-algorithms-Heapsort/Icon/sorting-algorithms-heapsort.icon b/Task/Sorting-algorithms-Heapsort/Icon/sorting-algorithms-heapsort.icon new file mode 100644 index 0000000000..4122db847b --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Icon/sorting-algorithms-heapsort.icon @@ -0,0 +1,37 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(heapsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure heapsort(X,op) #: return sorted list ascending(or descending) +local head,tail + + op := sortop(op,X) # select how and what we sort + + every head := (tail := *X) / 2 to 1 by -1 do # work back from from last parent node + X := siftdown(X,op,head,tail) # sift down from head to make the heap + + every tail := *X to 2 by -1 do { # work between the beginning and the tail to final positions + X[1] :=: X[tail] + X := siftdown(X,op,1,tail-1) # re-sift next (previous) branch after shortening the heap + } + + return X +end + +procedure siftdown(X,op,root,tail) #: the value @root is moved "down" the path of max(min) value to its level +local child + + while (child := root * 2) <= tail do { # move down the branch from root to tail + + if op(X[child],X[tail >= child + 1]) then # choose the larger(smaller) + child +:= 1 # ... child + + if op(X[root],X[child]) then { # root out of order? + X[child] :=: X[root] + root := child # follow max(min) branch + } + else + return X + } + return X +end diff --git a/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-1.j b/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-1.j new file mode 100644 index 0000000000..c3972e9260 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-1.j @@ -0,0 +1,17 @@ +swap=: C.~ < + +siftDown=: 4 : 0 + 'c e'=. x + while. e > c=.1+2*s=.c do. + before=. <&({&y) + if. e > 1+c do. c=.c+ c before c+1 end. + if. s before c do. y=. y swap c,s else. break. end. + end. + y +) + +heapSort=: 3 : 0 + if. 1>: c=. # y do. y return. end. + z=. siftDown&.>/ (c,~each i.<.c%2),<y NB. heapify + > ([ siftDown swap~)&.>/ (0,each}.i.c),z +) diff --git a/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-2.j b/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-2.j new file mode 100644 index 0000000000..e4054a2532 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/J/sorting-algorithms-heapsort-2.j @@ -0,0 +1,5 @@ + heapSort 1 5 2 7 3 9 4 6 8 1 +1 1 2 3 4 5 6 7 8 9 + + heapSort &. (a.&i.) 'aqwcdhkij' +acdhijkqw diff --git a/Task/Sorting-algorithms-Heapsort/Java/sorting-algorithms-heapsort.java b/Task/Sorting-algorithms-Heapsort/Java/sorting-algorithms-heapsort.java new file mode 100644 index 0000000000..83a143553e --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Java/sorting-algorithms-heapsort.java @@ -0,0 +1,53 @@ +public static void heapSort(int[] a){ + int count = a.length; + + //first place a in max-heap order + heapify(a, count); + + int end = count - 1; + while(end > 0){ + //swap the root(maximum value) of the heap with the + //last element of the heap + int tmp = a[end]; + a[end] = a[0]; + a[0] = tmp; + //put the heap back in max-heap order + siftDown(a, 0, end - 1); + //decrement the size of the heap so that the previous + //max value will stay in its proper place + end--; + } +} + +public static void heapify(int[] a, int count){ + //start is assigned the index in a of the last parent node + int start = (count - 2) / 2; //binary heap + + while(start >= 0){ + //sift down the node at index start to the proper place + //such that all nodes below the start index are in heap + //order + siftDown(a, start, count - 1); + start--; + } + //after sifting down the root all nodes/elements are in heap order +} + +public static void siftDown(int[] a, int start, int end){ + //end represents the limit of how far down the heap to sift + int root = start; + + while((root * 2 + 1) <= end){ //While the root has at least one child + int child = root * 2 + 1; //root*2+1 points to the left child + //if the child has a sibling and the child's value is less than its sibling's... + if(child + 1 <= end && a[child] < a[child + 1]) + child = child + 1; //... then point to the right child instead + if(a[root] < a[child]){ //out of max-heap order + int tmp = a[root]; + a[root] = a[child]; + a[child] = tmp; + root = child; //repeat to continue sifting down the child now + }else + return; + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Liberty-BASIC/sorting-algorithms-heapsort.liberty b/Task/Sorting-algorithms-Heapsort/Liberty-BASIC/sorting-algorithms-heapsort.liberty new file mode 100644 index 0000000000..43bb9bd59d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Liberty-BASIC/sorting-algorithms-heapsort.liberty @@ -0,0 +1,78 @@ +wikiSample=1 'comment out for random array + +data 6, 5, 3, 1, 8, 7, 2, 4 + itemCount = 20 +if wikiSample then itemCount = 8 + dim A(itemCount) + for i = 1 to itemCount + A(i) = int(rnd(1) * 100) + if wikiSample then read tmp: A(i)=tmp + next i + + print "Before Sort" + call printArray itemCount + + call heapSort itemCount + + print "After Sort" + call printArray itemCount +end + +'------------------------------------------ +sub heapSort count + call heapify count + + print "the heap" + call printArray count + + theEnd = count + while theEnd > 1 + call swap theEnd, 1 + call siftDown 1, theEnd-1 + theEnd = theEnd - 1 + wend +end sub + +sub heapify count + start = int(count / 2) + while start >= 1 + call siftDown start, count + start = start - 1 + wend +end sub + +sub siftDown start, theEnd + root = start + while root * 2 <= theEnd + child = root * 2 + swap = root + if A(swap) < A(child) then + swap = child + end if + if child+1 <= theEnd then + if A(swap) < A(child+1) then + swap = child + 1 + end if + end if + if swap <> root then + call swap root, swap + root = swap + else + exit sub + end if + wend +end sub + +sub swap a,b + tmp = A(a) + A(a) = A(b) + A(b) = tmp +end sub + +'=========================================== +sub printArray itemCount + for i = 1 to itemCount + print using("###", A(i)); + next i + print +end sub diff --git a/Task/Sorting-algorithms-Heapsort/LotusScript/sorting-algorithms-heapsort.lotusscript b/Task/Sorting-algorithms-Heapsort/LotusScript/sorting-algorithms-heapsort.lotusscript new file mode 100644 index 0000000000..b9b7957bd9 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/LotusScript/sorting-algorithms-heapsort.lotusscript @@ -0,0 +1,45 @@ +Public Sub heapsort(pavIn As Variant) + Dim liCount As Integer, liEnd As Integer + Dim lvTemp As Variant + liCount = UBound(pavIn) + 1 + + heapify pavIn, liCount + + liEnd = liCount - 1 + While liEnd > 0 + lvTemp = pavIn(liEnd) + pavIn(liEnd) = pavIn(0) + pavIn(0) = lvTemp + liEnd = liEnd -1 + siftDown pavIn,0, liEnd + Wend +End Sub + +Private Sub heapify(pavIn As Variant,piCount As Integer) + Dim liStart As Integer + liStart = (piCount - 2) / 2 + While liStart >=0 + siftDown pavIn, liStart, piCount -1 + liStart = liStart - 1 + Wend +End Sub + +Private Sub siftDown(pavIn As Variant, piStart As Integer, piEnd As Integer) + Dim liRoot As Integer, liChild As Integer + Dim lvTemp As Variant + liRoot = piStart + While liRoot *2 + 1 <= piEnd + liChild = liRoot *2 + 1 + If liChild +1 <= piEnd And pavIn(liChild) < pavIn(liChild + 1) Then + liChild = liChild + 1 + End If + If pavIn(liRoot) < pavIn(liChild) Then + lvTemp = pavIn(liRoot) + pavIn(liRoot) = pavIn(liChild) + pavIn(liChild) = lvTemp + liRoot = liChild + Else + Exit sub + End if + wend +End Sub diff --git a/Task/Sorting-algorithms-Heapsort/M4/sorting-algorithms-heapsort.m4 b/Task/Sorting-algorithms-Heapsort/M4/sorting-algorithms-heapsort.m4 new file mode 100644 index 0000000000..92831d9c92 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/M4/sorting-algorithms-heapsort.m4 @@ -0,0 +1,56 @@ +divert(-1) + +define(`randSeed',141592653) +define(`setRand', + `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))') +define(`rand_t',`eval(randSeed^(randSeed>>13))') +define(`random', + `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed') + +define(`set',`define(`$1[$2]',`$3')') +define(`get',`defn(`$1[$2]')') +define(`new',`set($1,size,0)') +dnl for the heap calculations, it's easier if origin is 0, so set value first +define(`append', + `set($1,get($1,size),$2)`'set($1,size,incr(get($1,size)))') + +dnl swap(<name>,<j>,<name>[<j>],<k>) using arg stack for the temporary +define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)') + +define(`deck', + `new($1)for(`x',1,$2, + `append(`$1',eval(random%100))')') +define(`show', + `for(`x',0,decr(get($1,size)),`get($1,x) ')') +define(`for', + `ifelse($#,0,``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') + +define(`ifywork', + `ifelse(eval($2>=0),1, + `siftdown($1,$2,$3)`'ifywork($1,decr($2),$3)')') +define(`heapify', + `define(`start',eval((get($1,size)-2)/2))`'ifywork($1,start, + decr(get($1,size)))') +define(`siftdown', + `define(`child',eval($2*2+1))`'ifelse(eval(child<=$3),1, + `ifelse(eval(child+1<=$3),1, + `ifelse(eval(get($1,child)<get($1,incr(child))),1, + `define(`child', + incr(child))')')`'ifelse(eval(get($1,$2)<get($1,child)),1, + `swap($1,$2,get($1,$2),child)`'siftdown($1,child,$3)')')') +define(`sortwork', + `ifelse($2,0, + `', + `swap($1,0,get($1,0),$2)`'siftdown($1,0,decr($2))`'sortwork($1, + decr($2))')') + +define(`heapsort', + `heapify($1)`'sortwork($1,decr(get($1,size)))') + +divert +deck(`a',10) +show(`a') +heapsort(`a') +show(`a') diff --git a/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-1.m b/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-1.m new file mode 100644 index 0000000000..faa6e9681a --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-1.m @@ -0,0 +1,40 @@ +function list = heapSort(list) + + function list = siftDown(list,root,theEnd) + while (root * 2) <= theEnd + + child = root * 2; + if (child + 1 <= theEnd) && (list(child) < list(child+1)) + child = child + 1; + end + + if list(root) < list(child) + list([root child]) = list([child root]); %Swap + root = child; + else + return + end + + end %while + end %siftDown + + count = numel(list); + + %Because heapify is called once in pseudo-code, it is inline here + start = floor(count/2); + + while start >= 1 + list = siftDown(list, start, count); + start = start - 1; + end + %End Heapify + + while count > 1 + + list([count 1]) = list([1 count]); %Swap + count = count - 1; + list = siftDown(list,1,count); + + end + +end diff --git a/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-2.m b/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-2.m new file mode 100644 index 0000000000..4bb4f92b7a --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/MATLAB/sorting-algorithms-heapsort-2.m @@ -0,0 +1,5 @@ +>> heapSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Heapsort/Mathematica/sorting-algorithms-heapsort.math b/Task/Sorting-algorithms-Heapsort/Mathematica/sorting-algorithms-heapsort.math new file mode 100644 index 0000000000..c768f5acda --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Mathematica/sorting-algorithms-heapsort.math @@ -0,0 +1,19 @@ +siftDown[list_,root_,theEnd_]:= + While[(root*2) <= theEnd, + child = root*2; + If[(child+1 <= theEnd)&&(list[[child]] < list[[child+1]]), child++;]; + If[list[[root]] < list[[child]], + list[[{root,child}]] = list[[{child,root}]]; root = child;, + Break[]; + ] + ] + +heapSort[list_] := Module[{ count, start}, + count = Length[list]; start = Floor[count/2]; + While[start >= 1,list = siftDown[list,start,count]; + start--; + ] + While[count > 1, list[[{count,1}]] = list[[{1,count}]]; + count--; list = siftDown[list,1,count]; + ] +] diff --git a/Task/Sorting-algorithms-Heapsort/NetRexx/sorting-algorithms-heapsort.netrexx b/Task/Sorting-algorithms-Heapsort/NetRexx/sorting-algorithms-heapsort.netrexx new file mode 100644 index 0000000000..53a542b170 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/NetRexx/sorting-algorithms-heapsort.netrexx @@ -0,0 +1,83 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] + +lists = [ - + placesList - + , heapSort(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method heapSort(a = String[], count = a.length) public constant binary returns String[] + + + rl = String[a.length] + al = List heapSort(Arrays.asList(a), count) + al.toArray(rl) + + return rl + +method heapSort(a = List, count = a.size) public constant binary returns ArrayList + + a = heapify(a, count) + + iend = count - 1 + loop label iend while iend > 0 + swap = a.get(0) + a.set(0, a.get(iend)) + a.set(iend, swap) + a = siftDown(a, 0, iend - 1) + iend = iend - 1 + end iend + + return ArrayList(a) + +method heapify(a = List, count = int) public constant binary returns List + + start = (count - 2) % 2 + + loop label strt while start >= 0 + a = siftDown(a, start, count - 1) + start = start - 1 + end strt + + return a + +method siftDown(a = List, istart = int, iend = int) public constant binary returns List + + root = istart + + loop label root while root * 2 + 1 <= iend + child = root * 2 + 1 + if child + 1 <= iend then do + if (Comparable a.get(child)).compareTo(Comparable a.get(child + 1)) < 0 then do + child = child + 1 + end + end + if (Comparable a.get(root)).compareTo(Comparable a.get(child)) < 0 then do + swap = a.get(root) + a.set(root, a.get(child)) + a.set(child, swap) + root = child + end + else do + leave root + end + end root + + return a diff --git a/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-1.ocaml b/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-1.ocaml new file mode 100644 index 0000000000..0bee1c9d35 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-1.ocaml @@ -0,0 +1,23 @@ +let heapsort a = + + let swap i j = + let t = a.(i) in a.(i) <- a.(j); a.(j) <- t in + + let sift k l = + let rec check x y = + if 2*x+1 < l then + let ch = + if y < l-1 && a.(y) < a.(y+1) then y+1 else y in + if a.(x) < a.(ch) then (swap x ch; check ch (2*ch+1)) in + check k (2*k+1) in + + let len = Array.length a in + + for start = (len/2)-1 downto 0 do + sift start len; + done; + + for term = len-1 downto 1 do + swap term 0; + sift 0 term; + done;; diff --git a/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-2.ocaml b/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-2.ocaml new file mode 100644 index 0000000000..9c96d6e164 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/OCaml/sorting-algorithms-heapsort-2.ocaml @@ -0,0 +1,10 @@ +let a = [|3;1;4;1;5;9;2;6;5;3;5;8;97;93;23;84;62;64;33;83;27;95|] in + heapsort a; + Array.iter (Printf.printf "%d ") a;; +print_newline ();; + +let s = "Just to show this is a type-checked polymorphic function" in +let b = Array.init (String.length s) (String.get s) in + heapsort b; + Array.iter print_char b;; +print_newline ();; diff --git a/Task/Sorting-algorithms-Heapsort/Objeck/sorting-algorithms-heapsort.objeck b/Task/Sorting-algorithms-Heapsort/Objeck/sorting-algorithms-heapsort.objeck new file mode 100644 index 0000000000..8d8b53546c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Objeck/sorting-algorithms-heapsort.objeck @@ -0,0 +1,53 @@ +bundle Default { + class HeapSort { + function : Main(args : String[]) ~ Nil { + values := [4, 3, 1, 5, 6, 2]; + HeapSort(values); + each(i : values) { + values[i]->PrintLine(); + }; + } + + function : HeapSort(a : Int[]) ~ Nil { + count := a->Size(); + Heapify(a, count); + + end := count - 1; + while(end > 0) { + tmp := a[end]; + a[end] := a[0]; + a[0] := tmp; + SiftDown(a, 0, end - 1); + end -= 1; + }; + } + + function : Heapify(a : Int[], count : Int) ~ Nil { + start := (count - 2) / 2; + while(start >= 0) { + SiftDown(a, start, count - 1); + start -= 1; + }; + } + + function : SiftDown(a : Int[], start : Int, end : Int) ~ Nil { + root := start; + while((root * 2 + 1) <= end) { + child := root * 2 + 1; + if(child + 1 <= end & a[child] < a[child + 1]) { + child := child + 1; + }; + + if(a[root] < a[child]) { + tmp := a[root]; + a[root] := a[child]; + a[child] := tmp; + root := child; + } + else { + return; + }; + }; + } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Oz/sorting-algorithms-heapsort.oz b/Task/Sorting-algorithms-Heapsort/Oz/sorting-algorithms-heapsort.oz new file mode 100644 index 0000000000..9101845a47 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Oz/sorting-algorithms-heapsort.oz @@ -0,0 +1,57 @@ +declare + proc {HeapSort A} + Low = {Array.low A} + High = {Array.high A} + Count = High-Low+1 + + %% heapify + LastParent = Low + (Count-2) div 2 + in + for Start in LastParent..Low;~1 do + {Siftdown A Start High} + end + + %% repeatedly put the maximum element to the end + %% and re-heapify the rest + for End in High..Low+1;~1 do + {Swap A End Low} + {Siftdown A Low End-1} + end + end + + proc {Siftdown A Start End} + Low = {Array.low A} + fun {FirstChildOf I} Low+(I-Low)*2+1 end + + Root = {NewCell Start} + in + for while:{FirstChildOf @Root} =< End + break:Break + do + Child = {NewCell {FirstChildOf @Root}} + in + if @Child + 1 =< End andthen A.@Child < A.(@Child + 1) then + Child := @Child + 1 + end + if A.@Root < A.@Child then + {Swap A @Root @Child} + Root := @Child + else + {Break} + end + end + end + + proc {Swap A I J} + A.J := (A.I := A.J) + end + + %% create array with indices ~1..7 and fill it + Arr = {Array.new ~1 7 0} + {Record.forAllInd unit(~1:3 0:1 4 1 5 9 2 6 5) + proc {$ I V} + Arr.I := V + end} +in + {HeapSort Arr} + {Show {Array.toRecord unit Arr}} diff --git a/Task/Sorting-algorithms-Heapsort/Pascal/sorting-algorithms-heapsort.pascal b/Task/Sorting-algorithms-Heapsort/Pascal/sorting-algorithms-heapsort.pascal new file mode 100644 index 0000000000..c7791af54e --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Pascal/sorting-algorithms-heapsort.pascal @@ -0,0 +1,77 @@ +program HeapSortDemo; + +type + TIntArray = array[4..15] of integer; + +var + data: TIntArray; + i: integer; + +procedure siftDown(var a: TIntArray; start, ende: integer); + var + root, child, swap: integer; + begin + root := start; + while root * 2 - start + 1 <= ende do + begin + child := root * 2 - start + 1; + if (child + 1 <= ende) and (a[child] < a[child + 1]) then + inc(child); + if a[root] < a[child] then + begin + swap := a[root]; + a[root] := a[child]; + a[child] := swap; + root := child; + end + else + exit; + end; + end; + +procedure heapify(var a: TIntArray); + var + start, count: integer; + begin + count := length(a); + start := low(a) + count div 2 - 1; + while start >= low(a) do + begin + siftdown(a, start, high(a)); + dec(start); + end; + end; + +procedure heapSort(var a: TIntArray); + var + ende, swap: integer; + begin + heapify(a); + ende := high(a); + while ende > low(a) do + begin + swap := a[low(a)]; + a[low(a)] := a[ende]; + a[ende] := swap; + dec(ende); + siftdown(a, low(a), ende); + end; + end; + +begin + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + heapSort(data); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Heapsort/Perl-6/sorting-algorithms-heapsort.pl6 b/Task/Sorting-algorithms-Heapsort/Perl-6/sorting-algorithms-heapsort.pl6 new file mode 100644 index 0000000000..fd1ed6e83c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Perl-6/sorting-algorithms-heapsort.pl6 @@ -0,0 +1,25 @@ +sub heap_sort ( @list is rw ) { + for ( 0 ..^ +@list div 2 ).reverse -> $start { + _sift_down $start, @list.end, @list; + } + + for ( 1 ..^ +@list ).reverse -> $end { + @list[ 0, $end ] .= reverse; + _sift_down 0, $end-1, @list; + } +} + +sub _sift_down ( $start, $end, @list is rw ) { + my $root = $start; + while ( my $child = $root * 2 + 1 ) <= $end { + $child++ if $child + 1 <= $end and [<] @list[ $child, $child+1 ]; + return if @list[$root] >= @list[$child]; + @list[ $root, $child ] .= reverse; + $root = $child; + } +} + +my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4; +say 'Input = ' ~ @data; +@data.&heap_sort; +say 'Output = ' ~ @data; diff --git a/Task/Sorting-algorithms-Heapsort/Perl/sorting-algorithms-heapsort.pl b/Task/Sorting-algorithms-Heapsort/Perl/sorting-algorithms-heapsort.pl new file mode 100644 index 0000000000..eceaf71aaa --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Perl/sorting-algorithms-heapsort.pl @@ -0,0 +1,45 @@ +my @my_list = (2,3,6,23,13,5,7,3,4,5); +heap_sort(\@my_list); +print "@my_list\n"; +exit; + +sub heap_sort +{ + my($list) = @_; + my $count = scalar @$list; + heapify($count,$list); + + my $end = $count - 1; + while($end > 0) + { + @$list[0,$end] = @$list[$end,0]; + sift_down(0,$end-1,$list); + $end--; + } +} +sub heapify +{ + my ($count,$list) = @_; + my $start = ($count - 2) / 2; + while($start >= 0) + { + sift_down($start,$count-1,$list); + $start--; + } +} +sub sift_down +{ + my($start,$end,$list) = @_; + + my $root = $start; + while($root * 2 + 1 <= $end) + { + my $child = $root * 2 + 1; + $child++ if($child + 1 <= $end && $list->[$child] < $list->[$child+1]); + if($list->[$root] < $list->[$child]) + { + @$list[$root,$child] = @$list[$child,$root]; + $root = $child; + }else{ return } + } +} diff --git a/Task/Sorting-algorithms-Heapsort/PicoLisp/sorting-algorithms-heapsort.l b/Task/Sorting-algorithms-Heapsort/PicoLisp/sorting-algorithms-heapsort.l new file mode 100644 index 0000000000..4b124d0558 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/PicoLisp/sorting-algorithms-heapsort.l @@ -0,0 +1,19 @@ +(de heapSort (A Cnt) + (let Cnt (length A) + (for (Start (/ Cnt 2) (gt0 Start) (dec Start)) + (siftDown A Start (inc Cnt)) ) + (for (End Cnt (> End 1) (dec End)) + (xchg (nth A End) A) + (siftDown A 1 End) ) ) + A ) + +(de siftDown (A Start End) + (use Child + (for (Root Start (> End (setq Child (* 2 Root)))) + (and + (> End (inc Child)) + (> (get A (inc Child)) (get A Child)) + (inc 'Child) ) + (NIL (> (get A Child) (get A Root))) + (xchg (nth A Root) (nth A Child)) + (setq Root Child) ) ) ) diff --git a/Task/Sorting-algorithms-Heapsort/PureBasic/sorting-algorithms-heapsort.purebasic b/Task/Sorting-algorithms-Heapsort/PureBasic/sorting-algorithms-heapsort.purebasic new file mode 100644 index 0000000000..141572c75d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/PureBasic/sorting-algorithms-heapsort.purebasic @@ -0,0 +1,36 @@ +Declare heapify(Array a(1), count) +Declare siftDown(Array a(1), start, ending) + +Procedure heapSort(Array a(1), count) + Protected ending=count-1 + heapify(a(), count) + While ending>0 + Swap a(ending),a(0) + siftDown(a(), 0, ending-1) + ending-1 + Wend +EndProcedure + +Procedure heapify(Array a(1), count) + Protected start=(count-2)/2 + While start>=0 + siftDown(a(),start,count-1) + start-1 + Wend +EndProcedure + +Procedure siftDown(Array a(1), start, ending) + Protected root=start, child + While (root*2+1)<=ending + child=root*2+1 + If child+1<=ending And a(child)<a(child+1) + child+1 + EndIf + If a(root)<a(child) + Swap a(root), a(child) + root=child + Else + Break + EndIf + Wend +EndProcedure diff --git a/Task/Sorting-algorithms-Heapsort/Python/sorting-algorithms-heapsort.py b/Task/Sorting-algorithms-Heapsort/Python/sorting-algorithms-heapsort.py new file mode 100644 index 0000000000..a03430294d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Python/sorting-algorithms-heapsort.py @@ -0,0 +1,24 @@ +def heapsort(lst): + ''' Heapsort. Note: this function sorts in-place (it mutates the list). ''' + + # in pseudo-code, heapify only called once, so inline it here + for start in range((len(lst)-2)/2, -1, -1): + siftdown(lst, start, len(lst)-1) + + for end in range(len(lst)-1, 0, -1): + lst[end], lst[0] = lst[0], lst[end] + siftdown(lst, 0, end - 1) + return lst + +def siftdown(lst, start, end): + root = start + while True: + child = root * 2 + 1 + if child > end: break + if child + 1 <= end and lst[child] < lst[child + 1]: + child += 1 + if lst[root] < lst[child]: + lst[root], lst[child] = lst[child], lst[root] + root = child + else: + break diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx new file mode 100644 index 0000000000..3e33938a33 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx @@ -0,0 +1,56 @@ +/*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-Heapsort/Ruby/sorting-algorithms-heapsort.rb b/Task/Sorting-algorithms-Heapsort/Ruby/sorting-algorithms-heapsort.rb new file mode 100644 index 0000000000..11b432ad1a --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ruby/sorting-algorithms-heapsort.rb @@ -0,0 +1,34 @@ +class Array + def heapsort + self.dup.heapsort! + end + + def heapsort! + # in pseudo-code, heapify only called once, so inline it here + ((length - 2) / 2).downto(0) {|start| siftdown(start, length - 1)} + + # "end" is a ruby keyword + (length - 1).downto(1) do |end_| + self[end_], self[0] = self[0], self[end_] + siftdown(0, end_ - 1) + end + self + end + + def siftdown(start, end_) + root = start + loop do + child = root * 2 + 1 + break if child > end_ + if child + 1 <= end_ and self[child] < self[child + 1] + child += 1 + end + if self[root] < self[child] + self[root], self[child] = self[child], self[root] + root = child + else + break + end + end + end +end diff --git a/Task/Sorting-algorithms-Heapsort/Scala/sorting-algorithms-heapsort.scala b/Task/Sorting-algorithms-Heapsort/Scala/sorting-algorithms-heapsort.scala new file mode 100644 index 0000000000..3f68398033 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Scala/sorting-algorithms-heapsort.scala @@ -0,0 +1,42 @@ +def heapSort[T](a: Array[T])(implicit ord: Ordering[T]) { + import scala.annotation.tailrec // Ensure functions are tail-recursive + import ord._ + + val indexOrdering = Ordering by a.apply + + def numberOfLeaves(heapSize: Int) = (heapSize + 1) / 2 + + def children(i: Int, heapSize: Int) = { + val leftChild = i * 2 + 1 + leftChild to leftChild + 1 takeWhile (_ < heapSize) + } + + def swap(i: Int, j: Int) = { + val tmp = a(i) + a(i) = a(j) + a(j) = tmp + } + + // Maintain partial ordering by bubbling down elements + @tailrec + def siftDown(i: Int, heapSize: Int) { + val childrenOfI = children(i, heapSize) + if (childrenOfI nonEmpty) { + val biggestChild = childrenOfI max indexOrdering + if (a(i) < a(biggestChild)) { + swap(i, biggestChild) + siftDown(biggestChild, heapSize) + } + } + } + + // Prepare heap by sifting down all non-leaf elements + for (i <- a.indices.reverse drop numberOfLeaves(a.size)) siftDown(i, a.size) + + // Sort from the end of the array forward, by swapping the highest element, + // which is always the top of the heap, to the end of the unsorted array + for (i <- a.indices.reverse) { + swap(0, i) + siftDown(0, i) + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Scheme/sorting-algorithms-heapsort.ss b/Task/Sorting-algorithms-Heapsort/Scheme/sorting-algorithms-heapsort.ss new file mode 100644 index 0000000000..f8d7cb0f1d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Scheme/sorting-algorithms-heapsort.ss @@ -0,0 +1,54 @@ +; swap two elements of a vector +(define (swap! v i j) + (define temp (vector-ref v i)) + (vector-set! v i (vector-ref v j)) + (vector-set! v j temp)) + +; sift element at node start into place +(define (sift-down! v start end) + (let ((child (+ (* start 2) 1))) + (cond + ((> child end) 'done) ; start has no children + (else + (begin + ; if child has a sibling node whose value is greater ... + (and (and (<= (+ child 1) end) + (< (vector-ref v child) (vector-ref v (+ child 1)))) + ; ... then we'll look at the sibling instead + (set! child (+ child 1))) + (if (< (vector-ref v start) (vector-ref v child)) + (begin + (swap! v start child) + (sift-down! v child end)) + 'done)))))) + +; transform v into a binary max-heap +(define (heapify v) + (define (iter v start) + (if (>= start 0) + (begin (sift-down! v start (- (vector-length v) 1)) + (iter v (- start 1))) + 'done)) + ; start sifting with final parent node of v + (iter v (quotient (- (vector-length v) 2) 2))) + +(define (heapsort v) + ; swap root and end node values, + ; sift the first element into place + ; and recurse with new root and next-to-end node + (define (iter v end) + (if (zero? end) + 'done + (begin + (swap! v 0 end) + (sift-down! v 0 (- end 1)) + (iter v (- end 1))))) + (begin + (heapify v) + ; start swapping with root and final node + (iter v (- (vector-length v) 1)))) + +; testing +(define uriah (list->vector '(3 5 7 9 0 8 1 4 2 6))) +(heapsort uriah) +uriah diff --git a/Task/Sorting-algorithms-Heapsort/Seed7/sorting-algorithms-heapsort.seed7 b/Task/Sorting-algorithms-Heapsort/Seed7/sorting-algorithms-heapsort.seed7 new file mode 100644 index 0000000000..1f363e915c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Seed7/sorting-algorithms-heapsort.seed7 @@ -0,0 +1,39 @@ +const proc: downheap (inout array elemType: arr, in var integer: k, in integer: n) is func + local + var elemType: help is elemType.value; + var integer: j is 0; + begin + if k <= n div 2 then + help := arr[k]; + repeat + j := 2 * k; + if j < n and arr[j] < arr[succ(j)] then + incr(j); + end if; + if help < arr[j] then + arr[k] := arr[j]; + k := j; + end if; + until help >= arr[j] or k > n div 2; + arr[k] := help; + end if; + end func; + +const proc: heapSort (inout array elemType: arr) is func + local + var integer: n is 0; + var integer: k is 0; + var elemType: help is elemType.value; + begin + n := length(arr); + for k range n div 2 downto 1 do + downheap(arr, k, n); + end for; + repeat + help := arr[1]; + arr[1] := arr[n]; + arr[n] := help; + decr(n); + downheap(arr, 1, n); + until n <= 1; + end func; diff --git a/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-1.tcl b/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-1.tcl new file mode 100644 index 0000000000..9a65f2b03f --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-1.tcl @@ -0,0 +1,39 @@ +package require Tcl 8.5 + +proc heapsort {list {count ""}} { + if {$count eq ""} { + set count [llength $list] + } + for {set i [expr {$count/2 - 1}]} {$i >= 0} {incr i -1} { + siftDown list $i [expr {$count - 1}] + } + for {set i [expr {$count - 1}]} {$i > 0} {} { + swap list $i 0 + incr i -1 + siftDown list 0 $i + } + return $list +} +proc siftDown {varName i j} { + upvar 1 $varName a + while true { + set child [expr {$i*2 + 1}] + if {$child > $j} { + break + } + if {$child+1 <= $j && [lindex $a $child] < [lindex $a $child+1]} { + incr child + } + if {[lindex $a $i] >= [lindex $a $child]} { + break + } + swap a $i $child + set i $child + } +} +proc swap {varName x y} { + upvar 1 $varName a + set tmp [lindex $a $x] + lset a $x [lindex $a $y] + lset a $y $tmp +} diff --git a/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-2.tcl b/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-2.tcl new file mode 100644 index 0000000000..272ade58e1 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Tcl/sorting-algorithms-heapsort-2.tcl @@ -0,0 +1 @@ +puts [heapsort {1 5 3 7 9 2 8 4 6 0}] diff --git a/Task/Sorting-algorithms-Insertion-sort/0DESCRIPTION b/Task/Sorting-algorithms-Insertion-sort/0DESCRIPTION new file mode 100644 index 0000000000..ff4b56fd38 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/0DESCRIPTION @@ -0,0 +1,19 @@ +{{Sorting Algorithm}} +{{wikipedia|Insertion sort}} +An <span style="font-family: serif">[[O]](''n''<sup>2</sup>)</span> sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. + +Although insertion sort is an <span style="font-family: serif">[[O]](''n''<sup>2</sup>)</span> algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases (i) small <span style="font-family: serif">''n''</span>, (ii) as the final finishing-off algorithm for <span style="font-family: serif">[[O]](''n'' log''n'')</span> algorithms such as [[Merge sort|mergesort]] and [[quicksort]]. + +The algorithm is as follows (from [[wp:Insertion_sort#Algorithm|wikipedia]]): + '''function''' ''insertionSort''(array A) + '''for''' i '''from''' 1 '''to''' length[A]-1 '''do''' + value := A[i] + j := i-1 + '''while''' j >= 0 '''and''' A[j] > value '''do''' + A[j+1] := A[j] + j := j-1 + '''done''' + A[j+1] = value + '''done''' + +Writing the algorithm for integers will suffice. diff --git a/Task/Sorting-algorithms-Insertion-sort/1META.yaml b/Task/Sorting-algorithms-Insertion-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Insertion-sort/ACL2/sorting-algorithms-insertion-sort.acl2 b/Task/Sorting-algorithms-Insertion-sort/ACL2/sorting-algorithms-insertion-sort.acl2 new file mode 100644 index 0000000000..e5a372b7f9 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/ACL2/sorting-algorithms-insertion-sort.acl2 @@ -0,0 +1,12 @@ +(defun insert (x xs) + (cond ((endp xs) (list x)) + ((< x (first xs)) + (cons x xs)) + (t (cons (first xs) + (insert x (rest xs)))))) + +(defun isort (xs) + (if (endp xs) + nil + (insert (first xs) + (isort (rest xs))))) diff --git a/Task/Sorting-algorithms-Insertion-sort/ALGOL-68/sorting-algorithms-insertion-sort.alg b/Task/Sorting-algorithms-Insertion-sort/ALGOL-68/sorting-algorithms-insertion-sort.alg new file mode 100644 index 0000000000..8be2ce72d9 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/ALGOL-68/sorting-algorithms-insertion-sort.alg @@ -0,0 +1,25 @@ +MODE DATA = REF CHAR; + +PROC in place insertion sort = (REF[]DATA item)VOID: +BEGIN + INT first := LWB item; + INT last := UPB item; + INT j; + DATA value; + FOR i FROM first + 1 TO last DO + value := item[i]; + j := i - 1; + # WHILE j >= LWB item AND j <= UPB item ANDF item[j] > value DO // example of ANDF extension # + WHILE ( j >= LWB item AND j <= UPB item | item[j]>value | FALSE ) DO # no extension! # + item[j + 1] := item[j]; + j -:= 1 + OD; + item[j + 1] := value + OD +END # in place insertion sort #; + +[32]CHAR data := "big fjords vex quick waltz nymph"; +[UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD; +in place insertion sort(ref data); +FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); +print((data)) diff --git a/Task/Sorting-algorithms-Insertion-sort/AWK/sorting-algorithms-insertion-sort.awk b/Task/Sorting-algorithms-Insertion-sort/AWK/sorting-algorithms-insertion-sort.awk new file mode 100644 index 0000000000..3d857c4063 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/AWK/sorting-algorithms-insertion-sort.awk @@ -0,0 +1,18 @@ +{ + line[NR] = $0 +} +END { # sort it with insertion sort + for(i=1; i <= NR; i++) { + value = line[i] + j = i - 1 + while( ( j > 0) && ( line[j] > value ) ) { + line[j+1] = line[j] + j-- + } + line[j+1] = value + } + #print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/ActionScript/sorting-algorithms-insertion-sort.as b/Task/Sorting-algorithms-Insertion-sort/ActionScript/sorting-algorithms-insertion-sort.as new file mode 100644 index 0000000000..8949d48d06 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/ActionScript/sorting-algorithms-insertion-sort.as @@ -0,0 +1,15 @@ +function insertionSort(array:Array) +{ + for(var i:int = 1; i < array.length;i++) + { + var value = array[i]; + var j:int = i-1; + while(j >= 0 && array[j] > value) + { + array[j+1] = array[j]; + j--; + } + array[j+1] = value; + } + return array; +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.ada b/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.ada new file mode 100644 index 0000000000..c3237f2ce6 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.ada @@ -0,0 +1,18 @@ +type Data_Array is array(Natural range <>) of Integer; + +procedure Insertion_Sort(Item : in out Data_Array) is + First : Natural := Item'First; + Last : Natural := Item'Last; + Value : Integer; + J : Integer; +begin + for I in (First + 1)..Last loop + Value := Item(I); + J := I - 1; + while J in Item'range and then Item(J) > Value loop + Item(J + 1) := Item(J); + J := J - 1; + end loop; + Item(J + 1) := Value; + end loop; +end Insertion_Sort; diff --git a/Task/Sorting-algorithms-Insertion-sort/AutoHotkey/sorting-algorithms-insertion-sort.ahk b/Task/Sorting-algorithms-Insertion-sort/AutoHotkey/sorting-algorithms-insertion-sort.ahk new file mode 100644 index 0000000000..c7ed736eaa --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/AutoHotkey/sorting-algorithms-insertion-sort.ahk @@ -0,0 +1,17 @@ +MsgBox % InsertionSort("") +MsgBox % InsertionSort("xxx") +MsgBox % InsertionSort("3,2,1") +MsgBox % InsertionSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") + +InsertionSort(var) { ; SORT COMMA SEPARATED LIST + StringSplit a, var, `, ; make array, size = a0 + Loop % a0-1 { + i := A_Index+1, v := a%i%, j := i-1 + While j>0 and a%j%>v + u := j+1, a%u% := a%j%, j-- + u := j+1, a%u% := v + } + Loop % a0 ; construct string from sorted array + sorted .= "," . a%A_Index% + Return SubStr(sorted,2) ; drop leading comma +} diff --git a/Task/Sorting-algorithms-Insertion-sort/BASIC/sorting-algorithms-insertion-sort.basic b/Task/Sorting-algorithms-Insertion-sort/BASIC/sorting-algorithms-insertion-sort.basic new file mode 100644 index 0000000000..af5158d980 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/BASIC/sorting-algorithms-insertion-sort.basic @@ -0,0 +1,30 @@ +DECLARE SUB InsertionSort (theList() AS INTEGER) + +DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING +FOR L = 0 TO 10 + n(L) = INT(RND * 32768) +NEXT +InsertionSort n() +FOR L = 1 TO 10 + PRINT n(L); ";"; +NEXT + +SUB InsertionSort (theList() AS INTEGER) + DIM insertionElementIndex AS INTEGER + FOR insertionElementIndex = 1 TO UBOUND(theList) + DIM insertionElement AS INTEGER + insertionElement = theList(insertionElementIndex) + DIM j AS INTEGER + j = insertionElementIndex - 1 + DO WHILE (j >= 0) + 'necessary for BASICs without short-circuit evaluation + IF (insertionElement < theList(j)) THEN + theList(j + 1) = theList(j) + j = j - 1 + ELSE + EXIT DO + END IF + LOOP + theList(j + 1) = insertionElement + NEXT +END SUB diff --git a/Task/Sorting-algorithms-Insertion-sort/BBC-BASIC/sorting-algorithms-insertion-sort.bbc b/Task/Sorting-algorithms-Insertion-sort/BBC-BASIC/sorting-algorithms-insertion-sort.bbc new file mode 100644 index 0000000000..668e7ae768 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/BBC-BASIC/sorting-algorithms-insertion-sort.bbc @@ -0,0 +1,21 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCinsertionsort(test(), 10) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCinsertionsort(a(), n%) + LOCAL i%, j%, t + FOR i% = 1 TO n%-1 + t = a(i%) + j% = i% + WHILE j%>0 AND t<a(ABS(j%-1)) + a(j%) = a(j%-1) + j% -= 1 + ENDWHILE + a(j%) = t + NEXT + ENDPROC diff --git a/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp b/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp new file mode 100644 index 0000000000..d74faf7d47 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp @@ -0,0 +1,8 @@ +#include <algorithm> + +template<typename Iter> +void insertion_sort(Iter beg, Iter end) +{ + for (Iter i = beg; i != end; ++i) + std::rotate(std::upper_bound(beg, i, *i), i, i+1); +} diff --git a/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c b/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c new file mode 100644 index 0000000000..ce7c5944e2 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c @@ -0,0 +1,19 @@ +#include <stddef.h> + +static void insertion_sort(int *a, const size_t n) { + size_t i, j; + int value; + for (i = 1; i < n; i++) { + value = a[i]; + for (j = i; j > 0 && value < a[j - 1]; j--) { + a[j] = a[j - 1]; + } + a[j] = value; + } +} + +int main(void) { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + insertion_sort(a, sizeof a / sizeof a[0]); + return 0; +} diff --git a/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake new file mode 100644 index 0000000000..93f515492b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake @@ -0,0 +1,31 @@ +# insertion_sort(var [value1 value2...]) sorts a list of integers. +function(insertion_sort var) + math(EXPR last "${ARGC} - 1") # Sort ARGV[1..last]. + foreach(i RANGE 2 ${last}) + # Extend the sorted area to ARGV[1..i]. + set(b ${i}) + set(v ${ARGV${b}}) + # Insert v == ARGV[b] in sorted order. While b > 1, check if b is + # too high, then decrement b. After loop, set ARGV[b] = v. + while(b GREATER 1) + math(EXPR a "${b} - 1") + set(u ${ARGV${a}}) + # Now u == ARGV[a]. Pretend v == ARGV[b]. Compare. + if(u GREATER ${v}) + # ARGV[a] and ARGV[b] are in wrong order. Fix by moving ARGV[a] + # to ARGV[b], making room for later insertion of v. + set(ARGV${b} ${u}) + else() + break() + endif() + math(EXPR b "${b} - 1") + endwhile() + set(ARGV${b} ${v}) + endforeach(i) + + set(answer) + foreach(i RANGE 1 ${last}) + list(APPEND answer ${ARGV${i}}) + endforeach(i) + set("${var}" "${answer}" PARENT_SCOPE) +endfunction(insertion_sort) diff --git a/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-2.cmake b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-2.cmake new file mode 100644 index 0000000000..03bae18f3e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-2.cmake @@ -0,0 +1,2 @@ +insertion_sort(result 33 11 44 22 66 55) +message(STATUS "${result}") # -- 11;22;33;44;55;66 diff --git a/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort.cobol b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort.cobol new file mode 100644 index 0000000000..5be2a4c227 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort.cobol @@ -0,0 +1,27 @@ + C-PROCESS SECTION. + PERFORM E-INSERTION VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 > WC-SIZE. + +... + + E-INSERTION SECTION. + E-000. + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP. + SET WB-IX-2 TO WB-IX-1. + + PERFORM F-PASS UNTIL WB-IX-2 NOT > 1 OR + WC-TEMP NOT < WB-ENTRY(WB-IX-2 - 1). + + IF WB-IX-1 NOT = WB-IX-2 + MOVE WC-TEMP TO WB-ENTRY(WB-IX-2). + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + MOVE WB-ENTRY(WB-IX-2 - 1) TO WB-ENTRY(WB-IX-2). + SET WB-IX-2 DOWN BY 1. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Insertion-sort/Clojure/sorting-algorithms-insertion-sort.clj b/Task/Sorting-algorithms-Insertion-sort/Clojure/sorting-algorithms-insertion-sort.clj new file mode 100644 index 0000000000..571ebd1899 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Clojure/sorting-algorithms-insertion-sort.clj @@ -0,0 +1,9 @@ +(defn in-sort! [data] + (letfn [(insert ([raw x](insert [] raw x)) + ([sorted [y & raw] x] + (if (nil? y) (conj sorted x) + (if (<= x y ) (concat sorted [x,y] raw) + (recur (conj sorted y) raw x )))))] + (reduce insert [] data))) +;Usage:(in-sort! [6,8,5,9,3,2,1,4,7]) +;Returns: [1 2 3 4 5 6 7 8 9] diff --git a/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort.lisp b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort.lisp new file mode 100644 index 0000000000..e539339124 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort.lisp @@ -0,0 +1,13 @@ +(defun span (predicate list) + (let ((tail (member-if-not predicate list))) + (values (ldiff list tail) tail))) + +(defun less-than (x) + (lambda (y) (< y x))) + +(defun insert (list elt) + (multiple-value-bind (left right) (span (less-than elt) list) + (append left (list elt) right))) + +(defun insertion-sort (list) + (reduce #'insert list :initial-value nil)) diff --git a/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d new file mode 100644 index 0000000000..684fdd8467 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d @@ -0,0 +1,15 @@ +void insertionSort(T)(T[] data) pure nothrow { + foreach (i, value; data[1 .. $]) { + auto j = i + 1; + for ( ; j > 0 && value < data[j - 1]; j--) + data[j] = data[j - 1]; + data[j] = value; + } +} + +void main() { + import std.stdio; + auto items = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; + items.insertionSort(); + writeln(items); +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-1.delphi b/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-1.delphi new file mode 100644 index 0000000000..2864c21d81 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-1.delphi @@ -0,0 +1,50 @@ +program TestInsertionSort; + +{$APPTYPE CONSOLE} + +{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array + +type + TItem = Integer; // declare ordinal type for array item +{$IFDEF DYNARRAY} + TArray = array of TItem; // dynamic array +{$ELSE} + TArray = array[0..15] of TItem; // static array +{$ENDIF} + +procedure InsertionSort(var A: TArray); +var + I, J: Integer; + Item: TItem; + +begin + for I:= 1 + Low(A) to High(A) do begin + Item:= A[I]; + J:= I - 1; + while (J >= Low(A)) and (A[J] > Item) do begin + A[J + 1]:= A[J]; + Dec(J); + end; + A[J + 1]:= Item; + end; +end; + +var + A: TArray; + I: Integer; + +begin +{$IFDEF DYNARRAY} + SetLength(A, 16); +{$ENDIF} + for I:= Low(A) to High(A) do + A[I]:= Random(100); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + InsertionSort(A); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + Readln; +end. diff --git a/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-2.delphi b/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-2.delphi new file mode 100644 index 0000000000..c8827a06cb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Delphi/sorting-algorithms-insertion-sort-2.delphi @@ -0,0 +1,17 @@ +procedure InsertionSort(var S: string); +var + I, J, L: Integer; + Ch: Char; + +begin + L:= Length(S); + for I:= 2 to L do begin + Ch:= S[I]; + J:= I - 1; + while (J > 0) and (S[J] > Ch) do begin + S[J + 1]:= S[J]; + Dec(J); + end; + S[J + 1]:= Ch; + end; +end; diff --git a/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-1.e b/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-1.e new file mode 100644 index 0000000000..f92191a09a --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-1.e @@ -0,0 +1,11 @@ +def insertionSort(array) { + for i in 1..!(array.size()) { + def value := array[i] + var j := i-1 + while (j >= 0 && array[j] > value) { + array[j + 1] := array[j] + j -= 1 + } + array[j+1] := value + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-2.e b/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-2.e new file mode 100644 index 0000000000..eef56a968b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/E/sorting-algorithms-insertion-sort-2.e @@ -0,0 +1,4 @@ +? def a := [71, 53, 22, 24, 83, 54, 39, 78, 65, 26, 60, 75, 67, 27, 52, 59, 93, 62, 85, 99, 88, 10, 91, 85, 13, 17, 14, 96, 55, 10, 61, 94, 27, 50, 75, 40, 47, 63, 10, 23].diverge() +> insertionSort(a) +> a +# value: [10, 10, 10, 13, 14, 17, 22, 23, 24, 26, 27, 27, 39, 40, 47, 50, 52, 53, 54, 55, 59, 60, 61, 62, 63, 65, 67, 71, 75, 75, 78, 83, 85, 85, 88, 91, 93, 94, 96, 99].diverge() diff --git a/Task/Sorting-algorithms-Insertion-sort/Eiffel/sorting-algorithms-insertion-sort.e b/Task/Sorting-algorithms-Insertion-sort/Eiffel/sorting-algorithms-insertion-sort.e new file mode 100644 index 0000000000..b5aad6e0fb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Eiffel/sorting-algorithms-insertion-sort.e @@ -0,0 +1,32 @@ +class + MY_SORTED_SET [G -> COMPARABLE] +inherit + TWO_WAY_SORTED_SET [G] + redefine + sort + end +create + make + +feature + sort + -- Insertion sort + local + l_j: INTEGER + l_value: like item + do + across 2 |..| count as ii loop + from + l_j := ii.item - 1 + l_value := Current.i_th (ii.item) + until + l_j < 1 or Current.i_th (l_j) <= l_value + loop + Current.i_th (l_j + 1) := Current.i_th (l_j) + l_j := l_j - 1 + end + Current.i_th (l_j + 1) := l_value + end + end + +end diff --git a/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.l b/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.l new file mode 100644 index 0000000000..7e55df64b5 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.l @@ -0,0 +1,44 @@ +(defun min-or-max-of-2-numbers (n1 n2 rel) + "n1 and n2 are two numbers, rel can be '< or '> according to +what sort of sorting is wanted, this function returns the greater +or smaller number n1 or n2" + (cond + ((eval (list rel n1 n2)) n1) + (t n2))) + +(defun min-or-max-of-a-list (lon rel) + "lon is a list of numbers, rel is '< or '>, this fonction +returns the higher or lower number of the list" + (if (cdr lon) + (min-or-max-of-2-numbers (car lon) + (min-or-max-of-a-list (cdr lon) rel) + rel) + (car lon))) + +(defun remove-number-from-list (n lon) + "lon is a list of numbers, n is a number belonging to the list, +this function returns the same list but the number n. If n is +present twice or more, it will be removed only once" + (if lon + (cond + ((= (car lon) n) (cdr lon)) + (t (cons (car lon) (remove-number-from-list n (cdr lon))))) + nil)) + + +(defun sort-insertion (lon rel) + "lon is a list of numbers, rel can be '< or '>, this function +returns a list containing the same elements but which is sorted +according to rel" + (if lon + (cons (min-or-max-of-a-list lon rel) + (sort-insertion + (remove-number-from-list + (min-or-max-of-a-list lon rel) + lon) + rel)) + nil)) + +;;; let's try it : + +(sort-insertion (list 1 2 3 9 8 7 25 12 3 2 1) '>) diff --git a/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-1.erl b/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-1.erl new file mode 100644 index 0000000000..07f93b925f --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-1.erl @@ -0,0 +1,8 @@ +-module(sort). +-export([insertion/1]). + +insertion(L) -> lists:foldl(fun insert/2, [], L). + +insert(X,[]) -> [X]; +insert(X,L=[H|_]) when X =< H -> [X|L]; +insert(X,[H|T]) -> [H|insert(X, T)]. diff --git a/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-2.erl b/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-2.erl new file mode 100644 index 0000000000..fd47c53541 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Erlang/sorting-algorithms-insertion-sort-2.erl @@ -0,0 +1,4 @@ +1> c(sort). +{ok,sort} +2> sort:insertion([5,3,9,4,1,6,8,2,7]). +[1,2,3,4,5,6,7,8,9] diff --git a/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.euphoria b/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.euphoria new file mode 100644 index 0000000000..33f8e96f1e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.euphoria @@ -0,0 +1,22 @@ +function insertion_sort(sequence s) + object temp + integer j + for i = 2 to length(s) do + temp = s[i] + j = i-1 + while j >= 1 and compare(s[j],temp) > 0 do + s[j+1] = s[j] + j -= 1 + end while + s[j+1] = temp + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,insertion_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Insertion-sort/Forth/sorting-algorithms-insertion-sort.fth b/Task/Sorting-algorithms-Insertion-sort/Forth/sorting-algorithms-insertion-sort.fth new file mode 100644 index 0000000000..fb1a119a1c --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Forth/sorting-algorithms-insertion-sort.fth @@ -0,0 +1,18 @@ +: insert ( start end -- start ) + dup @ >r ( r: v ) \ v = a[i] + begin + 2dup < \ j>0 + while + r@ over cell- @ < \ a[j-1] > v + while + cell- \ j-- + dup @ over cell+ ! \ a[j] = a[j-1] + repeat then + r> swap ! ; \ a[j] = v + +: sort ( array len -- ) + 1 ?do dup i cells + insert loop drop ; + +create test 7 , 3 , 0 , 2 , 9 , 1 , 6 , 8 , 4 , 5 , +test 10 sort +test 10 cells dump diff --git a/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-1.f b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-1.f new file mode 100644 index 0000000000..96067cab27 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-1.f @@ -0,0 +1,15 @@ +PURE SUBROUTINE Insertion_Sort(a) + REAL, INTENT(in out), DIMENSION(:) :: a + REAL :: temp + INTEGER :: i, j + + DO i = 2, SIZE(a) + j = i - 1 + temp = a(i) + DO WHILE (j>=1 .AND. a(j)>temp) + a(j+1) = a(j) + j = j - 1 + END DO + a(j+1) = temp + END DO +END SUBROUTINE Insertion_Sort diff --git a/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-2.f b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-2.f new file mode 100644 index 0000000000..ee133d83a8 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-2.f @@ -0,0 +1,7 @@ +DO i = 2, SIZE(a) + j = i - 1 + DO WHILE (j>=1 .AND. a(j) > a(i)) + j = j - 1 + END DO + a(j+1:i) = cshift(a(j+1:i),-1) +END DO diff --git a/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-3.f b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-3.f new file mode 100644 index 0000000000..727dc94751 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Fortran/sorting-algorithms-insertion-sort-3.f @@ -0,0 +1,14 @@ + SUBROUTINE SORT(N,A) + IMPLICIT NONE + INTEGER N,I,J + DOUBLE PRECISION A(N),X + DO 30 I=2,N + X=A(I) + J=I + 10 J=J-1 + IF(J.EQ.0 .OR. A(J).LE.X) GO TO 20 + A(J+1)=A(J) + GO TO 10 + 20 A(J+1)=X + 30 CONTINUE + END diff --git a/Task/Sorting-algorithms-Insertion-sort/GAP/sorting-algorithms-insertion-sort.gap b/Task/Sorting-algorithms-Insertion-sort/GAP/sorting-algorithms-insertion-sort.gap new file mode 100644 index 0000000000..8ea81dd042 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/GAP/sorting-algorithms-insertion-sort.gap @@ -0,0 +1,18 @@ +InsertionSort := function(L) + local n, i, j, x; + n := Length(L); + for i in [ 2 .. n ] do + x := L[i]; + j := i - 1; + while j >= 1 and L[j] > x do + L[j + 1] := L[j]; + j := j - 1; + od; + L[j + 1] := x; + od; +end; + +s := "BFKRIMPOQACNESWUTXDGLVZHYJ"; +InsertionSort(s); +s; +# "ABCDEFGHIJKLMNOPQRSTUVWXYZ" diff --git a/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-1.go b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-1.go new file mode 100644 index 0000000000..92a003ed63 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-1.go @@ -0,0 +1,23 @@ +package main + +import "fmt" + +func insertionSort(a []int) { + for i := 1; i < len(a); i++ { + value := a[i] + j := i - 1 + for j >= 0 && a[j] > value { + a[j+1] = a[j] + j = j - 1 + } + a[j+1] = value + } +} + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + insertionSort(list) + fmt.Println("sorted! ", list) +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-2.go b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-2.go new file mode 100644 index 0000000000..17d0dba642 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-2.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "sort" +) + +func insertionSort(a sort.Interface) { + for i := 1; i < a.Len(); i++ { + for j := i; j > 0 && a.Less(j, j-1); j-- { + a.Swap(j-1, j) + } + } +} + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + insertionSort(sort.IntSlice(list)) + fmt.Println("sorted! ", list) +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-3.go b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-3.go new file mode 100644 index 0000000000..2ef890f855 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Go/sorting-algorithms-insertion-sort-3.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "sort" +) + +func insertionSort(a []int) { + for i := 1; i < len(a); i++ { + value := a[i] + j := sort.Search(i, func(k int) bool { return a[k] > value }) + copy(a[j+1:i+1], a[j:i]) + a[j] = value + } +} + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + insertionSort(list) + fmt.Println("sorted! ", list) +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-1.groovy b/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-1.groovy new file mode 100644 index 0000000000..eeb673ea96 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-1.groovy @@ -0,0 +1,13 @@ +def insertionSort = { list -> + + def size = list.size() + (1..<size).each { i -> + def value = list[i] + def j = i - 1 + for (; j >= 0 && list[j] > value; j--) { + print "."; list[j+1] = list[j] + } + print "."; list[j+1] = value + } + list +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-2.groovy b/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-2.groovy new file mode 100644 index 0000000000..000ab50c45 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Groovy/sorting-algorithms-insertion-sort-2.groovy @@ -0,0 +1,2 @@ +println (insertionSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (insertionSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) diff --git a/Task/Sorting-algorithms-Insertion-sort/Haskell/sorting-algorithms-insertion-sort.hs b/Task/Sorting-algorithms-Insertion-sort/Haskell/sorting-algorithms-insertion-sort.hs new file mode 100644 index 0000000000..5fe1292889 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Haskell/sorting-algorithms-insertion-sort.hs @@ -0,0 +1,8 @@ +import Data.List (insert) + +insertionSort :: Ord a => [a] -> [a] +insertionSort = foldr insert [] + +-- Example use: +-- *Main> insertionSort [6,8,5,9,3,2,1,4,7] +-- [1,2,3,4,5,6,7,8,9] diff --git a/Task/Sorting-algorithms-Insertion-sort/HicEst/sorting-algorithms-insertion-sort.hicest b/Task/Sorting-algorithms-Insertion-sort/HicEst/sorting-algorithms-insertion-sort.hicest new file mode 100644 index 0000000000..b6e383ce00 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/HicEst/sorting-algorithms-insertion-sort.hicest @@ -0,0 +1,12 @@ +DO i = 2, LEN(A) + value = A(i) + j = i - 1 + 1 IF( j > 0 ) THEN + IF( A(j) > value ) THEN + A(j+1) = A(j) + j = j - 1 + GOTO 1 ! no WHILE in HicEst + ENDIF + ENDIF + A(j+1) = value +ENDDO diff --git a/Task/Sorting-algorithms-Insertion-sort/Icon/sorting-algorithms-insertion-sort.icon b/Task/Sorting-algorithms-Insertion-sort/Icon/sorting-algorithms-insertion-sort.icon new file mode 100644 index 0000000000..b750a12e38 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Icon/sorting-algorithms-insertion-sort.icon @@ -0,0 +1,17 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(insertionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure insertionsort(X,op) #: return sorted X +local i,temp + + op := sortop(op,X) # select how and what we sort + + every i := 2 to *X do { + temp := X[j := i] + while op(temp,X[1 <= (j -:= 1)]) do + X[j+1] := X[j] + X[j+1] := temp + } + return X +end diff --git a/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-1.io b/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-1.io new file mode 100644 index 0000000000..aefe5f6b29 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-1.io @@ -0,0 +1,17 @@ +List do( + insertionSortInPlace := method( + for(j, 1, size - 1, + key := at(j) + i := j - 1 + + while(i >= 0 and at(i) > key, + atPut(i + 1, at(i)) + i = i - 1 + ) + atPut(i + 1, key) + ) + ) +) + +lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) +lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) diff --git a/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-2.io b/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-2.io new file mode 100644 index 0000000000..dc871facab --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Io/sorting-algorithms-insertion-sort-2.io @@ -0,0 +1,13 @@ +List do( + insertionSortInPlace := method( + # In fact, we could've done slice(1, size - 1) foreach(...) + # but creating a new list in memory can only make it worse. + foreach(idx, key, + newidx := slice(0, idx) map(x, x > key) indexOf(true) + if(newidx, insertAt(removeAt(idx), newidx)) + ) + self) +) + +lst := list(7, 6, 5, 9, 8, 4, 3, 1, 2, 0) +lst insertionSortInPlace println # ==> list(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) diff --git a/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-1.j b/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-1.j new file mode 100644 index 0000000000..a834a6b521 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-1.j @@ -0,0 +1 @@ +isort=:((>: # ]) , [ , < #])/ diff --git a/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-2.j b/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-2.j new file mode 100644 index 0000000000..370932673d --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/J/sorting-algorithms-insertion-sort-2.j @@ -0,0 +1,2 @@ + isort 32 4 1 34 95 3 2 120 _38 +_38 1 2 3 4 32 34 95 120 diff --git a/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-1.java b/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-1.java new file mode 100644 index 0000000000..9dc95ddd16 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-1.java @@ -0,0 +1,11 @@ +public static void insertSort(int[] A){ + for(int i = 1; i < A.length; i++){ + int value = A[i]; + int j = i - 1; + while(j >= 0 && A[j] > value){ + A[j + 1] = A[j]; + j = j - 1; + } + A[j + 1] = value; + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-2.java b/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-2.java new file mode 100644 index 0000000000..abad35fb9b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Java/sorting-algorithms-insertion-sort-2.java @@ -0,0 +1,14 @@ +public static <E extends Comparable<? super E>> void insertionSort(List<E> a) { + for (int i = 1; i < a.size(); i++) { + int j = Math.abs(Collections.binarySearch(a.subList(0, i), a.get(i)) + 1); + Collections.rotate(a.subList(j, i+1), j - i); + } +} +public static <E extends Comparable<? super E>> void insertionSort(E[] a) { + for (int i = 1; i < a.length; i++) { + E x = a[i]; + int j = Math.abs(Arrays.binarySearch(a, 0, i, x) + 1); + System.arraycopy(a, j, a, j+1, i-j); + a[j] = x; + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/JavaScript/sorting-algorithms-insertion-sort.js b/Task/Sorting-algorithms-Insertion-sort/JavaScript/sorting-algorithms-insertion-sort.js new file mode 100644 index 0000000000..292376f34b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/JavaScript/sorting-algorithms-insertion-sort.js @@ -0,0 +1,13 @@ +function insertionSort (a) { + for (var i = 0; i < a.length; i++) { + var k = a[i]; + for (var j = i; j > 0 && k < a[j - 1]; j--) + a[j] = a[j - 1]; + a[j] = k; + } + return a; +} + +var a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; +insertionSort(a); +document.write(a.join(" ")); diff --git a/Task/Sorting-algorithms-Insertion-sort/Liberty-BASIC/sorting-algorithms-insertion-sort.liberty b/Task/Sorting-algorithms-Insertion-sort/Liberty-BASIC/sorting-algorithms-insertion-sort.liberty new file mode 100644 index 0000000000..1c22dda859 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Liberty-BASIC/sorting-algorithms-insertion-sort.liberty @@ -0,0 +1,31 @@ + itemCount = 20 + dim A(itemCount) + for i = 1 to itemCount + A(i) = int(rnd(1) * 100) + next i + + print "Before Sort" + gosub [printArray] + +'--- Insertion sort algorithm + for i = 2 to itemCount + value = A(i) + j = i-1 + while j >= 0 and A(j) > value + A(j+1) = A(j) + j = j-1 + wend + A(j+1) = value + next +'--- end of (Insertion sort algorithm) + + print "After Sort" + gosub [printArray] +end + +[printArray] + for i = 1 to itemCount + print using("###", A(i)); + next i + print +return diff --git a/Task/Sorting-algorithms-Insertion-sort/Lua/sorting-algorithms-insertion-sort.lua b/Task/Sorting-algorithms-Insertion-sort/Lua/sorting-algorithms-insertion-sort.lua new file mode 100644 index 0000000000..6857e66b31 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Lua/sorting-algorithms-insertion-sort.lua @@ -0,0 +1,16 @@ +function bins(tb, val, st, en) + local st, en = st or 1, en or #tb + local mid = math.floor((st + en)/2) + if en == st then return tb[st] > val and st or st+1 + else return tb[mid] > val and bins(tb, val, st, mid) or bins(tb, val, mid+1, en) + end +end +function isort(t) + local ret = {t[1], t[2]} + for i = 3, #t do + table.insert(ret, bins(ret, t[i]), t[i]) + end + return ret +end + +print(unpack(isort{4,5,2,7,8,3})) diff --git a/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-1.m b/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-1.m new file mode 100644 index 0000000000..40b2c6168f --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-1.m @@ -0,0 +1,16 @@ +function list = insertionSort(list) + + for i = (2:numel(list)) + + value = list(i); + j = i - 1; + + while (j >= 1) && (list(j) > value) + list(j+1) = list(j); + j = j-1; + end + + list(j+1) = value; + + end %for +end %insertionSort diff --git a/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-2.m b/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-2.m new file mode 100644 index 0000000000..b3eb109f51 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/MATLAB/sorting-algorithms-insertion-sort-2.m @@ -0,0 +1,5 @@ +>> insertionSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Insertion-sort/Mathematica/sorting-algorithms-insertion-sort.math b/Task/Sorting-algorithms-Insertion-sort/Mathematica/sorting-algorithms-insertion-sort.math new file mode 100644 index 0000000000..3a60fd0aa7 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Mathematica/sorting-algorithms-insertion-sort.math @@ -0,0 +1,7 @@ +insertionSort[a_List] := Module[{A = a}, + For[i = 2, i <= Length[A], i++, + value = A[[i]]; j = i - 1; + While[j >= 1 && A[[j]] > value, A[[j + 1]] = A[[j]]; j--;]; + A[[j + 1]] = value;]; +A +] diff --git a/Task/Sorting-algorithms-Insertion-sort/Maxima/sorting-algorithms-insertion-sort.maxima b/Task/Sorting-algorithms-Insertion-sort/Maxima/sorting-algorithms-insertion-sort.maxima new file mode 100644 index 0000000000..daed885799 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Maxima/sorting-algorithms-insertion-sort.maxima @@ -0,0 +1,12 @@ +insertion_sort(u) := block( + [n: length(u), x, j], + for i from 2 thru n do ( + x: u[i], + j: i - 1, + while j >= 1 and u[j] > x do ( + u[j + 1]: u[j], + j: j - 1 + ), + u[j + 1]: x + ) +)$ diff --git a/Task/Sorting-algorithms-Insertion-sort/Modula-3/sorting-algorithms-insertion-sort.mod3 b/Task/Sorting-algorithms-Insertion-sort/Modula-3/sorting-algorithms-insertion-sort.mod3 new file mode 100644 index 0000000000..24cf007297 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Modula-3/sorting-algorithms-insertion-sort.mod3 @@ -0,0 +1,16 @@ +MODULE InsertSort; + +PROCEDURE IntSort(VAR item: ARRAY OF INTEGER) = + VAR j, value: INTEGER; + BEGIN + FOR i := FIRST(item) + 1 TO LAST(item) DO + value := item[i]; + j := i - 1; + WHILE j >= FIRST(item) AND item[j] > value DO + item[j + 1] := item[j]; + DEC(j); + END; + item[j + 1] := value; + END; + END IntSort; +END InsertSort. diff --git a/Task/Sorting-algorithms-Insertion-sort/Nemerle/sorting-algorithms-insertion-sort.nemerle b/Task/Sorting-algorithms-Insertion-sort/Nemerle/sorting-algorithms-insertion-sort.nemerle new file mode 100644 index 0000000000..a3dd5e8259 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Nemerle/sorting-algorithms-insertion-sort.nemerle @@ -0,0 +1,27 @@ +using System.Console; +using Nemerle.English; + +module InsertSort +{ + public static Sort(this a : array[int]) : void + { + mutable value = 0; mutable j = 0; + foreach (i in [1 .. (a.Length - 1)]) + { + value = a[i]; j = i - 1; + while (j >= 0 and a[j] > value) + { + a[j + 1] = a[j]; + j = j - 1; + } + a[j + 1] = value; + } + } + + Main() : void + { + def arr = array[1, 4, 8, 3, 8, 3, 5, 2, 6]; + arr.Sort(); + foreach (i in arr) Write($"$i "); + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/NetRexx/sorting-algorithms-insertion-sort.netrexx b/Task/Sorting-algorithms-Insertion-sort/NetRexx/sorting-algorithms-insertion-sort.netrexx new file mode 100644 index 0000000000..a72b3f41ba --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/NetRexx/sorting-algorithms-insertion-sort.netrexx @@ -0,0 +1,47 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] + +lists = [ - + placesList - + , insertionSort(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method insertionSort(A = String[]) public constant binary returns String[] + + rl = String[A.length] + al = List insertionSort(Arrays.asList(A)) + al.toArray(rl) + + return rl + +method insertionSort(A = List) public constant binary returns ArrayList + + loop i_ = 1 to A.size - 1 + value = A.get(i_) + j_ = i_ - 1 + loop label j_ while j_ >= 0 + if (Comparable A.get(j_)).compareTo(Comparable value) <= 0 then leave j_ + A.set(j_ + 1, A.get(j_)) + j_ = j_ - 1 + end j_ + A.set(j_ + 1, value) + end i_ + + return ArrayList(A) diff --git a/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml b/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml new file mode 100644 index 0000000000..1a17698bc3 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml @@ -0,0 +1,9 @@ +let rec insert x = function + [] -> [x] +| y :: ys -> + if x <= y then x :: y :: ys + else y :: insert x ys +;; +let insertion_sort lst = List.fold_right insert lst [];; + +insertion_sort [6;8;5;9;3;2;1;4;7];; diff --git a/Task/Sorting-algorithms-Insertion-sort/Objeck/sorting-algorithms-insertion-sort.objeck b/Task/Sorting-algorithms-Insertion-sort/Objeck/sorting-algorithms-insertion-sort.objeck new file mode 100644 index 0000000000..3866756b48 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Objeck/sorting-algorithms-insertion-sort.objeck @@ -0,0 +1,23 @@ +bundle Default { + class Insert { + function : Main(args : String[]) ~ Nil { + values := [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10]; + InsertionSort(values); + each(i : values) { + values[i]->PrintLine(); + }; + } + + function : InsertionSort (a : Int[]) ~ Nil { + each(i : a) { + value := a[i]; + j := i - 1; + while(j >= 0 & a[j] > value) { + a[j + 1] := a[j]; + j -= 1; + }; + a[j + 1] := value; + }; + } + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Oz/sorting-algorithms-insertion-sort.oz b/Task/Sorting-algorithms-Insertion-sort/Oz/sorting-algorithms-insertion-sort.oz new file mode 100644 index 0000000000..febdb7ddcf --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Oz/sorting-algorithms-insertion-sort.oz @@ -0,0 +1,21 @@ +declare + proc {InsertionSort A} + Low = {Array.low A} + High = {Array.high A} + in + for I in Low+1..High do + Value = A.I + J = {NewCell I-1} + in + for while:@J >= Low andthen A.@J > Value do + A.(@J+1) := A.@J + J := @J - 1 + end + A.(@J+1) := Value + end + end + + Arr = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} +in + {InsertionSort Arr} + {Show {Array.toRecord unit Arr}} diff --git a/Task/Sorting-algorithms-Insertion-sort/PARI-GP/sorting-algorithms-insertion-sort.pari b/Task/Sorting-algorithms-Insertion-sort/PARI-GP/sorting-algorithms-insertion-sort.pari new file mode 100644 index 0000000000..4815078de1 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PARI-GP/sorting-algorithms-insertion-sort.pari @@ -0,0 +1,11 @@ +insertionSort(v)={ + for(i=1,#v-1, + my(j=i-1,x=v[i]); + while(j && v[j]>x, + v[j+1]=v[j]; + j-- + ); + v[j+1]=x + ); + v +}; diff --git a/Task/Sorting-algorithms-Insertion-sort/PHP/sorting-algorithms-insertion-sort.php b/Task/Sorting-algorithms-Insertion-sort/PHP/sorting-algorithms-insertion-sort.php new file mode 100644 index 0000000000..8b321db26e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PHP/sorting-algorithms-insertion-sort.php @@ -0,0 +1,15 @@ +function insertionSort(&$arr){ + for($i=0;$i<count($arr);$i++){ + $val = $arr[$i]; + $j = $i-1; + while($j>=0 && $arr[$j] > $val){ + $arr[$j+1] = $arr[$j]; + $j--; + } + $arr[$j+1] = $val; + } +} + +$arr = array(4,2,1,6,9,3,8,7); +insertionSort($arr); +echo implode(',',$arr); diff --git a/Task/Sorting-algorithms-Insertion-sort/PL-I/sorting-algorithms-insertion-sort.pli b/Task/Sorting-algorithms-Insertion-sort/PL-I/sorting-algorithms-insertion-sort.pli new file mode 100644 index 0000000000..86cf34574b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PL-I/sorting-algorithms-insertion-sort.pli @@ -0,0 +1,16 @@ +INSSORT: PROCEDURE (A); + DCL A(*) FIXED BIN(31); + DCL (I, J, V, N) FIXED BIN(31); + + N = HBOUND(A,1); M = LBOUND(A,1); + DO I=M+1 TO N; + V=A(I); + J=I-1; + DO WHILE (J > M-1); + if A(J) <= V then leave; + A(J+1)=A(J); J=J-1; + END; + A(J+1)=V; + END; + RETURN; +END INSSORT; diff --git a/Task/Sorting-algorithms-Insertion-sort/Perl-6/sorting-algorithms-insertion-sort.pl6 b/Task/Sorting-algorithms-Insertion-sort/Perl-6/sorting-algorithms-insertion-sort.pl6 new file mode 100644 index 0000000000..3df1adf1f8 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Perl-6/sorting-algorithms-insertion-sort.pl6 @@ -0,0 +1,15 @@ +sub insertion_sort ( @a is copy ) { + for 1 .. @a.end -> $i { + my $value = @a[$i]; + my $j; + loop ( $j = $i-1; $j >= 0 and @a[$j] > $value; $j-- ) { + @a[$j+1] = @a[$j]; + } + @a[$j+1] = $value; + } + return @a; +} + +my @data = 22, 7, 2, -5, 8, 4; +say 'input = ' ~ @data; +say 'output = ' ~ @data.&insertion_sort; diff --git a/Task/Sorting-algorithms-Insertion-sort/Perl/sorting-algorithms-insertion-sort.pl b/Task/Sorting-algorithms-Insertion-sort/Perl/sorting-algorithms-insertion-sort.pl new file mode 100644 index 0000000000..8590b0e6d7 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Perl/sorting-algorithms-insertion-sort.pl @@ -0,0 +1,16 @@ +sub insertion_sort { + my (@list) = @_; + foreach my $i (1 .. $#list) { + my $j = $i; + my $k = $list[$i]; + while ( $j > 0 && $k < $list[$j - 1]) { + $list[$j] = $list[$j - 1]; + $j--; + } + $list[$j] = $k; + } + return @list; +} + +my @a = insertion_sort(4, 65, 2, -31, 0, 99, 83, 782, 1); +print "@a\n"; diff --git a/Task/Sorting-algorithms-Insertion-sort/PicoLisp/sorting-algorithms-insertion-sort.l b/Task/Sorting-algorithms-Insertion-sort/PicoLisp/sorting-algorithms-insertion-sort.l new file mode 100644 index 0000000000..6263916907 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PicoLisp/sorting-algorithms-insertion-sort.l @@ -0,0 +1,6 @@ +(de insertionSort (Lst) + (for (I (cdr Lst) I (cdr I)) + (for (J Lst (n== J I) (cdr J)) + (T (> (car J) (car I)) + (rot J (offset I J)) ) ) ) + Lst ) diff --git a/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-1.pro b/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-1.pro new file mode 100644 index 0000000000..03d7116522 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-1.pro @@ -0,0 +1,14 @@ +insert_sort(L1,L2) :- + insert_sort_intern(L1,[],L2). + +insert_sort_intern([],L,L). +insert_sort_intern([H|T],L1,L) :- + insert(L1,H,L2), + insert_sort_intern(T,L2,L). + +insert([],X,[X]). +insert([H|T],X,[X,H|T]) :- + X =< H, + !. +insert([H|T],X,[H|T2]) :- + insert(T,X,T2). diff --git a/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-2.pro b/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-2.pro new file mode 100644 index 0000000000..8a04183d91 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Prolog/sorting-algorithms-insertion-sort-2.pro @@ -0,0 +1,19 @@ +% insertion sort +isort(L, LS) :- + foldl(insert, [], L, LS). + + +% foldl(Pred, Init, List, R). +foldl(_Pred, Val, [], Val). +foldl(Pred, Val, [H | T], Res) :- + call(Pred, Val, H, Val1), + foldl(Pred, Val1, T, Res). + +% insertion in a sorted list +insert([], N, [N]). + +insert([H | T], N, [N, H|T]) :- + N =< H, !. + +insert([H | T], N, [H|L1]) :- + insert(T, N, L1). diff --git a/Task/Sorting-algorithms-Insertion-sort/PureBasic/sorting-algorithms-insertion-sort.purebasic b/Task/Sorting-algorithms-Insertion-sort/PureBasic/sorting-algorithms-insertion-sort.purebasic new file mode 100644 index 0000000000..68c59a59f7 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PureBasic/sorting-algorithms-insertion-sort.purebasic @@ -0,0 +1,20 @@ +Procedure insertionSort(Array a(1)) + Protected low, high + Protected firstIndex, lastIndex = ArraySize(a()) + + If lastIndex > firstIndex + 1 + low = firstIndex + 1 + While low <= lastIndex + high = low + While high > firstIndex + If a(high) < a(high - 1) + Swap a(high), a(high - 1) + Else + Break + EndIf + high - 1 + Wend + low + 1 + Wend + EndIf +EndProcedure diff --git a/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-1.py b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-1.py new file mode 100644 index 0000000000..44a5c38e86 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-1.py @@ -0,0 +1,8 @@ +def insertion_sort(l): + for i in xrange(1, len(l)): + j = i-1 + key = l[i] + while (l[j] > key) and (j >= 0): + l[j+1] = l[j] + j -= 1 + l[j+1] = key diff --git a/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-2.py b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-2.py new file mode 100644 index 0000000000..9d8911ffab --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-2.py @@ -0,0 +1,15 @@ +def insertion_sort_bin(seq): + for i in range(1, len(seq)): + key = seq[i] + # invariant: ``seq[:i]`` is sorted + # find the least `low' such that ``seq[low]`` is not less then `key'. + # Binary search in sorted sequence ``seq[low:up]``: + low, up = 0, i + while up > low: + middle = (low + up) // 2 + if seq[middle] < key: + low = middle + 1 + else: + up = middle + # insert key at position ``low`` + seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:] diff --git a/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-3.py b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-3.py new file mode 100644 index 0000000000..99bcf04a5b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Python/sorting-algorithms-insertion-sort-3.py @@ -0,0 +1,4 @@ +import bisect +def insertion_sort_bin(seq): + for i in range(1, len(seq)): + bisect.insort(seq, seq.pop(i), 0, i) diff --git a/Task/Sorting-algorithms-Insertion-sort/Qi/sorting-algorithms-insertion-sort.qi b/Task/Sorting-algorithms-Insertion-sort/Qi/sorting-algorithms-insertion-sort.qi new file mode 100644 index 0000000000..a29b78c4ea --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Qi/sorting-algorithms-insertion-sort.qi @@ -0,0 +1,10 @@ +(define insert + X [] -> [X] + X [Y|Ys] -> [X Y|Ys] where (<= X Y) + X [Y|Ys] -> [Y|(insert X Ys)]) + +(define insertion-sort + [] -> [] + [X|Xs] -> (insert X (insertion-sort Xs))) + +(insertion-sort [6 8 5 9 3 2 1 4 7]) diff --git a/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort.r b/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort.r new file mode 100644 index 0000000000..9603ade853 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort.r @@ -0,0 +1,16 @@ +insertionsort <- function(x) +{ + for(i in 2:(length(x))) + { + value <- x[i] + j <- i - 1 + while(j >= 1 && x[j] > value) + { + x[j+1] <- x[j] + j <- j-1 + } + x[j+1] <- value + } + x +} +insertionsort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782 diff --git a/Task/Sorting-algorithms-Insertion-sort/REALbasic/sorting-algorithms-insertion-sort.realbasic b/Task/Sorting-algorithms-Insertion-sort/REALbasic/sorting-algorithms-insertion-sort.realbasic new file mode 100644 index 0000000000..b84e88882c --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/REALbasic/sorting-algorithms-insertion-sort.realbasic @@ -0,0 +1,11 @@ +Sub InsertionSort(theList() as Integer) + for insertionElementIndex as Integer = 1 to UBound(theList) + dim insertionElement as Integer = theList(insertionElementIndex) + dim j as Integer = insertionElementIndex - 1 + while (j >= 0) and (insertionElement < theList(j)) + theList(j + 1) = theList(j) + j = j - 1 + wend + theList(j + 1) = insertionElement + next +End Sub diff --git a/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx new file mode 100644 index 0000000000..a99a1b05b2 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx @@ -0,0 +1,38 @@ +/*REXX program sorts a stemmed array using the insertion-sort method.*/ +call gen@ /*generate the array's elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call insertionSort highItem /*invoke the insertion sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign default value to array. */ +@.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" +@.2 = "Monday's child is fair of face;" +@.3 = "Tuesday's child is full of grace;" +@.4 = "Wednesday's child is full of woe;" +@.5 = "Thursday's child has far to go;" +@.6 = "Friday's child is loving and giving;" +@.7 = "Saturday's child works hard for a living;" +@.8 = "But the child that is born on the Sabbath day" +@.9 = "Is blithe and bonny, good and gay." + do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ + end /*short and sweet DO loop, eh? */ +highItem=highItem-1 /*because of DO, adjust highItem.*/ +return +/*──────────────────────────────────INSERTIONSORT subroutine────────────*/ +insertionSort: procedure expose @.; parse arg highItem + do i=2 to highItem; value=@.i + do j=i-1 by -1 while j\==0 & @.j>value + jp=j+1; @.jp=@.j + end /*j*/ + jp=j+1 + @.jp=value + end /*i*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(highItem) /*the 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 that fits*/ +return diff --git a/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt b/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt new file mode 100644 index 0000000000..164fca7e69 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt @@ -0,0 +1,13 @@ +(require racket/match) + +(define (sort pred l) + (define (insert x y) + (match (list x y) + [(list x '()) (list x)] + [(list x (cons y ys)) + (if (pred x y) + (cons x (cons y ys)) + (cons y (f x ys)))])) + (match l + ['() '()] + [(cons x xs) (insert x (sort pred xs))])) diff --git a/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-1.rascal b/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-1.rascal new file mode 100644 index 0000000000..a4254e5da2 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-1.rascal @@ -0,0 +1,14 @@ +import List; + +public list[int] insertionSort(a){ + for(i <- [0..size(a)-1]){ + v = a[i]; + j = i-1; + while(j >= 0 && a[j] > v){ + a[j+1] = a[j]; + j -= 1; + } + a[j+1] = v; + } + return a; +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-2.rascal b/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-2.rascal new file mode 100644 index 0000000000..eab9d3c47e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Rascal/sorting-algorithms-insertion-sort-2.rascal @@ -0,0 +1,2 @@ +rascal>rascal>insertionSort([4, 65, 2, -31, 0, 99, 83, 782, 1]) +list[int]: [-31,0,1,2,4,65,83,99,782] diff --git a/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-1.rb b/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-1.rb new file mode 100644 index 0000000000..1e3f4bdfb0 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-1.rb @@ -0,0 +1,17 @@ +class Array + def insertionsort! + 1.upto(length - 1) do |i| + value = self[i] + j = i - 1 + while j >= 0 and self[j] > value + self[j+1] = self[j] + j -= 1 + end + self[j+1] = value + end + self + end +end +ary = [7,6,5,9,8,4,3,1,2,0] +ary.insertionsort! +# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-2.rb b/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-2.rb new file mode 100644 index 0000000000..f8b13edd28 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ruby/sorting-algorithms-insertion-sort-2.rb @@ -0,0 +1,17 @@ +class Array + def insertionsort! + return if length < 2 + + 1.upto(length - 1) do |i| + value = delete_at i + j = i - 1 + j -= 1 while j >= 0 && value < self[j] + insert(j + 1, value) + end + self + end +end + +ary = [7,6,5,9,8,4,3,1,2,0] +ary.insertionsort! +# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Insertion-sort/Run-BASIC/sorting-algorithms-insertion-sort.run b/Task/Sorting-algorithms-Insertion-sort/Run-BASIC/sorting-algorithms-insertion-sort.run new file mode 100644 index 0000000000..34a23908cd --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Run-BASIC/sorting-algorithms-insertion-sort.run @@ -0,0 +1,31 @@ +dim insSort(100) +sortEnd = 0 +global inSort +global sortEnd + +' -- insert some random numbers -- + +for i = 1 to 20 + a = int(1000 * rnd(1)) + x = insertSort(a) +next i + +' --- Print the Sorted Data ----- + +print "End Sort:";sortEnd ' number sorted +for i = 1 to sortEnd + print i;" ";insSort(i) ' location and sorted data +next i +wait + +function insertSort(x) ' Insert Sort Function +i = 1 +while x > insSort(i) and i <= sortEnd + i = i + 1 +wend +for j = sortEnd to i step -1 + insSort(j + 1) = insSort(j) +next j +insSort(i) = x +sortEnd = sortEnd + 1 +end function diff --git a/Task/Sorting-algorithms-Insertion-sort/SNOBOL4/sorting-algorithms-insertion-sort.sno b/Task/Sorting-algorithms-Insertion-sort/SNOBOL4/sorting-algorithms-insertion-sort.sno new file mode 100644 index 0000000000..8cec40b4f2 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/SNOBOL4/sorting-algorithms-insertion-sort.sno @@ -0,0 +1,20 @@ +* read data into an array + A = table() + i = 0 +readln A<i = i + 1> = trim(input) :s(readln) + aSize = i - 1 + +* sort array + i = 1 +loop1 value = A<i> + j = i - 1 +loop2 gt(j,0) gt(A<j>,value) :f(done2) + A<j + 1> = A<j> + j = j - 1 :(loop2) +done2 A<j + 1> = value + i = ?lt(i,aSize) i + 1 :s(loop1) + i = 1 + +* output sorted data +while output = A<i>; i = ?lt(i,aSize) i + 1 :s(while) +end diff --git a/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala b/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala new file mode 100644 index 0000000000..24e5d60ccb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala @@ -0,0 +1,4 @@ +def insert(list: List[Int], value: Int) = list.span(_ < value) match { + case (lower, upper) => lower ::: value :: upper +} +def insertSort(list: List[Int]) = list.foldLeft(List[Int]())(insert) diff --git a/Task/Sorting-algorithms-Insertion-sort/Scheme/sorting-algorithms-insertion-sort.ss b/Task/Sorting-algorithms-Insertion-sort/Scheme/sorting-algorithms-insertion-sort.ss new file mode 100644 index 0000000000..ed8f3b6be8 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Scheme/sorting-algorithms-insertion-sort.ss @@ -0,0 +1,16 @@ +(define (insert x lst) + (if (null? lst) + (list x) + (let ((y (car lst)) + (ys (cdr lst))) + (if (<= x y) + (cons x lst) + (cons y (insert x ys)))))) + +(define (insertion-sort lst) + (if (null? lst) + '() + (insert (car lst) + (insertion-sort (cdr lst))))) + +(insertion-sort '(6 8 5 9 3 2 1 4 7)) diff --git a/Task/Sorting-algorithms-Insertion-sort/Seed7/sorting-algorithms-insertion-sort.seed7 b/Task/Sorting-algorithms-Insertion-sort/Seed7/sorting-algorithms-insertion-sort.seed7 new file mode 100644 index 0000000000..bd7e03b5c5 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Seed7/sorting-algorithms-insertion-sort.seed7 @@ -0,0 +1,16 @@ +const proc: insertionSort (inout array elemType: arr) is func + local + var integer: i is 0; + var integer: j is 0; + var elemType: help is elemType.value; + begin + for i range 2 to length(arr) do + j := i; + help := arr[i]; + while j > 1 and arr[pred(j)] > help do + arr[j] := arr[pred(j)]; + decr(j); + end while; + arr[j] := help; + end for; + end func; diff --git a/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml b/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml new file mode 100644 index 0000000000..23f3642627 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Standard-ML/sorting-algorithms-insertion-sort.ml @@ -0,0 +1,10 @@ +fun insertion_sort cmp = let + fun insert (x, []) = [x] + | insert (x, y::ys) = + case cmp (x, y) of GREATER => y :: insert (x, ys) + | _ => x :: y :: ys +in + foldl insert [] +end; + +insertion_sort Int.compare [6,8,5,9,3,2,1,4,7]; diff --git a/Task/Sorting-algorithms-Insertion-sort/Tcl/sorting-algorithms-insertion-sort.tcl b/Task/Sorting-algorithms-Insertion-sort/Tcl/sorting-algorithms-insertion-sort.tcl new file mode 100644 index 0000000000..91225b651e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Tcl/sorting-algorithms-insertion-sort.tcl @@ -0,0 +1,16 @@ +package require Tcl 8.5 + +proc insertionsort {m} { + for {set i 1} {$i < [llength $m]} {incr i} { + set val [lindex $m $i] + set j [expr {$i - 1}] + while {$j >= 0 && [lindex $m $j] > $val} { + lset m [expr {$j + 1}] [lindex $m $j] + incr j -1 + } + lset m [expr {$j + 1}] $val + } + return $m +} + +puts [insertionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-1.unixpipes b/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-1.unixpipes new file mode 100644 index 0000000000..bbabaf6c90 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-1.unixpipes @@ -0,0 +1,4 @@ +selectionsort() { + read a + test -n "$a" && ( selectionsort | sort -nm <(echo $a) -) +} diff --git a/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-2.unixpipes b/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-2.unixpipes new file mode 100644 index 0000000000..c3ea1be707 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/UnixPipes/sorting-algorithms-insertion-sort-2.unixpipes @@ -0,0 +1 @@ +cat to.sort | selectionsort diff --git a/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-1.ursala b/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-1.ursala new file mode 100644 index 0000000000..8d6c63671a --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-1.ursala @@ -0,0 +1,3 @@ +#import nat + +insort = ~&i&& @hNCtX ~&r->lx ^\~&rt nleq-~rlrSPrhlPrSCPTlrShlPNCTPQ@rhPlD diff --git a/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-2.ursala b/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-2.ursala new file mode 100644 index 0000000000..c3d70996e9 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ursala/sorting-algorithms-insertion-sort-2.ursala @@ -0,0 +1,3 @@ +#cast %nL + +example = insort <45,82,69,82,104,58,88,112,89,74> diff --git a/Task/Sorting-algorithms-Insertion-sort/XPL0/sorting-algorithms-insertion-sort.xpl0 b/Task/Sorting-algorithms-Insertion-sort/XPL0/sorting-algorithms-insertion-sort.xpl0 new file mode 100644 index 0000000000..583e350da7 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/XPL0/sorting-algorithms-insertion-sort.xpl0 @@ -0,0 +1,21 @@ +code ChOut=8, IntOut=11; + +proc InsertionSort(A, L); \Sort array A of length L +int A, L; +int I, J, V; +[for I:= 1 to L-1 do + [V:= A(I); + J:= I-1; + while J>=0 and A(J)>V do + [A(J+1):= A(J); + J:= J-1; + ]; + A(J+1):= V; + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +InsertionSort(A, 10); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Insertion-sort/Yorick/sorting-algorithms-insertion-sort.yorick b/Task/Sorting-algorithms-Insertion-sort/Yorick/sorting-algorithms-insertion-sort.yorick new file mode 100644 index 0000000000..14b5a7d7eb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Yorick/sorting-algorithms-insertion-sort.yorick @@ -0,0 +1,11 @@ +func insertionSort(&A) { + for(i = 2; i <= numberof(A); i++) { + value = A(i); + j = i - 1; + while(j >= 1 && A(j) > value) { + A(j+1) = A(j); + j--; + } + A(j+1) = value; + } +} diff --git a/Task/Sorting-algorithms-Merge-sort/0DESCRIPTION b/Task/Sorting-algorithms-Merge-sort/0DESCRIPTION new file mode 100644 index 0000000000..9fa86aaed1 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/0DESCRIPTION @@ -0,0 +1,37 @@ +{{Sorting Algorithm}}[[Category:Recursion]]The '''merge sort''' is a recursive sort of order n*log(n). It is notable for having a worst case and average complexity of ''O(n*log(n))'', and a best case complexity of ''O(n)'' (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups). Then merge the groups back together so that their elements are in order. This is how the algorithm gets its "divide and conquer" description. + +Write a function to sort a collection of integers using the merge sort. The merge sort algorithm comes in two parts: a sort function and a merge function. The functions in pseudocode look like this: + '''function''' ''mergesort''(m) + '''var''' list left, right, result + '''if''' length(m) ≤ 1 + '''return''' m + '''else''' + '''var''' middle = length(m) / 2 + '''for each''' x '''in''' m '''up to''' middle - 1 + '''add''' x '''to''' left + '''for each''' x '''in''' m '''at and after''' middle + '''add''' x '''to''' right + left = mergesort(left) + right = mergesort(right) + '''if''' last(left) ≤ first(right) + '''append''' right '''to''' left + '''return''' left + result = merge(left, right) + '''return''' result + + '''function''' ''merge''(left,right) + '''var''' list result + '''while''' length(left) > 0 and length(right) > 0 + '''if''' first(left) ≤ first(right) + '''append''' first(left) '''to''' result + left = rest(left) + '''else''' + '''append''' first(right) '''to''' result + right = rest(right) + '''if''' length(left) > 0 + '''append''' rest(left) '''to''' result + '''if''' length(right) > 0 + '''append''' rest(right) '''to''' result + '''return''' result + +For more information see [[wp:Merge_sort|Wikipedia]] diff --git a/Task/Sorting-algorithms-Merge-sort/1META.yaml b/Task/Sorting-algorithms-Merge-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Merge-sort/ACL2/sorting-algorithms-merge-sort.acl2 b/Task/Sorting-algorithms-Merge-sort/ACL2/sorting-algorithms-merge-sort.acl2 new file mode 100644 index 0000000000..d70f8139c9 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ACL2/sorting-algorithms-merge-sort.acl2 @@ -0,0 +1,34 @@ +(defun split (xys) + (if (endp (rest xys)) + (mv xys nil) + (mv-let (xs ys) + (split (rest (rest xys))) + (mv (cons (first xys) xs) + (cons (second xys) ys))))) + +(defun mrg (xs ys) + (declare (xargs :measure (+ (len xs) (len ys)))) + (cond ((endp xs) ys) + ((endp ys) xs) + ((< (first xs) (first ys)) + (cons (first xs) (mrg (rest xs) ys))) + (t (cons (first ys) (mrg xs (rest ys)))))) + +(defthm split-shortens + (implies (consp (rest xs)) + (mv-let (ys zs) + (split xs) + (and (< (len ys) (len xs)) + (< (len zs) (len xs)))))) + +(defun msort (xs) + (declare (xargs + :measure (len xs) + :hints (("Goal" + :use ((:instance split-shortens)))))) + (if (endp (rest xs)) + xs + (mv-let (ys zs) + (split xs) + (mrg (msort ys) + (msort zs))))) diff --git a/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-1.alg b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-1.alg new file mode 100644 index 0000000000..1fe74f47f4 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-1.alg @@ -0,0 +1,41 @@ +MODE DATA = CHAR; + +PROC merge sort = ([]DATA m)[]DATA: ( + IF LWB m >= UPB m THEN + m + ELSE + INT middle = ( UPB m + LWB m ) OVER 2; + []DATA left = merge sort(m[:middle]); + []DATA right = merge sort(m[middle+1:]); + flex merge(left, right)[AT LWB m] + FI +); + +# FLEX version: A demonstration of FLEX for manipulating arrays # +PROC flex merge = ([]DATA in left, in right)[]DATA:( + [UPB in left + UPB in right]DATA result; + FLEX[0]DATA left := in left; + FLEX[0]DATA right := in right; + + FOR index TO UPB result DO + # change the direction of this comparison to change the direction of the sort # + IF LWB right > UPB right THEN + result[index:] := left; + stop iteration + ELIF LWB left > UPB left THEN + result[index:] := right; + stop iteration + ELIF left[1] <= right[1] THEN + result[index] := left[1]; + left := left[2:] + ELSE + result[index] := right[1]; + right := right[2:] + FI + OD; +stop iteration: + result +); + +[32]CHAR char array data := "big fjords vex quick waltz nymph"; +print((merge sort(char array data), new line)); diff --git a/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-2.alg b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-2.alg new file mode 100644 index 0000000000..c475876c4c --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-2.alg @@ -0,0 +1,38 @@ +PROC opt merge sort = ([]REF DATA m)[]REF DATA: ( + IF LWB m >= UPB m THEN + m + ELSE + INT middle = ( UPB m + LWB m ) OVER 2; + []REF DATA left = opt merge sort(m[:middle]); + []REF DATA right = opt merge sort(m[middle+1:]); + opt merge(left, right)[AT LWB m] + FI +); + +PROC opt merge = ([]REF DATA left, right)[]REF DATA:( + [UPB left - LWB left + 1 + UPB right - LWB right + 1]REF DATA result; + INT index left:=LWB left, index right:=LWB right; + + FOR index TO UPB result DO + # change the direction of this comparison to change the direction of the sort # + IF index right > UPB right THEN + result[index:] := left[index left:]; + stop iteration + ELIF index left > UPB left THEN + result[index:] := right[index right:]; + stop iteration + ELIF left[index left] <= right[index right] THEN + result[index] := left[index left]; index left +:= 1 + ELSE + result[index] := right[index right]; index right +:= 1 + FI + OD; +stop iteration: + result +); + +# create an array of pointers to the data being sorted # +[UPB char array data]REF DATA data; FOR i TO UPB char array data DO data[i] := char array data[i] OD; + +[]REF CHAR result = opt merge sort(data); +FOR i TO UPB result DO print((result[i])) OD; print(new line) diff --git a/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-3.alg b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-3.alg new file mode 100644 index 0000000000..2fd8e9d3df --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ALGOL-68/sorting-algorithms-merge-sort-3.alg @@ -0,0 +1,63 @@ +#NoEnv + +Test := [] +Loop 100 { + Random n, 0, 999 + Test.Insert(n) +} +Result := MergeSort(Test) +Loop % Result.MaxIndex() { + MsgBox, 1, , % Result[A_Index] + IfMsgBox Cancel + Break +} +Return + + +/* + Function MergeSort + Sorts an array by first recursively splitting it down to its + individual elements and then merging those elements in their + correct order. + + Parameters + Array The array to be sorted + + Returns + The sorted array +*/ +MergeSort(Array) + { + ; Return single element arrays + If (! Array.HasKey(2)) + Return Array + + ; Split array into Left and Right halfs + Left := [], Right := [], Middle := Array.MaxIndex() // 2 + Loop % Middle + Right.Insert(Array.Remove(Middle-- + 1)), Left.Insert(Array.Remove(1)) + If (Array.MaxIndex()) + Right.Insert(Array.Remove(1)) + + Left := MergeSort(Left), Right := MergeSort(Right) + + ; If all the Right values are greater than all the + ; Left values, just append Right at the end of Left. + If (Left[Left.MaxIndex()] <= Right[1]) { + Loop % Right.MaxIndex() + Left.Insert(Right.Remove(1)) + Return Left + } + ; Loop until one of the arrays is empty + While(Left.MaxIndex() and Right.MaxIndex()) + Left[1] <= Right[1] ? Array.Insert(Left.Remove(1)) + : Array.Insert(Right.Remove(1)) + + Loop % Left.MaxIndex() + Array.Insert(Left.Remove(1)) + + Loop % Right.MaxIndex() + Array.Insert(Right.Remove(1)) + + Return Array + } diff --git a/Task/Sorting-algorithms-Merge-sort/ActionScript/sorting-algorithms-merge-sort.as b/Task/Sorting-algorithms-Merge-sort/ActionScript/sorting-algorithms-merge-sort.as new file mode 100644 index 0000000000..52ea9279ef --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ActionScript/sorting-algorithms-merge-sort.as @@ -0,0 +1,50 @@ +function mergesort(a:Array) +{ + //Arrays of length 1 and 0 are always sorted + if(a.length <= 1) return a; + else + { + var middle:uint = a.length/2; + //split the array into two + var left:Array = new Array(middle); + var right:Array = new Array(a.length-middle); + var j:uint = 0, k:uint = 0; + //fill the left array + for(var i:uint = 0; i < middle; i++) + left[j++]=a[i]; + //fill the right array + for(i = middle; i< a.length; i++) + right[k++]=a[i]; + //sort the arrays + left = mergesort(left); + right = mergesort(right); + //If the last element of the left array is less than or equal to the first + //element of the right array, they are in order and don't need to be merged + if(left[left.length-1] <= right[0]) + return left.concat(right); + a = merge(left, right); + return a; + } +} + +function merge(left:Array, right:Array) +{ + var result:Array = new Array(left.length + right.length); + var j:uint = 0, k:uint = 0, m:uint = 0; + //merge the arrays in order + while(j < left.length && k < right.length) + { + if(left[j] <= right[k]) + result[m++] = left[j++]; + else + result[m++] = right[k++]; + } + //If one of the arrays has remaining entries that haven't been merged, they + //will be greater than the rest of the numbers merged so far, so put them on the + //end of the array. + for(; j < left.length; j++) + result[m++] = left[j]; + for(; k < right.length; k++) + result[m++] = right[k]; + return result; +} diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.ada b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.ada new file mode 100644 index 0000000000..c51250af0e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.ada @@ -0,0 +1,9 @@ +generic + type Element_Type is private; + type Index_Type is (<>); + type Collection_Type is array(Index_Type range <>) of Element_Type; + with function "<"(Left, Right : Element_Type) return Boolean is <>; + +package Mergesort is + function Sort(Item : Collection_Type) return Collection_Type; +end MergeSort; diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.ada b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.ada new file mode 100644 index 0000000000..e06335272b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.ada @@ -0,0 +1,62 @@ +package body Mergesort is + + ----------- + -- Merge -- + ----------- + + function Merge(Left, Right : Collection_Type) return Collection_Type is + Result : Collection_Type(Left'First..Right'Last); + Left_Index : Index_Type := Left'First; + Right_Index : Index_Type := Right'First; + Result_Index : Index_Type := Result'First; + begin + while Left_Index <= Left'Last and Right_Index <= Right'Last loop + if Left(Left_Index) <= Right(Right_Index) then + Result(Result_Index) := Left(Left_Index); + Left_Index := Index_Type'Succ(Left_Index); -- increment Left_Index + else + Result(Result_Index) := Right(Right_Index); + Right_Index := Index_Type'Succ(Right_Index); -- increment Right_Index + end if; + Result_Index := Index_Type'Succ(Result_Index); -- increment Result_Index + end loop; + if Left_Index <= Left'Last then + Result(Result_Index..Result'Last) := Left(Left_Index..Left'Last); + end if; + if Right_Index <= Right'Last then + Result(Result_Index..Result'Last) := Right(Right_Index..Right'Last); + end if; + return Result; + end Merge; + + ---------- + -- Sort -- + ---------- + + function Sort (Item : Collection_Type) return Collection_Type is + Result : Collection_Type(Item'range); + Middle : Index_Type; + begin + if Item'Length <= 1 then + return Item; + else + Middle := Index_Type'Val((Item'Length / 2) + Index_Type'Pos(Item'First)); + declare + Left : Collection_Type(Item'First..Index_Type'Pred(Middle)); + Right : Collection_Type(Middle..Item'Last); + begin + for I in Left'range loop + Left(I) := Item(I); + end loop; + for I in Right'range loop + Right(I) := Item(I); + end loop; + Left := Sort(Left); + Right := Sort(Right); + Result := Merge(Left, Right); + end; + return Result; + end if; + end Sort; + +end Mergesort; diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.ada b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.ada new file mode 100644 index 0000000000..892aab5fee --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.ada @@ -0,0 +1,19 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Mergesort; + +procedure Mergesort_Test is + type List_Type is array(Positive range <>) of Integer; + package List_Sort is new Mergesort(Integer, Positive, List_Type); + procedure Print(Item : List_Type) is + begin + for I in Item'range loop + Put(Integer'Image(Item(I))); + end loop; + New_Line; + end Print; + + List : List_Type := (1, 5, 2, 7, 3, 9, 4, 6); +begin + Print(List); + Print(List_Sort.Sort(List)); +end Mergesort_Test; diff --git a/Task/Sorting-algorithms-Merge-sort/AutoHotkey/sorting-algorithms-merge-sort.ahk b/Task/Sorting-algorithms-Merge-sort/AutoHotkey/sorting-algorithms-merge-sort.ahk new file mode 100644 index 0000000000..ed177fd324 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/AutoHotkey/sorting-algorithms-merge-sort.ahk @@ -0,0 +1,37 @@ +MsgBox % MSort("") +MsgBox % MSort("xxx") +MsgBox % MSort("3,2,1") +MsgBox % MSort("dog,000000,cat,pile,abcde,1,zz,xx,z") + +MSort(x) { ; Merge-sort of a comma separated list + If (2 > L:=Len(x)) + Return x ; empty or single item lists are sorted + StringGetPos p, x, `,, % "L" L//2 ; Find middle comma + Return Merge(MSort(SubStr(x,1,p)), MSort(SubStr(x,p+2))) ; Split, Sort, Merge +} + +Len(list) { + StringReplace t, list,`,,,UseErrorLevel ; #commas -> ErrorLevel + Return list="" ? 0 : ErrorLevel+1 +} + +Item(list,ByRef p) { ; item at position p, p <- next position + Return (p := InStr(list,",",0,i:=p+1)) ? SubStr(list,i,p-i) : SubStr(list,i) +} + +Merge(list0,list1) { ; Merge 2 sorted lists + IfEqual list0,, Return list1 + IfEqual list1,, Return list0 + i0 := Item(list0,p0:=0) + i1 := Item(list1,p1:=0) + Loop { + i := i0>i1 + list .= "," i%i% ; output smaller + If (p%i%) + i%i% := Item(list%i%,p%i%) ; get next item from processed list + Else { + i ^= 1 ; list is exhausted: attach rest of other + Return SubStr(list "," i%i% (p%i% ? "," SubStr(list%i%,p%i%+1) : ""), 2) + } + } +} diff --git a/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-1.bbc b/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-1.bbc new file mode 100644 index 0000000000..d6bce12d6d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-1.bbc @@ -0,0 +1,56 @@ +DEFPROC_MergeSort(Start%,End%) +REM ***************************************************************** +REM This procedure Merge Sorts the chunk of data% bounded by +REM Start% & End%. +REM ***************************************************************** + +LOCAL Middle% +IF End%=Start% ENDPROC + +IF End%-Start%=1 THEN + IF data%(End%)<data%(Start%) THEN + SWAP data%(Start%),data%(End%) + ENDIF + ENDPROC +ENDIF + +Middle%=Start%+(End%-Start%)/2 + +PROC_MergeSort(Start%,Middle%) +PROC_MergeSort(Middle%+1,End%) +PROC_Merge(Start%,Middle%,End%) + +ENDPROC +: +DEF PROC_Merge(Start%,Middle%,End%) + +LOCAL fh_size% +fh_size% = Middle%-Start%+1 + +FOR I%=0 TO fh_size%-1 + fh%(I%)=data%(Start%+I%) +NEXT I% + +I%=0 +J%=Middle%+1 +K%=Start% + +REPEAT + IF fh%(I%) <= data%(J%) THEN + data%(K%)=fh%(I%) + I%+=1 + K%+=1 + ELSE + data%(K%)=data%(J%) + J%+=1 + K%+=1 + ENDIF +UNTIL I%=fh_size% OR J%>End% + +WHILE I% < fh_size% + data%(K%)=fh%(I%) + I%+=1 + K%+=1 +ENDWHILE + +ENDPROC diff --git a/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-2.bbc b/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-2.bbc new file mode 100644 index 0000000000..2801c85418 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/BBC-BASIC/sorting-algorithms-merge-sort-2.bbc @@ -0,0 +1,15 @@ +REM Example of merge sort usage. +Size%=1000 + +S1%=Size%/2 + +DIM data%(Size%) +DIM fh%(S1%) + +FOR I%=1 TO Size% + data%(I%)=RND(100000) +NEXT + +PROC_MergeSort(1,Size%) + +END diff --git a/Task/Sorting-algorithms-Merge-sort/C++/sorting-algorithms-merge-sort.cpp b/Task/Sorting-algorithms-Merge-sort/C++/sorting-algorithms-merge-sort.cpp new file mode 100644 index 0000000000..bae6aaa220 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/C++/sorting-algorithms-merge-sort.cpp @@ -0,0 +1,21 @@ +#include <iterator> +#include <algorithm> // for std::inplace_merge +#include <functional> // for std::less + +template<typename RandomAccessIterator, typename Order> + void mergesort(RandomAccessIterator first, RandomAccessIterator last, Order order) +{ + if (last - first > 1) + { + RandomAccessIterator middle = first + (last - first) / 2; + mergesort(first, middle, order); + mergesort(middle, last, order); + std::inplace_merge(first, middle, last, order); + } +} + +template<typename RandomAccessIterator> + void mergesort(RandomAccessIterator first, RandomAccessIterator last) +{ + mergesort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>()); +} diff --git a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c new file mode 100644 index 0000000000..4fb5a2ab7f --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-1.c @@ -0,0 +1,60 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +inline +void merge(int *left, int l_len, int *right, int r_len, int *out) +{ + int i, j, k; + for (i = j = k = 0; i < l_len && j < r_len; ) + out[k++] = left[i] < right[j] ? left[i++] : right[j++]; + + while (i < l_len) out[k++] = left[i++]; + while (j < r_len) out[k++] = right[j++]; +} + +/* inner recursion of merge sort */ +void recur(int *buf, int *tmp, int len) +{ + int l = len / 2; + if (len <= 1) return; + + /* note that buf and tmp are swapped */ + recur(tmp, buf, l); + recur(tmp + l, buf + l, len - l); + + merge(tmp, l, tmp + l, len - l, buf); +} + +/* preparation work before recursion */ +void merge_sort(int *buf, int len) +{ + /* call alloc, copy and free only once */ + int *tmp = malloc(sizeof(int) * len); + memcpy(tmp, buf, sizeof(int) * len); + + recur(buf, tmp, len); + + free(tmp); +} + +int main() +{ +# define LEN 20 + int i, x[LEN]; + + for (i = 0; i < LEN; i++) + x[i] = rand() % LEN; + + puts("before sort:"); + for (i = 0; i < LEN; i++) printf("%d ", x[i]); + putchar('\n'); + + merge_sort(x, LEN); + + puts("after sort:"); + for (i = 0; i < LEN; i++) printf("%d ", x[i]); + putchar('\n'); + + return 0; +} diff --git a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c new file mode 100644 index 0000000000..bd3c52a544 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort-2.c @@ -0,0 +1,70 @@ +#include <stdlib.h> +#include <stdio.h> + +typedef struct link_s *link, link_t; +struct link_s { double v; link next; }; + +const link_t fnil = { 0./0., &fnil }; // sentinel +const link const nil = &fnil; + +link list_from_array(double *a, int len) +{ + link p = nil; + while (len--) { + link pp = malloc(sizeof(*pp)); + pp->v = a[len]; + pp->next = p; + p = pp; + } + return p; +} + +void show_list(link a) +{ + for (; a != nil; a = a->next) + printf("%g ", a->v); + putchar('\n'); +} + +link merge(link a, link b) +{ + link head = &(link_t){0, nil}, tail = head; + while (a != nil && b != nil) { + link *p = a->v <= b->v ? &a : &b; + tail->next = *p; + *p = (*p)->next; + tail = tail->next; + } + tail->next = a != nil ? a : b; + return head->next; +} + +link merge_sort(link p) +{ + if (p->next == nil) return p; + + link tail = p, mid = p; + // Seek to the middle of the list. This is O(n) for list + // length, so O(n log n) complexity to overall merge sort + // that an array wouldn't have to deal with. + while (1) { + tail = tail->next->next; + if (tail == nil) break; + mid = mid->next; + } + + tail = mid->next; + mid->next = nil; + + return merge(merge_sort(p), merge_sort(tail)); +} + +int main(void) +{ + double x[] = {5,3,6,1,2,6,2,0,3,5,7,8,2,4,9}; + link p = list_from_array(x, sizeof(x)/sizeof(x[0])); + + puts("list: "); show_list(p); + puts("sort: "); show_list(merge_sort(p)); + return 0; +} diff --git a/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cobol b/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cobol new file mode 100644 index 0000000000..1d25525857 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cobol @@ -0,0 +1,293 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. MERGESORT. + AUTHOR. DAVE STRATFORD. + DATE-WRITTEN. APRIL 2010. + INSTALLATION. HEXAGON SYSTEMS LIMITED. + ****************************************************************** + * MERGE SORT * + * The Merge sort uses a completely different paradigm, one of * + * divide and conquer, to many of the other sorts. The data set * + * is split into smaller sub sets upon which are sorted and then * + * merged together to form the final sorted data set. * + * This version uses the recursive method. Split the data set in * + * half and perform a merge sort on each half. This in turn splits* + * each half again and again until each set is just one or 2 items* + * long. A set of one item is already sorted so is ignored, a set * + * of two is compared and swapped as necessary. The smaller data * + * sets are then repeatedly merged together to eventually form the* + * full, sorted, set. * + * Since cobol cannot do recursion this module only simulates it * + * so is not as fast as a normal recursive version would be. * + * Scales very well to larger data sets, its relative complexity * + * means it is not suited to sorting smaller data sets: use an * + * Insertion sort instead as the Merge sort is a stable sort. * + ****************************************************************** + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + SOURCE-COMPUTER. ICL VME. + OBJECT-COMPUTER. ICL VME. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT FA-INPUT-FILE ASSIGN FL01. + SELECT FB-OUTPUT-FILE ASSIGN FL02. + + DATA DIVISION. + FILE SECTION. + FD FA-INPUT-FILE. + 01 FA-INPUT-REC. + 03 FA-DATA PIC 9(6). + + FD FB-OUTPUT-FILE. + 01 FB-OUTPUT-REC PIC 9(6). + + WORKING-STORAGE SECTION. + 01 WA-IDENTITY. + 03 WA-PROGNAME PIC X(10) VALUE "MERGESORT". + 03 WA-VERSION PIC X(6) VALUE "000001". + + 01 WB-TABLE. + 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 + INDEXED BY WB-IX-1 + WB-IX-2. + + 01 WC-VARS. + 03 WC-SIZE PIC S9(8) COMP SYNC. + 03 WC-TEMP PIC S9(8) COMP SYNC. + 03 WC-START PIC S9(8) COMP SYNC. + 03 WC-MIDDLE PIC S9(8) COMP SYNC. + 03 WC-END PIC S9(8) COMP SYNC. + + 01 WD-FIRST-HALF. + 03 WD-FH-MAX PIC S9(8) COMP SYNC. + 03 WD-ENTRY PIC 9(8) COMP SYNC OCCURS 50000 + INDEXED BY WD-IX. + + 01 WF-CONDITION-FLAGS. + 03 WF-EOF-FLAG PIC X. + 88 END-OF-FILE VALUE "Y". + 03 WF-EMPTY-FILE-FLAG PIC X. + 88 EMPTY-FILE VALUE "Y". + + 01 WS-STACK. + * This stack is big enough to sort a list of 1million items. + 03 WS-STACK-ENTRY OCCURS 20 INDEXED BY WS-STACK-TOP. + 05 WS-START PIC S9(8) COMP SYNC. + 05 WS-MIDDLE PIC S9(8) COMP SYNC. + 05 WS-END PIC S9(8) COMP SYNC. + 05 WS-FS-FLAG PIC X. + 88 FIRST-HALF VALUE "F". + 88 SECOND-HALF VALUE "S". + 88 WS-ALL VALUE "A". + 05 WS-IO-FLAG PIC X. + 88 WS-IN VALUE "I". + 88 WS-OUT VALUE "O". + + PROCEDURE DIVISION. + A-MAIN SECTION. + A-000. + PERFORM B-INITIALISE. + + IF NOT EMPTY-FILE + PERFORM C-PROCESS. + + PERFORM D-FINISH. + + A-999. + STOP RUN. + + B-INITIALISE SECTION. + B-000. + DISPLAY "*** " WA-PROGNAME " VERSION " + WA-VERSION " STARTING ***". + + MOVE ALL "N" TO WF-CONDITION-FLAGS. + OPEN INPUT FA-INPUT-FILE. + SET WB-IX-1 TO 0. + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG + WF-EMPTY-FILE-FLAG. + + PERFORM BA-READ-INPUT UNTIL END-OF-FILE. + + CLOSE FA-INPUT-FILE. + + SET WC-SIZE TO WB-IX-1. + + B-999. + EXIT. + + BA-READ-INPUT SECTION. + BA-000. + SET WB-IX-1 UP BY 1. + MOVE FA-DATA TO WB-ENTRY(WB-IX-1). + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG. + + BA-999. + EXIT. + + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE 1 TO WS-START(1). + MOVE WC-SIZE TO WS-END(1). + MOVE "F" TO WS-FS-FLAG(1). + MOVE "I" TO WS-IO-FLAG(1). + SET WS-STACK-TOP TO 2. + + PERFORM E-MERGE-SORT UNTIL WS-OUT(1). + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + D-FINISH SECTION. + D-000. + OPEN OUTPUT FB-OUTPUT-FILE. + SET WB-IX-1 TO 1. + + PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE. + + CLOSE FB-OUTPUT-FILE. + + DISPLAY "*** " WA-PROGNAME " FINISHED ***". + + D-999. + EXIT. + + DA-WRITE-OUTPUT SECTION. + DA-000. + WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). + SET WB-IX-1 UP BY 1. + + DA-999. + EXIT. + + ****************************************************************** + E-MERGE-SORT SECTION. + *===================== * + * This section controls the simulated recursion. * + ****************************************************************** + E-000. + IF WS-OUT(WS-STACK-TOP - 1) + GO TO E-010. + + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + + * First check size of part we are dealing with. + IF WC-END - WC-START = 0 + * Only 1 number in range, so simply set for output, and move on + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) + GO TO E-010. + + IF WC-END - WC-START = 1 + * 2 numbers, so compare and swap as necessary. Set for output + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) + IF WB-ENTRY(WC-START) > WB-ENTRY(WC-END) + MOVE WB-ENTRY(WC-START) TO WC-TEMP + MOVE WB-ENTRY(WC-END) TO WB-ENTRY(WC-START) + MOVE WC-TEMP TO WB-ENTRY(WC-END) + GO TO E-010 + ELSE + GO TO E-010. + + * More than 2, so split and carry on down + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2. + + MOVE WC-START TO WS-START(WS-STACK-TOP). + MOVE WC-MIDDLE TO WS-END(WS-STACK-TOP). + MOVE "F" TO WS-FS-FLAG(WS-STACK-TOP). + MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). + SET WS-STACK-TOP UP BY 1. + + GO TO E-999. + + E-010. + SET WS-STACK-TOP DOWN BY 1. + + IF SECOND-HALF(WS-STACK-TOP) + GO TO E-020. + + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2 + 1. + + MOVE WC-MIDDLE TO WS-START(WS-STACK-TOP). + MOVE WC-END TO WS-END(WS-STACK-TOP). + MOVE "S" TO WS-FS-FLAG(WS-STACK-TOP). + MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). + SET WS-STACK-TOP UP BY 1. + + GO TO E-999. + + E-020. + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2. + PERFORM H-PROCESS-MERGE. + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1). + + E-999. + EXIT. + + ****************************************************************** + H-PROCESS-MERGE SECTION. + *======================== * + * This section identifies which data is to be merged, and then * + * merges the two data streams into a single larger data stream. * + ****************************************************************** + H-000. + INITIALISE WD-FIRST-HALF. + COMPUTE WD-FH-MAX = WC-MIDDLE - WC-START + 1. + SET WD-IX TO 1. + + PERFORM HA-COPY-OUT VARYING WB-IX-1 FROM WC-START BY 1 + UNTIL WB-IX-1 > WC-MIDDLE. + + SET WB-IX-1 TO WC-START. + SET WB-IX-2 TO WC-MIDDLE. + SET WB-IX-2 UP BY 1. + SET WD-IX TO 1. + + PERFORM HB-MERGE UNTIL WD-IX > WD-FH-MAX OR WB-IX-2 > WC-END. + + PERFORM HC-COPY-BACK UNTIL WD-IX > WD-FH-MAX. + + H-999. + EXIT. + + HA-COPY-OUT SECTION. + HA-000. + MOVE WB-ENTRY(WB-IX-1) TO WD-ENTRY(WD-IX). + SET WD-IX UP BY 1. + + HA-999. + EXIT. + + HB-MERGE SECTION. + HB-000. + IF WB-ENTRY(WB-IX-2) < WD-ENTRY(WD-IX) + MOVE WB-ENTRY(WB-IX-2) TO WB-ENTRY(WB-IX-1) + SET WB-IX-2 UP BY 1 + ELSE + MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1) + SET WD-IX UP BY 1. + + SET WB-IX-1 UP BY 1. + + HB-999. + EXIT. + + HC-COPY-BACK SECTION. + HC-000. + MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1). + SET WD-IX UP BY 1. + SET WB-IX-1 UP BY 1. + + HC-999. + EXIT. diff --git a/Task/Sorting-algorithms-Merge-sort/Clojure/sorting-algorithms-merge-sort.clj b/Task/Sorting-algorithms-Merge-sort/Clojure/sorting-algorithms-merge-sort.clj new file mode 100644 index 0000000000..b120dde062 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Clojure/sorting-algorithms-merge-sort.clj @@ -0,0 +1,14 @@ +(defn merge* [left right] + (cond (nil? left) right + (nil? right) left + true (let [[l & *left] left + [r & *right] right] + (if (<= l r) (cons l (merge* *left right)) + (cons r (merge* left *right)))))) + +(defn merge-sort [L] + (let [[l & *L] L] + (if (nil? *L) + L + (let [[left right] (split-at (/ (count L) 2) L)] + (merge* (merge-sort left) (merge-sort right)))))) diff --git a/Task/Sorting-algorithms-Merge-sort/CoffeeScript/sorting-algorithms-merge-sort.coffeescript b/Task/Sorting-algorithms-Merge-sort/CoffeeScript/sorting-algorithms-merge-sort.coffeescript new file mode 100644 index 0000000000..5bba9aae23 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/CoffeeScript/sorting-algorithms-merge-sort.coffeescript @@ -0,0 +1,25 @@ +# This is a simple version of mergesort that returns brand-new arrays. +# A more sophisticated version would do more in-place optimizations. +merge_sort = (arr) -> + if arr.length <= 1 + return (elem for elem in arr) + m = Math.floor(arr.length / 2) + arr1 = merge_sort(arr.slice 0, m) + arr2 = merge_sort(arr.slice m) + result = [] + p1 = p2 = 0 + while true + if p1 >= arr1.length + if p2 >= arr2.length + return result + result.push arr2[p2] + p2 += 1 + else if p2 >= arr2.length or arr1[p1] < arr2[p2] + result.push arr1[p1] + p1 += 1 + else + result.push arr2[p2] + p2 += 1 + +do -> + console.log merge_sort [2,4,6,8,1,3,5,7,9,10,11,0,13,12] diff --git a/Task/Sorting-algorithms-Merge-sort/Common-Lisp/sorting-algorithms-merge-sort.lisp b/Task/Sorting-algorithms-Merge-sort/Common-Lisp/sorting-algorithms-merge-sort.lisp new file mode 100644 index 0000000000..fbe2c0415d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Common-Lisp/sorting-algorithms-merge-sort.lisp @@ -0,0 +1,7 @@ +(defun merge-sort (result-type sequence predicate) + (let ((split (floor (length sequence) 2))) + (if (zerop split) + (copy-seq sequence) + (merge result-type (merge-sort result-type (subseq sequence 0 split) predicate) + (merge-sort result-type (subseq sequence split) predicate) + predicate)))) diff --git a/Task/Sorting-algorithms-Merge-sort/Curry/sorting-algorithms-merge-sort.curry b/Task/Sorting-algorithms-Merge-sort/Curry/sorting-algorithms-merge-sort.curry new file mode 100644 index 0000000000..28bc032bcd --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Curry/sorting-algorithms-merge-sort.curry @@ -0,0 +1,30 @@ +-- merge sort: sorting two lists by merging the sorted first +-- and second half of the list + +sort :: ([a] -> [a] -> [a] -> Success) -> [a] -> [a] -> Success + +sort merge xs ys = + if length xs < 2 then ys =:= xs + else sort merge (firsthalf xs) us + & sort merge (secondhalf xs) vs + & merge us vs ys + where us,vs free + + +intMerge :: [Int] -> [Int] -> [Int] -> Success + +intMerge [] ys zs = zs =:= ys +intMerge (x:xs) [] zs = zs =:= x:xs +intMerge (x:xs) (y:ys) zs = + if (x > y) then intMerge (x:xs) ys us & zs =:= y:us + else intMerge xs (y:ys) vs & zs =:= x:vs + where us,vs free + +firsthalf xs = take (length xs `div` 2) xs +secondhalf xs = drop (length xs `div` 2) xs + + + +goal1 xs = sort intMerge [3,1,2] xs +goal2 xs = sort intMerge [3,1,2,5,4,8] xs +goal3 xs = sort intMerge [3,1,2,5,4,8,6,7,2,9,1,4,3] xs diff --git a/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d new file mode 100644 index 0000000000..5498d6ab86 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-1.d @@ -0,0 +1,13 @@ +import std.stdio, std.algorithm, std.array, std.range; + +T[] mergeSorted(T)(in T[] D) /*pure nothrow*/ { + if (D.length < 2) + return D.dup; + return [D[0 .. $ / 2].mergeSorted(), D[$ / 2 .. $].mergeSorted()] + .nWayUnion().array(); +} + +void main() { + auto a = [3, 4, 2, 5, 1, 6]; + writeln(a.mergeSorted()); +} diff --git a/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-2.d b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-2.d new file mode 100644 index 0000000000..697c27f27e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/D/sorting-algorithms-merge-sort-2.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm, core.stdc.stdlib, std.exception, + std.range; + +void mergeSort(T)(T[] data) if (hasSwappableElements!(typeof(data))) { + immutable L = data.length; + if (L < 2) return; + T* ptr = cast(T*)alloca(L * T.sizeof); + enforce(ptr != null); + ptr[0 .. L] = data[]; + mergeSort(ptr[0 .. L/2]); + mergeSort(ptr[L/2 .. L]); + [ptr[0 .. L/2], ptr[L/2 .. L]].nWayUnion().copy(data); +} + +void main() { + auto a = [3, 4, 2, 5, 1, 6]; + a.mergeSort(); + writeln(a); +} diff --git a/Task/Sorting-algorithms-Merge-sort/Dart/sorting-algorithms-merge-sort.dart b/Task/Sorting-algorithms-Merge-sort/Dart/sorting-algorithms-merge-sort.dart new file mode 100644 index 0000000000..a0d886ee5c --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Dart/sorting-algorithms-merge-sort.dart @@ -0,0 +1,54 @@ +merge(left, right, items) { + var a = 0; + var t; + + while (left.length != 0 && right.length != 0) { + if (right[0] < left[0]) { + t = right[0]; + right.removeRange(0,1); + } else { + t = left[0]; + left.removeRange(0,1); + } + items[a++] = t; + } + + while(left.length != 0) { + t = left[0]; + left.removeRange(0,1); + items[a++] = t; + } + + while(right.length != 0) { + t = right[0]; + right.removeRange(0,1); + items[a++] = t; + } +} + +mSort(items, tmp, l) { + if (l == 1) { + return; + } + + var m = (l/2).floor().toInt(); + var tmp_l = tmp.getRange(0, m); + var tmp_r = tmp.getRange(m, tmp.length-m); + + mSort(tmp_l, items.getRange(0,m), m); + mSort(tmp_r, items.getRange(m, items.length-m), l-m); + merge(tmp_l, tmp_r, items); +} + +merge_sort(items) { + mSort(items,items.getRange(0, items.length),items.length); +} + +void main() { + var arr=[1,5,2,7,3,9,4,6,8]; + print("Before sort"); + arr.forEach((var i)=>print("$i")); + merge_sort(arr); + print("After sort"); + arr.forEach((var i)=>print("$i")); +} diff --git a/Task/Sorting-algorithms-Merge-sort/E/sorting-algorithms-merge-sort.e b/Task/Sorting-algorithms-Merge-sort/E/sorting-algorithms-merge-sort.e new file mode 100644 index 0000000000..d180ac9d66 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/E/sorting-algorithms-merge-sort.e @@ -0,0 +1,20 @@ +def merge(var xs :List, var ys :List) { + var result := [] + while (xs =~ [x] + xr && ys =~ [y] + yr) { + if (x <= y) { + result with= x + xs := xr + } else { + result with= y + ys := yr + } + } + return result + xs + ys +} + +def sort(list :List) { + if (list.size() <= 1) { return list } + def split := list.size() // 2 + return merge(sort(list.run(0, split)), + sort(list.run(split))) +} diff --git a/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-1.erl b/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-1.erl new file mode 100644 index 0000000000..166eb33773 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-1.erl @@ -0,0 +1,4 @@ +mergeSort(L) when length(L) == 1 -> L; +mergeSort(L) when length(L) > 1 -> + {L1, L2} = lists:split(length(L) div 2, L), + lists:merge(mergeSort(L1), mergeSort(L2)). diff --git a/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-2.erl b/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-2.erl new file mode 100644 index 0000000000..6c68f365f7 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Erlang/sorting-algorithms-merge-sort-2.erl @@ -0,0 +1,13 @@ +pMergeSort(L) when length(L) == 1 -> L; +pMergeSort(L) when length(L) > 1 -> + {L1, L2} = lists:split(length(L) div 2, L), + spawn(mergesort, pMergeSort2, [L1, self()]), + spawn(mergesort, pMergeSort2, [L2, self()]), + mergeResults([]). + +pMergeSort2(L, Parent) when length(L) == 1 -> Parent ! L; +pMergeSort2(L, Parent) when length(L) > 1 -> + {L1, L2} = lists:split(length(L) div 2, L), + spawn(mergesort, pMergeSort2, [L1, self()]), + spawn(mergesort, pMergeSort2, [L2, self()]), + Parent ! mergeResults([]). diff --git a/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.euphoria b/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.euphoria new file mode 100644 index 0000000000..2eb77e9949 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.euphoria @@ -0,0 +1,37 @@ +function merge(sequence left, sequence right) + sequence result + result = {} + while length(left) > 0 and length(right) > 0 do + if compare(left[1], right[1]) <= 0 then + result = append(result, left[1]) + left = left[2..$] + else + result = append(result, right[1]) + right = right[2..$] + end if + end while + return result & left & right +end function + +function mergesort(sequence m) + sequence left, right + integer middle + if length(m) <= 1 then + return m + else + middle = floor(length(m)/2) + left = mergesort(m[1..middle]) + right = mergesort(m[middle+1..$]) + if compare(left[$], right[1]) <= 0 then + return left & right + elsif compare(right[$], left[1]) <= 0 then + return right & left + else + return merge(left, right) + end if + end if +end function + +constant s = rand(repeat(1000,10)) +? s +? mergesort(s) diff --git a/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-1.factor b/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-1.factor new file mode 100644 index 0000000000..c7715f39f4 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-1.factor @@ -0,0 +1,16 @@ +: mergestep ( accum seq1 seq2 -- accum seq1 seq2 ) +2dup [ first ] bi@ < +[ [ [ first ] [ rest-slice ] bi [ suffix ] dip ] dip ] +[ [ first ] [ rest-slice ] bi [ swap [ suffix ] dip ] dip ] +if ; + +: merge ( seq1 seq2 -- merged ) +[ { } ] 2dip +[ 2dup [ length 0 > ] bi@ and ] +[ mergestep ] while +append append ; + +: mergesort ( seq -- sorted ) +dup length 1 > +[ dup length 2 / floor [ head ] [ tail ] 2bi [ mergesort ] bi@ merge ] +[ ] if ; diff --git a/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-2.factor b/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-2.factor new file mode 100644 index 0000000000..0963bb1c5c --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Factor/sorting-algorithms-merge-sort-2.factor @@ -0,0 +1,2 @@ +( scratchpad ) { 4 2 6 5 7 1 3 } mergesort . +{ 1 2 3 4 5 6 7 } diff --git a/Task/Sorting-algorithms-Merge-sort/Forth/sorting-algorithms-merge-sort.fth b/Task/Sorting-algorithms-Merge-sort/Forth/sorting-algorithms-merge-sort.fth new file mode 100644 index 0000000000..819cfaa1f9 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Forth/sorting-algorithms-merge-sort.fth @@ -0,0 +1,23 @@ +: merge-step ( right mid left -- right mid+ left+ ) + over @ over @ < if + over @ >r + 2dup - over dup cell+ rot move + r> over ! + >r cell+ 2dup = if rdrop dup else r> then + then cell+ ; +: merge ( right mid left -- right left ) + dup >r begin 2dup > while merge-step repeat 2drop r> ; + +: mid ( l r -- mid ) over - 2/ cell negate and + ; + +: mergesort ( right left -- right left ) + 2dup cell+ <= if exit then + swap 2dup mid recurse rot recurse merge ; + +: sort ( addr len -- ) cells over + swap mergesort 2drop ; + +create test 8 , 1 , 5 , 3 , 9 , 0 , 2 , 7 , 6 , 4 , + +: .array ( addr len -- ) 0 do dup i cells + @ . loop drop ; + +test 10 2dup sort .array \ 0 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Merge-sort/Fortran/sorting-algorithms-merge-sort.f b/Task/Sorting-algorithms-Merge-sort/Fortran/sorting-algorithms-merge-sort.f new file mode 100644 index 0000000000..b8c01bb4c8 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Fortran/sorting-algorithms-merge-sort.f @@ -0,0 +1,69 @@ +subroutine Merge(A,NA,B,NB,C,NC) + + integer, intent(in) :: NA,NB,NC ! Normal usage: NA+NB = NC + integer, intent(in out) :: A(NA) ! B overlays C(NA+1:NC) + integer, intent(in) :: B(NB) + integer, intent(in out) :: C(NC) + + integer :: I,J,K + + I = 1; J = 1; K = 1; + do while(I <= NA .and. J <= NB) + if (A(I) <= B(J)) then + C(K) = A(I) + I = I+1 + else + C(K) = B(J) + J = J+1 + endif + K = K + 1 + enddo + do while (I <= NA) + C(K) = A(I) + I = I + 1 + K = K + 1 + enddo + return + +end subroutine merge + +recursive subroutine MergeSort(A,N,T) + + integer, intent(in) :: N + integer, dimension(N), intent(in out) :: A + integer, dimension((N+1)/2), intent (out) :: T + + integer :: NA,NB,V + + if (N < 2) return + if (N == 2) then + if (A(1) > A(2)) then + V = A(1) + A(1) = A(2) + A(2) = V + endif + return + endif + NA=(N+1)/2 + NB=N-NA + + call MergeSort(A,NA,T) + call MergeSort(A(NA+1),NB,T) + + if (A(NA) > A(NA+1)) then + T(1:NA)=A(1:NA) + call Merge(T,NA,A(NA+1),NB,A,N) + endif + return + +end subroutine MergeSort + +program TestMergeSort + + integer, parameter :: N = 8 + integer, dimension(N) :: A = (/ 1, 5, 2, 7, 3, 9, 4, 6 /) + integer, dimension ((N+1)/2) :: T + call MergeSort(A,N,T) + write(*,'(A,/,10I3)')'Sorted array :',A + +end program TestMergeSort diff --git a/Task/Sorting-algorithms-Merge-sort/Go/sorting-algorithms-merge-sort.go b/Task/Sorting-algorithms-Merge-sort/Go/sorting-algorithms-merge-sort.go new file mode 100644 index 0000000000..214424fb51 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Go/sorting-algorithms-merge-sort.go @@ -0,0 +1,44 @@ +package main + +import "fmt" + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} +var s = make([]int, len(a)/2+1) // scratch space for merge step + +func main() { + fmt.Println("before:", a) + mergeSort(a) + fmt.Println("after: ", a) +} + +func mergeSort(a []int) { + if len(a) < 2 { + return + } + mid := len(a) / 2 + mergeSort(a[:mid]) + mergeSort(a[mid:]) + if a[mid-1] <= a[mid] { + return + } + // merge step, with the copy-half optimization + copy(s, a[:mid]) + l, r := 0, mid + for i := 0; ; i++ { + if s[l] <= a[r] { + a[i] = s[l] + l++ + if l == mid { + break + } + } else { + a[i] = a[r] + r++ + if r == len(a) { + copy(a[i+1:], s[l:mid]) + break + } + } + } + return +} diff --git a/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-1.groovy b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-1.groovy new file mode 100644 index 0000000000..4faea88878 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-1.groovy @@ -0,0 +1,26 @@ +def merge = { List left, List right -> + List mergeList = [] + while (left && right) { + print "." + mergeList << ((left[-1] > right[-1]) ? left.pop() : right.pop()) + } + mergeList = mergeList.reverse() + mergeList = left + right + mergeList +} + +def mergeSort; +mergeSort = { List list -> + + def n = list.size() + if (n < 2) return list + + def middle = n.intdiv(2) + def left = [] + list[0..<middle] + def right = [] + list[middle..<n] + left = mergeSort(left) + right = mergeSort(right) + + if (left[-1] <= right[0]) return left + right + + merge(left, right) +} diff --git a/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-2.groovy b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-2.groovy new file mode 100644 index 0000000000..41e49af4ed --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Groovy/sorting-algorithms-merge-sort-2.groovy @@ -0,0 +1,9 @@ +println (mergeSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (mergeSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println () +println (mergeSort([10, 10.0, 10.00, 1])) +println (mergeSort([10, 10.00, 10.0, 1])) +println (mergeSort([10.0, 10, 10.00, 1])) +println (mergeSort([10.0, 10.00, 10, 1])) +println (mergeSort([10.00, 10, 10.0, 1])) +println (mergeSort([10.00, 10.0, 10, 1])) diff --git a/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs new file mode 100644 index 0000000000..65bdb16785 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-1.hs @@ -0,0 +1,13 @@ +merge [] ys = ys +merge xs [] = xs +merge xs@(x:xs') ys@(y:ys') | x <= y = x : merge xs' ys + | otherwise = y : merge xs ys' + +split (x:y:zs) = let (xs,ys) = split zs in (x:xs,y:ys) +split [x] = ([x],[]) +split [] = ([],[]) + +mergeSort [] = [] +mergeSort [x] = [x] +mergeSort xs = let (as,bs) = split xs + in merge (mergeSort as) (mergeSort bs) diff --git a/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-2.hs b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-2.hs new file mode 100644 index 0000000000..c3730d4a07 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-2.hs @@ -0,0 +1,7 @@ +mergePairs (sorted1 : sorted2 : sorteds) = merge sorted1 sorted2 : mergePairs sorteds +mergePairs sorteds = sorteds + +mergeSortBottomUp list = mergeAll (map (\x -> [x]) list) + +mergeAll [sorted] = sorted +mergeAll sorteds = mergeAll (mergePairs sorteds) diff --git a/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-3.hs b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-3.hs new file mode 100644 index 0000000000..9cf4aff971 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Haskell/sorting-algorithms-merge-sort-3.hs @@ -0,0 +1,15 @@ +sort = sortBy compare +sortBy cmp = mergeAll . sequences + where + sequences (a:b:xs) + | a `cmp` b == GT = descending b [a] xs + | otherwise = ascending b (a:) xs + sequences xs = [xs] + + descending a as (b:bs) + | a `cmp` b == GT = descending b (a:as) bs + descending a as bs = (a:as): sequences bs + + ascending a as (b:bs) + | a `cmp` b /= GT = ascending b (\ys -> as (a:ys)) bs + ascending a as bs = as [a]: sequences bs diff --git a/Task/Sorting-algorithms-Merge-sort/Icon/sorting-algorithms-merge-sort.icon b/Task/Sorting-algorithms-Merge-sort/Icon/sorting-algorithms-merge-sort.icon new file mode 100644 index 0000000000..f699b70d3b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Icon/sorting-algorithms-merge-sort.icon @@ -0,0 +1,49 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(mergesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure mergesort(X,op,lower,upper) #: return sorted list ascending(or descending) +local middle + + if /lower := 1 then { # top level call setup + upper := *X + op := sortop(op,X) # select how and what we sort + } + + if upper ~= lower then { # sort all sections with 2 or more elements + X := mergesort(X,op,lower,middle := lower + (upper - lower) / 2) + X := mergesort(X,op,middle+1,upper) + + if op(X[middle+1],X[middle]) then # @middle+1 < @middle merge if halves reversed + X := merge(X,op,lower,middle,upper) + } + return X +end + +procedure merge(X,op,lower,middle,upper) # merge two list sections within a larger list +local p1,p2,add + + p1 := lower + p2 := middle + 1 + add := if type(X) ~== "string" then put else "||" # extend X, strings require X := add (until ||:= is invocable) + + while p1 <= middle & p2 <= upper do + if op(X[p1],X[p2]) then { # @p1 < @p2 + X := add(X,X[p1]) # extend X temporarily (rather than use a separate temporary list) + p1 +:= 1 + } + else { + X := add(X,X[p2]) # extend X temporarily + p2 +:= 1 + } + + while X := add(X,X[middle >= p1]) do p1 +:= 1 # and rest of lower or ... + while X := add(X,X[upper >= p2]) do p2 +:= 1 # ... upper trailers if any + + if type(X) ~== "string" then # pull section's sorted elements from extension + every X[upper to lower by -1] := pull(X) + else + (X[lower+:(upper-lower+1)] := X[0-:(upper-lower+1)])[0-:(upper-lower+1)] := "" + + return X +end diff --git a/Task/Sorting-algorithms-Merge-sort/Io/sorting-algorithms-merge-sort.io b/Task/Sorting-algorithms-Merge-sort/Io/sorting-algorithms-merge-sort.io new file mode 100644 index 0000000000..11679f7041 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Io/sorting-algorithms-merge-sort.io @@ -0,0 +1,28 @@ +List do ( + merge := method(lst1, lst2, + result := list() + while(lst1 isNotEmpty or lst2 isNotEmpty, + if(lst1 first <= lst2 first) then( + result append(lst1 removeFirst) + ) else ( + result append(lst2 removeFirst) + ) + ) + result) + + mergeSort := method( + if (size > 1) then( + half_size := (size / 2) ceil + return merge(slice(0, half_size) mergeSort, + slice(half_size, size) mergeSort) + ) else (return self) + ) + + mergeSortInPlace := method( + copy(mergeSort) + ) +) + +lst := list(9, 5, 3, -1, 15, -2) +lst mergeSort println # ==> list(-2, -1, 3, 5, 9, 15) +lst mergeSortInPlace println # ==> list(-2, -1, 3, 5, 9, 15) diff --git a/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-1.j b/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-1.j new file mode 100644 index 0000000000..5473bbb7fc --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-1.j @@ -0,0 +1,3 @@ +merge =: ,`(({.@] , ($: }.))~` ({.@] , ($: }.)) @.(>&{.))@.(*@*&#) +split =: </.~ 0 1$~# +mergeSort =: merge & $: &>/ @ split ` ] @. (1>:#) diff --git a/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-2.j b/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-2.j new file mode 100644 index 0000000000..9799ac5183 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/J/sorting-algorithms-merge-sort-2.j @@ -0,0 +1,16 @@ +merge=: 4 : 0 + if. 0= x *@*&# y do. x,y return. end. + la=.x + ra=.y + z=.i.0 + while. la *@*&# ra do. + if. la >&{. ra do. + z=.z,{.ra + ra=.}.ra + else. + z=.z,{.la + la=.}.la + end. + end. + z,la,ra +) diff --git a/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java b/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java new file mode 100644 index 0000000000..bead13c08d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java @@ -0,0 +1,53 @@ +import java.util.List; +import java.util.ArrayList; +import java.util.Iterator; + +public class Merge { + public static <E extends Comparable<? super E>> List<E> mergeSort(List<E> m) { + if (m.size() <= 1) return m; + + int middle = m.size() / 2; + List<E> left = m.subList(0, middle); + List<E> right = m.subList(middle, m.size()); + + right = mergeSort(right); + left = mergeSort(left); + List<E> result = merge(left, right); + + return result; + } + + public static <E extends Comparable<? super E>> List<E> merge(List<E> left, List<E> right) { + List<E> result = new ArrayList<E>(); + Iterator<E> it1 = left.iterator(); + Iterator<E> it2 = right.iterator(); + + E x = it1.next(); + E y = it2.next(); + while (true) { + //change the direction of this comparison to change the direction of the sort + if (x.compareTo(y) <= 0) { + result.add(x); + if (it1.hasNext()) + x = it1.next(); + else { + result.add(y); + while (it2.hasNext()) + result.add(it2.next()); + break; + } + } else { + result.add(y); + if (it2.hasNext()) + y = it2.next(); + else { + result.add(x); + while (it1.hasNext()) + result.add(it1.next()); + break; + } + } + } + return result; + } +} diff --git a/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js new file mode 100644 index 0000000000..2f535386e0 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js @@ -0,0 +1,22 @@ +function merge(left,right,arr){ + var a=0; + while(left.length&&right.length) + arr[a++]=right[0]<left[0]?right.shift():left.shift(); + while(left.length)arr[a++]=left.shift(); + while(right.length)arr[a++]=right.shift(); +} +function mSort(arr,tmp,l){ + if(l==1)return; + var m=Math.floor(l/2), + tmp_l=tmp.slice(0,m), + tmp_r=tmp.slice(m); + mSort(tmp_l,arr.slice(0,m),m); + mSort(tmp_r,arr.slice(m),l-m); + merge(tmp_l,tmp_r,arr); +} +function merge_sort(arr){ + mSort(arr,arr.slice(),arr.length); +} + +var arr=[1,5,2,7,3,9,4,6,8]; +merge_sort(arr); // arr will now: 1,2,3,4,5,6,7,8,9 diff --git a/Task/Sorting-algorithms-Merge-sort/Liberty-BASIC/sorting-algorithms-merge-sort.liberty b/Task/Sorting-algorithms-Merge-sort/Liberty-BASIC/sorting-algorithms-merge-sort.liberty new file mode 100644 index 0000000000..09b058686e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Liberty-BASIC/sorting-algorithms-merge-sort.liberty @@ -0,0 +1,70 @@ + itemCount = 20 + dim A(itemCount) + dim tmp(itemCount) 'merge sort needs additionally same amount of storage + + for i = 1 to itemCount + A(i) = int(rnd(1) * 100) + next i + + print "Before Sort" + call printArray itemCount + + call mergeSort 1,itemCount + + print "After Sort" + call printArray itemCount +end + +'------------------------------------------ +sub mergeSort start, theEnd + if theEnd-start < 1 then exit sub + if theEnd-start = 1 then + if A(start)>A(theEnd) then + tmp=A(start) + A(start)=A(theEnd) + A(theEnd)=tmp + end if + exit sub + end if + middle = int((start+theEnd)/2) + call mergeSort start, middle + call mergeSort middle+1, theEnd + call merge start, middle, theEnd +end sub + +sub merge start, middle, theEnd + i = start: j = middle+1: k = start + while i<=middle OR j<=theEnd + select case + case i<=middle AND j<=theEnd + if A(i)<=A(j) then + tmp(k)=A(i) + i=i+1 + else + tmp(k)=A(j) + j=j+1 + end if + k=k+1 + case i<=middle + tmp(k)=A(i) + i=i+1 + k=k+1 + case else 'j<=theEnd + tmp(k)=A(j) + j=j+1 + k=k+1 + end select + wend + + for i = start to theEnd + A(i)=tmp(i) + next +end sub + +'=========================================== +sub printArray itemCount + for i = 1 to itemCount + print using("###", A(i)); + next i + print +end sub diff --git a/Task/Sorting-algorithms-Merge-sort/Logo/sorting-algorithms-merge-sort.logo b/Task/Sorting-algorithms-Merge-sort/Logo/sorting-algorithms-merge-sort.logo new file mode 100644 index 0000000000..e4130da0cf --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Logo/sorting-algorithms-merge-sort.logo @@ -0,0 +1,17 @@ +to split :size :front :list + if :size < 1 [output list :front :list] + output split :size-1 (lput first :list :front) (butfirst :list) +end + +to merge :small :large + if empty? :small [output :large] + ifelse lessequal? first :small first :large ~ + [output fput first :small merge butfirst :small :large] ~ + [output fput first :large merge butfirst :large :small] +end + +to mergesort :list + localmake "half split (count :list) / 2 [] :list + if empty? first :half [output :list] + output merge mergesort first :half mergesort last :half +end diff --git a/Task/Sorting-algorithms-Merge-sort/Logtalk/sorting-algorithms-merge-sort.logtalk b/Task/Sorting-algorithms-Merge-sort/Logtalk/sorting-algorithms-merge-sort.logtalk new file mode 100644 index 0000000000..bfc4058bad --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Logtalk/sorting-algorithms-merge-sort.logtalk @@ -0,0 +1,20 @@ +msort([], []) :- !. +msort([X], [X]) :- !. +msort([X, Y| Xs], Ys) :- + split([X, Y| Xs], X1s, X2s), + msort(X1s, Y1s), + msort(X2s, Y2s), + merge(Y1s, Y2s, Ys). + +split([], [], []). +split([X| Xs], [X| Ys], Zs) :- + split(Xs, Zs, Ys). + +merge([X| Xs], [Y| Ys], [X| Zs]) :- + X @=< Y, !, + merge(Xs, [Y| Ys], Zs). +merge([X| Xs], [Y| Ys], [Y| Zs]) :- + X @> Y, !, + merge([X | Xs], Ys, Zs). +merge([], Xs, Xs) :- !. +merge(Xs, [], Xs). diff --git a/Task/Sorting-algorithms-Merge-sort/Lucid/sorting-algorithms-merge-sort.lucid b/Task/Sorting-algorithms-Merge-sort/Lucid/sorting-algorithms-merge-sort.lucid new file mode 100644 index 0000000000..4df6bc6ad9 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Lucid/sorting-algorithms-merge-sort.lucid @@ -0,0 +1,17 @@ +msort(a) = if iseod(first next a) then a else merge(msort(b0),msort(b1)) fi + where + p = false fby not p; + b0 = a whenever p; + b1 = a whenever not p; + just(a) = ja + where + ja = a fby if iseod ja then eod else next a fi; + end; + merge(x,y) = if takexx then xx else yy fi + where + xx = (x) upon takexx; + yy = (y) upon not takexx; + takexx = if iseod(yy) then true elseif + iseod(xx) then false else xx <= yy fi; + end; + end; diff --git a/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-1.m b/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-1.m new file mode 100644 index 0000000000..5fa0fd2725 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-1.m @@ -0,0 +1,38 @@ +function list = mergeSort(list) + + if numel(list) <= 1 + return + else + middle = ceil(numel(list) / 2); + left = list(1:middle); + right = list(middle+1:end); + + left = mergeSort(left); + right = mergeSort(right); + + if left(end) <= right(1) + list = [left right]; + return + end + + %merge(left,right) + counter = 1; + while (numel(left) > 0) && (numel(right) > 0) + if(left(1) <= right(1)) + list(counter) = left(1); + left(1) = []; + else + list(counter) = right(1); + right(1) = []; + end + counter = counter + 1; + end + + if numel(left) > 0 + list(counter:end) = left; + elseif numel(right) > 0 + list(counter:end) = right; + end + %end merge + end %if +end %mergeSort diff --git a/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-2.m b/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-2.m new file mode 100644 index 0000000000..fbc1be5a4a --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/MATLAB/sorting-algorithms-merge-sort-2.m @@ -0,0 +1,5 @@ +>> mergeSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Merge-sort/Mathematica/sorting-algorithms-merge-sort.math b/Task/Sorting-algorithms-Merge-sort/Mathematica/sorting-algorithms-merge-sort.math new file mode 100644 index 0000000000..3c5ea12f69 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Mathematica/sorting-algorithms-merge-sort.math @@ -0,0 +1,19 @@ +MergeSort[m_List] := Module[{middle}, + If[Length[m] >= 2, + middle = Ceiling[Length[m]/2]; + Apply[Merge, + Map[MergeSort, Partition[m, middle, middle, {1, 1}, {}]]], + m + ] + ] + +Merge[left_List, right_List] := Module[ + {leftIndex = 1, rightIndex = 1}, + Table[ + Which[ + leftIndex > Length[left], right[[rightIndex++]], + rightIndex > Length[right], left[[leftIndex++]], + left[[leftIndex]] <= right[[rightIndex]], left[[leftIndex++]], + True, right[[rightIndex++]]], + {Length[left] + Length[right]}] + ] diff --git a/Task/Sorting-algorithms-Merge-sort/Maxima/sorting-algorithms-merge-sort.maxima b/Task/Sorting-algorithms-Merge-sort/Maxima/sorting-algorithms-merge-sort.maxima new file mode 100644 index 0000000000..55eeda2885 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Maxima/sorting-algorithms-merge-sort.maxima @@ -0,0 +1,22 @@ +merge(a, b) := block( + [c: [ ], i: 1, j: 1, p: length(a), q: length(b)], + while i <= p and j <= q do ( + if a[i] < b[j] then ( + c: endcons(a[i], c), + i: i + 1 + ) else ( + c: endcons(b[j], c), + j: j + 1 + ) + ), + if i > p then append(c, rest(b, j - 1)) else append(c, rest(a, i - 1)) +)$ + +mergesort(u) := block( + [n: length(u), k, a, b], + if n <= 1 then u else ( + a: rest(u, k: quotient(n, 2)), + b: rest(u, k - n), + merge(mergesort(a), mergesort(b)) + ) +)$ diff --git a/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury b/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury new file mode 100644 index 0000000000..e1e40f0f7b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Mercury/sorting-algorithms-merge-sort.mercury @@ -0,0 +1,33 @@ +:- func merge_sort(list(T)) = list(T). +merge_sort(U) = S :- merge_sort(U, S). + +:- pred merge_sort(list(T)::in, list(T)::out) is det. +merge_sort(U, S) :- merge_sort(list.length(U), U, S). + +:- pred merge_sort(int::in, list(T)::in, list(T)::out) is det. +merge_sort(L, U, S) :- + ( L > 1 -> + H = L // 2, + ( split(H, U, F, B) -> + merge_sort(H, F, SF), + merge_sort(L - H, B, SB), + merge(SF, SB, S) + ; throw(split_error) ) + ; S = U ). + +:- pred split(int::in, list(T)::in, list(T)::out, list(T)::out) is semidet. +split(N, L, S, E) :- + ( N = 0 -> S = [], E = L + ; N > 0, L = [H | L1], S = [H | S1], + split(N - 1, L1, S1, E) ). + +:- pred merge(list(T)::in, list(T)::in, list(T)::out) is det. +merge([], [], []). +merge([X|Xs], [], [X|Xs]). +merge([], [Y|Ys], [Y|Ys]). +merge([X|Xs], [Y|Ys], M) :- + ( compare(>, A, B) -> + merge([X|Xs], Ys, M0), + C = [Y|C0] + ; merge(Xs, [Y|Ys], C0), + C = [X|C0] ). diff --git a/Task/Sorting-algorithms-Merge-sort/NetRexx/sorting-algorithms-merge-sort.netrexx b/Task/Sorting-algorithms-Merge-sort/NetRexx/sorting-algorithms-merge-sort.netrexx new file mode 100644 index 0000000000..d9c2425ccb --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/NetRexx/sorting-algorithms-merge-sort.netrexx @@ -0,0 +1,83 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] + +lists = [ - + placesList - + , mergeSort(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method mergeSort(m = String[]) public constant binary returns String[] + + rl = String[m.length] + al = List mergeSort(Arrays.asList(m)) + al.toArray(rl) + + return rl + +method mergeSort(m = List) public constant binary returns ArrayList + + result = ArrayList(m.size) + left = ArrayList() + right = ArrayList() + if m.size > 1 then do + middle = m.size % 2 + loop x_ = 0 to middle - 1 + left.add(m.get(x_)) + end x_ + loop x_ = middle to m.size - 1 + right.add(m.get(x_)) + end x_ + left = mergeSort(left) + right = mergeSort(right) + if (Comparable left.get(left.size - 1)).compareTo(Comparable right.get(0)) <= 0 then do + left.addAll(right) + result.addAll(m) + end + else do + result = merge(left, right) + end + end + else do + result.addAll(m) + end + + return result + +method merge(left = List, right = List) public constant binary returns ArrayList + + result = ArrayList() + loop label mx while left.size > 0 & right.size > 0 + if (Comparable left.get(0)).compareTo(Comparable right.get(0)) <= 0 then do + result.add(left.get(0)) + left.remove(0) + end + else do + result.add(right.get(0)) + right.remove(0) + end + end mx + if left.size > 0 then do + result.addAll(left) + end + if right.size > 0 then do + result.addAll(right) + end + + return result diff --git a/Task/Sorting-algorithms-Merge-sort/OCaml/sorting-algorithms-merge-sort.ocaml b/Task/Sorting-algorithms-Merge-sort/OCaml/sorting-algorithms-merge-sort.ocaml new file mode 100644 index 0000000000..5ae06da9b3 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/OCaml/sorting-algorithms-merge-sort.ocaml @@ -0,0 +1,21 @@ +let rec split_at n xs = + match n, xs with + 0, xs -> + [], xs + | _, [] -> + failwith "index too large" + | n, x::xs when n > 0 -> + let xs', xs'' = split_at (pred n) xs in + x::xs', xs'' + | _, _ -> + invalid_arg "negative argument" + +let rec merge_sort cmp = function + [] -> [] + | [x] -> [x] + | xs -> + let xs, ys = split_at (List.length xs / 2) xs in + List.merge cmp (merge_sort cmp xs) (merge_sort cmp ys) + +let _ = + merge_sort compare [8;6;4;2;1;3;5;7;9] diff --git a/Task/Sorting-algorithms-Merge-sort/Oz/sorting-algorithms-merge-sort.oz b/Task/Sorting-algorithms-Merge-sort/Oz/sorting-algorithms-merge-sort.oz new file mode 100644 index 0000000000..d0a744c982 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Oz/sorting-algorithms-merge-sort.oz @@ -0,0 +1,15 @@ +declare + fun {MergeSort Xs} + case Xs + of nil then nil + [] [X] then [X] + else + Middle = {Length Xs} div 2 + Left Right + {List.takeDrop Xs Middle ?Left ?Right} + in + {List.merge {MergeSort Left} {MergeSort Right} Value.'<'} + end + end +in + {Show {MergeSort [3 1 4 1 5 9 2 6 5]}} diff --git a/Task/Sorting-algorithms-Merge-sort/PARI-GP/sorting-algorithms-merge-sort.pari b/Task/Sorting-algorithms-Merge-sort/PARI-GP/sorting-algorithms-merge-sort.pari new file mode 100644 index 0000000000..a5470a89bc --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PARI-GP/sorting-algorithms-merge-sort.pari @@ -0,0 +1,20 @@ +mergeSort(v)={ + if(#v<2, return(v)); + my(m=#v\2,left=vector(m,i,v[i]),right=vector(#v-m,i,v[m+i])); + left=mergeSort(left); + right=mergeSort(right); + merge(left, right) +}; +merge(u,v)={ + my(ret=vector(#u+#v),i=1,j=1); + for(k=1,#ret, + if(i<=#u & (j>#v | u[i]<v[j]), + ret[k]=u[i]; + i++ + , + ret[k]=v[j]; + j++ + ) + ); + ret +}; diff --git a/Task/Sorting-algorithms-Merge-sort/PHP/sorting-algorithms-merge-sort.php b/Task/Sorting-algorithms-Merge-sort/PHP/sorting-algorithms-merge-sort.php new file mode 100644 index 0000000000..7723ed2294 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PHP/sorting-algorithms-merge-sort.php @@ -0,0 +1,35 @@ +function mergesort($arr){ + if(count($arr) == 1 ) return $arr; + $mid = count($arr) / 2; + $left = array_slice($arr, 0, $mid); + $right = array_slice($arr, $mid); + $left = mergesort($left); + $right = mergesort($right); + return merge($left, $right); +} + +function merge($left, $right){ + $res = array(); + while (count($left) > 0 && count($right) > 0){ + if($left[0] > $right[0]){ + $res[] = $right[0]; + $right = array_slice($right , 1); + }else{ + $res[] = $left[0]; + $left = array_slice($left, 1); + } + } + while (count($left) > 0){ + $res[] = $left[0]; + $left = array_slice($left, 1); + } + while (count($right) > 0){ + $res[] = $right[0]; + $right = array_slice($right, 1); + } + return $res; +} + +$arr = array( 1, 5, 2, 7, 3, 9, 4, 6, 8); +$arr = mergesort($arr); +echo implode(',',$arr); diff --git a/Task/Sorting-algorithms-Merge-sort/PL-I/sorting-algorithms-merge-sort.pli b/Task/Sorting-algorithms-Merge-sort/PL-I/sorting-algorithms-merge-sort.pli new file mode 100644 index 0000000000..5f937fec88 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PL-I/sorting-algorithms-merge-sort.pli @@ -0,0 +1,49 @@ +MERGE: PROCEDURE (A,LA,B,LB,C); + +/* Merge A(1:LA) with B(1:LB), putting the result in C + B and C may share the same memory, but not with A. +*/ + DECLARE (A(*),B(*),C(*)) BYADDR POINTER; + DECLARE (LA,LB) BYVALUE NONASGN FIXED BIN(31); + DECLARE (I,J,K) FIXED BIN(31); + DECLARE (SX) CHAR(58) VAR BASED (PX); + DECLARE (SY) CHAR(58) VAR BASED (PY); + DECLARE (PX,PY) POINTER; + + I=1; J=1; K=1; + DO WHILE ((I <= LA) & (J <= LB)); + PX=A(I); PY=B(J); + IF(SX <= SY) THEN + DO; C(K)=A(I); K=K+1; I=I+1; END; + ELSE + DO; C(K)=B(J); K=K+1; J=J+1; END; + END; + DO WHILE (I <= LA); + C(K)=A(I); I=I+1; K=K+1; + END; + RETURN; +END MERGE; + +MERGESORT: PROCEDURE (AP,N) RECURSIVE ; + +/* Sort the array AP containing N pointers to strings */ + + DECLARE (AP(*)) BYADDR POINTER; + DECLARE (N) BYVALUE NONASGN FIXED BINARY(31); + DECLARE (M,I) FIXED BINARY; + DECLARE AMP1(1) POINTER BASED(PAM); + DECLARE (pX,pY,PAM) POINTER; + DECLARE SX CHAR(58) VAR BASED(pX); + DECLARE SY CHAR(58) VAR BASED(pY); + + IF (N=1) THEN RETURN; + M = trunc((N+1)/2); + IF (M>1) THEN CALL MERGESORT(AP,M); + PAM=ADDR(AP(M+1)); + IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M); + pX=AP(M); pY=AP(M+1); + IF SX <= SY then return; /* Skip Merge */ + DO I=1 to M; TP(I)=AP(I); END; + CALL MERGE(TP,M,AMP1,N-M,AP); + RETURN; +END MERGESORT; diff --git a/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort.pascal b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort.pascal new file mode 100644 index 0000000000..7bb13e8836 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort.pascal @@ -0,0 +1,84 @@ +program MergeSortDemo; + +type + TIntArray = array of integer; + +function merge(left, right: TIntArray): TIntArray; + var + i, j: integer; + begin + j := 0; + setlength(merge, length(left) + length(right)); + while (length(left) > 0) and (length(right) > 0) do + begin + if left[0] <= right[0] then + begin + merge[j] := left[0]; + inc(j); + for i := low(left) to high(left) - 1 do + left[i] := left[i+1]; + setlength(left, length(left) - 1); + end + else + begin + merge[j] := right[0]; + inc(j); + for i := low(right) to high(right) - 1 do + right[i] := right[i+1]; + setlength(right, length(right) - 1); + end; + end; + if length(left) > 0 then + for i := low(left) to high(left) do + merge[j + i] := left[i]; + j := j + length(left); + if length(right) > 0 then + for i := low(right) to high(right) do + merge[j + i] := right[i]; + end; + +function mergeSort(m: TIntArray): TIntArray; + var + left, right: TIntArray; + i, middle: integer; + begin + setlength(mergeSort, length(m)); + if length(m) = 1 then + mergeSort[0] := m[0] + else if length(m) > 1 then + begin + middle := length(m) div 2; + setlength(left, middle); + setlength(right, length(m)-middle); + for i := low(left) to high(left) do + left[i] := m[i]; + for i := low(right) to high(right) do + right[i] := m[middle+i]; + left := mergeSort(left); + right := mergeSort(right); + mergeSort := merge(left, right); + end; + end; + +var + data: TIntArray; + i: integer; + +begin + setlength(data, 8); + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + data := mergeSort(data); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Merge-sort/Perl-6/sorting-algorithms-merge-sort.pl6 b/Task/Sorting-algorithms-Merge-sort/Perl-6/sorting-algorithms-merge-sort.pl6 new file mode 100644 index 0000000000..57751d0d81 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Perl-6/sorting-algorithms-merge-sort.pl6 @@ -0,0 +1,17 @@ +sub merge_sort ( @a ) { + return @a if @a <= 1; + + my $m = @a.elems div 2; + my @l = merge_sort @a[ 0 ..^ $m ]; + my @r = merge_sort @a[ $m ..^ @a ]; + + return @l, @r if @l[*-1] !after @r[0]; + return gather { + take @l[0] before @r[0] ?? @l.shift !! @r.shift + while @l and @r; + take @l, @r; + } +} +my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4; +say 'input = ' ~ @data; +say 'output = ' ~ @data.&merge_sort; diff --git a/Task/Sorting-algorithms-Merge-sort/Perl/sorting-algorithms-merge-sort.pl b/Task/Sorting-algorithms-Merge-sort/Perl/sorting-algorithms-merge-sort.pl new file mode 100644 index 0000000000..803170b07e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Perl/sorting-algorithms-merge-sort.pl @@ -0,0 +1,18 @@ +sub merge_sort { + my @x = @_; + return @x if @x < 2; + my $m = int @x / 2; + my @a = merge_sort(@x[0 .. $m - 1]); + my @b = merge_sort(@x[$m .. $#x]); + for (@x) { + $_ = !@a ? shift @b + : !@b ? shift @a + : $a[0] <= $b[0] ? shift @a + : shift @b; + } + @x; +} + +my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); +@a = merge_sort @a; +print "@a\n"; diff --git a/Task/Sorting-algorithms-Merge-sort/PicoLisp/sorting-algorithms-merge-sort.l b/Task/Sorting-algorithms-Merge-sort/PicoLisp/sorting-algorithms-merge-sort.l new file mode 100644 index 0000000000..2dcc141919 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PicoLisp/sorting-algorithms-merge-sort.l @@ -0,0 +1,16 @@ +(de alt (List) + (if List (cons (car List) (alt (cddr List))) ()) ) + +(de merge (L1 L2) + (cond + ((not L2) L1) + ((< (car L1) (car L2)) + (cons (car L1) (merge L2 (cdr L1)))) + (T (cons (car L2) (merge L1 (cdr L2)))) ) ) + +(de mergesort (List) + (if (cdr List) + (merge (mergesort (alt List)) (mergesort (alt (cdr List)))) + List) ) + +(mergesort (8 1 5 3 9 0 2 7 6 4)) diff --git a/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh new file mode 100644 index 0000000000..efdb55c28b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh @@ -0,0 +1,105 @@ +Function Merge-Array( [Object[]] $lhs, [Object[]] $rhs ) +{ + $result = @() + $lhsl = $lhs.length + $rhsl = $rhs.length + if( $lhsl -gt 0 ) + { + if( $rhsl -gt 0 ) + { + $i = 0 + for( $j = 0; ( $i -lt $lhsl ) -and ( $j -lt $rhsl ); ) + { + if( $lhs[ $i ] -le $rhs[ $j ] ) + { + $result += $lhs[ $i ] + [void] ( $i++ ) + } else { + $result += $rhs[ $j ] + [void] ( $j++ ) + } + } + if( $i -lt $lhsl ) + { + $result += $lhs[ $i..( $lhsl - 1 ) ] + } + if( $j -lt $rhsl ) + { + $result += $rhs[ $j..( $rhsl - 1 ) ] + } + } else { + for( $i = 0; $i -lt $lhsl; $i++ ) + { + if( $rhs -le $lhs[ $i ] ) + { + $result += $rhs + break + } + $result += $lhs[ $i ] + } + if( $i -lt $lhsl ) + { + $result += $lhs[ $i..( $lhsl - 1 ) ] + } + } + } else { + if( $rhsl -gt 0 ) + { + for( $i = 0; $i -lt $rhsl; $i++ ) + { + if( $lhs -le $rhs[ $i ] ) + { + $result += $lhs + break + } + $result += $rhs[ $i ] + } + if( $i -lt $rhsl ) + { + $result += $rhs[ $i..( $rhsl - 1 ) ] + } + } else { + if( $lhs -lt $rhs ) + { + $result += $lhs + $result += $rhs + } else { + $result += $rhs + $result += $lhs + } + } + } + $result +} + +Function MergeSort( [Object[]] $data ) +{ + $datal = $data.length - 1 + if( $datal -gt 0 ) + { + $middle = [Math]::Floor( $datal / 2 ) + $left = @() + $left += MergeSort $data[ 0..$middle ] + $right = @() + $right += MergeSort $data[ ( $middle + 1 )..$datal ] + if( $left[ -1 ] -le $right[ 0 ] ) + { + $result = @() + $result += $left + $result += $right + $result + } elseif( $right[ -1 ] -le $left[ 0 ] ) + { + $result = @() + $result += $right + $result += $left + $result + } else { + Merge-Array $left $right + } + } else { + $data + } +} + +$l = 100; MergeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Merge-sort/Prolog/sorting-algorithms-merge-sort.pro b/Task/Sorting-algorithms-Merge-sort/Prolog/sorting-algorithms-merge-sort.pro new file mode 100644 index 0000000000..1dc4d1cabb --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Prolog/sorting-algorithms-merge-sort.pro @@ -0,0 +1,18 @@ +% msort( L, S ) +% True if S is a sorted copy of L, using merge sort +msort( [], [] ). +msort( [X], [X] ). +msort( U, S ) :- split(U, L, R), msort(L, SL), msort(R, SR), merge(SL, SR, S). + +% split( LIST, L, R ) +% Alternate elements of LIST in L and R +split( [], [], [] ). +split( [X], [X], [] ). +split( [L,R|T], [L|LT], [R|RT] ) :- split( T, LT, RT ). + +% merge( LS, RS, M ) +% Assuming LS and RS are sorted, True if M is the sorted merge of the two +merge( [], RS, RS ). +merge( LS, [], LS ). +merge( [L|LS], [R|RS], [L|T] ) :- L =< R, merge( LS, [R|RS], T). +merge( [L|LS], [R|RS], [R|T] ) :- L > R, merge( [L|LS], RS, T). diff --git a/Task/Sorting-algorithms-Merge-sort/PureBasic/sorting-algorithms-merge-sort.purebasic b/Task/Sorting-algorithms-Merge-sort/PureBasic/sorting-algorithms-merge-sort.purebasic new file mode 100644 index 0000000000..546bf848a8 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PureBasic/sorting-algorithms-merge-sort.purebasic @@ -0,0 +1,84 @@ +Procedure display(List m()) + ForEach m() + Print(LSet(Str(m()), 3," ")) + Next + PrintN("") +EndProcedure + +;overwrites list m() with the merger of lists ma() and mb() +Procedure merge(List m(), List ma(), List mb()) + FirstElement(m()) + Protected ma_elementExists = FirstElement(ma()) + Protected mb_elementExists = FirstElement(mb()) + Repeat + If ma() <= mb() + m() = ma(): NextElement(m()) + ma_elementExists = NextElement(ma()) + Else + m() = mb(): NextElement(m()) + mb_elementExists = NextElement(mb()) + EndIf + Until Not (ma_elementExists And mb_elementExists) + + If ma_elementExists + Repeat + m() = ma(): NextElement(m()) + Until Not NextElement(ma()) + ElseIf mb_elementExists + Repeat + m() = mb(): NextElement(m()) + Until Not NextElement(mb()) + EndIf +EndProcedure + +Procedure mergesort(List m()) + Protected NewList ma() + Protected NewList mb() + + If ListSize(m()) > 1 + Protected current, middle = (ListSize(m()) / 2 ) - 1 + + FirstElement(m()) + While current <= middle + AddElement(ma()) + ma() = m() + NextElement(m()): current + 1 + Wend + + PreviousElement(m()) + While NextElement(m()) + AddElement(mb()) + mb() = m() + Wend + + mergesort(ma()) + mergesort(mb()) + LastElement(ma()): FirstElement(mb()) + If ma() <= mb() + FirstElement(m()) + FirstElement(ma()) + Repeat + m() = ma(): NextElement(m()) + Until Not NextElement(ma()) + Repeat + m() = mb(): NextElement(m()) + Until Not NextElement(mb()) + Else + merge(m(), ma(), mb()) + EndIf + EndIf +EndProcedure + +If OpenConsole() + Define i + NewList x() + + For i = 1 To 21: AddElement(x()): x() = Random(60): Next + display(x()) + mergesort(x()) + display(x()) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-1.py b/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-1.py new file mode 100644 index 0000000000..9d4a916e52 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-1.py @@ -0,0 +1,13 @@ +from heapq import merge + +def merge_sort(m): + if len(m) <= 1: + return m + + middle = len(m) / 2 + left = m[:middle] + right = m[middle:] + + left = merge_sort(left) + right = merge_sort(right) + return list(merge(left, right)) diff --git a/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-2.py b/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-2.py new file mode 100644 index 0000000000..2af83c430e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Python/sorting-algorithms-merge-sort-2.py @@ -0,0 +1,17 @@ +def merge(left, right): + result = [] + left_idx, right_idx = 0, 0 + while left_idx < len(left) and right_idx < len(right): + # change the direction of this comparison to change the direction of the sort + if left[left_idx] <= right[right_idx]: + result.append(left[left_idx]) + left_idx += 1 + else: + result.append(right[right_idx]) + right_idx += 1 + + if left: + result.extend(left[left_idx:]) + if right: + result.extend(right[right_idx:]) + return result diff --git a/Task/Sorting-algorithms-Merge-sort/R/sorting-algorithms-merge-sort.r b/Task/Sorting-algorithms-Merge-sort/R/sorting-algorithms-merge-sort.r new file mode 100644 index 0000000000..b1d5a04e94 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/R/sorting-algorithms-merge-sort.r @@ -0,0 +1,40 @@ +mergesort <- function(m) +{ + merge_ <- function(left, right) + { + result <- c() + while(length(left) > 0 && length(right) > 0) + { + if(left[1] <= right[1]) + { + result <- c(result, left[1]) + left <- left[-1] + } else + { + result <- c(result, right[1]) + right <- right[-1] + } + } + if(length(left) > 0) result <- c(result, left) + if(length(right) > 0) result <- c(result, right) + result + } + + len <- length(m) + if(len <= 1) m else + { + middle <- length(m) / 2 + left <- m[1:floor(middle)] + right <- m[floor(middle+1):len] + left <- mergesort(left) + right <- mergesort(right) + if(left[length(left)] <= right[1]) + { + c(left, right) + } else + { + merge_(left, right) + } + } +} +mergesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782 diff --git a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort.rexx b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort.rexx new file mode 100644 index 0000000000..ca36354703 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort.rexx @@ -0,0 +1,63 @@ +/*REXX program sorts a (stemmed) array using the merge-sort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call mergeSort highItem /*invoke the merge sort for array*/ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign default value for @ stem*/ +@.1='---The seven deadly sins---' /*everybody: pick your favorite.*/ +@.2='===========================' +@.3='pride' +@.4='avarice' +@.5='wrath' +@.6='envy' +@.7='gluttony' +@.8='sloth' +@.9='lust' + do highItem=1 while @.highItem\=='' /*find number of entries*/ + end +highItem=highItem-1 /*adjust highItem by -1.*/ +return +/*──────────────────────────────────MERGETO@ subroutine─────────────────*/ +mergeTo@: procedure expose @. !.; parse arg L,n; if n==1 then return +if n==2 then do; h=L+1 + if @.L>@.h then do; _=@.h; @.h=@.L; @.L=_; end + return + end +m=n%2 +call mergeTo@ L+m,n-m +call mergeTo! L,m,1 +i=1; j=L+m; do k=L while k<j + if j==L+n | !.i<=@.j then do; @.k=!.i; i=i+1; end + else do; @.k=@.j; j=j+1; end + end /*k*/ +return +/*──────────────────────────────────MERGESORT subroutine────────────────*/ +mergeSort: procedure expose @.; call mergeTo@ 1,arg(1) +return +/*──────────────────────────────────MERGETO! subroutine─────────────────*/ +mergeTo!: procedure expose @. !.; parse arg L,n,_ +if n==1 then do; !._=@.L; return; end +if n==2 then do + h=L+1; q=1+_ + if @.L>@.h then do; q=_; _=q+1; end + !._=@.L; !.q=@.h + return + end +m=n%2 +call mergeTo@ L,m +call mergeTo! L+m,n-m,m+_ +i=L; j=m+_ + do k=_ while k<j + if j==n+_ | @.i<=!.j then do; !.k=@.i; i=i+1; end + else do; !.k=!.j; j=j+1; end + end /*k*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(highItem) /*maximum the width of any line. */ + do j=1 for highItem + say 'element' right(j,widthH) arg(1)':' @.j + end /*j*/ +say copies('─',60) /*show a seperator line (fence). */ +return diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb new file mode 100644 index 0000000000..328b661a8d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb @@ -0,0 +1,34 @@ +def merge_sort(m) + if m.length <= 1 + return m + end + + middle = m.length / 2 + left = m[0,middle] + right = m[middle..-1] + + left = merge_sort(left) + right = merge_sort(right) + merge(left, right) +end + +def merge(left, right) + result = [] + + until left.empty? || right.empty? + # change the direction of this comparison to change the direction of the sort + if left.first <= right.first + result << left.shift + else + result << right.shift + end + end + + unless left.empty? + result += left + end + unless right.empty? + result += right + end + result +end diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb new file mode 100644 index 0000000000..0354595a9d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb @@ -0,0 +1,36 @@ +class Array + def mergesort(&comparitor) + if length <= 1 + self + else + unless comparitor + comparitor = lambda {|a, b| a <=> b} + end + middle = length / 2 + left = self[0, middle].mergesort(&comparitor) + right = self[middle..-1].mergesort(&comparitor) + merge(left, right, comparitor) + end + end + + protected + def merge(left, right, comparitor) + if left.empty? + right + elsif right.empty? + left + elsif comparitor.call(left.first, right.first) <= 0 + [left.first] + merge(left[1..-1], right, comparitor) + else + [right.first] + merge(left, right[1..-1], comparitor) + end + end +end + +ary = [7,6,5,9,8,4,3,1,2,0] +ary.mergesort # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] +ary.mergesort {|a, b| b <=> a} # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] + +ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] +ary.mergesort {|a, b| a[1] <=> b[1]} +# => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]] diff --git a/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-1.scala b/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-1.scala new file mode 100644 index 0000000000..861169fc2a --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-1.scala @@ -0,0 +1,15 @@ +def mergeSort(input: List[Int]) = { + def merge(left: List[Int], right: List[Int]): Stream[Int] = (left, right) match { + case (x :: xs, y :: ys) if x <= y => x #:: merge(xs, right) + case (x :: xs, y :: ys) => y #:: merge(left, ys) + case _ => if (left.isEmpty) right.toStream else left.toStream + } + def sort(input: List[Int], length: Int): List[Int] = input match { + case Nil | List(_) => input + case _ => + val middle = length / 2 + val (left, right) = input splitAt middle + merge(sort(left, middle), sort(right, middle + length % 2)).toList + } + sort(input, input.length) +} diff --git a/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-2.scala b/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-2.scala new file mode 100644 index 0000000000..173428860f --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort-2.scala @@ -0,0 +1,2 @@ + case (x :: xs, y :: ys) if x < y => Stream.cons(x, merge(xs, right)) + case (x :: xs, y :: ys) => Stream.cons(y, merge(left, ys)) diff --git a/Task/Sorting-algorithms-Merge-sort/Scheme/sorting-algorithms-merge-sort.ss b/Task/Sorting-algorithms-Merge-sort/Scheme/sorting-algorithms-merge-sort.ss new file mode 100644 index 0000000000..5f2281a9ea --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Scheme/sorting-algorithms-merge-sort.ss @@ -0,0 +1,23 @@ +(define (merge-sort l gt?) + (define (merge left right) + (cond + ((null? left) + right) + ((null? right) + left) + ((gt? (car left) (car right)) + (cons (car right) + (merge left (cdr right)))) + (else + (cons (car left) + (merge (cdr left) right))))) + (define (take l n) + (if (zero? n) + (list) + (cons (car l) + (take (cdr l) (- n 1))))) + (let ((half (quotient (length l) 2))) + (if (zero? half) + l + (merge (merge-sort (take l half) gt?) + (merge-sort (list-tail l half) gt?))))) diff --git a/Task/Sorting-algorithms-Merge-sort/Seed7/sorting-algorithms-merge-sort.seed7 b/Task/Sorting-algorithms-Merge-sort/Seed7/sorting-algorithms-merge-sort.seed7 new file mode 100644 index 0000000000..176cc253bc --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Seed7/sorting-algorithms-merge-sort.seed7 @@ -0,0 +1,35 @@ +const proc: mergeSort2 (inout array elemType: arr, in integer: lo, in integer: hi, inout array elemType: scratch) is func + local + var integer: mid is 0; + var integer: k is 0; + var integer: t_lo is 0; + var integer: t_hi is 0; + begin + if lo < hi then + mid := (lo + hi) div 2; + mergeSort2(arr, lo, mid, scratch); + mergeSort2(arr, succ(mid), hi, scratch); + t_lo := lo; + t_hi := succ(mid); + for k range lo to hi do + if t_lo <= mid and (t_hi > hi or arr[t_lo] <= arr[t_hi]) then + scratch[k] := arr[t_lo]; + incr(t_lo); + else + scratch[k] := arr[t_hi]; + incr(t_hi); + end if; + end for; + for k range lo to hi do + arr[k] := scratch[k]; + end for; + end if; + end func; + +const proc: mergeSort2 (inout array elemType: arr) is func + local + var array elemType: scratch is 0 times elemType.value; + begin + scratch := length(arr) times elemType.value; + mergeSort2(arr, 1, length(arr), scratch); + end func; diff --git a/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml b/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml new file mode 100644 index 0000000000..f854d7afd7 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml @@ -0,0 +1,16 @@ +fun merge cmp ([], ys) = ys + | merge cmp (xs, []) = xs + | merge cmp (xs as x::xs', ys as y::ys') = + case cmp (x, y) of GREATER => y :: merge cmp (xs, ys') + | _ => x :: merge cmp (xs', ys) +; +fun merge_sort cmp [] = [] + | merge_sort cmp [x] = [x] + | merge_sort cmp xs = let + val ys = List.take (xs, length xs div 2) + val zs = List.drop (xs, length xs div 2) + in + merge cmp (merge_sort cmp ys, merge_sort cmp zs) + end +; +merge_sort Int.compare [8,6,4,2,1,3,5,7,9] diff --git a/Task/Sorting-algorithms-Merge-sort/Tcl/sorting-algorithms-merge-sort.tcl b/Task/Sorting-algorithms-Merge-sort/Tcl/sorting-algorithms-merge-sort.tcl new file mode 100644 index 0000000000..ede14f30cd --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Tcl/sorting-algorithms-merge-sort.tcl @@ -0,0 +1,33 @@ +package require Tcl 8.5 + +proc mergesort m { + set len [llength $m] + if {$len <= 1} { + return $m + } + set middle [expr {$len / 2}] + set left [lrange $m 0 [expr {$middle - 1}]] + set right [lrange $m $middle end] + return [merge [mergesort $left] [mergesort $right]] +} + +proc merge {left right} { + set result [list] + while {[set lleft [llength $left]] > 0 && [set lright [llength $right]] > 0} { + if {[lindex $left 0] <= [lindex $right 0]} { + set left [lassign $left value] + } else { + set right [lassign $right value] + } + lappend result $value + } + if {$lleft > 0} { + lappend result {*}$left + } + if {$lright > 0} { + set result [concat $result $right] ;# another way append elements + } + return $result +} + +puts [mergesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Merge-sort/UnixPipes/sorting-algorithms-merge-sort.unixpipes b/Task/Sorting-algorithms-Merge-sort/UnixPipes/sorting-algorithms-merge-sort.unixpipes new file mode 100644 index 0000000000..5b9bf030ff --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/UnixPipes/sorting-algorithms-merge-sort.unixpipes @@ -0,0 +1,16 @@ +split() { + (while read a b ; do + echo $a > $1 ; echo $b > $2 + done) +} + +mergesort() { + xargs -n 2 | (read a b; test -n "$b" && ( + lc="1.$1" ; gc="2.$1" + (echo $a $b;cat)|split >(mergesort $lc >$lc) >( mergesort $gc >$gc) + sort -m $lc $gc + rm -f $lc $gc; + ) || echo $a) +} + +cat to.sort | mergesort diff --git a/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-1.ursala b/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-1.ursala new file mode 100644 index 0000000000..49a27f1369 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-1.ursala @@ -0,0 +1,7 @@ +#import std + +mergesort "p" = @iNCS :-0 ~&B^?a\~&YaO "p"?abh/~&alh2faltPrXPRC ~&arh2falrtPXPRC + +#show+ + +example = mergesort(lleq) <'zoh','zpb','hhh','egi','bff','cii','yid'> diff --git a/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-2.ursala b/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-2.ursala new file mode 100644 index 0000000000..d2748bbb9d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ursala/sorting-algorithms-merge-sort-2.ursala @@ -0,0 +1 @@ +mergesort "p" = "p"-< diff --git a/Task/Sorting-algorithms-Merge-sort/V/sorting-algorithms-merge-sort.v b/Task/Sorting-algorithms-Merge-sort/V/sorting-algorithms-merge-sort.v new file mode 100644 index 0000000000..3c471210ab --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/V/sorting-algorithms-merge-sort.v @@ -0,0 +1,18 @@ +[merge + [mergei + uncons [swap [>] split] dip + [[*m] e2 [*a1] b1 a2 : [*m *a1 e2] b1 a2] view]. + + [a b : [] a b] view + [size zero?] [pop concat] + [mergei] + tailrec]. + +[msort + [splitat [arr a : [arr a take arr a drop]] view i]. + [splitarr dup size 2 / >int splitat]. + + [small?] [] + [splitarr] + [merge] + binrec]. diff --git a/Task/Sorting-algorithms-Merge-sort/XPL0/sorting-algorithms-merge-sort.xpl0 b/Task/Sorting-algorithms-Merge-sort/XPL0/sorting-algorithms-merge-sort.xpl0 new file mode 100644 index 0000000000..ac1d1200e5 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/XPL0/sorting-algorithms-merge-sort.xpl0 @@ -0,0 +1,26 @@ +code Reserve=3, ChOut=8, IntOut=11; + +proc MergeSort(A, Low, High); \Sort array A from Low to High +int A, Low, High; +int B, Mid, H, I, J, K; +[if Low >= High then return; +Mid:= (Low+High) >> 1; \split array in half (roughly) +MergeSort(A, Low, Mid); \sort left half +MergeSort(A, Mid+1, High); \sort right half +\Merge the two halves in to sorted order +B:= Reserve((High-Low+1)*4); \reserve space for working array (4 bytes/int) +H:= Low; I:= Low; J:= Mid+1; +while H<=Mid & J<=High do \merge while both halves have items + if A(H) <= A(J) then [B(I):= A(H); I:= I+1; H:= H+1] + else [B(I):= A(J); I:= I+1; J:= J+1]; +if H > Mid then \copy any remaining elements + for K:= J to High do [B(I):= A(K); I:= I+1] +else for K:= H to Mid do [B(I):= A(K); I:= I+1]; +for K:= Low to High do A(K):= B(K); +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +MergeSort(A, 0, 10-1); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Pancake-sort/0DESCRIPTION b/Task/Sorting-algorithms-Pancake-sort/0DESCRIPTION new file mode 100644 index 0000000000..a0a87c3b6a --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/0DESCRIPTION @@ -0,0 +1,16 @@ +{{Sorting Algorithm}} +Sort an array of integers (of any convenient size) into ascending order using [[wp:Pancake sorting|Pancake sorting]]. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: + Before: + '''6 7 8 9''' 2 5 3 4 1 + After: + '''9 8 7 6''' 2 5 3 4 1 + +Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it '''must''' be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) + +Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended). + +For more information on pancake sorting, see [[wp:Pancake sorting|the Wikipedia entry]]. + +See also: +* [[Number reversal game]] +* [[Topswops]] diff --git a/Task/Sorting-algorithms-Pancake-sort/1META.yaml b/Task/Sorting-algorithms-Pancake-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.ada b/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.ada new file mode 100644 index 0000000000..7f48fb8b75 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.ada @@ -0,0 +1,45 @@ +with Ada.Text_IO; +procedure Pancake_Sort is + generic + type Element_Type is private; + type Index_Type is range <>; + type Array_Type is array (Index_Type range <>) of Element_Type; + with function ">" (Left, Right : Element_Type) return Boolean is <>; + procedure Pancake_Sort (Data: in out Array_Type); + + procedure Pancake_Sort (Data: in out Array_Type) is + procedure Flip (Up_To : in Index_Type) is + Temp : constant Array_Type := Data (Data'First .. Up_To); + begin + for I in Temp'Range loop + Data (I) := Temp (Temp'First + Up_To - I); + end loop; + end Flip; + Max_Index : Index_Type; + begin + for I in reverse Data'First + 1 .. Data'Last loop + Max_Index := Data'First; + for A in Data'First + 1 .. I loop + if Data(A) > Data (Max_Index) then + Max_Index := A; + end if; + end loop; + if Max_Index /= I then + if Max_Index > Data'First then + Flip (Max_Index); + end if; + Flip (I); + end if; + end loop; + end Pancake_Sort; + + type Integer_Array is array (Positive range <>) of Integer; + procedure Int_Pancake_Sort is new Pancake_Sort (Integer, Positive, Integer_Array); + Test_Array : Integer_Array := (3, 14, 1, 5, 9, 2, 6, 3); +begin + Int_Pancake_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Pancake_Sort; diff --git a/Task/Sorting-algorithms-Pancake-sort/AutoHotkey/sorting-algorithms-pancake-sort.ahk b/Task/Sorting-algorithms-Pancake-sort/AutoHotkey/sorting-algorithms-pancake-sort.ahk new file mode 100644 index 0000000000..8e4c6a5e10 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/AutoHotkey/sorting-algorithms-pancake-sort.ahk @@ -0,0 +1,49 @@ +;--------------------------------------------------------------------------- +Loop { ; test loop +;--------------------------------------------------------------------------- + Loop, % Data0 := 10 + Random, Data%A_Index%, 10, 99 + Unsorted := Array2List("Data") + PancakeSort("Data") + Sorted := Array2List("Data") + MsgBox, 1, Pancake Sort, %Unsorted%`n%Sorted% + IfMsgBox, Cancel, Break +} + + + +;--------------------------------------------------------------------------- +PancakeSort(Array) { ; implementation of pancake sort algorithm +;--------------------------------------------------------------------------- + Loop, % %Array%0 - 1 { + m := 0 + Loop, % s := %Array%0 - A_Index + 1 + If (m <= %Array%%A_Index%) + m := %Array%%A_Index%, p := A_Index + If (p < s) && (p > 1) + Flip(Array, p) + If (p < s) + Flip(Array, s) + } +} + + + +;--------------------------------------------------------------------------- +Flip(Array, n) { ; flip the first n members of Array +;--------------------------------------------------------------------------- + Loop, % x := n // 2 { + i := n - A_Index + 1 + %Array%%i% := (%Array%%A_Index% "", %Array%%A_Index% := %Array%%i%) + } +} + + + +;--------------------------------------------------------------------------- +Array2List(Array) { ; returns a space separated list from an array +;--------------------------------------------------------------------------- + Loop, % %Array%0 + List .= (A_Index = 1 ? "" : " ") %Array%%A_Index% + Return, List +} diff --git a/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-1.basic b/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-1.basic new file mode 100644 index 0000000000..663856627d --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-1.basic @@ -0,0 +1,46 @@ +RANDOMIZE TIMER + +DIM nums(9) AS INTEGER +DIM L0 AS INTEGER, L1 AS INTEGER, n AS INTEGER + +'initial values +FOR L0 = 0 TO 9 + nums(L0) = L0 +NEXT +'scramble +FOR L0 = 9 TO 1 STEP -1 + n = INT(RND * (L0)) + 1 + IF n <> L0 THEN SWAP nums(n), nums(L0) +NEXT +'display initial condition +FOR L0 = 0 TO 9 + PRINT nums(L0); +NEXT +PRINT + +FOR L1 = 9 TO 1 STEP -1 + n = 0 + FOR L0 = 1 TO L1 + IF nums(n) < nums(L0) THEN n = L0 + NEXT + + IF (n < L1) THEN + IF (n > 0) THEN + FOR L0 = 0 TO (n \ 2) + SWAP nums(L0), nums(n - L0) + NEXT + FOR L0 = 0 TO 9 + PRINT nums(L0); + NEXT + PRINT + END IF + FOR L0 = 0 TO (L1 \ 2) + SWAP nums(L0), nums(L1 - L0) + NEXT + + FOR L0 = 0 TO 9 + PRINT nums(L0); + NEXT + PRINT + END IF +NEXT diff --git a/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-2.basic b/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-2.basic new file mode 100644 index 0000000000..cf336f7d8f --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/BASIC/sorting-algorithms-pancake-sort-2.basic @@ -0,0 +1,55 @@ +RANDOMIZE TIMER + +CONST delay = .1 'controls display speed + +DIM nums(14) AS INTEGER +DIM L0 AS INTEGER, L1 AS INTEGER, n AS INTEGER, ttmp AS SINGLE + +'initial values +FOR L0 = 0 TO 14 + nums(L0) = L0 +NEXT +'scramble +FOR L0 = 14 TO 1 STEP -1 + n = INT(RND * (L0)) + 1 + IF n <> L0 THEN SWAP nums(n), nums(L0) +NEXT + +'display initial condition +CLS +GOSUB displayer + +FOR L1 = 14 TO 1 STEP -1 + n = 0 + FOR L0 = 1 TO L1 + IF nums(n) < nums(L0) THEN n = L0 + NEXT + + IF (n < L1) THEN + IF (n > 0) THEN + FOR L0 = 0 TO (n \ 2) + SWAP nums(L0), nums(n - L0) + NEXT + GOSUB displayer + END IF + FOR L0 = 0 TO (L1 \ 2) + SWAP nums(L0), nums(L1 - L0) + NEXT + + GOSUB displayer + END IF +NEXT + +COLOR 7 +END + +displayer: + LOCATE 1, 1 + FOR L0 = 0 TO 14 + COLOR nums(L0) + 1 + IF nums(L0) < 10 THEN PRINT " "; + PRINT RTRIM$(LTRIM$(STR$(nums(L0)))); STRING$(nums(L0), 219); SPACE$(20) + NEXT + ttmp = TIMER + DO WHILE TIMER < ttmp + delay: LOOP + RETURN diff --git a/Task/Sorting-algorithms-Pancake-sort/BBC-BASIC/sorting-algorithms-pancake-sort.bbc b/Task/Sorting-algorithms-Pancake-sort/BBC-BASIC/sorting-algorithms-pancake-sort.bbc new file mode 100644 index 0000000000..670e3fe984 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/BBC-BASIC/sorting-algorithms-pancake-sort.bbc @@ -0,0 +1,32 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCpancakesort(test()) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCpancakesort(a()) + LOCAL i%, j%, m% + FOR i% = DIM(a(),1)+1 TO 2 STEP -1 + m% = 0 + FOR j% = 1 TO i%-1 + IF a(j%) > a(m%) m% = j% + NEXT + m% += 1 + IF m% < i% THEN + IF m% > 1 PROCflip(a(), m%) + PROCflip(a(), i%) + ENDIF + NEXT + ENDPROC + + DEF PROCflip(a(), n%) + IF n% < 2 ENDPROC + LOCAL i% + n% -= 1 + FOR i% = 0 TO n% DIV 2 + SWAP a(i%), a(n%-i%) + NEXT + ENDPROC diff --git a/Task/Sorting-algorithms-Pancake-sort/C++/sorting-algorithms-pancake-sort.cpp b/Task/Sorting-algorithms-Pancake-sort/C++/sorting-algorithms-pancake-sort.cpp new file mode 100644 index 0000000000..ea21a97cc6 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/C++/sorting-algorithms-pancake-sort.cpp @@ -0,0 +1,50 @@ +#include <algorithm> +#include <iostream> +#include <iterator> +#include <vector> + +// pancake sort template (calls predicate to determine order) +template <typename BidIt, typename Pred> +void pancake_sort(BidIt first, BidIt last, Pred order) +{ + if (std::distance(first, last) < 2) return; // no sort needed + + for (; first != last; --last) + { + BidIt mid = std::max_element(first, last, order); + if (mid == last - 1) + { + continue; // no flips needed + } + if (first != mid) + { + std::reverse(first, mid + 1); // flip element to front + } + std::reverse(first, last); // flip front to final position + } +} + +// pancake sort template (ascending order) +template <typename BidIt> +void pancake_sort(BidIt first, BidIt last) +{ + pancake_sort(first, last, std::less<typename std::iterator_traits<BidIt>::value_type>()); +} + +int main() +{ + std::vector<int> data; + for (int i = 0; i < 20; ++i) + { + data.push_back(i); // generate test data + } + std::random_shuffle(data.begin(), data.end()); // scramble data + + std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " ")); + std::cout << "\n"; + + pancake_sort(data.begin(), data.end()); // ascending pancake sort + + std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " ")); + std::cout << "\n"; +} diff --git a/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-1.c b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-1.c new file mode 100644 index 0000000000..b68d9d7621 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-1.c @@ -0,0 +1,42 @@ +int pancake_sort(int *list, unsigned int length) +{ + //If it's less than 2 long, just return it as sorting isn't really needed... + if(length<2) + return 0; + + int i,a,max_num_pos,moves; + moves=0; + + for(i=length;i>1;i--) + { + //Find position of the max number in pos(0) to pos(i) + max_num_pos=0; + for(a=0;a<i;a++) + { + if(list[a]>list[max_num_pos]) + max_num_pos=a; + } + + if(max_num_pos==i-1) + //It's where it need to be, skip + continue; + + + //Get the found max number to the beginning of the list (unless it already is) + if(max_num_pos) + { + moves++; + do_flip(list, length, max_num_pos+1); + } + + + //And then move it to the end of the range we're working with (pos(0) to pos(i)) + moves++; + do_flip(list, length, i); + + //Then everything above list[i-1] is sorted and don't need to be touched + + } + + return moves; +} diff --git a/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-2.c b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-2.c new file mode 100644 index 0000000000..ee83c8b65c --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-2.c @@ -0,0 +1,11 @@ +void do_flip(int *list, int length, int num) +{ + int swap; + int i=0; + for(i;i<--num;i++) + { + swap=list[i]; + list[i]=list[num]; + list[num]=swap; + } +} diff --git a/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-3.c b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-3.c new file mode 100644 index 0000000000..e916bee1f9 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/C/sorting-algorithms-pancake-sort-3.c @@ -0,0 +1,20 @@ +int main(int argc, char **argv) +{ + //Just need some random numbers. I chose <100 + int list[9]; + int i; + srand(time(NULL)); + for(i=0;i<9;i++) + list[i]=rand()%100; + + + //Print list, run code and print it again displaying number of moves + printf("\nOriginal: "); + print_array(list, 9); + + int moves = pancake_sort(list, 9, 1); + + printf("\nSorted: "); + print_array(list, 9); + printf(" - with a total of %d moves\n", moves); +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-1.lisp b/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-1.lisp new file mode 100644 index 0000000000..dfbac58340 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-1.lisp @@ -0,0 +1,11 @@ +(defun pancake-sort (seq) + "A destructive version of Pancake Sort that works with either lists or arrays of numbers." + (defun flip (lst index) + (setf (subseq lst 0 index) (reverse (subseq lst 0 index)))) + (loop with lst = (coerce seq 'list) + for i from (length lst) downto 2 + for index = (position (apply #'max (subseq lst 0 i)) lst) + do (unless (= index 0) + (flip lst (1+ index))) + (flip lst i) + finally (return (coerce lst (type-of seq))))) diff --git a/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-2.lisp b/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-2.lisp new file mode 100644 index 0000000000..71eed5859d --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Common-Lisp/sorting-algorithms-pancake-sort-2.lisp @@ -0,0 +1,6 @@ +CL-USER> (pancake-sort '(6 7 8 9 2 5 3 4 1)) ;list +(1 2 3 4 5 6 7 8 9) +CL-USER> (pancake-sort #(6 7 8 9 2 5 3 4 1)) ;array +#(1 2 3 4 5 6 7 8 9) +CL-USER> (pancake-sort #(6.5 7.5 8 9 2 5 3 4 1.0)) ;array with integer and floating point values +#(1.0 2 3 4 5 6.5 7.5 8 9) diff --git a/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d b/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d new file mode 100644 index 0000000000..8947b09a5b --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d @@ -0,0 +1,24 @@ +import std.stdio, std.algorithm; + +void pancakeSort(bool tutor=false, T)(T[] data) { + foreach_reverse (i; 2 .. data.length + 1) { + immutable maxIndex = i - data[0 .. i].minPos!q{a > b}().length; + if (maxIndex + 1 != i) { + if (maxIndex != 0) { + static if (tutor) + writeln("With: ", data, " doflip ", maxIndex + 1); + data[0 .. maxIndex + 1].reverse(); + } + + static if (tutor) + writeln("With: ", data, " doflip ", i); + data[0 .. i].reverse(); + } + } +} + +void main() { + char[] data = "769248135".dup; + pancakeSort!true(data); + writeln(data); +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.euphoria b/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.euphoria new file mode 100644 index 0000000000..e5c473bf40 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.euphoria @@ -0,0 +1,34 @@ +function flip(sequence s, integer n) + object temp + for i = 1 to n/2 do + temp = s[i] + s[i] = s[n-i+1] + s[n-i+1] = temp + end for + return s +end function + +function pancake_sort(sequence s) + integer m + for i = length(s) to 2 by -1 do + m = 1 + for j = 2 to i do + if compare(s[j], s[m]) > 0 then + m = j + end if + end for + + if m < i then + if m > 1 then + s = flip(s,m) + end if + s = flip(s,i) + end if + end for + return s +end function + +constant s = rand(repeat(100,10)) + +? s +? pancake_sort(s) diff --git a/Task/Sorting-algorithms-Pancake-sort/Fortran/sorting-algorithms-pancake-sort.f b/Task/Sorting-algorithms-Pancake-sort/Fortran/sorting-algorithms-pancake-sort.f new file mode 100644 index 0000000000..c96c234cd6 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Fortran/sorting-algorithms-pancake-sort.f @@ -0,0 +1,37 @@ +program Pancake_Demo + implicit none + + integer :: list(8) = (/ 1, 4, 7, 2, 5, 8, 3, 6 /) + + call Pancake_sort(list) + +contains + +subroutine Pancake_sort(a) + + integer, intent(in out) :: a(:) + integer :: i, maxpos + + write(*,*) a + do i = size(a), 2, -1 + +! Find position of max number between index 1 and i + maxpos = maxloc(a(1:i), 1) + +! is it in the correct position already? + if (maxpos == i) cycle + +! is it at the beginning of the array? If not flip array section so it is + if (maxpos /= 1) then + a(1:maxpos) = a(maxpos:1:-1) + write(*,*) a + end if + +! Flip array section to get max number to correct position + a(1:i) = a(i:1:-1) + write(*,*) a + end do + +end subroutine + +end program Pancake_Demo diff --git a/Task/Sorting-algorithms-Pancake-sort/Go/sorting-algorithms-pancake-sort.go b/Task/Sorting-algorithms-Pancake-sort/Go/sorting-algorithms-pancake-sort.go new file mode 100644 index 0000000000..2995f220b9 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Go/sorting-algorithms-pancake-sort.go @@ -0,0 +1,34 @@ +package main + +import "fmt" + +func main() { + list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + list.sort() + fmt.Println("sorted! ", list) +} + +type pancake []int + +func (a pancake) sort() { + for uns := len(a) - 1; uns > 0; uns-- { + // find largest in unsorted range + lx, lg := 0, a[0] + for i := 1; i <= uns; i++ { + if a[i] > lg { + lx, lg = i, a[i] + } + } + // move to final position in two flips + a.flip(lx) + a.flip(uns) + } +} + +func (a pancake) flip(r int) { + for l := 0; l < r; l, r = l+1, r-1 { + a[l], a[r] = a[r], a[l] + } +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-1.groovy b/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-1.groovy new file mode 100644 index 0000000000..db2a08d76e --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-1.groovy @@ -0,0 +1,16 @@ +def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] } + +def flip = { list, n -> (0..<((n+1)/2)).each { makeSwap(list, it, n-it) } } + +def pancakeSort = { list -> + def n = list.size() + (1..<n).reverse().each { i -> + def max = list[0..i].max() + def flipPoint = (i..0).find{ list[it] == max } + if (flipPoint != i) { + flip(list, flipPoint) + flip(list, i) + } + } + list +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-2.groovy b/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-2.groovy new file mode 100644 index 0000000000..cd75c0f67d --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Groovy/sorting-algorithms-pancake-sort-2.groovy @@ -0,0 +1,9 @@ +println (pancakeSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (pancakeSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println () +println (pancakeSort([10, 10.0, 10.00, 1])) +println (pancakeSort([10, 10.00, 10.0, 1])) +println (pancakeSort([10.0, 10, 10.00, 1])) +println (pancakeSort([10.0, 10.00, 10, 1])) +println (pancakeSort([10.00, 10, 10.0, 1])) +println (pancakeSort([10.00, 10.0, 10, 1])) diff --git a/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-1.hs b/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-1.hs new file mode 100644 index 0000000000..d17be0b4c5 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-1.hs @@ -0,0 +1,14 @@ +import Data.List +import Control.Arrow +import Control.Monad +import Data.Maybe + +dblflipIt :: (Ord a) => [a] -> [a] +dblflipIt = uncurry ((reverse.).(++)). first reverse + . ap (flip splitAt) (succ. fromJust. (elemIndex =<< maximum)) + +dopancakeSort :: (Ord a) => [a] -> [a] +dopancakeSort xs = dopcs (xs,[]) where + dopcs ([],rs) = rs + dopcs ([x],rs) = x:rs + dopcs (xs,rs) = dopcs $ (init &&& (:rs).last ) $ dblflipIt xs diff --git a/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-2.hs b/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-2.hs new file mode 100644 index 0000000000..ae25e84318 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Haskell/sorting-algorithms-pancake-sort-2.hs @@ -0,0 +1,2 @@ +*Main> dopancakeSort [3,2,1,0,2] +[0,1,2,2,3] diff --git a/Task/Sorting-algorithms-Pancake-sort/Icon/sorting-algorithms-pancake-sort.icon b/Task/Sorting-algorithms-Pancake-sort/Icon/sorting-algorithms-pancake-sort.icon new file mode 100644 index 0000000000..28eee3a8a8 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Icon/sorting-algorithms-pancake-sort.icon @@ -0,0 +1,41 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(pancakesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") + pancakeflip := pancakeflipshow # replace pancakeflip procedure with a variant that displays each flip + pancakesort([3, 14, 1, 5, 9, 2, 6, 3]) +end + +procedure pancakesort(X,op) #: return sorted list ascending(or descending) +local i,m + + op := sortop(op,X) # select how and what we sort + + every i := *X to 2 by -1 do { # work back to front + m := 1 + every j := 2 to i do + if op(X[m],X[j]) then m := j # find X that belongs @i high (or low) + if i ~= m then { # not already in-place + X := pancakeflip(X,m) # . bring max (min) to front + X := pancakeflip(X,i) # . unsorted portion of stack + } + } + return X +end + +procedure pancakeflip(X,tail) #: return X[1:tail] flipped +local i + + i := 0 + tail := integer(\tail|*X) + 1 | runerr(101,tail) + while X[(i +:= 1) < (tail -:= 1)] :=: X[i] # flip + return X +end + +procedure pancakeflipshow(X,tail) #: return X[1:tail] flipped (and display) +local i + + i := 0 + tail := integer(\tail|*X) + 1 | runerr(101,tail) + while X[(i +:= 1) < (tail -:= 1)] :=: X[i] # flip + every writes(" ["|right(!X,4)|" ]\n") # show X + return X +end diff --git a/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-1.j b/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-1.j new file mode 100644 index 0000000000..b85c1b99e4 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-1.j @@ -0,0 +1,6 @@ +flip=: C.~ C.@i.@- +unsorted=: #~ 1 , [: >./\. 2 >/\ ] +FlDown=: flip 1 + (i. >./)@unsorted +FlipUp=: flip 1 >. [:+/>./\&|.@(< {.) + +pancake=: FlipUp@FlDown^:_ diff --git a/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-2.j b/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-2.j new file mode 100644 index 0000000000..d8dd5580f9 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/J/sorting-algorithms-pancake-sort-2.j @@ -0,0 +1,3 @@ + (,:pancake) ?~9 +1 0 8 7 4 6 3 5 2 +0 1 2 3 4 5 6 7 8 diff --git a/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-1.java b/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-1.java new file mode 100644 index 0000000000..edfeb627aa --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-1.java @@ -0,0 +1,82 @@ +public class PancakeSort +{ + int[] heap; + + public String toString() { + String info = ""; + for (int x: heap) + info += x + " "; + return info; + } + + public void flip(int n) { + for (int i = 0; i < (n+1) / 2; ++i) { + int tmp = heap[i]; + heap[i] = heap[n-i]; + heap[n-i] = tmp; + } + System.out.println("flip(0.." + n + "): " + toString()); + } + + public int[] minmax(int n) { + int xm, xM; + xm = xM = heap[0]; + int posm = 0, posM = 0; + + for (int i = 1; i < n; ++i) { + if (heap[i] < xm) { + xm = heap[i]; + posm = i; + } + else if (heap[i] > xM) { + xM = heap[i]; + posM = i; + } + } + return new int[] {posm, posM}; + } + + public void sort(int n, int dir) { + if (n == 0) return; + + int[] mM = minmax(n); + int bestXPos = mM[dir]; + int altXPos = mM[1-dir]; + boolean flipped = false; + + if (bestXPos == n-1) { + --n; + } + else if (bestXPos == 0) { + flip(n-1); + --n; + } + else if (altXPos == n-1) { + dir = 1-dir; + --n; + flipped = true; + } + else { + flip(bestXPos); + } + sort(n, dir); + + if (flipped) { + flip(n); + } + } + + PancakeSort(int[] numbers) { + heap = numbers; + sort(numbers.length, 1); + } + + public static void main(String[] args) { + int[] numbers = new int[args.length]; + for (int i = 0; i < args.length; ++i) + numbers[i] = Integer.valueOf(args[i]); + + PancakeSort pancakes = new PancakeSort(numbers); + System.out.println(pancakes); + } +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-2.java b/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-2.java new file mode 100644 index 0000000000..de2db31627 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Java/sorting-algorithms-pancake-sort-2.java @@ -0,0 +1,16 @@ +$ java PancakeSort 1 2 5 4 3 10 9 8 7 +flip(0..5): 10 3 4 5 2 1 9 8 7 +flip(0..8): 7 8 9 1 2 5 4 3 10 +flip(0..2): 9 8 7 1 2 5 4 3 10 +flip(0..7): 3 4 5 2 1 7 8 9 10 +flip(0..2): 5 4 3 2 1 7 8 9 10 +flip(0..4): 1 2 3 4 5 7 8 9 10 +1 2 3 4 5 7 8 9 10 + +$ java PancakeSort 6 7 2 1 8 9 5 3 4 +flip(0..5): 9 8 1 2 7 6 5 3 4 +flip(0..8): 4 3 5 6 7 2 1 8 9 +flip(0..1): 3 4 5 6 7 2 1 8 9 +flip(0..4): 7 6 5 4 3 2 1 8 9 +flip(0..6): 1 2 3 4 5 6 7 8 9 +1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Pancake-sort/JavaScript/sorting-algorithms-pancake-sort.js b/Task/Sorting-algorithms-Pancake-sort/JavaScript/sorting-algorithms-pancake-sort.js new file mode 100644 index 0000000000..5a6bef78a7 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/JavaScript/sorting-algorithms-pancake-sort.js @@ -0,0 +1,33 @@ +Array.prototype.pancake_sort = function () { + for (var i = this.length - 1; i >= 1; i--) { + // find the index of the largest element not yet sorted + var max_idx = 0; + var max = this[0]; + for (var j = 1; j <= i; j++) { + if (this[j] > max) { + max = this[j]; + max_idx = j; + } + } + + if (max_idx == i) + continue; // element already in place + + var new_slice; + + // flip this max element to index 0 + if (max_idx > 0) { + new_slice = this.slice(0, max_idx+1).reverse(); + for (var j = 0; j <= max_idx; j++) + this[j] = new_slice[j]; + } + + // then flip the max element to its place + new_slice = this.slice(0, i+1).reverse(); + for (var j = 0; j <= i; j++) + this[j] = new_slice[j]; + } + return this; +} +ary = [7,6,5,9,8,4,3,1,2,0] +sorted = ary.concat().pancake_sort(); diff --git a/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-1.m b/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-1.m new file mode 100644 index 0000000000..fc564efd06 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-1.m @@ -0,0 +1,28 @@ +function list = pancakeSort(list) + + for i = (numel(list):-1:2) + + minElem = list(i); + minIndex = i; + + %Find the min element in the current subset of the list + for j = (i:-1:1) + if list(j) <= minElem + minElem = list(j); + minIndex = j; + end + end + + %If the element is already in the correct position don't flip + if i ~= minIndex + + %First flip flips the min element in the stack to the top + list(minIndex:-1:1) = list(1:minIndex); + + %Second flip flips the min element into the correct position in + %the stack + list(i:-1:1) = list(1:i); + + end + end %for +end %pancakeSort diff --git a/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-2.m b/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-2.m new file mode 100644 index 0000000000..b9177ef6a6 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/MATLAB/sorting-algorithms-pancake-sort-2.m @@ -0,0 +1,5 @@ +>> pancakeSort([4 3 1 5 6 2]) + +ans = + + 6 5 4 3 2 1 diff --git a/Task/Sorting-algorithms-Pancake-sort/Mathematica/sorting-algorithms-pancake-sort.math b/Task/Sorting-algorithms-Pancake-sort/Mathematica/sorting-algorithms-pancake-sort.math new file mode 100644 index 0000000000..38fc8685ad --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Mathematica/sorting-algorithms-pancake-sort.math @@ -0,0 +1,10 @@ +LMaxPosition[ a_, n_ ] := Part[Position[a[[;;n]],Max[a[[;;n]]]],1,1] + +SetAttributes[Flip,HoldFirst]; Flip[a_] := Set[a,Reverse[a]] + +pancakeSort[a_] : = For[n = Length[a], n > 1, n--, + If[LMaxPosition[a,n] < n, + Flip[a[[;;LMaxPosition[a,n]]]]; Print[a]; + Flip[a[[;;n]]]; Print[a]; + ]; +]; diff --git a/Task/Sorting-algorithms-Pancake-sort/OCaml/sorting-algorithms-pancake-sort.ocaml b/Task/Sorting-algorithms-Pancake-sort/OCaml/sorting-algorithms-pancake-sort.ocaml new file mode 100644 index 0000000000..4307e3815b --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/OCaml/sorting-algorithms-pancake-sort.ocaml @@ -0,0 +1,43 @@ +let rec sorted = function + | [] -> (true) + | x::y::_ when x > y -> (false) + | x::xs -> sorted xs + +let rev_until_max li = + let rec aux acc greater prefix suffix = function + | x::xs when x > greater -> aux (x::acc) x acc xs xs + | x::xs -> aux (x::acc) greater prefix suffix xs + | [] -> (greater, (prefix @ suffix)) + in + aux [] min_int [] li li + +let pancake_sort li = + let rec aux i li suffix = + let greater, li = rev_until_max li in + let suffix = greater :: suffix + and li = List.rev li in + if sorted li + then (li @ suffix), i + else aux (succ i) li suffix + in + aux 0 li [] + +let print_list li = + List.iter (Printf.printf " %d") li; + print_newline() + +let make_rand_list n bound = + let rec aux acc i = + if i >= n then (acc) + else aux ((Random.int bound)::acc) (succ i) + in + aux [] 0 + +let () = + Random.self_init(); + let li = make_rand_list 8 100 in + print_list li; + let res, n = pancake_sort li in + print_list res; + Printf.printf " sorted in %d loops\n" n; +;; diff --git a/Task/Sorting-algorithms-Pancake-sort/PARI-GP/sorting-algorithms-pancake-sort.pari b/Task/Sorting-algorithms-Pancake-sort/PARI-GP/sorting-algorithms-pancake-sort.pari new file mode 100644 index 0000000000..eb1da860a7 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PARI-GP/sorting-algorithms-pancake-sort.pari @@ -0,0 +1,20 @@ +pancakeSort(v)={ + my(top=#v); + while(top>1, + my(mx=1,t); + for(i=2,top,if(v[i]>v[mx], mx=i)); + if(mx==top, top--; next); + for(i=1,mx\2, + t=v[i]; + v[i]=v[mx+1-i]; + v[mx+1-i]=t + ); + for(i=1,top\2, + t=v[i]; + v[i]=v[top+1-i]; + v[top+1-i]=t + ); + top-- + ); + v +}; diff --git a/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-1.pli b/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-1.pli new file mode 100644 index 0000000000..33bd2cb894 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-1.pli @@ -0,0 +1,35 @@ +pancake_sort: procedure options (main); /* 23 April 2009 */ + declare a(10) fixed, (i, n, loc) fixed binary; + + a(1) = 3; a(2) = 9; a(3) = 2; a(4) = 7; a(5) = 10; + a(6) = 1; a(7) = 8; a(8) = 5; a(9) = 4; a(10) = 6; + + n = hbound(A,1); + put skip edit (A) (f(5)); + do i = 1 to n-1; + loc = max(A, n); + call flip (A, loc); + call flip (A, n); + n = n - 1; + put skip edit (A) (f(5)); + end; + +max: procedure (A, k) returns (fixed binary); + declare A(*) fixed, k fixed binary; + declare (i, maximum, loc) fixed binary; + maximum = A(1); loc = 1; + do i = 2 to k; + if A(i) > maximum then do; maximum = A(i); loc = i; end; + end; + return (loc); +end max; + +flip: procedure (A, k); + declare A(*) fixed, k fixed binary; + declare (i, t) fixed binary; + do i = 1 to (k+1)/2; + t = A(i); A(i) = A(k-i+1); A(k-i+1) = t; + end; +end flip; + +end pancake_sort; diff --git a/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-2.pli b/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-2.pli new file mode 100644 index 0000000000..186b2d442f --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PL-I/sorting-algorithms-pancake-sort-2.pli @@ -0,0 +1,10 @@ + 3 9 2 7 10 1 8 5 4 6 + 6 4 5 8 1 3 9 2 7 10 + 7 2 6 4 5 8 1 3 9 10 + 3 1 7 2 6 4 5 8 9 10 + 5 4 6 2 3 1 7 8 9 10 + 1 3 2 5 4 6 7 8 9 10 + 4 1 3 2 5 6 7 8 9 10 + 2 3 1 4 5 6 7 8 9 10 + 1 2 3 4 5 6 7 8 9 10 + 1 2 3 4 5 6 7 8 9 10 diff --git a/Task/Sorting-algorithms-Pancake-sort/Pascal/sorting-algorithms-pancake-sort.pascal b/Task/Sorting-algorithms-Pancake-sort/Pascal/sorting-algorithms-pancake-sort.pascal new file mode 100644 index 0000000000..dfbfaa66eb --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Pascal/sorting-algorithms-pancake-sort.pascal @@ -0,0 +1,65 @@ +Program PancakeSort (output); + +procedure flip(var b: array of integer; last: integer); + + var + swap, i: integer; + + begin + for i := low(b) to (last - low(b) - 1) div 2 do + begin + swap := b[i]; + b[i] := b[last-(i-low(b))]; + b[last-(i-low(b))] := swap; + end; + end; + +procedure PancakeSort(var a: array of integer); + + var + i, j, maxpos: integer; + + begin + for i := high(a) downto low(a) do + begin +// Find position of max number between beginning and i + maxpos := i; + for j := low(a) to i - 1 do + if a[j] > a[maxpos] then + maxpos := j; + +// is it in the correct position already? + if maxpos = i then + continue; + +// is it at the beginning of the array? If not flip array section so it is + if maxpos <> low(a) then + flip(a, maxpos); + +// Flip array section to get max number to correct position + flip(a, i); + end; + end; + +var + data: array of integer; + i: integer; + +begin + setlength(data, 8); + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + PancakeSort(data); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Pancake-sort/Perl-6/sorting-algorithms-pancake-sort.pl6 b/Task/Sorting-algorithms-Pancake-sort/Perl-6/sorting-algorithms-pancake-sort.pl6 new file mode 100644 index 0000000000..f95c3a15d3 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Perl-6/sorting-algorithms-pancake-sort.pl6 @@ -0,0 +1,20 @@ +sub pancake_sort ( @a is copy ) { + my $endpoint = @a.end; + while $endpoint > 0 and not [<] @a { + my $max_i = [0..$endpoint].max: { @a[$_] }; + my $max = @a[$max_i]; + if @a[$endpoint] == $max { + $endpoint-- while @a[$endpoint] == $max; + next; + } + # @a[$endpoint] is not $max, so it needs flipping; + # Flip twice if max is not already at the top. + @a[0..$max_i] .= reverse if $max_i != 0; + @a[0..$endpoint] .= reverse; + $endpoint--; + } + return @a; +} +my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4; +say 'input = ' ~ @data; +say 'output = ' ~ @data.&pancake_sort; diff --git a/Task/Sorting-algorithms-Pancake-sort/Perl/sorting-algorithms-pancake-sort.pl b/Task/Sorting-algorithms-Pancake-sort/Perl/sorting-algorithms-pancake-sort.pl new file mode 100644 index 0000000000..cb25e36cca --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Perl/sorting-algorithms-pancake-sort.pl @@ -0,0 +1,18 @@ +sub pancake { + my @x = @_; + for my $idx (0 .. $#x - 1) { + my $min = $idx; + $x[$min] > $x[$_] and $min = $_ for $idx + 1 .. $#x; + + next if $x[$min] == $x[$idx]; + + @x[$min .. $#x] = reverse @x[$min .. $#x] if $x[$min] != $x[-1]; + @x[$idx .. $#x] = reverse @x[$idx .. $#x]; + } + @x; +} + +my @a = map (int rand(100), 1 .. 10); +print "Before @a\n"; +@a = pancake(@a); +print "After @a\n"; diff --git a/Task/Sorting-algorithms-Pancake-sort/PicoLisp/sorting-algorithms-pancake-sort.l b/Task/Sorting-algorithms-Pancake-sort/PicoLisp/sorting-algorithms-pancake-sort.l new file mode 100644 index 0000000000..df75e66424 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PicoLisp/sorting-algorithms-pancake-sort.l @@ -0,0 +1,4 @@ +(de pancake (Lst) + (prog1 (flip Lst (index (apply max Lst) Lst)) + (for (L @ (cdr (setq Lst (cdr L))) (cdr L)) + (con L (flip Lst (index (apply max Lst) Lst))) ) ) ) diff --git a/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.psh b/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.psh new file mode 100644 index 0000000000..bad94a0fa7 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.psh @@ -0,0 +1,38 @@ +Function FlipPancake( [Object[]] $indata, $index = 1 ) +{ + $data=$indata.Clone() + $datal = $data.length - 1 + if( $index -gt 0 ) + { + if( $datal -gt $index ) + { + $first = $data[ $index..0 ] + $last = $data[ ( $index + 1 )..$datal ] + $data = $first + $last + } else { + $data = $data[ $index..0 ] + } + } + $data +} + +Function MaxIdx( [Object[]] $data ) +{ + $data | ForEach-Object { $max = $data[ 0 ]; $i = 0; $maxi = 0 } { if( $_ -gt $max ) { $max = $_; $maxi = $i }; $i++ } { $maxi } +} + +Function PancakeSort( [Object[]] $data, $index = 0 ) +{ + "unsorted - $data" + $datal = $data.length - 1 + if( $datal -gt 0 ) + { + for( $i = $datal; $i -gt 0; $i-- ) + { + $data = FlipPancake ( FlipPancake $data ( MaxIdx $data[ 0..$i ] ) ) $i + } + } + "sorted - $data" +} + +$l = 100; PancakeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Pancake-sort/PureBasic/sorting-algorithms-pancake-sort.purebasic b/Task/Sorting-algorithms-Pancake-sort/PureBasic/sorting-algorithms-pancake-sort.purebasic new file mode 100644 index 0000000000..fddd041492 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PureBasic/sorting-algorithms-pancake-sort.purebasic @@ -0,0 +1,43 @@ +If OpenConsole() + Define i, j, k, Loops + Dim Pile(9) + ;-------------------------------------------------------------- + ;- Create a Random Pile() + For i=1 To 9 ;- Initiate the Pile + Pile(i)=i + Next + For i=9 To 1 Step -1 ;- Do a Fisher-Yates shuffle + Swap Pile(i),Pile(Random(i-1)+1) + Next + Print("Random Pile() :") + For i=1 To 9 + Print(" "+Str(Pile(i))) + Next + ;-------------------------------------------------------------- + ;- Start Sorting + For i=9 To 2 Step -1 + If Pile(i)<>i ;- Only Flip it if the current cake need Swapping + Loops+1 + j=0 + Repeat ;- find place of Pancake(i) in the Pile() + j+1 + Until Pile(j)=i + + For k=1 To (j/2) ;- Flip it up + Swap Pile(k),Pile(j-k+1) + Next + For k=1 To i/2 ;- Flip in place + Swap Pile(k),Pile(i-k+1) + Next + + EndIf + Next + + Print(#CRLF$+"Resulting Pile() :") + For i=1 To 9 + Print(" "+str(Pile(i))) + Next + Print(#CRLF$+"All done in "+str(Loops)+" loops.") + Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input() + CloseConsole() +EndIf diff --git a/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-1.py b/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-1.py new file mode 100644 index 0000000000..2fc69109d9 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-1.py @@ -0,0 +1,20 @@ +tutor = False + +def pancakesort(data): + if len(data) <= 1: + return data + if tutor: print() + for size in range(len(data), 1, -1): + maxindex = max(range(size), key=data.__getitem__) + if maxindex+1 != size: + # This indexed max needs moving + if maxindex != 0: + # Flip the max item to the left + if tutor: print('With: %r doflip %i' + % ( ' '.join(str(x) for x in data), maxindex+1 )) + data[:maxindex+1] = reversed(data[:maxindex+1]) + # Flip it into its final position + if tutor: print('With: %r doflip %i' + % ( ' '.join(str(x) for x in data), size )) + data[:size] = reversed(data[:size]) + if tutor: print() diff --git a/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-2.py b/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-2.py new file mode 100644 index 0000000000..c621fd176f --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Python/sorting-algorithms-pancake-sort-2.py @@ -0,0 +1,10 @@ +if __name__ == '__main__': + import random + + tutor = True + data = list('123456789') + while data == sorted(data): + random.shuffle(data) + print('Original List: %r' % ' '.join(data)) + pancakesort(data) + print('Pancake Sorted List: %r' % ' '.join(data)) diff --git a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx new file mode 100644 index 0000000000..e7e3e32197 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx @@ -0,0 +1,59 @@ +/*REXX program sorts/shows an array using the pancake sort algorithm.*/ +call gen@ /*generate elements in the array.*/ +call show@ 'before sort' /*show the BEFORE array elements.*/ +call pancakeSort #items /*invoke the pancake sort. Yummy.*/ +call show@ ' after sort' /*show the AFTER array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────PANCAKESORT subroutine──────────────*/ +pancakeSort: procedure expose @.; parse arg n + + do n-1 /*perform this loop N-1 times.*/ + !=@.1; ?=1 + do j=2 to n + if @.j<=! then iterate + !=@.j; ?=j + end /*j*/ + call flip ?; call flip n + n=n-1 + end /*n-1*/ +return +/*──────────────────────────────────FLIP subroutine─────────────────────*/ +flip: procedure expose @.; parse arg w + do i=1 for (w+1)%2 /*In REXX, % is integer divide.*/ + kmip1=w-i+1; _=@.i; @.i=@.kmip1; @.kmip1=_ + end /*i*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.='' /*assign a default value. */ + /*Generate some bread primes which are primes of the*/ + /*form: (p-3)÷2 and 2∙p+3 where p is a prime.*/ + /*Bread primes are related to sandwich & meat primes.*/ + + @.1= 2 ; @.17= 113 ; @.33= -55 + @.2= 17 ; @.18= 461 ; @.34= -21 + @.3= 5 ; @.19= 137 ; @.35= -1 + @.4= 29 ; @.20= 557 ; @.36= -8 + @.5= 7 ; @.21= 167 ; @.37= -8 + @.6= 37 ; @.22= 677 ; @.38= -21 + @.7= 13 ; @.23= 173 ; @.39= -55 + @.8= 61 ; @.24= 701 ; @.40= 0 + @.9= 43 ; @.25= 797 ; @.41= 0 +@.10= 181 ; @.26= 1117 +@.11= 47 ; @.27= 307 /*The non-positive numbers*/ +@.12= 197 ; @.28= 1237 /*above are some negative */ +@.13= 67 ; @.29= 1597 /*Fibonacci numbers, some */ +@.14= 277 ; @.30= 463 /*of which where specified*/ +@.15= 97 ; @.31= 1861 /*twice just 'cause I felt*/ +@.16= 397 ; @.32= 467 /*like it. Also, added */ + /*two zeroes, just 'cause.*/ + do #items=1 while @.#items\==''; end /*find how many entries in array.*/ + +#items=#items-1 /*adjust the #items slightly. */ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(#items) /*the maximum width of any line. */ + do k=1 for #items + say 'element' right(k,widthH) arg(1)':' @.k + end /*k*/ +say copies('─',79) /*show an eyeball separator line.*/ +return diff --git a/Task/Sorting-algorithms-Pancake-sort/Ruby/sorting-algorithms-pancake-sort.rb b/Task/Sorting-algorithms-Pancake-sort/Ruby/sorting-algorithms-pancake-sort.rb new file mode 100644 index 0000000000..a20723ac42 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Ruby/sorting-algorithms-pancake-sort.rb @@ -0,0 +1,31 @@ +class Array + def pancake_sort! + num_flips = 0 + self.size.downto(2) do |i| + end_idx = i - 1 + max_idx = self[0..end_idx].each_with_index.max_by {|e| e[0]}.last + next if max_idx == end_idx + + if max_idx > 0 + self[0..max_idx] = self[0..max_idx].reverse + + if $DEBUG + num_flips += 1 + p [num_flips, self] + end + end + + self[0..end_idx] = self[0..end_idx].reverse + + if $DEBUG + num_flips += 1 + p [num_flips, self] + end + end + + self + end +end + +p a = (1..9).to_a.shuffle +p a.pancake_sort! diff --git a/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-1.tcl b/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-1.tcl new file mode 100644 index 0000000000..2e8f8851e4 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-1.tcl @@ -0,0 +1,24 @@ +package require Tcl 8.5 +# Some simple helper procedures +proc flip {nlist n} { + concat [lreverse [lrange $nlist 0 $n]] [lrange $nlist $n+1 end] +} +proc findmax {nlist limit} { + lsearch -exact $nlist [tcl::mathfunc::max {*}[lrange $nlist 0 $limit]] +} + +# Simple-minded pancake sort algorithm +proc pancakeSort {nlist {debug ""}} { + for {set i [llength $nlist]} {[incr i -1] > 0} {} { + set j [findmax $nlist $i] + if {$i != $j} { + if {$j} { + set nlist [flip $nlist $j] + if {$debug eq "debug"} {puts [incr flips]>>$nlist} + } + set nlist [flip $nlist $i] + if {$debug eq "debug"} {puts [incr flips]>>$nlist} + } + } + return $nlist +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-2.tcl b/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-2.tcl new file mode 100644 index 0000000000..14ace08aff --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Tcl/sorting-algorithms-pancake-sort-2.tcl @@ -0,0 +1 @@ +puts [pancakeSort {27916 5928 23535 14711 32184 14621 21093 14422 29844 11093} debug] diff --git a/Task/Sorting-algorithms-Pancake-sort/VBA/sorting-algorithms-pancake-sort.vba b/Task/Sorting-algorithms-Pancake-sort/VBA/sorting-algorithms-pancake-sort.vba new file mode 100644 index 0000000000..e77e359bd4 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/VBA/sorting-algorithms-pancake-sort.vba @@ -0,0 +1,66 @@ +'pancake sort +'uses two auxiliary routines "printarray" and "flip" + +Public Sub printarray(A) + For i = LBound(A) To UBound(A) + Debug.Print A(i), + Next + Debug.Print +End Sub + +Public Sub Flip(ByRef A, p1, p2, trace) +'flip first elements of A (p1 to p2) + If trace Then Debug.Print "we'll flip the first "; p2 - p1 + 1; "elements of the array" + Cut = Int((p2 - p1 + 1) / 2) + For i = 0 To Cut - 1 + 'flip position i and (n - i + 1) + temp = A(i) + A(i) = A(p2 - i) + A(p2 - i) = temp + Next +End Sub + +Public Sub pancakesort(ByRef A(), Optional trace As Boolean = False) +'sort A into ascending order using pancake sort + +lb = LBound(A) +ub = UBound(A) +Length = ub - lb + 1 +If Length <= 1 Then 'no need to sort + Exit Sub +End If + +For i = ub To lb + 1 Step -1 + 'find position of max. element in subarray A(lowerbound to i) + P = lb + Maximum = A(P) + For j = lb + 1 To i + If A(j) > Maximum Then + P = j + Maximum = A(j) + End If + Next j + 'check if maximum is already at end - then we don't need to flip + If P < i Then + 'flip the first part of the array up to the maximum so it is at the head - skip if it is already there + If P > 1 Then + Flip A, lb, P, trace + If trace Then printarray A + End If + 'now flip again so that it is in its final position + Flip A, lb, i, trace + If trace Then printarray A + End If +Next i +End Sub + +'test routine +Public Sub TestPancake(Optional trace As Boolean = False) +Dim A() +A = Array(5, 7, 8, 3, 1, 10, 9, 23, 50, 0) +Debug.Print "Initial array:" +printarray A +pancakesort A, trace +Debug.Print "Final array:" +printarray A +End Sub diff --git a/Task/Sorting-algorithms-Permutation-sort/0DESCRIPTION b/Task/Sorting-algorithms-Permutation-sort/0DESCRIPTION new file mode 100644 index 0000000000..b09a7263fd --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/0DESCRIPTION @@ -0,0 +1,6 @@ +{{Sorting Algorithm}}Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. + +Pseudocode: + '''while not''' InOrder(list) '''do''' + nextPermutation(list) + '''done''' diff --git a/Task/Sorting-algorithms-Permutation-sort/1META.yaml b/Task/Sorting-algorithms-Permutation-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Permutation-sort/ActionScript/sorting-algorithms-permutation-sort.as b/Task/Sorting-algorithms-Permutation-sort/ActionScript/sorting-algorithms-permutation-sort.as new file mode 100644 index 0000000000..4682ce82a4 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/ActionScript/sorting-algorithms-permutation-sort.as @@ -0,0 +1,31 @@ +//recursively builds the permutations of permutable, appended to front, and returns the first sorted permutation it encounters +function permutations(front:Array, permutable:Array):Array { + //If permutable has length 1, there is only one possible permutation. Check whether it's sorted + if (permutable.length==1) + return isSorted(front.concat(permutable)); + else + //There are multiple possible permutations. Generate them. + var i:uint=0,tmp:Array=null; + do + { + tmp=permutations(front.concat([permutable[i]]),remove(permutable,i)); + i++; + }while (i< permutable.length && tmp == null); + //If tmp != null, it contains the sorted permutation. If it does not contain the sorted permutation, return null. Either way, return tmp. + return tmp; +} +//returns the array if it's sorted, or null otherwise +function isSorted(data:Array):Array { + for (var i:uint = 1; i < data.length; i++) + if (data[i]<data[i-1]) + return null; + return data; +} +//returns a copy of array with the i'th element removed +function remove(array:Array, i:uint):Array { + return array.filter(function(item,index,array){return(index !=i)}) ; +} +//wrapper around the permutation function to provide a more logical interface +function permutationSort(array:Array):Array { + return permutations([],array); +} diff --git a/Task/Sorting-algorithms-Permutation-sort/AutoHotkey/sorting-algorithms-permutation-sort.ahk b/Task/Sorting-algorithms-Permutation-sort/AutoHotkey/sorting-algorithms-permutation-sort.ahk new file mode 100644 index 0000000000..53920de768 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/AutoHotkey/sorting-algorithms-permutation-sort.ahk @@ -0,0 +1,43 @@ +MsgBox % PermSort("") +MsgBox % PermSort("xxx") +MsgBox % PermSort("3,2,1") +MsgBox % PermSort("dog,000000,xx,cat,pile,abcde,1,cat") + +PermSort(var) { ; SORT COMMA SEPARATED LIST + Local i, sorted + StringSplit a, var, `, ; make array, size = a0 + + v0 := a0 ; auxiliary array for permutations + Loop %v0% + v%A_Index% := A_Index + + While unSorted("a","v") ; until sorted + NextPerm("v") ; try new permutations + + Loop % a0 ; construct string from sorted array + i := v%A_Index%, sorted .= "," . a%i% + Return SubStr(sorted,2) ; drop leading comma +} + +unSorted(a,v) { + Loop % %a%0-1 { + i := %v%%A_Index%, j := A_Index+1, j := %v%%j% + If (%a%%i% > %a%%j%) + Return 1 + } +} + +NextPerm(v) { ; the lexicographically next LARGER permutation of v1..v%v0% + Local i, i1, j, t + i := %v%0, i1 := i-1 + While %v%%i1% >= %v%%i% { + --i, --i1 + IfLess i1,1, Return 1 ; Signal the end + } + j := %v%0 + While %v%%j% <= %v%%i1% + --j + t := %v%%i1%, %v%%i1% := %v%%j%, %v%%j% := t, j := %v%0 + While i < j + t := %v%%i%, %v%%i% := %v%%j%, %v%%j% := t, ++i, --j +} diff --git a/Task/Sorting-algorithms-Permutation-sort/BBC-BASIC/sorting-algorithms-permutation-sort.bbc b/Task/Sorting-algorithms-Permutation-sort/BBC-BASIC/sorting-algorithms-permutation-sort.bbc new file mode 100644 index 0000000000..66b368cc1a --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/BBC-BASIC/sorting-algorithms-permutation-sort.bbc @@ -0,0 +1,45 @@ + DIM test(9) + test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1 + + perms% = 0 + WHILE NOT FNsorted(test()) + perms% += 1 + PROCnextperm(test()) + ENDWHILE + PRINT ;perms% " permutations required to sort "; DIM(test(),1)+1 " items." + END + + DEF PROCnextperm(a()) + LOCAL last%, maxindex%, p% + maxindex% = DIM(a(),1) + IF maxindex% < 1 THEN ENDPROC + p% = maxindex%-1 + WHILE a(p%) >= a(p%+1) + p% -= 1 + IF p% < 0 THEN + PROCreverse(a(), 0, maxindex%) + ENDPROC + ENDIF + ENDWHILE + last% = maxindex% + WHILE a(last%) <= a(p%) + last% -= 1 + ENDWHILE + SWAP a(p%), a(last%) + PROCreverse(a(), p%+1, maxindex%) + ENDPROC + + DEF PROCreverse(a(), first%, last%) + WHILE first% < last% + SWAP a(first%), a(last%) + first% += 1 + last% -= 1 + ENDWHILE + ENDPROC + + DEF FNsorted(d()) + LOCAL I% + FOR I% = 1 TO DIM(d(),1) + IF d(I%) < d(I%-1) THEN = FALSE + NEXT + = TRUE diff --git a/Task/Sorting-algorithms-Permutation-sort/C++/sorting-algorithms-permutation-sort.cpp b/Task/Sorting-algorithms-Permutation-sort/C++/sorting-algorithms-permutation-sort.cpp new file mode 100644 index 0000000000..d7c7f4983f --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/C++/sorting-algorithms-permutation-sort.cpp @@ -0,0 +1,10 @@ +#include <algorithm> + +template<typename ForwardIterator> + void permutation_sort(ForwardIterator begin, ForwardIterator end) +{ + while (std::next_permutation(begin, end)) + { + // -- this block intentionally left empty -- + } +} diff --git a/Task/Sorting-algorithms-Permutation-sort/C/sorting-algorithms-permutation-sort.c b/Task/Sorting-algorithms-Permutation-sort/C/sorting-algorithms-permutation-sort.c new file mode 100644 index 0000000000..0b29585467 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/C/sorting-algorithms-permutation-sort.c @@ -0,0 +1,46 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +typedef int(*cmp_func)(const void*, const void*); + +void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) +{ + char *p, *q, *tmp = malloc(msize); +# define A(i) ((char *)a + msize * (i)) +# define swap(a, b) {\ + memcpy(tmp, a, msize);\ + memcpy(a, b, msize);\ + memcpy(b, tmp, msize); } + while (1) { + /* find largest k such that a[k - 1] < a[k] */ + for (p = A(n - 1); (void*)p > a; p = q) + if (_cmp(q = p - msize, p) > 0) + break; + + if ((void*)p <= a) break; + + /* find largest l such that a[l] > a[k - 1] */ + for (p = A(n - 1); p > q; p-= msize) + if (_cmp(q, p) > 0) break; + + swap(p, q); /* swap a[k - 1], a[l] */ + /* flip a[k] through a[end] */ + for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize) + swap(p, q); + } + free(tmp); +} + +int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } + +int main() +{ + int i; + const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" }; + perm_sort(strs, 5, sizeof(*strs), scmp); + + for (i = 0; i < 5; i++) + printf("%s\n", strs[i]); + return 0; +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Clojure/sorting-algorithms-permutation-sort.clj b/Task/Sorting-algorithms-Permutation-sort/Clojure/sorting-algorithms-permutation-sort.clj new file mode 100644 index 0000000000..d92f1422bd --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Clojure/sorting-algorithms-permutation-sort.clj @@ -0,0 +1,6 @@ +(use '[clojure.contrib.combinatorics :only (permutations)]) + +(defn permutation-sort [s] + (first (filter (partial apply <=) (permutations s)))) + +(permutation-sort [2 3 5 3 5]) diff --git a/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-1.coffeescript b/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-1.coffeescript new file mode 100644 index 0000000000..756ed60393 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-1.coffeescript @@ -0,0 +1,60 @@ +# This code takes a ridiculously inefficient algorithm and rather futilely +# optimizes one part of it. Permutations are computed lazily. + +sorted_copy = (a) -> + # This returns a sorted copy of an array by lazily generating + # permutations of indexes and stopping when the indexes yield + # a sorted array. + indexes = [0...a.length] + ans = find_matching_permutation indexes, (permuted_indexes) -> + new_array = (a[i] for i in permuted_indexes) + console.log permuted_indexes, new_array + in_order(new_array) + (a[i] for i in ans) + +in_order = (a) -> + # return true iff array a is in increasing order. + return true if a.length <= 1 + for i in [0...a.length-1] + return false if a[i] > a[i+1] + true + +get_factorials = (n) -> + # return an array of the first n+1 factorials, starting with 0! + ans = [1] + f = 1 + for i in [1..n] + f *= i + ans.push f + ans + +permutation = (a, i, factorials) -> + # Return the i-th permutation of an array by + # using remainders of factorials to determine + # elements. + while a.length > 0 + f = factorials[a.length-1] + n = Math.floor(i / f) + i = i % f + elem = a[n] + a = a[0...n].concat(a[n+1...]) + elem + # The above loop gets treated like + # an array expression, so it returns + # all the elements. + +find_matching_permutation = (a, f_match) -> + factorials = get_factorials(a.length) + for i in [0...factorials[a.length]] + permuted_array = permutation(a, i, factorials) + if f_match permuted_array + return permuted_array + null + + +do -> + a = ['c', 'b', 'a', 'd'] + console.log 'input:', a + ans = sorted_copy a + console.log 'DONE!' + console.log 'sorted copy:', ans diff --git a/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-2.coffeescript b/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-2.coffeescript new file mode 100644 index 0000000000..788a1cfdaa --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/CoffeeScript/sorting-algorithms-permutation-sort-2.coffeescript @@ -0,0 +1,19 @@ +> coffee permute_sort.coffee +input: [ 'c', 'b', 'a', 'd' ] +[ 0, 1, 2, 3 ] [ 'c', 'b', 'a', 'd' ] +[ 0, 1, 3, 2 ] [ 'c', 'b', 'd', 'a' ] +[ 0, 2, 1, 3 ] [ 'c', 'a', 'b', 'd' ] +[ 0, 2, 3, 1 ] [ 'c', 'a', 'd', 'b' ] +[ 0, 3, 1, 2 ] [ 'c', 'd', 'b', 'a' ] +[ 0, 3, 2, 1 ] [ 'c', 'd', 'a', 'b' ] +[ 1, 0, 2, 3 ] [ 'b', 'c', 'a', 'd' ] +[ 1, 0, 3, 2 ] [ 'b', 'c', 'd', 'a' ] +[ 1, 2, 0, 3 ] [ 'b', 'a', 'c', 'd' ] +[ 1, 2, 3, 0 ] [ 'b', 'a', 'd', 'c' ] +[ 1, 3, 0, 2 ] [ 'b', 'd', 'c', 'a' ] +[ 1, 3, 2, 0 ] [ 'b', 'd', 'a', 'c' ] +[ 2, 0, 1, 3 ] [ 'a', 'c', 'b', 'd' ] +[ 2, 0, 3, 1 ] [ 'a', 'c', 'd', 'b' ] +[ 2, 1, 0, 3 ] [ 'a', 'b', 'c', 'd' ] +DONE! +sorted copy: [ 'a', 'b', 'c', 'd' ] diff --git a/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-1.lisp b/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-1.lisp new file mode 100644 index 0000000000..4ae5a7793f --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-1.lisp @@ -0,0 +1,34 @@ +(defun factorial (n) + (loop for result = 1 then (* i result) + for i from 2 to n + finally (return result))) + +(defun nth-permutation (k sequence) + (if (zerop (length sequence)) + (coerce () (type-of sequence)) + (let ((seq (etypecase sequence + (vector (copy-seq sequence)) + (sequence (coerce sequence 'vector))))) + (loop for j from 2 to (length seq) + do (setq k (truncate (/ k (1- j)))) + do (rotatef (aref seq (mod k j)) + (aref seq (1- j))) + finally (return (coerce seq (type-of sequence))))))) + +(defun sortedp (fn sequence) + (etypecase sequence + (list (loop for previous = #1='#:foo then i + for i in sequence + always (or (eq previous #1#) + (funcall fn i previous)))) + ;; copypasta + (vector (loop for previous = #1# then i + for i across sequence + always (or (eq previous #1#) + (funcall fn i previous)))))) + +(defun permutation-sort (fn sequence) + (loop for i below (factorial (length sequence)) + for permutation = (nth-permutation i sequence) + when (sortedp fn permutation) + do (return permutation))) diff --git a/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-2.lisp b/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-2.lisp new file mode 100644 index 0000000000..30c47cc6a9 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Common-Lisp/sorting-algorithms-permutation-sort-2.lisp @@ -0,0 +1,10 @@ +CL-USER> (time (permutation-sort #'> '(8 3 10 6 1 9 7 2 5 4))) +Evaluation took: + 5.292 seconds of real time + 5.204325 seconds of total run time (5.176323 user, 0.028002 system) + [ Run times consist of 0.160 seconds GC time, and 5.045 seconds non-GC time. ] + 98.34% CPU + 12,337,938,025 processor cycles + 611,094,240 bytes consed + +(1 2 3 4 5 6 7 8 9 10) diff --git a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d new file mode 100644 index 0000000000..c57dd5652e --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-1.d @@ -0,0 +1,15 @@ +import std.stdio, std.algorithm, permutations2; + +void permutationSort(T)(T[] items) /*pure nothrow*/ { + foreach (perm; permutations!false(items)) + if (isSorted(perm)) { + items[] = perm; + break; + } +} + +void main() { + auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; + permutationSort(data); + writeln(data); +} diff --git a/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d new file mode 100644 index 0000000000..edec30ae5e --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/D/sorting-algorithms-permutation-sort-2.d @@ -0,0 +1,11 @@ +import std.stdio, std.algorithm; + +void permutationSort(T)(T[] items) /*pure nothrow*/ { + while (nextPermutation(items)) {} +} + +void main() { + auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1]; + permutationSort(data); + writeln(data); +} diff --git a/Task/Sorting-algorithms-Permutation-sort/E/sorting-algorithms-permutation-sort.e b/Task/Sorting-algorithms-Permutation-sort/E/sorting-algorithms-permutation-sort.e new file mode 100644 index 0000000000..a90b65b260 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/E/sorting-algorithms-permutation-sort.e @@ -0,0 +1,40 @@ +def swap(container, ixA, ixB) { + def temp := container[ixA] + container[ixA] := container[ixB] + container[ixB] := temp +} + +/** Reverse order of elements of 'sequence' whose indexes are in the interval [ixLow, ixHigh] */ +def reverseRange(sequence, var ixLow, var ixHigh) { + while (ixLow < ixHigh) { + swap(sequence, ixLow, ixHigh) + ixLow += 1 + ixHigh -= 1 + } +} + +/** Algorithm from <http://marknelson.us/2002/03/01/next-permutation>, allegedly from a version of the C++ STL */ +def nextPermutation(sequence) { + def last := sequence.size() - 1 + var i := last + while (true) { + var ii := i + i -= 1 + if (sequence[i] < sequence[ii]) { + var j := last + 1 + while (!(sequence[i] < sequence[j -= 1])) {} # buried side effect + swap(sequence, i, j) + reverseRange(sequence, ii, last) + return true + } + if (i == 0) { + reverseRange(sequence, 0, last) + return false + } + } +} + +/** Note: Worst case on sorted list */ +def permutationSort(flexList) { + while (nextPermutation(flexList)) {} +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Go/sorting-algorithms-permutation-sort.go b/Task/Sorting-algorithms-Permutation-sort/Go/sorting-algorithms-permutation-sort.go new file mode 100644 index 0000000000..63e781dfa1 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Go/sorting-algorithms-permutation-sort.go @@ -0,0 +1,39 @@ +package main + +import "fmt" + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} + +// in place permutation sort of slice a +func main() { + fmt.Println("before:", a) + if len(a) > 1 && !recurse(len(a) - 1) { + // recurse should never return false from the top level. + // if it does, it means some code somewhere is busted, + // either the the permutation generation code or the + // sortedness testing code. + panic("sorted permutation not found!") + } + fmt.Println("after: ", a) +} + +// recursive permutation generator +func recurse(last int) bool { + if last <= 0 { + // bottom of recursion. test if sorted. + for i := len(a) - 1; a[i] >= a[i-1]; i-- { + if i == 1 { + return true + } + } + return false + } + for i := 0; i <= last; i++ { + a[i], a[last] = a[last], a[i] + if recurse(last - 1) { + return true + } + a[i], a[last] = a[last], a[i] + } + return false +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-1.groovy b/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-1.groovy new file mode 100644 index 0000000000..3e0b30c807 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-1.groovy @@ -0,0 +1,22 @@ +def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 } + +def makePermutation; +makePermutation = { list, i -> + def n = list.size() + if (n < 2) return list + def fact = factorial(n-1) + assert i < fact*n + + def index = i.intdiv(fact) + [list[index]] + makePermutation(list[0..<index] + list[(index+1)..<n], i % fact) +} + +def sorted = { a -> (1..<(a.size())).every { a[it-1] <= a[it] } } + +def permutationSort = { a -> + def n = a.size() + def fact = factorial(n) + def permuteA = makePermutation.curry(a) + def pIndex = (0..<fact).find { print "."; sorted(permuteA(it)) } + permuteA(pIndex) +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-2.groovy b/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-2.groovy new file mode 100644 index 0000000000..17af07c577 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Groovy/sorting-algorithms-permutation-sort-2.groovy @@ -0,0 +1,8 @@ +println permutationSort([7,0,12,-45,-1]) +println () +println permutationSort([10, 10.0, 10.00, 1]) +println permutationSort([10, 10.00, 10.0, 1]) +println permutationSort([10.0, 10, 10.00, 1]) +println permutationSort([10.0, 10.00, 10, 1]) +println permutationSort([10.00, 10, 10.0, 1]) +println permutationSort([10.00, 10.0, 10, 1]) diff --git a/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-1.hs b/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-1.hs new file mode 100644 index 0000000000..51a1bba798 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-1.hs @@ -0,0 +1,12 @@ +import Control.Monad + +permutationSort l = head [p | p <- permute l, sorted p] + +sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r) +sorted _ = True + +permute = foldM (flip insert) [] + +insert e [] = return [e] +insert e l@(h : t) = return (e : l) `mplus` + do { t' <- insert e t ; return (h : t') } diff --git a/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-2.hs b/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-2.hs new file mode 100644 index 0000000000..6d2698ad10 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Haskell/sorting-algorithms-permutation-sort-2.hs @@ -0,0 +1,6 @@ +import Data.List (permutations) + +permutationSort l = head [p | p <- permutations l, sorted p] + +sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r) +sorted _ = True diff --git a/Task/Sorting-algorithms-Permutation-sort/Icon/sorting-algorithms-permutation-sort.icon b/Task/Sorting-algorithms-Permutation-sort/Icon/sorting-algorithms-permutation-sort.icon new file mode 100644 index 0000000000..06d5dd6447 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Icon/sorting-algorithms-permutation-sort.icon @@ -0,0 +1,21 @@ +procedure do_permute(l, i, n) + if i >= n then + return l + else + suspend l[i to n] <-> l[i] & do_permute(l, i+1, n) + end + + procedure permute(l) + suspend do_permute(l, 1, *l) + end + + procedure sorted(l) + local i + if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1 + end + + procedure main() + local l + l := [6,3,4,5,1] + |( l := permute(l) & sorted(l)) \1 & every writes(" ",!l) + end diff --git a/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-1.j b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-1.j new file mode 100644 index 0000000000..107101fee5 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-1.j @@ -0,0 +1 @@ +ps =:(1+])^:((-.@-:/:~)@A.~)^:_ 0: diff --git a/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-2.j b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-2.j new file mode 100644 index 0000000000..ad4d49cfba --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-2.j @@ -0,0 +1 @@ +ps =: A.@:/: diff --git a/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-3.j b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-3.j new file mode 100644 index 0000000000..f5dcd3ba77 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/J/sorting-algorithms-permutation-sort-3.j @@ -0,0 +1,10 @@ + list =: 2 7 4 3 5 1 0 9 8 6 + + ps list +2380483 + + 2380483 A. list +0 1 2 3 4 5 6 7 8 9 + + (A.~ps) list +0 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-1.m b/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-1.m new file mode 100644 index 0000000000..0d94f4e318 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-1.m @@ -0,0 +1,13 @@ +function list = permutationSort(list) + + permutations = perms(1:numel(list)); %Generate all permutations of the item indicies + + %Test every permutation of the indicies of the original list + for i = (1:size(permutations,1)) + if issorted( list(permutations(i,:)) ) + list = list(permutations(i,:)); + return %Once the correct permutation of the original list is found break out of the program + end + end + +end diff --git a/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-2.m b/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-2.m new file mode 100644 index 0000000000..cff00fc555 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/MATLAB/sorting-algorithms-permutation-sort-2.m @@ -0,0 +1,5 @@ +>> permutationSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Permutation-sort/Mathematica/sorting-algorithms-permutation-sort.math b/Task/Sorting-algorithms-Permutation-sort/Mathematica/sorting-algorithms-permutation-sort.math new file mode 100644 index 0000000000..29562002dc --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Mathematica/sorting-algorithms-permutation-sort.math @@ -0,0 +1 @@ +PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &] diff --git a/Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ocaml b/Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ocaml new file mode 100644 index 0000000000..2666234974 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ocaml @@ -0,0 +1,12 @@ +let rec sorted = function + | e1 :: e2 :: r -> e1 <= e2 && sorted (e2 :: r) + | _ -> true + +let rec insert e = function + | [] -> [[e]] + | h :: t as l -> (e :: l) :: List.map (fun t' -> h :: t') (insert e t) + +let permute xs = List.fold_right (fun h z -> List.concat (List.map (insert h) z)) + xs [[]] + +let permutation_sort l = List.find sorted (permute l) diff --git a/Task/Sorting-algorithms-Permutation-sort/PARI-GP/sorting-algorithms-permutation-sort.pari b/Task/Sorting-algorithms-Permutation-sort/PARI-GP/sorting-algorithms-permutation-sort.pari new file mode 100644 index 0000000000..c7d62f2d4d --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PARI-GP/sorting-algorithms-permutation-sort.pari @@ -0,0 +1,10 @@ +permutationSort(v)={ + my(u); + for(k=1,(#v)!, + u=vecextract(v, numtoperm(#v,k)); + for(i=2,#u, + if(u[i]<u[i-1], next(2)) + ); + return(u) + ) +}; diff --git a/Task/Sorting-algorithms-Permutation-sort/PHP/sorting-algorithms-permutation-sort.php b/Task/Sorting-algorithms-Permutation-sort/PHP/sorting-algorithms-permutation-sort.php new file mode 100644 index 0000000000..07785ac1a1 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PHP/sorting-algorithms-permutation-sort.php @@ -0,0 +1,33 @@ +function inOrder($arr){ + for($i=0;$i<count($arr);$i++){ + if(isset($arr[$i+1])){ + if($arr[$i] > $arr[$i+1]){ + return false; + } + } + } + return true; +} + +function permute($items, $perms = array( )) { + if (empty($items)) { + if(inOrder($perms)){ + return $perms; + } + } else { + for ($i = count($items) - 1; $i >= 0; --$i) { + $newitems = $items; + $newperms = $perms; + list($foo) = array_splice($newitems, $i, 1); + array_unshift($newperms, $foo); + $res = permute($newitems, $newperms); + if($res){ + return $res; + } + } + } +} + +$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); +$arr = permute($arr); +echo implode(',',$arr); diff --git a/Task/Sorting-algorithms-Permutation-sort/Perl-6/sorting-algorithms-permutation-sort.pl6 b/Task/Sorting-algorithms-Permutation-sort/Perl-6/sorting-algorithms-permutation-sort.pl6 new file mode 100644 index 0000000000..e748ad1b23 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Perl-6/sorting-algorithms-permutation-sort.pl6 @@ -0,0 +1,33 @@ +# Lexicographic permuter from "Permutations" task. +sub next_perm ( @a ) { + my $j = @a.end - 1; + $j-- while $j >= 1 and [>] @a[ $j, $j+1 ]; + + my $aj = @a[$j]; + my $k = @a.end; + $k-- while [>] $aj, @a[$k]; + + @a[ $j, $k ] .= reverse; + + my Int $r = @a.end; + my Int $s = $j + 1; + while $r > $s { + @a[ $r, $s ] .= reverse; + $r--; + $s++; + } +} + +sub permutation_sort ( @a ) { + my @n = @a.keys; + my $perm_count = [*] 1 .. +@n; # Factorial + for ^$perm_count { + my @permuted_a = @a[ @n ]; + return @permuted_a if [le] @permuted_a; + next_perm(@n); + } +} + +my @data = < c b e d a >; # Halfway between abcde and edcba +say 'Input = ' ~ @data; +say 'Output = ' ~ @data.&permutation_sort; diff --git a/Task/Sorting-algorithms-Permutation-sort/Perl/sorting-algorithms-permutation-sort.pl b/Task/Sorting-algorithms-Permutation-sort/Perl/sorting-algorithms-permutation-sort.pl new file mode 100644 index 0000000000..48ade566d7 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Perl/sorting-algorithms-permutation-sort.pl @@ -0,0 +1,19 @@ +sub psort { + my ($x, $d) = @_; + + unless ($d //= $#$x) { + $x->[$_] < $x->[$_ - 1] and return for 1 .. $#$x; + return 1 + } + + for (0 .. $d) { + unshift @$x, splice @$x, $d, 1; + next if $x->[$d] < $x->[$d - 1]; + return 1 if psort($x, $d - 1); + } +} + +my @a = map+(int rand 100), 0 .. 10; +print "Before:\t@a\n"; +psort(\@a); +print "After:\t@a\n" diff --git a/Task/Sorting-algorithms-Permutation-sort/PicoLisp/sorting-algorithms-permutation-sort.l b/Task/Sorting-algorithms-Permutation-sort/PicoLisp/sorting-algorithms-permutation-sort.l new file mode 100644 index 0000000000..faa8bba3cb --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PicoLisp/sorting-algorithms-permutation-sort.l @@ -0,0 +1,9 @@ +(de permutationSort (Lst) + (let L Lst + (recur (L) # Permute + (if (cdr L) + (do (length L) + (T (recurse (cdr L)) Lst) + (rot L) + NIL ) + (apply <= Lst) ) ) ) ) diff --git a/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.psh b/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.psh new file mode 100644 index 0000000000..cb541e38e9 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.psh @@ -0,0 +1,40 @@ +Function PermutationSort( [Object[]] $indata, $index = 0, $k = 0 ) +{ + $data = $indata.Clone() + $datal = $data.length - 1 + if( $datal -gt 0 ) { + for( $j = $index; $j -lt $datal; $j++ ) + { + $sorted = ( PermutationSort $data ( $index + 1 ) $j )[0] + if( -not $sorted ) + { + $temp = $data[ $index ] + $data[ $index ] = $data[ $j + 1 ] + $data[ $j + 1 ] = $temp + } + } + if( $index -lt ( $datal - 1 ) ) + { + PermutationSort $data ( $index + 1 ) $j + } else { + $sorted = $true + for( $i = 0; ( $i -lt $datal ) -and $sorted; $i++ ) + { + $sorted = ( $data[ $i ] -le $data[ $i + 1 ] ) + } + $sorted + $data + } + } +} + +0..4 | ForEach-Object { $a = $_; 0..4 | Where-Object { -not ( $_ -match "$a" ) } | + ForEach-Object { $b = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b" ) } | + ForEach-Object { $c = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b|$c" ) } | + ForEach-Object { $d = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b|$c|$d" ) } | + ForEach-Object { $e=$_; "$( PermutationSort ( $a, $b, $c, $d, $e ) )" } + } + } + } +} +$l = 8; PermutationSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Permutation-sort/Prolog/sorting-algorithms-permutation-sort.pro b/Task/Sorting-algorithms-Permutation-sort/Prolog/sorting-algorithms-permutation-sort.pro new file mode 100644 index 0000000000..1631292660 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Prolog/sorting-algorithms-permutation-sort.pro @@ -0,0 +1,8 @@ +permutation_sort(L,S) :- permutation(L,S), sorted(S). + +sorted([]). +sorted([_]). +sorted([X,Y|ZS]) :- X =< Y, sorted([Y|ZS]). + +permutation([],[]). +permutation([X|XS],YS) :- permutation(XS,ZS), select(X,YS,ZS). diff --git a/Task/Sorting-algorithms-Permutation-sort/PureBasic/sorting-algorithms-permutation-sort.purebasic b/Task/Sorting-algorithms-Permutation-sort/PureBasic/sorting-algorithms-permutation-sort.purebasic new file mode 100644 index 0000000000..0764685ccb --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PureBasic/sorting-algorithms-permutation-sort.purebasic @@ -0,0 +1,58 @@ +Macro reverse(firstIndex, lastIndex) + first = firstIndex + last = lastIndex + While first < last + Swap cur(first), cur(last) + first + 1 + last - 1 + Wend +EndMacro + +Procedure nextPermutation(Array cur(1)) + Protected first, last, elementCount = ArraySize(cur()) + If elementCount < 2 + ProcedureReturn #False ;nothing to permute + EndIf + + ;Find the lowest position pos such that [pos] < [pos+1] + Protected pos = elementCount - 1 + While cur(pos) >= cur(pos + 1) + pos - 1 + If pos < 0 + reverse(0, elementCount) + ProcedureReturn #False ;no higher lexicographic permutations left, return lowest one instead + EndIf + Wend + + ;Swap [pos] with the highest positional value that is larger than [pos] + last = elementCount + While cur(last) <= cur(pos) + last - 1 + Wend + Swap cur(pos), cur(last) + + ;Reverse the order of the elements in the higher positions + reverse(pos + 1, elementCount) + ProcedureReturn #True ;next lexicographic permutation found +EndProcedure + +Procedure display(Array a(1)) + Protected i, fin = ArraySize(a()) + For i = 0 To fin + Print(Str(a(i))) + If i = fin: Continue: EndIf + Print(", ") + Next + PrintN("") +EndProcedure + +If OpenConsole() + Dim a(9) + a(0) = 8: a(1) = 3: a(2) = 10: a(3) = 6: a(4) = 1: a(5) = 9: a(6) = 7: a(7) = -4: a(8) = 5: a(9) = 3 + display(a()) + While nextPermutation(a()): Wend + display(a()) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Sorting-algorithms-Permutation-sort/Python/sorting-algorithms-permutation-sort.py b/Task/Sorting-algorithms-Permutation-sort/Python/sorting-algorithms-permutation-sort.py new file mode 100644 index 0000000000..b043c6dfea --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Python/sorting-algorithms-permutation-sort.py @@ -0,0 +1,4 @@ +from itertools import permutations + +in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1])) +perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next() diff --git a/Task/Sorting-algorithms-Permutation-sort/R/sorting-algorithms-permutation-sort.r b/Task/Sorting-algorithms-Permutation-sort/R/sorting-algorithms-permutation-sort.r new file mode 100644 index 0000000000..da50c406eb --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/R/sorting-algorithms-permutation-sort.r @@ -0,0 +1,15 @@ +permutationsort <- function(x) +{ + if(!require(e1071) stop("the package e1071 is required") + is.sorted <- function(x) all(diff(x) >= 0) + + perms <- permutations(length(x)) + i <- 1 + while(!is.sorted(x)) + { + x <- x[perms[i,]] + i <- i + 1 + } + x +} +permutationsort(c(1, 10, 9, 7, 3, 0)) diff --git a/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx new file mode 100644 index 0000000000..f148ca319a --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx @@ -0,0 +1,52 @@ +/*REXX program sorts an array using the permutation-sort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call permsets items /*generate items! permutations.*/ +call permSort items /*invoke the permutation sort. */ +call show@ ' after sort' /*show after array elements*/ +say; say 'Permutation sort took' ? "permutations to find the sorted list." +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign default value. */ +@.1 = '---Four_horsemen_of_the_Apocalypse---' +@.2 = '=====================================' +@.3 = 'Famine───black_horse' +@.4 = 'Death───pale_horse' +@.5 = 'Pestilence_[Slaughter]───red_horse' +@.6 = 'Conquest_[War]───white_horse' +list= /*[↓] find # of entries in array.*/ + do items=1 while @.items\==''; @@.items=@.items; end /*items*/ +items=items-1 /*adjust items slightly. */ +return +/*──────────────────────────────────INORDER subroutine──────────────────*/ +inOrder: parse arg q /*see if list Q is in order. */ +_=word(q,1); do j=2 to words(q); x=word(q,j) + if x<_ then return 0 /*Out of order? Then not sorted.*/ + _=x + end /*j*/ + do k=1 for items; _=word(#.?,k); @.k=@@._; end /*k*/ /*here it is*/ +return 1 /*they're all in order finally. */ +/*──────────────────────────────────PERMSETS subroutine─────────────────*/ +permsets: procedure expose !. # #.; parse arg n,#.; #=0 + do f=1 for n; !.f=f; end /*f*/; call .permAdd /*populate 1st perm*/ + do while .permNext(n,0); call .permAdd; end /*while ···*/ +return # +.permNext: procedure expose !.; parse arg n,i; nm=n-1 + do k=nm by -1 for nm; kp=k+1 + if !.k<!.kp then do; i=k; leave; end + end /*k*/ + do j=i+1 while j<n; parse value !.j !.n with !.n !.j; n=n-1; end +if i==0 then return 0; do j=i+1 while !.j<!.i; end /*j*/ +parse value !.j !.i with !.i !.j +return 1 +.permAdd: #=#+1; do j=1 for N; #.#=#.# !.j; end /*j*/; return +/*──────────────────────────────────PERMSORT subroutine─────────────────*/ +permSort: do ?=1 until inOrder(aList) /*look for the sorted permutation*/ +aList=; do m=1 for items; _=word(#.?,m); aList=aList @._; end /*m*/ + end /*?*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(items) /*maximum width of any line. */ + do j=1 for items; say 'element' right(j,widthH) arg(1)":" @.j; end /*j*/ +say copies('─', 79) /*show a nice separator line. */ +return diff --git a/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb b/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb new file mode 100644 index 0000000000..58b0a0b16a --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Ruby/sorting-algorithms-permutation-sort.rb @@ -0,0 +1,13 @@ +class Array + def permutationsort + permutations = permutation + begin + perm = permutations.next + end until perm.sorted? + perm + end + + def sorted? + each_cons(2).all? {|a, b| a <= b} + end +end diff --git a/Task/Sorting-algorithms-Permutation-sort/Scheme/sorting-algorithms-permutation-sort.ss b/Task/Sorting-algorithms-Permutation-sort/Scheme/sorting-algorithms-permutation-sort.ss new file mode 100644 index 0000000000..971e15f219 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Scheme/sorting-algorithms-permutation-sort.ss @@ -0,0 +1,25 @@ +(define (insertions e list) + (if (null? list) + (cons (cons e list) list) + (cons (cons e list) + (map (lambda (tail) (cons (car list) tail)) + (insertions e (cdr list)))))) + +(define (permutations list) + (if (null? list) + (cons list list) + (apply append (map (lambda (permutation) + (insertions (car list) permutation)) + (permutations (cdr list)))))) + +(define (sorted? list) + (cond ((null? list) #t) + ((null? (cdr list)) #t) + ((<= (car list) (cadr list)) (sorted? (cdr list))) + (else #f))) + +(define (permutation-sort list) + (let loop ((permutations (permutations list))) + (if (sorted? (car permutations)) + (car permutations) + (loop (cdr permutations))))) diff --git a/Task/Sorting-algorithms-Permutation-sort/Tcl/sorting-algorithms-permutation-sort.tcl b/Task/Sorting-algorithms-Permutation-sort/Tcl/sorting-algorithms-permutation-sort.tcl new file mode 100644 index 0000000000..a5af5f92bc --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Tcl/sorting-algorithms-permutation-sort.tcl @@ -0,0 +1,11 @@ +package require Tcl 8.5 +package require struct::list + +proc inorder {list} {::tcl::mathop::<= {*}$list} + +proc permutationsort {list} { + while { ! [inorder $list]} { + set list [struct::list nextperm $list] + } + return $list +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Ursala/sorting-algorithms-permutation-sort.ursala b/Task/Sorting-algorithms-Permutation-sort/Ursala/sorting-algorithms-permutation-sort.ursala new file mode 100644 index 0000000000..84bd7ab275 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Ursala/sorting-algorithms-permutation-sort.ursala @@ -0,0 +1,7 @@ +#import std + +permsort "p" = ~&ihB+ ordered"p"*~+ permutations + +#cast %sL + +example = permsort(lleq) <'pmf','oao','ejw','hhp','oqh','ock','dwj'> diff --git a/Task/Sorting-algorithms-Quicksort/0DESCRIPTION b/Task/Sorting-algorithms-Quicksort/0DESCRIPTION new file mode 100644 index 0000000000..76735d609a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/0DESCRIPTION @@ -0,0 +1,61 @@ +{{Sorting Algorithm}}[[Category:Recursion]] +{{wikipedia|Quicksort}} + +The task is to sort an array (or list) elements using the ''quicksort'' algorithm. The elements must have a strict weak order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers. + +Quicksort, also known as ''partition-exchange sort'', uses these steps. + +# Choose any element of the array to be the pivot. +# Divide all other elements (except the pivot) into two partitions. +#* All elements less than the pivot must be in the first partition. +#* All elements greater than the pivot must be in the second partition. +# Use recursion to sort both partitions. +# Join the first sorted partition, the pivot, and the second sorted partition. + +The best pivot creates partitions of equal length (or lengths differing by 1). The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array). The runtime of Quicksort ranges from ''[[O]](n ''log'' n)'' with the best pivots, to ''[[O]](n<sup>2</sup>)'' with the worst pivots, where ''n'' is the number of elements in the array. + +This is a simple quicksort algorithm, adapted from Wikipedia. + + '''function''' ''quicksort''(array) + less, equal, greater ''':=''' three empty arrays + '''if''' length(array) > 1 + pivot ''':=''' ''select any element of'' array + '''for each''' x '''in''' array + '''if''' x < pivot '''then add''' x '''to''' less + '''if''' x = pivot '''then add''' x '''to''' equal + '''if''' x > pivot '''then add''' x '''to''' greater + quicksort(less) + quicksort(greater) + array ''':=''' concatenate(less, equal, greater) + +A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays. + + '''function''' ''quicksort''(array) + '''if''' length(array) > 1 + pivot ''':=''' ''select any element of'' array + left ''':= first index of''' array + right ''':=''' '''last index of''' array + '''while''' left ≤ right + '''while''' array[left] < pivot + left := left + 1 + '''while''' array[right] > pivot + right := right - 1 + '''if''' left ≤ right + '''swap''' array[left] '''with''' array[right] + left := left + 1 + right := right - 1 + quicksort(array '''from first index to''' right) + quicksort(array '''from''' left '''to last index''') + +Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with [[../Merge sort|merge sort]], because both sorts have an average time of ''[[O]](n ''log'' n)''. + +: ''"On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times."'' — http://perldoc.perl.org/sort.html + +Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end. + +* Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort. +* Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase. + +With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention! + +This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations. diff --git a/Task/Sorting-algorithms-Quicksort/1META.yaml b/Task/Sorting-algorithms-Quicksort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-1.acl2 b/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-1.acl2 new file mode 100644 index 0000000000..f0d5755277 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-1.acl2 @@ -0,0 +1,17 @@ +(defun partition (p xs) + (if (endp xs) + (mv nil nil) + (mv-let (less more) + (partition p (rest xs)) + (if (< (first xs) p) + (mv (cons (first xs) less) more) + (mv less (cons (first xs) more)))))) + +(defun qsort (xs) + (if (endp xs) + nil + (mv-let (less more) + (partition (first xs) (rest xs)) + (append (qsort less) + (list (first xs)) + (qsort more))))) diff --git a/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-2.acl2 b/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-2.acl2 new file mode 100644 index 0000000000..59bfa41903 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ACL2/sorting-algorithms-quicksort-2.acl2 @@ -0,0 +1,2 @@ +> (qsort '(8 6 7 5 3 0 9)) +(0 3 5 6 7 8 9) diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg new file mode 100644 index 0000000000..1fe7cc4b16 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg @@ -0,0 +1,47 @@ +PROC partition =(REF [] DATA array, PROC (REF DATA, REF DATA) BOOL cmp)INT: ( + INT begin:=LWB array; + INT end:=UPB array; + WHILE begin < end DO + WHILE begin < end DO + IF cmp(array[begin], array[end]) THEN + DATA tmp=array[begin]; + array[begin]:=array[end]; + array[end]:=tmp; + GO TO break while decr end + FI; + end -:= 1 + OD; + break while decr end: SKIP; + WHILE begin < end DO + IF cmp(array[begin], array[end]) THEN + DATA tmp=array[begin]; + array[begin]:=array[end]; + array[end]:=tmp; + GO TO break while incr begin + FI; + begin +:= 1 + OD; + break while incr begin: SKIP + OD; + begin +); + +PROC qsort=(REF [] DATA array, PROC (REF DATA, REF DATA) BOOL cmp)VOID: ( + IF LWB array < UPB array THEN + INT i := partition(array, cmp); + PAR ( # remove PAR for single threaded sort # + qsort(array[:i-1], cmp), + qsort(array[i+1:], cmp) + ) + FI +); + +MODE DATA = INT; +PROC cmp=(REF DATA a,b)BOOL: a>b; + +main:( + []DATA const l=(5,4,3,2,1); + [UPB const l]DATA l:=const l; + qsort(l,cmp); + printf(($g(3)$,l)) +) diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-2.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-2.alg new file mode 100644 index 0000000000..66eb51d453 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-2.alg @@ -0,0 +1,3 @@ + qsort ← {1≥⍴⍵:⍵⋄e←⍵[?⍴⍵]⋄ (∇(⍵<e)/⍵) , ((⍵=e)/⍵) , ∇(⍵>e)/⍵} + qsort 1 3 5 7 9 8 6 4 2 +1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Quicksort/AWK/sorting-algorithms-quicksort.awk b/Task/Sorting-algorithms-Quicksort/AWK/sorting-algorithms-quicksort.awk new file mode 100644 index 0000000000..6b1d0ed464 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/AWK/sorting-algorithms-quicksort.awk @@ -0,0 +1,113 @@ +# the following qsort implementation extracted from: +# +# ftp://ftp.armory.com/pub/lib/awk/qsort +# +# Copyleft GPLv2 John DuBois +# +# @(#) qsort 1.2.1 2005-10-21 +# 1990 john h. dubois iii (john@armory.com) +# +# qsortArbIndByValue(): Sort an array according to the values of its elements. +# +# Input variables: +# +# Arr[] is an array of values with arbitrary (associative) indices. +# +# Output variables: +# +# k[] is returned with numeric indices 1..n. The values assigned to these +# indices are the indices of Arr[], ordered so that if Arr[] is stepped +# through in the order Arr[k[1]] .. Arr[k[n]], it will be stepped through in +# order of the values of its elements. +# +# Return value: The number of elements in the arrays (n). +# +# NOTES: +# +# Full example for accessing results: +# +# foolist["second"] = 2; +# foolist["zero"] = 0; +# foolist["third"] = 3; +# foolist["first"] = 1; +# +# outlist[1] = 0; +# n = qsortArbIndByValue(foolist, outlist) +# +# for (i = 1; i <= n; i++) { +# printf("item at %s has value %d\n", outlist[i], foolist[outlist[i]]); +# } +# delete outlist; +# +function qsortArbIndByValue(Arr, k, + ArrInd, ElNum) +{ + ElNum = 0; + for (ArrInd in Arr) { + k[++ElNum] = ArrInd; + } + qsortSegment(Arr, k, 1, ElNum); + return ElNum; +} +# +# qsortSegment(): Sort a segment of an array. +# +# Input variables: +# +# Arr[] contains data with arbitrary indices. +# +# k[] has indices 1..nelem, with the indices of Arr[] as values. +# +# Output variables: +# +# k[] is modified by this function. The elements of Arr[] that are pointed to +# by k[start..end] are sorted, with the values of elements of k[] swapped +# so that when this function returns, Arr[k[start..end]] will be in order. +# +# Return value: None. +# +function qsortSegment(Arr, k, start, end, + left, right, sepval, tmp, tmpe, tmps) +{ + if ((end - start) < 1) { # 0 or 1 elements + return; + } + # handle two-element case explicitly for a tiny speedup + if ((end - start) == 1) { + if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) { + k[start] = tmpe; + k[end] = tmps; + } + return; + } + # Make sure comparisons act on these as numbers + left = start + 0; + right = end + 0; + sepval = Arr[k[int((left + right) / 2)]]; + # Make every element <= sepval be to the left of every element > sepval + while (left < right) { + while (Arr[k[left]] < sepval) { + left++; + } + while (Arr[k[right]] > sepval) { + right--; + } + if (left < right) { + tmp = k[left]; + k[left++] = k[right]; + k[right--] = tmp; + } + } + if (left == right) + if (Arr[k[left]] < sepval) { + left++; + } else { + right--; + } + if (start < right) { + qsortSegment(Arr, k, start, right); + } + if (left < end) { + qsortSegment(Arr, k, left, end); + } +} diff --git a/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-1.as b/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-1.as new file mode 100644 index 0000000000..8d45206067 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-1.as @@ -0,0 +1,11 @@ +function quickSort (array:Array):Array +{ + if (array.length <= 1) + return array; + + var pivot:Number = array[Math.round(array.length / 2)]; + + return quickSort(array.filter(function (x:Number, index:int, array:Array):Boolean { return x < pivot; })).concat( + array.filter(function (x:Number, index:int, array:Array):Boolean { return x == pivot; })).concat( + quickSort(array.filter(function (x:Number, index:int, array:Array):Boolean { return x > pivot; }))); +} diff --git a/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-2.as b/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-2.as new file mode 100644 index 0000000000..e37370053d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ActionScript/sorting-algorithms-quicksort-2.as @@ -0,0 +1,24 @@ +function quickSort (array:Array):Array +{ + if (array.length <= 1) + return array; + + var pivot:Number = array[Math.round(array.length / 2)]; + + var less:Array = []; + var equal:Array = []; + var greater:Array = []; + + for each (var x:Number in array) { + if (x < pivot) + less.push(x); + if (x == pivot) + equal.push(x); + if (x > pivot) + greater.push(x); + } + + return quickSort(less).concat( + equal).concat( + quickSort(greater)); +} diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.ada b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.ada new file mode 100644 index 0000000000..2c8d25658e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.ada @@ -0,0 +1,10 @@ +----------------------------------------------------------------------- +-- Generic Quicksort procedure +----------------------------------------------------------------------- +generic + type Element_Type is private; + type Index_Type is (<>); + type Element_Array is array(Index_Type range <>) of Element_Type; + with function "<" (Left, Right : Element_Type) return Boolean is <>; + with function ">" (Left, Right : Element_Type) return Boolean is <>; +procedure Sort(Item : in out Element_Array); diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada new file mode 100644 index 0000000000..20f410a28b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada @@ -0,0 +1,48 @@ +----------------------------------------------------------------------- +-- Generic Quicksort procedure +----------------------------------------------------------------------- + +procedure Sort (Item : in out Element_Array) is + + procedure Swap(Left, Right : in out Element_Type) is + Temp : Element_Type := Left; + begin + Left := Right; + Right := Temp; + end Swap; + + Pivot_Index : Index_Type; + Pivot_Value : Element_Type; + Right : Index_Type := Item'Last; + Left : Index_Type := Item'First; + +begin + if Item'Length > 1 then + Pivot_Index := Index_Type'Val((Index_Type'Pos(Item'Last) + 1 + + Index_Type'Pos(Item'First)) / 2); + Pivot_Value := Item(Pivot_Index); + + Left := Item'First; + Right := Item'Last; + loop + while Left < Item'Last and then Item(Left) < Pivot_Value loop + Left := Index_Type'Succ(Left); + end loop; + while Right > Item'First and then Item(Right) > Pivot_Value loop + Right := Index_Type'Pred(Right); + end loop; + exit when Left >= Right; + Swap(Item(Left), Item(Right)); + if Left < Item'Last and Right > Item'First then + Left := Index_Type'Succ(Left); + Right := Index_Type'Pred(Right); + end if; + end loop; + if Right > Item'First then + Sort(Item(Item'First..Index_Type'Pred(Right))); + end if; + if Left < Item'Last then + Sort(Item(Left..Item'Last)); + end if; + end if; +end Sort; diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.ada b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.ada new file mode 100644 index 0000000000..f9ae107d9b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.ada @@ -0,0 +1,32 @@ +with Sort; +with Ada.Text_Io; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; + +procedure Sort_Test is + type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); + type Sales is array(Days range <>) of Float; + procedure Sort_Days is new Sort(Float, Days, Sales); + + procedure Print(Item : Sales) is + begin + for I in Item'range loop + Put(Item => Item(I), Fore => 5, Aft => 2, Exp => 0); + end loop; + end Print; + + Weekly_Sales : Sales := (Mon => 300.0, + Tue => 700.0, + Wed => 800.0, + Thu => 500.0, + Fri => 200.0, + Sat => 100.0, + Sun => 900.0); + +begin + + Print(Weekly_Sales); + Ada.Text_Io.New_Line(2); + Sort_Days(Weekly_Sales); + Print(Weekly_Sales); + +end Sort_Test; diff --git a/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort.ahk b/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort.ahk new file mode 100644 index 0000000000..a17b5f3524 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/AutoHotkey/sorting-algorithms-quicksort.ahk @@ -0,0 +1,24 @@ +MsgBox % quicksort("8,4,9,2,1") + +quicksort(list) +{ + StringSplit, list, list, `, + If (list0 <= 1) + Return list + pivot := list1 + Loop, Parse, list, `, + { + If (A_LoopField < pivot) + less = %less%,%A_LoopField% + Else If (A_LoopField > pivot) + more = %more%,%A_LoopField% + Else + pivotlist = %pivotlist%,%A_LoopField% + } + StringTrimLeft, less, less, 1 + StringTrimLeft, more, more, 1 + StringTrimLeft, pivotList, pivotList, 1 + less := quicksort(less) + more := quicksort(more) + Return less . pivotList . more +} diff --git a/Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic new file mode 100644 index 0000000000..ece4d2803e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic @@ -0,0 +1,50 @@ +DECLARE SUB quicksort (arr() AS INTEGER, leftN AS INTEGER, rightN AS INTEGER) + +DIM q(99) AS INTEGER +DIM n AS INTEGER + +RANDOMIZE TIMER + +FOR n = 0 TO 99 + q(n) = INT(RND * 9999) +NEXT + +OPEN "output.txt" FOR OUTPUT AS 1 + FOR n = 0 TO 99 + PRINT #1, q(n), + NEXT + PRINT #1, + quicksort q(), 0, 99 + FOR n = 0 TO 99 + PRINT #1, q(n), + NEXT +CLOSE + +SUB quicksort (arr() AS INTEGER, leftN AS INTEGER, rightN AS INTEGER) + DIM pivot AS INTEGER, leftNIdx AS INTEGER, rightNIdx AS INTEGER + leftNIdx = leftN + rightNIdx = rightN + IF (rightN - leftN) > 0 THEN + pivot = (leftN + rightN) / 2 + WHILE (leftNIdx <= pivot) AND (rightNIdx >= pivot) + WHILE (arr(leftNIdx) < arr(pivot)) AND (leftNIdx <= pivot) + leftNIdx = leftNIdx + 1 + WEND + WHILE (arr(rightNIdx) > arr(pivot)) AND (rightNIdx >= pivot) + rightNIdx = rightNIdx - 1 + WEND + SWAP arr(leftNIdx), arr(rightNIdx) + leftNIdx = leftNIdx + 1 + rightNIdx = rightNIdx - 1 + IF (leftNIdx - 1) = pivot THEN + rightNIdx = rightNIdx + 1 + pivot = rightNIdx + ELSEIF (rightNIdx + 1) = pivot THEN + leftNIdx = leftNIdx - 1 + pivot = leftNIdx + END IF + WEND + quicksort arr(), leftN, pivot - 1 + quicksort arr(), pivot + 1, rightN + END IF +END SUB diff --git a/Task/Sorting-algorithms-Quicksort/BBC-BASIC/sorting-algorithms-quicksort.bbc b/Task/Sorting-algorithms-Quicksort/BBC-BASIC/sorting-algorithms-quicksort.bbc new file mode 100644 index 0000000000..9560603c23 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/BBC-BASIC/sorting-algorithms-quicksort.bbc @@ -0,0 +1,28 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCquicksort(test(), 0, 10) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCquicksort(a(), s%, n%) + LOCAL l%, p, r%, t% + IF n% < 2 THEN ENDPROC + t% = s% + n% - 1 + l% = s% + r% = t% + p = a((l% + r%) DIV 2) + REPEAT + WHILE a(l%) < p l% += 1 : ENDWHILE + WHILE a(r%) > p r% -= 1 : ENDWHILE + IF l% <= r% THEN + SWAP a(l%), a(r%) + l% += 1 + r% -= 1 + ENDIF + UNTIL l% > r% + IF s% < r% PROCquicksort(a(), s%, r% - s% + 1) + IF l% < t% PROCquicksort(a(), l%, t% - l% + 1 ) + ENDPROC diff --git a/Task/Sorting-algorithms-Quicksort/BCPL/sorting-algorithms-quicksort.bcpl b/Task/Sorting-algorithms-Quicksort/BCPL/sorting-algorithms-quicksort.bcpl new file mode 100644 index 0000000000..4dcba1c476 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/BCPL/sorting-algorithms-quicksort.bcpl @@ -0,0 +1,53 @@ +// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10. + +GET "libhdr.h" + +LET quicksort(v, n) BE qsort(v+1, v+n) + +AND qsort(l, r) BE +{ WHILE l+8<r DO + { LET midpt = (l+r)/2 + // Select a good(ish) median value. + LET val = middle(!l, !midpt, !r) + LET i = partition(val, l, r) + // Only use recursion on the smaller partition. + TEST i>midpt THEN { qsort(i, r); r := i-1 } + ELSE { qsort(l, i-1); l := i } + } + + FOR p = l+1 TO r DO // Now perform insertion sort. + FOR q = p-1 TO l BY -1 TEST q!0<=q!1 THEN BREAK + ELSE { LET t = q!0 + q!0 := q!1 + q!1 := t + } +} + +AND middle(a, b, c) = a<b -> b<c -> b, + a<c -> c, + a, + b<c -> a<c -> a, + c, + b + +AND partition(median, p, q) = VALOF +{ LET t = ? + WHILE !p < median DO p := p+1 + WHILE !q > median DO q := q-1 + IF p>=q RESULTIS p + t := !p + !p := !q + !q := t + p, q := p+1, q-1 +} REPEAT + +LET start() = VALOF { + LET v = VEC 1000 + FOR i = 1 TO 1000 DO v!i := randno(1_000_000) + quicksort(v, 1000) + FOR i = 1 TO 1000 DO + { IF i MOD 10 = 0 DO newline() + writef(" %i6", v!i) + } + newline() +} diff --git a/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-1.cpp b/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-1.cpp new file mode 100644 index 0000000000..a9bddce10f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-1.cpp @@ -0,0 +1,70 @@ +#include <iterator> +#include <algorithm> // for std::partition +#include <functional> // for std::less + +// helper function for median of three +template<typename T> + T median(T t1, T t2, T t3) +{ + if (t1 < t2) + { + if (t2 < t3) + return t2; + else if (t1 < t3) + return t3; + else + return t1; + } + else + { + if (t1 < t3) + return t1; + else if (t2 < t3) + return t3; + else + return t2; + } +} + +// helper object to get <= from < +template<typename Order> struct non_strict_op: + public std::binary_function<typename Order::second_argument_type, + typename Order::first_argument_type, + bool> +{ + non_strict_op(Order o): order(o) {} + bool operator()(typename Order::second_argument_type arg1, + typename Order::first_argument_type arg2) const + { + return !order(arg2, arg1); + } +private: + Order order; +}; + +template<typename Order> non_strict_op<Order> non_strict(Order o) +{ + return non_strict_op<Order>(o); +} + +template<typename RandomAccessIterator, + typename Order> + void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order) +{ + if (first != last && first+1 != last) + { + typedef typename std::iterator_traits<RandomAccessIterator>::value_type value_type; + RandomAccessIterator mid = first + (last - first)/2; + value_type pivot = median(*first, *mid, *(last-1)); + RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot)); + RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot)); + quicksort(first, split1, order); + quicksort(split2, last, order); + } +} + +template<typename RandomAccessIterator> + void quicksort(RandomAccessIterator first, RandomAccessIterator last) +{ + quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>()); +} diff --git a/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-2.cpp b/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-2.cpp new file mode 100644 index 0000000000..5e2ef2a7f7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/C++/sorting-algorithms-quicksort-2.cpp @@ -0,0 +1,22 @@ +#include <iterator> +#include <algorithm> // for std::partition +#include <functional> // for std::less + +template<typename RandomAccessIterator, + typename Order> + void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order) +{ + if (last - first > 1) + { + RandomAccessIterator split = std::partition(first+1, last, std::bind2nd(order, *first)); + std::iter_swap(first, split-1); + quicksort(first, split-1, order); + quicksort(split, last, order); + } +} + +template<typename RandomAccessIterator> + void quicksort(RandomAccessIterator first, RandomAccessIterator last) +{ + quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>()); +} diff --git a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c new file mode 100644 index 0000000000..0d3695d4a7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c @@ -0,0 +1,29 @@ +void quick_sort (int *a, int n) { + if (n < 2) + return; + int p = a[n / 2]; + int *l = a; + int *r = a + n - 1; + while (l <= r) { + if (*l < p) { + l++; + continue; + } + if (*r > p) { + r--; + continue; // we need to check the condition (l <= r) every time we change the value of l or r + } + int t = *l; + *l++ = *r; + *r-- = t; + } + quick_sort(a, r - a + 1); + quick_sort(l, a + n - l); +} + +int main () { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + quick_sort(a, n); + return 0; +} diff --git a/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-1.clj b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-1.clj new file mode 100644 index 0000000000..cd90e224f2 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-1.clj @@ -0,0 +1,7 @@ +(defn qsort [L] + (if (empty? L) + '() + (let [[pivot & L2] L] + (lazy-cat (qsort (for [y L2 :when (< y pivot)] y)) + (list pivot) + (qsort (for [y L2 :when (>= y pivot)] y)))))) diff --git a/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-2.clj b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-2.clj new file mode 100644 index 0000000000..9bd60e2272 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-2.clj @@ -0,0 +1,5 @@ +(defn qsort [[pvt & rs]] + (if pvt + `(~@(qsort (filter #(< % pvt) rs)) + ~pvt + ~@(qsort (filter #(>= % pvt) rs))))) diff --git a/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-3.clj b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-3.clj new file mode 100644 index 0000000000..7322112c9e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-3.clj @@ -0,0 +1,6 @@ +(defn qsort [[pivot & xs]] + (when pivot + (let [smaller #(< % pivot)] + (lazy-cat (qsort (filter smaller xs)) + [pivot] + (qsort (remove smaller xs)))))) diff --git a/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-4.clj b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-4.clj new file mode 100644 index 0000000000..1aa1a3307f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-4.clj @@ -0,0 +1,4 @@ +(defn qsort3 [[pvt :as coll]] + (when pvt + (let [{left -1 mid 0 right 1} (group-by #(compare % pvt) coll)] + (lazy-cat (qsort3 left) mid (qsort3 right))))) diff --git a/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-5.clj b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-5.clj new file mode 100644 index 0000000000..855e176a0c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Clojure/sorting-algorithms-quicksort-5.clj @@ -0,0 +1,5 @@ +(defn qsort3 [[pivot :as coll]] + (when pivot + (lazy-cat (qsort (filter #(< % pivot) coll)) + (filter #{pivot} coll) + (qsort (filter #(> % pivot) coll))))) diff --git a/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffeescript b/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffeescript new file mode 100644 index 0000000000..efe43b686f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/CoffeeScript/sorting-algorithms-quicksort.coffeescript @@ -0,0 +1,35 @@ +# This shows quicksort-in-place. +quicksort = (a) -> + swap = (i, j) -> + return if i == j + [a[i], a[j]] = [a[j], a[i]] + + divide = (v, start, end) -> + first_big = start + j = start + while j <= end + if a[j] < v + swap first_big, j + first_big += 1 + j += 1 + first_big + + partition = (start, end) -> + v = a[end] + first_big = divide v, start, end-1 + swap first_big, end + first_big + + qs = (start, end) -> + return if start >= end + m = partition start, end + qs start, m-1 + qs m+1, end + + qs 0, a.length - 1 + +# test +do -> + a = [1, 3, 5, 7, 9, 8, 6, 4, 2, 0, 3.5] + quicksort(a) + console.log a # [ 0, 1, 2, 3, 3.5, 4, 5, 6, 7, 8, 9 ] diff --git a/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-1.lisp b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-1.lisp new file mode 100644 index 0000000000..c992f88e47 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-1.lisp @@ -0,0 +1,6 @@ +(defun quicksort (list &aux (pivot (car list)) ) + (if (cdr list) + (nconc (quicksort (remove-if-not #'(lambda (x) (< x pivot)) list)) + (remove-if-not #'(lambda (x) (= x pivot)) list) + (quicksort (remove-if-not #'(lambda (x) (> x pivot)) list))) + list)) diff --git a/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-2.lisp b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-2.lisp new file mode 100644 index 0000000000..2d497db676 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-2.lisp @@ -0,0 +1,6 @@ +(defun qs (list) + (if (cdr list) + (flet ((pivot (test) + (remove (car list) list :test-not test))) + (nconc (qs (pivot #'>)) (pivot #'=) (qs (pivot #'<)))) + list)) diff --git a/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-3.lisp b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-3.lisp new file mode 100644 index 0000000000..6925745a25 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Common-Lisp/sorting-algorithms-quicksort-3.lisp @@ -0,0 +1,14 @@ +(defun quicksort (sequence) + (labels ((swap (a b) (rotatef (elt sequence a) (elt sequence b))) + (sub-sort (left right) + (when (< left right) + (let ((pivot (elt sequence right)) + (index left)) + (loop for i from left below right + when (<= (elt sequence i) pivot) + do (swap i (prog1 index (incf index)))) + (swap right index) + (sub-sort left (1- index)) + (sub-sort (1+ index) right))))) + (sub-sort 0 (1- (length sequence))) + sequence)) diff --git a/Task/Sorting-algorithms-Quicksort/Curry/sorting-algorithms-quicksort.curry b/Task/Sorting-algorithms-Quicksort/Curry/sorting-algorithms-quicksort.curry new file mode 100644 index 0000000000..75feb98595 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Curry/sorting-algorithms-quicksort.curry @@ -0,0 +1,7 @@ +-- quicksort using higher-order functions: + +qsort :: [Int] -> [Int] +qsort [] = [] +qsort (x:l) = qsort (filter (<x) l) ++ x : qsort (filter (>=x) l) + +goal = qsort [2,3,1,0] diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d new file mode 100644 index 0000000000..392a36fcca --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d @@ -0,0 +1,14 @@ +import std.stdio; + +T[] quickSort(T)(T[] items) { + if (items.length <= 1) + return items; + T[] less, more; + foreach (x; items[1 .. $]) + (x < items[0] ? less : more) ~= x; + return quickSort(less) ~ items[0] ~ quickSort(more); +} + +void main() { + writeln(quickSort([4, 65, 2, -31, 0, 99, 2, 83, 782, 1])); +} diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d new file mode 100644 index 0000000000..02679b3e83 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-2.d @@ -0,0 +1,18 @@ +import std.stdio; +import std.algorithm; + +void quickSort(T)(T[] items) +{ + if (items.length >= 2) { + auto parts = partition3(items, items[$ / 2]); + quickSort(parts[0]); + quickSort(parts[2]); + } +} + +void main() +{ + auto items = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; + quickSort(items); + writeln(items); +} diff --git a/Task/Sorting-algorithms-Quicksort/Dart/sorting-algorithms-quicksort.dart b/Task/Sorting-algorithms-Quicksort/Dart/sorting-algorithms-quicksort.dart new file mode 100644 index 0000000000..300c616ae3 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Dart/sorting-algorithms-quicksort.dart @@ -0,0 +1,39 @@ +quickSort(List a) { + if (a.length <= 1) { + return a; + } + + var pivot = a[0]; + var less = []; + var more = []; + var pivotList = []; + + // Partition + a.forEach((var i){ + if (i.compareTo(pivot) < 0) { + less.add(i); + } else if (i.compareTo(pivot) > 0) { + more.add(i); + } else { + pivotList.add(i); + } + }); + + // Recursively sort sublists + less = quickSort(less); + more = quickSort(more); + + // Concatenate results + less.addAll(pivotList); + less.addAll(more); + return less; +} + +void main() { + var arr=[1,5,2,7,3,9,4,6,8]; + print("Before sort"); + arr.forEach((var i)=>print("$i")); + arr = quickSort(arr); + print("After sort"); + arr.forEach((var i)=>print("$i")); +} diff --git a/Task/Sorting-algorithms-Quicksort/E/sorting-algorithms-quicksort.e b/Task/Sorting-algorithms-Quicksort/E/sorting-algorithms-quicksort.e new file mode 100644 index 0000000000..855b78eb07 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/E/sorting-algorithms-quicksort.e @@ -0,0 +1,47 @@ +def quicksort := { + + def swap(container, ixA, ixB) { + def temp := container[ixA] + container[ixA] := container[ixB] + container[ixB] := temp + } + + def partition(array, var first :int, var last :int) { + if (last <= first) { return } + + # Choose a pivot + def pivot := array[def pivotIndex := (first + last) // 2] + + # Move pivot to end temporarily + swap(array, pivotIndex, last) + + var swapWith := first + + # Scan array except for pivot, and... + for i in first..!last { + if (array[i] <= pivot) { # items ≤ the pivot + swap(array, i, swapWith) # are moved to consecutive positions on the left + swapWith += 1 + } + } + + # Swap pivot into between-partition position. + # Because of the swapping we know that everything before swapWith is less + # than or equal to the pivot, and the item at swapWith (since it was not + # swapped) is greater than the pivot, so inserting the pivot at swapWith + # will preserve the partition. + swap(array, swapWith, last) + return swapWith + } + + def quicksortR(array, first :int, last :int) { + if (last <= first) { return } + def pivot := partition(array, first, last) + quicksortR(array, first, pivot - 1) + quicksortR(array, pivot + 1, last) + } + + def quicksort(array) { # returned from block + quicksortR(array, 0, array.size() - 1) + } +} diff --git a/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl new file mode 100644 index 0000000000..3c130f1867 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Erlang/sorting-algorithms-quicksort.erl @@ -0,0 +1,3 @@ +qsort([]) -> []; +qsort([X|Xs]) -> + qsort([ Y || Y <- Xs, Y < X]) ++ [X] ++ qsort([ Y || Y <- Xs, Y >= X]). diff --git a/Task/Sorting-algorithms-Quicksort/Factor/sorting-algorithms-quicksort.factor b/Task/Sorting-algorithms-Quicksort/Factor/sorting-algorithms-quicksort.factor new file mode 100644 index 0000000000..cfa610d60d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Factor/sorting-algorithms-quicksort.factor @@ -0,0 +1,5 @@ +: qsort ( seq -- seq ) + dup empty? [ + unclip [ [ < ] curry partition [ qsort ] bi@ ] keep + prefix append + ] unless ; diff --git a/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl b/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl new file mode 100644 index 0000000000..150baa4178 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl @@ -0,0 +1,15 @@ +# (sort keep compare xs) sorts the list xs using the three-way comparison +# function. It keeps duplicates if the keep flag is true, otherwise it +# discards them and returns only the unique entries. + +\sort == + (\keep\compare\xs + xs end \x\xs + + \lo = (filter (\y compare y x T F F) xs) + \hi = (filter (\y compare y x F keep T) xs) + + append (sort keep compare lo); + item x; + sort keep compare hi + ) diff --git a/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth b/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth new file mode 100644 index 0000000000..32a653412c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth @@ -0,0 +1,23 @@ +defer lessthan ( a@ b@ -- ? ) ' < is lessthan + +: mid ( l r -- mid ) over - 2/ -cell and + ; + +: exch ( addr1 addr2 -- ) dup @ >r over @ swap ! r> swap ! ; + +: partition ( l r -- l r r2 l2 ) + 2dup mid @ >r ( r: pivot ) + 2dup begin + swap begin dup @ r@ lessthan while cell+ repeat + swap begin r@ over @ lessthan while cell- repeat + 2dup <= if 2dup exch >r cell+ r> cell- then + 2dup > until r> drop ; + +: qsort ( l r -- ) + partition swap rot + \ 2over 2over - + < if 2swap then + 2dup < if recurse else 2drop then + 2dup < if recurse else 2drop then ; + +: sort ( array len -- ) + dup 2 < if 2drop exit then + 1- cells over + qsort ; diff --git a/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f new file mode 100644 index 0000000000..2540a01faf --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Fortran/sorting-algorithms-quicksort.f @@ -0,0 +1,78 @@ +MODULE Qsort_Module + +IMPLICIT NONE + +CONTAINS + +RECURSIVE SUBROUTINE Qsort(a) + + INTEGER, INTENT(IN OUT) :: a(:) + INTEGER :: split + + IF(size(a) > 1) THEN + CALL Partition(a, split) + CALL Qsort(a(:split-1)) + CALL Qsort(a(split:)) + END IF + +END SUBROUTINE Qsort + +SUBROUTINE Partition(a, marker) + + INTEGER, INTENT(IN OUT) :: a(:) + INTEGER, INTENT(OUT) :: marker + INTEGER :: left, right, pivot, temp + + pivot = (a(1) + a(size(a))) / 2 ! Average of first and last elements to prevent quadratic + left = 0 ! behavior with sorted or reverse sorted data + right = size(a) + 1 + + DO WHILE (left < right) + right = right - 1 + DO WHILE (a(right) > pivot) + right = right-1 + END DO + left = left + 1 + DO WHILE (a(left) < pivot) + left = left + 1 + END DO + IF (left < right) THEN + temp = a(left) + a(left) = a(right) + a(right) = temp + END IF + END DO + + IF (left == right) THEN + marker = left + 1 + ELSE + marker = left + END IF + +END SUBROUTINE Partition + +END MODULE Qsort_Module + +PROGRAM Quicksort + + USE Qsort_Module + + IMPLICIT NONE + INTEGER, PARAMETER :: n = 100 + INTEGER :: array(n) + INTEGER :: i + REAL :: x + CALL RANDOM_SEED + DO i = 1, n + CALL RANDOM_NUMBER(x) + array(i) = INT(x * 10000) + END DO + + WRITE (*, "(A)") "array is :-" + WRITE (*, "(10I5)") array + CALL Qsort(array) + WRITE (*,*) + WRITE (*, "(A)") "sorted array is :-" + WRITE (*,"(10I5)") array + +END PROGRAM Quicksort diff --git a/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort.go b/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort.go new file mode 100644 index 0000000000..cc1d6ff83e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Go/sorting-algorithms-quicksort.go @@ -0,0 +1,93 @@ +package main + +import "fmt" + +func main() { + list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} + fmt.Println("unsorted:", list) + + quicksort(list) + fmt.Println("sorted! ", list) +} + +func quicksort(a []int) { + var pex func(int, int) + pex = func(lower, upper int) { + for { + switch upper - lower { + case -1, 0: // 0 or 1 item in segment. nothing to do here! + return + case 1: // 2 items in segment + // < operator respects strict weak order + if a[upper] < a[lower] { + // a quick exchange and we're done. + a[upper], a[lower] = a[lower], a[upper] + } + return + // Hoare suggests optimized sort-3 or sort-4 algorithms here, + // but does not provide an algorithm. + } + + // Hoare stresses picking a bound in a way to avoid worst case + // behavior, but offers no suggestions other than picking a + // random element. A function call to get a random number is + // relatively expensive, so the method used here is to simply + // choose the middle element. This at least avoids worst case + // behavior for the obvious common case of an already sorted list. + bx := (upper + lower) / 2 + b := a[bx] // b = Hoare's "bound" (aka "pivot") + lp := lower // lp = Hoare's "lower pointer" + up := upper // up = Hoare's "upper pointer" + outer: + for { + // use < operator to respect strict weak order + for lp < upper && !(b < a[lp]) { + lp++ + } + for { + if lp > up { + // "pointers crossed!" + break outer + } + // < operator for strict weak order + if a[up] < b { + break // inner + } + up-- + } + // exchange + a[lp], a[up] = a[up], a[lp] + lp++ + up-- + } + // segment boundary is between up and lp, but lp-up might be + // 1 or 2, so just call segment boundary between lp-1 and lp. + if bx < lp { + // bound was in lower segment + if bx < lp-1 { + // exchange bx with lp-1 + a[bx], a[lp-1] = a[lp-1], b + } + up = lp - 2 + } else { + // bound was in upper segment + if bx > lp { + // exchange + a[bx], a[lp] = a[lp], b + } + up = lp - 1 + lp++ + } + // "postpone the larger of the two segments" = recurse on + // the smaller segment, then iterate on the remaining one. + if up-lower < upper-lp { + pex(lower, up) + lower = lp + } else { + pex(lp, upper) + upper = up + } + } + } + pex(0, len(a)-1) +} diff --git a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs new file mode 100644 index 0000000000..57a0c178fd --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-1.hs @@ -0,0 +1,2 @@ +qsort [] = [] +qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x] diff --git a/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs new file mode 100644 index 0000000000..ff105489ed --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Haskell/sorting-algorithms-quicksort-2.hs @@ -0,0 +1,4 @@ +import Data.List + +qsort [] = [] +qsort (x:xs) = qsort ys ++ x : qsort zs where (ys, zs) = partition (< x) xs diff --git a/Task/Sorting-algorithms-Quicksort/IDL/sorting-algorithms-quicksort.idl b/Task/Sorting-algorithms-Quicksort/IDL/sorting-algorithms-quicksort.idl new file mode 100644 index 0000000000..30699e4cf6 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/IDL/sorting-algorithms-quicksort.idl @@ -0,0 +1,5 @@ +function qs, arr + if (count = n_elements(arr)) lt 2 then return,arr + pivot = total(arr) / count ; use the average for want of a better choice + return,[qs(arr[where(arr le pivot)]),qs(arr[where(arr gt pivot)])] + end diff --git a/Task/Sorting-algorithms-Quicksort/Icon/sorting-algorithms-quicksort.icon b/Task/Sorting-algorithms-Quicksort/Icon/sorting-algorithms-quicksort.icon new file mode 100644 index 0000000000..75675da65b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Icon/sorting-algorithms-quicksort.icon @@ -0,0 +1,46 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(quicksort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure quicksort(X,op,lower,upper) #: return sorted list +local pivot,x + + if /lower := 1 then { # top level call setup + upper := *X + op := sortop(op,X) # select how and what we sort + } + + if upper - lower > 0 then { + every x := quickpartition(X,op,lower,upper) do # find a pivot and sort ... + /pivot | X := x # ... how to return 2 values w/o a structure + X := quicksort(X,op,lower,pivot-1) # ... left + X := quicksort(X,op,pivot,upper) # ... right + } + + return X +end + +procedure quickpartition(X,op,lower,upper) #: quicksort partitioner helper +local pivot +static pivotL +initial pivotL := list(3) + + pivotL[1] := X[lower] # endpoints + pivotL[2] := X[upper] # ... and + pivotL[3] := X[lower+?(upper-lower)] # ... random midpoint + if op(pivotL[2],pivotL[1]) then pivotL[2] :=: pivotL[1] # mini- + if op(pivotL[3],pivotL[2]) then pivotL[3] :=: pivotL[2] # ... sort + pivot := pivotL[2] # median is pivot + + lower -:= 1 + upper +:= 1 + while lower < upper do { # find values on wrong side of pivot ... + while op(pivot,X[upper -:= 1]) # ... rightmost + while op(X[lower +:=1],pivot) # ... leftmost + if lower < upper then # not crossed yet + X[lower] :=: X[upper] # ... swap + } + + suspend lower # 1st return pivot point + suspend X # 2nd return modified X (in case immutable) +end diff --git a/Task/Sorting-algorithms-Quicksort/Io/sorting-algorithms-quicksort.io b/Task/Sorting-algorithms-Quicksort/Io/sorting-algorithms-quicksort.io new file mode 100644 index 0000000000..f39aa7b38d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Io/sorting-algorithms-quicksort.io @@ -0,0 +1,18 @@ +List do( + quickSort := method( + if(size > 1) then( + pivot := at(size / 2 floor) + return select(x, x < pivot) quickSort appendSeq( + select(x, x == pivot) appendSeq(select(x, x > pivot) quickSort) + ) + ) else(return self) + ) + + quickSortInPlace := method( + copy(quickSort) + ) +) + +lst := list(5, -1, -4, 2, 9) +lst quickSort println # ==> list(-4, -1, 2, 5, 9) +lst quickSortInPlace println # ==> list(-4, -1, 2, 5, 9) diff --git a/Task/Sorting-algorithms-Quicksort/J/sorting-algorithms-quicksort.j b/Task/Sorting-algorithms-Quicksort/J/sorting-algorithms-quicksort.j new file mode 100644 index 0000000000..c878b47bc5 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/J/sorting-algorithms-quicksort.j @@ -0,0 +1,12 @@ +sel=: 1 : 'x # [' + +quicksort=: 3 : 0 + if. + 1 >: #y + do. + y + else. + e=. y{~?#y + (quicksort y <sel e),(y =sel e),quicksort y >sel e + end. +) diff --git a/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java b/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java new file mode 100644 index 0000000000..141b6dec14 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java @@ -0,0 +1,28 @@ +public static <E extends Comparable<? super E>> List<E> quickSort(List<E> arr) { + if (arr.size() <= 1) + return arr; + E pivot = arr.getFirst(); //This pivot can change to get faster results + + List<E> less = new LinkedList<E>(); + List<E> pivotList = new LinkedList<E>(); + List<E> more = new LinkedList<E>(); + + // Partition + for (E i: arr) { + if (i.compareTo(pivot) < 0) + less.add(i); + else if (i.compareTo(pivot) > 0) + more.add(i); + else + pivotList.add(i); + } + + // Recursively sort sublists + less = quickSort(less); + more = quickSort(more); + + // Concatenate results + less.addAll(pivotList); + less.addAll(more); + return less; +} diff --git a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js new file mode 100644 index 0000000000..a660d645b8 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js @@ -0,0 +1,30 @@ +function sort(array, less) { + + function swap(i, j) { var t=array[i]; array[i]=array[j]; array[j]=t } + + function quicksort(left, right) { + + if (left < right) { + + var pivot = array[(left + right) >> 1]; + var left_new = left, right_new = right; + + do { + while (less(array[left_new], pivot) + left_new++; + while (less(pivot, array[right_new]) + right_new--; + if (left_new <= right_new) + swap(left_new++, right_new--); + } while (left_new <= right_new); + + quicksort(left, right_new); + quicksort(left_new, right); + + } + } + + quicksort(0, array.length-1); + + return array; +} diff --git a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js new file mode 100644 index 0000000000..6d5a253808 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js @@ -0,0 +1,11 @@ +Array.prototype.quick_sort = function () +{ + if (this.length <= 1) + return this; + + var pivot = this[Math.round(this.length / 2)]; + + return this.filter(function (x) { return x < pivot }).quick_sort().concat( + this.filter(function (x) { return x == pivot })).concat( + this.filter(function (x) { return x > pivot }).quick_sort()); +} diff --git a/Task/Sorting-algorithms-Quicksort/Joy/sorting-algorithms-quicksort.joy b/Task/Sorting-algorithms-Quicksort/Joy/sorting-algorithms-quicksort.joy new file mode 100644 index 0000000000..6541ba3bac --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Joy/sorting-algorithms-quicksort.joy @@ -0,0 +1,6 @@ +DEFINE qsort == + [small] # termination condition: 0 or 1 element + [] # do nothing + [uncons [>] split] # pivot and two lists + [enconcat] # insert the pivot after the recursion + binrec. # recursion on the two lists diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-1.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-1.k new file mode 100644 index 0000000000..f4fb64bb4d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-1.k @@ -0,0 +1 @@ +quicksort:{f:*x@1?#x;:[0=#x;x;,/(_f x@&x<f;x@&x=f;_f x@&x>f)]} diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-2.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-2.k new file mode 100644 index 0000000000..ea47c90b1c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-2.k @@ -0,0 +1 @@ + quicksort 1 3 5 7 9 8 6 4 2 diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k new file mode 100644 index 0000000000..95a4bfeafe --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k @@ -0,0 +1 @@ +1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k new file mode 100644 index 0000000000..a3caf9086b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k @@ -0,0 +1 @@ + _f() diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k new file mode 100644 index 0000000000..0aef1c1c3a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k @@ -0,0 +1 @@ + :[....] diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k new file mode 100644 index 0000000000..bb65ec570f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k @@ -0,0 +1 @@ + f:*x@1?#x diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k new file mode 100644 index 0000000000..3a21fcbaf3 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k @@ -0,0 +1,9 @@ + :[ + 0=#x; / if length of x is zero + x; / then return x + / else + ,/( / join the results of: + _f x@&x<f / sort (recursively) elements less than f (pivot) + x@&x=f / element equal to f + _f x@&x>f) / sort (recursively) elements greater than f + ] diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k new file mode 100644 index 0000000000..38d72b5d2a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k @@ -0,0 +1 @@ + t@<t:1 3 5 7 9 8 6 4 2 diff --git a/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-1.logo b/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-1.logo new file mode 100644 index 0000000000..2fca80cf8e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-1.logo @@ -0,0 +1,16 @@ +; quicksort (lists, functional) + +to small? :list + output or [empty? :list] [empty? butfirst :list] +end +to quicksort :list + if small? :list [output :list] + localmake "pivot first :list + output (sentence + quicksort filter [? < :pivot] butfirst :list + filter [? = :pivot] :list + quicksort filter [? > :pivot] butfirst :list + ) +end + +show quicksort [1 3 5 7 9 8 6 4 2] diff --git a/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-2.logo b/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-2.logo new file mode 100644 index 0000000000..8e0845e2d4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Logo/sorting-algorithms-quicksort-2.logo @@ -0,0 +1,34 @@ +; quicksort (arrays, in-place) + +to incr :name + make :name (thing :name) + 1 +end +to decr :name + make :name (thing :name) - 1 +end +to swap :i :j :a + localmake "t item :i :a + setitem :i :a item :j :a + setitem :j :a :t +end + +to quick :a :low :high + if :high <= :low [stop] + localmake "l :low + localmake "h :high + localmake "pivot item ashift (:l + :h) -1 :a + do.while [ + while [(item :l :a) < :pivot] [incr "l] + while [(item :h :a) > :pivot] [decr "h] + if :l <= :h [swap :l :h :a incr "l decr "h] + ] [:l <= :h] + quick :a :low :h + quick :a :l :high +end +to sort :a + quick :a first :a count :a +end + +make "test {1 3 5 7 9 8 6 4 2} +sort :test +show :test diff --git a/Task/Sorting-algorithms-Quicksort/Logtalk/sorting-algorithms-quicksort.logtalk b/Task/Sorting-algorithms-Quicksort/Logtalk/sorting-algorithms-quicksort.logtalk new file mode 100644 index 0000000000..ea5b2212d9 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Logtalk/sorting-algorithms-quicksort.logtalk @@ -0,0 +1,17 @@ +quicksort(List, Sorted) :- + quicksort(List, [], Sorted). + +quicksort([], Sorted, Sorted). +quicksort([Pivot| Rest], Acc, Sorted) :- + partition(Rest, Pivot, Smaller0, Bigger0), + quicksort(Smaller0, [Pivot| Bigger], Sorted), + quicksort(Bigger0, Acc, Bigger). + +partition([], _, [], []). +partition([X| Xs], Pivot, Smalls, Bigs) :- + ( X @< Pivot -> + Smalls = [X| Rest], + partition(Xs, Pivot, Rest, Bigs) + ; Bigs = [X| Rest], + partition(Xs, Pivot, Smalls, Rest) + ). diff --git a/Task/Sorting-algorithms-Quicksort/Lua/sorting-algorithms-quicksort.lua b/Task/Sorting-algorithms-Quicksort/Lua/sorting-algorithms-quicksort.lua new file mode 100644 index 0000000000..b487c73e09 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Lua/sorting-algorithms-quicksort.lua @@ -0,0 +1,25 @@ +--in-place quicksort +function quicksort(t, start, endi) + start, endi = start or 1, endi or #t + --partition w.r.t. first element + if(endi - start < 2) then return t end + local pivot = start + for i = start + 1, endi do + if t[i] <= t[pivot] then + local temp = t[pivot + 1] + t[pivot + 1] = t[pivot] + if(i == pivot + 1) then + t[pivot] = temp + else + t[pivot] = t[i] + t[i] = temp + end + pivot = pivot + 1 + end + end + t = quicksort(t, start, pivot - 1) + return quicksort(t, pivot + 1, endi) +end + +--example +print(unpack(quicksort{5, 2, 7, 3, 4, 7, 1})) diff --git a/Task/Sorting-algorithms-Quicksort/Lucid/sorting-algorithms-quicksort.lucid b/Task/Sorting-algorithms-Quicksort/Lucid/sorting-algorithms-quicksort.lucid new file mode 100644 index 0000000000..6850b33c06 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Lucid/sorting-algorithms-quicksort.lucid @@ -0,0 +1,10 @@ +qsort(a) = if eof(first a) then a else follow(qsort(b0),qsort(b1)) fi + where + p = first a < a; + b0 = a whenever p; + b1 = a whenever not p; + follow(x,y) = if xdone then y upon xdone else x fi + where + xdone = iseod x fby xdone or iseod x; + end; + end diff --git a/Task/Sorting-algorithms-Quicksort/M4/sorting-algorithms-quicksort.m4 b/Task/Sorting-algorithms-Quicksort/M4/sorting-algorithms-quicksort.m4 new file mode 100644 index 0000000000..46eb0a17f9 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/M4/sorting-algorithms-quicksort.m4 @@ -0,0 +1,28 @@ +dnl return the first element of a list when called in the funny way seen below +define(`arg1', `$1')dnl +dnl +dnl append lists 1 and 2 +define(`append', + `ifelse(`$1',`()', + `$2', + `ifelse(`$2',`()', + `$1', + `substr($1,0,decr(len($1))),substr($2,1)')')')dnl +dnl +dnl separate list 2 based on pivot 1, appending to left 3 and right 4, +dnl until 2 is empty, and then combine the sort of left with pivot with +dnl sort of right +define(`sep', + `ifelse(`$2', `()', + `append(append(quicksort($3),($1)),quicksort($4))', + `ifelse(eval(arg1$2<=$1),1, + `sep($1,(shift$2),append($3,(arg1$2)),$4)', + `sep($1,(shift$2),$3,append($4,(arg1$2)))')')')dnl +dnl +dnl pick first element of list 1 as pivot and separate based on that +define(`quicksort', + `ifelse(`$1', `()', + `()', + `sep(arg1$1,(shift$1),`()',`()')')')dnl +dnl +quicksort((3,1,4,1,5,9)) diff --git a/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-1.m b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-1.m new file mode 100644 index 0000000000..f78b7c6c6f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-1.m @@ -0,0 +1,21 @@ +function sortedArray = quickSort(array) + + if numel(array) <= 1 %If the array has 1 element then it can't be sorted + sortedArray = array; + return + end + + pivot = array(end); + array(end) = []; + + %Create two new arrays which contain the elements that are less than or + %equal to the pivot called "less" and greater than the pivot called + %"greater" + less = array( array <= pivot ); + greater = array( array > pivot ); + + %The sorted array is the concatenation of the sorted "less" array, the + %pivot and the sorted "greater" array in that order + sortedArray = [quickSort(less) pivot quickSort(greater)]; + +end diff --git a/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-2.m b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-2.m new file mode 100644 index 0000000000..0a34085aa7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-2.m @@ -0,0 +1,13 @@ +function sortedArray = quickSort(array) + + if numel(array) <= 1 %If the array has 1 element then it can't be sorted + sortedArray = array; + return + end + + pivot = array(end); + array(end) = []; + + sortedArray = [quickSort( array(array <= pivot) ) pivot quickSort( array(array > pivot) )]; + +end diff --git a/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-3.m b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-3.m new file mode 100644 index 0000000000..96617274c9 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/MATLAB/sorting-algorithms-quicksort-3.m @@ -0,0 +1,5 @@ +quickSort([4,3,7,-2,9,1]) + +ans = + + -2 1 3 4 7 9 diff --git a/Task/Sorting-algorithms-Quicksort/MAXScript/sorting-algorithms-quicksort.maxscript b/Task/Sorting-algorithms-Quicksort/MAXScript/sorting-algorithms-quicksort.maxscript new file mode 100644 index 0000000000..a3f9bf44a8 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/MAXScript/sorting-algorithms-quicksort.maxscript @@ -0,0 +1,28 @@ +fn quickSort arr = +( + less = #() + pivotList = #() + more = #() + if arr.count <= 1 then + ( + arr + ) + else + ( + pivot = arr[arr.count/2] + for i in arr do + ( + case of + ( + (i < pivot): (append less i) + (i == pivot): (append pivotList i) + (i > pivot): (append more i) + ) + ) + less = quickSort less + more = quickSort more + less + pivotList + more + ) +) +a = #(4, 89, -3, 42, 5, 0, 2, 889) +a = quickSort a diff --git a/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math new file mode 100644 index 0000000000..d0e87fe0dd --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math @@ -0,0 +1,5 @@ +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-Quicksort/Modula-2/sorting-algorithms-quicksort-1.mod2 b/Task/Sorting-algorithms-Quicksort/Modula-2/sorting-algorithms-quicksort-1.mod2 new file mode 100644 index 0000000000..10bf1506d8 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-2/sorting-algorithms-quicksort-1.mod2 @@ -0,0 +1,11 @@ +(*#####################*) + DEFINITION MODULE QSORT; +(*#####################*) + +FROM SYSTEM IMPORT ADDRESS; + +TYPE CmpFuncPtrs = PROCEDURE(ADDRESS, ADDRESS):INTEGER; + + PROCEDURE QuickSortPtrs(VAR Array:ARRAY OF ADDRESS; N:CARDINAL; + Compare:CmpFuncPtrs); +END QSORT. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-2/sorting-algorithms-quicksort-2.mod2 b/Task/Sorting-algorithms-Quicksort/Modula-2/sorting-algorithms-quicksort-2.mod2 new file mode 100644 index 0000000000..fb157e0387 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-2/sorting-algorithms-quicksort-2.mod2 @@ -0,0 +1,127 @@ +(*##########################*) + IMPLEMENTATION MODULE QSORT; +(*##########################*) + +FROM SYSTEM IMPORT ADDRESS; + +CONST SmallPartition = 9; + +(* +NOTE + 1.Reference on QuickSort: "Implementing Quicksort Programs", Robert + Sedgewick, Communications of the ACM, Oct 78, v21 #10. +*) + +(*==============================================================*) + PROCEDURE QuickSortPtrs(VAR Array:ARRAY OF ADDRESS; N:CARDINAL; + Compare:CmpFuncPtrs); +(*==============================================================*) + + (*-----------------------------*) + PROCEDURE Swap(VAR A,B:ADDRESS); + (*-----------------------------*) + + VAR temp :ADDRESS; + + BEGIN + + temp := A; A := B; B := temp; + + END Swap; + + (*-------------------------------*) + PROCEDURE TstSwap(VAR A,B:ADDRESS); + (*-------------------------------*) + + VAR temp :ADDRESS; + + BEGIN + + IF Compare(A,B) > 0 THEN + temp := A; A := B; B := temp; + END; + + END TstSwap; + + (*--------------*) + PROCEDURE Isort; + (*--------------*) + (* + Insertion sort. + *) + + VAR i,j :CARDINAL; + temp :ADDRESS; + + BEGIN + + IF N < 2 THEN RETURN END; + + FOR i := N-2 TO 0 BY -1 DO + IF Compare(Array[i],Array[i+1]) > 0 THEN + temp := Array[i]; + j := i+1; + REPEAT + Array[j-1] := Array[j]; + INC(j); + UNTIL (j = N) OR (Compare(Array[j],temp) >= 0); + Array[j-1] := temp; + END; + END; + + END Isort; + + (*----------------------------------*) + PROCEDURE Quick(left,right:CARDINAL); + (*----------------------------------*) + + VAR + i,j, + second :CARDINAL; + Partition :ADDRESS; + + BEGIN + + IF right > left THEN + i := left; j := right; + + Swap(Array[left],Array[(left+right) DIV 2]); + + second := left+1; (* insure 2nd element is in *) + TstSwap(Array[second], Array[right]); (* the lower part, last elem *) + TstSwap(Array[left], Array[right]); (* in the upper part *) + TstSwap(Array[second], Array[left]); (* THUS, only one test is *) + (* needed in repeat loops *) + Partition := Array[left]; + + LOOP + REPEAT INC(i) UNTIL Compare(Array[i],Partition) >= 0; + REPEAT DEC(j) UNTIL Compare(Array[j],Partition) <= 0; + IF j < i THEN + EXIT + END; + Swap(Array[i],Array[j]); + END; (*loop*) + Swap(Array[left],Array[j]); + + IF (j > 0) AND (j-1-left >= SmallPartition) THEN + Quick(left,j-1); + END; + IF right-i >= SmallPartition THEN + Quick(i,right); + END; + END; + + END Quick; + + BEGIN (* QuickSortPtrs --------------------------------------------------*) + +IF N > SmallPartition THEN (* won't work for 2 elements *) + Quick(0,N-1); +END; + +Isort; + +END QuickSortPtrs; + +END QSORT. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-1.mod3 b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-1.mod3 new file mode 100644 index 0000000000..c4ccff4b5e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-1.mod3 @@ -0,0 +1,5 @@ +GENERIC INTERFACE ArraySort(Elem); + +PROCEDURE Sort(VAR a: ARRAY OF Elem.T; cmp := Elem.Compare); + +END ArraySort. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-2.mod3 b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-2.mod3 new file mode 100644 index 0000000000..0ec8653067 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-2.mod3 @@ -0,0 +1,87 @@ +GENERIC MODULE ArraySort (Elem); + +PROCEDURE Sort (VAR a: ARRAY OF Elem.T; cmp := Elem.Compare) = + BEGIN + QuickSort (a, 0, NUMBER (a), cmp); + InsertionSort (a, 0, NUMBER (a), cmp); + END Sort; + +PROCEDURE QuickSort (VAR a: ARRAY OF Elem.T; lo, hi: INTEGER; + cmp := Elem.Compare) = + CONST CutOff = 9; + VAR i, j: INTEGER; key, tmp: Elem.T; + BEGIN + WHILE (hi - lo > CutOff) DO (* sort a[lo..hi) *) + + (* use median-of-3 to select a key *) + i := (hi + lo) DIV 2; + IF cmp (a[lo], a[i]) < 0 THEN + IF cmp (a[i], a[hi-1]) < 0 THEN + key := a[i]; + ELSIF cmp (a[lo], a[hi-1]) < 0 THEN + key := a[hi-1]; a[hi-1] := a[i]; a[i] := key; + ELSE + key := a[lo]; a[lo] := a[hi-1]; a[hi-1] := a[i]; a[i] := key; + END; + ELSE (* a[lo] >= a[i] *) + IF cmp (a[hi-1], a[i]) < 0 THEN + key := a[i]; tmp := a[hi-1]; a[hi-1] := a[lo]; a[lo] := tmp; + ELSIF cmp (a[lo], a[hi-1]) < 0 THEN + key := a[lo]; a[lo] := a[i]; a[i] := key; + ELSE + key := a[hi-1]; a[hi-1] := a[lo]; a[lo] := a[i]; a[i] := key; + END; + END; + + (* partition the array *) + i := lo+1; j := hi-2; + + (* find the first hole *) + WHILE cmp (a[j], key) > 0 DO DEC (j) END; + tmp := a[j]; + DEC (j); + + LOOP + IF (i > j) THEN EXIT END; + + WHILE i < hi AND cmp (a[i], key) < 0 DO INC (i) END; + IF (i > j) THEN EXIT END; + a[j+1] := a[i]; + INC (i); + + WHILE j > lo AND cmp (a[j], key) > 0 DO DEC (j) END; + IF (i > j) THEN IF (j = i-1) THEN DEC (j) END; EXIT END; + a[i-1] := a[j]; + DEC (j); + END; + + (* fill in the last hole *) + a[j+1] := tmp; + i := j+2; + + (* then, recursively sort the smaller subfile *) + IF (i - lo < hi - i) + THEN QuickSort (a, lo, i-1, cmp); lo := i; + ELSE QuickSort (a, i, hi, cmp); hi := i-1; + END; + + END; (* WHILE (hi-lo > CutOff) *) + END QuickSort; + +PROCEDURE InsertionSort (VAR a: ARRAY OF Elem.T; lo, hi: INTEGER; + cmp := Elem.Compare) = + VAR j: INTEGER; key: Elem.T; + BEGIN + FOR i := lo+1 TO hi-1 DO + key := a[i]; + j := i-1; + WHILE (j >= lo) AND cmp (key, a[j]) < 0 DO + a[j+1] := a[j]; + DEC (j); + END; + a[j+1] := key; + END; + END InsertionSort; + +BEGIN +END ArraySort. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-3.mod3 b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-3.mod3 new file mode 100644 index 0000000000..f0fb9ba840 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-3.mod3 @@ -0,0 +1 @@ +INTERFACE TextSort = ArraySort(Text) END TextSort. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-4.mod3 b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-4.mod3 new file mode 100644 index 0000000000..f91691abfe --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-4.mod3 @@ -0,0 +1 @@ +MODULE TextSort = ArraySort(Text) END TextSort. diff --git a/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-5.mod3 b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-5.mod3 new file mode 100644 index 0000000000..e35956de7e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Modula-3/sorting-algorithms-quicksort-5.mod3 @@ -0,0 +1,13 @@ +MODULE Main; + +IMPORT IO, TextSort; + +VAR arr := ARRAY [1..10] OF TEXT {"Foo", "bar", "!ooF", "Modula-3", "hickup", + "baz", "quuz", "Zeepf", "woo", "Rosetta Code"}; + +BEGIN + TextSort.Sort(arr); + FOR i := FIRST(arr) TO LAST(arr) DO + IO.Put(arr[i] & "\n"); + END; +END Main. diff --git a/Task/Sorting-algorithms-Quicksort/Nemerle/sorting-algorithms-quicksort.nemerle b/Task/Sorting-algorithms-Quicksort/Nemerle/sorting-algorithms-quicksort.nemerle new file mode 100644 index 0000000000..252c55e6a2 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Nemerle/sorting-algorithms-quicksort.nemerle @@ -0,0 +1,23 @@ +using System; +using System.Console; +using Nemerle.Collections.NList; + +module Quicksort +{ + Qsort[T] (x : list[T]) : list[T] + where T : IComparable + { + |[] => [] + |x::xs => Qsort($[y|y in xs, (y.CompareTo(x) < 0)]) + [x] + Qsort($[y|y in xs, (y.CompareTo(x) > 0)]) + } + + Main() : void + { + def empty = []; + def single = [2]; + def several = [2, 6, 1, 7, 3, 9, 4]; + WriteLine(Qsort(empty)); + WriteLine(Qsort(single)); + WriteLine(Qsort(several)); + } +} diff --git a/Task/Sorting-algorithms-Quicksort/NetRexx/sorting-algorithms-quicksort.netrexx b/Task/Sorting-algorithms-Quicksort/NetRexx/sorting-algorithms-quicksort.netrexx new file mode 100644 index 0000000000..eed0078d21 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/NetRexx/sorting-algorithms-quicksort.netrexx @@ -0,0 +1,100 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] +lists = [ - + placesList - + , quickSortSimple(String[] Arrays.copyOf(placesList, placesList.length)) - + , quickSortInplace(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method quickSortSimple(array = String[]) public constant binary returns String[] + + rl = String[array.length] + al = List quickSortSimple(Arrays.asList(array)) + al.toArray(rl) + + return rl + +method quickSortSimple(array = List) public constant binary returns ArrayList + + if array.size > 1 then do + less = ArrayList() + equal = ArrayList() + greater = ArrayList() + + pivot = array.get(Random().nextInt(array.size - 1)) + loop x_ = 0 to array.size - 1 + if (Comparable array.get(x_)).compareTo(Comparable pivot) < 0 then less.add(array.get(x_)) + if (Comparable array.get(x_)).compareTo(Comparable pivot) = 0 then equal.add(array.get(x_)) + if (Comparable array.get(x_)).compareTo(Comparable pivot) > 0 then greater.add(array.get(x_)) + end x_ + less = quickSortSimple(less) + greater = quickSortSimple(greater) + out = ArrayList(array.size) + out.addAll(less) + out.addAll(equal) + out.addAll(greater) + + array = out + end + + return ArrayList array + +method quickSortInplace(array = String[]) public constant binary returns String[] + + rl = String[array.length] + al = List quickSortInplace(Arrays.asList(array)) + al.toArray(rl) + + return rl + +method quickSortInplace(array = List, ixL = int 0, ixR = int array.size - 1) public constant binary returns ArrayList + + if ixL < ixR then do + ixP = int ixL + (ixR - ixL) % 2 + ixP = quickSortInplacePartition(array, ixL, ixR, ixP) + quickSortInplace(array, ixL, ixP - 1) + quickSortInplace(array, ixP + 1, ixR) + end + + array = ArrayList(array) + return ArrayList array + +method quickSortInplacePartition(array = List, ixL = int, ixR = int, ixP = int) public constant binary returns int + + pivotValue = array.get(ixP) + rValue = array.get(ixR) + array.set(ixP, rValue) + array.set(ixR, pivotValue) + ixStore = ixL + loop i_ = ixL to ixR - 1 + iValue = array.get(i_) + if (Comparable iValue).compareTo(Comparable pivotValue) < 0 then do + storeValue = array.get(ixStore) + array.set(i_, storeValue) + array.set(ixStore, iValue) + ixStore = ixStore + 1 + end + end i_ + storeValue = array.get(ixStore) + rValue = array.get(ixR) + array.set(ixStore, rValue) + array.set(ixR, storeValue) + + return ixStore diff --git a/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-1.nial b/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-1.nial new file mode 100644 index 0000000000..7eda9cfbfd --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-1.nial @@ -0,0 +1,8 @@ +quicksort is fork [ >= [1 first,tally], + pass, + link [ + quicksort sublist [ < [pass, first], pass ], + sublist [ match [pass,first],pass ], + quicksort sublist [ > [pass,first], pass ] + ] +] diff --git a/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-2.nial b/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-2.nial new file mode 100644 index 0000000000..39c89d5172 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Nial/sorting-algorithms-quicksort-2.nial @@ -0,0 +1,2 @@ +|quicksort [5, 8, 7, 4, 3] +=3 4 5 7 8 diff --git a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod new file mode 100644 index 0000000000..f06b9f131b --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-1.nimrod @@ -0,0 +1,17 @@ +proc QuickSort(list: seq[int]): seq[int] = + if len(list) == 0: + return @[] + + var pivot = list[0] + + var left: seq[int] = @[] + var right: seq[int] = @[] + for i in low(list)+1..high(list): + if list[i] <= pivot: + left.add(list[i]) + elif list[i] > pivot: + right.add(list[i]) + + result = QuickSort(left) + result.add(pivot) + result.add(QuickSort(right)) diff --git a/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod new file mode 100644 index 0000000000..76e6fbe37d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Nimrod/sorting-algorithms-quicksort-2.nimrod @@ -0,0 +1,3 @@ +var sorted: seq[int] = QuickSort(@[5,2,1,6,2,3,1,2,123,21,54,6,1]) +for i in items(sorted): + echo(i) diff --git a/Task/Sorting-algorithms-Quicksort/OCaml/sorting-algorithms-quicksort.ocaml b/Task/Sorting-algorithms-Quicksort/OCaml/sorting-algorithms-quicksort.ocaml new file mode 100644 index 0000000000..afad078442 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/OCaml/sorting-algorithms-quicksort.ocaml @@ -0,0 +1,8 @@ +let rec quicksort gt = function + | [] -> [] + | x::xs -> + let ys, zs = List.partition (gt x) xs in + (quicksort gt ys) @ (x :: (quicksort gt zs)) + +let _ = + quicksort (>) [4; 65; 2; -31; 0; 99; 83; 782; 1] diff --git a/Task/Sorting-algorithms-Quicksort/Objeck/sorting-algorithms-quicksort.objeck b/Task/Sorting-algorithms-Quicksort/Objeck/sorting-algorithms-quicksort.objeck new file mode 100644 index 0000000000..e9901a2b36 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Objeck/sorting-algorithms-quicksort.objeck @@ -0,0 +1,47 @@ +class QuickSort { + function : Main(args : String[]) ~ Nil { + array := [1, 3, 5, 7, 9, 8, 6, 4, 2]; + Sort(array); + each(i : array) { + array[i]->PrintLine(); + }; + } + + function : Sort(array : Int[]) ~ Nil { + size := array->Size(); + if(size <= 1) { + return; + }; + Sort(array, 0, size - 1); + } + + function : native : Sort(array : Int[], low : Int, high : Int) ~ Nil { + i := low; j := high; + pivot := array[low + (high-low)/2]; + + while(i <= j) { + while(array[i] < pivot) { + i+=1; + }; + + while(array[j] > pivot) { + j-=1; + }; + + if (i <= j) { + temp := array[i]; + array[i] := array[j]; + array[j] := temp; + i+=1; j-=1; + }; + }; + + if(low < j) { + Sort(array, low, j); + }; + + if(i < high) { + Sort(array, i, high); + }; + } +} diff --git a/Task/Sorting-algorithms-Quicksort/Octave/sorting-algorithms-quicksort.octave b/Task/Sorting-algorithms-Quicksort/Octave/sorting-algorithms-quicksort.octave new file mode 100644 index 0000000000..de587a5577 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Octave/sorting-algorithms-quicksort.octave @@ -0,0 +1,12 @@ +function f=quicksort(v) % v must be a column vector + f = v; n=length(v); + if(n > 1) + vl = min(f); vh = max(f); % min, max + p = (vl+vh)*0.5; % pivot + ia = find(f < p); ib = find(f == p); ic=find(f > p); + f = [quicksort(f(ia)); f(ib); quicksort(f(ic))]; + end +endfunction + +N=30; v=rand(N,1); tic,u=quicksort(v); toc +u diff --git a/Task/Sorting-algorithms-Quicksort/Oz/sorting-algorithms-quicksort.oz b/Task/Sorting-algorithms-Quicksort/Oz/sorting-algorithms-quicksort.oz new file mode 100644 index 0000000000..c95ad17946 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Oz/sorting-algorithms-quicksort.oz @@ -0,0 +1,13 @@ +declare + fun {QuickSort Xs} + case Xs of nil then nil + [] Pivot|Xr then + fun {IsSmaller X} X < Pivot end + Smaller Larger + in + {List.partition Xr IsSmaller ?Smaller ?Larger} + {Append {QuickSort Smaller} Pivot|{QuickSort Larger}} + end + end +in + {Show {QuickSort [3 1 4 1 5 9 2 6 5]}} diff --git a/Task/Sorting-algorithms-Quicksort/PARI-GP/sorting-algorithms-quicksort.pari b/Task/Sorting-algorithms-Quicksort/PARI-GP/sorting-algorithms-quicksort.pari new file mode 100644 index 0000000000..6cbfe45039 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PARI-GP/sorting-algorithms-quicksort.pari @@ -0,0 +1,15 @@ +quickSort(v)={ + if(#v<2, return(v)); + my(less=List(),more=List(),same=List(),pivot); + pivot=median([v[random(#v)+1],v[random(#v)+1],v[random(#v)+1]]); \\ Middle-of-three + for(i=1,#v, + if(v[i]<pivot, + listput(less, v[i]), + if(v[i]==pivot, listput(same, v[i]), listput(more, v[i])) + ) + ); + concat(quickSort(Vec(less)), concat(Vec(same), quickSort(Vec(more)))) +}; +median(v)={ + vecsort(v)[#v>>1] +}; diff --git a/Task/Sorting-algorithms-Quicksort/PHP/sorting-algorithms-quicksort.php b/Task/Sorting-algorithms-Quicksort/PHP/sorting-algorithms-quicksort.php new file mode 100644 index 0000000000..901c54481e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PHP/sorting-algorithms-quicksort.php @@ -0,0 +1,20 @@ +function quicksort($arr){ + $loe = $gt = array(); + if(count($arr) < 2){ + return $arr; + } + $pivot_key = key($arr); + $pivot = array_shift($arr); + foreach($arr as $val){ + if($val <= $pivot){ + $loe[] = $val; + }elseif ($val > $pivot){ + $gt[] = $val; + } + } + return array_merge(quicksort($loe),array($pivot_key=>$pivot),quicksort($gt)); +} + +$arr = array(1, 3, 5, 7, 9, 8, 6, 4, 2); +$arr = quicksort($arr); +echo implode(',',$arr); diff --git a/Task/Sorting-algorithms-Quicksort/PL-I/sorting-algorithms-quicksort.pli b/Task/Sorting-algorithms-Quicksort/PL-I/sorting-algorithms-quicksort.pli new file mode 100644 index 0000000000..624cce083c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PL-I/sorting-algorithms-quicksort.pli @@ -0,0 +1,49 @@ +DCL (T(20)) FIXED BIN(31); /* scratch space of length N */ + +QUICKSORT: PROCEDURE (A,AMIN,AMAX,N) RECURSIVE ; + DECLARE (A(*)) FIXED BIN(31); + DECLARE (N,AMIN,AMAX) FIXED BIN(31) NONASGN; + DECLARE (I,J,IA,IB,IC,PIV) FIXED BIN(31); + DECLARE (P,Q) POINTER; + DECLARE (AP(1)) FIXED BIN(31) BASED(P); + + IF(N <= 1)THEN RETURN; + IA=0; IB=0; IC=N+1; + PIV=(AMIN+AMAX)/2; + DO I=1 TO N; + IF(A(I) < PIV)THEN DO; + IA+=1; A(IA)=A(I); + END; ELSE IF(A(I) > PIV) THEN DO; + IC-=1; T(IC)=A(I); + END; ELSE DO; + IB+=1; T(IB)=A(I); + END; + END; + DO I=1 TO IB; A(I+IA)=T(I); END; + DO I=IC TO N; A(I)=T(N+IC-I); END; + P=ADDR(A(IC)); + IC=N+1-IC; + IF(IA > 1) THEN CALL QUICKSORT(A, AMIN, PIV-1,IA); + IF(IC > 1) THEN CALL QUICKSORT(AP,PIV+1,AMAX, IC); + RETURN; +END QUICKSORT; + MINMAX: PROC(A,AMIN,AMAX,N); + DCL (AMIN,AMAX) FIXED BIN(31), + (N,A(*)) FIXED BIN(31) NONASGN ; + DCL (I,X,Y) FIXED BIN(31); + + AMIN=A(N); AMAX=AMIN; + DO I=1 TO N-1; + X=A(I); Y=A(I+1); + IF (X < Y)THEN DO; + IF (X < AMIN) THEN AMIN=X; + IF (Y > AMAX) THEN AMAX=Y; + END; ELSE DO; + IF (X > AMAX) THEN AMAX=X; + IF (Y < AMIN) THEN AMIN=Y; + END; + END; + RETURN; +END MINMAX; +CALL MINMAX(A,AMIN,AMAX,N); +CALL QUICKSORT(A,AMIN,AMAX,N); diff --git a/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal new file mode 100644 index 0000000000..1bed5e0b66 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Pascal/sorting-algorithms-quicksort.pascal @@ -0,0 +1,23 @@ +{ X is array of LongInt } +Procedure QuickSort ( Left, Right : LongInt ); +Var + i, j : LongInt; + tmp, pivot : LongInt; { tmp & pivot are the same type as the elements of array } +Begin + i:=Left; + j:=Right; + pivot := X[(Left + Right) shr 1]; // pivot := X[(Left + Rigth) div 2] + Repeat + While pivot > X[i] Do i:=i+1; + While pivot < X[j] Do j:=j-1; + If i<j Then Begin + tmp:=X[i]; + X[i]:=X[j]; + X[j]:=tmp; + j:=j-1; + i:=i+1; + End; + Until i>j; + If Left<j Then QuickSort(Left,j); + If i<Right Then QuickSort(i,Right); +End; diff --git a/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 b/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 new file mode 100644 index 0000000000..11d9270739 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 @@ -0,0 +1,12 @@ +# Empty list sorts to the empty list + multi quicksort([]) { () } + + # Otherwise, extract first item as pivot... + multi quicksort([$pivot, *@rest]) { + # Partition. + my @before := @rest.grep(* before $pivot); + my @after := @rest.grep(* !before $pivot); + + # Sort the partitions. + (quicksort(@before), $pivot, quicksort(@after)) + } diff --git a/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl b/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl new file mode 100644 index 0000000000..048d3e22b1 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl @@ -0,0 +1,10 @@ +sub quick_sort { + my @a = @_; + return @a if @a < 2; + my $p = pop @a; + quick_sort(grep $_ < $p, @a), $p, quick_sort(grep $_ >= $p, @a); +} + +my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); +@a = quick_sort @a; +print "@a\n"; diff --git a/Task/Sorting-algorithms-Quicksort/PicoLisp/sorting-algorithms-quicksort.l b/Task/Sorting-algorithms-Quicksort/PicoLisp/sorting-algorithms-quicksort.l new file mode 100644 index 0000000000..14c5ae7b02 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PicoLisp/sorting-algorithms-quicksort.l @@ -0,0 +1,7 @@ +(de quicksort (L) + (if (cdr L) + (let Pivot (car L) + (append (quicksort (filter '((A) (< A Pivot)) (cdr L))) + (filter '((A) (= A Pivot)) L ) + (quicksort (filter '((A) (> A Pivot)) (cdr L)))) ) + L) ) diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort.psh b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort.psh new file mode 100644 index 0000000000..44bcd433dc --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort.psh @@ -0,0 +1,52 @@ +Function SortThree( [Array] $data ) +{ + if( $data[ 0 ] -gt $data[ 1 ] ) + { + if( $data[ 0 ] -lt $data[ 2 ] ) + { + $data = $data[ 1, 0, 2 ] + } elseif ( $data[ 1 ] -lt $data[ 2 ] ){ + $data = $data[ 1, 2, 0 ] + } else { + $data = $data[ 2, 1, 0 ] + } + } else { + if( $data[ 0 ] -gt $data[ 2 ] ) + { + $data = $data[ 2, 0, 1 ] + } elseif( $data[ 1 ] -gt $data[ 2 ] ) { + $data = $data[ 0, 2, 1 ] + } + } + $data +} + +Function QuickSort( [Array] $data, $rand = ( New-Object Random ) ) +{ + $datal = $data.length + if( $datal -gt 3 ) + { + [void] $datal-- + $median = ( SortThree $data[ 0, ( $rand.Next( 1, $datal - 1 ) ), -1 ] )[ 1 ] + $lt = @() + $eq = @() + $gt = @() + $data | ForEach-Object { if( $_ -lt $median ) { $lt += $_ } elseif( $_ -eq $median ) { $eq += $_ } else { $gt += $_ } } + $lt = ( QuickSort $lt $rand ) + $gt = ( QuickSort $gt $rand ) + $data = @($lt) + $eq + $gt + } elseif( $datal -eq 3 ) { + $data = SortThree( $data ) + } elseif( $datal -eq 2 ) { + if( $data[ 0 ] -gt $data[ 1 ] ) + { + $data = $data[ 1, 0 ] + } + } + $data +} + +QuickSort 5,3,1,2,4 +QuickSort 'e','c','a','b','d' +QuickSort 0.5,0.3,0.1,0.2,0.4 +$l = 100; QuickSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Quicksort/Prolog/sorting-algorithms-quicksort.pro b/Task/Sorting-algorithms-Quicksort/Prolog/sorting-algorithms-quicksort.pro new file mode 100644 index 0000000000..85a54cd44f --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Prolog/sorting-algorithms-quicksort.pro @@ -0,0 +1,8 @@ +qsort( [], [] ). +qsort( [H|U], S ) :- splitBy(H, U, L, R), qsort(L, SL), qsort(R, SR), append(SL, [H|SR], S). + +% splitBy( H, U, LS, RS ) +% True if LS = { L in U | L <= H }; RS = { R in U | R > H } +splitBy( _, [], [], []). +splitBy( H, [U|T], [U|LS], RS ) :- U =< H, splitBy(H, T, LS, RS). +splitBy( H, [U|T], LS, [U|RS] ) :- U > H, splitBy(H, T, LS, RS). diff --git a/Task/Sorting-algorithms-Quicksort/PureBasic/sorting-algorithms-quicksort.purebasic b/Task/Sorting-algorithms-Quicksort/PureBasic/sorting-algorithms-quicksort.purebasic new file mode 100644 index 0000000000..bdc0394f08 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PureBasic/sorting-algorithms-quicksort.purebasic @@ -0,0 +1,37 @@ +Procedure qSort(Array a(1), firstIndex, lastIndex) + Protected low, high, pivotValue + + low = firstIndex + high = lastIndex + pivotValue = a((firstIndex + lastIndex) / 2) + + Repeat + + While a(low) < pivotValue + low + 1 + Wend + + While a(high) > pivotValue + high - 1 + Wend + + If low <= high + Swap a(low), a(high) + low + 1 + high - 1 + EndIf + + Until low > high + + If firstIndex < high + qSort(a(), firstIndex, high) + EndIf + + If low < lastIndex + qSort(a(), low, lastIndex) + EndIf +EndProcedure + +Procedure quickSort(Array a(1)) + qSort(a(),0,ArraySize(a())) +EndProcedure diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-1.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-1.py new file mode 100644 index 0000000000..48cfd980de --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-1.py @@ -0,0 +1,21 @@ +def quickSort(arr): + less = [] + pivotList = [] + more = [] + if len(arr) <= 1: + return arr + else: + pivot = arr[0] + for i in arr: + if i < pivot: + less.append(i) + elif i > pivot: + more.append(i) + else: + pivotList.append(i) + less = quickSort(less) + more = quickSort(more) + return less + pivotList + more + +a = [4, 65, 2, -31, 0, 99, 83, 782, 1] +a = quickSort(a) diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-2.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-2.py new file mode 100644 index 0000000000..9be6a27206 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-2.py @@ -0,0 +1,4 @@ +def qsort(L): + return (qsort([y for y in L[1:] if y < L[0]]) + + L[:1] + + qsort([y for y in L[1:] if y >= L[0]])) if len(L) > 1 else L diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-3.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-3.py new file mode 100644 index 0000000000..8d56022b2e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-3.py @@ -0,0 +1,8 @@ +def qsort(list): + if not list: + return [] + else: + pivot = list[0] + less = [x for x in list if x < pivot] + more = [x for x in list[1:] if x >= pivot] + return qsort(less) + [pivot] + qsort(more) diff --git a/Task/Sorting-algorithms-Quicksort/Qi/sorting-algorithms-quicksort.qi b/Task/Sorting-algorithms-Quicksort/Qi/sorting-algorithms-quicksort.qi new file mode 100644 index 0000000000..c80b43c949 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Qi/sorting-algorithms-quicksort.qi @@ -0,0 +1,12 @@ +(define keep + _ [] -> [] + Pred [A|Rest] -> [A | (keep Pred Rest)] where (Pred A) + Pred [_|Rest] -> (keep Pred Rest)) + +(define quicksort + [] -> [] + [A|R] -> (append (quicksort (keep (>= A) R)) + [A] + (quicksort (keep (< A) R)))) + +(quicksort [6 8 5 9 3 2 2 1 4 7]) diff --git a/Task/Sorting-algorithms-Quicksort/R/sorting-algorithms-quicksort.r b/Task/Sorting-algorithms-Quicksort/R/sorting-algorithms-quicksort.r new file mode 100644 index 0000000000..b6ac16a412 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/R/sorting-algorithms-quicksort.r @@ -0,0 +1,12 @@ +qsort <- function(v) { + if ( length(v) > 1 ) + { + pivot <- (min(v) + max(v))/2.0 # Could also use pivot <- median(v) + c(qsort(v[v < pivot]), v[v == pivot], qsort(v[v > pivot])) + } else v +} + +N <- 100 +vs <- runif(N) +system.time(u <- qsort(vs)) +print(u) diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx new file mode 100644 index 0000000000..2939321bd4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx @@ -0,0 +1,119 @@ +/*REXX program sorts a stemmed array using the quicksort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show before array elements.*/ +call quickSort highItem /*here come da judge, here come..*/ +call show@ ' after sort' /*show after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────QUICKSORT subroutine────────────────*/ +quickSort: procedure expose @. /*access the caller's local var. */ +a.1=1; b.1=arg(1); $=1 + + do while $\==0; l=a.$; t=b.$; $=$-1 + if t<2 then iterate + h=l+t-1 + ?=l+t%2 + if @.h<@.l then if @.?<@.h then do; p=@.h; @.h=@.l; end + else if @.?>@.l then p=@.l + else do; p=@.?; @.?=@.l; end + else if @.?<@.l then p=@.l + else if @.?>@.h then do; p=@.h; @.h=@.l; end + else do; p=@.?; @.?=@.l; end + j=l+1 + k=h + do forever + do j=j while j<=k & @.j<=p; end /*a tinie-tiny loop*/ + do k=k by -1 while j <k & @.k>=p; end /*another tiny loop*/ + if j>=k then leave + _=@.j; @.j=@.k; @.k=_ + end /*forever*/ + + k=j-1; @.l=@.k; @.k=p + $=$+1 + if j<=? then do; a.$=j; b.$=h-j+1; $=$+1; a.$=l; b.$=k-l; end + else do; a.$=l; b.$=k-l; $=$+1; a.$=j; b.$=h-j+1; end + end /*while $\==0*/ + +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.=''; maxL=0 /*assign default value. */ +@.1 =" Rivers that form part of a state's (USA) border " +@.2 ='=' +@.3 ="Chattahoochee River: Alabama, Georgia" +@.4 ="Colorado River: Arizona, Nevada, California, Baja California (Mexico)" +@.5 ="St. Francis River: Arkansas, Missouri" +@.6 ="Poteau River: Arkansas, Oklahoma" +@.7 ="Byram River: Connecticut, New York" +@.8 ="Pawcatuck River: Connecticut, Rhode Island" +@.9 ="Perdido River: Florida, Alabama" +@.10="St. Marys River: Florida, Georgia" +@.11="Chattooga River: Georgia, South Carolina" +@.12="Tugaloo River: Georgia, South Carolina" +@.13="Snake River: Idaho, Washington, Oregon" +@.14="Wabash River: Illinois, Indiana" +@.15="Ohio River: Illinois, Indiana, Ohio, Kentucky, West Virginia" +@.16="Des Moines River: Iowa, Missouri" +@.17="Tennessee River: Kentucky, Tennessee, Mississippi, Alabama" +@.18="Big Sandy River: Kentucky, West Virginia" +@.19="Tug Fork River: Kentucky, West Virginia, Virginia" +@.20="Monument Creek: Maine, New Brunswick (Canda)" +@.21="St. Croix River: Maine, New Brunswick (Canda)" +@.22="Piscataqua River: Maine, New Hampshire" +@.23="St. Francis River: Maine, Quebec (Canada)" +@.24="St. John River: Maine, Quebec (Canada)" +@.25="Pocomoke River: Maryland, Virginia" +@.26="Potomac River: Maryland, Virginia, city of Washington (District of Columbia), West Virginia" +@.27="Montreal River: Michigan (upper peninsula ), Wisconsin" +@.28="Detroit River: Michigan, Ontario (Canada)" +@.29="St. Clair River: Michigan, Ontario (Canada)" +@.30="St. Marys River: Michigan, Ontario (Canada)" +@.31="Brule River: Michigan, Wisconsin" +@.32="Menominee River: Michigan, Wisconsin" +@.33="Pigeon River: Minnesota, Ontario (Canada)" +@.34="Rainy River: Minnesota, Ontario (Canada)" +@.35="St. Croix River: Minnesota, Wisconsin" +@.36="St. Louis River: Minnesota, Wisconsin" +@.37="Mississippi River: Minnesota, Wisconsin, Iowa, Illinois, Missouri, Kentucky, Tennesse, Arkansas, Mississippi, Louisiana" +@.38="Pearl River: Mississippi, Louisiana" +@.39="Halls Stream: New Hampshire, Canada" +@.40="Salmon Falls River: New Hampshire, Maine" +@.41="Connecticut River: New Hampshire, Vermont" +@.42="Hudson River (lower part only): New Jersey, New York" +@.43="Arthur Kill: New Jersey, New York (tidal strait)" +@.44="Kill Van Kull: New Jersey, New York (tidal strait)" +@.45="Rio Grande: New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila De Zaragoza (Mexico), Chihuahua (Mexico)" +@.46="Niagara River: New York, Ontario (Canada)" +@.47="St. Lawrence River: New York, Ontario (Canada)" +@.48="Delaware River: New York, Pennsylvania, New Jersey, Delaware" +@.49="Catawba River: North Carolina, South Carolina" +@.50="Red River of the North: North Dakota, Minnesota" +@.51="Great Miami River (mouth only): Ohio, Indiana" +@.52="Arkansas River: Oklahoma, Arkansas" +@.53="Palmer River: Rhode Island, Massachusetts" +@.54="Runnins River: Rhode Island, Massachusetts" +@.55="Savannah River: South Carolina, Georgia" +@.56="Big Sioux River: South Dakota, Iowa" +@.57="Bois de Sioux River: South Dakota, Minnesota, North Dakota" +@.58="Missouri River: South Dakota, Nebraska, Iowa, Missouri, Kansas" +@.59="Sabine River: Texas, Louisiana" +@.60="Red River (Mississippi watershed): Texas, Oklahoma, Arkansas" +@.61="Poultney River: Vermont, New York" +@.62="Blackwater River: Virginia, North Carolina" +@.63="Columbia River: Washington, Oregon" + + do highItem=1 while @.highItem\=='' /*find how many entries, and also*/ + maxL=max(maxL,length(@.highItem)) /* find the maximum width entry.*/ + end + +highItem=highItem-1 /*adjust highItem slightly. */ +@.1=centre(@.1,maxL,'-') /*adjust the header information. */ +@.2=copies(@.2,maxL) /*adjust the header separator. */ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: widthH=length(highItem) /*maximum width of any line. */ + + do j=1 for highItem /*show each array item.*/ + say 'element' right(j,widthH) arg(1)':' @.j + end + +say copies('█',maxL+widthH+22) /*show a separator line. */ +return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx new file mode 100644 index 0000000000..fad5dd7a99 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx @@ -0,0 +1,86 @@ + a = '4 65 2 -31 0 99 83 782 1' + do i = 1 to words(a) + queue word(a, i) + end + call quickSort + parse pull item + do queued() + call charout ,item', ' + parse pull item + end + say item + exit + +quickSort: procedure +/* In classic Rexx, arguments are passed by value, not by reference so stems + cannot be passed as arguments nor used as return values. Putting their + contents on the external data queue is a way to bypass this issue. */ + + /* construct the input stem */ + arr.0 = queued() + do i = 1 to arr.0 + parse pull arr.i + end + less.0 = 0 + pivotList.0 = 0 + more.0 = 0 + if arr.0 <= 1 then do + if arr.0 = 1 then + queue arr.1 + return + end + else do + pivot = arr.1 + do i = 1 to arr.0 + item = arr.i + select + when item < pivot then do + j = less.0 + 1 + less.j = item + less.0 = j + end + when item > pivot then do + j = more.0 + 1 + more.j = item + more.0 = j + end + otherwise + j = pivotList.0 + 1 + pivotList.j = item + pivotList.0 = j + end + end + end + /* recursive call to sort the less. stem */ + do i = 1 to less.0 + queue less.i + end + if queued() > 0 then do + call quickSort + less.0 = queued() + do i = 1 to less.0 + parse pull less.i + end + end + /* recursive call to sort the more. stem */ + do i = 1 to more.0 + queue more.i + end + if queued() > 0 then do + call quickSort + more.0 = queued() + do i = 1 to more.0 + parse pull more.i + end + end + /* put the contents of all 3 stems on the queue in order */ + do i = 1 to less.0 + queue less.i + end + do i = 1 to pivotList.0 + queue pivotList.i + end + do i = 1 to more.0 + queue more.i + end + return diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb new file mode 100644 index 0000000000..cfbb58e0c3 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb @@ -0,0 +1,9 @@ +class Array + def quick_sort + return self if length <= 1 + pivot = self[length / 2] + find_all { |i| i < pivot }.quick_sort + + find_all { |i| i == pivot } + + find_all { |i| i > pivot }.quick_sort + end +end diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb new file mode 100644 index 0000000000..6780ffb011 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb @@ -0,0 +1,10 @@ +class Array + def quick_sort + return self if length <= 1 + pivot = self[0] + less, greatereq = self[1..-1].partition { |x| x < pivot } + less.quick_sort + + [pivot] + + greatereq.quick_sort + end +end diff --git a/Task/Sorting-algorithms-Quicksort/Run-BASIC/sorting-algorithms-quicksort.run b/Task/Sorting-algorithms-Quicksort/Run-BASIC/sorting-algorithms-quicksort.run new file mode 100644 index 0000000000..2840a95812 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Run-BASIC/sorting-algorithms-quicksort.run @@ -0,0 +1,45 @@ +' ------------------------------- +' quick sort +' ------------------------------- +size = 50 +dim s(size) ' array to sort +for i = 1 to size ' fill it with some random numbers + s(i) = rnd(0) * 100 +next i + +lft = 1 +rht = size + +[qSort] + lftHold = lft + rhtHold = rht + pivot = s(lft) + while lft < rht + while (s(rht) >= pivot) and (lft < rht) : rht = rht - 1 :wend + if lft <> rht then + s(lft) = s(rht) + lft = lft + 1 + end if + while (s(lft) <= pivot) and (lft < rht) : lft = lft + 1 :wend + if lft <> rht then + s(rht) = s(lft) + rht = rht - 1 + end if + wend + + s(lft) = pivot + pivot = lft + lft = lftHold + rht = rhtHold + if lft < pivot then + rht = pivot - 1 + goto [qSort] + end if + if rht > pivot then + lft = pivot + 1 + goto [qSort] + end if + +for i = 1 to size + print i;"-->";s(i) +next i diff --git a/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-1.setl b/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-1.setl new file mode 100644 index 0000000000..36d22f1410 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-1.setl @@ -0,0 +1,22 @@ +a := [2,5,8,7,0,9,1,3,6,4]; +qsort(a); +print(a); + +proc qsort(rw a); + if #a > 1 then + pivot := a(#a div 2 + 1); + l := 1; + r := #a; + (while l < r) + (while a(l) < pivot) l +:= 1; end; + (while a(r) > pivot) r -:= 1; end; + swap(a(l), a(r)); + end; + qsort(a(1..l-1)); + qsort(a(r+1..#a)); + end if; +end proc; + +proc swap(rw x, rw y); + [y,x] := [x,y]; +end proc; diff --git a/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-2.setl b/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-2.setl new file mode 100644 index 0000000000..538f7ad159 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/SETL/sorting-algorithms-quicksort-2.setl @@ -0,0 +1,12 @@ +a := [2,5,8,7,0,9,1,3,6,4]; +print(qsort(a)); + +proc qsort(a); + if #a > 1 then + pivot := a(#a div 2 + 1); + a := qsort([x in a | x < pivot]) + + [x in a | x = pivot] + + qsort([x in a | x > pivot]); + end if; + return a; +end proc; diff --git a/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-1.sa b/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-1.sa new file mode 100644 index 0000000000..a39845bc4c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-1.sa @@ -0,0 +1,26 @@ +class SORT{T < $IS_LT{T}} is + + private afilter(a:ARRAY{T}, cmp:ROUT{T,T}:BOOL, p:T):ARRAY{T} is + filtered ::= #ARRAY{T}; + loop v ::= a.elt!; + if cmp.call(v, p) then + filtered := filtered.append(|v|); + end; + end; + return filtered; + end; + + private mlt(a, b:T):BOOL is return a < b; end; + private mgt(a, b:T):BOOL is return a > b; end; + quick_sort(inout a:ARRAY{T}) is + if a.size < 2 then return; end; + pivot ::= a.median; + left:ARRAY{T} := afilter(a, bind(mlt(_,_)), pivot); + right:ARRAY{T} := afilter(a, bind(mgt(_,_)), pivot); + quick_sort(inout left); + quick_sort(inout right); + res ::= #ARRAY{T}; + res := res.append(left, |pivot|, right); + a := res; + end; +end; diff --git a/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-2.sa b/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-2.sa new file mode 100644 index 0000000000..c6df1ac647 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Sather/sorting-algorithms-quicksort-2.sa @@ -0,0 +1,8 @@ +class MAIN is + main is + a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4, 656, -11|; + b ::= a.copy; + SORT{INT}::quick_sort(inout a); + #OUT + a + "\n" + b.sort + "\n"; + end; +end; diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-1.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-1.scala new file mode 100644 index 0000000000..56f0ab8fff --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-1.scala @@ -0,0 +1,7 @@ +def quicksortInt(coll: List[Int]): List[Int] = + if (coll.isEmpty) { + coll + } else { + val (smaller, bigger) = coll.tail partition (_ < coll.head) + quicksortInt(smaller) ::: coll.head :: quicksortInt(bigger) + } diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-2.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-2.scala new file mode 100644 index 0000000000..6e6f4d60bd --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-2.scala @@ -0,0 +1,7 @@ +def quicksortFunc[T](coll: List[T], lessThan: (T, T) => Boolean): List[T] = + if (coll.isEmpty) { + coll + } else { + val (smaller, bigger) = coll.tail partition (lessThan(_, coll.head)) + quicksortFunc(smaller, lessThan) ::: coll.head :: quicksortFunc(bigger, lessThan) + } diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-3.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-3.scala new file mode 100644 index 0000000000..7044d1793c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-3.scala @@ -0,0 +1,7 @@ +def quicksortOrd[T <% Ordered[T]](coll: List[T]): List[T] = + if (coll.isEmpty) { + coll + } else { + val (smaller, bigger) = coll.tail partition (_ < coll.head) + quicksortOrd(smaller) ::: coll.head :: quicksortOrd(bigger) + } diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-4.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-4.scala new file mode 100644 index 0000000000..330d4ba3b4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-4.scala @@ -0,0 +1,11 @@ +def quicksort + [T, CC[X] <: Seq[X] with SeqLike[X, CC[X]]] // My type parameters + (coll: CC[T]) // My explicit parameter + (implicit o: T => Ordered[T], cbf: CanBuildFrom[CC[T], T, CC[T]]) // My implicit parameters + : CC[T] = // My return type + if (coll.isEmpty) { + coll + } else { + val (smaller, bigger) = coll.tail partition (_ < coll.head) + quicksort(smaller) ++ (coll.head +: quicksort(bigger)) + } diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala new file mode 100644 index 0000000000..be7a82ec30 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala @@ -0,0 +1,6 @@ +def quicksortInt(list: List[Int]): List[Int] = list match { + case head :: tail => + val (smaller, bigger) = tail partition (_ < head) + quicksortInt(smaller) ::: head :: quicksortInt(bigger) + case list => list + } diff --git a/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.ss b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.ss new file mode 100644 index 0000000000..0c01e5663c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.ss @@ -0,0 +1,22 @@ +(define (split-by l p k) + (let loop ((low '()) + (high '()) + (l l)) + (cond ((null? l) + (k low high)) + ((p (car l)) + (loop low (cons (car l) high) (cdr l))) + (else + (loop (cons (car l) low) high (cdr l)))))) + +(define (quicksort l gt?) + (if (null? l) + '() + (split-by (cdr l) + (lambda (x) (gt? x (car l))) + (lambda (low high) + (append (quicksort low gt?) + (list (car l)) + (quicksort high gt?)))))) + +(quicksort '(1 3 5 7 9 8 6 4 2) >) diff --git a/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.ss b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.ss new file mode 100644 index 0000000000..08393156cc --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.ss @@ -0,0 +1,8 @@ +(define (quicksort l gt?) + (if (null? l) + '() + (append (quicksort (filter (lambda (x) (gt? (car l) x)) (cdr l)) gt?) + (list (car l)) + (quicksort (filter (lambda (x) (not (gt? (car l) x))) (cdr l)) gt?)))) + +(quicksort '(1 3 5 7 9 8 6 4 2) >) diff --git a/Task/Sorting-algorithms-Quicksort/Seed7/sorting-algorithms-quicksort.seed7 b/Task/Sorting-algorithms-Quicksort/Seed7/sorting-algorithms-quicksort.seed7 new file mode 100644 index 0000000000..f2142294b7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Seed7/sorting-algorithms-quicksort.seed7 @@ -0,0 +1,35 @@ +const proc: quickSort (inout array elemType: arr, in integer: left, in integer: right) is func + local + var elemType: compare_elem is elemType.value; + var integer: less_idx is 0; + var integer: greater_idx is 0; + var elemType: help is elemType.value; + begin + if right > left then + compare_elem := arr[right]; + less_idx := pred(left); + greater_idx := right; + repeat + repeat + incr(less_idx); + until arr[less_idx] >= compare_elem; + repeat + decr(greater_idx); + until arr[greater_idx] <= compare_elem or greater_idx = left; + if less_idx < greater_idx then + help := arr[less_idx]; + arr[less_idx] := arr[greater_idx]; + arr[greater_idx] := help; + end if; + until less_idx >= greater_idx; + arr[right] := arr[less_idx]; + arr[less_idx] := compare_elem; + quickSort(arr, left, pred(less_idx)); + quickSort(arr, succ(less_idx), right); + end if; + end func; + +const proc: quickSort (inout array elemType: arr) is func + begin + quickSort(arr, 1, length(arr)); + end func; diff --git a/Task/Sorting-algorithms-Quicksort/Standard-ML/sorting-algorithms-quicksort.ml b/Task/Sorting-algorithms-Quicksort/Standard-ML/sorting-algorithms-quicksort.ml new file mode 100644 index 0000000000..c222db7c74 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Standard-ML/sorting-algorithms-quicksort.ml @@ -0,0 +1,7 @@ +fun quicksort [] = [] + | quicksort (x::xs) = + let + val (left, right) = List.partition (fn y => y<x) xs + in + quicksort left @ [x] @ quicksort right + end diff --git a/Task/Sorting-algorithms-Quicksort/Tcl/sorting-algorithms-quicksort.tcl b/Task/Sorting-algorithms-Quicksort/Tcl/sorting-algorithms-quicksort.tcl new file mode 100644 index 0000000000..08bcb1c83a --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Tcl/sorting-algorithms-quicksort.tcl @@ -0,0 +1,15 @@ +package require Tcl 8.5 + +proc quicksort {m} { + if {[llength $m] <= 1} { + return $m + } + set pivot [lindex $m 0] + set less [set equal [set greater [list]]] + foreach x $m { + lappend [expr {$x < $pivot ? "less" : $x > $pivot ? "greater" : "equal"}] $x + } + return [concat [quicksort $less] $equal [quicksort $greater]] +} + +puts [quicksort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Quicksort/UnixPipes/sorting-algorithms-quicksort.unixpipes b/Task/Sorting-algorithms-Quicksort/UnixPipes/sorting-algorithms-quicksort.unixpipes new file mode 100644 index 0000000000..796d04dba9 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/UnixPipes/sorting-algorithms-quicksort.unixpipes @@ -0,0 +1,16 @@ +split() { + (while read n ; do + test $1 -gt $n && echo $n > $2 || echo $n > $3 + done) +} + +qsort() { + (read p; test -n "$p" && ( + lc="1.$1" ; gc="2.$1" + split $p >(qsort $lc >$lc) >(qsort $gc >$gc); + cat $lc <(echo $p) $gc + rm -f $lc $gc; + )) +} + +cat to.sort | qsort diff --git a/Task/Sorting-algorithms-Quicksort/Ursala/sorting-algorithms-quicksort.ursala b/Task/Sorting-algorithms-Quicksort/Ursala/sorting-algorithms-quicksort.ursala new file mode 100644 index 0000000000..4f79bfc934 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ursala/sorting-algorithms-quicksort.ursala @@ -0,0 +1,7 @@ +#import nat + +quicksort "p" = ~&itB^?a\~&a ^|WrlT/~& "p"*|^\~& "p"?hthPX/~&th ~&h + +#cast %nL + +example = quicksort(nleq) <694,1377,367,506,3712,381,1704,1580,475,1872> diff --git a/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-1.v b/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-1.v new file mode 100644 index 0000000000..9fe1ddd1e5 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-1.v @@ -0,0 +1,7 @@ +[qsort + [joinparts [p [*l1] [*l2] : [*l1 p *l2]] view]. + [split_on_first uncons [>] split]. + [small?] + [] + [split_on_first [l1 l2 : [l1 qsort l2 qsort joinparts]] view i] + ifte]. diff --git a/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-2.v b/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-2.v new file mode 100644 index 0000000000..f56bc87cde --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/V/sorting-algorithms-quicksort-2.v @@ -0,0 +1,5 @@ +[qsort + [small?] [] + [uncons [>] split] + [[p [*l] [*g] : [*l p *g]] view] + binrec]. diff --git a/Task/Sorting-algorithms-Quicksort/VBA/sorting-algorithms-quicksort.vba b/Task/Sorting-algorithms-Quicksort/VBA/sorting-algorithms-quicksort.vba new file mode 100644 index 0000000000..336e4b71aa --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/VBA/sorting-algorithms-quicksort.vba @@ -0,0 +1,63 @@ +Public Sub Quick(a() As Variant, last As Integer) +' quicksort a Variant array (1-based, numbers or strings) +Dim aLess() As Variant +Dim aEq() As Variant +Dim aGreater() As Variant +Dim pivot As Variant +Dim naLess As Integer +Dim naEq As Integer +Dim naGreater As Integer + +If last > 1 Then + 'choose pivot in the middle of the array + pivot = a(Int((last + 1) / 2)) + 'construct arrays + naLess = 0 + naEq = 0 + naGreater = 0 + For Each el In a() + If el > pivot Then + naGreater = naGreater + 1 + ReDim Preserve aGreater(1 To naGreater) + aGreater(naGreater) = el + ElseIf el < pivot Then + naLess = naLess + 1 + ReDim Preserve aLess(1 To naLess) + aLess(naLess) = el + Else + naEq = naEq + 1 + ReDim Preserve aEq(1 To naEq) + aEq(naEq) = el + End If + Next + 'sort arrays "less" and "greater" + Quick aLess(), naLess + Quick aGreater(), naGreater + 'concatenate + P = 1 + For i = 1 To naLess + a(P) = aLess(i): P = P + 1 + Next + For i = 1 To naEq + a(P) = aEq(i): P = P + 1 + Next + For i = 1 To naGreater + a(P) = aGreater(i): P = P + 1 + Next +End If +End Sub + +Public Sub QuicksortTest() +Dim a(1 To 26) As Variant + + 'populate a with numbers in descending order, then sort + For i = 1 To 26: a(i) = 26 - i: Next + Quick a(), 26 + For i = 1 To 26: Debug.Print a(i);: Next + Debug.Print + 'now populate a with strings in descending order, then sort + For i = 1 To 26: a(i) = Chr$(Asc("z") + 1 - i) & "-stuff": Next + Quick a(), 26 + For i = 1 To 26: Debug.Print a(i); " ";: Next + Debug.Print +End Sub diff --git a/Task/Sorting-algorithms-Quicksort/XPL0/sorting-algorithms-quicksort.xpl0 b/Task/Sorting-algorithms-Quicksort/XPL0/sorting-algorithms-quicksort.xpl0 new file mode 100644 index 0000000000..9b886cda49 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/XPL0/sorting-algorithms-quicksort.xpl0 @@ -0,0 +1,34 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated strings + +proc QSort(Array, Num); \Quicksort Array into ascending order +char Array; \address of array to sort +int Num; \number of elements in the array +int I, J, Mid, Temp; +[I:= 0; +J:= Num-1; +Mid:= Array(J>>1); +while I <= J do + [while Array(I) < Mid do I:= I+1; + while Array(J) > Mid do J:= J-1; + if I <= J then + [Temp:= Array(I); Array(I):= Array(J); Array(J):= Temp; + I:= I+1; + J:= J-1; + ]; + ]; +if I < Num-1 then QSort(@Array(I), Num-I); +if J > 0 then QSort(Array, J+1); +]; \QSort + +func StrLen(Str); \Return number of characters in an ASCIIZ string +char Str; +int I; +for I:= 0 to -1>>1-1 do + if Str(I) = 0 then return I; + +char Str; +[Str:= "Pack my box with five dozen liquor jugs."; +QSort(Str, StrLen(Str), 1); +Text(0, Str); CrLf(0); +] diff --git a/Task/Sorting-algorithms-Radix-sort/0DESCRIPTION b/Task/Sorting-algorithms-Radix-sort/0DESCRIPTION new file mode 100644 index 0000000000..0dff29f3ec --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/0DESCRIPTION @@ -0,0 +1,2 @@ +{{Sorting Algorithm}} +In this task, the goal is to sort an integer array with the [[wp:Radix sort|radix sort algorithm]]. The primary purpose is to complete the characterization of sort algorithms task. diff --git a/Task/Sorting-algorithms-Radix-sort/1META.yaml b/Task/Sorting-algorithms-Radix-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada b/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada new file mode 100644 index 0000000000..c9e849b58b --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada @@ -0,0 +1,83 @@ +with Ada.Text_IO; +procedure Radix_Sort is + type Integer_Array is array (Positive range <>) of Integer; + + procedure Least_Significant_Radix_Sort (Data : in out Integer_Array; Base : Positive := 10) is + type Bucket is record + Count : Natural := 0; + Content : Integer_Array (Data'Range); + end record; + + subtype Bucket_Index is Integer range -Base + 1 .. Base - 1; + type Bucket_Array is array (Bucket_Index) of Bucket; + + procedure Append (To : in out Bucket; Item : Integer) is + begin + To.Count := To.Count + 1; + To.Content (To.Count) := Item; + end Append; + + function Get_Nth_Digit (Value : Integer; N : Positive) return Integer is + Result : Integer := (Value / (Base ** (N - 1))) mod Base; + begin + if Value < 0 then + Result := -Result; + end if; + return Result; + end Get_Nth_Digit; + + function Get_Maximum return Natural is + Result : Natural := 0; + begin + for I in Data'Range loop + if abs (Data (I)) > Result then + Result := abs (Data (I)); + end if; + end loop; + return Result; + end Get_Maximum; + + function Split (Pass : Positive) return Bucket_Array is + Buckets : Bucket_Array; + begin + for I in Data'Range loop + Append (To => Buckets (Get_Nth_Digit (Data (I), Pass)), + Item => Data (I)); + end loop; + return Buckets; + end Split; + + function Merge (Buckets : Bucket_Array) return Integer_Array is + Result : Integer_Array (Data'Range); + Current_Index : Positive := 1; + begin + for Sublist in Buckets'Range loop + for Item in 1 .. Buckets (Sublist).Count loop + Result (Current_Index) := Buckets (Sublist).Content (Item); + Current_Index := Current_Index + 1; + end loop; + end loop; + return Result; + end Merge; + + Max_Number : Natural := Get_Maximum; + Digit_Count : Positive := 1; + begin + -- count digits of biggest number + while Max_Number > Base loop + Digit_Count := Digit_Count + 1; + Max_Number := Max_Number / Base; + end loop; + for Pass in 1 .. Digit_Count loop + Data := Merge (Split (Pass)); + end loop; + end Least_Significant_Radix_Sort; + + Test_Array : Integer_Array := (170, 45, 75, -90, -802, 24, 2, 66); +begin + Least_Significant_Radix_Sort (Test_Array, 4); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Radix_Sort; diff --git a/Task/Sorting-algorithms-Radix-sort/BBC-BASIC/sorting-algorithms-radix-sort.bbc b/Task/Sorting-algorithms-Radix-sort/BBC-BASIC/sorting-algorithms-radix-sort.bbc new file mode 100644 index 0000000000..fdfb61bb02 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/BBC-BASIC/sorting-algorithms-radix-sort.bbc @@ -0,0 +1,37 @@ + DIM test%(9) + test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCradixsort(test%(), 10, 10) + FOR i% = 0 TO 9 + PRINT test%(i%) ; + NEXT + PRINT + END + + DEF PROCradixsort(a%(), n%, r%) + LOCAL d%, e%, i%, l%, m%, b%(), bucket%() + DIM b%(n%-1), bucket%(r%-1) + FOR i% = 0 TO n%-1 + IF a%(i%) < l% l% = a%(i%) + IF a%(i%) > m% m% = a%(i%) + NEXT + a%() -= l% + m% -= l% + e% = 1 + WHILE m% DIV e% + bucket%() = 0 + FOR i% = 0 TO n%-1 + bucket%(a%(i%) DIV e% MOD r%) += 1 + NEXT + FOR i% = 1 TO r%-1 + bucket%(i%) += bucket%(i% - 1) + NEXT + FOR i% = n%-1 TO 0 STEP -1 + d% = a%(i%) DIV e% MOD r% + bucket%(d%) -= 1 + b%(bucket%(d%)) = a%(i%) + NEXT + a%() = b%() + e% *= r% + ENDWHILE + a%() += l% + ENDPROC diff --git a/Task/Sorting-algorithms-Radix-sort/C++/sorting-algorithms-radix-sort.cpp b/Task/Sorting-algorithms-Radix-sort/C++/sorting-algorithms-radix-sort.cpp new file mode 100644 index 0000000000..4cde91daa8 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/C++/sorting-algorithms-radix-sort.cpp @@ -0,0 +1,53 @@ +#include <algorithm> +#include <iostream> +#include <iterator> + +// Radix sort comparator for 32-bit two's complement integers +class radix_test +{ + const int bit; // bit position [0..31] to examine +public: + radix_test(int offset) : bit(offset) {} // constructor + + bool operator()(int value) const // function call operator + { + if (bit == 31) // sign bit + return value < 0; // negative int to left partition + else + return !(value & (1 << bit)); // 0 bit to left partition + } +}; + +// Least significant digit radix sort +void lsd_radix_sort(int *first, int *last) +{ + for (int lsb = 0; lsb < 32; ++lsb) // least-significant-bit + { + std::stable_partition(first, last, radix_test(lsb)); + } +} + +// Most significant digit radix sort (recursive) +void msd_radix_sort(int *first, int *last, int msb = 31) +{ + if (first != last && msb >= 0) + { + int *mid = std::partition(first, last, radix_test(msb)); + msb--; // decrement most-significant-bit + msd_radix_sort(first, mid, msb); // sort left partition + msd_radix_sort(mid, last, msb); // sort right partition + } +} + +// test radix_sort +int main() +{ + int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 }; + + lsd_radix_sort(data, data + 8); + // msd_radix_sort(data, data + 8); + + std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " ")); + + return 0; +} diff --git a/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c new file mode 100644 index 0000000000..911337fc55 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c @@ -0,0 +1,57 @@ +#include <stdio.h> +#include <limits.h> +#include <stdlib.h> + +typedef unsigned uint; +#define swap(a, b) { tmp = a; a = b; b = tmp; } +#define each(i, x) for (i = 0; i < x; i++) + +/* sort unsigned ints */ +static void rad_sort_u(uint *from, uint *to, uint bit) +{ + if (!bit || to < from + 1) return; + + uint *ll = from, *rr = to - 1, tmp; + while (1) { + /* find left most with bit, and right most without bit, swap */ + while (ll < rr && !(*ll & bit)) ll++; + while (ll < rr && (*rr & bit)) rr--; + if (ll >= rr) break; + swap(*ll, *rr); + } + + if (!(bit & *ll) && ll < to) ll++; + bit >>= 1; + + rad_sort_u(from, ll, bit); + rad_sort_u(ll, to, bit); +} + +/* sort signed ints: flip highest bit, sort as unsigned, flip back */ +static void radix_sort(int *a, const size_t len) +{ + size_t i; + uint *x = (uint*) a; + + each(i, len) x[i] ^= INT_MIN; + rad_sort_u(x, x + len, INT_MIN); + each(i, len) x[i] ^= INT_MIN; +} + +static inline void radix_sort_unsigned(uint *a, const size_t len) +{ + rad_sort_u(a, a + len, (uint)INT_MIN); +} + +int main(void) +{ + int len = 16, x[16], i; + size_t len = 16, i; + each(i, len) x[i] = rand() % 512 - 256; + + radix_sort(x, len); + + each(i, len) printf("%d%c", x[i], i + 1 < len ? ' ' : '\n'); + + return 0; +} diff --git a/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-1.d b/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-1.d new file mode 100644 index 0000000000..f3623975bc --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-1.d @@ -0,0 +1,33 @@ +import std.stdio, std.math, std.traits, std.range, std.algorithm; + +ElementType!R[] radixSort(size_t N=10, R)(R r) +if (hasLength!R && isRandomAccessRange!R && + isIntegral!(ElementType!R)) { + alias ElementType!R E; + + static if (isDynamicArray!R) + alias r res; // input is array => in place sort + else + E[] res = r.array(); // input is Range => return a new array + + E absMax = r.map!abs().reduce!max(); + immutable nPasses = 1 + cast(int)(log(absMax) / log(N)); + + foreach (pass; 0 .. nPasses) { + auto bucket = new E[][](2 * N - 1, 0); + foreach (v; res) { + int bIdx = abs(v / (N ^^ pass)) % N; + bIdx = (v < 0) ? -bIdx : bIdx; + bucket[N + bIdx - 1] ~= v; + } + res = bucket.join(); + } + + return res; +} + +void main() { + auto items = [170, 45, 75, -90, 2, 24, -802, 66]; + items.radixSort().writeln(); + items.map!q{1 - a}().radixSort().writeln(); +} diff --git a/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-2.d b/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-2.d new file mode 100644 index 0000000000..0b118d013a --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/D/sorting-algorithms-radix-sort-2.d @@ -0,0 +1,58 @@ +import std.array, std.traits; + +// considered pure for this program +extern(C) void* alloca(in size_t length) pure nothrow; + +void radixSort(size_t MAX_ALLOCA=5_000, U)(U[] data) +pure nothrow if (isUnsigned!U) { + static void radix(in uint byteIndex, in U[] source, U[] dest) + pure nothrow { + immutable size_t sourceSize = source.length; + ubyte* curByte = (cast(ubyte*)source.ptr) + byteIndex; + uint[ubyte.max + 1] byteCounter; + for (size_t i = 0; i < sourceSize; i++, curByte += U.sizeof) + byteCounter[*curByte]++; + + { + uint indexStart; + foreach (uint i; 0 .. byteCounter.length) { + immutable size_t tempCount = byteCounter[i]; + byteCounter[i] = indexStart; + indexStart += tempCount; + } + } + + curByte = (cast(ubyte*)source.ptr) + byteIndex; + for (size_t i = 0; i < sourceSize; i++, curByte += U.sizeof) { + uint* countPtr = byteCounter.ptr + *curByte; + dest[*countPtr] = source[i]; + (*countPtr)++; + } + } + + U[] tempData; + if (U.sizeof * data.length <= MAX_ALLOCA) { + U* ptr = cast(U*)alloca(data.length * U.sizeof); + if (ptr != null) + tempData = ptr[0 .. data.length]; + } + if (tempData.empty) + tempData = uninitializedArray!(U[])(data.length); + + static if (U.sizeof == 1) { + radix(0, data, tempData); + data[] = tempData[]; + } else { + for (uint i = 0; i < U.sizeof; i += 2) { + radix(i + 0, data, tempData); + radix(i + 1, tempData, data); + } + } +} + +void main() { + import std.stdio; + uint[] items = [170, 45, 75, 4294967206, 2, 24, 4294966494, 66]; + items.radixSort(); + writeln(items); +} diff --git a/Task/Sorting-algorithms-Radix-sort/Go/sorting-algorithms-radix-sort.go b/Task/Sorting-algorithms-Radix-sort/Go/sorting-algorithms-radix-sort.go new file mode 100644 index 0000000000..3658ada39a --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Go/sorting-algorithms-radix-sort.go @@ -0,0 +1,45 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" +) + +// declarations for word size of data +type word int32 +const wordLen = 4 +const highBit = -1 << 31 + +var data = []word{170, 45, 75, -90, -802, 24, 2, 66} + +func main() { + buf := bytes.NewBuffer(nil) + ds := make([][]byte, len(data)) + for i, x := range data { + binary.Write(buf, binary.LittleEndian, x^highBit) + b := make([]byte, wordLen) + buf.Read(b) + ds[i] = b + } + bins := make([][][]byte, 256) + for i := 0; i < wordLen; i++ { + for _, b := range ds { + bins[b[i]] = append(bins[b[i]], b) + } + j := 0 + for k, bs := range bins { + copy(ds[j:], bs) + j += len(bs) + bins[k] = bs[:0] + } + } + fmt.Println("original:", data) + var w word + for i, b := range ds { + buf.Write(b) + binary.Read(buf, binary.LittleEndian, &w) + data[i] = w^highBit + } + fmt.Println("sorted: ", data) +} diff --git a/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-1.groovy b/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-1.groovy new file mode 100644 index 0000000000..0d24e3a7f6 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-1.groovy @@ -0,0 +1,24 @@ +def radixSort = { final radixExponent, list -> + def fromBuckets = new TreeMap([0:list]) + def toBuckets = new TreeMap() + final radix = 2**radixExponent + final mask = radix - 1 + final radixDigitSize = (int)Math.ceil(64/radixExponent) + final digitWidth = radixExponent + (0..<radixDigitSize).each { radixDigit -> + fromBuckets.values().findAll { it != null }.flatten().each { + print '.' + long bucketNumber = (long)((((long)it) >>> digitWidth*radixDigit) & mask) + toBuckets[bucketNumber] = toBuckets[bucketNumber] ?: [] + toBuckets[bucketNumber] << it + } + (fromBuckets, toBuckets) = [toBuckets, fromBuckets] + toBuckets.clear() + } + final overflow = 2**(63 % radixExponent) + final pos = {it < overflow} + final neg = {it >= overflow} + final keys = fromBuckets.keySet() + final twosComplIndx = [] + (keys.findAll(neg)) + (keys.findAll(pos)) + twosComplIndx.collect { fromBuckets[it] }.findAll { it != null }.flatten() +} diff --git a/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-2.groovy b/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-2.groovy new file mode 100644 index 0000000000..c41baba98b --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Groovy/sorting-algorithms-radix-sort-2.groovy @@ -0,0 +1,19 @@ +println (radixSort(3, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (radixSort(3, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (radixSort(3, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4])) +println () +println (radixSort(8, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (radixSort(8, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (radixSort(8, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4])) +println () +println (radixSort(11, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (radixSort(11, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (radixSort(11, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4])) +println () +println (radixSort(16, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (radixSort(16, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (radixSort(16, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4])) +println () +println (radixSort(32, [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (radixSort(32, [88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +println (radixSort(32, [23,-76,-990,580,97,57,350000,Long.MAX_VALUE,89,Long.MIN_VALUE,51,38,95*2**48,92,-24*2**48,46,31*2**32,24,14,12,57,78,4])) diff --git a/Task/Sorting-algorithms-Radix-sort/Haskell/sorting-algorithms-radix-sort.hs b/Task/Sorting-algorithms-Radix-sort/Haskell/sorting-algorithms-radix-sort.hs new file mode 100644 index 0000000000..be043ce942 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Haskell/sorting-algorithms-radix-sort.hs @@ -0,0 +1,22 @@ +import Data.Bits (Bits(testBit, bitSize)) +import Data.List (partition) + +lsdSort :: (Ord a, Bits a) => [a] -> [a] +lsdSort = fixSort positiveLsdSort + +msdSort :: (Ord a, Bits a) => [a] -> [a] +msdSort = fixSort positiveMsdSort + +-- Fix a sort that puts negative numbers at the end, like positiveLsdSort and positiveMsdSort +fixSort sorter list = uncurry (flip (++)) (break (< 0) (sorter list)) + +positiveLsdSort :: (Bits a) => [a] -> [a] +positiveLsdSort list = foldl step list [0..bitSize (head list)] where + step list bit = uncurry (++) (partition (not . flip testBit bit) list) + +positiveMsdSort :: (Bits a) => [a] -> [a] +positiveMsdSort list = aux (bitSize (head list) - 1) list where + aux _ [] = [] + aux (-1) list = list + aux bit list = aux (bit - 1) lower ++ aux (bit - 1) upper where + (lower, upper) = partition (not . flip testBit bit) list diff --git a/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-1.j b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-1.j new file mode 100644 index 0000000000..a7b154d157 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-1.j @@ -0,0 +1,11 @@ +radixSortR =: 3 : 0 NB. base radixSort data +16 radixSortR y +: +keys =. x #.^:_1 y NB. compute keys +length =. #{.keys +extra =. (-length) {."0 buckets =. i.x +for_pass. i.-length do. + keys =. ; (buckets,pass{"1 keys) <@:}./.extra,keys +end. +x#.keys NB. restore the data +) diff --git a/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-2.j b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-2.j new file mode 100644 index 0000000000..31925dfa50 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-2.j @@ -0,0 +1 @@ +radixsort=: (] #~ [: +/ =/) i.@(>./) diff --git a/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-3.j b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-3.j new file mode 100644 index 0000000000..8a1c19f955 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-3.j @@ -0,0 +1,2 @@ + radixsort ?.@#~10 +4 5 6 6 6 6 6 8 8 diff --git a/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-4.j b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-4.j new file mode 100644 index 0000000000..0f91bc7002 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-4.j @@ -0,0 +1 @@ +rsort=: (] + radixsort@:-) <./ diff --git a/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-5.j b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-5.j new file mode 100644 index 0000000000..3c082e7703 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/J/sorting-algorithms-radix-sort-5.j @@ -0,0 +1,2 @@ + rsort _6+?.@#~10 +_2 _1 0 0 0 0 0 2 2 diff --git a/Task/Sorting-algorithms-Radix-sort/Perl-6/sorting-algorithms-radix-sort.pl6 b/Task/Sorting-algorithms-Radix-sort/Perl-6/sorting-algorithms-radix-sort.pl6 new file mode 100644 index 0000000000..da1424f9fc --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Perl-6/sorting-algorithms-radix-sort.pl6 @@ -0,0 +1,13 @@ +sub radsort (@ints) { + my $maxlen = [max] @ints».chars; + my @list = @ints».fmt("\%0{$maxlen}d"); + + for reverse ^$maxlen -> $r { + my @buckets = @list.classify( *.substr($r,1) ).sort: *.key; + if !$r and @buckets[0].key eq '-' { @buckets[0].value .= reverse } + @list = map *.value.values, @buckets; + } + @list».Int; +} + +.say for radsort (-2_000 .. 2_000).roll(20); diff --git a/Task/Sorting-algorithms-Radix-sort/PicoLisp/sorting-algorithms-radix-sort.l b/Task/Sorting-algorithms-Radix-sort/PicoLisp/sorting-algorithms-radix-sort.l new file mode 100644 index 0000000000..e5d5f7a8ef --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/PicoLisp/sorting-algorithms-radix-sort.l @@ -0,0 +1,15 @@ +(de radixSort (Lst) + (let Mask 1 + (while + (let (Pos (list NIL NIL) Neg (list NIL NIL) Flg) + (for N Lst + (queue + (if2 (ge0 N) (bit? Mask N) + (cdr Pos) Pos Neg (cdr Neg) ) + N ) + (and (>= (abs N) Mask) (on Flg)) ) + (setq + Lst (conc (apply conc Neg) (apply conc Pos)) + Mask (* 2 Mask) ) + Flg ) ) ) + Lst ) diff --git a/Task/Sorting-algorithms-Radix-sort/PureBasic/sorting-algorithms-radix-sort.purebasic b/Task/Sorting-algorithms-Radix-sort/PureBasic/sorting-algorithms-radix-sort.purebasic new file mode 100644 index 0000000000..db97dc7243 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/PureBasic/sorting-algorithms-radix-sort.purebasic @@ -0,0 +1,86 @@ +Structure bucket + List i.i() +EndStructure + +DataSection + ;sets specify the size (1 based) followed by each integer + set1: + Data.i 10 ;size + Data.i 1, 3, 8, 9, 0, 0, 8, 7, 1, 6 ;data + set2: + Data.i 8 + Data.i 170, 45, 75, 90, 2, 24, 802, 66 + set3: + Data.i 8 + Data.i 170, 45, 75, 90, 2, 24, -802, -66 +EndDataSection + +Procedure setIntegerArray(Array x(1), *setPtr) + Protected i, count + count = PeekI(*setPtr) - 1 ;convert to zero based count + *setPtr + SizeOf(Integer) ;move pointer forward to data + Dim x(count) + For i = 0 To count + x(i) = PeekI(*setPtr + i * SizeOf(Integer)) + Next +EndProcedure + +Procedure displayArray(Array x(1)) + Protected i, Size = ArraySize(x()) + For i = 0 To Size + Print(Str(x(i))) + If i < Size: Print(", "): EndIf + Next + PrintN("") +EndProcedure + +Procedure radixSort(Array x(1), Base = 10) + Protected count = ArraySize(x()) + If Base < 1 Or count < 1: ProcedureReturn: EndIf ;exit due to invalid values + + Protected i, pv, digit, digitCount, maxAbs, pass, index + ;find element with largest number of digits + For i = 0 To count + If Abs(x(i)) > maxAbs + maxAbs = Abs(x(i)) + EndIf + Next + + digitCount = Int(Log(maxAbs)/Log(Base)) + 1 + + For pass = 1 To digitCount + Dim sortBuckets.bucket(Base * 2 - 1) + pv = Pow(Base, pass - 1) + + ;place elements in buckets according to the current place-value's digit + For index = 0 To count + digit = Int(x(index)/pv) % Base + Base + AddElement(sortBuckets(digit)\i()) + sortBuckets(digit)\i() = x(index) + Next + + ;transfer contents of buckets back into array + index = 0 + For digit = 1 To (Base * 2) - 1 + ForEach sortBuckets(digit)\i() + x(index) = sortBuckets(digit)\i() + index + 1 + Next + Next + Next +EndProcedure + +If OpenConsole() + Dim x(0) + setIntegerArray(x(), ?set1) + radixSort(x()): displayArray(x()) + + setIntegerArray(x(), ?set2) + radixSort(x()): displayArray(x()) + + setIntegerArray(x(), ?set3) + radixSort(x(), 2): displayArray(x()) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py b/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py new file mode 100644 index 0000000000..8c0975bbfd --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Python/sorting-algorithms-radix-sort.py @@ -0,0 +1,47 @@ +#python2.6 < +from math import log + +def getDigit(num, base, digit_num): + # pulls the selected digit + return (num // base ** digit_num) % base + +def makeBlanks(size): + # create a list of empty lists to hold the split by digit + return [ [] for i in range(size) ] + +def split(a_list, base, digit_num): + buckets = makeBlanks(base) + for num in a_list: + # append the number to the list selected by the digit + buckets[getDigit(num, base, digit_num)].append(num) + return buckets + +# concatenate the lists back in order for the next step +def merge(a_list): + new_list = [] + for sublist in a_list: + new_list.extend(sublist) + return new_list + +def maxAbs(a_list): + # largest abs value element of a list + return max(abs(num) for num in a_list) + +def split_by_sign(a_list): + # splits values by sign - negative values go to the first bucket, + # non-negative ones into the second + buckets = [[], []] + for num in a_list: + if num < 0: + buckets[0].append(num) + else: + buckets[1].append(num) + return buckets + +def radixSort(a_list, base): + # there are as many passes as there are digits in the longest number + passes = int(log(maxAbs(a_list), base) + 1) + new_list = list(a_list) + for digit_num in range(passes): + new_list = merge(split(new_list, base, digit_num)) + return merge(split_by_sign(new_list)) diff --git a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx new file mode 100644 index 0000000000..b500657641 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx @@ -0,0 +1,81 @@ +/*REXX program performs a radix sort on a stemmed integer array. */ +aList='0 2 3 4 5 5 7 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 9 11', + '29 10 31 10 14 19 12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12', + '20 17 53 11 16 13 22 31 59 12 61 33 13 12 18 16 67 21 26 14 71 12', + '73 39 13 23 18 18 79 13 12 43 83 14 22 45 32 17 89 13 20 27 34 49', + '24 13 97 16 17 14 101 22 103 19 15 55 107 13 109 18 40 15 113 -42' +/*excluding -42, the abbreviated list is called the integer log function*/ + +mina=word(aList,1); maxa=mina + + do n=1 for words(aList); x=word(aList,n); @.n=x /*list ──► array.*/ + mina=min(x,mina); maxa=max(x,maxa) + width=max(length(abs(mina)),length(maxa)) + end + +n=words(aList); w=length(n); call radSort n + + do j=1 for n + say 'item' right(j,w) "after the radix sort:" right(@.j,width+1) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────RADSORT subroutine─────────────────*/ +radSort: procedure expose @. width; parse arg size; mote=c2d(' '); #=1 +!.#._b=1 +!.#._i=1 +!.#._n=size; do i=1 for size; y=@.i; @.i=right(abs(y),width,0) + if y<0 then @.i='-'@.i + end /*i*/ +/*══════════════════════════════════════where the rubber meets the road.*/ + do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; radi=!.#._i; H= + #=#-1 + do j=low for n; parse var @.j =(radi) _ +1; ctr._=ctr._+1 + if ctr._==1 then if _\=='' then do + if _<<L then L=_ + if _>>H then H=_ + end + end /*j*/ + + if L>>H then iterate + _= + if L==H then if ctr._==0 then do; #=#+1; !.#._b=low + !.#._n=n + !.#._i=radi+1; iterate + end + + L=c2d(L); H=c2d(H); ?=ctr._+low; top._=?; ts=mote; max=L + + do k=L to H; _=d2c(k,1); cen=ctr._ + if cen>ts then parse value cen k with ts max + ?=?+cen; top._=? + end /*k*/ + pivot=low + + do while pivot<low+n; it=@.pivot + do forever + parse var it =(radi) _ +1; cen=top._-1; if pivot>=cen then leave + top._=cen; ?=@.cen; @.cen=it; it=? + end /*forever*/ + top._=pivot; @.pivot=it; pivot=pivot+ctr._ + end /*while pivot<low+n*/ + + i=max + + do until i==max; _=d2c(i,1); i=i+1; if i>H then i=L; d=ctr._ + if d<=mote then do; if d>1 then call .radSortP top._,d; iterate; end + #=#+1; !.#._b=top._ + !.#._n=d + !.#._i=radi+1 + end /*until i==max*/ + end /*while #\==0 */ +/*═════════════════════════════════════we're done with the heavy lifting*/ + + do i=1 for size; @.i=@.i+0; end /*i*/ +return +/*───────────────────────────────────.radSortP subroutine───────────────*/ +.radSortP: parse arg bbb,nnn + do k=bbb+1 for nnn-1; q=@.k + do j=k-1 by -1 to bbb while q<<@.j; jp=j+1; @.jp=@.j; end + jp=j+1; @.jp=q + end /*k*/ +return diff --git a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb new file mode 100644 index 0000000000..1f2b50944a --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb @@ -0,0 +1,24 @@ +class Array + def radix_sort(base=10) + ary = dup + rounds = (Math.log(self.max.abs)/Math.log(base)).ceil + rounds.times do |i| + buckets = Hash.new {|h,k| h[k] = []} + ary.each do |n| + digit = (n/base**i) % base + digit = digit + base unless n<0 + buckets[digit] << n + end + ary = buckets.values_at(*(0..2*base)).compact.flatten + p [i, ary] if $DEBUG + end + ary + end + def radix_sort!(base=10) + replace radix_sort(base) + end +end + +p [1, 3, 8, 9, 0, 0, 8, 7, 1, 6].radix_sort +p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort +p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort diff --git a/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-1.tcl b/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-1.tcl new file mode 100644 index 0000000000..e0626ae878 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-1.tcl @@ -0,0 +1,33 @@ +package require Tcl 8.5 +proc splitByRadix {lst base power} { + # create a list of empty lists to hold the split by digit + set out [lrepeat [expr {$base*2}] {}] + foreach item $lst { + # pulls the selected digit + set digit [expr {($item / $base ** $power) % $base + $base * ($item >= 0)}] + # append the number to the list selected by the digit + lset out $digit [list {*}[lindex $out $digit] $item] + } + return $out +} + +# largest abs value element of a list +proc tcl::mathfunc::maxabs {lst} { + set max [abs [lindex $lst 0]] + for {set i 1} {$i < [llength $lst]} {incr i} { + set v [abs [lindex $lst $i]] + if {$max < $v} {set max $v} + } + return $max +} + +proc radixSort {lst {base 10}} { + # there are as many passes as there are digits in the longest number + set passes [expr {int(log(maxabs($lst))/log($base) + 1)}] + # For each pass... + for {set pass 0} {$pass < $passes} {incr pass} { + # Split by radix, then merge back into the list + set lst [concat {*}[splitByRadix $lst $base $pass]] + } + return $lst +} diff --git a/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-2.tcl b/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-2.tcl new file mode 100644 index 0000000000..e3f02eadb6 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Tcl/sorting-algorithms-radix-sort-2.tcl @@ -0,0 +1,3 @@ +puts [radixSort {1 3 8 9 0 0 8 7 1 6}] +puts [radixSort {170 45 75 90 2 24 802 66}] +puts [radixSort {170 45 75 90 2 24 -802 -66}] diff --git a/Task/Sorting-algorithms-Selection-sort/0DESCRIPTION b/Task/Sorting-algorithms-Selection-sort/0DESCRIPTION new file mode 100644 index 0000000000..7ab15ff371 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/0DESCRIPTION @@ -0,0 +1,7 @@ +{{Sorting Algorithm}} +In this task, the goal is to sort an [[array]] (or list) of elements using the Selection sort algorithm. It works as follows: + +First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. +Its asymptotic complexity is [[O]](n<sup>2</sup>) making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg writing to flash memory or EEPROM. No other sorting algorithm has less data movement. + +For more information see the article on [[wp:Selection_sort|Wikipedia]]. diff --git a/Task/Sorting-algorithms-Selection-sort/1META.yaml b/Task/Sorting-algorithms-Selection-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Selection-sort/ALGOL-68/sorting-algorithms-selection-sort.alg b/Task/Sorting-algorithms-Selection-sort/ALGOL-68/sorting-algorithms-selection-sort.alg new file mode 100644 index 0000000000..56b894bcc7 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/ALGOL-68/sorting-algorithms-selection-sort.alg @@ -0,0 +1,26 @@ +MODE DATA = REF CHAR; + +PROC in place selection sort = (REF[]DATA a)VOID: +BEGIN + INT min; + DATA temp; + FOR i FROM LWB a TO UPB a DO + min := i; + FOR j FROM i + 1 TO UPB a DO + IF a [min] > a [j] THEN + min := j + FI + OD; + IF min /= i THEN + temp := a [i]; + a [i] := a [min]; + a [min] := temp + FI + OD +END # in place selection sort #; + +[32]CHAR data := "big fjords vex quick waltz nymph"; +[UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD; +in place selection sort(ref data); +FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line); +print((data)) diff --git a/Task/Sorting-algorithms-Selection-sort/AWK/sorting-algorithms-selection-sort.awk b/Task/Sorting-algorithms-Selection-sort/AWK/sorting-algorithms-selection-sort.awk new file mode 100644 index 0000000000..b29de73cd7 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/AWK/sorting-algorithms-selection-sort.awk @@ -0,0 +1,28 @@ +function getminindex(gl, gi, gs) +{ + min = gl[gi] + gm = gi + for(gj=gi; gj <= gs; gj++) { + if ( gl[gj] < min ) { + min = gl[gj] + gm = gj + } + } + return gm +} + +{ + line[NR] = $0 +} +END { # sort it with selection sort + for(i=1; i <= NR; i++) { + mi = getminindex(line, i, NR) + t = line[i] + line[i] = line[mi]; + line[mi] = t + } + #print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/ActionScript/sorting-algorithms-selection-sort.as b/Task/Sorting-algorithms-Selection-sort/ActionScript/sorting-algorithms-selection-sort.as new file mode 100644 index 0000000000..a0f02fd634 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/ActionScript/sorting-algorithms-selection-sort.as @@ -0,0 +1,18 @@ +function selectionSort(input: Array):Array { + //find the i'th element + for (var i:uint = 0; i < input.length; i++) { + //set minIndex to an arbitrary value + var minIndex:uint=i; + //find the smallest number + for (var j:uint = i; j < input.length; j++) { + if (input[j]<input[minIndex]) { + minIndex=j; + } + } + //swap the smallest number into place + var tmp:Number=input[i]; + input[i]=input[minIndex]; + input[minIndex]=tmp; + } + return input; +} diff --git a/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.ada b/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.ada new file mode 100644 index 0000000000..cce8d3a3a8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.ada @@ -0,0 +1,31 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Selection_Sort is + + type Integer_Array is array (Positive range <>) of Integer; + procedure Sort (A : in out Integer_Array) is + Min : Positive; + Temp : Integer; + begin + for I in A'First..A'Last - 1 loop + Min := I; + for J in I + 1..A'Last loop + if A (Min) > A (J) then + Min := J; + end if; + end loop; + if Min /= I then + Temp := A (I); + A (I) := A (Min); + A (Min) := Temp; + end if; + end loop; + end Sort; + + A : Integer_Array := (4, 9, 3, -2, 0, 7, -5, 1, 6, 8); +begin + Sort (A); + for I in A'Range loop + Put (Integer'Image (A (I)) & " "); + end loop; +end Test_Selection_Sort; diff --git a/Task/Sorting-algorithms-Selection-sort/AutoHotkey/sorting-algorithms-selection-sort.ahk b/Task/Sorting-algorithms-Selection-sort/AutoHotkey/sorting-algorithms-selection-sort.ahk new file mode 100644 index 0000000000..fcf531541a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/AutoHotkey/sorting-algorithms-selection-sort.ahk @@ -0,0 +1,21 @@ +MsgBox % SelecSort("") +MsgBox % SelecSort("xxx") +MsgBox % SelecSort("3,2,1") +MsgBox % SelecSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") + +SelecSort(var) { ; SORT COMMA SEPARATED LIST + StringSplit a, var, `, ; make array, size = a0 + + Loop % a0-1 { + i := A_Index, mn := a%i%, j := m := i + Loop % a0-i { ; find minimum + j++ + If (a%j% < mn) + mn := a%j%, m := j + } + t := a%i%, a%i% := a%m%, a%m% := t ; swap first with minimum + } + Loop % a0 ; construct string from sorted array + sorted .= "," . a%A_Index% + Return SubStr(sorted,2) ; drop leading comma +} diff --git a/Task/Sorting-algorithms-Selection-sort/BBC-BASIC/sorting-algorithms-selection-sort.bbc b/Task/Sorting-algorithms-Selection-sort/BBC-BASIC/sorting-algorithms-selection-sort.bbc new file mode 100644 index 0000000000..42e4d1d773 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/BBC-BASIC/sorting-algorithms-selection-sort.bbc @@ -0,0 +1,9 @@ +DEF PROC_SelectionSort(Size%) +FOR I% = 1 TO Size%-1 + lowest% = I% + FOR J% = (I% + 1) TO Size% + IF data%(J%) < data%(lowest%) lowest% = J% + NEXT J% + IF I%<>lowest% SWAP data%(I%),data%(lowest%) +NEXT I% +ENDPROC diff --git a/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp b/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp new file mode 100644 index 0000000000..74e722815a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp @@ -0,0 +1,8 @@ +#include <algorithm> +#include <iterator> + +template<typename ForwardIterator> +void selectionSort(ForwardIterator begin, ForwardIterator end) { + for(ForwardIterator i = begin; i != end; ++i) + std::iter_swap(i, std::min_element(i, end)); +} diff --git a/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c b/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c new file mode 100644 index 0000000000..7a9e675083 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c @@ -0,0 +1,19 @@ +void selection_sort (int *a, int n) { + int i, j, m, t; + for (i = 0; i < n; i++) { + for (j = i, m = i; j < n; j++) { + if (a[j] < a[m]) + m = j; + } + t = a[i]; + a[i] = a[m]; + a[m] = t; + } +} + +int main () { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + selection_sort(a, n); + return 0; +} diff --git a/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cobol b/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cobol new file mode 100644 index 0000000000..46bcb31363 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cobol @@ -0,0 +1,28 @@ + PERFORM E-SELECTION VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 = WC-SIZE. + +... + + E-SELECTION SECTION. + E-000. + SET WC-LOWEST TO WB-IX-1. + ADD 1 WC-LOWEST GIVING WC-START + + PERFORM F-PASS VARYING WB-IX-2 FROM WC-START BY 1 + UNTIL WB-IX-2 > WC-SIZE. + + IF WB-IX-1 NOT = WC-LOWEST + MOVE WB-ENTRY(WC-LOWEST) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WC-LOWEST) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1). + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-2) < WB-ENTRY(WC-LOWEST) + SET WC-LOWEST TO WB-IX-2. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Selection-sort/Clojure/sorting-algorithms-selection-sort.clj b/Task/Sorting-algorithms-Selection-sort/Clojure/sorting-algorithms-selection-sort.clj new file mode 100644 index 0000000000..1a51e8aa42 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Clojure/sorting-algorithms-selection-sort.clj @@ -0,0 +1,22 @@ +(import 'java.util.ArrayList) + +(defn arr-swap! [#^ArrayList arr i j] + (let [t (.get arr i)] + (doto arr + (.set i (.get arr j)) + (.set j t)))) + +(defn sel-sort! + ([arr] (sel-sort! compare arr)) + ([cmp #^ArrayList arr] + (let [n (.size arr)] + (letfn [(move-min! + [start-i] + (loop [i start-i] + (when (< i n) + (when (< (cmp (.get arr i) (.get arr start-i)) 0) + (arr-swap! arr start-i i)) + (recur (inc i)))))] + (doseq [start-i (range (dec n))] + (move-min! start-i)) + arr)))) diff --git a/Task/Sorting-algorithms-Selection-sort/Common-Lisp/sorting-algorithms-selection-sort.lisp b/Task/Sorting-algorithms-Selection-sort/Common-Lisp/sorting-algorithms-selection-sort.lisp new file mode 100644 index 0000000000..9da07343c5 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Common-Lisp/sorting-algorithms-selection-sort.lisp @@ -0,0 +1,37 @@ +(defun selection-sort-vector (array predicate) + (do ((length (length array)) + (i 0 (1+ i))) + ((eql i length) array) + (do ((mindex i) + (min (aref array i)) + (j i (1+ j))) + ((eql j length) + (rotatef (aref array i) (aref array mindex))) + (when (funcall predicate (aref array j) min) + (setf min (aref array j) + mindex j))))) + +(defun selection-sort-list (list predicate) + (flet ((min-first (list) + (do ((before-min nil) + (min (first list)) + (prev list (rest prev)) + (curr (rest list) (rest curr))) + ((endp curr) + (if (null before-min) list + (let ((min (cdr before-min))) + (rplacd before-min (cdr min)) + (rplacd min list) + min))) + (when (funcall predicate (first curr) min) + (setf before-min prev + min (first curr)))))) + (let ((result (min-first list))) + (do ((head result (rest head))) + ((endp (rest head)) result) + (rplacd head (min-first (rest head))))))) + +(defun selection-sort (sequence predicate) + (etypecase sequence + (list (selection-sort-list sequence predicate)) + (vector (selection-sort-vector sequence predicate)))) diff --git a/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d b/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d new file mode 100644 index 0000000000..714851f538 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/D/sorting-algorithms-selection-sort.d @@ -0,0 +1,63 @@ +import std.stdio, std.algorithm, std.array, std.traits; + +template AreSortableArrayItems(T) { + enum AreSortableArrayItems = isMutable!T && + __traits(compiles, T.init < T.init) && + !isNarrowString!(T[]); +} + +void selectionSort(T)(T[] data) if (AreSortableArrayItems!T) { + foreach (i, ref d; data) + d.swap(data[i .. $].minPos().front); +} unittest { + int[] a0; + selectionSort(a0); + + auto a1 = [1]; + selectionSort(a1); + assert(a1 == [1]); + + auto a2 = ["a", "b"]; + selectionSort(a2); + assert(a2 == ["a", "b"]); + + auto a3 = ["b", "a"]; + selectionSort(a3); + assert(a3 == ["a", "b"]); + + auto a4 = ['a', 'b']; + static assert(!__traits(compiles, selectionSort(a4))); + + dchar[] a5 = ['b', 'a']; + selectionSort(a5); + assert(a5 == "ab"d); + + import std.typecons; + alias Nullable!int N; + auto a6 = [N(2), N(1)]; + selectionSort(a6); // Not nothrow. + assert(a6 == [N(1), N(2)]); + + auto a7 = [1.0+0i, 2.0+0i]; // To be deprecated. + static assert(!__traits(compiles, selectionSort(a7))); + + import std.complex; + auto a8 = [complex(1), complex(2)]; + static assert(!__traits(compiles, selectionSort(a8))); + + static struct F { + int x; + int opCmp(F f) { // Not pure. + return x < f.x ? -1 : (x > f.x ? 1 : 0); + } + } + auto a9 = [F(2), F(1)]; + selectionSort(a9); + assert(a9 == [F(1), F(2)]); +} + +void main() { + auto a = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2]; + a.selectionSort(); + writeln(a); +} diff --git a/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-1.delphi b/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-1.delphi new file mode 100644 index 0000000000..94d5476ccd --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-1.delphi @@ -0,0 +1,49 @@ +program TestSelectionSort; + +{$APPTYPE CONSOLE} + +{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array + +type + TItem = Integer; // declare ordinal type for array item +{$IFDEF DYNARRAY} + TArray = array of TItem; // dynamic array +{$ELSE} + TArray = array[0..15] of TItem; // static array +{$ENDIF} + +procedure SelectionSort(var A: TArray); +var + Item: TItem; + I, J, M: Integer; + +begin + for I:= Low(A) to High(A) - 1 do begin + M:= I; + for J:= I + 1 to High(A) do + if A[J] < A[M] then M:= J; + Item:= A[M]; + A[M]:= A[I]; + A[I]:= Item; + end; +end; + +var + A: TArray; + I: Integer; + +begin +{$IFDEF DYNARRAY} + SetLength(A, 16); +{$ENDIF} + for I:= Low(A) to High(A) do + A[I]:= Random(100); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + SelectionSort(A); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + Readln; +end. diff --git a/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-2.delphi b/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-2.delphi new file mode 100644 index 0000000000..d11a8b3070 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Delphi/sorting-algorithms-selection-sort-2.delphi @@ -0,0 +1,16 @@ +procedure SelectionSort(var S: string); +var + Lowest: Char; + I, J, M, L: Integer; + +begin + L:= Length(S); + for I:= 1 to L - 1 do begin + M:= I; + for J:= I + 1 to L do + if S[J] < S[M] then M:= J; + Lowest:= S[M]; + S[M]:= S[I]; + S[I]:= Lowest; + end; +end; diff --git a/Task/Sorting-algorithms-Selection-sort/E/sorting-algorithms-selection-sort.e b/Task/Sorting-algorithms-Selection-sort/E/sorting-algorithms-selection-sort.e new file mode 100644 index 0000000000..d47f8c9c96 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/E/sorting-algorithms-selection-sort.e @@ -0,0 +1,28 @@ +def selectionSort := { + def cswap(c, a, b) { + def t := c[a] + c[a] := c[b] + c[b] := t + println(c) + } + + def indexOfMin(array, first, last) { + var min := array[first] + var mini := first + for i in (first+1)..last { + if (array[i] < min) { + min := array[i] + mini := i + } + } + return mini + } + + /** Selection sort (in-place). */ + def selectionSort(array) { + def last := (array.size()-1) + for i in 0..(last - 1) { + cswap(array, i, indexOfMin(array, i + 1, last)) + } + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.euphoria b/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.euphoria new file mode 100644 index 0000000000..177b2bb0ac --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.euphoria @@ -0,0 +1,24 @@ +function selection_sort(sequence s) + object tmp + integer m + for i = 1 to length(s) do + m = i + for j = i+1 to length(s) do + if compare(s[j],s[m]) < 0 then + m = j + end if + end for + tmp = s[i] + s[i] = s[m] + s[m] = tmp + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,selection_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Selection-sort/Forth/sorting-algorithms-selection-sort.fth b/Task/Sorting-algorithms-Selection-sort/Forth/sorting-algorithms-selection-sort.fth new file mode 100644 index 0000000000..b534f24427 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Forth/sorting-algorithms-selection-sort.fth @@ -0,0 +1,17 @@ +defer less? ' < is less? + +: least ( start end -- least ) + over cell+ do + i @ over @ less? if drop i then + cell +loop ; +: selection ( array len -- ) + cells over + tuck ( end start end ) + cell- swap do ( end ) + i over least ( end least ) + i @ over @ i ! swap ! + cell +loop drop ; + +create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 , + +array 10 selection +array 10 cells dump diff --git a/Task/Sorting-algorithms-Selection-sort/Fortran/sorting-algorithms-selection-sort.f b/Task/Sorting-algorithms-Selection-sort/Fortran/sorting-algorithms-selection-sort.f new file mode 100644 index 0000000000..ed99785d8c --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Fortran/sorting-algorithms-selection-sort.f @@ -0,0 +1,27 @@ +PROGRAM SELECTION + + IMPLICIT NONE + + INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /) + + WRITE(*,"(A,10I5)") "Unsorted array:", intArray + CALL Selection_sort(intArray) + WRITE(*,"(A,10I5)") "Sorted array :", intArray + +CONTAINS + + SUBROUTINE Selection_sort(a) + INTEGER, INTENT(IN OUT) :: a(:) + INTEGER :: i, minIndex, temp + + DO i = 1, SIZE(a)-1 + minIndex = MINLOC(a(i:), 1) + i - 1 + IF (a(i) > a(minIndex)) THEN + temp = a(i) + a(i) = a(minIndex) + a(minIndex) = temp + END IF + END DO + END SUBROUTINE Selection_sort + +END PROGRAM SELECTION diff --git a/Task/Sorting-algorithms-Selection-sort/GAP/sorting-algorithms-selection-sort.gap b/Task/Sorting-algorithms-Selection-sort/GAP/sorting-algorithms-selection-sort.gap new file mode 100644 index 0000000000..b7a179f61e --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/GAP/sorting-algorithms-selection-sort.gap @@ -0,0 +1,20 @@ +SelectionSort := function(v) + local i, j, k, n, m; + n := Size(v); + for i in [1 .. n] do + k := i; + m := v[i]; + for j in [i + 1 .. n] do + if v[j] < m then + k := j; + m := v[j]; + fi; + od; + v[k] := v[i]; + v[i] := m; + od; +end; + +v := List([1 .. 100], n -> Random([1 .. 100])); +SelectionSort(v); +v; diff --git a/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-1.go b/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-1.go new file mode 100644 index 0000000000..1f710c3e55 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-1.go @@ -0,0 +1,26 @@ +package main + +import "fmt" + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} + +func main() { + fmt.Println("before:", a) + selectionSort(a) + fmt.Println("after: ", a) +} + +func selectionSort(a []int) { + last := len(a) - 1 + for i := 0; i < last; i++ { + aMin := a[i] + iMin := i + for j := i + 1; j < len(a); j++ { + if a[j] < aMin { + aMin = a[j] + iMin = j + } + } + a[i], a[iMin] = aMin, a[i] + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-2.go b/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-2.go new file mode 100644 index 0000000000..ccc8d1f07a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Go/sorting-algorithms-selection-sort-2.go @@ -0,0 +1,27 @@ +package main + +import ( + "sort" + "fmt" +) + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} + +func main() { + fmt.Println("before:", a) + selectionSort(sort.IntSlice(a)) + fmt.Println("after: ", a) +} + +func selectionSort(a sort.Interface) { + last := a.Len() - 1 + for i := 0; i < last; i++ { + iMin := i + for j := i + 1; j < a.Len(); j++ { + if a.Less(j, iMin) { + iMin = j + } + } + a.Swap(i, iMin) + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs new file mode 100644 index 0000000000..23afec4ad8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs @@ -0,0 +1,7 @@ +import Data.List (unfoldr) + +selectionSort = unfoldr selectionSort' where + selectionSort' [] = Nothing + selectionSort' (first:lst) = Just $ foldl f (first, []) lst + f (small, output) x | x < small = (x, small:output) + | otherwise = (small, x:output) diff --git a/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.haxe b/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.haxe new file mode 100644 index 0000000000..cd3a659d14 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.haxe @@ -0,0 +1,18 @@ +static function selectionSort(arr:Array<Int>) { + var len = arr.length; + for (index in 0...len) + { + var minIndex = index; + for (remainingIndex in (index+1)...len) + { + if (arr[minIndex] > arr[remainingIndex]) { + minIndex = remainingIndex; + } + } + if (index != minIndex) { + var temp = arr[index]; + arr[index] = arr[minIndex]; + arr[minIndex] = temp; + } + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Icon/sorting-algorithms-selection-sort.icon b/Task/Sorting-algorithms-Selection-sort/Icon/sorting-algorithms-selection-sort.icon new file mode 100644 index 0000000000..4618af84a0 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Icon/sorting-algorithms-selection-sort.icon @@ -0,0 +1,17 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + + +procedure selectionsort(X,op) #: return sorted list ascending(or descending) +local i,m + + op := sortop(op,X) # select how and what we sort + every i := 1 to *X-1 do { + m := i + every j := i + 1 to *X do + if op(X[j],X[m]) then m := j # find X that belongs @i low (or high) + X[m ~= i] :=: X[m] + } + return X +end diff --git a/Task/Sorting-algorithms-Selection-sort/Io/sorting-algorithms-selection-sort.io b/Task/Sorting-algorithms-Selection-sort/Io/sorting-algorithms-selection-sort.io new file mode 100644 index 0000000000..6966b3f4e8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Io/sorting-algorithms-selection-sort.io @@ -0,0 +1,10 @@ +List do ( + selectionSortInPlace := method( + size repeat(idx, + swapIndices(idx, indexOf(slice(idx, size) min)) + ) + ) +) + +l := list(-1, 4, 2, -9) +l selectionSortInPlace println # ==> list(-9, -1, 2, 4) diff --git a/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-1.j b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-1.j new file mode 100644 index 0000000000..2f00ea9d35 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-1.j @@ -0,0 +1,9 @@ +selectionSort=: verb define + data=. y + for_xyz. y do. + temp=. xyz_index }. data + nvidx=. xyz_index + temp i. <./ temp + data=. ((xyz_index, nvidx) { data) (nvidx, xyz_index) } data + end. + data +) diff --git a/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-2.j b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-2.j new file mode 100644 index 0000000000..3ce1594ae8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-2.j @@ -0,0 +1,2 @@ +ix=: C.~ <@~.@(0, (i. <./)) +ss1=: ({. , $:@}.)@ix^:(*@#) diff --git a/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-3.j b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-3.j new file mode 100644 index 0000000000..1d32f8d04c --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/J/sorting-algorithms-selection-sort-3.j @@ -0,0 +1,6 @@ + [data=. 6 15 19 12 14 19 0 17 0 14 +6 15 19 12 14 19 0 17 0 14 + selectionSort data +0 0 6 12 14 14 15 17 19 19 + ss1 data +0 0 6 12 14 14 15 17 19 19 diff --git a/Task/Sorting-algorithms-Selection-sort/Java/sorting-algorithms-selection-sort.java b/Task/Sorting-algorithms-Selection-sort/Java/sorting-algorithms-selection-sort.java new file mode 100644 index 0000000000..68172d1ef7 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Java/sorting-algorithms-selection-sort.java @@ -0,0 +1,15 @@ +public static void sort(int[] nums){ + for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ + int smallest = Integer.MAX_VALUE; + int smallestAt = currentPlace+1; + for(int check = currentPlace; check<nums.length;check++){ + if(nums[check]<smallest){ + smallestAt = check; + smallest = nums[check]; + } + } + int temp = nums[currentPlace]; + nums[currentPlace] = nums[smallestAt]; + nums[smallestAt] = temp; + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Liberty-BASIC/sorting-algorithms-selection-sort.liberty b/Task/Sorting-algorithms-Selection-sort/Liberty-BASIC/sorting-algorithms-selection-sort.liberty new file mode 100644 index 0000000000..1018edd2c8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Liberty-BASIC/sorting-algorithms-selection-sort.liberty @@ -0,0 +1,31 @@ + itemCount = 20 + dim A(itemCount) + for i = 1 to itemCount + A(i) = int(rnd(1) * 100) + next i + + print "Before Sort" + gosub [printArray] + +'--- Selection sort algorithm + for i = 1 to itemCount-1 + jMin = i + for j = i+1 to itemCount + if A(j) < A(jMin) then jMin = j + next + tmp = A(i) + A(i) = A(jMin) + A(jMin) = tmp + next +'--- end of (Selection sort algorithm) + + print "After Sort" + gosub [printArray] +end + +[printArray] + for i = 1 to itemCount + print using("###", A(i)); + next i + print +return diff --git a/Task/Sorting-algorithms-Selection-sort/Lua/sorting-algorithms-selection-sort.lua b/Task/Sorting-algorithms-Selection-sort/Lua/sorting-algorithms-selection-sort.lua new file mode 100644 index 0000000000..81c755dec0 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Lua/sorting-algorithms-selection-sort.lua @@ -0,0 +1,20 @@ +function SelectionSort( f ) + for k = 1, #f-1 do + local idx = k + for i = k+1, #f do + if f[i] < f[idx] then + idx = i + end + end + f[k], f[idx] = f[idx], f[k] + end +end + + +f = { 15, -3, 0, -1, 5, 4, 5, 20, -8 } + +SelectionSort( f ) + +for i in next, f do + print( f[i] ) +end diff --git a/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-1.m b/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-1.m new file mode 100644 index 0000000000..5909205b61 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-1.m @@ -0,0 +1,24 @@ +function list = selectionSort(list) + + listSize = numel(list); + + for i = (1:listSize-1) + + minElem = list(i); + minIndex = i; + + %This for loop can be vectorized, but there will be no significant + %increase in sorting efficiency. + for j = (i:listSize) + if list(j) <= minElem + minElem = list(j); + minIndex = j; + end + end + + if i ~= minIndex + list([minIndex i]) = list([i minIndex]); %Swap + end + + end %for +end %selectionSort diff --git a/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-2.m b/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-2.m new file mode 100644 index 0000000000..435bb66e99 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/MATLAB/sorting-algorithms-selection-sort-2.m @@ -0,0 +1,5 @@ +>> selectionSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Selection-sort/MAXScript/sorting-algorithms-selection-sort.maxscript b/Task/Sorting-algorithms-Selection-sort/MAXScript/sorting-algorithms-selection-sort.maxscript new file mode 100644 index 0000000000..4cf01d130f --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/MAXScript/sorting-algorithms-selection-sort.maxscript @@ -0,0 +1,20 @@ +fn selectionSort arr = +( + local min = undefined + for i in 1 to arr.count do + ( + min = i + for j in i+1 to arr.count do + ( + if arr[j] < arr[min] then + ( + min = j + ) + ) + swap arr[i] arr[min] + ) + arr +) + +data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8) +print data diff --git a/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-1.math b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-1.math new file mode 100644 index 0000000000..e6d8bd9df6 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-1.math @@ -0,0 +1,12 @@ +SelectSort[x_List] := Module[{n = 1, temp, xi = x, j}, + While[n <= Length@x, + temp = xi[[n]]; + For[j = n, j <= Length@x, j++, + If[xi[[j]] < temp, temp = xi[[j]]]; + ]; + xi[[n ;;]] = {temp}~Join~ + Delete[xi[[n ;;]], First@Position[xi[[n ;;]], temp] ]; + n++; + ]; + xi + ] diff --git a/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-2.math b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-2.math new file mode 100644 index 0000000000..5f84c6e17a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-2.math @@ -0,0 +1 @@ +SelectSort2[x_List]:= Flatten[{Min@x, If[Length@x > 1, SelectSort2@Drop[x, First@Position[x, Min@x]], {}] }]; diff --git a/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-3.math b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-3.math new file mode 100644 index 0000000000..ec38f2cb6f --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Mathematica/sorting-algorithms-selection-sort-3.math @@ -0,0 +1,8 @@ +{And @@ Table[l = RandomInteger[150, RandomInteger[1000]]; + Through[And[Length@# == Length@SelectSort@# &, OrderedQ@SelectSort@# &]@l], + {RandomInteger[150]}], + Block[{$RecursionLimit = Infinity}, + And @@ Table[l = RandomInteger[150, RandomInteger[1000]]; + Through[And[Length@# == Length@SelectSort2@# &, OrderedQ@SelectSort2@# &]@l], + {RandomInteger[150]}] + ]} diff --git a/Task/Sorting-algorithms-Selection-sort/Maxima/sorting-algorithms-selection-sort.maxima b/Task/Sorting-algorithms-Selection-sort/Maxima/sorting-algorithms-selection-sort.maxima new file mode 100644 index 0000000000..83f89be07a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Maxima/sorting-algorithms-selection-sort.maxima @@ -0,0 +1,14 @@ +selection_sort(v) := block([k, m, n], +n: length(v), +for i: 1 thru n do ( + k: i, + m: v[i], + for j: i + 1 thru n do + if v[j] < m then (k: j, m: v[j]), + v[k]: v[i], + v[i]: m +))$ + +v: makelist(random(199) - 99, i, 1, 10); /* [52, -85, 41, -70, -59, 88, 19, 80, 90, 44] */ +selection_sort(v)$ +v; /* [-85, -70, -59, 19, 41, 44, 52, 80, 88, 90] */ diff --git a/Task/Sorting-algorithms-Selection-sort/Nemerle/sorting-algorithms-selection-sort.nemerle b/Task/Sorting-algorithms-Selection-sort/Nemerle/sorting-algorithms-selection-sort.nemerle new file mode 100644 index 0000000000..26ef88bc54 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Nemerle/sorting-algorithms-selection-sort.nemerle @@ -0,0 +1,27 @@ +using System; +using System.Console; + +module Selection +{ + public static Sort[T](this a : array[T]) : void + where T : IComparable + { + mutable k = 0; + def lastindex = a.Length - 1; + + foreach (i in [0 .. lastindex]) + { + k = i; + foreach (j in [i .. lastindex]) + when (a[j].CompareTo(a[k]) < 0) k = j; + a[i] <-> a[k]; + } + } + + Main() : void + { + def arr = array[6, 2, 8, 3, 9, 4, 7, 3, 9, 1]; + arr.Sort(); + foreach (i in arr) Write($"$i "); + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/NetRexx/sorting-algorithms-selection-sort.netrexx b/Task/Sorting-algorithms-Selection-sort/NetRexx/sorting-algorithms-selection-sort.netrexx new file mode 100644 index 0000000000..7eeea9a9ab --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/NetRexx/sorting-algorithms-selection-sort.netrexx @@ -0,0 +1,56 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] + +lists = [ - + placesList - + , selectionSort(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method selectionSort(a = String[]) public constant binary returns String[] + + rl = String[a.length] + al = List selectionSort(Arrays.asList(a)) + al.toArray(rl) + + return rl + +method selectionSort(a = List) public constant binary returns ArrayList + + ra = ArrayList(a) + n = ra.size + + iPos = int + iMin = int + + loop iPos = 0 to n - 1 + iMin = iPos + loop i_ = iPos + 1 to n - 1 + if (Comparable ra.get(i_)).compareTo(Comparable ra.get(iMin)) < 0 then do + iMin = i_ + end + end i_ + if iMin \= iPos then do + swap = ra.get(iPos) + ra.set(iPos, ra.get(iMin)) + ra.set(iMin, swap) + end + end iPos + + return ra diff --git a/Task/Sorting-algorithms-Selection-sort/OCaml/sorting-algorithms-selection-sort.ocaml b/Task/Sorting-algorithms-Selection-sort/OCaml/sorting-algorithms-selection-sort.ocaml new file mode 100644 index 0000000000..239f892f02 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/OCaml/sorting-algorithms-selection-sort.ocaml @@ -0,0 +1,9 @@ +let rec selection_sort = function + [] -> [] + | first::lst -> + let rec select_r small output = function + [] -> small :: selection_sort output + | x::xs when x < small -> select_r x (small::output) xs + | x::xs -> select_r small (x::output) xs + in + select_r first [] lst diff --git a/Task/Sorting-algorithms-Selection-sort/Oz/sorting-algorithms-selection-sort.oz b/Task/Sorting-algorithms-Selection-sort/Oz/sorting-algorithms-selection-sort.oz new file mode 100644 index 0000000000..c40ffc93aa --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Oz/sorting-algorithms-selection-sort.oz @@ -0,0 +1,30 @@ +declare + proc {SelectionSort Arr} + proc {Swap K L} + Arr.K := (Arr.L := Arr.K) + end + Low = {Array.low Arr} + High = {Array.high Arr} + in + %% for every index I of the array + for I in Low..High do + %% find the index of the minimum element + %% with an index >= I + Min = {NewCell Arr.I} + MinIndex = {NewCell I} + in + for J in I..High do + if Arr.J < @Min then + Min := Arr.J + MinIndex := J + end + end + %% and put that minimum element to the left + {Swap @MinIndex I} + end + end + + A = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)} +in + {SelectionSort A} + {Show {Array.toRecord unit A}} diff --git a/Task/Sorting-algorithms-Selection-sort/PARI-GP/sorting-algorithms-selection-sort.pari b/Task/Sorting-algorithms-Selection-sort/PARI-GP/sorting-algorithms-selection-sort.pari new file mode 100644 index 0000000000..4f170a9124 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PARI-GP/sorting-algorithms-selection-sort.pari @@ -0,0 +1,12 @@ +selectionSort(v)={ + for(i=1,#v-1, + my(mn=i,t); + for(j=i+1,#v, + if(v[j]<v[mn],mn=j) + ); + t=v[mn]; + v[mn]=v[i]; + v[i]=t + ); + v +}; diff --git a/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-1.php b/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-1.php new file mode 100644 index 0000000000..6cd98a9cf0 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-1.php @@ -0,0 +1,12 @@ +function selection_sort(&$arr) { + $n = count($arr); + for($i = 0; $i < count($arr); $i++) { + $min = $i; + for($j = $i + 1; $j < $n; $j++){ + if($arr[$j] < $arr[$min]){ + $min = $j; + } + } + list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-2.php b/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-2.php new file mode 100644 index 0000000000..3b2cfc6ab7 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PHP/sorting-algorithms-selection-sort-2.php @@ -0,0 +1,9 @@ +function selectionsort($arr,$result=array()){ + if(count($arr) == 0){ + return $result; + } + $nresult = $result; + $nresult[] = min($arr); + unset($arr[array_search(min($arr),$arr)]); + return selectionsort($arr,$nresult); +} diff --git a/Task/Sorting-algorithms-Selection-sort/Perl-6/sorting-algorithms-selection-sort.pl6 b/Task/Sorting-algorithms-Selection-sort/Perl-6/sorting-algorithms-selection-sort.pl6 new file mode 100644 index 0000000000..c6fce64243 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Perl-6/sorting-algorithms-selection-sort.pl6 @@ -0,0 +1,11 @@ +sub selection_sort ( @a is copy ) { + for 0 ..^ @a.end -> $i { + my $min = [ $i+1 .. @a.end ].min: { @a[$_] }; + @a[$i, $min] = @a[$min, $i] if @a[$i] > @a[$min]; + } + return @a; +} + +my @data = 22, 7, 2, -5, 8, 4; +say 'input = ' ~ @data; +say 'output = ' ~ @data.&selection_sort; diff --git a/Task/Sorting-algorithms-Selection-sort/Perl/sorting-algorithms-selection-sort.pl b/Task/Sorting-algorithms-Selection-sort/Perl/sorting-algorithms-selection-sort.pl new file mode 100644 index 0000000000..46e9d0475a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Perl/sorting-algorithms-selection-sort.pl @@ -0,0 +1,7 @@ +sub selection_sort + {my @a = @_; + foreach my $i (0 .. $#a - 1) + {my $min = $i + 1; + $a[$_] < $a[$min] and $min = $_ foreach $min .. $#a; + $a[$i] > $a[$min] and @a[$i, $min] = @a[$min, $i];} + return @a;} diff --git a/Task/Sorting-algorithms-Selection-sort/PicoLisp/sorting-algorithms-selection-sort.l b/Task/Sorting-algorithms-Selection-sort/PicoLisp/sorting-algorithms-selection-sort.l new file mode 100644 index 0000000000..ccc85ea251 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PicoLisp/sorting-algorithms-selection-sort.l @@ -0,0 +1,5 @@ +(de selectionSort (Lst) + (map + '((L) (and (cdr L) (xchg L (member (apply min @) L)))) + Lst ) + Lst ) diff --git a/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.psh b/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.psh new file mode 100644 index 0000000000..e5e878a874 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.psh @@ -0,0 +1,20 @@ +Function SelectionSort( [Array] $data ) +{ + $datal=$data.length-1 + 0..( $datal - 1 ) | ForEach-Object { + $min = $data[ $_ ] + $mini = $_ + ( $_ + 1 )..$datal | ForEach-Object { + if( $data[ $_ ] -lt $min ) { + $min = $data[ $_ ] + $mini = $_ + } + } + $temp = $data[ $_ ] + $data[ $_ ] = $min + $data[ $mini ] = $temp + } + $data +} + +$l = 100; SelectionSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) ) diff --git a/Task/Sorting-algorithms-Selection-sort/PureBasic/sorting-algorithms-selection-sort.purebasic b/Task/Sorting-algorithms-Selection-sort/PureBasic/sorting-algorithms-selection-sort.purebasic new file mode 100644 index 0000000000..2a630c2668 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PureBasic/sorting-algorithms-selection-sort.purebasic @@ -0,0 +1,14 @@ +Procedure selectionSort(Array a(1)) + Protected i, j, lastIndex, minIndex + + lastIndex = ArraySize(a()) + For i = 0 To lastIndex - 1 + minIndex = i + For j = i + 1 To lastIndex + If a(minIndex) > a(j) + minIndex = j + EndIf + Next + Swap a(minIndex), a(i) + Next +EndProcedure diff --git a/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py b/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py new file mode 100644 index 0000000000..efa4588b0c --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py @@ -0,0 +1,5 @@ +def selectionSort(lst): + for i in range(0,len(lst)-1): + mn = min(range(i,len(lst)), key=lst.__getitem__) + lst[i],lst[mn] = lst[mn],lst[i] + return lst diff --git a/Task/Sorting-algorithms-Selection-sort/Qi/sorting-algorithms-selection-sort.qi b/Task/Sorting-algorithms-Selection-sort/Qi/sorting-algorithms-selection-sort.qi new file mode 100644 index 0000000000..0af462342d --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Qi/sorting-algorithms-selection-sort.qi @@ -0,0 +1,10 @@ +(define select-r + Small [] Output -> [Small | (selection-sort Output)] + Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small) + Small [X|Xs] Output -> (select-r Small Xs [X|Output])) + +(define selection-sort + [] -> [] + [First|Lst] -> (select-r First Lst [])) + +(selection-sort [8 7 4 3 2 0 9 1 5 6]) diff --git a/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-1.r b/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-1.r new file mode 100644 index 0000000000..331c139103 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-1.r @@ -0,0 +1,11 @@ +selectionsort.loop <- function(x) +{ + lenx <- length(x) + for(i in seq_along(x)) + { + mini <- (i - 1) + which.min(x[i:lenx]) + start_ <- seq_len(i-1) + x <- c(x[start_], x[mini], x[-c(start_, mini)]) + } + x +} diff --git a/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-2.r b/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-2.r new file mode 100644 index 0000000000..caa6fd1efa --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/R/sorting-algorithms-selection-sort-2.r @@ -0,0 +1,8 @@ +selectionsort.rec <- function(x) +{ + if(length(x) > 1) + { + mini <- which.min(x) + c(x[mini], selectionsort(x[-mini])) + } else x +} diff --git a/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx b/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx new file mode 100644 index 0000000000..9f6c830407 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx @@ -0,0 +1,35 @@ +/*REXX program sorts an array using the selection-sort method. */ +@.='' /*assign a default value to stem.*/ +@.1='---The seven hills of Rome:---' +@.2='==============================' +@.3='Caelian' +@.4='Palatine' +@.5='Capitoline' +@.6='Virminal' +@.7='Esquiline' +@.8='Quirinal' +@.9='Aventine' + do items=1 until @.items=='' /*find # items.*/ + end +items=items-1 /*adjust the # of items slightly.*/ +call show@ 'before sort' /*show the before array elements,*/ +call selectionSort items /*invoke the selection sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SELECTIONSORT subroutine────────────*/ +selectionSort: procedure expose @.; parse arg n + + do j=1 for n-1 + _=@.j; p=j; do k=j+1 to n + if @.k<_ then do; _=@.k; p=k; end + end /*k*/ + if p==j then iterate + _=@.j; @.j=@.p; @.p=_ + end /*j*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: w=length(items); do i=1 for items + say 'element' right(i,w) arg(1)":" @.i + end /*i*/ +say copies('─',79) /*show a nice separator line. */ +return diff --git a/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb b/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb new file mode 100644 index 0000000000..5b3430c1e5 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb @@ -0,0 +1,18 @@ +class Array + def selectionsort! + 0.upto(length - 2) do |i| + (min_idx = i + 1).upto(length - 1) do |j| + if self[j] < self[min_idx] + min_idx = j + end + end + if self[i] > self[min_idx] + self[i], self[min_idx] = self[min_idx], self[i] + end + end + self + end +end +ary = [7,6,5,9,8,4,3,1,2,0] +ary.selectionsort! +# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Sorting-algorithms-Selection-sort/Run-BASIC/sorting-algorithms-selection-sort.run b/Task/Sorting-algorithms-Selection-sort/Run-BASIC/sorting-algorithms-selection-sort.run new file mode 100644 index 0000000000..4ee8501fe2 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Run-BASIC/sorting-algorithms-selection-sort.run @@ -0,0 +1,21 @@ +siz = 10 +dim srdData(siz) +for i = 1 to siz +srtData(i) = rnd(0) * 100 +next i + +FOR i = 1 TO siz-1 + lo = i + FOR j = (i + 1) TO siz + IF srtData(j) < srtData(lo) lo = j + NEXT j + if i <> lo then + temp = srtData(i) + srtData(i) = srtData(lo) + srtData(lo) = temp + end if +NEXT i + +for i = 1 to siz +print i;chr$(9);srtData(i) +next i diff --git a/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-1.scala b/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-1.scala new file mode 100644 index 0000000000..2ca0dffbd3 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-1.scala @@ -0,0 +1,6 @@ +def swap(a: Array[Int], i1: Int, i2: Int) = { val tmp = a(i1); a(i1) = a(i2); a(i2) = tmp } + +def selectionSort(a: Array[Int]) = + for (i <- 0 until a.size - 1) + swap(a, i, (i + 1 until a.size).foldLeft(i)((currMin, index) => + if (a(index) < a(currMin)) index else currMin)) diff --git a/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-2.scala b/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-2.scala new file mode 100644 index 0000000000..ef7b2cd802 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Scala/sorting-algorithms-selection-sort-2.scala @@ -0,0 +1,3 @@ +def selectionSort(a: Array[Int]) = for (i <- 0 until a.size - 1) ( + { (i1: Int, i2: Int) => val tmp = a(i1); a(i1) = a(i2); a(i2) = tmp } + ) (i, (i + 1 until a.size).foldLeft(i)((currMin, index) => if (a(index) < a(currMin)) index else currMin) ) diff --git a/Task/Sorting-algorithms-Selection-sort/Seed7/sorting-algorithms-selection-sort.seed7 b/Task/Sorting-algorithms-Selection-sort/Seed7/sorting-algorithms-selection-sort.seed7 new file mode 100644 index 0000000000..38d8ecef57 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Seed7/sorting-algorithms-selection-sort.seed7 @@ -0,0 +1,19 @@ +const proc: selectionSort (inout array elemType: arr) is func + local + var integer: i is 0; + var integer: j is 0; + var integer: min is 0; + var elemType: help is elemType.value; + begin + for i range 1 to length(arr) - 1 do + min := i; + for j range i + 1 to length(arr) do + if arr[j] < arr[min] then + min := j; + end if; + end for; + help := arr[min]; + arr[min] := arr[i]; + arr[i] := help; + end for; + end func; diff --git a/Task/Sorting-algorithms-Selection-sort/Standard-ML/sorting-algorithms-selection-sort.ml b/Task/Sorting-algorithms-Selection-sort/Standard-ML/sorting-algorithms-selection-sort.ml new file mode 100644 index 0000000000..f403fff768 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Standard-ML/sorting-algorithms-selection-sort.ml @@ -0,0 +1,13 @@ +fun selection_sort [] = [] + | selection_sort (first::lst) = + let + val (small, output) = foldl + (fn (x, (small, output)) => + if x < small then + (x, small::output) + else + (small, x::output) + ) (first, []) lst + in + small :: selection_sort output + end diff --git a/Task/Sorting-algorithms-Selection-sort/Tcl/sorting-algorithms-selection-sort.tcl b/Task/Sorting-algorithms-Selection-sort/Tcl/sorting-algorithms-selection-sort.tcl new file mode 100644 index 0000000000..c287793e52 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Tcl/sorting-algorithms-selection-sort.tcl @@ -0,0 +1,20 @@ +package require Tcl 8.5 +package require struct::list + +proc selectionsort {A} { + set len [llength $A] + for {set i 0} {$i < $len - 1} {incr i} { + set min_idx [expr {$i + 1}] + for {set j $min_idx} {$j < $len} {incr j} { + if {[lindex $A $j] < [lindex $A $min_idx]} { + set min_idx $j + } + } + if {[lindex $A $i] > [lindex $A $min_idx]} { + struct::list swap A $i $min_idx + } + } + return $A +} + +puts [selectionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-1.ursala b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-1.ursala new file mode 100644 index 0000000000..2cc0819360 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-1.ursala @@ -0,0 +1,3 @@ +#import std + +selection_sort "p" = @iNX ~&l->rx ^(gldif ==,~&r)^/~&l ^|C/"p"$- ~& diff --git a/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-2.ursala b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-2.ursala new file mode 100644 index 0000000000..ee738e4227 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-2.ursala @@ -0,0 +1 @@ +selection_sort "p" = ~&itB^?a\~&a ^|JahPfatPRC/~& ~=-~BrhPltPClhPrtPCTlrTQrS^D/"p"$- ~& diff --git a/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-3.ursala b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-3.ursala new file mode 100644 index 0000000000..e4d51e5389 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ursala/sorting-algorithms-selection-sort-3.ursala @@ -0,0 +1,4 @@ +#import nat +#cast %nL + +example = selection_sort(nleq) <294,263,240,473,596,392,621,348,220,815> diff --git a/Task/Sorting-algorithms-Selection-sort/VBA/sorting-algorithms-selection-sort.vba b/Task/Sorting-algorithms-Selection-sort/VBA/sorting-algorithms-selection-sort.vba new file mode 100644 index 0000000000..4f1731c4c2 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/VBA/sorting-algorithms-selection-sort.vba @@ -0,0 +1,18 @@ +sub swap( byref a, byref b) + dim tmp + tmp = a + a = b + b = tmp +end sub + +function selectionSort (a) + for i = 0 to ubound(a) + k = i + for j=i+1 to ubound(a) + if a(j) < a(i) then + swap a(i), a(j) + end if + next + next + selectionSort = a +end function diff --git a/Task/Sorting-algorithms-Selection-sort/XPL0/sorting-algorithms-selection-sort.xpl0 b/Task/Sorting-algorithms-Selection-sort/XPL0/sorting-algorithms-selection-sort.xpl0 new file mode 100644 index 0000000000..7bff840e37 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/XPL0/sorting-algorithms-selection-sort.xpl0 @@ -0,0 +1,26 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated strings + +proc SelSort(A, N); \Selection sort +char A; \address of array +int N; \number of elements in array (size) +int I, J, S, JS, T; +[for I:= 0 to N-2 do + [S:= (~0)>>1; + for J:= I to N-1 do \find smallest element + if A(J) < S then [S:= A(J); JS:= J]; + T:= A(I); A(I):= A(JS); A(JS):= T; + ]; +]; + +func StrLen(Str); \Return number of characters in an ASCIIZ string +char Str; +int I; +for I:= 0 to -1>>1-1 do + if Str(I) = 0 then return I; + +char Str; +[Str:= "Pack my box with five dozen liquor jugs."; +SelSort(Str, StrLen(Str)); +Text(0, Str); CrLf(0); +] diff --git a/Task/Sorting-algorithms-Shell-sort/0DESCRIPTION b/Task/Sorting-algorithms-Shell-sort/0DESCRIPTION new file mode 100644 index 0000000000..427e510d99 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/0DESCRIPTION @@ -0,0 +1,3 @@ +{{Sorting Algorithm}} +In this task, the goal is to sort an array of elements using the [[wp:Shell sort|Shell sort]] algorithm, a diminishing increment sort. The Shell sort is named after its inventor, Donald Shell, who published the algorithm in 1959. Shellsort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. +[http://www.cs.princeton.edu/~rs/shell/] Other good sequences are found at the [https://oeis.org/search?q=shell+sort On-Line Encyclopedia of Integer Sequences]. diff --git a/Task/Sorting-algorithms-Shell-sort/1META.yaml b/Task/Sorting-algorithms-Shell-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg new file mode 100644 index 0000000000..3247a4d4b5 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/ALGOL-68/sorting-algorithms-shell-sort.alg @@ -0,0 +1,24 @@ +MODE TYPE = CHAR; + +PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:( + INT inc := ( UPB seq + LWB seq + 1 ) OVER 2; + WHILE inc NE 0 DO + FOR index FROM LWB seq TO UPB seq DO + INT i := index; + TYPE el = seq[i]; + WHILE ( i - LWB seq >= inc | seq[i - inc] > el | FALSE ) DO + seq[i] := seq[i - inc]; + i -:= inc + OD; + seq[i] := el + OD; + inc := IF inc = 2 THEN 1 ELSE ENTIER(inc * 5 / 11) FI + OD; + seq +); + +PROC shell sort = ([]TYPE seq)[]TYPE: + in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq); + +[]TYPE char array data = "big fjords vex quick waltz nymph"; +print((shell sort(char array data), new line)) diff --git a/Task/Sorting-algorithms-Shell-sort/AWK/sorting-algorithms-shell-sort.awk b/Task/Sorting-algorithms-Shell-sort/AWK/sorting-algorithms-shell-sort.awk new file mode 100644 index 0000000000..ac244c08cc --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/AWK/sorting-algorithms-shell-sort.awk @@ -0,0 +1,25 @@ +{ + line[NR] = $0 +} +END { # sort it with shell sort + increment = int(NR / 2) + while ( increment > 0 ) { + for(i=increment+1; i <= NR; i++) { + j = i + temp = line[i] + while ( (j >= increment+1) && (line[j-increment] > temp) ) { + line[j] = line[j-increment] + j -= increment + } + line[j] = temp + } + if ( increment == 2 ) + increment = 1 + else + increment = int(increment*5/11) + } + #print it + for(i=1; i <= NR; i++) { + print line[i] + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/ActionScript/sorting-algorithms-shell-sort.as b/Task/Sorting-algorithms-Shell-sort/ActionScript/sorting-algorithms-shell-sort.as new file mode 100644 index 0000000000..378eaefeba --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/ActionScript/sorting-algorithms-shell-sort.as @@ -0,0 +1,18 @@ +function shellSort(data:Array):Array +{ + var inc:uint = data.length/2; + while(inc > 0) + { + for(var i:uint = inc; i< data.length; i++) + { + var tmp:Object = data[i]; + for(var j:uint = i; j >= inc && data[j-inc] > tmp; j -=inc) + { + data[j] = data[j-inc]; + } + data[j] = tmp; + } + inc = Math.round(inc/2.2); + } + return data; +} diff --git a/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.ada b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.ada new file mode 100644 index 0000000000..fbcc30e0ee --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.ada @@ -0,0 +1,7 @@ +generic + type Element_Type is digits <>; + type Index_Type is (<>); + type Array_Type is array(Index_Type range <>) of Element_Type; +package Shell_Sort is + procedure Sort(Item : in out Array_Type); +end Shell_Sort; diff --git a/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.ada b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.ada new file mode 100644 index 0000000000..6a2af6e13b --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.ada @@ -0,0 +1,30 @@ +package body Shell_Sort is + + ---------- + -- Sort -- + ---------- + + procedure Sort (Item : in out Array_Type) is + Increment : Natural := Index_Type'Pos(Item'Last) / 2; + J : Index_Type; + Temp : Element_Type; + begin + while Increment > 0 loop + for I in Index_Type'Val(Increment) .. Item'Last loop + J := I; + Temp := Item(I); + while J > Index_Type'val(Increment) and then Item (Index_Type'Val(Index_Type'Pos(J) - Increment)) > Temp loop + Item(J) := Item (Index_Type'Val(Index_Type'Pos(J) - Increment)); + J := Index_Type'Val(Index_Type'Pos(J) - Increment); + end loop; + Item(J) := Temp; + end loop; + if Increment = 2 then + Increment := 1; + else + Increment := Increment * 5 / 11; + end if; + end loop; + end Sort; + +end Shell_Sort; diff --git a/Task/Sorting-algorithms-Shell-sort/AutoHotkey/sorting-algorithms-shell-sort.ahk b/Task/Sorting-algorithms-Shell-sort/AutoHotkey/sorting-algorithms-shell-sort.ahk new file mode 100644 index 0000000000..35759cfe5f --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/AutoHotkey/sorting-algorithms-shell-sort.ahk @@ -0,0 +1,20 @@ +MsgBox % ShellSort("") +MsgBox % ShellSort("xxx") +MsgBox % ShellSort("3,2,1") +MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z") +MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10") + +ShellSort(var) { ; SORT COMMA SEPARATED LIST + StringSplit a, var, `, ; make array (length = a0) + inc := a0 + While inc:=round(inc/2.2) ; geometric gap sequence + Loop % a0-inc { ; insertion sort: + i := A_Index+inc, t := a%i%, j := i, k := j-inc + While j > inc && a%k% > t + a%j% := a%k%, j := k, k -= inc + a%j% := t + } + Loop % a0 ; construct string from sorted array + s .= "," . a%A_Index% + Return SubStr(s,2) ; drop leading comma +} diff --git a/Task/Sorting-algorithms-Shell-sort/BBC-BASIC/sorting-algorithms-shell-sort.bbc b/Task/Sorting-algorithms-Shell-sort/BBC-BASIC/sorting-algorithms-shell-sort.bbc new file mode 100644 index 0000000000..7c130fbffb --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/BBC-BASIC/sorting-algorithms-shell-sort.bbc @@ -0,0 +1,25 @@ + DIM test(9) + test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCshellsort(test(), 10) + FOR i% = 0 TO 9 + PRINT test(i%) ; + NEXT + PRINT + END + + DEF PROCshellsort(a(), n%) + LOCAL h%, i%, j%, k + h% = n% + WHILE h% + IF h% = 2 h% = 1 ELSE h% DIV= 2.2 + FOR i% = h% TO n% - 1 + k = a(i%) + j% = i% + WHILE j% >= h% AND k < a(ABS(j% - h%)) + a(j%) = a(j% - h%) + j% -= h% + ENDWHILE + a(j%) = k + NEXT + ENDWHILE + ENDPROC diff --git a/Task/Sorting-algorithms-Shell-sort/BCPL/sorting-algorithms-shell-sort.bcpl b/Task/Sorting-algorithms-Shell-sort/BCPL/sorting-algorithms-shell-sort.bcpl new file mode 100644 index 0000000000..d797ca0c73 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/BCPL/sorting-algorithms-shell-sort.bcpl @@ -0,0 +1,49 @@ +GET "libhdr" + +LET shellsort(v, upb) BE +{ LET m = 1 + UNTIL m>upb DO m := m*3 + 1 // Find first suitable value in the + // series: 1, 4, 13, 40, 121, 364, ... + { m := m/3 + FOR i = m+1 TO upb DO + { LET vi = v!i + LET j = i + { LET k = j - m + IF k<=0 | v!k < vi BREAK + v!j := v!k + j := k + } REPEAT + v!j := vi + } + } REPEATUNTIL m=1 +} + +MANIFEST { upb = 10000 } + +LET start() = VALOF +{ LET v = getvec(upb) + + try("shell", shellsort, v, upb) + + writes("*nEnd of test*n") + freevec(v) + RESULTIS 0 +} + +AND try(name, sortroutine, v, upb) BE +{ // delay, referencing the first and last elements of v + FOR i = 1 TO 50000 DO v!upb := v!1 + writef("*nSetting %n words of data for %s sort*n", upb, name) + FOR i = 1 TO upb DO v!i := randno(10000) + writef("Entering %s sort routine*n", name) + sortroutine(v, upb) + writes("Sorting complete*n") + TEST sorted(v, upb) + THEN writes("The data is now sorted*n") + ELSE writef("### ERROR: %s sort does not work*n", name) +} + +AND sorted(v, n) = VALOF +{ //FOR i = 1 TO n-1 UNLESS v!i<=v!(i+1) RESULTIS FALSE + RESULTIS TRUE +} diff --git a/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c b/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c new file mode 100644 index 0000000000..220e3c2b74 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c @@ -0,0 +1,19 @@ +void shell_sort (int *a, int n) { + int h, i, j, k; + for (h = n; h /= 2;) { + for (i = h; i < n; i++) { + k = a[i]; + for (j = i; j >= h && k < a[j - h]; j -= h) { + a[j] = a[j - h]; + } + a[j] = k; + } + } +} + +int main (int ac, char **av) { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + shell_sort(a, n); + return 0; +} diff --git a/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort.cobol b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort.cobol new file mode 100644 index 0000000000..cd22b51835 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort.cobol @@ -0,0 +1,55 @@ + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + DIVIDE WC-SIZE BY 2 GIVING WC-GAP. + + PERFORM E-PROCESS-GAP UNTIL WC-GAP = 0. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + + E-PROCESS-GAP SECTION. + E-000. + PERFORM F-SELECTION VARYING WB-IX-1 FROM WC-GAP BY 1 + UNTIL WB-IX-1 > WC-SIZE. + + DIVIDE WC-GAP BY 2.2 GIVING WC-GAP. + + E-999. + EXIT. + + F-SELECTION SECTION. + F-000. + SET WB-IX-2 TO WB-IX-1. + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP. + + SET WB-IX-3 TO WB-IX-2. + SET WB-IX-3 DOWN BY WC-GAP. + PERFORM G-PASS UNTIL WB-IX-2 NOT > WC-GAP + * The next line logically reads : + * or wb-entry(wb-ix-2 - wc-gap) not > wc-temp. + OR WB-ENTRY(WB-IX-3) NOT > WC-TEMP. + + IF WB-IX-1 NOT = WB-IX-2 + MOVE WC-TEMP TO WB-ENTRY(WB-IX-2). + + F-999. + EXIT. + + G-PASS SECTION. + * Note that WB-IX-3 is WC-GAP less than WB-IX-2. + * Logically this should be : + * move wb-entry(wb-ix-2 - wc-gap) to wb-entry(wb-ix-2). + * set wb-ix-2 down by wc-gap. + * Unfortunately wb-entry(wb-ix-2 - wc-gap) is not legal in C2 cobol + G-000. + MOVE WB-ENTRY(WB-IX-3) TO WB-ENTRY(WB-IX-2). + SET WB-IX-2 DOWN BY WC-GAP. + SET WB-IX-3 DOWN BY WC-GAP. + + G-999. + EXIT. diff --git a/Task/Sorting-algorithms-Shell-sort/Common-Lisp/sorting-algorithms-shell-sort.lisp b/Task/Sorting-algorithms-Shell-sort/Common-Lisp/sorting-algorithms-shell-sort.lisp new file mode 100644 index 0000000000..588dd3680f --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Common-Lisp/sorting-algorithms-shell-sort.lisp @@ -0,0 +1,20 @@ +(defun gap-insertion-sort (array predicate gap) + (let ((length (length array))) + (if (< length 2) array + (do ((i 1 (1+ i))) ((eql i length) array) + (do ((x (aref array i)) + (j i (- j gap))) + ((or (< (- j gap) 0) + (not (funcall predicate x (aref array (1- j))))) + (setf (aref array j) x)) + (setf (aref array j) (aref array (- j gap)))))))) + +(defconstant +gaps+ + '(1750 701 301 132 57 23 10 4 1) + "The best sequence of gaps, according to Marcin Ciura.") + +(defun shell-sort (array predicate &optional (gaps +gaps+)) + (assert (eql 1 (car (last gaps))) (gaps) + "Last gap of ~w is not 1." gaps) + (dolist (gap gaps array) + (gap-insertion-sort array predicate gap))) diff --git a/Task/Sorting-algorithms-Shell-sort/D/sorting-algorithms-shell-sort.d b/Task/Sorting-algorithms-Shell-sort/D/sorting-algorithms-shell-sort.d new file mode 100644 index 0000000000..8c9d6c4d5a --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/D/sorting-algorithms-shell-sort.d @@ -0,0 +1,21 @@ +import std.stdio: writeln; + +void shellSort(T)(T[] seq) pure nothrow { + int inc = seq.length / 2; + while (inc) { + foreach (ref i, el; seq) { + while (i >= inc && seq[i - inc] > el) { + seq[i] = seq[i - inc]; + i -= inc; + } + seq[i] = el; + } + inc = (inc == 2) ? 1 : cast(int)(inc * 5.0 / 11); + } +} + +void main() { + auto data = [22, 7, 2, -5, 8, 4]; + shellSort(data); + writeln(data); +} diff --git a/Task/Sorting-algorithms-Shell-sort/E/sorting-algorithms-shell-sort.e b/Task/Sorting-algorithms-Shell-sort/E/sorting-algorithms-shell-sort.e new file mode 100644 index 0000000000..80d576716f --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/E/sorting-algorithms-shell-sort.e @@ -0,0 +1,14 @@ +/** Shell sort (in-place) */ +def shellSort(array) { + var inc := array.size() // 2 + while (inc.aboveZero()) { + for var i => a in array { + while (i >= inc && (def b := array[i - inc]) > a) { + array[i] := b + i -= inc + } + array[i] := a + } + inc := if (inc <=> 2) { 1 } else { (inc * 5.0 / 11).floor() } + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/Eiffel/sorting-algorithms-shell-sort.e b/Task/Sorting-algorithms-Shell-sort/Eiffel/sorting-algorithms-shell-sort.e new file mode 100644 index 0000000000..9f815aea05 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Eiffel/sorting-algorithms-shell-sort.e @@ -0,0 +1,42 @@ +class + MY_SORTED_SET [G -> COMPARABLE] +inherit + TWO_WAY_SORTED_SET [G] + redefine + sort + end +create + make + +feature + + sort + -- Shell sort + local + inc: INTEGER + j: INTEGER + l_value: like item + do + from + inc := (count.to_double / 2.0).rounded + until + inc <= 0 + loop + across inc |..| (count - 1) as ii + loop + l_value := Current [ii.item + 1] + from + j := ii.item + until + j < inc or Current [j - inc + 1] <= l_value + loop + Current [j + 1] := Current [j - inc + 1] + j := j - inc + end + Current [j + 1] := l_value + end + inc := (inc.to_double / 2.2).rounded + end + end + +end diff --git a/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.euphoria b/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.euphoria new file mode 100644 index 0000000000..9ef6454c66 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.euphoria @@ -0,0 +1,24 @@ +function shell_sort(sequence s) + integer gap,j + object temp + gap = floor(length(s)/2) + while gap > 0 do + for i = gap to length(s) do + temp = s[i] + j=i-gap + while j >= 1 and compare(temp, s[j]) <= 0 do + s[j+gap]=s[j] + j -= gap + end while + s[j+gap] = temp + end for + gap = floor(gap/2) + end while + return s +end function + +constant s = rand(repeat(1000,10)) +puts(1,"Before: ") +? s +puts(1,"After: ") +? shell_sort(s) diff --git a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth new file mode 100644 index 0000000000..fe093038cc --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-1.fth @@ -0,0 +1,21 @@ +defer less? ' < is less? + +: shell { array len -- } + 1 begin dup len u<= while 2* 1+ repeat { gap } + begin gap 5 11 */ dup to gap while + len gap do + array i cells + + dup @ swap ( temp last ) + begin gap cells - + array over u<= + while 2dup @ less? + while dup gap cells + over @ swap ! + repeat then + gap cells + ! + loop + repeat ; + +create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 , + +array 10 shell +array 10 cells dump diff --git a/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth new file mode 100644 index 0000000000..00f3bb89c0 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Forth/sorting-algorithms-shell-sort-2.fth @@ -0,0 +1,28 @@ +defer precedes ' < is precedes + +: (shell) ( a n h -- a n h) + over >r tuck ( a h n h) + ?do ( a h) + i swap >r ( a j R: h) + 2dup cells + @ -rot ( k a j R: h) + begin ( k a j R: h) + dup r@ - dup >r 0< 0= ( k a j f R: h j-h) + while ( k a j R: h j-h) + -rot over over r@ cells + @ ( j k a k v R: h j-h) + precedes >r rot r> ( k a j f R: h j-h) + while ( k a j R: h j-h) + over r@ cells + @ >r ( k a j R: h j-h a[j-h]) + 2dup cells + r> swap ! ( k a j R: h j-h) + drop r> ( k a j' R: h) + repeat then ( k a j R: h j-h) + rot >r 2dup cells + ( a j a[j] R: h j-h k) + r> swap ! r> drop drop r> ( a h) + loop r> swap +; + ( a n --) +: shell dup begin 5 11 */ dup while (shell) repeat drop 2drop ; + +create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 , + +array 10 shell +array 10 cells dump diff --git a/Task/Sorting-algorithms-Shell-sort/Fortran/sorting-algorithms-shell-sort.f b/Task/Sorting-algorithms-Shell-sort/Fortran/sorting-algorithms-shell-sort.f new file mode 100644 index 0000000000..c3915c82e1 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Fortran/sorting-algorithms-shell-sort.f @@ -0,0 +1,51 @@ +MODULE sort + +CONTAINS + +SUBROUTINE Shell_Sort(a) + + IMPLICIT NONE + INTEGER :: i, j, increment + REAL :: temp + REAL, INTENT(in out) :: a(:) + + increment = SIZE(a) / 2 + DO WHILE (increment > 0) + DO i = increment+1, SIZE(a) + j = i + temp = a(i) + DO WHILE (j >= increment+1 .AND. a(j-increment) > temp) + a(j) = a(j-increment) + j = j - increment + END DO + a(j) = temp + END DO + IF (increment == 2) THEN + increment = 1 + ELSE + increment = increment * 5 / 11 + END IF + END DO + +END SUBROUTINE Shell_Sort + +END MODULE sort + +PROGRAM Shellsort + +USE sort + + IMPLICIT NONE + REAL :: array(1000) + + CALL RANDOM_SEED + CALL RANDOM_NUMBER(array) + + WRITE (*,*) "Unsorted array" + WRITE (*,*) array + WRITE (*,*) + CALL Shell_Sort(array) + WRITE (*,*) "Sorted array" + WRITE (*,*) array + +END PROGRAM Shellsort diff --git a/Task/Sorting-algorithms-Shell-sort/Go/sorting-algorithms-shell-sort.go b/Task/Sorting-algorithms-Shell-sort/Go/sorting-algorithms-shell-sort.go new file mode 100644 index 0000000000..4cf91a6cfa --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Go/sorting-algorithms-shell-sort.go @@ -0,0 +1,19 @@ +package main + +import "fmt" + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} + +func main() { + fmt.Println("before:", a) + for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { + for i := inc; i < len(a); i++ { + j, temp := i, a[i] + for ; j >= inc && a[j-inc] > temp; j -= inc { + a[j] = a[j-inc] + } + a[j] = temp + } + } + fmt.Println("after: ", a) +} diff --git a/Task/Sorting-algorithms-Shell-sort/Haskell/sorting-algorithms-shell-sort.hs b/Task/Sorting-algorithms-Shell-sort/Haskell/sorting-algorithms-shell-sort.hs new file mode 100644 index 0000000000..5a31be0251 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Haskell/sorting-algorithms-shell-sort.hs @@ -0,0 +1,6 @@ +import Data.List + +shellSort xs = foldr (invColumnize (map (foldr insert []))) xs gaps + where gaps = takeWhile (< length xs) $ iterate (succ.(3*)) 1 + invColumnize f k = concat. transpose. f. transpose + . takeWhile (not.null). unfoldr (Just. splitAt k) diff --git a/Task/Sorting-algorithms-Shell-sort/Icon/sorting-algorithms-shell-sort.icon b/Task/Sorting-algorithms-Shell-sort/Icon/sorting-algorithms-shell-sort.icon new file mode 100644 index 0000000000..43c2a6e563 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Icon/sorting-algorithms-shell-sort.icon @@ -0,0 +1,21 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(shellsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure shellsort(X,op) #: return sorted X +local i,j,inc,temp + + op := sortop(op,X) # select how and what we sort + + inc := *X/2 + while inc > 0 do { + every i := inc to *X do { + temp := X[j := i] + while op(temp,X[j - (j >= inc)]) do + X[j] := X[j -:= inc] + X[j] := temp + } + inc := if inc = 2 then 1 else inc*5/11 # switch to insertion near the end + } + return X +end diff --git a/Task/Sorting-algorithms-Shell-sort/Io/sorting-algorithms-shell-sort.io b/Task/Sorting-algorithms-Shell-sort/Io/sorting-algorithms-shell-sort.io new file mode 100644 index 0000000000..a34b349158 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Io/sorting-algorithms-shell-sort.io @@ -0,0 +1,21 @@ +List do( + shellSortInPlace := method( + gap := (size / 2) round + while(gap > 0, + for(i, gap, size - 1, + key := at(i) + j := i + + while(j >= gap and at(j - gap) > key, + atPut(j, at(j - gap)) + j = j - gap + ) + atPut(j, key) + ) + gap = (gap / 2.2) round + ) + self) +) + +l := list(2, 3, 4, 5, 1) +l shellSortInPlace println # ==> list(1, 2, 3, 4, 5) diff --git a/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort.j b/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort.j new file mode 100644 index 0000000000..0ea8c40f19 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort.j @@ -0,0 +1,4 @@ +gaps =: [: }: 1 (1+3*])^:(> {:)^:a:~ # +insert =: (I.~ {. ]) , [ , ] }.~ I.~ +gapinss =: #@] {. ,@|:@(] insert//.~ #@] $ i.@[) +shellSort =: [: ; gapinss &.>/@(< ,~ ]&.>@gaps) diff --git a/Task/Sorting-algorithms-Shell-sort/Java/sorting-algorithms-shell-sort.java b/Task/Sorting-algorithms-Shell-sort/Java/sorting-algorithms-shell-sort.java new file mode 100644 index 0000000000..d359ce53b7 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Java/sorting-algorithms-shell-sort.java @@ -0,0 +1,19 @@ +public static void shell(int[] a) { + int increment = a.length / 2; + while (increment > 0) { + for (int i = increment; i < a.length; i++) { + int j = i; + int temp = a[i]; + while (j >= increment && a[j - increment] > temp) { + a[j] = a[j - increment]; + j = j - increment; + } + a[j] = temp; + } + if (increment == 2) { + increment = 1; + } else { + increment *= (5.0 / 11); + } + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/JavaScript/sorting-algorithms-shell-sort.js b/Task/Sorting-algorithms-Shell-sort/JavaScript/sorting-algorithms-shell-sort.js new file mode 100644 index 0000000000..361a7e6162 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/JavaScript/sorting-algorithms-shell-sort.js @@ -0,0 +1,18 @@ +function shellSort (a) { + for (var h = a.length; h = parseInt(h / 2);) { + for (var i = h; i < a.length; i++) { + var k = a[i]; + for (var j = i; j >= h && k < a[j - h]; j -= h) + a[j] = a[j - h]; + a[j] = k; + } + } + return a; +} + +var a = []; +var n = location.href.match(/\?(\d+)|$/)[1] || 10; +for (var i = 0; i < n; i++) + a.push(parseInt(Math.random() * 100)); +shellSort(a); +document.write(a.join(" ")); diff --git a/Task/Sorting-algorithms-Shell-sort/Lisaac/sorting-algorithms-shell-sort.lisaac b/Task/Sorting-algorithms-Shell-sort/Lisaac/sorting-algorithms-shell-sort.lisaac new file mode 100644 index 0000000000..5055914b12 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Lisaac/sorting-algorithms-shell-sort.lisaac @@ -0,0 +1,46 @@ +Section Header + ++ name := SHELL_SORT; + +- external := `#include <time.h>`; + +Section Public + +- main <- ( + + a : ARRAY[INTEGER]; + + a := ARRAY[INTEGER].create 0 to 100; + `srand(time(NULL))`; + 0.to 100 do { i : INTEGER; + a.put `rand()`:INTEGER to i; + }; + + shell a; + + a.foreach { item : INTEGER; + item.print; + '\n'.print; + }; +); + +- shell a : ARRAY[INTEGER] <- ( + + lower, length, increment, temp : INTEGER; + + lower := a.lower; + length := a.upper - lower + 1; + increment := length; + { + increment := increment / 2; + increment > 0 + }.while_do { + increment.to (length - 1) do { i : INTEGER; + j : INTEGER; + temp := a.item(lower + i); + j := i - increment; + { (j >= 0) && { a.item(lower + j) > temp } }.while_do { + a.put (a.item(lower + j)) to (lower + j + increment); + j := j - increment; + }; + a.put temp to (lower + j + increment); + }; + }; +); diff --git a/Task/Sorting-algorithms-Shell-sort/Lua/sorting-algorithms-shell-sort.lua b/Task/Sorting-algorithms-Shell-sort/Lua/sorting-algorithms-shell-sort.lua new file mode 100644 index 0000000000..2912de3eb7 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Lua/sorting-algorithms-shell-sort.lua @@ -0,0 +1,24 @@ +function shellsort( a ) + local inc = math.ceil( #a / 2 ) + while inc > 0 do + for i = inc, #a do + local tmp = a[i] + local j = i + while j > inc and a[j-inc] > tmp do + a[j] = a[j-inc] + j = j - inc + end + a[j] = tmp + end + inc = math.floor( 0.5 + inc / 2.2 ) + end + + return a +end + +a = { -12, 3, 0, 4, 7, 4, 8, -5, 9 } +a = shellsort( a ) + +for _, i in pairs(a) do + print(i) +end diff --git a/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-1.m b/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-1.m new file mode 100644 index 0000000000..ed651cbe64 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-1.m @@ -0,0 +1,26 @@ +function list = shellSort(list) + + N = numel(list); + increment = round(N/2); + + while increment > 0 + + for i = (increment+1:N) + temp = list(i); + j = i; + while (j >= increment+1) && (list(j-increment) > temp) + list(j) = list(j-increment); + j = j - increment; + end + + list(j) = temp; + + end %for + + if increment == 2 %This case causes shell sort to become insertion sort + increment = 1; + else + increment = round(increment/2.2); + end + end %while +end %shellSort diff --git a/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-2.m b/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-2.m new file mode 100644 index 0000000000..4d39d04a89 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/MATLAB/sorting-algorithms-shell-sort-2.m @@ -0,0 +1,5 @@ +>> shellSort([4 3 1 5 6 2]) + +ans = + + 1 2 3 4 5 6 diff --git a/Task/Sorting-algorithms-Shell-sort/Mathematica/sorting-algorithms-shell-sort.math b/Task/Sorting-algorithms-Shell-sort/Mathematica/sorting-algorithms-shell-sort.math new file mode 100644 index 0000000000..b601493700 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Mathematica/sorting-algorithms-shell-sort.math @@ -0,0 +1,16 @@ +shellSort[ lst_ ] := Module[ {list = lst, incr, temp, i, j}, + incr = Round[Length[list]/2]; + While[incr > 0, + + For[i = incr + 1, i < Length[list], i++, + + temp = list[[i]]; j = i; + + While[(j >= (incr + 1)) && (list[[j - incr]] > temp) , + list[[j]] = list[[j - incr]]; j = j-incr; + ]; + + list[[j]] = temp;]; + If[incr == 2, incr = 1, incr = Round[incr/2.2]] +]; list +] diff --git a/Task/Sorting-algorithms-Shell-sort/NetRexx/sorting-algorithms-shell-sort.netrexx b/Task/Sorting-algorithms-Shell-sort/NetRexx/sorting-algorithms-shell-sort.netrexx new file mode 100644 index 0000000000..779f228fb3 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/NetRexx/sorting-algorithms-shell-sort.netrexx @@ -0,0 +1,45 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] +sortedList = shellSort(String[] Arrays.copyOf(placesList, placesList.length)) + +lists = [placesList, sortedList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method shellSort(a = String[]) public constant binary returns String[] + + n = a.length + inc = int Math.round(double n / 2.0) + loop label inc while inc > 0 + loop i_ = inc to n - 1 + temp = a[i_] + j_ = i_ + loop label j_ while j_ >= inc + if \(a[j_ - inc].compareTo(temp) > 0) then leave j_ + a[j_] = a[j_ - inc] + j_ = j_ - inc + end j_ + a[j_] = temp + end i_ + inc = int Math.round(double inc / 2.2) + end inc + + return a + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue diff --git a/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-1.ocaml b/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-1.ocaml new file mode 100644 index 0000000000..34b5e4f30d --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-1.ocaml @@ -0,0 +1,21 @@ +let shellsort a = + let len = Array.length a in + let incSequence = [| 412771; 165103; 66041; 26417; 10567; + 4231; 1693; 673; 269; 107; 43; 17; 7; 3; 1 |] in + + Array.iter (fun increment -> + if (increment * 2) <= len then + for i = increment to pred len do + let temp = a.(i) in + let rec loop j = + if j < 0 || a.(j) <= temp then (j) + else begin + a.(j + increment) <- a.(j); + loop (j - increment) + end + in + let j = loop (i - increment) in + a.(j + increment) <- temp; + done; + ) incSequence; +;; diff --git a/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-2.ocaml b/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-2.ocaml new file mode 100644 index 0000000000..16830a8005 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/OCaml/sorting-algorithms-shell-sort-2.ocaml @@ -0,0 +1,10 @@ +let () = + let arraysize = 1000 in (* or whatever *) + Random.self_init(); + let intArray = + Array.init arraysize (fun _ -> Random.int 4000) + in + shellsort intArray; + Array.iter (Printf.printf " %d") intArray; + print_newline(); +;; diff --git a/Task/Sorting-algorithms-Shell-sort/Objeck/sorting-algorithms-shell-sort.objeck b/Task/Sorting-algorithms-Shell-sort/Objeck/sorting-algorithms-shell-sort.objeck new file mode 100644 index 0000000000..6b0d6a4180 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Objeck/sorting-algorithms-shell-sort.objeck @@ -0,0 +1,34 @@ +bundle Default { + class ShellSort { + function : Main(args : String[]) ~ Nil { + a := [1, 3, 7, 21, 48, 112,336, 861, 1968, 4592, 13776,33936, 86961, 198768, 463792, 1391376,3402672, 8382192, 21479367, 49095696, 114556624,343669872, 52913488, 2085837936]; + Shell(a); + each(i : a) { + IO.Console->Print(a[i])->Print(", "); + }; + IO.Console->PrintLine(); + } + + function : native : Shell(a : Int[]) ~ Nil { + increment := a->Size() / 2; + while(increment > 0) { + for(i := increment; i < a->Size(); i += 1;) { + j := i; + temp := a[i]; + while(j >= increment & a[j - increment] > temp) { + a[j] := a[j - increment]; + j -= increment; + }; + a[j] := temp; + }; + + if(increment = 2) { + increment := 1; + } + else { + increment *= (5.0 / 11); + }; + }; + } + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/PARI-GP/sorting-algorithms-shell-sort.pari b/Task/Sorting-algorithms-Shell-sort/PARI-GP/sorting-algorithms-shell-sort.pari new file mode 100644 index 0000000000..ed56960523 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PARI-GP/sorting-algorithms-shell-sort.pari @@ -0,0 +1,14 @@ +shellSort(v)={ + my(inc=#v\2); + while(inc, + for(i=inc+1,#v, + my(t=v[i],j=i); + while(j>inc && v[j-inc]>t, + v[j]=v[j-=inc] + ); + v[j]=t + ); + inc \= 2.2 + ); + v +}; diff --git a/Task/Sorting-algorithms-Shell-sort/PHP/sorting-algorithms-shell-sort.php b/Task/Sorting-algorithms-Shell-sort/PHP/sorting-algorithms-shell-sort.php new file mode 100644 index 0000000000..5053e66e55 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PHP/sorting-algorithms-shell-sort.php @@ -0,0 +1,19 @@ +function shellSort($arr) +{ + $inc = round(count($arr)/2); + while($inc > 0) + { + for($i = $inc; $i < count($arr);$i++){ + $temp = $arr[$i]; + $j = $i; + while($j >= $inc && $arr[$j-$inc] > $temp) + { + $arr[$j] = $arr[$j - $inc]; + $j -= $inc; + } + $arr[$j] = $temp; + } + $inc = round($inc/2.2); + } + return $arr; +} diff --git a/Task/Sorting-algorithms-Shell-sort/PL-I/sorting-algorithms-shell-sort.pli b/Task/Sorting-algorithms-Shell-sort/PL-I/sorting-algorithms-shell-sort.pli new file mode 100644 index 0000000000..08858a8521 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PL-I/sorting-algorithms-shell-sort.pli @@ -0,0 +1,23 @@ +/* Based on Rosetta Fortran */ +Shell_Sort: PROCEDURE (A); + DECLARE A(*) FIXED; + DECLARE ( i, j, increment) FIXED BINARY (31); + DECLARE temp FIXED; + + increment = DIMENSION(a) / 2; + DO WHILE (increment > 0); + DO i = lbound(A,1)+increment TO hbound(a,1); + j = i; + temp = a(i); + DO WHILE (j >= increment+1 & a(j-increment) > temp); + a(j) = a(j-increment); + j = j - increment; + END; + a(j) = temp; + END; + IF increment = 2 THEN + increment = 1; + ELSE + increment = increment * 5 / 11; + END; +END SHELL_SORT; diff --git a/Task/Sorting-algorithms-Shell-sort/Pascal/sorting-algorithms-shell-sort.pascal b/Task/Sorting-algorithms-Shell-sort/Pascal/sorting-algorithms-shell-sort.pascal new file mode 100644 index 0000000000..07d8e015e6 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Pascal/sorting-algorithms-shell-sort.pascal @@ -0,0 +1,23 @@ +Const + MaxN = 100; { number of elements (my example is 100) } +Type + TArray = Array [0..MaxN] of Integer; + +Procedure ShellSort ( var A : TArray; N : Integer ); +Var + i, j, step, tmp : Integer; +Begin + step:=N div 2; // step:=step shr 1 + While step>0 Do Begin + For i:=step to N Do Begin + tmp:=A[i]; + j:=i; + While (j>=step) and (A[j-step]>tmp) Do Begin + A[j]:=A[j-step]; + dec(j,step); + End; + A[j]:=tmp; + End; + step:=step div 2; // step:=step shr 1 + End; +End; diff --git a/Task/Sorting-algorithms-Shell-sort/Perl-6/sorting-algorithms-shell-sort.pl6 b/Task/Sorting-algorithms-Shell-sort/Perl-6/sorting-algorithms-shell-sort.pl6 new file mode 100644 index 0000000000..7072ba4ff6 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Perl-6/sorting-algorithms-shell-sort.pl6 @@ -0,0 +1,20 @@ +sub shell_sort ( @a is copy ) { + loop ( my $gap = (@a/2).round; $gap > 0; $gap = ( $gap * 5 / 11 ).round ) { + for $gap .. @a.end -> $i { + my $temp = @a[$i]; + + my $j; + loop ( $j = $i; $j >= $gap; $j -= $gap ) { + my $v = @a[$j - $gap]; + last if $v <= $temp; + @a[$j] = $v; + } + + @a[$j] = $temp; + } + } + return @a; +} +my @data = 22, 7, 2, -5, 8, 4; +say 'input = ' ~ @data; +say 'output = ' ~ @data.&shell_sort; diff --git a/Task/Sorting-algorithms-Shell-sort/Perl/sorting-algorithms-shell-sort.pl b/Task/Sorting-algorithms-Shell-sort/Perl/sorting-algorithms-shell-sort.pl new file mode 100644 index 0000000000..63fd0633b3 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Perl/sorting-algorithms-shell-sort.pl @@ -0,0 +1,18 @@ +sub shell_sort { + my (@a, $h, $i, $j, $k) = @_; + for ($h = @a; $h = int $h / 2;) { + for $i ($h .. $#a) { + $k = $a[$i]; + for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) { + $a[$j] = $a[$j - $h]; + } + $a[$j] = $k; + } + } + @a; +} + +my @a = map int rand 100, 1 .. $ARGV[0] || 10; +say "@a"; +@a = shell_sort @a; +say "@a"; diff --git a/Task/Sorting-algorithms-Shell-sort/PicoLisp/sorting-algorithms-shell-sort.l b/Task/Sorting-algorithms-Shell-sort/PicoLisp/sorting-algorithms-shell-sort.l new file mode 100644 index 0000000000..3fda05e1b0 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PicoLisp/sorting-algorithms-shell-sort.l @@ -0,0 +1,9 @@ +(de shellSort (A) + (for (Inc (*/ (length A) 2) (gt0 Inc) (*/ Inc 10 22)) + (for (I Inc (get A I) (inc I)) + (let (Tmp @ J I) + (while (and (>= J Inc) (> (get A (- J Inc)) Tmp)) + (set (nth A J) (get A (- J Inc))) + (dec 'J Inc) ) + (set (nth A J) Tmp) ) ) ) + A ) diff --git a/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.psh b/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.psh new file mode 100644 index 0000000000..58cd3d5f80 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.psh @@ -0,0 +1,26 @@ +Function ShellSort( [Array] $data ) +{ + # http://oeis.org/A108870 + $A108870 = [Int64[]] ( 1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, 30301, 68178, 153401, 345152, 776591, 1747331, 3931496, 8845866, 19903198, 44782196, 100759940, 226709866, 510097200, 1147718700, 2582367076, 5810325920, 13073233321, 29414774973 ) + $datal = $data.length - 1 + $inci = [Array]::BinarySearch( $A108870, [Int64] ( [Math]::Floor( $datal / 2 ) ) ) + if( $inci -lt 0 ) + { + $inci = ( $inci -bxor -1 ) - 1 + } + $A108870[ $inci..0 ] | ForEach-Object { + $inc = $_ + $_..$datal | ForEach-Object { + $temp = $data[ $_ ] + $j = $_ + for( ; ( $j -ge $inc ) -and ( $data[ $j - $inc ] -gt $temp ); $j -= $inc ) + { + $data[ $j ] = $data[ $j - $inc ] + } + $data[ $j ] = $temp + } + } + $data +} + +$l = 10000; ShellSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) ) diff --git a/Task/Sorting-algorithms-Shell-sort/PureBasic/sorting-algorithms-shell-sort.purebasic b/Task/Sorting-algorithms-Shell-sort/PureBasic/sorting-algorithms-shell-sort.purebasic new file mode 100644 index 0000000000..e677f1d9e1 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PureBasic/sorting-algorithms-shell-sort.purebasic @@ -0,0 +1,22 @@ +#STEP=2.2 + +Procedure Shell_sort(Array A(1)) + Protected l=ArraySize(A()), increment=Int(l/#STEP) + Protected i, j, temp + While increment + For i= increment To l + j=i + temp=A(i) + While j>=increment And A(j-increment)>temp + A(j)=A(j-increment) + j-increment + Wend + A(j)=temp + Next i + If increment=2 + increment=1 + Else + increment*(5.0/11) + EndIf + Wend +EndProcedure diff --git a/Task/Sorting-algorithms-Shell-sort/Python/sorting-algorithms-shell-sort.py b/Task/Sorting-algorithms-Shell-sort/Python/sorting-algorithms-shell-sort.py new file mode 100644 index 0000000000..6f768ecff6 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Python/sorting-algorithms-shell-sort.py @@ -0,0 +1,13 @@ +def shell(seq): + inc = len(seq) // 2 + while inc: + for i, el in enumerate(seq): + while i >= inc and seq[i - inc] > el: + seq[i] = seq[i - inc] + i -= inc + seq[i] = el + inc = 1 if inc == 2 else int(inc * 5.0 / 11) + +data = [22, 7, 2, -5, 8, 4] +shell(data) +print data # [-5, 2, 4, 7, 8, 22] diff --git a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx new file mode 100644 index 0000000000..693d34bbf0 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx @@ -0,0 +1,56 @@ +/*REXX program sorts an (stemmed) array using the shellsort method. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call shellSort highItem /*invoke the shell sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @.= /*assign default value to stem. */ + @.1='3 character abbreviations for states of the USA' /*predates ZIP.*/ + @.2='===============================================' + @.3='RHO Rhode Island and Providence Plantations' ; @.36='NMX New Mexico' + @.4='CAL California' ; @.20='NEV Nevada' ; @.37='IND Indiana' + @.5='KAN Kansas' ; @.21='TEX Texas' ; @.38='MOE Missouri' + @.6='MAS Massachusetts' ; @.22='VGI Virginia' ; @.39='COL Colorado' + @.7='WAS Washington' ; @.23='OHI Ohio' ; @.40='CON Connecticut' + @.8='HAW Hawaii' ; @.24='NHM New Hampshire'; @.41='MON Montana' + @.9='NCR North Carolina'; @.25='MAE Maine' ; @.42='LOU Louisiana' +@.10='SCR South Carolina'; @.26='MIC Michigan' ; @.43='IOW Iowa' +@.11='IDA Idaho' ; @.27='MIN Minnesota' ; @.44='ORE Oregon' +@.12='NDK North Dakota' ; @.28='MIS Mississippi' ; @.45='ARK Arkansas' +@.13='SDK South Dakota' ; @.29='WIS Wisconsin' ; @.46='ARZ Arizona' +@.14='NEB Nebraska' ; @.30='OKA Oklahoma' ; @.47='UTH Utah' +@.15='DEL Delaware' ; @.31='ALA Alabama' ; @.48='KTY Kentucky' +@.16='PEN Pennsylvania' ; @.32='FLA Florida' ; @.49='WVG West Virginia' +@.17='TEN Tennessee' ; @.33='MLD Maryland' ; @.50='NWJ New Jersey' +@.18='GEO Georgia' ; @.34='ALK Alaska' ; @.51='NYK New York' +@.19='VER Vermont' ; @.35='ILL Illinois' ; @.52='WYO Wyoming' + + do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ + end + +highItem=highItem-1 /*adjust the highItem slightly.*/ +return +/*──────────────────────────────────SHELLSORT subroutine───────---──────*/ +shellSort: procedure expose @.; parse arg highItem +i=highItem%2 + do while i\==0 + do j=i+1 to highItem; k=j; kmi=k-i + _=@.j + do while k>=i+1 & @.kmi>_; @.k=@.kmi + k=k-i; kmi=k-i + end /*while k>=i+1 & ...*/ + @.k=_ + end /*j*/ + + if i==2 then i=1 + else i=i*5%11 + end /*while i\==0*/ +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 (a fence)*/ +return diff --git a/Task/Sorting-algorithms-Shell-sort/Ruby/sorting-algorithms-shell-sort.rb b/Task/Sorting-algorithms-Shell-sort/Ruby/sorting-algorithms-shell-sort.rb new file mode 100644 index 0000000000..ba244c5417 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Ruby/sorting-algorithms-shell-sort.rb @@ -0,0 +1,21 @@ +class Array + def shellsort! + inc = length / 2 + while inc != 0 + inc.step(length-1) do |i| + el = self[i] + while i >= inc and self[i - inc] > el + self[i] = self[i - inc] + i -= inc + end + self[i] = el + end + inc = (inc == 2 ? 1 : (inc * 5.0 / 11).to_i) + end + self + end +end + +data = [22, 7, 2, -5, 8, 4] +data.shellsort! +p data # [-5, 2, 4, 7, 8, 22] diff --git a/Task/Sorting-algorithms-Shell-sort/Run-BASIC/sorting-algorithms-shell-sort.run b/Task/Sorting-algorithms-Shell-sort/Run-BASIC/sorting-algorithms-shell-sort.run new file mode 100644 index 0000000000..2282cda4fb --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Run-BASIC/sorting-algorithms-shell-sort.run @@ -0,0 +1,22 @@ +siz = 100 +dim a(siz) +for i = 1 to siz + a(i) = rnd(1) * 1000 +next i + +' ------------------------------- +' Shell Sort +' ------------------------------- +incr = int(siz / 2) +WHILE incr > 0 + for i = 1 to siz + j = i + temp = a(i) + WHILE (j >= incr and a(abs(j-incr)) > temp) + a(j) = a(j-incr) + j = j - incr + WEND + a(j) = temp + next i + incr = int(incr / 2.2) +WEND diff --git a/Task/Sorting-algorithms-Shell-sort/Scala/sorting-algorithms-shell-sort.scala b/Task/Sorting-algorithms-Shell-sort/Scala/sorting-algorithms-shell-sort.scala new file mode 100644 index 0000000000..3bfa53df3c --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Scala/sorting-algorithms-shell-sort.scala @@ -0,0 +1,27 @@ +object ShellSort { + def incSeq(len:Int)=new Iterator[Int]{ + private[this] var x:Int=len/2 + def hasNext=x>0 + def next()={x=if (x==2) 1 else x*5/11; x} + } + + def InsertionSort(a:Array[Int], inc:Int)={ + for (i <- inc until a.length; temp=a(i)){ + var j=i; + while (j>=inc && a(j-inc)>temp){ + a(j)=a(j-inc) + j=j-inc + } + a(j)=temp + } + } + + def shellSort(a:Array[Int])=for(inc<-incSeq(a.length)) InsertionSort(a, inc) + + def main(args: Array[String]): Unit = { + var a=Array(2, 5, 3, 4, 3, 9, 3, 2, 5, 4, 1, 3, 22, 7, 2, -5, 8, 4) + println(a.mkString(",")) + shellSort(a) + println(a.mkString(",")) + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/Seed7/sorting-algorithms-shell-sort.seed7 b/Task/Sorting-algorithms-Shell-sort/Seed7/sorting-algorithms-shell-sort.seed7 new file mode 100644 index 0000000000..58a82bcf75 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Seed7/sorting-algorithms-shell-sort.seed7 @@ -0,0 +1,21 @@ +const proc: shellSort (inout array elemType: arr) is func + local + var integer: i is 0; + var integer: j is 0; + var integer: increment is 0; + var elemType: help is elemType.value; + begin + increment := length(arr) div 2; + while increment > 0 do + for i range 1 to length(arr) do + j := i; + help := arr[i]; + while j > increment and arr[j - increment] > help do + arr[j] := arr[j - increment]; + j -:= increment; + end while; + arr[j] := help; + end for; + increment := increment div 2; + end while; + end func; diff --git a/Task/Sorting-algorithms-Shell-sort/Tcl/sorting-algorithms-shell-sort.tcl b/Task/Sorting-algorithms-Shell-sort/Tcl/sorting-algorithms-shell-sort.tcl new file mode 100644 index 0000000000..1834c27d4d --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Tcl/sorting-algorithms-shell-sort.tcl @@ -0,0 +1,21 @@ +package require Tcl 8.5 + +proc shellsort {m} { + set len [llength $m] + set inc [expr {$len / 2}] + while {$inc > 0} { + for {set i $inc} {$i < $len} {incr i} { + set j $i + set temp [lindex $m $i] + while {$j >= $inc && [set val [lindex $m [expr {$j - $inc}]]] > $temp} { + lset m $j $val + incr j -$inc + } + lset m $j $temp + } + set inc [expr {$inc == 2 ? 1 : $inc * 5 / 11}] + } + return $m +} + +puts [shellsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Shell-sort/XPL0/sorting-algorithms-shell-sort.xpl0 b/Task/Sorting-algorithms-Shell-sort/XPL0/sorting-algorithms-shell-sort.xpl0 new file mode 100644 index 0000000000..df24aafea3 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/XPL0/sorting-algorithms-shell-sort.xpl0 @@ -0,0 +1,36 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated strings + + +proc SSort(A, N); \Shell sort array in ascending order +char A; \address of array +int N; \number of elements in array (size) +int I, J, Gap, JG, T; +[Gap:= N>>1; +while Gap > 0 do + [for I:= Gap to N-1 do + [J:= I - Gap; + loop [JG:= J + Gap; + if A(J) <= A(JG) then quit; + T:= A(J); A(J):= A(JG); A(JG):= T; \swap elements + J:= J - Gap; + if J < 0 then quit; + ]; + ]; + Gap:= Gap>>1; + ]; +]; \SSort + + +func StrLen(Str); \Return number of characters in an ASCIIZ string +char Str; +int I; +for I:= 0 to -1>>1-1 do + if Str(I) = 0 then return I; + + +char Str; +[Str:= "Pack my box with five dozen liquor jugs."; +SSort(Str, StrLen(Str)); +Text(0, Str); CrLf(0); +] diff --git a/Task/Sorting-algorithms-Sleep-sort/0DESCRIPTION b/Task/Sorting-algorithms-Sleep-sort/0DESCRIPTION new file mode 100644 index 0000000000..db24f461f6 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/0DESCRIPTION @@ -0,0 +1,6 @@ +{{Sorting Algorithm}} +In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. + +Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. + +Sleep sort was [http://dis.4chan.org/read/prog/1295544154 presented] anonymously on 4chan and has been [http://news.ycombinator.com/item?id=2657277 discussed] on Hacker News. diff --git a/Task/Sorting-algorithms-Sleep-sort/1META.yaml b/Task/Sorting-algorithms-Sleep-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.ada b/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.ada new file mode 100644 index 0000000000..e541508ed1 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.ada @@ -0,0 +1,15 @@ +with Ada.Text_IO; +with Ada.Command_Line; use Ada.Command_Line; +procedure SleepSort is + task type PrintTask (num : Integer); + task body PrintTask is begin + delay Duration (num) / 100.0; + Ada.Text_IO.Put(num'Img); + end PrintTask; + type TaskAcc is access PrintTask; + TaskList : array (1 .. Argument_Count) of TaskAcc; +begin + for i in TaskList'Range loop + TaskList(i) := new PrintTask(Integer'Value(Argument(i))); + end loop; +end SleepSort; diff --git a/Task/Sorting-algorithms-Sleep-sort/BBC-BASIC/sorting-algorithms-sleep-sort.bbc b/Task/Sorting-algorithms-Sleep-sort/BBC-BASIC/sorting-algorithms-sleep-sort.bbc new file mode 100644 index 0000000000..dc410811a2 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/BBC-BASIC/sorting-algorithms-sleep-sort.bbc @@ -0,0 +1,24 @@ + INSTALL @lib$+"TIMERLIB" + + DIM test%(9) + test%() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1 + + FOR i% = 0 TO DIM(test%(),1) + p% = EVAL("!^PROCtask" + STR$(i%)) + tid% = FN_ontimer(100 + test%(i%), p%, 0) + NEXT + + REPEAT + WAIT 0 + UNTIL FALSE + + DEF PROCtask0 : PRINT test%(0) : ENDPROC + DEF PROCtask1 : PRINT test%(1) : ENDPROC + DEF PROCtask2 : PRINT test%(2) : ENDPROC + DEF PROCtask3 : PRINT test%(3) : ENDPROC + DEF PROCtask4 : PRINT test%(4) : ENDPROC + DEF PROCtask5 : PRINT test%(5) : ENDPROC + DEF PROCtask6 : PRINT test%(6) : ENDPROC + DEF PROCtask7 : PRINT test%(7) : ENDPROC + DEF PROCtask8 : PRINT test%(8) : ENDPROC + DEF PROCtask9 : PRINT test%(9) : ENDPROC diff --git a/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-1.c b/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-1.c new file mode 100644 index 0000000000..b29940a5ad --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-1.c @@ -0,0 +1,13 @@ +#include <stdlib.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/wait.h> + +int main(int c, char **v) +{ + while (--c > 1 && !fork()); + sleep(c = atoi(v[c])); + printf("%d\n", c); + wait(0); + return 0; +} diff --git a/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-2.c b/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-2.c new file mode 100644 index 0000000000..cfe878c7ff --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/C/sorting-algorithms-sleep-sort-2.c @@ -0,0 +1,8 @@ +% ./a.out 5 1 3 2 11 6 4 +1 +2 +3 +4 +5 +6 +11 diff --git a/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-1.coffeescript b/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-1.coffeescript new file mode 100644 index 0000000000..102fc77e56 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-1.coffeescript @@ -0,0 +1,11 @@ +after = (s, f) -> setTimeout f, s*1000 + +# Setting Computer Science back at least a century, maybe more, +# this algorithm sorts integers using a highly parallelized algorithm. +sleep_sort = (arr) -> + for n in arr + do (n) -> after n, -> console.log n + +do -> + input = (parseInt(arg) for arg in process.argv[2...]) + sleep_sort input diff --git a/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-2.coffeescript b/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-2.coffeescript new file mode 100644 index 0000000000..b8ee409251 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/CoffeeScript/sorting-algorithms-sleep-sort-2.coffeescript @@ -0,0 +1,10 @@ +> time coffee sleep_sort.coffee 5, 1, 3, 4, 2 +1 +2 +3 +4 +5 + +real 0m5.184s +user 0m0.147s +sys 0m0.024s diff --git a/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d b/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d new file mode 100644 index 0000000000..fd48d46551 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/D/sorting-algorithms-sleep-sort.d @@ -0,0 +1,21 @@ +import std.stdio, std.conv, std.datetime, core.thread; + +final class SleepSorter: Thread { + private immutable uint val; + + this(in uint n) { + super(&run); + val = n; + } + + private void run() { + Thread.sleep(dur!"msecs"(1000 * val)); + writef("%d ", val); + } +} + +void main(in string[] args) { + if (args.length > 1) + foreach (arg; args[1 .. $]) + (new SleepSorter(to!uint(arg))).start(); +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Delphi/sorting-algorithms-sleep-sort.delphi b/Task/Sorting-algorithms-Sleep-sort/Delphi/sorting-algorithms-sleep-sort.delphi new file mode 100644 index 0000000000..6558edbdc9 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Delphi/sorting-algorithms-sleep-sort.delphi @@ -0,0 +1,59 @@ +program SleepSortDemo; + +{$APPTYPE CONSOLE} + +uses + Windows, SysUtils, Classes; + +type + TSleepThread = class(TThread) + private + FValue: Integer; + FLock: PRTLCriticalSection; + protected + constructor Create(AValue: Integer; ALock: PRTLCriticalSection); + procedure Execute; override; + end; + +constructor TSleepThread.Create(AValue: Integer; ALock: PRTLCriticalSection); +begin + FValue:= AValue; + FLock:= ALock; + inherited Create(False); +end; + +procedure TSleepThread.Execute; +begin + Sleep(1000 * FValue); + EnterCriticalSection(FLock^); + Write(FValue:3); + LeaveCriticalSection(FLock^); +end; + +var + A: array[0..15] of Integer; + Handles: array[0..15] of THandle; + Threads: array[0..15] of TThread; + Lock: TRTLCriticalSection; + I: Integer; + +begin + for I:= Low(A) to High(A) do + A[I]:= Random(15); + for I:= Low(A) to High(A) do + Write(A[I]:3); + Writeln; + + InitializeCriticalSection(Lock); + for I:= Low(A) to High(A) do begin + Threads[I]:= TSleepThread.Create(A[I], @Lock); + Handles[I]:= Threads[I].Handle; + end; + WaitForMultipleObjects(Length(A), @Handles, True, INFINITE); + for I:= Low(A) to High(A) do + Threads[I].Free; + DeleteCriticalSection(Lock); + + Writeln; + ReadLn; +end. diff --git a/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.euphoria b/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.euphoria new file mode 100644 index 0000000000..f27918ee4c --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.euphoria @@ -0,0 +1,31 @@ +include get.e + +integer count + +procedure sleeper(integer key) + ? key + count -= 1 +end procedure + +sequence s, val +atom task + +s = command_line() +s = s[3..$] +if length(s)=0 then + puts(1,"Nothing to sort.\n") +else + count = 0 + for i = 1 to length(s) do + val = value(s[i]) + if val[1] = GET_SUCCESS then + task = task_create(routine_id("sleeper"),{val[2]}) + task_schedule(task,{val[2],val[2]}/10) + count += 1 + end if + end for + + while count do + task_yield() + end while +end if diff --git a/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go b/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go new file mode 100644 index 0000000000..3062bcdf30 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go @@ -0,0 +1,27 @@ +package main + +import ( + "log" + "os" + "strconv" + "sync" + "time" +) + +func main() { + lg := log.New(os.Stdout, "", 0) + var wg sync.WaitGroup + wg.Add(len(os.Args) - 1) + for _, a := range os.Args[1:] { + if i, err := strconv.ParseInt(a, 10, 64); err != nil { + lg.Print(err) + wg.Done() + } else { + time.AfterFunc(time.Duration(i*int64(time.Second)), func() { + lg.Print(i) + wg.Done() + }) + } + } + wg.Wait() +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort.hs b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort.hs new file mode 100644 index 0000000000..a05c427547 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort.hs @@ -0,0 +1,12 @@ +import System.Environment +import Control.Concurrent +import Control.Monad + +sleepSort :: [Int] -> IO () +sleepSort values = do + chan <- newChan + forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time)) + forM_ values (const (readChan chan >>= print)) + +main :: IO () +main = getArgs >>= sleepSort . map read diff --git a/Task/Sorting-algorithms-Sleep-sort/Java/sorting-algorithms-sleep-sort.java b/Task/Sorting-algorithms-Sleep-sort/Java/sorting-algorithms-sleep-sort.java new file mode 100644 index 0000000000..24b3a53071 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Java/sorting-algorithms-sleep-sort.java @@ -0,0 +1,31 @@ +import java.util.concurrent.CountDownLatch; + +public class SleepSort { + public static void sleepSortAndPrint(int[] nums) { + final CountDownLatch doneSignal = new CountDownLatch(nums.length); + for (final int num : nums) { + new Thread(new Runnable() { + public void run() { + doneSignal.countDown(); + try { + doneSignal.await(); + + //using straight milliseconds produces unpredictable + //results with small numbers + //using 1000 here gives a nifty demonstration + Thread.sleep(num * 1000); + System.out.println(num); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }).start(); + } + } + public static void main(String[] args) { + int[] nums = new int[args.length]; + for (int i = 0; i < args.length; i++) + nums[i] = Integer.parseInt(args[i]); + sleepSortAndPrint(nums); + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js new file mode 100644 index 0000000000..a030ead4be --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js @@ -0,0 +1,5 @@ +Array.prototype.timeoutSort = function (f) { + this.forEach(function (n) { + setTimeout(function () { f(n) }, 5 * n) + }); +} diff --git a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js new file mode 100644 index 0000000000..1413764370 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js @@ -0,0 +1 @@ +[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + 'br'); }) diff --git a/Task/Sorting-algorithms-Sleep-sort/Mathematica/sorting-algorithms-sleep-sort.math b/Task/Sorting-algorithms-Sleep-sort/Mathematica/sorting-algorithms-sleep-sort.math new file mode 100644 index 0000000000..5c842ba372 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Mathematica/sorting-algorithms-sleep-sort.math @@ -0,0 +1,2 @@ +SleepSort = RunScheduledTask[Print@#, {#, 1}] & /@ # &; +SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0}; diff --git a/Task/Sorting-algorithms-Sleep-sort/NetRexx/sorting-algorithms-sleep-sort.netrexx b/Task/Sorting-algorithms-Sleep-sort/NetRexx/sorting-algorithms-sleep-sort.netrexx new file mode 100644 index 0000000000..0948cbf3f4 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/NetRexx/sorting-algorithms-sleep-sort.netrexx @@ -0,0 +1,59 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +import java.util.concurrent.CountDownLatch + +-- ============================================================================= +class RSortingSleepsort + properties constant private + dflt = '-6 3 1 4 5 2 3 -7 1 6 001 3 -9 2 5 -009 -8 4 6 1 9 8 7 6 5 -7 3 4 5 2 0 -2 -1 -5 -4 -3 -0 000 0' + properties indirect + startLatch = CountDownLatch + doneLatch = CountDownLatch + floor = 0 + sorted = '' + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method main(args = String[]) public static + arg = Rexx(args) + if arg = '' then arg = dflt + say ' unsorted:' arg + say ' sorted:' (RSortingSleepsort()).sleepSort(arg) + return + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method sleepSort(iArg) public + setStartLatch(CountDownLatch(1)) -- used to put all threads on hold until we're ready to run + setDoneLatch(CountDownLatch(iArg.words())) -- used to indicate all work is done + loop mn = 1 to iArg.words() + setFloor(getFloor().min(iArg.word(mn))) -- save smallest -ve number so we can use it as a scale for sleep + Thread(SortThread(iArg.word(mn))).start() -- loop through input and create a thread for each element + end mn + getStartLatch().countDown() -- cry 'Havoc', and let slip the dogs of war. + do + getDoneLatch().await() -- wait for worker threads to complete + catch ix = InterruptedException + ix.printStackTrace() + end + return getSorted() + +-- ============================================================================= +class RSortingSleepsort.SortThread dependent implements Runnable + properties indirect + num + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method SortThread(nm) + setNum(nm) + return + -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + method run() public + do + parent.getStartLatch().await() -- wait until all threads are constructed + sleepTime = getNum() + parent.getFloor().abs() -- shifted by value of smallest number (permits numbers < 0) + sleepTime = sleepTime * 250 -- scale up; milliseconds are not granular enough + Thread.sleep(sleepTime) -- wait for this number's turn to run + catch ie = InterruptedException + ie.printStackTrace() + end + do protect parent -- lock the parent to prevent collisions + parent.setSorted((parent.getSorted() num).strip()) -- stow the number in the results List + end + parent.getDoneLatch().countDown() -- this one's done; decrement the latch + return diff --git a/Task/Sorting-algorithms-Sleep-sort/Objeck/sorting-algorithms-sleep-sort.objeck b/Task/Sorting-algorithms-Sleep-sort/Objeck/sorting-algorithms-sleep-sort.objeck new file mode 100644 index 0000000000..92d7b785b6 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Objeck/sorting-algorithms-sleep-sort.objeck @@ -0,0 +1,31 @@ +use System.Concurrency; +use Collection; + +bundle Default { + class Item from Thread { + @value : Int; + + New(value : Int) { + Parent(); + @value := value; + } + + method : public : Run(param : System.Base) ~ Nil { + Sleep(1000 * @value); + @value->PrintLine(); + } + } + + class SleepSort { + function : Main(args : String[]) ~ Nil { + items := Vector->New(); + each(i : args) { + items->AddBack(Item->New(args[i]->ToInt())); + }; + + each(i : items) { + items->Get(i)->As(Item)->Execute(Nil); + }; + } + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m new file mode 100644 index 0000000000..c71f7186fd --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Objective-C/sorting-algorithms-sleep-sort.m @@ -0,0 +1,14 @@ +#import <Foundation/Foundation.h> + +int main(int argc, char **argv) +{ + NSOperationQueue *queue = [NSOperationQueue new]; + while (--argc) { + int i = atoi(argv[argc]); + [queue addOperationWithBlock: ^{ + sleep(i); + NSLog(@"%d\n", i); + }]; + } + [queue waitUntilAllOperationsAreFinished]; +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 b/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 new file mode 100644 index 0000000000..aab08a11d5 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 @@ -0,0 +1,7 @@ +use MuEvent; + +for <6 8 1 12 2 14 5 2 1 0> -> $item { + MuEvent::timer( after => $item, cb => sub { say $item } ); +} + +MuEvent::run; diff --git a/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-1.pl b/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-1.pl new file mode 100644 index 0000000000..bd2149175a --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-1.pl @@ -0,0 +1,4 @@ +1 while ($_ = shift and @ARGV and !fork); +sleep $_; +print "$_\n"; +wait; diff --git a/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-2.pl b/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-2.pl new file mode 100644 index 0000000000..8064440954 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Perl/sorting-algorithms-sleep-sort-2.pl @@ -0,0 +1,12 @@ +use Coro; +$ret = Coro::Channel->new; +@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11); + +for my $n (@nums){ + async { + Coro::cede for 1..$n; + $ret->put($n); + } +} + +print $ret->get,"\n" for 1..@nums; diff --git a/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-1.l b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-1.l new file mode 100644 index 0000000000..ad8c84da0e --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-1.l @@ -0,0 +1,8 @@ +(de sleepSort (Lst) + (make + (for (I . N) Lst + (task (- I) (* N 100) N N I I + (link N) + (pop 'Lst) + (task (- I)) ) ) + (wait NIL (not Lst)) ) ) diff --git a/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-2.l b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-2.l new file mode 100644 index 0000000000..d318221315 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-2.l @@ -0,0 +1,8 @@ +(de sleepSort (Lst) + (make + (for N Lst + (task (pipe (wait (* N 100))) N N + (link N) + (pop 'Lst) + (task (close @)) ) ) + (wait NIL (not Lst)) ) ) diff --git a/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-3.l b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-3.l new file mode 100644 index 0000000000..16179ed006 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/PicoLisp/sorting-algorithms-sleep-sort-3.l @@ -0,0 +1,5 @@ +(for N (3 1 4 1 5 9 2 6 5) + (unless (fork) + (call 'sleep N) + (msg N) + (bye) ) ) diff --git a/Task/Sorting-algorithms-Sleep-sort/Prolog/sorting-algorithms-sleep-sort.pro b/Task/Sorting-algorithms-Sleep-sort/Prolog/sorting-algorithms-sleep-sort.pro new file mode 100644 index 0000000000..24bc375adc --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Prolog/sorting-algorithms-sleep-sort.pro @@ -0,0 +1,8 @@ +sleep_sort(L) :- + thread_pool_create(rosetta, 1024, []) , + maplist(initsort, L, LID), + maplist(thread_join, LID, _LStatus), + thread_pool_destroy(rosetta). + +initsort(V, Id) :- + thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []). diff --git a/Task/Sorting-algorithms-Sleep-sort/PureBasic/sorting-algorithms-sleep-sort.purebasic b/Task/Sorting-algorithms-Sleep-sort/PureBasic/sorting-algorithms-sleep-sort.purebasic new file mode 100644 index 0000000000..69fa2717ec --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/PureBasic/sorting-algorithms-sleep-sort.purebasic @@ -0,0 +1,17 @@ +NewMap threads() + +Procedure Foo(n) + Delay(n) + PrintN(Str(n)) +EndProcedure + +If OpenConsole() + For i=1 To CountProgramParameters() + threads(Str(i)) = CreateThread(@Foo(), Val(ProgramParameter())) + Next + + ForEach threads() + WaitThread(threads()) + Next + Print("Press ENTER to exit"): Input() +EndIf diff --git a/Task/Sorting-algorithms-Sleep-sort/Python/sorting-algorithms-sleep-sort.py b/Task/Sorting-algorithms-Sleep-sort/Python/sorting-algorithms-sleep-sort.py new file mode 100644 index 0000000000..3efa5a3f8c --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Python/sorting-algorithms-sleep-sort.py @@ -0,0 +1,20 @@ +from time import sleep +from threading import Timer + +def sleepsort(values): + sleepsort.result = [] + def add1(x): + sleepsort.result.append(x) + mx = values[0] + for v in values: + if mx < v: mx = v + Timer(v, add1, [v]).start() + sleep(mx+1) + return sleepsort.result + +if __name__ == '__main__': + x = [3,2,4,7,3,6,9,1] + if sleepsort(x) == sorted(x): + print('sleep sort worked for:',x) + else: + print('sleep sort FAILED for:',x) diff --git a/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx b/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx new file mode 100644 index 0000000000..9489ea84b2 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx @@ -0,0 +1,46 @@ +/*REXX program implements a sleep sort (with numbers entered from C.L.)*/ +numeric digits 300 /*over the top, but what the hey!*/ + /* (above) ... from vaudeville.*/ +#.= /*placeholder for the array of #s*/ +stuff='1e9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0' /*alphabetically*/ +parse arg numbers /*let the user specify on the CL.*/ +if numbers='' then numbers=stuff /*Not specified? Then use default*/ +N=words(numbers) /*N is the number of numbers. */ +w=length(N) /*width of N (for nice output).*/ +say N 'numbers to be sorted:' numbers /*informative informational info.*/ + + do j=1 for N /*let's start to boogie-woogie. */ + #.j=word(numbers,j) /*plug in one number at a time. */ + if datatype(#.j,'Numeric') then #.j = #.j/1 /*normalize it if num.*/ + call fork /*REGINA REXX supports FORK func.*/ + call sortItem j /*start a sort for array number. */ + end /*j*/ + + do forever while \inOrder(N) /*wait for the sorts to complete.*/ + call sleep 1 /*1 sec is the min effective time*/ + end /*forever while*/ /*well, other than zero seconds. */ + +m=max(length(#.1),length(#.N)) /*width of smallest | largest num*/ +say; say 'after sort:'; indent=left('',20) /*same as: COPIES(' ',20) */ + /*∙∙∙but LEFT pads [much faster]*/ + do k=1 for N /*list (sorted) array's elements.*/ + say indent 'array element' right(k,w) '───>' right(#.k,m) + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────SortItem subroutine────────────────*/ +sortItem: procedure expose #.; parse arg ? /*sorts single item.*/ + do Asort=1 until \switched /*cook until cooked.*/ + switched=0 /*honky-dorey so far*/ + do i=1 while #.i\=='' & \switched + if #.? >= #.i then iterate /*this one ok*/ + parse value #.? #.i with #.i #.? + switched=1 /*yup, we done switched one.*/ + end /*i*/ + if Asort//?==0 then call sleep switched /*sleep if last*/ + end /*Asort*/ +return /*Sleeping Beauty awakes. Not to worry: (c) = circa 1697.*/ +/*───────────────────────────────────InOrder subroutine─────────────────*/ +inOrder: procedure expose #.; parse arg howMany /*is array in order? */ + do m=1 for howMany-1; next=m+1; if #.m>#.next then return 0 + end /*m*/ /*keep looking for fountain of yut*/ +return 1 /*yes, indicate with an indicator.*/ diff --git a/Task/Sorting-algorithms-Sleep-sort/Racket/sorting-algorithms-sleep-sort.rkt b/Task/Sorting-algorithms-Sleep-sort/Racket/sorting-algorithms-sleep-sort.rkt new file mode 100644 index 0000000000..a6706ab078 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Racket/sorting-algorithms-sleep-sort.rkt @@ -0,0 +1,15 @@ +#lang racket + +;; accepts a list to sort +(define (sleep-sort lst) + (define done (make-channel)) + (for ([elem lst]) + (thread + (λ () + (sleep elem) + (channel-put done elem)))) + (for/list ([_ (length lst)]) + (channel-get done))) + +;; outputs '(2 5 5 7 8 9 10) +(sleep-sort '(5 8 2 7 9 10 5)) diff --git a/Task/Sorting-algorithms-Sleep-sort/Ruby/sorting-algorithms-sleep-sort.rb b/Task/Sorting-algorithms-Sleep-sort/Ruby/sorting-algorithms-sleep-sort.rb new file mode 100644 index 0000000000..21881d2aef --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Ruby/sorting-algorithms-sleep-sort.rb @@ -0,0 +1,15 @@ +require 'thread' + +nums = ARGV.collect(&:to_i) +sorted = [] +mutex = Mutex.new + +threads = nums.collect do |n| + Thread.new do + sleep 0.01 * n + mutex.synchronize {sorted << n} + end +end +threads.each {|t| t.join} + +p sorted diff --git a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust new file mode 100644 index 0000000000..e4b3a99965 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust @@ -0,0 +1,13 @@ +extern mod std; +use std::timer::sleep; +use std::uv::global_loop; + +fn main() { + for os::args().tail().each |&arg| { + do task::spawn { + let n = uint::from_str(arg).get(); + sleep(global_loop::get(), n); + io::println(arg); + } + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala new file mode 100644 index 0000000000..d1e337a6e3 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Scala/sorting-algorithms-sleep-sort.scala @@ -0,0 +1,12 @@ +object SleepSort { + def sort(nums:Seq[Int])=nums foreach {n => + scala.concurrent.ops.spawn{ + Thread.sleep(500*n) + print(n+" ") + } + } + + def main(args:Array[String])={ + sort(args map (_.toInt)) + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Tcl/sorting-algorithms-sleep-sort.tcl b/Task/Sorting-algorithms-Sleep-sort/Tcl/sorting-algorithms-sleep-sort.tcl new file mode 100644 index 0000000000..090599f44b --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Tcl/sorting-algorithms-sleep-sort.tcl @@ -0,0 +1,14 @@ +#!/bin/env tclsh +set count 0 +proc process val { + puts $val + incr ::count +} +# Schedule the output of the values +foreach val $argv { + after [expr {$val * 10}] [list process $val] +} +# Run event loop until all values output... +while {$count < $argc} { + vwait count +} diff --git a/Task/Sorting-algorithms-Sleep-sort/UNIX-Shell/sorting-algorithms-sleep-sort.sh b/Task/Sorting-algorithms-Sleep-sort/UNIX-Shell/sorting-algorithms-sleep-sort.sh new file mode 100644 index 0000000000..deb8b9de9a --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/UNIX-Shell/sorting-algorithms-sleep-sort.sh @@ -0,0 +1,10 @@ +f() { + sleep "$1" + echo "$1" +} +while [ -n "$1" ] +do + f "$1" & + shift +done +wait diff --git a/Task/Sorting-algorithms-Stooge-sort/0DESCRIPTION b/Task/Sorting-algorithms-Stooge-sort/0DESCRIPTION new file mode 100644 index 0000000000..0068f7b411 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/0DESCRIPTION @@ -0,0 +1,10 @@ +{{sorting Algorithm}}{{wikipedia|Stooge sort}}Show the [[wp:Stooge sort|Stooge Sort]] for an array of integers. The Stooge Sort algorithm is as follows: + <b>algorithm</b> stoogesort(<b>array</b> L, i = 0, j = <b>length</b>(L)-1) + <b>if</b> L[j] < L[i] <b>then</b> + L[i] <b>↔</b> L[j] + <b>if</b> j - i > 1 <b>then</b> + t <b>:=</b> (j - i + 1)/3 + stoogesort(L, i , j-t) + stoogesort(L, i+t, j ) + stoogesort(L, i , j-t) + <b>return</b> L diff --git a/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.ada b/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.ada new file mode 100644 index 0000000000..22d8bdd6ff --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.ada @@ -0,0 +1,32 @@ +with Ada.Text_IO; +procedure Stooge is + type Integer_Array is array (Positive range <>) of Integer; + procedure Swap (Left, Right : in out Integer) is + Temp : Integer := Left; + begin + Left := Right; + Right := Temp; + end Swap; + procedure Stooge_Sort (List : in out Integer_Array) is + T : Natural := List'Length / 3; + begin + if List (List'Last) < List (List'First) then + Swap (List (List'Last), List (List'First)); + end if; + if List'Length > 2 then + Stooge_Sort (List (List'First .. List'Last - T)); + Stooge_Sort (List (List'First + T .. List'Last)); + Stooge_Sort (List (List'First .. List'Last - T)); + end if; + end Stooge_Sort; + Test_Array : Integer_Array := (1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7); +begin + Stooge_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + if I /= Test_Array'Last then + Ada.Text_IO.Put (", "); + end if; + end loop; + Ada.Text_IO.New_Line; +end Stooge; diff --git a/Task/Sorting-algorithms-Stooge-sort/BASIC/sorting-algorithms-stooge-sort.basic b/Task/Sorting-algorithms-Stooge-sort/BASIC/sorting-algorithms-stooge-sort.basic new file mode 100644 index 0000000000..7a790f3c90 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/BASIC/sorting-algorithms-stooge-sort.basic @@ -0,0 +1,34 @@ +DECLARE SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG) + +RANDOMIZE TIMER + +CONST arraysize = 10 + +DIM x(arraysize) AS LONG +DIM i AS LONG + +PRINT "Before: "; +FOR i = 0 TO arraysize + x(i) = INT(RND * 100) + PRINT x(i); " "; +NEXT +PRINT + +stoogesort x(), 0, arraysize + +PRINT "After: "; +FOR i = 0 TO arraysize + PRINT x(i); " "; +NEXT +PRINT + +SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG) + IF L(j) < L(i) THEN SWAP L(i), L(j) + IF (j - i) > 1 THEN + DIM t AS LONG + t = (j - i + 1) / 3 + stoogesort L(), i, j - t + stoogesort L(), i + t, j + stoogesort L(), i, j - t + END IF +END SUB diff --git a/Task/Sorting-algorithms-Stooge-sort/BBC-BASIC/sorting-algorithms-stooge-sort.bbc b/Task/Sorting-algorithms-Stooge-sort/BBC-BASIC/sorting-algorithms-stooge-sort.bbc new file mode 100644 index 0000000000..18ff4184fe --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/BBC-BASIC/sorting-algorithms-stooge-sort.bbc @@ -0,0 +1,19 @@ + DIM test%(9) + test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 + PROCstoogesort(test%(), 0, DIM(test%(),1)) + FOR i% = 0 TO 9 + PRINT test%(i%) ; + NEXT + PRINT + END + + DEF PROCstoogesort(l%(), i%, j%) + LOCAL t% + IF l%(j%) < l%(i%) SWAP l%(i%), l%(j%) + IF j% - i% > 1 THEN + t% = (j% - i% + 1)/3 + PROCstoogesort(l%(), i%, j%-t%) + PROCstoogesort(l%(), i%+t%, j%) + PROCstoogesort(l%(), i%, j%-t%) + ENDIF + ENDPROC diff --git a/Task/Sorting-algorithms-Stooge-sort/C/sorting-algorithms-stooge-sort.c b/Task/Sorting-algorithms-Stooge-sort/C/sorting-algorithms-stooge-sort.c new file mode 100644 index 0000000000..477e874a58 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/C/sorting-algorithms-stooge-sort.c @@ -0,0 +1,31 @@ +#include <stdio.h> + +#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0) + +void StoogeSort(int a[], int i, int j) +{ + int t; + + if (a[j] < a[i]) SWAP(a[i], a[j]); + if (j - i > 1) + { + t = (j - i + 1) / 3; + StoogeSort(a, i, j - t); + StoogeSort(a, i + t, j); + StoogeSort(a, i, j - t); + } +} + +int main(int argc, char *argv[]) +{ + int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; + int i, n; + + n = sizeof(nums)/sizeof(int); + StoogeSort(nums, 0, n-1); + + for(i = 0; i <= n-1; i++) + printf("%5d", nums[i]); + + return 0; +} diff --git a/Task/Sorting-algorithms-Stooge-sort/D/sorting-algorithms-stooge-sort.d b/Task/Sorting-algorithms-Stooge-sort/D/sorting-algorithms-stooge-sort.d new file mode 100644 index 0000000000..5e7d370e02 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/D/sorting-algorithms-stooge-sort.d @@ -0,0 +1,19 @@ +import std.stdio, std.algorithm, std.array; + +void stoogeSort(T)(T[] seq) pure nothrow { + if (seq.back < seq.front) + swap(seq.front, seq.back); + + if (seq.length > 2) { + immutable m = seq.length / 3; + seq[0 .. $ - m].stoogeSort(); + seq[m .. $].stoogeSort(); + seq[0 .. $ - m].stoogeSort(); + } +} + +void main() { + auto data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5]; + data.stoogeSort(); + writeln(data); +} diff --git a/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.euphoria b/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.euphoria new file mode 100644 index 0000000000..de61faef71 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.euphoria @@ -0,0 +1,25 @@ +function stooge(sequence s, integer i, integer j) + object temp + integer t + if compare(s[j], s[i]) < 0 then + temp = s[i] + s[i] = s[j] + s[j] = temp + end if + if j - i > 1 then + t = floor((j - i + 1)/3) + s = stooge(s, i , j-t) + s = stooge(s, i+t, j ) + s = stooge(s, i , j-t) + end if + return s +end function + +function stoogesort(sequence s) + return stooge(s,1,length(s)) +end function + +constant s = rand(repeat(1000,10)) + +? s +? stoogesort(s) diff --git a/Task/Sorting-algorithms-Stooge-sort/Fortran/sorting-algorithms-stooge-sort.f b/Task/Sorting-algorithms-Stooge-sort/Fortran/sorting-algorithms-stooge-sort.f new file mode 100644 index 0000000000..ed91dc223d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Fortran/sorting-algorithms-stooge-sort.f @@ -0,0 +1,31 @@ +program Stooge + implicit none + + integer :: i + integer :: array(50) = (/ (i, i = 50, 1, -1) /) ! Reverse sorted array + + call Stoogesort(array) + write(*,"(10i5)") array + +contains + +recursive subroutine Stoogesort(a) + integer, intent(in out) :: a(:) + integer :: j, t, temp + + j = size(a) + if(a(j) < a(1)) then + temp = a(j) + a(j) = a(1) + a(1) = temp + end if + + if(j > 2) then + t = j / 3 + call Stoogesort(a(1:j-t)) + call Stoogesort(a(1+t:j)) + call Stoogesort(a(1:j-t)) + end if + +end subroutine +end program diff --git a/Task/Sorting-algorithms-Stooge-sort/Go/sorting-algorithms-stooge-sort.go b/Task/Sorting-algorithms-Stooge-sort/Go/sorting-algorithms-stooge-sort.go new file mode 100644 index 0000000000..12791393f8 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Go/sorting-algorithms-stooge-sort.go @@ -0,0 +1,25 @@ +package main + +import "fmt" + +var a = []int{170, 45, 75, -90, -802, 24, 2, 66} + +func main() { + fmt.Println("before:", a) + stoogesort(a) + fmt.Println("after: ", a) + fmt.Println("nyuk nyuk nyuk") +} + +func stoogesort(a []int) { + last := len(a) - 1 + if a[last] < a[0] { + a[0], a[last] = a[last], a[0] + } + if last > 1 { + t := len(a) / 3 + stoogesort(a[:len(a)-t]) + stoogesort(a[t:]) + stoogesort(a[:len(a)-t]) + } +} diff --git a/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs new file mode 100644 index 0000000000..ff49580f1f --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs @@ -0,0 +1,20 @@ +import Data.List +import Control.Arrow +import Control.Monad + +insertAt e k = uncurry(++).second ((e:).drop 1). splitAt k + +swapElems :: [a] -> Int -> Int -> [a] +swapElems xs i j = insertAt (xs!!j) i $ insertAt (xs!!i) j xs + +stoogeSort [] = [] +stoogeSort [x] = [x] +stoogeSort xs = doss 0 (length xs - 1) xs +doss :: (Ord a) => Int -> Int -> [a] -> [a] +doss i j xs + | j-i>1 = doss i (j-t) $ doss (i+t) j $ doss i (j-t) xs' + | otherwise = xs' + where t = (j-i+1)`div`3 + xs' + | xs!!j < xs!!i = swapElems xs i j + | otherwise = xs diff --git a/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-2.hs b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-2.hs new file mode 100644 index 0000000000..22667f31b5 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-2.hs @@ -0,0 +1,2 @@ +*Main> stoogeSort [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] +[-6,-5,-3,-2,1,3,3,4,5,5,7,7,7,9,10] diff --git a/Task/Sorting-algorithms-Stooge-sort/Icon/sorting-algorithms-stooge-sort.icon b/Task/Sorting-algorithms-Stooge-sort/Icon/sorting-algorithms-stooge-sort.icon new file mode 100644 index 0000000000..3fbdd31c19 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Icon/sorting-algorithms-stooge-sort.icon @@ -0,0 +1,22 @@ +procedure main() #: demonstrate various ways to sort a list and string + demosort(stoogesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") +end + +procedure stoogesort(X,op,i,j) #: return sorted list ascending(or descending) +local t + + if /i := 0 then { + j := *X + op := sortop(op,X) # select how and what we sort + } + + if op(X[j],X[i]) then + X[i] :=: X[j] + if j - i > 1 then { + t := (j - i + 1) / 3 + X := stoogesort(X,op,i,j-t) + X := stoogesort(X,op,i+t,j) + X := stoogesort(X,op,i,j-t) + } + return X # X must be returned and assigned to sort a string +end diff --git a/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-1.j b/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-1.j new file mode 100644 index 0000000000..4547ad2793 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-1.j @@ -0,0 +1,11 @@ +swapElems=: |.@:{`[`]} + +stoogeSort=: 3 : 0 + (0,<:#y) stoogeSort y +: + if. >/x{y do. y=.x swapElems y end. + if. 1<-~/x do. + t=. <.3%~1+-~/x + (x-0,t) stoogeSort (x+t,0) stoogeSort (x-0,t) stoogeSort y + else. y end. +) diff --git a/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-2.j b/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-2.j new file mode 100644 index 0000000000..b1f850b8ba --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/J/sorting-algorithms-stooge-sort-2.j @@ -0,0 +1,3 @@ + (,: stoogeSort) ?~13 +3 10 8 4 7 12 1 2 11 6 5 9 0 +0 1 2 3 4 5 6 7 8 9 10 11 12 diff --git a/Task/Sorting-algorithms-Stooge-sort/Java/sorting-algorithms-stooge-sort.java b/Task/Sorting-algorithms-Stooge-sort/Java/sorting-algorithms-stooge-sort.java new file mode 100644 index 0000000000..7756233cf5 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Java/sorting-algorithms-stooge-sort.java @@ -0,0 +1,27 @@ +import java.util.Arrays; + +public class Stooge { + public static void main(String[] args) { + int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; + stoogeSort(nums); + System.out.println(Arrays.toString(nums)); + } + + public static void stoogeSort(int[] L) { + stoogeSort(L, 0, L.length - 1); + } + + public static void stoogeSort(int[] L, int i, int j) { + if (L[j] < L[i]) { + int tmp = L[i]; + L[i] = L[j]; + L[j] = tmp; + } + if (j - i > 1) { + int t = (j - i + 1) / 3; + stoogeSort(L, i, j - t); + stoogeSort(L, i + t, j); + stoogeSort(L, i, j - t); + } + } +} diff --git a/Task/Sorting-algorithms-Stooge-sort/Lua/sorting-algorithms-stooge-sort.lua b/Task/Sorting-algorithms-Stooge-sort/Lua/sorting-algorithms-stooge-sort.lua new file mode 100644 index 0000000000..805403f2bd --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Lua/sorting-algorithms-stooge-sort.lua @@ -0,0 +1,26 @@ +local Y = function (f) + return (function(x) return x(x) end)(function(x) return f(function(...) return x(x)(...) end) end) +end + +function stoogesort(L, pred) + + pred = pred or function(a,b) return a < b end + + Y(function(recurse) + return function(i,j) + if pred(L[j], L[i]) then + L[j],L[i] = L[i],L[j] + end + if j - i > 1 then + local t = math.floor((j - i + 1)/3) + recurse(i,j-t) + recurse(i+t,j) + recurse(i,j-t) + end + end + end)(1,#L) + + return L +end + +print(unpack(stoogesort{9,7,8,5,6,3,4,2,1,0})) diff --git a/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-1.m b/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-1.m new file mode 100644 index 0000000000..39a6f97126 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-1.m @@ -0,0 +1,18 @@ +%Required inputs: +%i = 1 +%j = length(list) +% +function list = stoogeSort(list,i,j) + + if list(j) < list(i) + list([i j]) = list([j i]); + end + + if (j - i) > 1 + t = round((j-i+1)/3); + list = stoogeSort(list,i,j-t); + list = stoogeSort(list,i+t,j); + list = stoogeSort(list,i,j-t); + end + +end diff --git a/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-2.m b/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-2.m new file mode 100644 index 0000000000..3a4e18f599 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/MATLAB/sorting-algorithms-stooge-sort-2.m @@ -0,0 +1,5 @@ +>> stoogeSort([1 -6 4 -9],1,4) + +ans = + + -9 -6 1 4 diff --git a/Task/Sorting-algorithms-Stooge-sort/Mathematica/sorting-algorithms-stooge-sort.math b/Task/Sorting-algorithms-Stooge-sort/Mathematica/sorting-algorithms-stooge-sort.math new file mode 100644 index 0000000000..019353f45c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Mathematica/sorting-algorithms-stooge-sort.math @@ -0,0 +1,11 @@ +stoogeSort[lst_, I_, J_] := Module[{i = I, j = J, list = lst}, + + If[list[[j]] < list[[i]], list[[{i,j}]] = list[[{j,i}]];] + + If[(j-i) > 1, t = Round[(j-i+1)/3]; + list=stoogeSort[list,i,j-t]; + list=stoogeSort[list,i+t,j]; + list=stoogeSort[list,i,j-t];]; + + list +] diff --git a/Task/Sorting-algorithms-Stooge-sort/NetRexx/sorting-algorithms-stooge-sort.netrexx b/Task/Sorting-algorithms-Stooge-sort/NetRexx/sorting-algorithms-stooge-sort.netrexx new file mode 100644 index 0000000000..62fc9be8d6 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/NetRexx/sorting-algorithms-stooge-sort.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +iList = [int 1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] +sList = Arrays.copyOf(iList, iList.length) + +sList = stoogeSort(sList) + +lists = [iList, sList] +loop ln = 0 to lists.length - 1 + cl = lists[ln] + rpt = Rexx('') + loop ct = 0 to cl.length - 1 + rpt = rpt cl[ct] + end ct + say '['rpt.strip().changestr(' ', ',')']' + end ln + +return + +method stoogeSort(L_ = int[], i_ = 0, j_ = L_.length - 1) public static returns int[] + + if L_[j_] < L_[i_] then do + Lt = L_[i_] + L_[i_] = L_[j_] + L_[j_] = Lt + end + if j_ - i_ > 1 then do + t_ = (j_ - i_ + 1) % 3 + L_ = stoogeSort(L_, i_, j_ - t_) + L_ = stoogeSort(L_, i_ + t_, j_) + L_ = stoogeSort(L_, i_, j_ - t_) + end + + return L_ diff --git a/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-1.ocaml b/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-1.ocaml new file mode 100644 index 0000000000..1cdd542cfc --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-1.ocaml @@ -0,0 +1,17 @@ +let swap ar i j = + let tmp = ar.(i) in + ar.(i) <- ar.(j); + ar.(j) <- tmp + +let stoogesort ar = + let rec aux i j = + if ar.(j) < ar.(i) then + swap ar i j + else if j - i > 1 then begin + let t = (j - i + 1) / 3 in + aux (i) (j-t); + aux (i+t) (j); + aux (i) (j-t); + end + in + aux 0 (Array.length ar - 1) diff --git a/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-2.ocaml b/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-2.ocaml new file mode 100644 index 0000000000..57cf915ef0 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/OCaml/sorting-algorithms-stooge-sort-2.ocaml @@ -0,0 +1,5 @@ +let () = + let ar = [| 3; 1; 7; 2; 6; 5; 4; 9; 8 |] in + stoogesort ar; + Array.iter (Printf.printf " %d") ar; + print_newline() diff --git a/Task/Sorting-algorithms-Stooge-sort/Objeck/sorting-algorithms-stooge-sort.objeck b/Task/Sorting-algorithms-Stooge-sort/Objeck/sorting-algorithms-stooge-sort.objeck new file mode 100644 index 0000000000..d35e0b20cb --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Objeck/sorting-algorithms-stooge-sort.objeck @@ -0,0 +1,31 @@ +bundle Default { + class Stooge { + function : Main(args : String[]) ~ Nil { + nums := [1, 4, 5, 3, -6, 3, 7, 10, -2, -5]; + StoogeSort(nums); + each(i : nums) { + IO.Console->Print(nums[i])->Print(","); + }; + IO.Console->PrintLine(); + } + + function : native : StoogeSort(l : Int[]) ~ Nil { + StoogeSort(l, 0, l->Size() - 1); + } + + function : native : StoogeSort(l : Int[], i : Int, j : Int) ~ Nil { + if(l[j] < l[i]) { + tmp := l[i]; + l[i] := l[j]; + l[j] := tmp; + }; + + if(j - i > 1) { + t := (j - i + 1) / 3; + StoogeSort(l, i, j - t); + StoogeSort(l, i + t, j); + StoogeSort(l, i, j - t); + }; + } + } +} diff --git a/Task/Sorting-algorithms-Stooge-sort/Oz/sorting-algorithms-stooge-sort.oz b/Task/Sorting-algorithms-Stooge-sort/Oz/sorting-algorithms-stooge-sort.oz new file mode 100644 index 0000000000..44bc31e531 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Oz/sorting-algorithms-stooge-sort.oz @@ -0,0 +1,40 @@ +declare + proc {StoogeSort Arr} + proc {Swap I J} + Tmp = Arr.I + in + Arr.I := Arr.J + Arr.J := Tmp + end + + proc {Sort I J} + Size = J-I+1 + in + if Arr.J < Arr.I then + {Swap I J} + end + if Size >= 3 then + Third = Size div 3 + in + {Sort I J-Third} + {Sort I+Third J} + {Sort I J-Third} + end + end + in + {Sort {Array.low Arr} {Array.high Arr}} + end + + Arr = {Tuple.toArray unit(1 4 5 3 ~6 3 7 10 ~2 ~5 7 5 9 ~3 7)} +in + {System.printInfo "\nUnsorted: "} + for I in {Array.low Arr}..{Array.high Arr} do + {System.printInfo Arr.I#", "} + end + + {StoogeSort Arr} + + {System.printInfo "\nSorted : "} + for I in {Array.low Arr}..{Array.high Arr} do + {System.printInfo Arr.I#", "} + end diff --git a/Task/Sorting-algorithms-Stooge-sort/PARI-GP/sorting-algorithms-stooge-sort.pari b/Task/Sorting-algorithms-Stooge-sort/PARI-GP/sorting-algorithms-stooge-sort.pari new file mode 100644 index 0000000000..192a73ca43 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PARI-GP/sorting-algorithms-stooge-sort.pari @@ -0,0 +1,20 @@ +stoogeSort(v)={ + local(v=v); \\ Give children access to v + ss(1,#v); \\ Sort + v +} + +ss(i,j)={ + my(t); + if(v[j]<v[i], + t=v[i]; + v[i]=v[j]; + v[j]=t + ); + if(j-i > 1, + t=(1+j-i)\3; + ss(i,j-t); + ss(i+t,j); + ss(i,j-t) + ) +}; diff --git a/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php b/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php new file mode 100644 index 0000000000..e40e271d7c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php @@ -0,0 +1,14 @@ +function stoogeSort(&$arr, $i, $j) +{ + if($arr[$j] < $arr[$i]) + { + list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); + } + if(($j - $i) > 1) + { + $t = ($j - $i + 1) / 3; + stoogesort($arr, $i, $j - $t); + stoogesort($arr, $i + $t, $j); + stoogesort($arr, $i, $j - $t); + } +} diff --git a/Task/Sorting-algorithms-Stooge-sort/PL-I/sorting-algorithms-stooge-sort.pli b/Task/Sorting-algorithms-Stooge-sort/PL-I/sorting-algorithms-stooge-sort.pli new file mode 100644 index 0000000000..738f08fd7c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PL-I/sorting-algorithms-stooge-sort.pli @@ -0,0 +1,17 @@ +stoogesort: procedure (L) recursive; /* 16 August 2010 */ + declare L(*) fixed binary; + declare (i, j, t, temp) fixed binary; + + j = hbound(L,1); + do i = lbound(L, 1) to j; + if L(j) < L(i) then + do; temp = L(i); L(i) = L(j); L(j) = temp; end; + if j - i > 1 then + do; + t = (j - i + 1)/3; + call stoogesort(L, i , j-t); + call stoogesort(L, i+t, j ); + call stoogesort(L, i , j-t); + end; + end; +end stoogesort; diff --git a/Task/Sorting-algorithms-Stooge-sort/Pascal/sorting-algorithms-stooge-sort.pascal b/Task/Sorting-algorithms-Stooge-sort/Pascal/sorting-algorithms-stooge-sort.pascal new file mode 100644 index 0000000000..d40ab2dfda --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Pascal/sorting-algorithms-stooge-sort.pascal @@ -0,0 +1,46 @@ +program StoogeSortDemo; + +type + TIntArray = array of integer; + +procedure stoogeSort(var m: TIntArray; i, j: integer); + var + t, temp: integer; + begin + if m[j] < m[i] then + begin + temp := m[j]; + m[j] := m[i]; + m[i] := temp; + end; + if j - i > 1 then + begin + t := (j - i + 1) div 3; + stoogesort(m, i, j-t); + stoogesort(m, i+t, j); + stoogesort(m, i, j-t); + end; + end; + +var + data: TIntArray; + i: integer; + +begin + setlength(data, 8); + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + stoogeSort(data, low(data), high(data)); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Stooge-sort/Perl-6/sorting-algorithms-stooge-sort.pl6 b/Task/Sorting-algorithms-Stooge-sort/Perl-6/sorting-algorithms-stooge-sort.pl6 new file mode 100644 index 0000000000..317ce1011a --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Perl-6/sorting-algorithms-stooge-sort.pl6 @@ -0,0 +1,17 @@ +sub stoogesort( @L is rw, $i = 0, $j = @L.end ) { + @L[$j,$i] = @L[$i,$j] if @L[$i] > @L[$j]; + + my $interval = $j - $i; + + if $interval > 1 { + my $t = ( $interval + 1 ) div 3; + stoogesort( @L, $i , $j-$t ); + stoogesort( @L, $i+$t, $j ); + stoogesort( @L, $i , $j-$t ); + } + return @L; +} + +my @L = 1, 4, 5, 3, -6, 3, 7, 10, -2, -5; + +stoogesort(@L).Str.say; diff --git a/Task/Sorting-algorithms-Stooge-sort/Perl/sorting-algorithms-stooge-sort.pl b/Task/Sorting-algorithms-Stooge-sort/Perl/sorting-algorithms-stooge-sort.pl new file mode 100644 index 0000000000..ec7b6f637c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Perl/sorting-algorithms-stooge-sort.pl @@ -0,0 +1,23 @@ +sub stooge { + use integer; + my ($x, $i, $j) = @_; + + $i //= 0; + $j //= $#$x; + + if ( $x->[$j] < $x->[$i] ) { + @$x[$i, $j] = @$x[$j, $i]; + } + if ( $j - $i > 1 ) { + my $t = ($j - $i + 1) / 3; + stooge( $x, $i, $j - $t ); + stooge( $x, $i + $t, $j ); + stooge( $x, $i, $j - $t ); + } +} + + +my @a = map (int rand(100), 1 .. 10); +print "Before @a\n"; +stooge(\@a); +print "After @a\n"; diff --git a/Task/Sorting-algorithms-Stooge-sort/PicoLisp/sorting-algorithms-stooge-sort.l b/Task/Sorting-algorithms-Stooge-sort/PicoLisp/sorting-algorithms-stooge-sort.l new file mode 100644 index 0000000000..48adfcb56d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PicoLisp/sorting-algorithms-stooge-sort.l @@ -0,0 +1,11 @@ +(de stoogeSort (L N) + (default N (length L)) + (let P (nth L N) + (when (> (car L) (car P)) + (xchg L P) ) ) + (when (> N 2) + (let D (/ N 3) + (stoogeSort L (- N D)) + (stoogeSort (nth L (inc D)) (- N D)) + (stoogeSort L (- N D)) ) ) + L ) diff --git a/Task/Sorting-algorithms-Stooge-sort/PowerBASIC/sorting-algorithms-stooge-sort.powerbasic b/Task/Sorting-algorithms-Stooge-sort/PowerBASIC/sorting-algorithms-stooge-sort.powerbasic new file mode 100644 index 0000000000..7dbc64460d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PowerBASIC/sorting-algorithms-stooge-sort.powerbasic @@ -0,0 +1,41 @@ +%arraysize = 10 + +SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG) + IF L(j) < L(i) THEN SWAP L(i), L(j) + IF (j - i) > 1 THEN + DIM t AS LONG + t = (j - i + 1) / 3 + stoogesort L(), i, j - t + stoogesort L(), i + t, j + stoogesort L(), i, j - t + END IF +END SUB + +FUNCTION PBMAIN () AS LONG + RANDOMIZE TIMER + + DIM x(%arraysize) AS LONG + DIM i AS LONG, s AS STRING + + s = "Before: " + FOR i = 0 TO %arraysize + x(i) = INT(RND * 100) + s = s & STR$(x(i)) & " " + NEXT + + stoogesort x(), 0, %arraysize + + #IF %DEF(%PB_CC32) + PRINT s + s = "" + #ELSE + s = s & $CRLF + #ENDIF + + s = s & "After: " + FOR i = 0 TO %arraysize + s = s & STR$(x(i)) & " " + NEXT + + ? s +END FUNCTION diff --git a/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.psh b/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.psh new file mode 100644 index 0000000000..e232f91697 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.psh @@ -0,0 +1,22 @@ +Function StoogeSort( [Int32[]] $L ) +{ + $i = 0 + $j = $L.length-1 + if( $L[$j] -lt $L[$i] ) + { + $L[$i] = $L[$i] -bxor $L[$j] + $L[$j] = $L[$i] -bxor $L[$j] + $L[$i] = $L[$i] -bxor $L[$j] + } + if( $j -gt 1 ) + { + $t = [int] ( ( $j + 1 ) / 3 ) + $k = $j - $t + 1 + [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) + [Array]::ConstrainedCopy( [Int32[]] ( StoogeSort( $L[$t..$j ] ) ), 0, $L, $t, $k ) + [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) + } + $L +} + +StoogeSort 9, 7, 5, 3, 1, 2, 4, 6, 8 diff --git a/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-1.purebasic b/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-1.purebasic new file mode 100644 index 0000000000..49c9aacd51 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-1.purebasic @@ -0,0 +1,14 @@ +Procedure Stooge_Sort(Array L.i(1), i=0 , j=0) + If j=0 + j=ArraySize(L()) + EndIf + If L(i)>L(j) + Swap L(i), L(j) + EndIf + If j-i>1 + Protected t=(j-i+1)/3 + Stooge_Sort(L(), i, j-t) + Stooge_Sort(L(), i+t, j ) + Stooge_Sort(L(), i, j-t) + EndIf +EndProcedure diff --git a/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-2.purebasic b/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-2.purebasic new file mode 100644 index 0000000000..5d75107e51 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PureBasic/sorting-algorithms-stooge-sort-2.purebasic @@ -0,0 +1,15 @@ +Define AmountOfPosts=(?Stop_Data-?Start_data)/SizeOf(Integer) +Dim Xyz.i(AmountOfPosts) +CopyMemory(?Start_data, @Xyz(), ?Stop_Data-?Start_data) + +Stooge_Sort(Xyz()) + +For i=0 To ArraySize(Xyz()) + Debug Xyz(i) +Next i + +DataSection + Start_data: + Data.i 1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7 + Stop_Data: +EndDataSection diff --git a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py new file mode 100644 index 0000000000..a2cfc8b70c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py @@ -0,0 +1,15 @@ +>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] +>>> def stoogesort(L, i=0, j=None): + if j is None: + j = len(L) - 1 + if L[j] < L[i]: + L[i], L[j] = L[j], L[i] + if j - i > 1: + t = (j - i + 1) // 3 + stoogesort(L, i , j-t) + stoogesort(L, i+t, j ) + stoogesort(L, i , j-t) + return L + +>>> stoogesort(data) +[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10] diff --git a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py new file mode 100644 index 0000000000..ff797d404c --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py @@ -0,0 +1,15 @@ +>>> def stoogesort(L, i, j): + if L[j] < L[i]: + L[i], L[j] = L[j], L[i] + if j - i > 1: + t = (j - i + 1) // 3 + stoogesort(L, i , j-t) + stoogesort(L, i+t, j ) + stoogesort(L, i , j-t) + return L + +>>> def stooge(L): return stoogesort(L, 0, len(L) - 1) + +>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] +>>> stooge(data) +[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10] diff --git a/Task/Sorting-algorithms-Stooge-sort/REXX/sorting-algorithms-stooge-sort.rexx b/Task/Sorting-algorithms-Stooge-sort/REXX/sorting-algorithms-stooge-sort.rexx new file mode 100644 index 0000000000..9352a30531 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/REXX/sorting-algorithms-stooge-sort.rexx @@ -0,0 +1,35 @@ +/*REXX program to sort an integer array L [elements start at zero]. */ +highItem=19 /*define 0 ──► 19 elements. */ +widthH=length(highItem) /*width of biggest element number*/ +widthL=0 /*width of largest element value.*/ + + do k=0 to highItem /*populate the array with stuff. */ + L.k=2*k + (k * -1**k) /*kinda generate randomish nums. */ + if L.k==0 then L.k=-100-k /*if zero, make a negative number*/ + widthL=max(widthL,length(L.k)) /*compute maximum width so far. */ + end /*k*/ + +call showL 'before sort' /*show the before array elements.*/ +call stoogeSort 0,highItem /*invoke the Stooge Sort. */ +call showL ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SHOWL subroutine────────────────────*/ +showL: sepLength=22+widthH+widthL /*compute separator width. */ +say copies('-',sepLength) /*show the 1st separator line. */ + + do j=0 to highItem + say 'element' right(j,widthH) arg(1)":" right(L.j,widthL) + end /*j*/ + +say copies('=', sepLength) /*show the 2nd separator line. */ +return +/*──────────────────────────────────STOOGESORT subroutine───────────────*/ +stoogeSort: procedure expose L.; parse arg i,j /*sort from I ──> J.*/ +if L.j<L.i then parse value L.i L.j with L.j L.i /*swap L.i with L.j*/ +if j-i>1 then do + t=(j-i+1) % 3 /* % is REXX integer division. */ + call stoogesort i , j-t + call stoogesort i+t, j + call stoogesort i , j-t + end +return diff --git a/Task/Sorting-algorithms-Stooge-sort/Ruby/sorting-algorithms-stooge-sort.rb b/Task/Sorting-algorithms-Stooge-sort/Ruby/sorting-algorithms-stooge-sort.rb new file mode 100644 index 0000000000..a1cbc4d081 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Ruby/sorting-algorithms-stooge-sort.rb @@ -0,0 +1,20 @@ +class Array + def stoogesort + self.dup.stoogesort! + end + + def stoogesort!(i = 0, j = self.length-1) + if self[j] < self[i] + self[i], self[j] = self[j], self[i] + end + if j - i > 1 + t = (j - i + 1)/3 + stoogesort!(i, j-t) + stoogesort!(i+t, j) + stoogesort!(i, j-t) + end + self + end +end + +p [1,4,5,3,-6,3,7,10,-2,-5].stoogesort diff --git a/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort.st b/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort.st new file mode 100644 index 0000000000..2de18c5d9d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort.st @@ -0,0 +1,24 @@ +OrderedCollection extend [ + stoogeSortFrom: i to: j [ + (self at: j) < (self at: i) + ifTrue: [ self swapElement: i with: j ]. + j - i > 1 + ifTrue: [ + |t| t := (j - i + 1)//3. + self stoogeSortFrom: i to: (j-t). + self stoogeSortFrom: (i+t) to: j. + self stoogeSortFrom: i to: (j-t) + ] + ] + stoogeSort [ self stoogeSortFrom: 1 to: (self size) ] + swapElement: i with: j [ + |t| t := self at: i. + self at: i put: (self at: j). + self at: j put: t + ] +]. + +|test| +test := #( 1 4 5 3 -6 3 7 10 -2 -5) asOrderedCollection. +test stoogeSort. +test printNl. diff --git a/Task/Sorting-algorithms-Stooge-sort/Tcl/sorting-algorithms-stooge-sort.tcl b/Task/Sorting-algorithms-Stooge-sort/Tcl/sorting-algorithms-stooge-sort.tcl new file mode 100644 index 0000000000..e088c1191d --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Tcl/sorting-algorithms-stooge-sort.tcl @@ -0,0 +1,22 @@ +package require Tcl 8.5 + +proc stoogesort {L {i 0} {j -42}} { + if {$j == -42} {# Magic marker + set j [expr {[llength $L]-1}] + } + set Li [lindex $L $i] + set Lj [lindex $L $j] + if {$Lj < $Li} { + lset L $i $Lj + lset L $j $Li + } + if {$j-$i > 1} { + set t [expr {($j-$i+1)/3}] + set L [stoogesort $L $i [expr {$j-$t}]] + set L [stoogesort $L [expr {$i+$t}] $j] + set L [stoogesort $L $i [expr {$j-$t}]] + } + return $L +} + +stoogesort {1 4 5 3 -6 3 7 10 -2 -5} diff --git a/Task/Sorting-algorithms-Stooge-sort/XPL0/sorting-algorithms-stooge-sort.xpl0 b/Task/Sorting-algorithms-Stooge-sort/XPL0/sorting-algorithms-stooge-sort.xpl0 new file mode 100644 index 0000000000..444e150ccb --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/XPL0/sorting-algorithms-stooge-sort.xpl0 @@ -0,0 +1,20 @@ +code ChOut=8, IntOut=11; \intrinsic routines + +proc StoogeSort(L, I, J); \Sort array L +int L, I, J; +int T; +[if L(J) < L(I) then + [T:= L(I); L(I):= L(J); L(J):= T]; \swap +if J-I > 1 then + [T:= (J-I+1)/3; + StoogeSort(L, I, J-T); + StoogeSort(L, I+T, J); + StoogeSort(L, I, J-T); + ]; +]; + +int A, I; +[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; +StoogeSort(A, 0, 10-1); +for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; +] diff --git a/Task/Sorting-algorithms-Stooge-sort/Yorick/sorting-algorithms-stooge-sort.yorick b/Task/Sorting-algorithms-Stooge-sort/Yorick/sorting-algorithms-stooge-sort.yorick new file mode 100644 index 0000000000..5602f288d7 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Yorick/sorting-algorithms-stooge-sort.yorick @@ -0,0 +1,12 @@ +func stoogesort(&L, i, j) { + if(is_void(i)) i = 1; + if(is_void(j)) j = numberof(L); + if(L(j) < L(i)) + L([i,j]) = L([j,i]); + if(j - i > 1) { + t = (j - i + 1)/3; + stoogesort, L, i, j-t; + stoogesort, L, i+t, j; + stoogesort, L, i, j-t; + } +} diff --git a/Task/Sorting-algorithms-Strand-sort/0DESCRIPTION b/Task/Sorting-algorithms-Strand-sort/0DESCRIPTION new file mode 100644 index 0000000000..371a72a1a0 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/0DESCRIPTION @@ -0,0 +1,3 @@ +{{Sorting Algorithm}} +{{Wikipedia|Strand sort}} +Implement the [[wp:Strand sort|Strand sort]]. This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list. diff --git a/Task/Sorting-algorithms-Strand-sort/1META.yaml b/Task/Sorting-algorithms-Strand-sort/1META.yaml new file mode 100644 index 0000000000..42def8b652 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Sorting Algorithms diff --git a/Task/Sorting-algorithms-Strand-sort/C++/sorting-algorithms-strand-sort.cpp b/Task/Sorting-algorithms-Strand-sort/C++/sorting-algorithms-strand-sort.cpp new file mode 100644 index 0000000000..1cc990fb6b --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/C++/sorting-algorithms-strand-sort.cpp @@ -0,0 +1,22 @@ +#include <list> + +template <typename T> +std::list<T> strandSort(std::list<T> lst) { + if (lst.size() <= 1) + return lst; + std::list<T> result; + std::list<T> sorted; + while (!lst.empty()) { + sorted.push_back(lst.front()); + lst.pop_front(); + for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) { + if (sorted.back() <= *it) { + sorted.push_back(*it); + it = lst.erase(it); + } else + it++; + } + result.merge(sorted); + } + return result; +} diff --git a/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-1.c b/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-1.c new file mode 100644 index 0000000000..60f4c9c228 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-1.c @@ -0,0 +1,78 @@ +#include <stdio.h> + +typedef struct node_t *node, node_t; +struct node_t { int v; node next; }; +typedef struct { node head, tail; } slist; + +void push(slist *l, node e) { + if (!l->head) l->head = e; + if (l->tail) l->tail->next = e; + l->tail = e; +} + +node removehead(slist *l) { + node e = l->head; + if (e) { + l->head = e->next; + e->next = 0; + } + return e; +} + +void join(slist *a, slist *b) { + push(a, b->head); + a->tail = b->tail; +} + +void merge(slist *a, slist *b) { + slist r = {0}; + while (a->head && b->head) + push(&r, removehead(a->head->v <= b->head->v ? a : b)); + + join(&r, a->head ? a : b); + *a = r; + b->head = b->tail = 0; +} + +void sort(int *ar, int len) +{ + node_t all[len]; + + // array to list + for (int i = 0; i < len; i++) + all[i].v = ar[i], all[i].next = i < len - 1 ? all + i + 1 : 0; + + slist list = {all, all + len - 1}, rem, strand = {0}, res = {0}; + + for (node e = 0; list.head; list = rem) { + rem.head = rem.tail = 0; + while ((e = removehead(&list))) + push((!strand.head || e->v >= strand.tail->v) ? &strand : &rem, e); + + merge(&res, &strand); + } + + // list to array + for (int i = 0; res.head; i++, res.head = res.head->next) + ar[i] = res.head->v; +} + +void show(const char *title, int *x, int len) +{ + printf("%s ", title); + for (int i = 0; i < len; i++) + printf("%3d ", x[i]); + putchar('\n'); +} + +int main(void) +{ + int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2}; +# define SIZE sizeof(x)/sizeof(int) + + show("before sort:", x, SIZE); + sort(x, sizeof(x)/sizeof(int)); + show("after sort: ", x, SIZE); + + return 0; +} diff --git a/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-2.c b/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-2.c new file mode 100644 index 0000000000..fcb43f0bc6 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/C/sorting-algorithms-strand-sort-2.c @@ -0,0 +1,2 @@ +before sort: -2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 +after sort: -4 -3 -2 -2 -1 0 0 2 2 3 4 5 5 5 5 diff --git a/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-1.cmake b/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-1.cmake new file mode 100644 index 0000000000..0e3857c125 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-1.cmake @@ -0,0 +1,62 @@ +# strand_sort(<output variable> [<value>...]) sorts a list of integers. +function(strand_sort var) + # Strand sort moves elements from _ARGN_ to _answer_. + set(answer) # answer: a sorted list + while(DEFINED ARGN) + # Split _ARGN_ into two lists, _accept_ and _reject_. + set(accept) # accept: elements in sorted order + set(reject) # reject: all other elements + set(p) + foreach(e ${ARGN}) + if(DEFINED p AND p GREATER ${e}) + list(APPEND reject ${e}) + else() + list(APPEND accept ${e}) + set(p ${e}) + endif() + endforeach(e) + + # Prepare to merge _accept_ into _answer_. First, convert both lists + # into arrays, for better indexing: set(e ${answer${i}}) is faster + # than list(GET answer ${i} e). + set(la 0) + foreach(e ${answer}) + math(EXPR la "${la} + 1") + set(answer${la} ${e}) + endforeach(e) + set(lb 0) + foreach(e ${accept}) + math(EXPR lb "${lb} + 1") + set(accept${lb} ${e}) + endforeach(e) + + # Merge _accept_ into _answer_. + set(answer) + set(ia 1) + set(ib 1) + while(NOT ia GREATER ${la}) # Iterate elements of _answer_. + set(ea ${answer${ia}}) + while(NOT ib GREATER ${lb}) # Take elements from _accept_, + set(eb ${accept${ib}}) # while they are less than + if(eb LESS ${ea}) # next element of _answer_. + list(APPEND answer ${eb}) + math(EXPR ib "${ib} + 1") + else() + break() + endif() + endwhile() + list(APPEND answer ${ea}) # Take next from _answer_. + math(EXPR ia "${ia} + 1") + endwhile() + while(NOT ib GREATER ${lb}) # Take rest of _accept_. + list(APPEND answer ${accept${ib}}) + math(EXPR ib "${ib} + 1") + endwhile() + + # This _reject_ becomes next _ARGN_. If _reject_ is empty, then + # set(ARGN) undefines _ARGN_, breaking the loop. + set(ARGN ${reject}) + endwhile(DEFINED ARGN) + + set("${var}" ${answer} PARENT_SCOPE) +endfunction(strand_sort) diff --git a/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-2.cmake b/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-2.cmake new file mode 100644 index 0000000000..8023596630 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/CMake/sorting-algorithms-strand-sort-2.cmake @@ -0,0 +1,2 @@ +strand_sort(result 11 55 55 44 11 33 33 44 22 22) +message(STATUS "${result}") # -- 11;11;22;22;33;33;44;44;55;55 diff --git a/Task/Sorting-algorithms-Strand-sort/Clojure/sorting-algorithms-strand-sort.clj b/Task/Sorting-algorithms-Strand-sort/Clojure/sorting-algorithms-strand-sort.clj new file mode 100644 index 0000000000..80587efaac --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Clojure/sorting-algorithms-strand-sort.clj @@ -0,0 +1,35 @@ +(ns rosettacode.strand-sort) + +(defn merge-join + "Produces a globally sorted seq from two sorted seqables" + [[a & la :as all] [b & lb :as bll]] + (cond (nil? a) bll + (nil? b) all + (< a b) (cons a (lazy-seq (merge-join la bll))) + true (cons b (lazy-seq (merge-join all lb))))) + +(defn unbraid + "Separates a sorted list from a sequence" + [u] + (when (seq u) + (loop [[x & xs] u + u [] + s [] + e x] + (if (nil? x) + [s u] + (if (>= x e) + (recur xs u (conj s x) x) + (recur xs (conj u x) s e)))))) + +(defn strand-sort + "http://en.wikipedia.org/wiki/Strand_sort" + [s] + (loop [[s u] (unbraid s) + m nil] + (if s + (recur (unbraid u) (merge-join m s)) + m))) + +(strand-sort [1, 6, 3, 2, 1, 7, 5, 3]) +;;=> (1 1 2 3 3 5 6 7) diff --git a/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-1.lisp b/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-1.lisp new file mode 100644 index 0000000000..f4ab900e79 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-1.lisp @@ -0,0 +1,11 @@ +(defun strand-sort (l cmp) + (if l + (let* ((l (reverse l)) + (o (list (car l))) n) + (loop for i in (cdr l) do + (push i (if (funcall cmp (car o) i) n o))) + (merge 'list o (strand-sort n cmp) #'<)))) + +(let ((r (loop repeat 15 collect (random 10)))) + (print r) + (print (strand-sort r #'<))) diff --git a/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-2.lisp b/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-2.lisp new file mode 100644 index 0000000000..df6854b48b --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Common-Lisp/sorting-algorithms-strand-sort-2.lisp @@ -0,0 +1,2 @@ +(5 8 6 0 6 8 4 7 0 7 1 5 3 3 6) +(0 0 1 3 3 4 5 5 6 6 6 7 7 8 8) 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 new file mode 100644 index 0000000000..8d85f190cb --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort.d @@ -0,0 +1,44 @@ +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/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.euphoria b/Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.euphoria new file mode 100644 index 0000000000..cc33d5f53b --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.euphoria @@ -0,0 +1,43 @@ +function merge(sequence left, sequence right) + sequence result + result = {} + while length(left) > 0 and length(right) > 0 do + if left[$] <= right[1] then + exit + elsif right[$] <= left[1] then + return result & right & left + elsif left[1] < right[1] then + result = append(result,left[1]) + left = left[2..$] + else + result = append(result,right[1]) + right = right[2..$] + end if + end while + return result & left & right +end function + +function strand_sort(sequence s) + integer j + sequence result + result = {} + while length(s) > 0 do + j = length(s) + for i = 1 to length(s)-1 do + if s[i] > s[i+1] then + j = i + exit + end if + end for + + result = merge(result,s[1..j]) + s = s[j+1..$] + end while + return result +end function + +constant s = rand(repeat(1000,10)) +puts(1,"Before: ") +? s +puts(1,"After: ") +? strand_sort(s) diff --git a/Task/Sorting-algorithms-Strand-sort/Go/sorting-algorithms-strand-sort.go b/Task/Sorting-algorithms-Strand-sort/Go/sorting-algorithms-strand-sort.go new file mode 100644 index 0000000000..32f7651880 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Go/sorting-algorithms-strand-sort.go @@ -0,0 +1,93 @@ +package main + +import "fmt" + +type link struct { + int + next *link +} + +func linkInts(s []int) *link { + if len(s) == 0 { + return nil + } + return &link{s[0], linkInts(s[1:])} +} + +func (l *link) String() string { + if l == nil { + return "nil" + } + r := fmt.Sprintf("[%d", l.int) + for l = l.next; l != nil; l = l.next { + r = fmt.Sprintf("%s %d", r, l.int) + } + return r + "]" +} + +func main() { + a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) + fmt.Println("before:", a) + b := strandSort(a) + fmt.Println("after: ", b) +} + +func strandSort(a *link) (result *link) { + for a != nil { + // build sublist + sublist := a + a = a.next + sTail := sublist + for p, pPrev := a, a; p != nil; p = p.next { + if p.int > sTail.int { + // append to sublist + sTail.next = p + sTail = p + // remove from a + if p == a { + a = p.next + } else { + pPrev.next = p.next + } + } else { + pPrev = p + } + } + sTail.next = nil // terminate sublist + if result == nil { + result = sublist + continue + } + // merge + var m, rr *link + if sublist.int < result.int { + m = sublist + sublist = m.next + rr = result + } else { + m = result + rr = m.next + } + result = m + for { + if sublist == nil { + m.next = rr + break + } + if rr == nil { + m.next = sublist + break + } + if sublist.int < rr.int { + m.next = sublist + m = sublist + sublist = m.next + } else { + m.next = rr + m = rr + rr = m.next + } + } + } + return +} diff --git a/Task/Sorting-algorithms-Strand-sort/Haskell/sorting-algorithms-strand-sort.hs b/Task/Sorting-algorithms-Strand-sort/Haskell/sorting-algorithms-strand-sort.hs new file mode 100644 index 0000000000..4940b2162e --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Haskell/sorting-algorithms-strand-sort.hs @@ -0,0 +1,16 @@ +-- Same merge as in Merge Sort +merge :: (Ord a) => [a] -> [a] -> [a] +merge [] ys = ys +merge xs [] = xs +merge (x : xs) (y : ys) + | x <= y = x : merge xs (y : ys) + | otherwise = y : merge (x : xs) ys + +strandSort :: (Ord a) => [a] -> [a] +strandSort [] = [] +strandSort (x : xs) = merge strand (strandSort rest) where + (strand, rest) = extractStrand x xs + extractStrand x [] = ([x], []) + extractStrand x (x1 : xs) + | x <= x1 = let (strand, rest) = extractStrand x1 xs in (x : strand, rest) + | otherwise = let (strand, rest) = extractStrand x xs in (strand, x1 : rest) diff --git a/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-1.j b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-1.j new file mode 100644 index 0000000000..0a1a5f7452 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-1.j @@ -0,0 +1 @@ +strandSort=: (#~ merge $:^:(0<#)@(#~ -.)) (= >./\) diff --git a/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-2.j b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-2.j new file mode 100644 index 0000000000..41cf1828fb --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-2.j @@ -0,0 +1,2 @@ + strandSort 3 1 5 4 2 +1 2 3 4 5 diff --git a/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-3.j b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-3.j new file mode 100644 index 0000000000..8a62a0a430 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/J/sorting-algorithms-strand-sort-3.j @@ -0,0 +1,8 @@ + ((#~ ; $:^:(0<#)@(#~ -.)) (= >./\)) 3 1 5 4 2 +┌───┬───┬─┬┐ +│3 5│1 4│2││ +└───┴───┴─┴┘ + ((#~ ; $:^:(0<#)@(#~ -.)) (= >./\)) 3 3 1 2 4 3 5 6 +┌─────────┬─────┬┐ +│3 3 4 5 6│1 2 3││ +└─────────┴─────┴┘ diff --git a/Task/Sorting-algorithms-Strand-sort/Java/sorting-algorithms-strand-sort.java b/Task/Sorting-algorithms-Strand-sort/Java/sorting-algorithms-strand-sort.java new file mode 100644 index 0000000000..11b9b5b996 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Java/sorting-algorithms-strand-sort.java @@ -0,0 +1,46 @@ +import java.util.Arrays; +import java.util.LinkedList; + +public class Strand{ + // note: the input list is destroyed + public static <E extends Comparable<? super E>> + LinkedList<E> strandSort(LinkedList<E> list){ + if(list.size() <= 1) return list; + + LinkedList<E> result = new LinkedList<E>(); + while(list.size() > 0){ + LinkedList<E> sorted = new LinkedList<E>(); + sorted.add(list.removeFirst()); //same as remove() or remove(0) + for(Iterator<E> it = list.iterator(); it.hasNext(); ){ + E elem = it.next(); + if(sorted.peekLast().compareTo(elem) <= 0){ + sorted.addLast(elem); //same as add(elem) or add(0, elem) + it.remove(); + } + } + result = merge(sorted, result); + } + return result; + } + + private static <E extends Comparable<? super E>> + LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){ + LinkedList<E> result = new LinkedList<E>(); + while(!left.isEmpty() && !right.isEmpty()){ + //change the direction of this comparison to change the direction of the sort + if(left.peek().compareTo(right.peek()) <= 0) + result.add(left.remove()); + else + result.add(right.remove()); + } + result.addAll(left); + result.addAll(right); + return result; + } + + public static void main(String[] args){ + System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5)))); + System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5)))); + System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6)))); + } +} diff --git a/Task/Sorting-algorithms-Strand-sort/Mathematica/sorting-algorithms-strand-sort.math b/Task/Sorting-algorithms-Strand-sort/Mathematica/sorting-algorithms-strand-sort.math new file mode 100644 index 0000000000..b1ec844295 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Mathematica/sorting-algorithms-strand-sort.math @@ -0,0 +1,8 @@ +StrandSort[ input_ ] := Module[ {results = {}, A = input}, +While[Length@A > 0, + sublist = {A[[1]]}; A = A[[2;;All]]; + For[i = 1, i < Length@A, i++, + If[ A[[i]] > Last@sublist, AppendTo[sublist, A[[i]]]; A = Delete[A, i];] + ]; + results = #[[Ordering@#]]&@Join[sublist, results];]; +results ] diff --git a/Task/Sorting-algorithms-Strand-sort/NetRexx/sorting-algorithms-strand-sort.netrexx b/Task/Sorting-algorithms-Strand-sort/NetRexx/sorting-algorithms-strand-sort.netrexx new file mode 100644 index 0000000000..f2593b9d52 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/NetRexx/sorting-algorithms-strand-sort.netrexx @@ -0,0 +1,73 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +import java.util.List + +placesList = [String - + "UK London", "US New York", "US Boston", "US Washington" - + , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - +] + +lists = [ - + placesList - + , strandSort(String[] Arrays.copyOf(placesList, placesList.length)) - +] + +loop ln = 0 to lists.length - 1 + cl = lists[ln] + loop ct = 0 to cl.length - 1 + say cl[ct] + end ct + say + end ln + +return + +method strandSort(A = String[]) public constant binary returns String[] + + rl = String[A.length] + al = List strandSort(Arrays.asList(A)) + al.toArray(rl) + + return rl + +method strandSort(Alst = List) public constant binary returns ArrayList + + A = ArrayList(Alst) + result = ArrayList() + loop label A_ while A.size > 0 + sublist = ArrayList() + sublist.add(A.get(0)) + A.remove(0) + loop i_ = 0 while i_ < A.size - 1 + if (Comparable A.get(i_)).compareTo(Comparable sublist.get(sublist.size - 1)) > 0 then do + sublist.add(A.get(i_)) + A.remove(i_) + end + end i_ + result = merge(result, sublist) + end A_ + + return result + +method merge(left = List, right = List) public constant binary returns ArrayList + + result = ArrayList() + loop label mx while left.size > 0 & right.size > 0 + if (Comparable left.get(0)).compareTo(Comparable right.get(0)) <= 0 then do + result.add(left.get(0)) + left.remove(0) + end + else do + result.add(right.get(0)) + right.remove(0) + end + end mx + if left.size > 0 then do + result.addAll(left) + end + if right.size > 0 then do + result.addAll(right) + end + + return result diff --git a/Task/Sorting-algorithms-Strand-sort/OCaml/sorting-algorithms-strand-sort.ocaml b/Task/Sorting-algorithms-Strand-sort/OCaml/sorting-algorithms-strand-sort.ocaml new file mode 100644 index 0000000000..812b3ef19d --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/OCaml/sorting-algorithms-strand-sort.ocaml @@ -0,0 +1,12 @@ +let rec strand_sort (cmp : 'a -> 'a -> int) : 'a list -> 'a list = function + [] -> [] + | x::xs -> + let rec extract_strand x = function + [] -> [x], [] + | x1::xs when cmp x x1 <= 0 -> + let strand, rest = extract_strand x1 xs in x::strand, rest + | x1::xs -> + let strand, rest = extract_strand x xs in strand, x1::rest + in + let strand, rest = extract_strand x xs in + List.merge cmp strand (strand_sort cmp rest) diff --git a/Task/Sorting-algorithms-Strand-sort/PARI-GP/sorting-algorithms-strand-sort.pari b/Task/Sorting-algorithms-Strand-sort/PARI-GP/sorting-algorithms-strand-sort.pari new file mode 100644 index 0000000000..aad5062188 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/PARI-GP/sorting-algorithms-strand-sort.pari @@ -0,0 +1,30 @@ +strandSort(v)={ + my(sorted=[],unsorted=v,remaining,working); + while(#unsorted, + remaining=working=List(); + listput(working, unsorted[1]); + for(i=2,#unsorted, + if(unsorted[i]<working[#working], + listput(remaining, unsorted[i]) + , + listput(working, unsorted[i]) + ) + ); + unsorted=Vec(remaining); + sorted=merge(sorted, Vec(working)) + ); + sorted +}; +merge(u,v)={ + my(ret=vector(#u+#v),i=1,j=1); + for(k=1,#ret, + if(i<=#u & (j>#v | u[i]<v[j]), + ret[k]=u[i]; + i++ + , + ret[k]=v[j]; + j++ + ) + ); + ret +}; diff --git a/Task/Sorting-algorithms-Strand-sort/PHP/sorting-algorithms-strand-sort.php b/Task/Sorting-algorithms-Strand-sort/PHP/sorting-algorithms-strand-sort.php new file mode 100644 index 0000000000..31bd91dc92 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/PHP/sorting-algorithms-strand-sort.php @@ -0,0 +1,38 @@ +$lst = new SplDoublyLinkedList(); +foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) + $lst->push($v); +foreach (strandSort($lst) as $v) + echo "$v "; + +function strandSort(SplDoublyLinkedList $lst) { + $result = new SplDoublyLinkedList(); + while (!$lst->isEmpty()) { + $sorted = new SplDoublyLinkedList(); + $remain = new SplDoublyLinkedList(); + $sorted->push($lst->shift()); + foreach ($lst as $item) { + if ($sorted->top() <= $item) { + $sorted->push($item); + } else { + $remain->push($item); + } + } + $result = _merge($sorted, $result); + $lst = $remain; + } + return $result; +} + +function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { + $res = new SplDoublyLinkedList(); + while (!$left->isEmpty() && !$right->isEmpty()) { + if ($left->bottom() <= $right->bottom()) { + $res->push($left->shift()); + } else { + $res->push($right->shift()); + } + } + foreach ($left as $v) $res->push($v); + foreach ($right as $v) $res->push($v); + return $res; +} diff --git a/Task/Sorting-algorithms-Strand-sort/PL-I/sorting-algorithms-strand-sort.pli b/Task/Sorting-algorithms-Strand-sort/PL-I/sorting-algorithms-strand-sort.pli new file mode 100644 index 0000000000..e5fbee3880 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/PL-I/sorting-algorithms-strand-sort.pli @@ -0,0 +1,91 @@ +strand: procedure options (main); /* 27 Oct. 2012 */ + declare A(100) fixed, used(100) bit (1), sorted fixed controlled; + declare (temp, work) fixed controlled; + declare (i, j, k, n) fixed binary; + + n = hbound(A, 1); + used = '1'b; + A = random()*99; + + put edit (A) (f(3)); + + do while (allocation(sorted) < n); + call fetch (A, work); + call move (temp, work); + + call merge(sorted, temp); + /* Merges elements in SORTED with elements in TEMP. */ + end; + /* Transfer the sorted elements to A. */ + do i = 1 to allocation(sorted); + A(i) = sorted; free sorted; + end; + /* Print the sorted values. */ + put skip list ('The sorted values are:'); + put skip edit (A) (f(3)); + +/* Merges elements of SORTED with elements of TEMP and places */ +/* the result in SORTED. */ +/* Elements in SORTED and TEMP are in forward order. */ +merge: procedure (sorted, temp); + declare (sorted, temp) fixed controlled; + declare work fixed controlled; + declare (j_ok, k_ok) bit (1); + + do until ((k_ok | j_ok) = '0'b); + k_ok = allocation(sorted) > 0; + j_ok = allocation(temp) > 0; + if k_ok & j_ok then + do; + if sorted <= temp then + do; allocate work; work = sorted; free sorted; end; + else + do; allocate work; work = temp; free temp; end; + end; + else + if allocation(temp) = 0 then + /* temp is empty; copy remainder of sorted into work */ + do while (allocation(sorted) > 0); + allocate work; work = sorted; free sorted; + end; + else + /* sorted is empty; copy remainder of temp onto work */ + do while (allocation(temp) > 0); + allocate work; work = temp; free temp; + end; + end; + + call move (sorted, work); /* Move the values to SORTED. */ + +end merge; + +/* Collect a thread of ascending values from aray A, and stack them in temp. */ +/* Note: the values in temp are in reverse order. */ +fetch: procedure (A, temp); + declare A(*) fixed, temp controlled fixed; + declare i fixed binary; + + do i = 1 to hbound(A,1); + if used(i) then + do; allocate temp; temp = A(i); used(i) = '0'b; go to found; end; + end; +found: + do i = i+1 to hbound(A,1); + if (temp <= A(i)) & used(i) then + do; allocate temp; temp = A(i); used(i) = '0'b; end; + end; +end fetch; + +/* Copy the stack at TEMP to the stack at SORTED. */ +/* In TEMP, elements are in reverse order; */ +/* in SORTED, elements are in forward order. */ +move: procedure (sorted, temp); + declare (sorted, temp) fixed controlled; + + do while (allocation(sorted) > 0); free sorted; end; + do while (allocation (temp) > 0); + allocate sorted; sorted = temp; free temp; + end; +end move; + +end strand; diff --git a/Task/Sorting-algorithms-Strand-sort/Pascal/sorting-algorithms-strand-sort.pascal b/Task/Sorting-algorithms-Strand-sort/Pascal/sorting-algorithms-strand-sort.pascal new file mode 100644 index 0000000000..d4998674ae --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Pascal/sorting-algorithms-strand-sort.pascal @@ -0,0 +1,79 @@ +program StrandSortDemo; + +type + TIntArray = array of integer; + +function merge(left: TIntArray; right: TIntArray): TIntArray; + var + i, j, k: integer; + begin + setlength(merge, length(left) + length(right)); + i := low(merge); + j := low(left); + k := low(right); + repeat + if ((left[j] <= right[k]) and (j <= high(left))) or (k > high(right)) then + begin + merge[i] := left[j]; + inc(j); + end + else + begin + merge[i] := right[k]; + inc(k); + end; + inc(i); + until i > high(merge); + end; + +function StrandSort(s: TIntArray): TIntArray; + var + strand: TIntArray; + i, j: integer; + begin + setlength(StrandSort, length(s)); + setlength(strand, length(s)); + i := low(s); + repeat + StrandSort[i] := s[i]; + inc(i); + until (s[i] < s[i-1]); + setlength(StrandSort, i); + repeat + setlength(strand, 1); + j := low(strand); + strand[j] := s[i]; + while (s[i+1] > s[i]) and (i < high(s)) do + begin + inc(i); + inc(j); + setlength(strand, length(strand) + 1); + Strand[j] := s[i]; + end; + StrandSort := merge(StrandSort, strand); + inc(i); + until (i > high(s)); + end; + +var + data: TIntArray; + i: integer; + +begin + setlength(data, 8); + Randomize; + writeln('The data before sorting:'); + for i := low(data) to high(data) do + begin + data[i] := Random(high(data)); + write(data[i]:4); + end; + writeln; + data := StrandSort(data); + writeln('The data after sorting:'); + for i := low(data) to high(data) do + begin + write(data[i]:4); + end; + writeln; +end. diff --git a/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 b/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 new file mode 100644 index 0000000000..7bbeff70b1 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Perl-6/sorting-algorithms-strand-sort.pl6 @@ -0,0 +1,41 @@ +sub infix:<M> (@x, @y) { + gather { + while @x and @y { + given @x[0] cmp @y[0] { + when Increase { take @x.shift } + when Decrease { take @y.shift } + when Same { take @x.shift, @y.shift } + } + } + take @x, @y; + } +} + +sub strand (@x is rw) { + my $prev = -Inf; + my $i = 0; + gather while $i < @x { + if @x[$i] before $prev { + $i++; + } + else { + take $prev = splice(@x, $i, 1)[0]; + } + } +} + +sub strand_sort (@x is copy) { + my @out; + @out M= strand(@x) while @x; + @out; +} + +my @a = (^100).roll(10); +say "Before @a[]"; +@a = strand_sort(@a); +say "After @a[]"; + +@a = <The quick brown fox jumps over the lazy dog>; +say "Before @a[]"; +@a = strand_sort(@a); +say "After @a[]"; diff --git a/Task/Sorting-algorithms-Strand-sort/Perl/sorting-algorithms-strand-sort.pl b/Task/Sorting-algorithms-Strand-sort/Perl/sorting-algorithms-strand-sort.pl new file mode 100644 index 0000000000..98989a0826 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Perl/sorting-algorithms-strand-sort.pl @@ -0,0 +1,40 @@ +use 5.10.0; # for given/when +sub merge { + my ($x, $y) = @_; + my @out; + while (@$x and @$y) { + given ($x->[-1] <=> $y->[-1]) { + when( 1) { unshift @out, pop @$x } + when(-1) { unshift @out, pop @$y } + default { splice @out, 0, 0, pop(@$x), pop(@$y) } + } + } + return @$x, @$y, @out +} + +sub strand { + my $x = shift; + my @out = shift @$x // return; + if (@$x) { + for (-@$x .. -1) { + if ($x->[$_] >= $out[-1]) { + push @out, splice @$x, $_, 1 + } + } + } + return @out +} + +sub strand_sort { + my @x = @_; + my @out; + while (my @strand = strand(\@x)) { + @out = merge(\@out, \@strand) + } + @out +} + +my @a = map (int rand(100), 1 .. 10); +say "Before @a"; +@a = strand_sort(@a); +say "After @a"; diff --git a/Task/Sorting-algorithms-Strand-sort/PicoLisp/sorting-algorithms-strand-sort.l b/Task/Sorting-algorithms-Strand-sort/PicoLisp/sorting-algorithms-strand-sort.l new file mode 100644 index 0000000000..963e1b6614 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/PicoLisp/sorting-algorithms-strand-sort.l @@ -0,0 +1,21 @@ +(de strandSort (Lst) + (let Res NIL # Result list + (while Lst + (let Sub (circ (car Lst)) # Build sublist as fifo + (setq + Lst (filter + '((X) + (or + (> (car Sub) X) + (nil (fifo 'Sub X)) ) ) + (cdr Lst) ) + Res (make + (while (or Res Sub) # Merge + (link + (if2 Res Sub + (if (>= (car Res) (cadr Sub)) + (fifo 'Sub) + (pop 'Res) ) + (pop 'Res) + (fifo 'Sub) ) ) ) ) ) ) ) + Res ) ) diff --git a/Task/Sorting-algorithms-Strand-sort/PureBasic/sorting-algorithms-strand-sort.purebasic b/Task/Sorting-algorithms-Strand-sort/PureBasic/sorting-algorithms-strand-sort.purebasic new file mode 100644 index 0000000000..e5e2f52041 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/PureBasic/sorting-algorithms-strand-sort.purebasic @@ -0,0 +1,82 @@ +Procedure strandSort(List a()) + Protected NewList subList() + Protected NewList results() + + While ListSize(a()) > 0 + ClearList(subList()) + AddElement(subList()) + FirstElement(a()) + subList() = a() + DeleteElement(a()) + ForEach a() + If a() >= subList() + AddElement(subList()) + subList() = a() + DeleteElement(a()) + EndIf + Next + + ;merge lists + FirstElement(subList()) + If Not FirstElement(results()) + ;copy all of sublist() to results() + MergeLists(subList(), results(), #PB_List_Last) + Else + Repeat + If subList() < results() + InsertElement(results()) + results() = subList() + DeleteElement(subList()) + If Not NextElement(subList()) + Break + EndIf + ElseIf Not NextElement(results()) + ;add remainder of sublist() to end of results() + MergeLists(subList(), results(), #PB_List_Last) + Break + EndIf + ForEver + EndIf + + Wend + CopyList(results(), a()) +EndProcedure + +Procedure.s listContents(List a()) + Protected output.s + PushListPosition(a()) + ForEach a() + output + Str(a()) + "," + Next + PopListPosition(a()) + ProcedureReturn Left(output, Len(output) - 1) +EndProcedure + +Procedure setupList(List a()) + ClearList(a()) + Protected elementCount, i + + elementCount = Random(5) + 10 + For i = 1 To elementCount + AddElement(a()) + a() = Random(10) - 5 + Next +EndProcedure + + +If OpenConsole() + NewList sample() + Define i + + For i = 1 To 3 + setupList(sample()) + PrintN("List " + Str(i) + ":") + PrintN(" Before: " + listContents(sample())) + strandSort(sample()) + PrintN(" After : " + listContents(sample())) + PrintN("") + Next + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-1.py b/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-1.py new file mode 100644 index 0000000000..1541b95ec3 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-1.py @@ -0,0 +1,27 @@ +def merge_list(a, b): + out = [] + while len(a) and len(b): + if a[0] < b[0]: + out.append(a.pop(0)) + else: + out.append(b.pop(0)) + out += a + out += b + return out + +def strand(a): + i, s = 0, [a.pop(0)] + while i < len(a): + if a[i] > s[-1]: + s.append(a.pop(i)) + else: + i += 1 + return s + +def strand_sort(a): + out = strand(a) + while len(a): + out = merge_list(out, strand(a)) + return out + +print strand_sort([1, 6, 3, 2, 1, 7, 5, 3]) diff --git a/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-2.py b/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-2.py new file mode 100644 index 0000000000..7edaa8aabb --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Python/sorting-algorithms-strand-sort-2.py @@ -0,0 +1 @@ +[1, 1, 2, 3, 3, 5, 6, 7] diff --git a/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx new file mode 100644 index 0000000000..0be8a3d765 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx @@ -0,0 +1,32 @@ +/*REXX program uses a strand sort to sort a random list of words | nums.*/ +parse arg size minv maxv,old /*get options from command line. */ +if size=='' then size=20 /*no size? Then use the default.*/ +if minv=='' then minv=0 /*no minV? " " " " */ +if maxv=='' then maxv=size /*no maxV? " " " " */ + do i=1 for size /*generate random # list*/ + old=old random(0,maxv-minv)+minv + end /*i*/ +old=space(old) /*remove any extraneous blanks. */ +say center('unsorted list',length(old),"="); say old; say +new=strand_sort(old) /*sort the list of random numbers*/ +say center('sorted list' ,length(new),"="); say new +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────STRAND_SORT subroutine──────────────*/ +strand_sort: procedure; parse arg x; y= + do while words(x)\==0; w=words(x) + do j=1 for w-1 /*any number|word out of order?*/ + if word(x,j)>word(x,j+1) then do; w=j; leave; end + end /*j*/ + y=merge(y,subword(x,1,w)); x=subword(x,w+1) + end /*while words(x)\==0*/ +return y +/*──────────────────────────────────MERGE subroutine────────────────────*/ +merge: procedure; parse arg a.1,a.2; p= + do forever /*keep at it while 2 lists exist.*/ + do i=1 to 2; w.i=words(a.i); end /*find number of entries in lists*/ + if w.1*w.2==0 then leave /*if any list is empty, then stop*/ + if word(a.1,w.1) <= word(a.2,1) then leave /*lists are now sorted?*/ + if word(a.2,w.2) <= word(a.1,1) then return space(p a.2 a.1) + #=1+(word(a.1,1) >= word(a.2,1)); p=p word(a.#,1); a.#=subword(a.#,2) + end /*forever*/ +return space(p a.1 a.2) diff --git a/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb new file mode 100644 index 0000000000..ba23a270fe --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb @@ -0,0 +1,34 @@ +class Array + def strandsort + a = self.dup + result = [] + while a.length > 0 + sublist = [a.shift] + a.each_with_index . + inject([]) do |remove, (val, idx)| + if val > sublist[-1] + sublist << val + remove.unshift(idx) + end + remove + end . + each {|idx| a.delete_at(idx)} + + idx = 0 + while idx < result.length and not sublist.empty? + if sublist[0] < result[idx] + result.insert(idx, sublist.shift) + end + idx += 1 + end + result += sublist if not sublist.empty? + end + result + end + + def strandsort! + self.replace(strandsort) + end +end + +p [1, 6, 3, 2, 1, 7, 5, 3].strandsort diff --git a/Task/Sorting-algorithms-Strand-sort/Tcl/sorting-algorithms-strand-sort.tcl b/Task/Sorting-algorithms-Strand-sort/Tcl/sorting-algorithms-strand-sort.tcl new file mode 100644 index 0000000000..2a33ea7a49 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Tcl/sorting-algorithms-strand-sort.tcl @@ -0,0 +1,41 @@ +proc merge {listVar toMerge} { + upvar 1 $listVar v + set i [set j 0] + set out {} + while {$i<[llength $v] && $j<[llength $toMerge]} { + if {[set a [lindex $v $i]] < [set b [lindex $toMerge $j]]} { + lappend out $a + incr i + } else { + lappend out $b + incr j + } + } + # Done the merge, but will be one source with something left + # This will handle all that by doing a merge of the remnants onto the end + set v [concat $out [lrange $v $i end] [lrange $toMerge $j end]] + return +} + +proc strandSort A { + set results {} + while {[llength $A]} { + set sublist [lrange $A 0 0] + # We build a list of items that weren't filtered rather than removing "in place" + # because this fits better with the way Tcl values work (the underlying data + # structure is an array, not a linked list). + set newA {} + foreach a [lrange $A 1 end] { + if {$a > [lindex $sublist end]} { + lappend sublist $a + } else { + lappend newA $a + } + } + set A $newA + merge results $sublist + } + return $results +} + +puts [strandSort {3 1 5 4 2}] diff --git a/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-1.ursala b/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-1.ursala new file mode 100644 index 0000000000..22d9ddeaed --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-1.ursala @@ -0,0 +1,5 @@ +strand_sort "r" = # parameterized by a relational predicate "r" + +@NiX -+ + :-0 ~&B^?a\~&Y@a "r"?abh/~&alh2faltPrXPRC ~&arh2falrtPXPRC, + ~&r->l ^|rlPlCrrPX/~& @hNCNXtX ~&r->lbx "r"?rllPXh/~&llPrhPlrPCXrtPX ~&rhPllPClrPXrtPX+- diff --git a/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-2.ursala b/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-2.ursala new file mode 100644 index 0000000000..740618882e --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Ursala/sorting-algorithms-strand-sort-2.ursala @@ -0,0 +1,3 @@ +#cast %nL + +x = (strand_sort nat-nleq) <3,1,5,4,2> diff --git a/Task/Soundex/0DESCRIPTION b/Task/Soundex/0DESCRIPTION new file mode 100644 index 0000000000..01957a1e49 --- /dev/null +++ b/Task/Soundex/0DESCRIPTION @@ -0,0 +1 @@ +Soundex is an algorithm for creating indices for words based on their pronunciation. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from [[wp:soundex|the WP article]]). diff --git a/Task/Soundex/1META.yaml b/Task/Soundex/1META.yaml new file mode 100644 index 0000000000..35429e6214 --- /dev/null +++ b/Task/Soundex/1META.yaml @@ -0,0 +1,2 @@ +--- +note: text processing diff --git a/Task/Soundex/ALGOL-68/soundex.alg b/Task/Soundex/ALGOL-68/soundex.alg new file mode 100644 index 0000000000..e6f3285acc --- /dev/null +++ b/Task/Soundex/ALGOL-68/soundex.alg @@ -0,0 +1,65 @@ + PROC soundex = (STRING s) STRING: + BEGIN + PROC encode = (CHAR c) CHAR: + BEGIN + # We assume the alphabet is contiguous. # + "-123-12*-22455-12623-1*2-2"[ABS to lower(c) - ABS "a" + 1] + END; + INT soundex code length = 4; + STRING result := soundex code length * "0"; + IF s /= "" THEN + CHAR previous; + INT j; + result[j := 1] := s[1]; + previous := encode(s[1]); + FOR i FROM 2 TO UPB s WHILE j < soundex code length + DO + IF is alpha(s[i]) THEN + CHAR code = encode(s[i]); + IF is digit(code) AND code /= previous THEN + result[j +:= 1] := code; + previous := code + ELIF code = "-" THEN + # Only vowels (y counts here) hide the last-added character # + previous := code + FI + FI + OD + FI; + result + END; + + # Test code to persuade one that it does work. # + + MODE TEST = STRUCT (STRING input, STRING expected output); + + [] TEST soundex test = ( + ("Soundex", "S532"), ("Example", "E251"), + ("Sownteks", "S532"), ("Ekzampul", "E251"), + ("Euler", "E460"), ("Gauss", "G200"), + ("Hilbert", "H416"), ("Knuth", "K530"), + ("Lloyd", "L300"), ("Lukasiewicz", "L222"), + ("Ellery", "E460"), ("Ghosh", "G200"), + ("Heilbronn", "H416"), ("Kant", "K530"), + ("Ladd", "L300"), ("Lissajous", "L222"), + ("Wheaton", "W350"), ("Burroughs", "B620"), + ("Burrows", "B620"), ("O'Hara", "O600"), + ("Washington", "W252"), ("Lee", "L000"), + ("Gutierrez", "G362"), ("Pfister", "P236"), + ("Jackson", "J250"), ("Tymczak", "T522"), + ("VanDeusen", "V532"), ("Ashcraft", "A261") + ); + + # + Apologies for the magic number in the padding of the input + and the wired-in heading. + # + + print(("Test name Code Got", newline, "----------------------", newline)); + FOR i FROM LWB soundex test TO UPB soundex test + DO + STRING output = soundex(input OF soundex test[i]); + printf(($g, n (12 - UPB input OF soundex test[i]) x$, input OF soundex test[i])); + printf(($g, 1x, g, 1x$, expected output OF soundex test[i], output)); + printf(($b("ok", "not ok"), 1l$, output = expected output OF soundex test[i])) + OD diff --git a/Task/Soundex/AWK/soundex.awk b/Task/Soundex/AWK/soundex.awk new file mode 100644 index 0000000000..9763af6b74 --- /dev/null +++ b/Task/Soundex/AWK/soundex.awk @@ -0,0 +1,59 @@ +#!/usr/bin/awk -f +BEGIN { + subsep = ", " + delete homs +} + +/^[a-zA-Z]/ { + sdx = strToSoundex($0) + addHom(sdx, $0) +} + +END { + showHoms(3) +} + +function strToSoundex(s, sdx, i, ch, cd, lch) { + if (length(s) == 0) return "" + s = tolower(s) + lch = substr(s, 1, 1); + sdx = toupper(lch) + lch = charToSoundex(lch) + for (i = 2; i <= length(s); i++) { + ch = substr(s, i, 1) + cd = charToSoundex(ch) + if (cd == 7) continue; + if (cd && cd != lch) sdx = sdx cd + lch = cd + } + sdx = substr(sdx "0000", 1, 4) + return sdx +} + +function charToSoundex(ch, cd) { + if (ch ~ /[bfpv]/) cd = 1 + else if (ch ~ /[cgjkqsxz]/) cd = 2 + else if (ch ~ /[dt]/) cd = 3 + else if (ch == "l") cd = 4 + else if (ch ~ /[mn]/) cd = 5 + else if (ch == "r") cd = 6 + else if (ch ~ /[hw]/) cd = 7 + else cd = 0 + return cd; +} + +function addHom(sdx, word) { + if (!(homs[sdx])) homs[sdx] = "" + homs[sdx] = homs[sdx] (homs[sdx] == "" ? "" : subsep) word +} + +function showHoms(toShow, i, n, wl, j) { + for (i in homs) { + printf i " " + n = split(homs[i], wl, subsep) + for (j = 1; j <= toShow && j <= n; j++) { + printf wl[j] " " + } + print (n > toShow ? "..." : "") + } +} diff --git a/Task/Soundex/Ada/soundex.ada b/Task/Soundex/Ada/soundex.ada new file mode 100644 index 0000000000..25378b9318 --- /dev/null +++ b/Task/Soundex/Ada/soundex.ada @@ -0,0 +1,42 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Characters.Handling; use Ada.Characters.Handling; +procedure Soundex is + type UStrings is array(Natural range <>) of Unbounded_String; + function "+"(S:String) return Unbounded_String renames To_Unbounded_String; + + function toSoundex (instr : String) return String is + str : String := To_Upper(instr); + output : String := "0000"; + spos : Integer := str'First+1; opos : Positive := 2; + map : array(0..255) of Character := (others => ' '); + last : Integer := str'First; + begin + map(65..90) := " 123 12- 22455 12623 1-2 2"; + for i in str'Range loop str(i) := map(Character'Pos(str(i))); end loop; + output(1) := str(str'First); + while (opos <= 4 and spos <= str'Last) loop + if str(spos) /= '-' and str(spos) /= ' ' then + if (str(spos-1) = '-' and last = spos-2) and then + (str(spos) = str(spos-2)) then null; + elsif (str(spos) = output(opos-1) and last = spos-1) then last := spos; + else output(opos) := str(spos); opos := opos + 1; last := spos; + end if; + end if; + spos := spos + 1; + end loop; + output(1) := To_Upper(instr(instr'First)); + return output; + end toSoundex; + + cases : constant UStrings := (+"Soundex", +"Example", +"Sownteks", + +"Ekzampul", +"Euler", +"Gauss", +"Hilbert", +"Knuth", +"Lloyd", + +"Lukasiewicz", +"Ellery", +"Ghosh", +"Heilbronn", +"Kant", + +"Ladd", +"Lissajous", +"Wheaton", +"Burroughs", +"Burrows", + +"O'Hara", +"Washington", +"Lee", +"Gutierrez", +"Pfister", + +"Jackson", +"Tymczak", +"VanDeusen", +"Ashcraft"); +begin + for i in cases'Range loop + Put_Line(To_String(cases(i))&" = "&toSoundex(To_String(cases(i)))); + end loop; +end Soundex; diff --git a/Task/Soundex/AutoHotkey/soundex.ahk b/Task/Soundex/AutoHotkey/soundex.ahk new file mode 100644 index 0000000000..07e36fbe47 --- /dev/null +++ b/Task/Soundex/AutoHotkey/soundex.ahk @@ -0,0 +1,38 @@ +getCode(c){ + If c in B,F,P,V + return 1 + If c in C,G,J,K,Q,S,X,Z + return 2 + If c in D,T + return 3 + If c = L + return 4 + If c in M,N + return 5 + If c = R + return 6 +} + +soundex(s){ + code := SubStr(s, 1, 1) + ,previous := 7 + ,i := 1 + While ++i <= StrLen(s){ + current := getCode(SubStr(s, i, 1)) + If StrLen(current) > 0 And current <> previous + code := code . current + previous := current + } + soundex := SubStr(code, 1, 4) + If StrLen(code) < 4 + soundex .= String(4 - StrLen(code), "0") + return soundex +} + +String(a, n){ + Loop n + o .= a + return a +} + +MsgBox % Soundex("Soundex") "`n" Soundex("Sowndeks") "`n" Soundex("Ashcroft") "`n" Soundex("Ashkrofd") diff --git a/Task/Soundex/BBC-BASIC/soundex.bbc b/Task/Soundex/BBC-BASIC/soundex.bbc new file mode 100644 index 0000000000..b02e2a10de --- /dev/null +++ b/Task/Soundex/BBC-BASIC/soundex.bbc @@ -0,0 +1,28 @@ + DATA Ashcraft, Ashcroft, Gauss, Ghosh, Hilbert, Heilbronn, Lee, Lloyd + DATA Moses, Pfister, Robert, Rupert, Rubin, Tymczak, Soundex, Example + FOR i% = 1 TO 16 + READ name$ + PRINT """" name$ """" TAB(15) FNsoundex(name$) + NEXT + END + + DEF FNsoundex(name$) + LOCAL i%, n%, p%, n$, s$ + name$ = FNupper(name$) + n$ = "01230129022455012623019202" + s$ = LEFT$(name$,1) + p% = VALMID$(n$, ASCs$ - 64, 1) + FOR i% = 2 TO LEN(name$) + n% = VALMID$(n$, ASCMID$(name$,i%,1) - 64, 1) + IF n% IF n% <> 9 IF n% <> p% s$ += STR$(n%) + IF n% <> 9 p% = n% + NEXT + = LEFT$(s$ + "000", 4) + + DEF FNupper(A$) + LOCAL A%,C% + FOR A% = 1 TO LEN(A$) + C% = ASCMID$(A$,A%) + IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32) + NEXT + = A$ diff --git a/Task/Soundex/C-sharp/soundex.cs b/Task/Soundex/C-sharp/soundex.cs new file mode 100644 index 0000000000..3a2ca63f21 --- /dev/null +++ b/Task/Soundex/C-sharp/soundex.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Soundex +{ + internal static class Program + { + private static void Main() + { + var testWords = new TestWords + { + {"Soundex", "S532"}, + {"Example", "E251"}, + {"Sownteks", "S532"}, + {"Ekzampul", "E251"}, + {"Euler", "E460"}, + {"Gauss", "G200"}, + {"Hilbert", "H416"}, + {"Knuth", "K530"}, + {"Lloyd", "L300"}, + {"Lukasiewicz", "L222"}, + {"Ellery", "E460"}, + {"Ghosh", "G200"}, + {"Heilbronn", "H416"}, + {"Kant", "K530"}, + {"Ladd", "L300"}, + {"Lissajous", "L222"}, + {"Wheaton", "W350"}, + {"Burroughs", "B620"}, + {"Burrows", "B620"}, + {"O'Hara", "O600"}, + {"Washington", "W252"}, + {"Lee", "L000"}, + {"Gutierrez", "G362"}, + {"Pfister", "P236"}, + {"Jackson", "J250"}, + {"Tymczak", "T522"}, + {"VanDeusen", "V532"}, + {"Ashcraft", "A261"} + }; + + foreach (var testWord in testWords) + Console.WriteLine("{0} -> {1} ({2})", testWord.Word.PadRight(11), testWord.ActualSoundex, + (testWord.ExpectedSoundex == testWord.ActualSoundex)); + } + + // List<TestWord> wrapper to make declaration simpler. + private class TestWords : List<TestWord> + { + public void Add(string word, string expectedSoundex) + { + Add(new TestWord(word, expectedSoundex)); + } + } + + private class TestWord + { + public TestWord(string word, string expectedSoundex) + { + Word = word; + ExpectedSoundex = expectedSoundex; + ActualSoundex = Soundex(word); + } + + public string Word { get; private set; } + public string ExpectedSoundex { get; private set; } + public string ActualSoundex { get; private set; } + } + + private static string Soundex(string word) + { + const string soundexAlphabet = "0123012#02245501262301#202"; + string soundexString = ""; + char lastSoundexChar = '?'; + word = word.ToUpper(); + + foreach (var c in from ch in word + where ch >= 'A' && + ch <= 'Z' && + soundexString.Length < 4 + select ch) + { + char thisSoundexChar = soundexAlphabet[c - 'A']; + + if (soundexString.Length == 0) + soundexString += c; + else if (thisSoundexChar == '#') + continue; + else if (thisSoundexChar != '0' && + thisSoundexChar != lastSoundexChar) + soundexString += thisSoundexChar; + + lastSoundexChar = thisSoundexChar; + } + + return soundexString.PadRight(4, '0'); + } + } +} diff --git a/Task/Soundex/C/soundex.c b/Task/Soundex/C/soundex.c new file mode 100644 index 0000000000..3ed494ed44 --- /dev/null +++ b/Task/Soundex/C/soundex.c @@ -0,0 +1,97 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> + +/* for ASCII only */ +static char code[128] = { 0 }; +void add_code(const char *s, int c) +{ + while (*s) { + code[(int)*s] = code[0x20 ^ (int)*s] = c; + s++; + } +} + +void init() +{ + static const char *cls[] = + { "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0}; + int i; + for (i = 0; cls[i]; i++) + add_code(cls[i], i - 1); +} + +/* returns a static buffer; user must copy if want to save + result across calls */ +const char* soundex(const char *s) +{ + static char out[5]; + int c, prev, i; + + out[0] = out[4] = 0; + if (!s || !*s) return out; + + out[0] = *s++; + + /* first letter, though not coded, can still affect next letter: Pfister */ + prev = code[(int)out[0]]; + for (i = 1; *s && i < 4; s++) { + if ((c = code[(int)*s]) == prev) continue; + + if (c == -1) prev = 0; /* vowel as separator */ + else if (c > 0) { + out[i++] = c + '0'; + prev = c; + } + } + while (i < 4) out[i++] = '0'; + return out; +} + +int main() +{ + int i; + const char *sdx, *names[][2] = { + {"Soundex", "S532"}, + {"Example", "E251"}, + {"Sownteks", "S532"}, + {"Ekzampul", "E251"}, + {"Euler", "E460"}, + {"Gauss", "G200"}, + {"Hilbert", "H416"}, + {"Knuth", "K530"}, + {"Lloyd", "L300"}, + {"Lukasiewicz", "L222"}, + {"Ellery", "E460"}, + {"Ghosh", "G200"}, + {"Heilbronn", "H416"}, + {"Kant", "K530"}, + {"Ladd", "L300"}, + {"Lissajous", "L222"}, + {"Wheaton", "W350"}, + {"Burroughs", "B620"}, + {"Burrows", "B620"}, + {"O'Hara", "O600"}, + {"Washington", "W252"}, + {"Lee", "L000"}, + {"Gutierrez", "G362"}, + {"Pfister", "P236"}, + {"Jackson", "J250"}, + {"Tymczak", "T522"}, + {"VanDeusen", "V532"}, + {"Ashcraft", "A261"}, + {0, 0} + }; + + init(); + + puts(" Test name Code Got\n----------------------"); + for (i = 0; names[i][0]; i++) { + sdx = soundex(names[i][0]); + printf("%11s %s %s ", names[i][0], names[i][1], sdx); + printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok"); + } + + return 0; +} diff --git a/Task/Soundex/COBOL/soundex.cobol b/Task/Soundex/COBOL/soundex.cobol new file mode 100644 index 0000000000..ddb4d1ebda --- /dev/null +++ b/Task/Soundex/COBOL/soundex.cobol @@ -0,0 +1,143 @@ +**** soundex-test ********************************************* +* Demonstrate the soundex encoding functions. +*************************************************************** +Identification division. +Program-id. soundex-test. + +Data division. +Working-storage section. +01 sample-word-list. + 05 sample-words. + 10 filler pic x(15) value "soundex". + 10 filler pic x(15) value "example". + 10 filler pic x(15) value "sownteks". + 10 filler pic x(15) value "ekzampul". + 10 filler pic x(15) value "Euler". + 10 filler pic x(15) value "Gauss". + 10 filler pic x(15) value "Hilbert". + 10 filler pic x(15) value "Knuth". + 10 filler pic x(15) value "Lloyd". + 10 filler pic x(15) value "Lukasiewicz". + 10 filler pic x(15) value "Ellery". + 10 filler pic x(15) value "ghosh". + 10 filler pic x(15) value "Heilbronn". + 10 filler pic x(15) value "Kand". + 10 filler pic x(15) value "Ladd". + 10 filler pic x(15) value "lissajous". + 10 filler pic x(15) value "Wheaton". + 10 filler pic x(15) value "Burroughs". + 10 filler pic x(15) value "burrows". + 10 filler pic x(15) value "O'Hara". + 10 filler pic x(15) value "Washington". + 10 filler pic x(15) value "lee". + 10 filler pic x(15) value "Gutierrez". + 10 filler pic x(15) value "Phister". + 10 filler pic x(15) value "Jackson". + 10 filler pic x(15) value "tymczak". + 10 filler pic x(15) value "Vandeusen". + 10 filler pic x(15) value "Ashcraft". + 05 sample-word redefines sample-words + pic x(15) occurs 28 times indexed by wrd-idx. +01 wrd-code pic x999. + +Procedure division. + Perform varying wrd-idx from 1 by 1 until wrd-idx greater than 28 + call "soundex-encode" using + by content sample-word(wrd-idx) + by reference wrd-code + display wrd-code " " sample-word(wrd-idx) + end-perform. + Stop run. + + +*** soundex-encode ******************************************** +* Given a string return its soundex encoding. +*************************************************************** +Identification division. +Program-id. soundex-encode. + +Data division. +Local-storage section. +01 str-idx pic 99. +01 let-code pic 9. +01 prv-let-code pic 9. +01 sdx-idx pic 9 value 1. + +Linkage section. +01 str-to-encode. + 05 str-first-let pic x. + 05 str-rest-let pic x occurs 14 times. +01 sdx-code. + 05 sdx-first-let pic x. + 05 sdx-nums pic 9 occurs 3 times. + +Procedure division using + by content str-to-encode + by reference sdx-code. + Perform encode-start thru encode-done. + Goback. + +Encode-start. + Move zeros to sdx-code. + Move function upper-case(str-first-let) to sdx-first-let. + Call "soundex-char" using + by content str-first-let + by reference let-code. + Move let-code to prv-let-code. + +Encode-string. + Perform varying str-idx from 1 by 1 + until str-idx greater than 15 or sdx-idx greater than 3 + call "soundex-char" using + by content str-rest-let(str-idx) + by reference let-code + if let-code not equal 7 then + if let-code not equal 0 and let-code not equal prv-let-code then + move let-code to sdx-nums(sdx-idx) + add 1 to sdx-idx + end-if + move let-code to prv-let-code + end-if + end-perform. + +Encode-done. + End program soundex-encode. + + +*** soundex-char ********************************************** +* Given a character, return its soundex encoding. +* Code 7 is for h or w, which an encoder should ignore when +* either one separates double letters. +*************************************************************** +Identification division. +Program-id. soundex-char. + +Data division. +Local-storage section. +01 lc-chr pic x. + 88 code1 value "b", "f", "p", "v". + 88 code2 value "c", "g", "j", "k", "q", "s", "x", "z". + 88 code3 value "d", "t". + 88 code4 value "l". + 88 code5 value "m", "n". + 88 code6 value "r". + 88 code7 value "h", "w". + +Linkage section. +01 char-to-encode pic x. +01 char-sdx-code pic 9. + +Procedure division using + by content char-to-encode + by reference char-sdx-code. + Move function lower-case(char-to-encode) to lc-chr. + If code1 then move 1 to char-sdx-code + else if code2 then move 2 to char-sdx-code + else if code3 then move 3 to char-sdx-code + else if code4 then move 4 to char-sdx-code + else if code5 then move 5 to char-sdx-code + else if code6 then move 6 to char-sdx-code + else if code7 then move 7 to char-sdx-code + else move 0 to char-sdx-code + end-if. + End program soundex-char. diff --git a/Task/Soundex/Cache-ObjectScript/soundex.cos b/Task/Soundex/Cache-ObjectScript/soundex.cos new file mode 100644 index 0000000000..e7ac0007a6 --- /dev/null +++ b/Task/Soundex/Cache-ObjectScript/soundex.cos @@ -0,0 +1,9 @@ +Class Utils.Phonetic [ Abstract ] +{ + +ClassMethod ToSoundex(String As %String) As %String [ Language = mvbasic ] +{ + Return Soundex(String) +} + +} diff --git a/Task/Soundex/Clipper-XBase++/soundex.clipper b/Task/Soundex/Clipper-XBase++/soundex.clipper new file mode 100644 index 0000000000..b3ab128454 --- /dev/null +++ b/Task/Soundex/Clipper-XBase++/soundex.clipper @@ -0,0 +1,64 @@ +FUNCTION Soundex(cWord) + + /* + + This is a Clipper/XBase++ implementation of the standard American Soundex procedure. + + */ +LOCAL cSoundex, i, nLast, cChar, nCode + +cWord:=ALLTRIM(UPPER(cWord)) +cSoundex:=LEFT(cWord, 1) // first letter is first char +nLast:=-1 +FOR i:=2 TO LEN(cWord) + cChar:=SUBSTR(cWord, i, 1) // get char + nCode:=SoundexCode(cChar) // get soundex code for char + IF nCode=0 // if 0, ignore + LOOP + ENDIF + IF nCode#nLast // if not same code, add to soundex + nLast:=nCode // and replace the last one + cSoundex+=STR(nCode, 1) + ENDIF +NEXT +cSoundex:=PADR(cSoundex, 4, "0") + +RETURN(cSoundex) + +******************************************************************************* +STATIC FUNCTION SoundexCode(cLetter) +LOCAL aCodes:={"BFPV", "CGJKQSXZ", "DT", "L", "MN", "R"}, i, nRet:=0 + +FOR i:=1 TO LEN(aCodes) + IF cLetter $ aCodes[i] + nRet:=i + EXIT + ENDIF +NEXT + +RETURN(nRet) + +******************************************************************************* +FUNCTION SoundexDifference(cSound1, cSound2) +LOCAL nMatch:=0, nLen1, nLen2, i + +nLen1:=LEN(cSound1) +nLen2:=LEN(cSound2) + +// make the two words the same length. This is a safety. They both should be 4 characters long. +IF nLen1 > nLen2 + cSound2:=PADR(cSound2, nLen1-nLen2, "0") +ELSEIF nLen1 < nLen2 + cSound1:=PADR(cSound1, nLen2-nLen1, "0") +ENDIF + +// compare the corresponding characters between the two words +FOR i:=1 TO LEN(cSound1) + IF SUBSTR(cSound1, i, 1) == SUBSTR(cSound2, i, 1) + ++nMatch + ENDIF +NEXT + +RETURN(nMatch) + +******************************************************************************* diff --git a/Task/Soundex/Clojure/soundex.clj b/Task/Soundex/Clojure/soundex.clj new file mode 100644 index 0000000000..2ed505d5c1 --- /dev/null +++ b/Task/Soundex/Clojure/soundex.clj @@ -0,0 +1,20 @@ +(defn get-code [c] + (case c + (\B \F \P \V) 1 + (\C \G \J \K + \Q \S \X \Z) 2 + (\D \T) 3 + \L 4 + (\M \N) 5 + \R 6 + nil)) ;(\A \E \I \O \U \H \W \Y) + +(defn soundex [s] + (let [[f & s] (.toUpperCase s)] + (-> (map get-code s) + distinct + (concat , "0000") + (->> (cons f ,) + (remove nil? ,) + (take 4 ,) + (apply str ,))))) diff --git a/Task/Soundex/Common-Lisp/soundex.lisp b/Task/Soundex/Common-Lisp/soundex.lisp new file mode 100644 index 0000000000..3cbc3e2200 --- /dev/null +++ b/Task/Soundex/Common-Lisp/soundex.lisp @@ -0,0 +1,22 @@ +(defun get-code (c) + (case c + ((#\B #\F #\P #\V) #\1) + ((#\C #\G #\J #\K + #\Q #\S #\X #\Z) #\2) + ((#\D #\T) #\3) + (#\L #\4) + ((#\M #\N) #\5) + (#\R #\6))) + +(defun soundex (s) + (if (zerop (length s)) + "" + (let* ((l (coerce (string-upcase s) 'list)) + (o (list (first l)))) + (loop for c in (rest l) + for cg = (get-code c) and + for cp = #\Z then cg + when (and cg (not (eql cg cp))) do + (push cg o) + finally + (return (subseq (coerce (nreverse `(#\0 #\0 #\0 ,@o)) 'string) 0 4)))))) diff --git a/Task/Soundex/D/soundex-1.d b/Task/Soundex/D/soundex-1.d new file mode 100644 index 0000000000..3c3752ffba --- /dev/null +++ b/Task/Soundex/D/soundex-1.d @@ -0,0 +1,15 @@ +import std.stdio: writeln; +import std.string: soundex; + +void main() { + assert(soundex("soundex") == "S532"); + assert(soundex("example") == "E251"); + assert(soundex("ciondecks") == "C532"); + assert(soundex("ekzampul") == "E251"); + assert(soundex("Robert") == "R163"); + assert(soundex("Rupert") == "R163"); + assert(soundex("Rubin") == "R150"); + assert(soundex("Ashcraft") == "A261"); + assert(soundex("Ashcroft") == "A261"); + assert(soundex("Tymczak") == "T522"); +} diff --git a/Task/Soundex/D/soundex-2.d b/Task/Soundex/D/soundex-2.d new file mode 100644 index 0000000000..890fa5456a --- /dev/null +++ b/Task/Soundex/D/soundex-2.d @@ -0,0 +1,67 @@ +import std.string: toUpper, replace; +import std.ascii: isUpper; + +/***************************** +Soundex is a phonetic algorithm for indexing names by +sound, as pronounced in English. See: +http://en.wikipedia.org/wiki/Soundex +*/ +/*pure nothrow*/ string soundex(in string name) +// Adapted from public domain Python code by Gregory Jorgensen: +// http://code.activestate.com/recipes/52213/ +out(result) { // postcondition + assert(result.length == 4); + assert(result[0] == '0' || isUpper(result[0])); + + if (name.length == 0) + assert(result == "0000"); + + // this is too much fiddly + int charCount = 0; + foreach (dchar c; name) + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) + charCount++; + assert((charCount == 0) == (result == "0000")); +} body { + // digits holds the soundex values for the alphabet + static immutable digits = "01230120022455012623010202"; + string firstChar, result; + + // translate alpha chars in name to soundex digits + foreach (dchar c; name.toUpper()) { + if (c >= 'A' && c <= 'Z') { + if (!firstChar.length) + firstChar ~= c; // remember first letter + immutable char d = digits[c - 'A']; + // duplicate consecutive soundex digits are skipped + if (!result.length || d != result[$ - 1]) + result ~= d; + } + } + + // return 0000 if the name is empty + if (!firstChar.length) + return "0000"; + + // replace first digit with first alpha character + assert(result.length > 0); + result = firstChar ~ result[1 .. $]; + + // remove all 0s from the soundex code + result = result.replace("0", ""); // not pure + + // return soundex code padded to 4 zeros + return (result ~ "0000")[0 .. 4]; +} unittest { // tests of soundex() + auto tests = [["", "0000"], ["12346", "0000"], + ["he", "H000"], ["soundex", "S532"], + ["example", "E251"], ["ciondecks", "C532"], + ["ekzampul", "E251"], ["résumé", "R250"], + ["Robert", "R163"], ["Rupert", "R163"], + ["Rubin", "R150"], ["Ashcraft", "A226"], + ["Ashcroft", "A226"]]; + foreach (pair; tests) + assert(soundex(pair[0]) == pair[1]); +} + +void main() {} diff --git a/Task/Soundex/Delphi/soundex.delphi b/Task/Soundex/Delphi/soundex.delphi new file mode 100644 index 0000000000..7ec33d2c14 --- /dev/null +++ b/Task/Soundex/Delphi/soundex.delphi @@ -0,0 +1,15 @@ +program SoundexDemo; + +{$APPTYPE CONSOLE} + +uses + SysUtils, + StrUtils; + +begin + Writeln(Soundex('Soundex')); + Writeln(Soundex('Example')); + Writeln(Soundex('Sownteks')); + Writeln(Soundex('Ekzampul')); + Readln; +end. diff --git a/Task/Soundex/Erlang/soundex.erl b/Task/Soundex/Erlang/soundex.erl new file mode 100644 index 0000000000..c7e911bd95 --- /dev/null +++ b/Task/Soundex/Erlang/soundex.erl @@ -0,0 +1,45 @@ +-module(soundex). +-export([soundex/1]). + +soundex([]) -> + []; +soundex(Str) -> + [Head|Tail] = string:to_upper(Str), + [Head | isoundex(Tail, [], todigit(Head))]. + +isoundex([], Acc, _) -> + case length(Acc) of + N when N == 3 -> + lists:reverse(Acc); + N when N < 3 -> + isoundex([], [$0 | Acc], ignore); + N when N > 3 -> + isoundex([], lists:sublist(Acc, N-2, N), ignore) + end; +isoundex([Head|Tail], Acc, Lastn) -> + Dig = todigit(Head), + case Dig of + Dig when Dig /= $0, Dig /= Lastn -> + isoundex(Tail, [Dig | Acc], Dig); + _ -> + case Head of + $H -> + isoundex(Tail, Acc, Lastn); + $W -> + isoundex(Tail, Acc, Lastn); + N when N >= $A, N =< $Z -> + isoundex(Tail, Acc, Dig); + _ -> + isoundex(Tail, Acc, Lastn) % This clause handles non alpha characters + end + end. + +todigit(Chr) -> + Digits = "01230120022455012623010202", + HeadOff = Chr - $A + 1, + case HeadOff of + N when N > 0, N < 27 -> + lists:nth(HeadOff, Digits); + _ -> % Treat non alpha characters as a vowel + $0 + end. diff --git a/Task/Soundex/Forth/soundex.fth b/Task/Soundex/Forth/soundex.fth new file mode 100644 index 0000000000..7f99ae3374 --- /dev/null +++ b/Task/Soundex/Forth/soundex.fth @@ -0,0 +1,42 @@ +: alpha-table create does> swap 32 or [char] a - 0 max 26 min + 1+ c@ ; + +alpha-table soundex-code + ," 123 12. 22455 12623 1.2 2 " + \ ABCDEFGHIJKLMNOPQRSTUVWXYZ + +: soundex ( name len -- pad len ) + over c@ pad c! \ First character verbatim + pad 1+ 3 [char] 0 fill \ Pad to four characters with zeros + 1 pad c@ soundex-code ( count code ) + 2swap bounds do + i c@ soundex-code ( count code next ) + 2dup = if drop else \ runs are ignored + dup [char] . = if drop else \ W, H don't separate runs of consonants + dup bl = if nip else \ vowels separate consonants but aren't coded + nip + 2dup swap pad + c! + swap 1+ + tuck 4 = if leave then + then then then + loop + 2drop pad 4 ; + +\ Knuth's test cases +s" Euler" soundex cr type \ E460 +s" Gauss" soundex cr type \ G200 +s" Hilbert" soundex cr type \ H416 +s" Knuth" soundex cr type \ K530 +s" Lloyd" soundex cr type \ L300 +s" Lukasiewicz" soundex cr type \ L222 (W test) +s" Ellery" soundex cr type \ E460 +s" Ghosh" soundex cr type \ G200 +s" Heilbronn" soundex cr type \ H416 +s" Kant" soundex cr type \ K530 +s" Ladd" soundex cr type \ L300 +s" Lissajous" soundex cr type \ L222 + +s" Wheaton" soundex cr type \ W350 +s" Ashcraft" soundex cr type \ A261 (H tests) +s" Burroughs" soundex cr type \ B620 +s" Burrows" soundex cr type \ B620 (W test) (any Welsh names?) +s" O'Hara" soundex cr type \ O600 (punctuation test) diff --git a/Task/Soundex/Go/soundex.go b/Task/Soundex/Go/soundex.go new file mode 100644 index 0000000000..36189931ff --- /dev/null +++ b/Task/Soundex/Go/soundex.go @@ -0,0 +1,83 @@ +package main + +import ( + "errors" + "fmt" + "unicode" +) + +var code = []byte("01230127022455012623017202") + +func soundex(s string) (string, error) { + var sx [4]byte + var sxi int + var cx, lastCode byte + for i, c := range s { + switch { + case !unicode.IsLetter(c): + if c < ' ' || c == 127 { + return "", errors.New("ASCII control characters disallowed") + } + if i == 0 { + return "", errors.New("initial character must be a letter") + } + lastCode = '0' + continue + case c >= 'A' && c <= 'Z': + cx = byte(c - 'A') + case c >= 'a' && c <= 'z': + cx = byte(c - 'a') + default: + return "", errors.New("non-ASCII letters unsupported") + } + // cx is valid letter index at this point + if i == 0 { + sx[0] = cx + 'A' + sxi = 1 + continue + } + switch x := code[cx]; x { + case '7', lastCode: + case '0': + lastCode = '0' + default: + sx[sxi] = x + if sxi == 3 { + return string(sx[:]), nil + } + sxi++ + lastCode = x + } + } + if sxi == 0 { + return "", errors.New("no letters present") + } + for ; sxi < 4; sxi++ { + sx[sxi] = '0' + } + return string(sx[:]), nil +} + +func main() { + for _, s := range []string{ + "Robert", // WP test case = R163 + "Rupert", // WP test case = R163 + "Rubin", // WP test case = R150 + "ashcroft", // WP test case = A261 + "ashcraft", // s and c combine across h, t not needed + "moses", // s's don't combine across e + "O'Mally", // apostrophe allowed, adjacent ll's combine + "d jay", // spaces allowed + "R2-D2", // digits, hyphen allowed + "12p2", // just not in leading position + "naïve", // non ASCII disallowed + "", // empty string disallowed + "bump\t", // ASCII control characters disallowed + } { + if x, err := soundex(s); err == nil { + fmt.Println("soundex", s, "=", x) + } else { + fmt.Printf("\"%s\" fail. %s\n", s, err) + } + } +} diff --git a/Task/Soundex/Groovy/soundex.groovy b/Task/Soundex/Groovy/soundex.groovy new file mode 100644 index 0000000000..075d1935df --- /dev/null +++ b/Task/Soundex/Groovy/soundex.groovy @@ -0,0 +1,23 @@ +def soundex(s) { + def code = "" + def lookup = [ + B : 1, F : 1, P : 1, V : 1, + C : 2, G : 2, J : 2, K : 2, Q : 2, S : 2, X : 2, Z : 2, + D : 3, T : 3, + L : 4, + M : 5, N : 5, + R : 6 + ] + s[1..-1].toUpperCase().inject(7) { lastCode, letter -> + def letterCode = lookup[letter] + if(letterCode && letterCode != lastCode) { + code += letterCode + } + } + return "${s[0]}${code}0000"[0..3] +} + +println(soundex("Soundex")) +println(soundex("Sownteks")) +println(soundex("Example")) +println(soundex("Ekzampul")) diff --git a/Task/Soundex/Haskell/soundex-1.hs b/Task/Soundex/Haskell/soundex-1.hs new file mode 100644 index 0000000000..c09ccf5b28 --- /dev/null +++ b/Task/Soundex/Haskell/soundex-1.hs @@ -0,0 +1,2 @@ +import Text.PhoneticCode.Soundex +import Control.Arrow diff --git a/Task/Soundex/Haskell/soundex-2.hs b/Task/Soundex/Haskell/soundex-2.hs new file mode 100644 index 0000000000..51989c7a95 --- /dev/null +++ b/Task/Soundex/Haskell/soundex-2.hs @@ -0,0 +1,5 @@ +*Main> mapM_ print $ map (id &&& soundexSimple) ["Soundex", "Example", "Sownteks", "Ekzampul"] +("Soundex","S532") +("Example","E251") +("Sownteks","S532") +("Ekzampul","E251") diff --git a/Task/Soundex/Icon/soundex.icon b/Task/Soundex/Icon/soundex.icon new file mode 100644 index 0000000000..7e8b8e55df --- /dev/null +++ b/Task/Soundex/Icon/soundex.icon @@ -0,0 +1,21 @@ +procedure main(arglist) # computes soundex of each argument +every write(x := !arglist, " => ",soundex(x)) +end + +procedure soundex(name) + local dig,i,x + static con + initial { # construct mapping x[i] => i all else . + x := ["bfpv","cgjkqsxz","dt","l","mn","r"] + every ( dig := con := "") ||:= repl(i := 1 to *x,*x[i]) do con ||:= x[i] + con := map(map(&lcase,con,dig),&lcase,repl(".",*&lcase)) + } + + name := map(name) # lower case + name[1] := map(name[1],&lcase,&ucase) # upper case 1st + name := map(name,&lcase,con) # map cons + every x := !"123456" do + while name[find(x||x,name)+:2] := x # kill duplicates + while name[upto('.',name)] := "" # kill . + return left(name,4,"0") +end diff --git a/Task/Soundex/J/soundex-1.j b/Task/Soundex/J/soundex-1.j new file mode 100644 index 0000000000..e48a5869e9 --- /dev/null +++ b/Task/Soundex/J/soundex-1.j @@ -0,0 +1,7 @@ +removeDups =: {.;.1~ (1 , }. ~: }: ) +codes =: ;: 'BFPV CGJKQSXZ DT L MN R HW' + +soundex =: 3 : 0 + if. 0=# k=.toupper y do. '0' return. end. + ({.k), ,": ,. 3 {. 0-.~ }. removeDups 7 0:`(I.@:=)`]} , k >:@I.@:(e. &>)"0 _ codes +) diff --git a/Task/Soundex/J/soundex-2.j b/Task/Soundex/J/soundex-2.j new file mode 100644 index 0000000000..6ee75a9b0e --- /dev/null +++ b/Task/Soundex/J/soundex-2.j @@ -0,0 +1,10 @@ +names=: 'Lloyd Woolcock Donnell Baragwanath Williams Ashcroft Euler Ellery Gauss Ghosh Hilbert Heilbronn Knuth Kant Ladd Lukasiewicz Lissajous' +soundexNames=: 'L300 W422 D540 B625 W452 A226 E460 E460 G200 G200 H416 H416 K530 K530 L300 L222 L222' + + soundex &> ;: names +L300 +W422 +D540 +B625 +W452 +.... diff --git a/Task/Soundex/J/soundex-3.j b/Task/Soundex/J/soundex-3.j new file mode 100644 index 0000000000..2a72802d9a --- /dev/null +++ b/Task/Soundex/J/soundex-3.j @@ -0,0 +1,2 @@ + soundexNames-:(soundex &.>) &. ;: names +1 diff --git a/Task/Soundex/Java/soundex.java b/Task/Soundex/Java/soundex.java new file mode 100644 index 0000000000..1512261393 --- /dev/null +++ b/Task/Soundex/Java/soundex.java @@ -0,0 +1,41 @@ +public static void main(String[] args){ + System.out.println(soundex("Soundex")); + System.out.println(soundex("Example")); + System.out.println(soundex("Sownteks")); + System.out.println(soundex("Ekzampul")); + } + +private static String getCode(char c){ + switch(c){ + case 'B': case 'F': case 'P': case 'V': + return "1"; + case 'C': case 'G': case 'J': case 'K': + case 'Q': case 'S': case 'X': case 'Z': + return "2"; + case 'D': case 'T': + return "3"; + case 'L': + return "4"; + case 'M': case 'N': + return "5"; + case 'R': + return "6"; + default: + return ""; + } +} + +public static String soundex(String s){ + String code, previous, soundex; + code = s.toUpperCase().charAt(0) + ""; + previous = "7"; + for(int i = 1;i < s.length();i++){ + String current = getCode(s.toUpperCase().charAt(i)); + if(current.length() > 0 && !current.equals(previous)){ + code = code + current; + } + previous = current; + } + soundex = (code + "0000").substring(0, 4); + return soundex; +} diff --git a/Task/Soundex/JavaScript/soundex.js b/Task/Soundex/JavaScript/soundex.js new file mode 100644 index 0000000000..24f605375d --- /dev/null +++ b/Task/Soundex/JavaScript/soundex.js @@ -0,0 +1,81 @@ +var soundex = function (s) { + var a = s.toLowerCase().split('') + f = a.shift(), + r = '', + codes = { + a: '', e: '', i: '', o: '', u: '', + b: 1, f: 1, p: 1, v: 1, + c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, + d: 3, t: 3, + l: 4, + m: 5, n: 5, + r: 6 + }; + + r = f + + a + .map(function (v, i, a) { return codes[v] }) + .filter(function (v, i, a) { return ((i === 0) ? v !== codes[f] : v !== a[i - 1]); }) + .join(''); + + return (r + '000').slice(0, 4).toUpperCase(); +}; + +var tests = { + "Soundex": "S532", + "Example": "E251", + "Sownteks": "S532", + "Ekzampul": "E251", + "Euler": "E460", + "Gauss": "G200", + "Hilbert": "H416", + "Knuth": "K530", + "Lloyd": "L300", + "Lukasiewicz": "L222", + "Ellery": "E460", + "Ghosh": "G200", + "Heilbronn": "H416", + "Kant": "K530", + "Ladd": "L300", + "Lissajous": "L222", + "Wheaton": "W350", + "Ashcraft": "A226", + "Burroughs": "B622", + "Burrows": "B620", + "O'Hara": "O600" + }; + +for (var i in tests) + if (tests.hasOwnProperty(i)) { + console.log( + i + + ' \t' + + tests[i] + + '\t' + + soundex(i) + + '\t' + + (soundex(i) === tests[i]) + ); +} + +// Soundex S532 S532 true +// Example E251 E251 true +// Sownteks S532 S532 true +// Ekzampul E251 E251 true +// Euler E460 E460 true +// Gauss G200 G200 true +// Hilbert H416 H416 true +// Knuth K530 K530 true +// Lloyd L300 L300 true +// Lukasiewicz L222 L222 true +// Ellery E460 E460 true +// Ghosh G200 G200 true +// Heilbronn H416 H416 true +// Kant K530 K530 true +// Ladd L300 L300 true +// Lissajous L222 L222 true +// Wheaton W350 W350 true +// Ashcraft A226 A226 true +// Burroughs B622 B622 true +// Burrows B620 B620 true +// O'Hara O600 O600 true diff --git a/Task/Soundex/MUMPS/soundex.mumps b/Task/Soundex/MUMPS/soundex.mumps new file mode 100644 index 0000000000..bc752188eb --- /dev/null +++ b/Task/Soundex/MUMPS/soundex.mumps @@ -0,0 +1,48 @@ +SOUNDEX(X,NARA=0) + ;Converts a string to its Soundex value. + ;Empty strings return "0000". Non-alphabetic ASCII characters are ignored. + ;X is the name to be converted to Soundex + ;NARA is a flag, defaulting to zero, for which implementation to perform. + ;If NARA is 0, do what seems to be the Knuth implementation + ;If NARA is a positive integer, do the NARA implementation. + ; This varies the soundex rule for "W" and "H", and adds variants for prefixed names separated by carets. + ; http://www.archives.gov/publications/general-info-leaflets/55-census.html + ;Y is the string to be returned + ;UP is the list of upper case letters + ;LO is the list of lower case letters + ;PREFIX is a list of prefixes to be stripped off + ;X1 is the upper case version of X + ;X2 is the name without a prefix + ;Y2 is the soundex of a name without a prefix + ;C is a loop variable + ;DX is a list of Soundex values, in alphabetical order. Underscores are used for the NARA variation letters + ;XD is a partially processed translation of X into soundex values + NEW Y,UP,LO,PREFIX,X1,X2,Y2,C,DX,XD + SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;Upper case characters + SET LO="abcdefghijklmnopqrstuvwxyz" ;Lower case characters + SET DX=" 123 12_ 22455 12623 1_2 2" ;Soundex values + SET PREFIX="VAN^CO^DE^LA^LE" ;Prefixes that could create an alternate soundex value + SET Y="" ;Y is the value to be returned + SET X1=$TRANSLATE(X,LO,UP) ;Make local copy, and force all letters to be upper case + SET XD=$TRANSLATE(X1,UP,DX) ;Soundex values for string + ; + SET Y=$EXTRACT(X1,1,1) ;Get first character + FOR C=2:1:$LENGTH(X1) QUIT:$L(Y)>=4 DO + . ;ignore doubled letters OR and side-by-side soundex values OR same soundex on either side of "H" or "W" + . QUIT:($EXTRACT(X1,C,C)=$EXTRACT(X1,C-1,C-1)) + . QUIT:($EXTRACT(XD,C,C)=$EXTRACT(XD,C-1,C-1)) + . ;ignore non-alphabetic characters + . QUIT:UP'[($EXTRACT(X1,C,C)) + . QUIT:NARA&(($EXTRACT(XD,C-1,C-1)="_")&(C>2))&($EXTRACT(XD,C,C)=$EXTRACT(XD,C-2,C-2)) + . QUIT:" _"[$EXTRACT(XD,C,C) + . SET Y=Y_$EXTRACT(XD,C,C) + ; Pad with "0" so string length is 4 + IF $LENGTH(Y)<4 FOR C=$L(Y):1:3 SET Y=Y_"0" + IF NARA DO + . FOR C=1:1:$LENGTH(PREFIX,"^") DO + . . IF $EXTRACT(X1,1,$LENGTH($PIECE(PREFIX,"^",C)))=$PIECE(PREFIX,"^",C) DO + . . . ;Take off the prefix, and any leading spaces + . . . SET X2=$EXTRACT(X1,$LENGTH($PIECE(PREFIX,"^",C))+1,$LENGTH(X1)-$PIECE(PREFIX,"^",C)) FOR QUIT:UP[$E(X2,1,1) SET X2=$E(X2,2,$L(X2)) + . . . SET Y2=$$SOUNDEX(X2,NARA) SET Y=Y_"^"_Y2 + KILL UP,LO,PREFIX,X1,X2,Y2,C,DX,XD + QUIT Y diff --git a/Task/Soundex/Mathematica/soundex.math b/Task/Soundex/Mathematica/soundex.math new file mode 100644 index 0000000000..51b8c2acce --- /dev/null +++ b/Task/Soundex/Mathematica/soundex.math @@ -0,0 +1,9 @@ +Soundex[ input_ ] := Module[{x = input, head, body}, +{head, body} = {First@#, Rest@#}&@ToLowerCase@Characters@x; +body = (Select[body, FreeQ[Characters["aeiouyhw"],#]&] /. {("b"|"f"|"p"|"v")->1, +("c"|"g"|"j"|"k"|"q"|"s"|"x"|"z")->2, ("d"|"t")->3,"l"->4 ,("m"|"n")->5, "r"->6}); +If[Length[body] < 3, + body = PadRight[body, 3], + body = DeleteDuplicates[body] +]; +StringJoin @@ ToString /@ PrependTo[ body[[1 ;; 3]], ToUpperCase@head]] diff --git a/Task/Soundex/OCaml/soundex-1.ocaml b/Task/Soundex/OCaml/soundex-1.ocaml new file mode 100644 index 0000000000..2f20a5cc37 --- /dev/null +++ b/Task/Soundex/OCaml/soundex-1.ocaml @@ -0,0 +1,35 @@ +let c2d = function + | 'B' | 'F' | 'P' | 'V' -> "1" + | 'C' | 'G' | 'J' | 'K' | 'Q' | 'S' | 'X' | 'Z' -> "2" + | 'D' | 'T' -> "3" + | 'L' -> "4" + | 'M' | 'N' -> "5" + | 'R' -> "6" + | _ -> "" + +let rec dbl acc = function + | [] -> (List.rev acc) + | [c] -> List.rev(c::acc) + | c1::(c2::_ as tl) -> + if c1 = c2 + then dbl acc tl + else dbl (c1::acc) tl + +let pad s = + match String.length s with + | 0 -> s ^ "000" + | 1 -> s ^ "00" + | 2 -> s ^ "0" + | 3 -> s + | _ -> String.sub s 0 3 + +let soundex_aux rem = + pad(String.concat "" (dbl [] (List.map c2d rem))) + +let soundex s = + let s = String.uppercase s in + let cl = ref [] in + String.iter (fun c -> cl := c :: !cl) s; + match dbl [] (List.rev !cl) with + | c::rem -> (String.make 1 c) ^ (soundex_aux rem) + | [] -> invalid_arg "soundex" diff --git a/Task/Soundex/OCaml/soundex-2.ocaml b/Task/Soundex/OCaml/soundex-2.ocaml new file mode 100644 index 0000000000..1cda23456d --- /dev/null +++ b/Task/Soundex/OCaml/soundex-2.ocaml @@ -0,0 +1,31 @@ +let tests = [ + "Soundex", "S532"; + "Example", "E251"; + "Sownteks", "S532"; + "Ekzampul", "E251"; + "Euler", "E460"; + "Gauss", "G200"; + "Hilbert", "H416"; + "Knuth", "K530"; + "Lloyd", "L300"; + "Lukasiewicz", "L222"; + "Ellery", "E460"; + "Ghosh", "G200"; + "Heilbronn", "H416"; + "Kant", "K530"; + "Ladd", "L300"; + "Lissajous", "L222"; + "Wheaton", "W350"; + "Ashcraft", "A226"; + "Burroughs", "B622"; + "Burrows", "B620"; + "O'Hara", "O600"; + ] + +let () = + print_endline " Word \t Code Found Status"; + List.iter (fun (word, code1) -> + let code2 = soundex word in + let status = if code1 = code2 then "OK " else "Arg" in + Printf.printf " \"%s\" \t %s %s %s\n" word code1 code2 status + ) tests diff --git a/Task/Soundex/PHP/soundex.php b/Task/Soundex/PHP/soundex.php new file mode 100644 index 0000000000..fbeefb8342 --- /dev/null +++ b/Task/Soundex/PHP/soundex.php @@ -0,0 +1,6 @@ +<?php +echo soundex("Soundex"), "\n"; // S532 +echo soundex("Example"), "\n"; // E251 +echo soundex("Sownteks"), "\n"; // S532 +echo soundex("Ekzampul"), "\n"; // E251 +?> diff --git a/Task/Soundex/PL-I/soundex.pli b/Task/Soundex/PL-I/soundex.pli new file mode 100644 index 0000000000..02e1766f18 --- /dev/null +++ b/Task/Soundex/PL-I/soundex.pli @@ -0,0 +1,39 @@ +Soundex: procedure (pword) returns (character(4)); + declare pword character (*) varying, value character (length(pword)) varying; + declare word character (length(pword)); + declare (prevCode, currCode) character (1); + declare alphabet CHARACTER (26) STATIC INITIAL ('AEIOUHWYBFPVCGJKQSXZDTLMNR'); + declare replace character (26) static initial ('00000000111122222222334556'); + declare i fixed binary; + + word = pword; + + /* Buffer to build up with character codes */ + value = ''; + + /* Make sure the word is at least two characters in length. */ + if length(word) <= 1 then return (word); + + word = uppercase(word); /* Convert to uppercase. */ + + /* The current and previous character codes */ + prevCode = '0'; + + value = substr(word, 1, 1); /* The first character is unchanged. */ + + word = Translate (word, replace, alphabet); + + /* Loop through the remaining characters ... */ + do i = 2 to length(word); + currCode = substr(word, i, 1); + /* Check to see if the current code is the same as the last one */ + if currCode ^= prevCode & currCode ^= '0' then + /* If the current code is a vowel, ignore it. */ + value = value || currCode; + /* Set the new previous character code */ + prevCode = currCode; + end; /* of do i = ... */ + + return ( left(value, 4, '0') ); /* Pad, if necessary. */ + +end Soundex; diff --git a/Task/Soundex/Perl-6/soundex.pl6 b/Task/Soundex/Perl-6/soundex.pl6 new file mode 100644 index 0000000000..81a626dead --- /dev/null +++ b/Task/Soundex/Perl-6/soundex.pl6 @@ -0,0 +1,49 @@ +sub soundex ($name --> Str) { + my $first = substr($name,0,1).uc; + gather { + take $first; + my $fakefirst = ''; + $fakefirst = "de " if $first ~~ /^ <[AEIOUWH]> /; + "$fakefirst$name".lc.trans('wh' => '') ~~ / + ^ + [ + [ + | <[ bfpv ]>+ { take 1 } + | <[ cgjkqsxz ]>+ { take 2 } + | <[ dt ]>+ { take 3 } + | <[ l ]>+ { take 4 } + | <[ mn ]>+ { take 5 } + | <[ r ]>+ { take 6 } + ] + || . + ]+ + $ { take 0,0,0 } + /; + }.flat.[0,2,3,4].join; +} + +for < Soundex S532 + Example E251 + Sownteks S532 + Ekzampul E251 + Euler E460 + Gauss G200 + Hilbert H416 + Knuth K530 + Lloyd L300 + Lukasiewicz L222 + Ellery E460 + Ghosh G200 + Heilbronn H416 + Kant K530 + Ladd L300 + Lissajous L222 + Wheaton W350 + Ashcraft A261 + Burroughs B620 + Burrows B620 + O'Hara O600 > +-> $n, $s { + my $s2 = soundex($n); + say $n.fmt("%16s "), $s, $s eq $s2 ?? " OK" !! " NOT OK $s2"; +} diff --git a/Task/Soundex/Perl/soundex.pl b/Task/Soundex/Perl/soundex.pl new file mode 100644 index 0000000000..49d07f237a --- /dev/null +++ b/Task/Soundex/Perl/soundex.pl @@ -0,0 +1,5 @@ +use Text::Soundex; +print soundex("Soundex"), "\n"; # S532 +print soundex("Example"), "\n"; # E251 +print soundex("Sownteks"), "\n"; # S532 +print soundex("Ekzampul"), "\n"; # E251 diff --git a/Task/Soundex/PicoLisp/soundex.l b/Task/Soundex/PicoLisp/soundex.l new file mode 100644 index 0000000000..09a933abb7 --- /dev/null +++ b/Task/Soundex/PicoLisp/soundex.l @@ -0,0 +1,21 @@ +(de soundex (Str) + (pack + (pad -4 + (cons + (uppc (char (char Str))) + (head 3 + (let Last NIL + (extract + '((C) + (and + (setq C + (case (uppc C) + (`(chop "BFPV") "1") + (`(chop "CGJKQSXZ") "2") + (("D" "T") "3") + ("L" "4") + (("M" "N") "5") + ("R" "6") ) ) + (<> Last C) + (setq Last C) ) ) + (cdr (chop Str)) ) ) ) ) ) ) ) diff --git a/Task/Soundex/PureBasic/soundex.purebasic b/Task/Soundex/PureBasic/soundex.purebasic new file mode 100644 index 0000000000..8323c4312c --- /dev/null +++ b/Task/Soundex/PureBasic/soundex.purebasic @@ -0,0 +1,41 @@ +Procedure.s getCode(c.s) + Protected getCode.s = "" + + If FindString("BFPV", c ,1) : getCode = "1" : EndIf + If FindString("CGJKQSXZ", c ,1) : getCode = "2" : EndIf + If FindString("DT", c ,1) : getCode = "3" : EndIf + If "L" = c : getCode = "4" : EndIf + If FindString("MN", c ,1) : getCode = "5" : EndIf + If "R" = c : getCode = "6" : EndIf + If FindString("HW", c ,1) : getCode = "." : EndIf + ProcedureReturn getCode +EndProcedure + +Procedure.s soundex(word.s) + Protected.s previous.s = "" , code.s , current , soundex + Protected.i i + + word = UCase(word) + code = Mid(word,1,1) + previous = "" + For i = 2 To (Len(word) + 1) + current = getCode(Mid(word, i, 1)) + If current = "." : Continue : EndIf + If Len(current) > 0 And current <> previous + code + current + EndIf + previous = current + If Len(code) = 4 + Break + EndIf + Next + If Len(code) < 4 + code = LSet(code, 4,"0") + EndIf + ProcedureReturn code +EndProcedure + +OpenConsole() + +PrintN (soundex("Lukasiewicz")) +PrintN("Press any key to exit"): Repeat: Until Inkey() <> "" diff --git a/Task/Soundex/Python/soundex-1.py b/Task/Soundex/Python/soundex-1.py new file mode 100644 index 0000000000..2f280b28b4 --- /dev/null +++ b/Task/Soundex/Python/soundex-1.py @@ -0,0 +1,10 @@ +from itertools import groupby + +def soundex(word): + codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r") + soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod) + cmap2 = lambda kar: soundDict.get(kar, '9') + sdx = ''.join(cmap2(kar) for kar in word.lower()) + sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9') + sdx3 = sdx2[0:4].ljust(4,'0') + return sdx3 diff --git a/Task/Soundex/Python/soundex-2.py b/Task/Soundex/Python/soundex-2.py new file mode 100644 index 0000000000..0d11a946c0 --- /dev/null +++ b/Task/Soundex/Python/soundex-2.py @@ -0,0 +1,8 @@ +>>>print soundex("soundex") +S532 +>>>print soundex("example") +E251 +>>>print soundex("ciondecks") +C532 +>>>print soundex("ekzampul") +E251 diff --git a/Task/Soundex/REXX/soundex.rexx b/Task/Soundex/REXX/soundex.rexx new file mode 100644 index 0000000000..73f894c377 --- /dev/null +++ b/Task/Soundex/REXX/soundex.rexx @@ -0,0 +1,100 @@ +/*REXX program demonstrates Soundex codes from some words | commandLine.*/ +_=; @.= +parse arg @.0 . /*allow input from command line. */ + @.1 ='12346' ; #.1 ='0000' + @.4 ='4-H' ; #.4 ='H000' + @.11 ='Ashcraft' ; #.11 ='A261' + @.12 ='Ashcroft' ; #.12 ='A261' + @.18 ='auerbach' ; #.18 ='A612' + @.20 ='Baragwanath' ; #.20 ='B625' + @.22 ='bar' ; #.22 ='B600' + @.23 ='barre' ; #.23 ='B600' + @.20 ='Baragwanath' ; #.20 ='B625' + @.28 ='Burroughs' ; #.28 ='B620' + @.29 ='Burrows' ; #.29 ='B620' + @.30 ='C.I.A.' ; #.30 ='C000' + @.37 ='coöp' ; #.37 ='C100' + @.43 ='D-day' ; #.43 ='D000' + @.44 ='d jay' ; #.44 ='D200' + @.45 ='de la Rosa' ; #.45 ='D462' + @.46 ='Donnell' ; #.46 ='D540' + @.47 ='Dracula' ; #.47 ='D624' + @.48 ='Drakula' ; #.48 ='D624' + @.49 ='Du Pont' ; #.49 ='D153' + @.50 ='Ekzampul' ; #.50 ='E251' + @.51 ='example' ; #.51 ='E251' + @.55 ='Ellery' ; #.55 ='E460' + @.59 ='Euler' ; #.59 ='E460' + @.60 ='F.B.I.' ; #.60 ='F000' + @.70 ='Gauss' ; #.70 ='G200' + @.71 ='Ghosh' ; #.71 ='G200' + @.72 ='Gutierrez' ; #.72 ='G362' + @.80 ='he' ; #.80 ='H000' + @.81 ='Heilbronn' ; #.81 ='H416' + @.84 ='Hilbert' ; #.84 ='H416' + @.100='Jackson' ; #.100='J250' + @.104='Johnny' ; #.104='J500' + @.105='Jonny' ; #.105='J500' + @.110='Kant' ; #.110='K530' + @.116='Knuth' ; #.116='K530' + @.120='Ladd' ; #.120='L300' + @.124='Llyod' ; #.124='L300' + @.125='Lee' ; #.125='L000' + @.126='Lissajous' ; #.126='L222' + @.128='Lukasiewicz' ; #.128='L222' + @.130='naïve' ; #.130='N100' + @.141='Miller' ; #.141='M460' + @.143='Moses' ; #.143='M220' + @.146='Moskowitz' ; #.146='M232' + @.147='Moskovitz' ; #.147='M213' + @.150="O'Conner" ; #.150='O256' + @.151="O'Connor" ; #.151='O256' + @.152="O'Hara" ; #.152='O600' + @.153="O'Mally" ; #.153='O540' + @.161='Peters' ; #.161='P362' + @.162='Peterson' ; #.162='P362' + @.165='Pfister' ; #.165='P236' + @.180='R2-D2' ; #.180='R300' + @.182='rÄ≈sumÅ∙' ; #.182='R250' + @.184='Robert' ; #.184='R163' + @.185='Rupert' ; #.185='R163' + @.187='Rubin' ; #.187='R150' + @.191='Soundex' ; #.191='S532' + @.192='sownteks' ; #.192='S532' + @.199='Swhgler' ; #.199='S460' + @.202="'til" ; #.202='T400' + @.208='Tymczak' ; #.208='T522' + @.216='Uhrbach' ; #.216='U612' + @.221='Van de Graaff' ; #.221='V532' + @.222='VanDeusen' ; #.222='V532' + @.230='Washington' ; #.230='W252' + @.233='Wheaton' ; #.233='W350' + @.234='Williams' ; #.234='W452' + @.236='Woolcock' ; #.236='W422' + + do k=0 to 300; if @.k=='' then iterate ; $=soundex(@.k) + say word('nope [ok]',1+($==#.k|k==0)) _ $ 'is the Soundex for' @.k + if k==0 then leave + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────SOUNDEX subroutine─────────────────*/ +soundex: procedure; arg thing /*ARG automatically uppercases it*/ +old_alphabet = 'AEIOUYHWBFPVCGJKQSXZDTLMNR' +new_alphabet = '@@@@@@**111122222222334556' +word= + do i=1 for length(thing) /*handle special chars: - ' _ etc*/ + _=substr(thing,i,1) + if datatype(_,'M') then word=word || _ /*it's a letter, then OK*/ + end /*i*/ + +value=strip(left(word,1)) /*first character is left alone. */ +word=translate(word, new_alphabet, old_alphabet) +prev=translate(value,new_alphabet, old_alphabet) /*the previous code.*/ + + do j=2 to length(word) /*process remainder of the word. */ + ?=substr(word,j,1) + if ?\==prev & datatype(?,'W') then do; value=value || ?; prev=?; end + else if ?=='@' then prev=? + end /*j*/ + +return left(value,4,0) /*return padded value with zeroes*/ diff --git a/Task/Soundex/Ruby/soundex.rb b/Task/Soundex/Ruby/soundex.rb new file mode 100644 index 0000000000..0e5e67bdce --- /dev/null +++ b/Task/Soundex/Ruby/soundex.rb @@ -0,0 +1,28 @@ +class String + + SoundexChars = 'BFPVCGJKQSXZDTLMNR' + SoundexNums = '111122222222334556' + SoundexCharsEx = '^' + SoundexChars + SoundexCharsDel = '^A-Z' + + # desc: http://en.wikipedia.org/wiki/Soundex + def soundex(census = true) + str = self.upcase.delete(SoundexCharsDel) + str[0,1] + str[1..-1].delete(SoundexCharsEx). + tr_s(SoundexChars, SoundexNums)\ + [0 .. (census ? 2 : -1)]. + ljust(3, '0') rescue '' + end + + def sounds_like(other) + self.soundex == other.soundex + end +end + +%w(Soundex Sownteks Example Ekzampul foo bar).each_slice(2) do |word1, word2| + [word1, word2].each {|word| puts '%-8s -> %s' % [word, word.soundex]} + + print "'#{word1}' " + print word1.sounds_like(word2) ? "sounds" : "does not sound" + print " like '#{word2}'\n" +end diff --git a/Task/Soundex/Run-BASIC/soundex.run b/Task/Soundex/Run-BASIC/soundex.run new file mode 100644 index 0000000000..96fc4e5c30 --- /dev/null +++ b/Task/Soundex/Run-BASIC/soundex.run @@ -0,0 +1,42 @@ +global val$ +val$(1) = "BPFV" +val$(2) = "CSGJKQXZ" +val$(3) = "DT" +val$(4) = "L" +val$(5) = "MN" +val$(6) = "R" + +' --------------------------------- +' show soundex on these words +' --------------------------------- +w$(1) = "Robert" 'R163 +w$(2) = "Rupert" 'R163 +w$(3) = "Rubin" 'R150 +w$(4) = "moses" 'M220 +w$(5) = "O'Mally" 'O540 +w$(6) = "d jay" 'D200 + +for i = 1 to 6 + print w$(i);" soundex:";soundex$(w$(i)) +next i +wait + +' --------------------------------- +' Return soundex of word +' --------------------------------- +function soundex$(a$) +a$ = upper$(a$) +for i = 2 to len(a$) + theLtr$ = mid$(a$,i,1) + s$ = "0" + if instr("AEIOUYHW |",theLtr$) <> 0 then s$ = "" + if theLtr$ <> preLtr$ then + for j = 1 to 6 + if instr(val$(j),theLtr$) <> 0 then s$ = str$(j) + next j + end if + sdx$ = sdx$ + s$ + preLtr$ = theLtr$ +next i +soundex$ = left$(a$,1) + left$(sdx$;"000",3) +end function diff --git a/Task/Soundex/SNOBOL4/soundex.sno b/Task/Soundex/SNOBOL4/soundex.sno new file mode 100644 index 0000000000..a4023fc9e4 --- /dev/null +++ b/Task/Soundex/SNOBOL4/soundex.sno @@ -0,0 +1,26 @@ +* # Soundex coding +* # ABCDEFGHIJKLMNOPQRSTUVWXYZ +* # 01230127022455012623017202 + + define('soundex(str)init,ch') :(soundex_end) +soundex sdxmap = '01230127022455012623017202' + str = replace(str,&lcase,&ucase) +sdx1 str notany(&ucase) = :s(sdx1) + init = substr(str,1,1) + str = replace(str,&ucase,sdxmap) +sdx2 str len(1) $ ch span(*ch) = ch :s(sdx2) +* # Omit next line for Knuth's simple Soundex +sdx3 str len(1) $ ch ('7' *ch) = ch :s(sdx3) + str len(1) = init +sdx4 str any('07') = :s(sdx4) + str = substr(str,1,4) + str = lt(size(str),4) str dupl('0',4 - size(str)) + soundex = str :(return) +soundex_end + +* # Test and display + test = " Washington Lee Gutierrez Pfister Jackson Tymczak" ++ " Ashcroft Swhgler O'Connor Rhys-Davies" +loop test span(' ') break(' ') . name = :f(end) + output = soundex(name) ' ' name :(loop) +end diff --git a/Task/Soundex/Scala/soundex-1.scala b/Task/Soundex/Scala/soundex-1.scala new file mode 100644 index 0000000000..50901278b0 --- /dev/null +++ b/Task/Soundex/Scala/soundex-1.scala @@ -0,0 +1,25 @@ +def soundex(s:String)={ + var code=s.head.toUpper.toString + var previous=getCode(code.head) + for(ch <- s.drop(1); current=getCode(ch.toUpper)){ + if (!current.isEmpty && current!=previous) + code+=current + previous=current + } + code+="0000" + code.slice(0,4) +} + +def getCode(c:Char)={ + val code=Map("1"->List('B','F','P','V'), + "2"->List('C','G','J','K','Q','S','X','Z'), + "3"->List('D', 'T'), + "4"->List('L'), + "5"->List('M', 'N'), + "6"->List('R')) + + code.find(_._2.exists(_==c)) match { + case Some((k,_)) => k + case _ => "" + } +} diff --git a/Task/Soundex/Scala/soundex-2.scala b/Task/Soundex/Scala/soundex-2.scala new file mode 100644 index 0000000000..69e1c5738c --- /dev/null +++ b/Task/Soundex/Scala/soundex-2.scala @@ -0,0 +1,27 @@ +def main(args: Array[String]): Unit = { + val tests=Map( + "Soundex" -> "S532", + "Euler" -> "E460", + "Gauss" -> "G200", + "Hilbert" -> "H416", + "Knuth" -> "K530", + "Lloyd" -> "L300", + "Lukasiewicz" -> "L222", + "Ellery" -> "E460", + "Ghosh" -> "G200", + "Heilbronn" -> "H416", + "Kant" -> "K530", + "Ladd" -> "L300", + "Lissajous" -> "L222", + "Wheaton" -> "W350", + "Ashcraft" -> "A226", + "Burroughs" -> "B622", + "Burrows" -> "B620", + "O'Hara" -> "O600") + + tests.foreach{(v)=> + val code=soundex(v._1) + val status=if (code==v._2) "OK" else "ERROR" + printf("Name: %-20s Code: %s Found: %s - %s\n", v._1, v._2, code, status) + } +} diff --git a/Task/Soundex/Scheme/soundex.ss b/Task/Soundex/Scheme/soundex.ss new file mode 100644 index 0000000000..95519bc3a8 --- /dev/null +++ b/Task/Soundex/Scheme/soundex.ss @@ -0,0 +1,70 @@ +;; The American Soundex System +;; +;; The soundex code consist of the first letter of the name followed +;; by three digits. These three digits are determined by dropping the +;; letters a, e, i, o, u, h, w and y and adding three digits from the +;; remaining letters of the name according to the table below. There +;; are only two additional rules. (1) If two or more consecutive +;; letters have the same code, they are coded as one letter. (2) If +;; there are an insufficient numbers of letters to make the three +;; digits, the remaining digits are set to zero. + +;; Soundex Table + +;; 1 b,f,p,v +;; 2 c,g,j,k,q,s,x,z +;; 3 d, t +;; 4 l +;; 5 m, n +;; 6 r + +;; Examples: + +;; Miller M460 +;; Peterson P362 +;; Peters P362 +;; Auerbach A612 +;; Uhrbach U612 +;; Moskowitz M232 +;; Moskovitz M213 + +(define (char->soundex c) + (case (char-upcase c) + ((#\B #\F #\P #\V) #\1) + ((#\C #\G #\J #\K #\Q #\S #\X #\Z) #\2) + ((#\D #\T) #\3) + ((#\L) #\4) + ((#\M #\N) #\5) + ((#\R) #\6) + (else #\nul))) + +(define (collapse-dups lst) + (if (= (length lst) 1) lst + (if (equal? (car lst) (cadr lst)) + (collapse-dups (cdr lst)) + (cons (car lst) (collapse-dups (cdr lst)))))) + +(define (remove-nul lst) + (filter (lambda (c) + (not (equal? c #\nul))) + lst)) + +(define (force-len n lst) + (cond ((= n 0) '()) + ((null? lst) (force-len n (list #\0))) + (else (cons (car lst) (force-len (- n 1) (cdr lst)))))) + +(define (soundex s) + (let ((slst (string->list s))) + (force-len 4 (cons (char-upcase (car slst)) + (remove-nul + (collapse-dups + (map char->soundex (cdr slst)))))))) + +(soundex "miller") +(soundex "Peterson") +(soundex "PETERS") +(soundex "auerbach") +(soundex "Uhrbach") +(soundex "Moskowitz") +(soundex "Moskovitz") diff --git a/Task/Soundex/Smalltalk/soundex.st b/Task/Soundex/Smalltalk/soundex.st new file mode 100644 index 0000000000..8eb94300e8 --- /dev/null +++ b/Task/Soundex/Smalltalk/soundex.st @@ -0,0 +1 @@ +PhoneticStringUtilities soundexCodeOf: 'Soundex' "-> S532" diff --git a/Task/Soundex/TSE-SAL/soundex.tse b/Task/Soundex/TSE-SAL/soundex.tse new file mode 100644 index 0000000000..18e6e6d95b --- /dev/null +++ b/Task/Soundex/TSE-SAL/soundex.tse @@ -0,0 +1,81 @@ +// library: string: get: soundex <description></description> <version>1.0.0.0.35</version> <version control></version control> (filenamemacro=getstgso.s) [kn, ri, sa, 15-10-2011 18:23:04] +STRING PROC FNStringGetSoundexS( STRING inS ) + // Except the first character, you replace each character in the string with its corresponding mapping number + // Idea is that you give characters with the same sound the same mapping number (e.g. 'c' is replaced by '2'. And 'k' which might sound the same as a 'c' is also replaced by the same '2' + STRING map1S[255] = "AEHIOUWYBFPVCGJKQSXZDTLMNR" + STRING map2S[255] = "00000000111122222222334556" + STRING s[255] = Upper( inS ) + STRING soundexS[255] = "" + STRING characterCurrentS[255] = "" + STRING characterPreviousS[255] = "?" + STRING characterMapS[255] = "" + INTEGER mapPositionI = 0 + INTEGER minI = 1 + INTEGER I = minI + INTEGER maxI = Length( s ) + I = minI + characterCurrentS = SubStr( s, I, 1 ) + mapPositionI = Pos( characterCurrentS, map1S ) + WHILE ( ( I <= maxI ) AND ( Length( soundexS ) < 4 ) AND ( NOT ( mapPositionI == 0 ) ) ) + // Skip double letters, like CC, KK, PP, ... + IF ( NOT ( mapPositionI == 0 ) ) AND ( NOT ( characterCurrentS == characterPreviousS ) ) + characterPreviousS = characterCurrentS + // First character is extracted unchanged, for sorting purposes. + IF ( I == minI ) + soundexS = Format( soundexS, characterCurrentS ) + ELSE + mapPositionI = Pos( characterCurrentS, map1S ) + IF ( NOT ( mapPositionI == 0 ) ) + characterMapS = SubStr( map2S, mapPositionI, 1 ) + // skip vowels A, E, I, O, U, further also H, W and Y. In general all characters which have a mapping value of "0" + IF ( NOT ( characterMapS == "0" ) ) + soundexS = Format( soundexS, characterMapS ) + ENDIF + ENDIF + ENDIF + ENDIF + I = I + 1 + characterCurrentS = SubStr( s, I, 1 ) + ENDWHILE + IF ( NOT ( soundexS == "" ) ) + WHILE ( Length( soundexS ) < 4 ) + soundexS = Format( soundexS, "0" ) + ENDWHILE + ENDIF + RETURN( soundexS ) +END + +PROC Main() + STRING s1[255] = "John Doe" + // Warn( Format( FNStringGetSoundexS( "Ashcraft" ) ) ) // gives e.g. "A226" // using another rule the value might be "A261" (see Wikipedia, soundex) + // Warn( Format( FNStringGetSoundexS( "Ashcroft" ) ) ) // gives e.g. "A226" // using another rule the value might be "A261" (see Wikipedia, soundex) + // Warn( Format( FNStringGetSoundexS( "Davidson, Greg" ) ) ) // gives e.g. "D132" + // Warn( Format( FNStringGetSoundexS( "Dracula" ) ) ) // gives e.g. "D624" + // Warn( Format( FNStringGetSoundexS( "Drakula" ) ) ) // gives e.g. "D624" + // Warn( Format( FNStringGetSoundexS( "Darwin" ) ) ) // gives e.g. "D650" + // Warn( Format( FNStringGetSoundexS( "Darwin, Daemon" ) ) ) // gives e.g. "D650" + // Warn( Format( FNStringGetSoundexS( "Darwin, Ian" ) ) ) // gives e.g. "D650" + // Warn( Format( FNStringGetSoundexS( "Derwin" ) ) ) // gives e.g. "D650" + // Warn( Format( FNStringGetSoundexS( "Darwent, William" ) ) ) // gives e.g. "D653" + // Warn( Format( FNStringGetSoundexS( "Ellery" ) ) ) // gives e.g. "E460" + // Warn( Format( FNStringGetSoundexS( "Euler" ) ) ) // gives e.g. "E460" + // Warn( Format( FNStringGetSoundexS( "Ghosh" ) ) ) // gives e.g. "G200" + // Warn( Format( FNStringGetSoundexS( "Gauss" ) ) ) // gives e.g. "G200" + // Warn( Format( FNStringGetSoundexS( "Heilbronn" ) ) ) // gives e.g. "H416" + // Warn( Format( FNStringGetSoundexS( "Hilbert" ) ) ) // gives e.g. "H416" + // Warn( Format( FNStringGetSoundexS( "Johnny" ) ) ) // gives e.g. "J500" + // Warn( Format( FNStringGetSoundexS( "Jonny" ) ) ) // gives e.g. "J500" + // Warn( Format( FNStringGetSoundexS( "Kant" ) ) ) // gives e.g. "K530" + // Warn( Format( FNStringGetSoundexS( "Knuth" ) ) ) // gives e.g. "K530" + // Warn( Format( FNStringGetSoundexS( "Lissajous" ) ) ) // gives e.g. "L222" + // Warn( Format( FNStringGetSoundexS( "Lukasiewicz" ) ) ) // gives e.g. "L222" + // Warn( Format( FNStringGetSoundexS( "Ladd" ) ) ) // gives e.g. "L300" + // Warn( Format( FNStringGetSoundexS( "Lloyd" ) ) ) // gives e.g. "L300" + // Warn( Format( FNStringGetSoundexS( "Rubin" ) ) ) // gives e.g. "R150" + // Warn( Format( FNStringGetSoundexS( "Robert" ) ) ) // gives e.g. "R163" + // Warn( Format( FNStringGetSoundexS( "Rupert" ) ) ) // gives e.g. "R163" + REPEAT + IF ( NOT ( Ask( "string: get: soundex = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF + Warn( Format( FNStringGetSoundexS( s1 ) ) ) + UNTIL FALSE +END diff --git a/Task/Soundex/TUSCRIPT/soundex.tuscript b/Task/Soundex/TUSCRIPT/soundex.tuscript new file mode 100644 index 0000000000..e197e290ad --- /dev/null +++ b/Task/Soundex/TUSCRIPT/soundex.tuscript @@ -0,0 +1,30 @@ +$$ MODE DATA + +$$ BUILD X_TABLE soundex = * +:b:1:f:1:p:1:v:1: +:c:2:g:2:j:2:k:2:1:2:s:2:x:2:z:2: +:d:3:t:3: +:l:4: +:m:5:n:5: +:r:6: + +$$ names="Christiansen'Kris Jenson'soundex'Lloyd'Woolcock'Donnell'Baragwanath'Williams'Ashcroft'Euler'Ellery'Gauss'Ghosh'Hilbert'Heilbronn'Knuth'Kant'Ladd'Lukasiewicz'Lissajous'Wheaton'Burroughs'Burrows" + +$$ MODE TUSCRIPT,{} +LOOP/CLEAR n=names + first=EXTRACT (n,1,2),second=EXTRACT (n,2,3) + IF (first==second) THEN + rest=EXTRACT (n,3,0) + ELSE + rest=EXTRACT (n,2,0) + ENDIF + + soundex=EXCHANGE (rest,soundex) + soundex=STRINGS (soundex,":{\0}:a:e:i:o:u:") + soundex=REDUCE (soundex) + soundex=STRINGS (soundex,":{\0}:",0,0,1,0,"") + soundex=CONCAT (soundex,"000") + soundex=EXTRACT (soundex,0,4) + + PRINT first,soundex,"=",n +ENDLOOP diff --git a/Task/Soundex/TXR/soundex-1.txr b/Task/Soundex/TXR/soundex-1.txr new file mode 100644 index 0000000000..a7fdbaba96 --- /dev/null +++ b/Task/Soundex/TXR/soundex-1.txr @@ -0,0 +1,74 @@ +@(next :args) +@### +@# soundex-related filters +@### +@(deffilter remdbl ("AA" "A") ("BB" "B") ("CC" "C") ("DD" "D") ("EE" "E") + ("FF" "F") ("GG" "G") ("HH" "H") ("II" "I") ("JJ" "J") + ("KK" "K") ("LL" "L") ("MM" "M") ("NN" "N") ("OO" "O") + ("PP" "P") ("QQ" "Q") ("RR" "R") ("SS" "S") ("TT" "T") + ("UU" "U") ("VV" "V") ("WW" "W") ("XX" "X") ("YY" "Y") + ("ZZ" "Z")) +@(deffilter code ("B" "F" "P" "V" "1") + ("C" "G" "J" "K" "Q" "S" "X" "Z" "2") + ("D" "T" "3") ("L" "4") ("M" "N" "5") + ("R" "6") ("A" "E" "I" "O" "U" "Y" "0") ("H" "W" "")) +@(deffilter squeeze ("11" "111" "1111" "11111" "1") + ("22" "222" "2222" "22222" "2") + ("33" "333" "3333" "33333" "3") + ("44" "444" "4444" "44444" "4") + ("55" "555" "5555" "55555" "5") + ("66" "666" "6666" "66666" "6")) +@(bind prefix ("VAN" "CON" "DE" "DI" "LA" "LE")) +@(deffilter remzero ("0" "")) +@### +@# soundex function +@### +@(define soundex (in out)) +@ (local nodouble letters remainder first rest coded) +@ (next :string in) +@ (coll)@{letters /[A-Za-z]+/}@(end) +@ (cat letters "") +@ (output :into nodouble :filter (:upcase remdbl)) +@letters +@ (end) +@ (next :list nodouble) +@ (maybe) +@prefix@remainder +@ (output :into nodouble) +@nodouble +@remainder +@ (end) +@ (end) +@ (next :list nodouble) +@ (collect) +@{first 1}@rest +@ (output :filter (code squeeze remzero) :into coded) +@{rest}000 +@ (end) +@ (next :list coded) +@{digits 3}@(skip) +@ (end) +@ (output :into out) +@ (rep):@first@digits@(first)@first@digits@(end) +@ (end) +@ (cat out) +@(end) +@### +@# process arguments and list soundex codes +@### +@(collect :vars ()) +@input +@ (output :filter (:fun soundex)) +@input +@ (end) +@(end) +@### +@# compare first and second argument under soundex +@### +@(bind (first_arg second_arg . rest_args) input) +@(cases) +@ (bind first_arg second_arg :filter (:fun soundex)) +@ (output) +"@first_arg" and "@second_arg" match under soundex +@ (end) +@(end) diff --git a/Task/Soundex/TXR/soundex-2.txr b/Task/Soundex/TXR/soundex-2.txr new file mode 100644 index 0000000000..19c0428bd6 --- /dev/null +++ b/Task/Soundex/TXR/soundex-2.txr @@ -0,0 +1,27 @@ +@(next :args) +@(do (defun get-code (c) + (cond ((memq c '(#\B #\F #\P #\V)) #\1) + ((memq c '(#\C #\G #\J #\K + #\Q #\S #\X #\Z)) #\2) + ((memq c '(#\D #\T)) #\3) + ((eql c #\L) #\4) + ((memq c '(#\M #\N)) #\5) + ((eq c #\R) #\6))) + + (defun soundex (s) + (if (zerop (length s)) + "" + (let* ((su (upcase-str s)) + (o (chr-str su 0))) + (for ((i 1) (l (length su)) cp cg) + ((< i l) (sub-str (cat-str '(,o "000") nil) 0 4)) + ((inc i) (set cp cg)) + (set cg (get-code (chr-str su i))) + (if (and cg (null (eql cg cp))) + (set o (cat-str '(,o ,cg) nil)))))))) +@(collect) +@arg +@ (output) +@arg -> @(soundex arg) +@ (end) +@(end) diff --git a/Task/Soundex/Tcl/soundex.tcl b/Task/Soundex/Tcl/soundex.tcl new file mode 100644 index 0000000000..d719d2e577 --- /dev/null +++ b/Task/Soundex/Tcl/soundex.tcl @@ -0,0 +1,6 @@ +package require soundex + +foreach string {"Soundex" "Example" "Sownteks" "Ekzampul"} { + set soundexCode [soundex::knuth $string] + puts "\"$string\" has code $soundexCode" +} diff --git a/Task/Soundex/VBScript/soundex.vbscript b/Task/Soundex/VBScript/soundex.vbscript new file mode 100644 index 0000000000..37f576d4b0 --- /dev/null +++ b/Task/Soundex/VBScript/soundex.vbscript @@ -0,0 +1,33 @@ +Function getCode(c) + Select Case c + Case "B", "F", "P", "V" + getCode = "1" + Case "C", "G", "J", "K", "Q", "S", "X", "Z" + getCode = "2" + Case "D", "T" + getCode = "3" + Case "L" + getCode = "4" + Case "M", "N" + getCode = "5" + Case "R" + getCode = "6" + End Select +End Function + +Function soundex(s) + Dim code, previous + code = UCase(Mid(s, 1, 1)) + previous = 7 + For i = 2 to (Len(s) + 1) + current = getCode(UCase(Mid(s, i, 1))) + If Len(current) > 0 And current <> previous Then + code = code & current + End If + previous = current + Next + soundex = Mid(code, 1, 4) + If Len(code) < 4 Then + soundex = soundex & String(4 - Len(code), "0") + End If +End Function diff --git a/Task/Soundex/XPL0/soundex.xpl0 b/Task/Soundex/XPL0/soundex.xpl0 new file mode 100644 index 0000000000..6437c8f188 --- /dev/null +++ b/Task/Soundex/XPL0/soundex.xpl0 @@ -0,0 +1,35 @@ +code CrLf=9, Text=12; +string 0; \use zero-terminated strings + +func Soundex(S1); \Convert name to Soundex string (e.g: Rubin = R150) +char S1; +char S2(80), Tbl; +int I, J, Char, Dig, Dig0; +[ \abcdefghijklmnopqrstuvwxyz +Tbl:= "01230120022455012623010202"; +I:= 0; J:= 0; \convert all letters to digits +repeat Char:= S1(I); I:= I+1; + if Char>=^A & Char<=^Z then \convert letter to lowercase + Char:= Char + $20; + if Char>=^a & Char<=^z & \eliminate non letters + Char#^h & Char#^w then \eliminate h and w + [Dig:= Tbl(Char-^a); \convert letter to digit + if Dig#^0 & Dig#Dig0 ! J=0 then \filter out zeros and doubles + [S2(J):= Dig; J:= J+1]; \ but always store first digit + Dig0:= Dig; \save digit to detect doubles + ]; +until S1(I) = 0; +while J<4 do [S2(J):= ^0; J:= J+1]; \pad with zeros to get 3 digits +S2(0):= S1(0) & ~$20; S2(4):= 0; \insert first letter & terminate +return S2; \BEWARE: very temporary string +]; + +int I, Name; +[Name:=["Ashcraft", "Ashcroft", "de la Rosa", "Gauss", "Ghosh", "Heilbronn", + "Hilbert", "Knuth", "Lee", "Lloyd", "Moses", "O'Hara", "Pfister", + "R2-D2", "Robert", "Rubin", "Rupert", "Tymczak", "Soundex", "Example"]; +for I:= 0 to 20-1 do + [Text(0, Soundex(Name(I))); Text(0, " "); + Text(0, Name(I)); CrLf(0); + ]; +] diff --git a/Task/Special-characters/0DESCRIPTION b/Task/Special-characters/0DESCRIPTION new file mode 100644 index 0000000000..da7de69eb4 --- /dev/null +++ b/Task/Special-characters/0DESCRIPTION @@ -0,0 +1,5 @@ +Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done. + +List the special characters and show escape sequences in the language. + +See also: [[Quotes]] diff --git a/Task/Special-characters/1META.yaml b/Task/Special-characters/1META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/Special-characters/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/Special-characters/ALGOL-68/special-characters-1.alg b/Task/Special-characters/ALGOL-68/special-characters-1.alg new file mode 100644 index 0000000000..a7535997f3 --- /dev/null +++ b/Task/Special-characters/ALGOL-68/special-characters-1.alg @@ -0,0 +1,5 @@ +printf(($"flip:"g"!"l$,flip)); +printf(($"flop:"g"!"l$,flop)); +printf(($"blank:"g"!"l$,blank)); +printf(($"error char:"g"!"l$,error char)); +printf(($"null character:"g"!"l$,null character)) diff --git a/Task/Special-characters/ALGOL-68/special-characters-2.alg b/Task/Special-characters/ALGOL-68/special-characters-2.alg new file mode 100644 index 0000000000..aec95a98f8 --- /dev/null +++ b/Task/Special-characters/ALGOL-68/special-characters-2.alg @@ -0,0 +1,4 @@ +print(("new page:",new page)); +print(("new line:",new line)); +print(("space:",space)); +print(("backspace:",backspace)) diff --git a/Task/Special-characters/Ada/special-characters-1.ada b/Task/Special-characters/Ada/special-characters-1.ada new file mode 100644 index 0000000000..8fe75ee77d --- /dev/null +++ b/Task/Special-characters/Ada/special-characters-1.ada @@ -0,0 +1,6 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test is +begin + Put ("Quote """ & ''' & """" & Character'Val (10)); +end Test; diff --git a/Task/Special-characters/Ada/special-characters-2.ada b/Task/Special-characters/Ada/special-characters-2.ada new file mode 100644 index 0000000000..69b0b57c80 --- /dev/null +++ b/Task/Special-characters/Ada/special-characters-2.ada @@ -0,0 +1,6 @@ +with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO; + +procedure Test is +begin + Put ("Unicode """ & ''' & """" & Wide_Wide_Character'Val (10)); +end Test; diff --git a/Task/Special-characters/C++/special-characters-1.cpp b/Task/Special-characters/C++/special-characters-1.cpp new file mode 100644 index 0000000000..3a25dff430 --- /dev/null +++ b/Task/Special-characters/C++/special-characters-1.cpp @@ -0,0 +1,2 @@ +std::cout << "Tür\n"; +std::cout << "T\u00FC\n"; diff --git a/Task/Special-characters/C++/special-characters-2.cpp b/Task/Special-characters/C++/special-characters-2.cpp new file mode 100644 index 0000000000..62144a6814 --- /dev/null +++ b/Task/Special-characters/C++/special-characters-2.cpp @@ -0,0 +1,2 @@ +extern int Tür; // if the compiler allows literal ü +extern int T\u00FCr; // should in theory work everywhere diff --git a/Task/Special-characters/C++/special-characters-3.cpp b/Task/Special-characters/C++/special-characters-3.cpp new file mode 100644 index 0000000000..6f16bb9bf9 --- /dev/null +++ b/Task/Special-characters/C++/special-characters-3.cpp @@ -0,0 +1,2 @@ +int const\ +ant; // defines a variable of type int named constant, not a variable of type int const named ant diff --git a/Task/Special-characters/C++/special-characters-4.cpp b/Task/Special-characters/C++/special-characters-4.cpp new file mode 100644 index 0000000000..a09903310a --- /dev/null +++ b/Task/Special-characters/C++/special-characters-4.cpp @@ -0,0 +1,2 @@ +char const str = "a string literal"; +char c = 'x'; // a character literal diff --git a/Task/Special-characters/C++/special-characters-5.cpp b/Task/Special-characters/C++/special-characters-5.cpp new file mode 100644 index 0000000000..604782e4dc --- /dev/null +++ b/Task/Special-characters/C++/special-characters-5.cpp @@ -0,0 +1 @@ +#include <iostream> diff --git a/Task/Special-characters/C++/special-characters-6.cpp b/Task/Special-characters/C++/special-characters-6.cpp new file mode 100644 index 0000000000..a6fd717694 --- /dev/null +++ b/Task/Special-characters/C++/special-characters-6.cpp @@ -0,0 +1,5 @@ +#define STR(x) #x +int main() +{ + std::cout << STR(Hello world) << std::endl; // STR(Hello world) expands to "Hello world" +} diff --git a/Task/Special-characters/C++/special-characters-7.cpp b/Task/Special-characters/C++/special-characters-7.cpp new file mode 100644 index 0000000000..a35003278c --- /dev/null +++ b/Task/Special-characters/C++/special-characters-7.cpp @@ -0,0 +1,2 @@ +#define THE(x) the_ ## x +int THE(answer) = 42; // THE(answer) expands to the_answer diff --git a/Task/Special-characters/E/special-characters.e b/Task/Special-characters/E/special-characters.e new file mode 100644 index 0000000000..70993d4189 --- /dev/null +++ b/Task/Special-characters/E/special-characters.e @@ -0,0 +1,3 @@ +? println(`1 + 1$\n= ${1 + 1}`) +1 + 1 += 2 diff --git a/Task/Special-characters/Forth/special-characters-1.fth b/Task/Special-characters/Forth/special-characters-1.fth new file mode 100644 index 0000000000..db5e00005f --- /dev/null +++ b/Task/Special-characters/Forth/special-characters-1.fth @@ -0,0 +1,4 @@ + 10 \ single cell number + -10 \ negative single cell number + 10. \ double cell number + 10e \ floating-point number diff --git a/Task/Special-characters/Forth/special-characters-2.fth b/Task/Special-characters/Forth/special-characters-2.fth new file mode 100644 index 0000000000..1d7b7c1f21 --- /dev/null +++ b/Task/Special-characters/Forth/special-characters-2.fth @@ -0,0 +1,3 @@ + #10 \ decimal + $10 \ hex + %10 \ binary diff --git a/Task/Special-characters/Haskell/special-characters-1.hs b/Task/Special-characters/Haskell/special-characters-1.hs new file mode 100644 index 0000000000..559994a353 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-1.hs @@ -0,0 +1,2 @@ +-- comment here until end of line +{- comment here -} diff --git a/Task/Special-characters/Haskell/special-characters-2.hs b/Task/Special-characters/Haskell/special-characters-2.hs new file mode 100644 index 0000000000..23d506d3b2 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-2.hs @@ -0,0 +1,2 @@ +! # $ % & * + - . / < = > ? @ \ ^ | - ~ : +: as first character denotes constructor diff --git a/Task/Special-characters/Haskell/special-characters-3.hs b/Task/Special-characters/Haskell/special-characters-3.hs new file mode 100644 index 0000000000..6576dac827 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-3.hs @@ -0,0 +1 @@ +.. : :: = \ | <- -> @ ~ => _ diff --git a/Task/Special-characters/Haskell/special-characters-4.hs b/Task/Special-characters/Haskell/special-characters-4.hs new file mode 100644 index 0000000000..8696060ac6 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-4.hs @@ -0,0 +1 @@ +`identifier` (to use as infix operator) diff --git a/Task/Special-characters/Haskell/special-characters-5.hs b/Task/Special-characters/Haskell/special-characters-5.hs new file mode 100644 index 0000000000..740aa81a8a --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-5.hs @@ -0,0 +1,2 @@ +'.' +\ escapes diff --git a/Task/Special-characters/Haskell/special-characters-6.hs b/Task/Special-characters/Haskell/special-characters-6.hs new file mode 100644 index 0000000000..4c6438ad68 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-6.hs @@ -0,0 +1,2 @@ +"..." +\ escapes diff --git a/Task/Special-characters/Haskell/special-characters-7.hs b/Task/Special-characters/Haskell/special-characters-7.hs new file mode 100644 index 0000000000..69a336ca8f --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-7.hs @@ -0,0 +1,7 @@ +\a alert +\b backspace +\f form feed +\n new line +\r carriage return +\t horizontal tab +\v vertical tab diff --git a/Task/Special-characters/Haskell/special-characters-8.hs b/Task/Special-characters/Haskell/special-characters-8.hs new file mode 100644 index 0000000000..478cdcc270 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-8.hs @@ -0,0 +1,5 @@ +( ) (grouping) +( , ) (tuple type/tuple constructor) +{ ; } (grouping inside let, where, do, case without layout) +[ , ] (list type/list constructor) +[ | ] (list comprehension) diff --git a/Task/Special-characters/Haskell/special-characters-9.hs b/Task/Special-characters/Haskell/special-characters-9.hs new file mode 100644 index 0000000000..821ba4cd91 --- /dev/null +++ b/Task/Special-characters/Haskell/special-characters-9.hs @@ -0,0 +1,4 @@ +Upper case (identifiers) +Lower case (identifiers) +Digits (numbers) +Symbol/punctuation (operators) diff --git a/Task/Special-characters/J/special-characters-1.j b/Task/Special-characters/J/special-characters-1.j new file mode 100644 index 0000000000..5a955b99e2 --- /dev/null +++ b/Task/Special-characters/J/special-characters-1.j @@ -0,0 +1,6 @@ + '' NB. empty string + + '''' NB. one quote character +' + '''''' NB. two quote characters +'' diff --git a/Task/Special-characters/J/special-characters-2.j b/Task/Special-characters/J/special-characters-2.j new file mode 100644 index 0000000000..c37e4f4f29 --- /dev/null +++ b/Task/Special-characters/J/special-characters-2.j @@ -0,0 +1 @@ + 'For example, this is a character literal' diff --git a/Task/Special-characters/J/special-characters-3.j b/Task/Special-characters/J/special-characters-3.j new file mode 100644 index 0000000000..dd1549bd64 --- /dev/null +++ b/Task/Special-characters/J/special-characters-3.j @@ -0,0 +1,3 @@ + 1 + 1 0 1 0 1 0 1 + _3.14159e6 diff --git a/Task/Special-characters/J/special-characters-4.j b/Task/Special-characters/J/special-characters-4.j new file mode 100644 index 0000000000..2b8c8c1c15 --- /dev/null +++ b/Task/Special-characters/J/special-characters-4.j @@ -0,0 +1,2 @@ + 3l1t3 +|ill-formed number diff --git a/Task/Special-characters/J/special-characters-5.j b/Task/Special-characters/J/special-characters-5.j new file mode 100644 index 0000000000..a71e211d90 --- /dev/null +++ b/Task/Special-characters/J/special-characters-5.j @@ -0,0 +1 @@ + example=: ARGV NB. example and ARGV are user definable words diff --git a/Task/Special-characters/J/special-characters-6.j b/Task/Special-characters/J/special-characters-6.j new file mode 100644 index 0000000000..d41c1c0f20 --- /dev/null +++ b/Task/Special-characters/J/special-characters-6.j @@ -0,0 +1 @@ + +/ .* NB. + / . and * are all meaningful tokens in J diff --git a/Task/Special-characters/Java/special-characters-1.java b/Task/Special-characters/Java/special-characters-1.java new file mode 100644 index 0000000000..e9971e37ea --- /dev/null +++ b/Task/Special-characters/Java/special-characters-1.java @@ -0,0 +1,4 @@ +& | ^ ~ //bitwise AND, OR, XOR, and NOT +>> << //bitwise arithmetic shift +>>> //bitwise logical shift ++ - * / = % //+ can be used for String concatenation) diff --git a/Task/Special-characters/Java/special-characters-2.java b/Task/Special-characters/Java/special-characters-2.java new file mode 100644 index 0000000000..a81c56b38b --- /dev/null +++ b/Task/Special-characters/Java/special-characters-2.java @@ -0,0 +1,3 @@ +x = x + 2 is the same as x += 2 +++ -- //increment and decrement--before a variable for pre (++x), after for post(x++) +== < > != <= >= //comparison diff --git a/Task/Special-characters/Java/special-characters-3.java b/Task/Special-characters/Java/special-characters-3.java new file mode 100644 index 0000000000..b0d789a80c --- /dev/null +++ b/Task/Special-characters/Java/special-characters-3.java @@ -0,0 +1,3 @@ +! //NOT +&& || //short-circuit AND, OR +^ & | //long-circuit XOR, AND, OR diff --git a/Task/Special-characters/Java/special-characters-4.java b/Task/Special-characters/Java/special-characters-4.java new file mode 100644 index 0000000000..377e46b481 --- /dev/null +++ b/Task/Special-characters/Java/special-characters-4.java @@ -0,0 +1,9 @@ +{ } //scope +( ) //for functions +; //statement terminator +[ ] //array index +" //string literal +' //character literal +? : //ternary operator +// //comment prefix (can be escaped by \u unicode escape sequence see below) +/* */ //comment enclosures (can be escaped by \u unicode escape sequence see below) diff --git a/Task/Special-characters/Java/special-characters-5.java b/Task/Special-characters/Java/special-characters-5.java new file mode 100644 index 0000000000..26219546c2 --- /dev/null +++ b/Task/Special-characters/Java/special-characters-5.java @@ -0,0 +1,10 @@ +\b //Backspace +\n //Line Feed +\r //Carriage Return +\f //Form Feed +\t //Tab +\0 //Null) Note. This is actually a OCTAL escape but handy nonetheless +\' //Single Quote +\" //Double Quote +\\ //Backslash +\DDD //Octal Escape Sequence, D is a number between 0 and 7; can only express characters from 0 to 255 (i.e. \0 to \377) diff --git a/Task/Special-characters/Java/special-characters-6.java b/Task/Special-characters/Java/special-characters-6.java new file mode 100644 index 0000000000..a774526cc3 --- /dev/null +++ b/Task/Special-characters/Java/special-characters-6.java @@ -0,0 +1 @@ +\uHHHH //Unicode Escape Sequence, H is any hexadecimal digit between 0 and 9 and between A and F diff --git a/Task/Special-characters/Java/special-characters-7.java b/Task/Special-characters/Java/special-characters-7.java new file mode 100644 index 0000000000..3c272e233f --- /dev/null +++ b/Task/Special-characters/Java/special-characters-7.java @@ -0,0 +1 @@ +// hello \u000A this looks like a comment diff --git a/Task/Special-characters/Java/special-characters-8.java b/Task/Special-characters/Java/special-characters-8.java new file mode 100644 index 0000000000..acb7a01894 --- /dev/null +++ b/Task/Special-characters/Java/special-characters-8.java @@ -0,0 +1 @@ +"hello \u0022 is this a string?" diff --git a/Task/Special-characters/Java/special-characters-9.java b/Task/Special-characters/Java/special-characters-9.java new file mode 100644 index 0000000000..59070f1b86 --- /dev/null +++ b/Task/Special-characters/Java/special-characters-9.java @@ -0,0 +1,3 @@ +/* + * c:\unix\home\ + */ diff --git a/Task/Special-characters/LaTeX/special-characters.tex b/Task/Special-characters/LaTeX/special-characters.tex new file mode 100644 index 0000000000..d4f3800f04 --- /dev/null +++ b/Task/Special-characters/LaTeX/special-characters.tex @@ -0,0 +1 @@ +5\% of \$10 diff --git a/Task/Special-characters/Mathematica/special-characters.math b/Task/Special-characters/Mathematica/special-characters.math new file mode 100644 index 0000000000..bc3ac0889a --- /dev/null +++ b/Task/Special-characters/Mathematica/special-characters.math @@ -0,0 +1,12 @@ +Markup : +() Sequence +{} List +" String +\ Escape for following character +(* *) Comment block +base^^number`s +` Context +[[]] Indexed reference + +Within expression: +\ At end of line: Continue on next line, skipping white space diff --git a/Task/Special-characters/OCaml/special-characters.ocaml b/Task/Special-characters/OCaml/special-characters.ocaml new file mode 100644 index 0000000000..80a97a4b55 --- /dev/null +++ b/Task/Special-characters/OCaml/special-characters.ocaml @@ -0,0 +1,10 @@ +\\ backslash +\" double quote +\' single quote +\n line feed +\r carriage return +\t tab +\b backspace +\ (backslash followed by a space) space +\DDD where D is a decimal digit; the character with code DDD in decimal +\xHH where H is a hex digit; the character with code HH in hex diff --git a/Task/Special-characters/Objeck/special-characters-1.objeck b/Task/Special-characters/Objeck/special-characters-1.objeck new file mode 100644 index 0000000000..98a77159a0 --- /dev/null +++ b/Task/Special-characters/Objeck/special-characters-1.objeck @@ -0,0 +1,7 @@ +\b //Backspace +\n //Line Feed +\r //Carriage Return +\t //Tab +\0 //Null +\' //Single Quote +\" //Double Q diff --git a/Task/Special-characters/Objeck/special-characters-2.objeck b/Task/Special-characters/Objeck/special-characters-2.objeck new file mode 100644 index 0000000000..a774526cc3 --- /dev/null +++ b/Task/Special-characters/Objeck/special-characters-2.objeck @@ -0,0 +1 @@ +\uHHHH //Unicode Escape Sequence, H is any hexadecimal digit between 0 and 9 and between A and F diff --git a/Task/Special-characters/PARI-GP/special-characters-1.pari b/Task/Special-characters/PARI-GP/special-characters-1.pari new file mode 100644 index 0000000000..810bd3c24d --- /dev/null +++ b/Task/Special-characters/PARI-GP/special-characters-1.pari @@ -0,0 +1 @@ +is square(9) diff --git a/Task/Special-characters/PARI-GP/special-characters-2.pari b/Task/Special-characters/PARI-GP/special-characters-2.pari new file mode 100644 index 0000000000..be2b5ccbb2 --- /dev/null +++ b/Task/Special-characters/PARI-GP/special-characters-2.pari @@ -0,0 +1 @@ +issquare(9) diff --git a/Task/Special-characters/PARI-GP/special-characters-3.pari b/Task/Special-characters/PARI-GP/special-characters-3.pari new file mode 100644 index 0000000000..04f3a47877 --- /dev/null +++ b/Task/Special-characters/PARI-GP/special-characters-3.pari @@ -0,0 +1 @@ +iss qua re(9) diff --git a/Task/Special-characters/PL-I/special-characters.pli b/Task/Special-characters/PL-I/special-characters.pli new file mode 100644 index 0000000000..f3d8f50033 --- /dev/null +++ b/Task/Special-characters/PL-I/special-characters.pli @@ -0,0 +1,2 @@ +'John''s pen' which is stored as <<John's pen>> +"He said ""Go!"" and opened the door" which is stored as <<He said "Go!" and opened the door>> diff --git a/Task/Special-characters/PureBasic/special-characters.purebasic b/Task/Special-characters/PureBasic/special-characters.purebasic new file mode 100644 index 0000000000..5310cdac61 --- /dev/null +++ b/Task/Special-characters/PureBasic/special-characters.purebasic @@ -0,0 +1,2 @@ +a=1 ; The ';' indicates that a comment starts +b=2*a: a=b*33 ; b will now be 2, and a=66 diff --git a/Task/Special-characters/REXX/special-characters-1.rexx b/Task/Special-characters/REXX/special-characters-1.rexx new file mode 100644 index 0000000000..268e821eb0 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-1.rexx @@ -0,0 +1,5 @@ + if a¬==b then say 'not equal' + if a ¬== b then say 'not equal' + if a ¬ = = b then say 'not equal' + if a ¬ , + = = b then say 'not equal' diff --git a/Task/Special-characters/REXX/special-characters-10.rexx b/Task/Special-characters/REXX/special-characters-10.rexx new file mode 100644 index 0000000000..ffae99aca2 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-10.rexx @@ -0,0 +1 @@ + jjj = "Quote the Raven, ""Nevermore""" diff --git a/Task/Special-characters/REXX/special-characters-11.rexx b/Task/Special-characters/REXX/special-characters-11.rexx new file mode 100644 index 0000000000..b5d8f2d5ad --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-11.rexx @@ -0,0 +1,3 @@ + lf = '000001010'b /* (ASCII) */ + cr = "1101"B /* (ASCII) */ + greeting = '100100001100101011011000110110001101111'b /* (ASCII) Hello */ diff --git a/Task/Special-characters/REXX/special-characters-12.rexx b/Task/Special-characters/REXX/special-characters-12.rexx new file mode 100644 index 0000000000..2c6a80a92f --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-12.rexx @@ -0,0 +1,5 @@ + lf = '0A'x /* (ASCII) */ + lf = 'a'x /*same as above. */ + lf = "a"X /*same as above. */ + cr = '0D'x /* (ASCII) */ + greeting = '48656C6C6F'x /* (ASCII) Hello */ diff --git a/Task/Special-characters/REXX/special-characters-13.rexx b/Task/Special-characters/REXX/special-characters-13.rexx new file mode 100644 index 0000000000..9cfec5ba9c --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-13.rexx @@ -0,0 +1 @@ +something=12 -- an assignment, what else diff --git a/Task/Special-characters/REXX/special-characters-14.rexx b/Task/Special-characters/REXX/special-characters-14.rexx new file mode 100644 index 0000000000..e0383b4116 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-14.rexx @@ -0,0 +1 @@ +something=--12 diff --git a/Task/Special-characters/REXX/special-characters-15.rexx b/Task/Special-characters/REXX/special-characters-15.rexx new file mode 100644 index 0000000000..9f92358fef --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-15.rexx @@ -0,0 +1,5 @@ +x='--12 ++12 -12.000 +12 12 12. 012 0012 0012.00 1.2E1 1.2e+1 --12e-00 120e-1 ++12 ++12. 0--12 00--12 --12' + do j=1 for words(x) + interpret 'something=' word(x,j) + say 'j=' j ' x=' x ' something='something + end diff --git a/Task/Special-characters/REXX/special-characters-16.rexx b/Task/Special-characters/REXX/special-characters-16.rexx new file mode 100644 index 0000000000..ffb445bfec --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-16.rexx @@ -0,0 +1,4 @@ +say 'enter an expression:' +parse pull x +interpret 'expression=' x +say 'expression=' expression diff --git a/Task/Special-characters/REXX/special-characters-17.rexx b/Task/Special-characters/REXX/special-characters-17.rexx new file mode 100644 index 0000000000..4020db0dc7 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-17.rexx @@ -0,0 +1 @@ + x=5; y=6;z=y**2; say x y z diff --git a/Task/Special-characters/REXX/special-characters-18.rexx b/Task/Special-characters/REXX/special-characters-18.rexx new file mode 100644 index 0000000000..ca43d71310 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-18.rexx @@ -0,0 +1,2 @@ + say 'The sum of the first three numbers in the file "INSTANCE.INPUTS" is', + a b c ' and the total of all three is' grandTotal diff --git a/Task/Special-characters/REXX/special-characters-19.rexx b/Task/Special-characters/REXX/special-characters-19.rexx new file mode 100644 index 0000000000..dbc955954e --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-19.rexx @@ -0,0 +1,2 @@ + say 'The sums of the first three numbers in the file "INSTANCE.INPUTS" is', /*tell sums.*/ + a b c ' and the total of all three is' grandTotal diff --git a/Task/Special-characters/REXX/special-characters-2.rexx b/Task/Special-characters/REXX/special-characters-2.rexx new file mode 100644 index 0000000000..ccd5a8e17b --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-2.rexx @@ -0,0 +1 @@ +If a/=b Then Say 'a is not equal to b' diff --git a/Task/Special-characters/REXX/special-characters-20.rexx b/Task/Special-characters/REXX/special-characters-20.rexx new file mode 100644 index 0000000000..4317de2e1c --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-20.rexx @@ -0,0 +1,3 @@ + secondChar = substr(xxx, 2, 1) + thirdChar = substr(xxx,3,1) + pruned = strip(zebra, 'Trailing', ".") /*remove trailing period(s).*/ diff --git a/Task/Special-characters/REXX/special-characters-3.rexx b/Task/Special-characters/REXX/special-characters-3.rexx new file mode 100644 index 0000000000..77a69d7e8b --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-3.rexx @@ -0,0 +1,3 @@ + y = (a+b)/(c-d) + z = ((y-2)/(y+2)) / ((a**2 * b**2)* abs(j)) + p = 2**(2**3) diff --git a/Task/Special-characters/REXX/special-characters-4.rexx b/Task/Special-characters/REXX/special-characters-4.rexx new file mode 100644 index 0000000000..729050a4b0 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-4.rexx @@ -0,0 +1,3 @@ + tn = time() + tc = time('C') + x = strip(y,,'+') diff --git a/Task/Special-characters/REXX/special-characters-5.rexx b/Task/Special-characters/REXX/special-characters-5.rexx new file mode 100644 index 0000000000..17eba6c9bf --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-5.rexx @@ -0,0 +1 @@ + a = 'ready, set, go!' diff --git a/Task/Special-characters/REXX/special-characters-6.rexx b/Task/Special-characters/REXX/special-characters-6.rexx new file mode 100644 index 0000000000..c01e016d96 --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-6.rexx @@ -0,0 +1 @@ + a = "ready, set, go!" diff --git a/Task/Special-characters/REXX/special-characters-7.rexx b/Task/Special-characters/REXX/special-characters-7.rexx new file mode 100644 index 0000000000..e93bcb370d --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-7.rexx @@ -0,0 +1,2 @@ + nuttin ='' + nothing="" diff --git a/Task/Special-characters/REXX/special-characters-8.rexx b/Task/Special-characters/REXX/special-characters-8.rexx new file mode 100644 index 0000000000..091ddd8e3a --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-8.rexx @@ -0,0 +1 @@ + yyy = 'John''s pen' diff --git a/Task/Special-characters/REXX/special-characters-9.rexx b/Task/Special-characters/REXX/special-characters-9.rexx new file mode 100644 index 0000000000..22317cae1b --- /dev/null +++ b/Task/Special-characters/REXX/special-characters-9.rexx @@ -0,0 +1 @@ + yyy = "John's pen" diff --git a/Task/Special-characters/Tcl/special-characters.tcl b/Task/Special-characters/Tcl/special-characters.tcl new file mode 100644 index 0000000000..766b2535ae --- /dev/null +++ b/Task/Special-characters/Tcl/special-characters.tcl @@ -0,0 +1,20 @@ +{...} ;# group in one word, without substituting content; nests +"..." ;# group in one word, with substituting content +[...] ;# evaluate content as script, then substitute with its result; nests +$foo ;# substitute with content of variable foo +$bar(foo) ;# substitute with content of element 'foo' of array 'bar' +\a ;# audible alert (bell) +\b ;# backspace +\f ;# form feed +\n ;# newline +\r ;# carriage return +\t ;# Tab +\v ;# vertical tab +\\ ;# backslash +\ooo ;# the Unicode with octal value 'ooo' +\xhh ;# the character with hexadecimal value 'hh' +\uhhhh ;# the Unicode with hexadecimal value 'hhhh' +# ;# if first character of a word expected to be a command, begin comment + ;# (extends till end of line) +{*} ;# if first characters of a word, interpret as list of words to substitute, + ;# not single word (introduced with Tcl 8.5) diff --git a/Task/Special-variables/0DESCRIPTION b/Task/Special-variables/0DESCRIPTION new file mode 100644 index 0000000000..6f0da90a05 --- /dev/null +++ b/Task/Special-variables/0DESCRIPTION @@ -0,0 +1 @@ +Special variables have a predefined meaning within the programming language. The task is to list the special variables used within the language. diff --git a/Task/Special-variables/1META.yaml b/Task/Special-variables/1META.yaml new file mode 100644 index 0000000000..d12c4ff10b --- /dev/null +++ b/Task/Special-variables/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Special variables diff --git a/Task/Special-variables/ALGOL-68/special-variables-1.alg b/Task/Special-variables/ALGOL-68/special-variables-1.alg new file mode 100644 index 0000000000..5b09c00127 --- /dev/null +++ b/Task/Special-variables/ALGOL-68/special-variables-1.alg @@ -0,0 +1,56 @@ +#!/usr/local/bin/a68g --script # + +FORMAT f = $g": ["g"]"l$; + +printf((f, + "pi", pi, + "random", random, # actually a procedure # + + "flip", flip, + "flop", flop, + "TRUE", TRUE, + "FALSE", FALSE, + + "error char", error char, + "null character", null character, +CO "NIL", NIL, NIL is not printable END CO + +# "lengths" details how many distinctive precisions are permitted. # +# e.g. int length = 3 suggests 3 distincts types: # +# INT, LONG INT, and LONG LONG INT # + "bits shorths", bits shorths, + "bits lengths", bits lengths, + "bytes shorths", bytes shorths, + "bytes lengths", bytes lengths, + "int shorths", int shorths, + "int lengths", int lengths, + "real shorths", real shorths, + "real lengths", real lengths, + + "max abs char", max abs char, +# short/long int/real also possible # + "max int", max int, + "small real", small real, + "max real", max real, + +# "width" indicates how many characters are require to prepresent the value # +# short/long bits/bytes/int/real also possible # + "bits width", bits width, + "bytes width", bytes width, + "int width", int width, + "real width", real width, + "exp width", exp width +)); + +# ALL the following are actually procedures # +print(( + "space: [", space, "]", new line, + "new line: [", new line, "]", new line, + "new page: [", new page, "]", new line +CO the following are standard, but not implemented in algol68g + "char number: [", char number, "]", new line, + "line number: [", line number, "]", new line, + "page number: [", page number, "]", new line +END CO +)); +SKIP diff --git a/Task/Special-variables/ALGOL-68/special-variables-2.alg b/Task/Special-variables/ALGOL-68/special-variables-2.alg new file mode 100644 index 0000000000..d77e4864ee --- /dev/null +++ b/Task/Special-variables/ALGOL-68/special-variables-2.alg @@ -0,0 +1,115 @@ +#!/usr/local/bin/a68g --script # + +printf(($g": [", g, "] & [",g,"]"l$, + "Math constants", "long","long long", + "pi", long pi, long long pi, + "Physical Constants", "mksa","cgs", + "Fundamental constants", "mksa","cgs", + " speed of light", mksa speed of light, cgs speed of light, + " vacuum permeability", mksa vacuum permeability, "~", # cgs vacuum permeability,# + " vacuum permittivity", mksa vacuum permittivity, "~", # cgs vacuum permittivity,# + " num avogadro", num avogadro,"~", + " faraday", mksa faraday, cgs faraday, + " boltzmann", mksa boltzmann, cgs boltzmann, + " molar gas", mksa molar gas, cgs molar gas, + " standard gas volume", mksa standard gas volume, cgs standard gas volume, + " planck constant", mksa planck constant, cgs planck constant, + " planck constant bar", mksa planck constant bar, cgs planck constant bar, + " gauss", mksa gauss, cgs gauss, + " micron", mksa micron, cgs micron, + " hectare", mksa hectare, cgs hectare, + " miles per hour", mksa miles per hour, cgs miles per hour, + " kilometers per hour", mksa kilometers per hour, cgs kilometers per hour, + "Astronomy and astrophysics", "mksa","cgs", + " astronomical unit", mksa astronomical unit, cgs astronomical unit, + " gravitational constant", mksa gravitational constant, cgs gravitational constant, + " light year", mksa light year, cgs light year, + " parsec", mksa parsec, cgs parsec, + " grav accel", mksa grav accel, cgs grav accel, + " solar mass", mksa solar mass, cgs solar mass, + "Atomic and nuclear physics", "mksa","cgs", + " electron charge", mksa electron charge, cgs electron charge, + " electron volt", mksa electron volt, cgs electron volt, + " unified atomic mass", mksa unified atomic mass, cgs unified atomic mass, + " mass electron", mksa mass electron, cgs mass electron, + " mass muon", mksa mass muon, cgs mass muon, + " mass proton", mksa mass proton, cgs mass proton, + " mass neutron", mksa mass neutron, cgs mass neutron, + " num fine structure", num fine structure,"~", + " rydberg", mksa rydberg, cgs rydberg, + " bohr radius", mksa bohr radius, cgs bohr radius, + " angstrom", mksa angstrom, cgs angstrom, + " barn", mksa barn, cgs barn, + " bohr magneton", mksa bohr magneton, cgs bohr magneton, + " nuclear magneton", mksa nuclear magneton, cgs nuclear magneton, + " electron magnetic moment", mksa electron magnetic moment, cgs electron magnetic moment, + " proton magnetic moment", mksa proton magnetic moment, cgs proton magnetic moment, + "Time", "mksa","cgs", + " minute", mksa minute, cgs minute, + " hour", mksa hour, cgs hour, + " day", mksa day, cgs day, + " week", mksa week, cgs week, + "Imperial units", "mksa","cgs", + " inch", mksa inch, cgs inch, + " foot", mksa foot, cgs foot, + " yard", mksa yard, cgs yard, + " mile", mksa mile, cgs mile, + " mil", mksa mil, cgs mil, + "Nautical units", "mksa","cgs", + " nautical mile", mksa nautical mile, cgs nautical mile, + " fathom", mksa fathom, cgs fathom, + " knot", mksa knot, cgs knot, + "Volume", "mksa","cgs", + " acre", mksa acre, cgs acre, + " liter", mksa liter, cgs liter, + " us gallon", mksa us gallon, cgs us gallon, + " canadian gallon", mksa canadian gallon, cgs canadian gallon, + " uk gallon", mksa uk gallon, cgs uk gallon, + " quart", mksa quart, cgs quart, + " pint", mksa pint, cgs pint, + "Mass and weight", "mksa","cgs", + " pound mass", mksa pound mass, cgs pound mass, + " ounce mass", mksa ounce mass, cgs ounce mass, + " ton", mksa ton, cgs ton, + " metric ton", mksa metric ton, cgs metric ton, + " uk ton", mksa uk ton, cgs uk ton, + " troy ounce", mksa troy ounce, cgs troy ounce, + " carat", mksa carat, cgs carat, + " gram force", mksa gram force, cgs gram force, + " pound force", mksa pound force, cgs pound force, + " kilopound force", mksa kilopound force, cgs kilopound force, + " poundal", mksa poundal, cgs poundal, + "Thermal energy and power", "mksa","cgs", + " calorie", mksa calorie, cgs calorie, + " btu", mksa btu, cgs btu, + " therm", mksa therm, cgs therm, + " horsepower", mksa horsepower, cgs horsepower, + "Pressure", "mksa","cgs", + " bar", mksa bar, cgs bar, + " std atmosphere", mksa std atmosphere, cgs std atmosphere, + " torr", mksa torr, cgs torr, + " meter of mercury", mksa meter of mercury, cgs meter of mercury, + " inch of mercury", mksa inch of mercury, cgs inch of mercury, + " inch of water", mksa inch of water, cgs inch of water, + " psi", mksa psi, cgs psi, + "Viscosity", "mksa","cgs", + " poise", mksa poise, cgs poise, + " stokes", mksa stokes, cgs stokes, + "Light and illumination", "mksa","cgs", + " stilb", mksa stilb, cgs stilb, + " lumen", mksa lumen, cgs lumen, + " lux", mksa lux, cgs lux, + " phot", mksa phot, cgs phot, + " footcandle", mksa footcandle, cgs footcandle, + " lambert", mksa lambert, cgs lambert, + " footlambert", mksa footlambert, cgs footlambert, + "Radioactivity", "mksa","cgs", + " curie", mksa curie, cgs curie, + " roentgen", mksa roentgen, cgs roentgen, + " rad", mksa rad, cgs rad, + "Force and energy", "mksa","cgs", + " newton", mksa newton, cgs newton, + " dyne", mksa dyne, cgs dyne, + " joule", mksa joule, cgs joule, + " erg", mksa erg, cgs erg +)) diff --git a/Task/Special-variables/C/special-variables.c b/Task/Special-variables/C/special-variables.c new file mode 100644 index 0000000000..8bbc712548 --- /dev/null +++ b/Task/Special-variables/C/special-variables.c @@ -0,0 +1 @@ +int main(int argc, char **argv){...} diff --git a/Task/Special-variables/Icon/special-variables.icon b/Task/Special-variables/Icon/special-variables.icon new file mode 100644 index 0000000000..e56ae6b917 --- /dev/null +++ b/Task/Special-variables/Icon/special-variables.icon @@ -0,0 +1,77 @@ +# &keyword # type returned(indicators) - brief description +# indicators: +# * - generates multiple values +# = - modifiable +# ? - may fail (e.g. status inquiry) +# U - Unicon +# G - Icon or Unicon with Graphics +# +&allocated # integer(*) - report memory allocated in total and by storage regions +&ascii # cset - ASCII character set +&clock # string - time of day +&col # integer(=G) - column location of pointer +&collections # integer(*) - garbage collection activity in total and by storage region +&column # integer(U) - source code column +&control # null(?G) - control key state +&cset # cset - universal character set +¤t # co-expression - current co-expression +&date # string - today's date +&dateline # string - time stamp +&digits # cset - digit characters +&dump # integer(=) - termination dump +&e # real - natural log e +&error # integer(=) - enable/disable error conversion/fail on error +&errno # integer(?) - variable containing error number from previous posix command +&errornumber # integer(?) - error number of last error converted to failure +&errortext # string(?) - error message of last error converted to failure +&errorvalue # any(?) - erroneous value of last error converted to failure +&errout # file - standard error file +&eventcode # integer(=U) - program execution event in monitored program +&eventsource # co-expression(=U) - source of events in monitoring program +&eventvalue # any(=U) - value from event in monitored program +&fail # none - always fails +&features # string(*) - identifying features in this version of Icon/Unicon +&file # string - current source file +&host # string - host machine name +&input # file - standard input file +&interval # integer(G) - time between input events +&lcase # cset - lowercase letters +&ldrag # integer(G) - left button drag +&letters # cset - letters +&level # integer - call depth +&line # integer - current source line number +&lpress # integer(G) - left button press +&lrelease # integer(G) - left button release +&main # co-expression - main task +&mdrag # integer(G) - middle button drag +&meta # null(?G) - meta key state +&mpress # integer(G) - middle button press +&mrelease # integer(G) - middle button release +&now # integer(U) - current time +&null # null - null value +&output # file - standard output file +&pick # string (U) - variable containing the result of 3D selection +&phi # real - golden ratio +&pos # integer(=) - string scanning position +&progname # string(=) - program name +&random # integer(=) - random number seed +&rdrag # integer(G) - right button drag +®ions # integer(*) - region sizes +&resize # integer(G) - window resize +&row # integer(=G) - row location of pointer +&rpress # integer(G) - right button press +&rrelease # integer(G) - right button release +&shift # null(?G) - shift key state +&source # co-expression - invoking co-expression +&storage # integer(*) - memory in use in each region +&subject # string - string scanning subject +&syserr # integer - halt on system error +&time # integer(=) - elapsed time in milliseconds +&trace # integer(=) - trace program +&ucase # cset - upper case letters +&version # string - version +&window # window(=G) - the current graphics rendering window +&x # integer(=G) - pointer horizontal position +&y # integer(=G) - pointer vertical position +# keywords may also fail if the corresponding feature is not present. +# Other variants of Icon (e.g. MT-Icon) will have different mixes of keywords. diff --git a/Task/Special-variables/JavaScript/special-variables-1.js b/Task/Special-variables/JavaScript/special-variables-1.js new file mode 100644 index 0000000000..f11ae337d8 --- /dev/null +++ b/Task/Special-variables/JavaScript/special-variables-1.js @@ -0,0 +1,5 @@ +var obj = { + foo: 1, + bar: function () { return this.foo; } +}; +obj.bar(); // returns 1 diff --git a/Task/Special-variables/JavaScript/special-variables-2.js b/Task/Special-variables/JavaScript/special-variables-2.js new file mode 100644 index 0000000000..089afd7f81 --- /dev/null +++ b/Task/Special-variables/JavaScript/special-variables-2.js @@ -0,0 +1,8 @@ +function concat() { + var s = ""; + for (var i = 0; i < arguments.length; i++) { + s += arguments[i]; + } + return s; +} +concat("a", "b", "c"); // returns "abc" diff --git a/Task/Special-variables/ML-I/special-variables-1.ml b/Task/Special-variables/ML-I/special-variables-1.ml new file mode 100644 index 0000000000..f5e50bebf4 --- /dev/null +++ b/Task/Special-variables/ML-I/special-variables-1.ml @@ -0,0 +1,32 @@ +MCSKIP "WITH" NL +"" Special variables +"" There are four different kinds of variables in ML/I. +"" Permanent (P) variables - these have no special predefined values. +"" Character (C) variables - these have no special predefined values. +"" Temporary (T) variables - a macro has at least three of these, and +"" those have predefined values. +"" System (S) variables - these are for control and status. The number +"" of these is implementation dependent. +MCSKIP MT,<> +MCINS %. +MCDEF TVARDEMO , NL +AS <T-variables are local to the current macro call +T1 is the number of arguments to current macro call - value is %T1. +T2 is the number of macro calls so far - value is %T2. +T3 is the current depth of nesting - value is %T3. +> +TVARDEMO xxx,yyy + +MCDEF SVARDEMO WITHS NL +AS <The first nine S-variables are implementation independent +S1 controls startline insertion - value is %S1. +S2 is the current source text line number - value is %S2. +S3 controls error messages related to warning markers - value is %S3. +S4 controls context printout after a <MCNOTE> - value is %S4. +S5 is the count of processing errors - value is %S5. +S6 enables the definition of an atom to be changed - value is %S6. +S7, S8 and S9 are currently unused. + +All other S-variables have implementation defined meanings. +> +SVARDEMO diff --git a/Task/Special-variables/ML-I/special-variables-2.ml b/Task/Special-variables/ML-I/special-variables-2.ml new file mode 100644 index 0000000000..9f9158ca5a --- /dev/null +++ b/Task/Special-variables/ML-I/special-variables-2.ml @@ -0,0 +1,15 @@ +T-variables are local to the current macro call +T1 is the number of arguments to current macro call - value is 2 +T2 is the number of macro calls so far - value is 5 +T3 is the current depth of nesting - value is 1 + +The first nine S-variables are implementation independent +S1 controls startline insertion - value is 0 +S2 is the current source text line number - value is 32 +S3 controls error messages related to warning markers - value is 0 +S4 controls context printout after a MCNOTE - value is 0 +S5 is the count of processing errors - value is 0 +S6 enables the definition of an atom to be changed - value is -1 +S7, S8 and S9 are currently unused. + +All other S-variables have implementation defined meanings. diff --git a/Task/Special-variables/Mathematica/special-variables.math b/Task/Special-variables/Mathematica/special-variables.math new file mode 100644 index 0000000000..f311a84edd --- /dev/null +++ b/Task/Special-variables/Mathematica/special-variables.math @@ -0,0 +1,45 @@ +Grid[Partition[Names["$*"],4]] +-> +$Aborted $ActivationGroupID $ActivationKey $ActivationUserRegistered +$AddOnsDirectory $AllowDataUpdates $AllowDocumentationUpdates $AllowInternet +$AssertFunction $Assumptions $BaseDirectory $BatchInput +$BatchOutput $BoxForms $ByteOrdering $Canceled +$CharacterEncoding $CharacterEncodings $CommandLine $CompilationTarget +$ConditionHold $ConfiguredKernels $Context $ContextPath +$ControlActiveSetting $CreationDate $CurrentLink $DateStringFormat +$DefaultFont $DefaultFrontEnd $DefaultImagingDevice $DefaultPath +$Display $DisplayFunction $DistributedContexts $DynamicEvaluation +$Echo $Epilog $ExportFormats $Failed +$FinancialDataSource $FormatType $FrontEnd $FrontEndSession +$GeoLocation $HistoryLength $HomeDirectory $IgnoreEOF +$ImagingDevices $ImportFormats $InitialDirectory $Input +$InputFileName $Inspector $InstallationDate $InstallationDirectory +$InstalledServices $InterfaceEnvironment $InternetProxyRules $IterationLimit +$KernelCount $KernelID $Language $LaunchDirectory +$LibraryPath $LicenseExpirationDate $LicenseID $LicenseProcesses +$LicenseServer $LicenseSubprocesses $LicenseType $Line +$Linked $LinkSupported $LoadedFiles $MachineAddresses +$MachineDomain $MachineDomains $MachineEpsilon $MachineID +$MachineName $MachinePrecision $MachineType $MaxExtraPrecision +$MaxLicenseProcesses $MaxLicenseSubprocesses $MaxMachineNumber $MaxNumber +$MaxPiecewiseCases $MaxPrecision $MaxRootDegree $MessageGroups +$MessageList $MessagePrePrint $Messages $MinMachineNumber +$MinNumber $MinorReleaseNumber $MinPrecision $ModuleNumber +$NetworkLicense $NewMessage $NewSymbol $Notebooks +$NumberMarks $Off $OperatingSystem $Output +$OutputForms $OutputSizeLimit $Packages $PacletSite +$ParentLink $ParentProcessID $PasswordFile $PatchLevelID +$Path $PathnameSeparator $PerformanceGoal $PipeSupported +$Post $Pre $PreferencesDirectory $PrePrint +$PreRead $PrintForms $PrintLiteral $PrintServiceRequest +$PrintServiceResponse $PrintShortErrorMessages $PrintWSDLDebug $ProcessID +$ProcessorCount $ProcessorType $ProductInformation $ProgramName +$RandomState $RecursionLimit $ReleaseNumber $RootDirectory +$ScheduledTask $ScriptCommandLine $SessionID $SetParentLink +$SharedFunctions $SharedVariables $SoundDisplay $SoundDisplayFunction +$SuppressInputFormHeads $SynchronousEvaluation $SyntaxHandler $System +$SystemCharacterEncoding $SystemID $SystemWordLength $TemporaryDirectory +$TemporaryPrefix $TextStyle $TimedOut $TimeUnit +$TimeZone $TopDirectory $TraceOff $TraceOn +$TracePattern $TracePostAction $TracePreAction $Urgent +$UserAddOnsDirectory $UserBaseDirectory $UserBasePacletsDirectory $UserDocumentsDirectory diff --git a/Task/Special-variables/Maxima/special-variables.maxima b/Task/Special-variables/Maxima/special-variables.maxima new file mode 100644 index 0000000000..e5a9e8d78f --- /dev/null +++ b/Task/Special-variables/Maxima/special-variables.maxima @@ -0,0 +1,7 @@ +/* There are many special variables in Maxima: more than 250 are used for options, for example */ +fpprec; /* precision for big floats */ +obase; /* number base for output */ + +/* Other variables are read-only, and give the list of user-defined variables, functions... */ +infolists; /* give the names of all available lists */ +[labels, values, functions, macros, arrays, myoptions, props, aliases, rules, gradefs, dependencies, let_rule_packages, structures] diff --git a/Task/Special-variables/NetRexx/special-variables.netrexx b/Task/Special-variables/NetRexx/special-variables.netrexx new file mode 100644 index 0000000000..e76181066f --- /dev/null +++ b/Task/Special-variables/NetRexx/special-variables.netrexx @@ -0,0 +1,34 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +class RCSpecialVariables + +method RCSpecialVariables() + x = super.toString + y = this.toString + say '<super>'x'</super>' + say '<this>'y'</this>' + say '<class>'RCSpecialVariables.class'</class>' + say '<digits>'digits'</digits>' + say '<form>'form'</form>' + say '<[1, 2, 3].length>' + say [1, 2, 3].length + say '</[1, 2, 3].length>' + say '<null>' + say null + say '</null>' + say '<source>'source'</source>' + say '<sourceline>'sourceline'</sourceline>' + say '<trace>'trace'</trace>' + say '<version>'version'</version>' + + say 'Type an answer:' + say '<ask>'ask'</ask>' + + return + +method main(args = String[]) public static + + RCSpecialVariables() + + return diff --git a/Task/Special-variables/OCaml/special-variables-1.ocaml b/Task/Special-variables/OCaml/special-variables-1.ocaml new file mode 100644 index 0000000000..05ebcc2ff7 --- /dev/null +++ b/Task/Special-variables/OCaml/special-variables-1.ocaml @@ -0,0 +1,38 @@ +val argv : string array +(** The command line arguments given to the process. + The first element is the command name used to invoke the program. + The following elements are the command-line arguments + given to the program. *) + +val executable_name : string +(** The name of the file containing the executable currently running. *) + +val interactive : bool ref +(** This reference is initially set to [false] in standalone + programs and to [true] if the code is being executed under + the interactive toplevel system [ocaml]. *) + +val os_type : string +(** Operating system currently executing the Caml program. One of +- ["Unix"] (for all Unix versions, including Linux and Mac OS X), +- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw), +- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *) + +val word_size : int +(** Size of one word on the machine currently executing the Caml + program, in bits: 32 or 64. *) + +val max_string_length : int +(** Maximum length of a string. *) + +val max_array_length : int +(** Maximum length of a normal array. The maximum length of a float + array is [max_array_length/2] on 32-bit machines and + [max_array_length] on 64-bit machines. *) + +val ocaml_version : string +(** [ocaml_version] is the version of Objective Caml. + It is a string of the form ["major.minor[.patchlevel][+additional-info]"], + where [major], [minor], and [patchlevel] are integers, and + [additional-info] is an arbitrary string. The [[.patchlevel]] and + [[+additional-info]] parts may be absent. *) diff --git a/Task/Special-variables/OCaml/special-variables-2.ocaml b/Task/Special-variables/OCaml/special-variables-2.ocaml new file mode 100644 index 0000000000..d633eedd55 --- /dev/null +++ b/Task/Special-variables/OCaml/special-variables-2.ocaml @@ -0,0 +1,15 @@ +val max_int : int +(** The greatest representable integer. *) + +val min_int : int +(** The smallest representable integer. *) + +val max_float : float +(** The largest positive finite value of type [float]. *) + +val min_float : float +(** The smallest positive, non-zero, non-denormalized value of type [float]. *) + +val epsilon_float : float +(** The difference between [1.0] and the smallest exactly representable + floating-point number greater than [1.0]. *) diff --git a/Task/Special-variables/Perl-6/special-variables-1.pl6 b/Task/Special-variables/Perl-6/special-variables-1.pl6 new file mode 100644 index 0000000000..498e396a9e --- /dev/null +++ b/Task/Special-variables/Perl-6/special-variables-1.pl6 @@ -0,0 +1,5 @@ + $foo scalar (object) + @foo ordered array + %foo unordered hash (associative array) + &foo code/rule/token/regex + ::foo package/module/class/role/subset/enum/type/grammar diff --git a/Task/Special-variables/Perl-6/special-variables-2.pl6 b/Task/Special-variables/Perl-6/special-variables-2.pl6 new file mode 100644 index 0000000000..cfcc0d0692 --- /dev/null +++ b/Task/Special-variables/Perl-6/special-variables-2.pl6 @@ -0,0 +1,10 @@ + $foo # ordinary scoping + $.foo # object attribute public accessor + $^foo # self-declared formal positional parameter + $:foo # self-declared formal named parameter + $*foo # dynamically overridable global variable + $?foo # compiler hint variable + $=foo # Pod variable + $<foo> # match variable, short for $/{'foo'} + $!foo # object attribute private storage + $~foo # the foo sublanguage seen by the parser at this lexical spot diff --git a/Task/Special-variables/Perl-6/special-variables-3.pl6 b/Task/Special-variables/Perl-6/special-variables-3.pl6 new file mode 100644 index 0000000000..cede2cace7 --- /dev/null +++ b/Task/Special-variables/Perl-6/special-variables-3.pl6 @@ -0,0 +1,56 @@ + $_ # The implicit variable lexically scoped to the current block + @_ # Implicit array of parameters to the current block. Still available but rarely used or needed with the improved sub signatures + $! # Current Exception object + $/ # Last match + $0, $1, $2... # Captured values from match: $/[0], $/[1], $/[2] ... + $?ARCH # Host architecture + $?XARCH # Target architecture + @*ARGS # command-line arguments + $*ARGFILES # The magic command-line input handle + &?BLOCK # current block (itself) + ::?CLASS # current class (as package or type name) + $?CLASS # current class + @=COMMENT # All the comment blocks in the file + %?CONFIG # configuration hash + $*CWD # current working directory + $=DATA # data block handle (=begin DATA ... =end) + @=DATA # Same as above, but array + %?DEEPMAGIC # Controls the mappings of magical names to sub definitions + $?DISTRO # Which OS distribution am I compiling under + $*DISTRO # Which OS distribution am I running under + $*EGID # effective group id + %*ENV # system environment variables + $*ERR # Standard error handle + $*EUID # effective user id + $*EXECUTABLE_NAME # executable name + $?FILE # current filename of source file + $?GRAMMAR # current grammar + $*GID # group id + $*IN # Standard input handle; is an IO object + @*INC # where to search for user modules (but not std lib!) + $?KERNEL # operating system compiled for + $*KERNEL # operating system running under + %?LANG # What is the current set of interwoven languages? + $*LANG # LANG variable from %*ENV that defines what human language is used + $?LINE # current line number in source file + %*META-ARGS # Meta-arguments + $?MODULE # current module + %*OPTS # Options from command line + %*OPT... # Options from command line to be passed down + $*OUT # Standard output handle + $?PACKAGE # current package + $?PERL # Which Perl am I compiled for? + $*PERL # perl version running under + $*PID # system process id + %=POD # POD + $*PROGRAM_NAME # name of the Perl program being executed + %*PROTOCOLS # Stores the methods needed for the uri() function + ::?ROLE # current role (as package or type name) + $?ROLE # current role + &?ROUTINE # current sub or method (itself) + $?SCOPE # Current "my" scope + $*TZ # Local time zone + $*UID # system user id + $?USAGE # Default usage message generated at compile time + $?VM # Which virtual machine am I compiling under + $?XVM # Which virtual machine am I cross-compiling for diff --git a/Task/Special-variables/Perl-6/special-variables-4.pl6 b/Task/Special-variables/Perl-6/special-variables-4.pl6 new file mode 100644 index 0000000000..8b9a7c7274 --- /dev/null +++ b/Task/Special-variables/Perl-6/special-variables-4.pl6 @@ -0,0 +1,3 @@ + * # A standalone term that has no fixed value, instead it captures the notion of "Whatever", + # the meaning of which is decided lazily by whatever it is an argument to. + # See the "*" section of http://perlcabal.org/syn/S02.html#Built-In_Data_Types diff --git a/Task/Special-variables/Python/special-variables.py b/Task/Special-variables/Python/special-variables.py new file mode 100644 index 0000000000..265b92a677 --- /dev/null +++ b/Task/Special-variables/Python/special-variables.py @@ -0,0 +1,2 @@ +names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) +print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) ) diff --git a/Task/Special-variables/REXX/special-variables.rexx b/Task/Special-variables/REXX/special-variables.rexx new file mode 100644 index 0000000000..bd615b0449 --- /dev/null +++ b/Task/Special-variables/REXX/special-variables.rexx @@ -0,0 +1,28 @@ +/*REXX program to demonstrate REXX special variables: RC, RESULT, SIGL. */ + /*line two. */ + /*line three.*/ say copies('=',75) +rc=1/3 /*line four. */ +signal youWho /*line five. */ +myLoo='this got skipped' /*line six. */ +youwho: /*line seven.*/ +say 'SIGL=' sigl +say 'REXX source statement' SIGL '=' sourceline(sigl) + say copies('=',75) +g=44 +call someFunc g +say 'rc=' rc +say 'result=' result + say copies('=',75) +h=66 +hh=someFunc(h) +say 'rc=' rc +say 'result=' result +say 'hh=' hh + say copies('=',75) +'DIR C:\ /ad | find /i /v "Volume " ' +say 'rc=' rc +say 'result=' result + say copies('=',75) +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────someFunc subroutine.───────────────*/ +someFunc: procedure; parse arg x; return x/2 diff --git a/Task/Special-variables/Smalltalk/special-variables-1.st b/Task/Special-variables/Smalltalk/special-variables-1.st new file mode 100644 index 0000000000..e84eedd69a --- /dev/null +++ b/Task/Special-variables/Smalltalk/special-variables-1.st @@ -0,0 +1 @@ +Smalltalk keys diff --git a/Task/Special-variables/Smalltalk/special-variables-2.st b/Task/Special-variables/Smalltalk/special-variables-2.st new file mode 100644 index 0000000000..8e234d76f3 --- /dev/null +++ b/Task/Special-variables/Smalltalk/special-variables-2.st @@ -0,0 +1 @@ +Float precision diff --git a/Task/Special-variables/Smalltalk/special-variables-3.st b/Task/Special-variables/Smalltalk/special-variables-3.st new file mode 100644 index 0000000000..0355430ad3 --- /dev/null +++ b/Task/Special-variables/Smalltalk/special-variables-3.st @@ -0,0 +1 @@ +Smalltalk version diff --git a/Task/Special-variables/Tcl/special-variables.tcl b/Task/Special-variables/Tcl/special-variables.tcl new file mode 100644 index 0000000000..10cbaccf17 --- /dev/null +++ b/Task/Special-variables/Tcl/special-variables.tcl @@ -0,0 +1,3 @@ +10 PRINT "The border colour is "; PEEK (23624): REM bordcr +20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop +30 POKE 23609,50: REM set keyboard pip to 50 diff --git a/Task/Speech-synthesis/0DESCRIPTION b/Task/Speech-synthesis/0DESCRIPTION new file mode 100644 index 0000000000..03a462c190 --- /dev/null +++ b/Task/Speech-synthesis/0DESCRIPTION @@ -0,0 +1,2 @@ +<!-- this task to be in "Temporal media" category once ready. -->[[Category:Speech synthesis]][[Category:Temporal media]] +Render the text “<tt>This is an example of speech synthesis.</tt>” as speech. diff --git a/Task/Speech-synthesis/1META.yaml b/Task/Speech-synthesis/1META.yaml new file mode 100644 index 0000000000..f22ec02786 --- /dev/null +++ b/Task/Speech-synthesis/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Temporal media diff --git a/Task/Speech-synthesis/AutoHotkey/speech-synthesis.ahk b/Task/Speech-synthesis/AutoHotkey/speech-synthesis.ahk new file mode 100644 index 0000000000..29421dff7f --- /dev/null +++ b/Task/Speech-synthesis/AutoHotkey/speech-synthesis.ahk @@ -0,0 +1,2 @@ +talk := ComObjCreate("sapi.spvoice") +talk.Speak("This is an example of speech synthesis.") diff --git a/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 b/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 new file mode 100644 index 0000000000..18dc7fbcfd --- /dev/null +++ b/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 @@ -0,0 +1 @@ +say "Goodbye, World for the " + 123456 + "th time." diff --git a/Task/Speech-synthesis/BBC-BASIC/speech-synthesis.bbc b/Task/Speech-synthesis/BBC-BASIC/speech-synthesis.bbc new file mode 100644 index 0000000000..814f353c6f --- /dev/null +++ b/Task/Speech-synthesis/BBC-BASIC/speech-synthesis.bbc @@ -0,0 +1,39 @@ + SPF_ASYNC = 1 + ON ERROR SYS `CoUninitialize` : PRINT 'REPORT$ : END + ON CLOSE SYS `CoUninitialize` : QUIT + + SYS "LoadLibrary","OLE32.DLL" TO O% + SYS "GetProcAddress",O%,"CoInitialize" TO `CoInitialize` + SYS "GetProcAddress",O%,"CoUninitialize" TO `CoUninitialize` + SYS "GetProcAddress",O%,"CoCreateInstance" TO `CoCreateInstance` + + SYS `CoInitialize`,0 + voice% = FN_voice_create + PROC_voice_speak(voice%, "This is an example of speech synthesis") + PROC_voice_wait(voice%) + PROC_voice_free(voice%) + SYS `CoUninitialize` + END + + DEF FN_voice_create + LOCAL C%, D%, F%, I%, M%, P%, V% + DIM C% LOCAL 15, I% LOCAL 15 + C%!0 = &96749377 : C%!4 = &11D23391 : C%!8 = &C000E39E : C%!12 = &9673794F + I%!0 = &6C44DF74 : I%!4 = &499272B9 : I%!8 = &99EFECA1 : I%!12 = &D422046E + SYS `CoCreateInstance`, C%, 0, 5, I%, ^V% + IF V%=0 ERROR 100, "SAPI5 not available" + = V% + + DEF PROC_voice_speak(V%, M$) + DIM M% LOCAL 2*LENM$+1 + SYS "MultiByteToWideChar", 0, 0, M$, -1, M%, LENM$+1 + SYS !(!V%+80), V%, M%, SPF_ASYNC, 0 + ENDPROC + + DEF PROC_voice_wait(V%) + SYS !(!V%+128), V% + ENDPROC + + DEF PROC_voice_free(V%) + SYS !(!V%+8), V% + ENDPROC diff --git a/Task/Speech-synthesis/C/speech-synthesis.c b/Task/Speech-synthesis/C/speech-synthesis.c new file mode 100644 index 0000000000..f31a4fd5b2 --- /dev/null +++ b/Task/Speech-synthesis/C/speech-synthesis.c @@ -0,0 +1,32 @@ +#include <sys/wait.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +void talk(const char *s) +{ + pid_t pid; + int status; + + pid = fork(); + if (pid < 0) { + perror("fork"); + exit(1); + } + + if (pid == 0) { + execlp("espeak", "espeak", s, (void*)0); + perror("espeak"); + _exit(1); + } + + waitpid(pid, &status, 0); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) + exit(1); +} + +int main() +{ + talk("This is an example of speech synthesis."); + return 0; +} diff --git a/Task/Speech-synthesis/Haskell/speech-synthesis.hs b/Task/Speech-synthesis/Haskell/speech-synthesis.hs new file mode 100644 index 0000000000..feef3f452c --- /dev/null +++ b/Task/Speech-synthesis/Haskell/speech-synthesis.hs @@ -0,0 +1,5 @@ +import System + +say x = system $ "espeak " ++ show x + +main = say "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/Liberty-BASIC/speech-synthesis.liberty b/Task/Speech-synthesis/Liberty-BASIC/speech-synthesis.liberty new file mode 100644 index 0000000000..ca0aedd6bf --- /dev/null +++ b/Task/Speech-synthesis/Liberty-BASIC/speech-synthesis.liberty @@ -0,0 +1,3 @@ +nomainwin +run "C:\Program Files\eSpeak\command_line\espeak "; chr$( 34); "This is an example of speech synthesis."; chr$( 34) +end diff --git a/Task/Speech-synthesis/Locomotive-Basic/speech-synthesis.locomotive b/Task/Speech-synthesis/Locomotive-Basic/speech-synthesis.locomotive new file mode 100644 index 0000000000..0bf97cf382 --- /dev/null +++ b/Task/Speech-synthesis/Locomotive-Basic/speech-synthesis.locomotive @@ -0,0 +1 @@ +|say,"This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/Mathematica/speech-synthesis.math b/Task/Speech-synthesis/Mathematica/speech-synthesis.math new file mode 100644 index 0000000000..901e57c240 --- /dev/null +++ b/Task/Speech-synthesis/Mathematica/speech-synthesis.math @@ -0,0 +1 @@ +Speak["This is an example of speech synthesis."] diff --git a/Task/Speech-synthesis/PicoLisp/speech-synthesis.l b/Task/Speech-synthesis/PicoLisp/speech-synthesis.l new file mode 100644 index 0000000000..eaa15a2153 --- /dev/null +++ b/Task/Speech-synthesis/PicoLisp/speech-synthesis.l @@ -0,0 +1 @@ +(call 'espeak "This is an example of speech synthesis.") diff --git a/Task/Speech-synthesis/Ruby/speech-synthesis-1.rb b/Task/Speech-synthesis/Ruby/speech-synthesis-1.rb new file mode 100644 index 0000000000..06c7ff2f60 --- /dev/null +++ b/Task/Speech-synthesis/Ruby/speech-synthesis-1.rb @@ -0,0 +1,21 @@ +module OperatingSystem + require 'rbconfig' + module_function + def operating_system + case RbConfig::CONFIG["host_os"] + when /linux/i + :linux + when /cygwin|mswin|mingw|windows/i + :windows + when /darwin/i + :mac + when /solaris/i + :solaris + else + nil + end + end + def linux?; operating_system == :linux; end + def windows?; operating_system == :windows; end + def mac?; operating_system == :mac; end +end diff --git a/Task/Speech-synthesis/Ruby/speech-synthesis-2.rb b/Task/Speech-synthesis/Ruby/speech-synthesis-2.rb new file mode 100644 index 0000000000..05412fce6a --- /dev/null +++ b/Task/Speech-synthesis/Ruby/speech-synthesis-2.rb @@ -0,0 +1,17 @@ +load 'operating_system.rb' + +def speak(text) + if OperatingSystem.windows? + require 'win32/sapi5' + v = Win32::SpVoice.new + v.Speak(text) + elsif OperatingSystem.mac? + IO.popen(["say"], "w") {|pipe| pipe.puts text} + else + # Try to run "espeak". No OperatingSystem check: "espeak" is + # for Linux but is also an optional package for BSD. + IO.popen(["espeak", "-stdin"], "w") {|pipe| pipe.puts text} + end +end + +speak 'This is an example of speech synthesis.' diff --git a/Task/Speech-synthesis/Tcl/speech-synthesis-1.tcl b/Task/Speech-synthesis/Tcl/speech-synthesis-1.tcl new file mode 100644 index 0000000000..a0ae0ce9f3 --- /dev/null +++ b/Task/Speech-synthesis/Tcl/speech-synthesis-1.tcl @@ -0,0 +1 @@ +exec festival --tts << "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/Tcl/speech-synthesis-2.tcl b/Task/Speech-synthesis/Tcl/speech-synthesis-2.tcl new file mode 100644 index 0000000000..f63cd17857 --- /dev/null +++ b/Task/Speech-synthesis/Tcl/speech-synthesis-2.tcl @@ -0,0 +1 @@ +exec say << "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/Tcl/speech-synthesis-3.tcl b/Task/Speech-synthesis/Tcl/speech-synthesis-3.tcl new file mode 100644 index 0000000000..097109ac2f --- /dev/null +++ b/Task/Speech-synthesis/Tcl/speech-synthesis-3.tcl @@ -0,0 +1,5 @@ +package require tcom + +set msg "This is an example of speech synthesis." +set voice [::tcom::ref createobject Sapi.SpVoice] +$voice Speak $msg 0 diff --git a/Task/Speech-synthesis/Tcl/speech-synthesis-4.tcl b/Task/Speech-synthesis/Tcl/speech-synthesis-4.tcl new file mode 100644 index 0000000000..e512b939d1 --- /dev/null +++ b/Task/Speech-synthesis/Tcl/speech-synthesis-4.tcl @@ -0,0 +1,13 @@ +proc speak {msg} { + global tcl_platform + if {$tcl_platform(platform) eq "windows"} { + package require tcom + set voice [::tcom::ref createobject Sapi.SpVoice] + $voice Speak $msg 0 + } elseif {$tcl_platform(os) eq "Darwin"} { + exec say << $msg + } else { + exec festival --tts << $msg + } +} +speak "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/UNIX-Shell/speech-synthesis.sh b/Task/Speech-synthesis/UNIX-Shell/speech-synthesis.sh new file mode 100644 index 0000000000..2dd0494891 --- /dev/null +++ b/Task/Speech-synthesis/UNIX-Shell/speech-synthesis.sh @@ -0,0 +1,2 @@ +#!/bin/sh +espeak "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/VBScript/speech-synthesis.vbscript b/Task/Speech-synthesis/VBScript/speech-synthesis.vbscript new file mode 100644 index 0000000000..8f8ef001b5 --- /dev/null +++ b/Task/Speech-synthesis/VBScript/speech-synthesis.vbscript @@ -0,0 +1,4 @@ +Dim message, sapi +message = "This is an example of speech synthesis." +Set sapi = CreateObject("sapi.spvoice") +sapi.Speak message diff --git a/Task/Speech-synthesis/ZX-Spectrum-Basic/speech-synthesis.zx b/Task/Speech-synthesis/ZX-Spectrum-Basic/speech-synthesis.zx new file mode 100644 index 0000000000..f8b49bf584 --- /dev/null +++ b/Task/Speech-synthesis/ZX-Spectrum-Basic/speech-synthesis.zx @@ -0,0 +1 @@ +10 LET s$="(th)is is an exampul of sp(ee)(ch) sin(th)esis":PAUSE 1 diff --git a/Task/Spiral-matrix/0DESCRIPTION b/Task/Spiral-matrix/0DESCRIPTION new file mode 100644 index 0000000000..9b6d76fc4c --- /dev/null +++ b/Task/Spiral-matrix/0DESCRIPTION @@ -0,0 +1,10 @@ +Produce a spiral array. A spiral array is a square arrangement of the first <tt>N<sup>2</sup></tt> natural numbers, where the numbers increase sequentially as you go around the edges of the array spiralling inwards. + +For example, given 5, produce this array: +<pre> + 0 1 2 3 4 +15 16 17 18 5 +14 23 24 19 6 +13 22 21 20 7 +12 11 10 9 8 +</pre> diff --git a/Task/Spiral-matrix/1META.yaml b/Task/Spiral-matrix/1META.yaml new file mode 100644 index 0000000000..1e81690bbc --- /dev/null +++ b/Task/Spiral-matrix/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Matrices diff --git a/Task/Spiral-matrix/ALGOL-68/spiral-matrix.alg b/Task/Spiral-matrix/ALGOL-68/spiral-matrix.alg new file mode 100644 index 0000000000..6db91b1142 --- /dev/null +++ b/Task/Spiral-matrix/ALGOL-68/spiral-matrix.alg @@ -0,0 +1,34 @@ +INT empty=0; + +PROC spiral = (INT n)[,]INT: ( + INT dx:=1, dy:=0; # Starting increments # + INT x:=0, y:=0; # Starting location # + [0:n-1,0:n-1]INT my array; + FOR y FROM LWB my array TO UPB my array DO + FOR x FROM LWB my array TO UPB my array DO + my array[x,y]:=empty + OD + OD; + FOR i TO n**2 DO + my array[x,y] := i; + INT nx:=x+dx, ny:=y+dy; + IF ( 0<=nx AND nx<n AND 0<=ny AND ny<n | my array[nx,ny] = empty | FALSE ) THEN + x:=nx; y:=ny + ELSE + INT swap:=dx; dx:=-dy; dy:=swap; + x+:=dx; y+:=dy + FI + OD; + my array +); + +PROC print spiral = ([,]INT my array)VOID:( + FOR y FROM LWB my array TO UPB my array DO + FOR x FROM LWB my array TO UPB my array DO + print(whole(my array[x,y],-3)) + OD; + print(new line) + OD +); + +print spiral(spiral(5)) diff --git a/Task/Spiral-matrix/AWK/spiral-matrix.awk b/Task/Spiral-matrix/AWK/spiral-matrix.awk new file mode 100644 index 0000000000..794d1f7b3d --- /dev/null +++ b/Task/Spiral-matrix/AWK/spiral-matrix.awk @@ -0,0 +1,39 @@ +# syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size] +# converted from BBC BASIC +BEGIN { +# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2 + offset = (offset == "") ? 0 : offset + size = (ARGV[1] == "") ? 5 : ARGV[1] + if (offset !~ /^[01]$/) { exit(1) } + if (size !~ /^[0-9]+$/) { exit(1) } + bot_col = bot_row = 0 + top_col = top_row = size - 1 + direction = col = row = 0 + for (i=0; i<=size*size-1; i++) { # build + arr[col,row] = i + offset + if (direction == 0) { + if (col < top_col) { col++ } + else { direction = 1 ; row++ ; bot_row++ } + } + else if (direction == 1) { + if (row < top_row) { row++ } + else { direction = 2 ; col-- ; top_col-- } + } + else if (direction == 2) { + if (col > bot_col) { col-- } + else { direction = 3 ; row-- ; top_row-- } + } + else if (direction == 3) { + if (row > bot_row) { row-- } + else { direction = 0 ; col++ ; bot_col++ } + } + } + width = length(size ^ 2 - 1 + offset) + 1 # column width + for (i=0; i<size; i++) { # print + for (j=0; j<size; j++) { + printf("%*d",width,arr[j,i]) + } + printf("\n") + } + exit(0) +} diff --git a/Task/Spiral-matrix/Ada/spiral-matrix-1.ada b/Task/Spiral-matrix/Ada/spiral-matrix-1.ada new file mode 100644 index 0000000000..b87535521b --- /dev/null +++ b/Task/Spiral-matrix/Ada/spiral-matrix-1.ada @@ -0,0 +1,67 @@ +-- Spiral Square +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; + +procedure Spiral_Square is + type Array_Type is array(Positive range <>, Positive range <>) of Natural; + + function Spiral (N : Positive) return Array_Type is + Result : Array_Type(1..N, 1..N); + Row : Natural := 1; + Col : Natural := 1; + Max_Row : Natural := N; + Max_Col : Natural := N; + Min_Row : Natural := 1; + Min_Col : Natural := 1; + begin + for I in 0..N**2 - 1 loop + Result(Row, Col) := I; + if Row = Min_Row then + Col := Col + 1; + if Col > Max_Col then + Col := Max_Col; + Row := Row + 1; + end if; + elsif Col = Max_Col then + Row := Row + 1; + if Row > Max_Row then + Row := Max_Row; + Col := Col - 1; + end if; + elsif Row = Max_Row then + Col := Col - 1; + if Col < Min_Col then + Col := Min_Col; + Row := Row - 1; + end if; + elsif Col = Min_Col then + Row := Row - 1; + if Row = Min_Row then -- Reduce spiral + Min_Row := Min_Row + 1; + Max_Row := Max_Row - 1; + Row := Min_Row; + Min_Col := Min_Col + 1; + Max_Col := Max_Col - 1; + Col := Min_Col; + end if; + end if; + end loop; + return Result; + end Spiral; + + procedure Print(Item : Array_Type) is + Num_Digits : constant Float := Log(X => Float(Item'Length(1)**2), Base => 10.0); + Spacing : constant Positive := Integer(Num_Digits) + 2; + begin + for I in Item'range(1) loop + for J in Item'range(2) loop + Put(Item => Item(I,J), Width => Spacing); + end loop; + New_Line; + end loop; + end Print; + +begin + Print(Spiral(5)); +end Spiral_Square; diff --git a/Task/Spiral-matrix/Ada/spiral-matrix-2.ada b/Task/Spiral-matrix/Ada/spiral-matrix-2.ada new file mode 100644 index 0000000000..edee29745e --- /dev/null +++ b/Task/Spiral-matrix/Ada/spiral-matrix-2.ada @@ -0,0 +1,33 @@ +function Spiral (N : Positive) return Array_Type is + Result : Array_Type (1..N, 1..N); + Left : Positive := 1; + Right : Positive := N; + Top : Positive := 1; + Bottom : Positive := N; + Index : Natural := 0; +begin + while Left < Right loop + for I in Left..Right - 1 loop + Result (Top, I) := Index; + Index := Index + 1; + end loop; + for J in Top..Bottom - 1 loop + Result (J, Right) := Index; + Index := Index + 1; + end loop; + for I in reverse Left + 1..Right loop + Result (Bottom, I) := Index; + Index := Index + 1; + end loop; + for J in reverse Top + 1..Bottom loop + Result (J, Left) := Index; + Index := Index + 1; + end loop; + Left := Left + 1; + Right := Right - 1; + Top := Top + 1; + Bottom := Bottom - 1; + end loop; + Result (Top, Left) := Index; + return Result; +end Spiral; diff --git a/Task/Spiral-matrix/AutoHotkey/spiral-matrix.ahk b/Task/Spiral-matrix/AutoHotkey/spiral-matrix.ahk new file mode 100644 index 0000000000..96ebb8530e --- /dev/null +++ b/Task/Spiral-matrix/AutoHotkey/spiral-matrix.ahk @@ -0,0 +1,26 @@ +n := 5, dx := x := y := v := 1, dy := 0 + +Loop % n*n { + a_%x%_%y% := v++ + nx := x+dx, ny := y+dy + If (1 > nx || nx > n || 1 > ny || ny > n || a_%nx%_%ny%) + t := dx, dx := -dy, dy := t + x := x+dx, y := y+dy +} + +Loop %n% { ; generate printout + y := A_Index ; for each row + Loop %n% ; and for each column + s .= a_%A_Index%_%y% "`t" ; attach stored index + s .= "`n" ; row is complete +} +MsgBox %s% ; show output +/* +--------------------------- +1 2 3 4 5 +16 17 18 19 6 +15 24 25 20 7 +14 23 22 21 8 +13 12 11 10 9 +--------------------------- +*/ diff --git a/Task/Spiral-matrix/BBC-BASIC/spiral-matrix.bbc b/Task/Spiral-matrix/BBC-BASIC/spiral-matrix.bbc new file mode 100644 index 0000000000..70b180742a --- /dev/null +++ b/Task/Spiral-matrix/BBC-BASIC/spiral-matrix.bbc @@ -0,0 +1,18 @@ + N%=5 + @%=LENSTR$(N%*N%-1)+1 + BotCol%=0 : TopCol%=N%-1 + BotRow%=0 : TopRow%=N%-1 + DIM Matrix%(TopCol%,TopRow%) + + Dir%=0 : Col%=0 : Row%=0 + FOR I%=0 TO N%*N%-1 + Matrix%(Col%,Row%)=I% + PRINT TAB(Col%*@%,Row%) I% + CASE Dir% OF + WHEN 0: IF Col% < TopCol% THEN Col%+=1 ELSE Dir%=1 : Row%+=1 : BotRow%+=1 + WHEN 1: IF Row% < TopRow% THEN Row%+=1 ELSE Dir%=2 : Col%-=1 : TopCol%-=1 + WHEN 2: IF Col% > BotCol% THEN Col%-=1 ELSE Dir%=3 : Row%-=1 : TopRow%-=1 + WHEN 3: IF Row% > BotRow% THEN Row%-=1 ELSE Dir%=0 : Col%+=1 : BotCol%+=1 + ENDCASE + NEXT + END diff --git a/Task/Spiral-matrix/C++/spiral-matrix.cpp b/Task/Spiral-matrix/C++/spiral-matrix.cpp new file mode 100644 index 0000000000..0a5bcb88bf --- /dev/null +++ b/Task/Spiral-matrix/C++/spiral-matrix.cpp @@ -0,0 +1,67 @@ +#include <vector> +#include <memory> // for auto_ptr +#include <cmath> // for the ceil and log10 and floor functions +#include <iostream> +#include <iomanip> // for the setw function + +using namespace std; + +typedef vector< int > IntRow; +typedef vector< IntRow > IntTable; + +auto_ptr< IntTable > getSpiralArray( int dimension ) +{ + auto_ptr< IntTable > spiralArrayPtr( new IntTable( + dimension, IntRow( dimension ) ) ); + + int numConcentricSquares = static_cast< int >( ceil( + static_cast< double >( dimension ) / 2.0 ) ); + + int j; + int sideLen = dimension; + int currNum = 0; + + for ( int i = 0; i < numConcentricSquares; i++ ) + { + // do top side + for ( j = 0; j < sideLen; j++ ) + ( *spiralArrayPtr )[ i ][ i + j ] = currNum++; + + // do right side + for ( j = 1; j < sideLen; j++ ) + ( *spiralArrayPtr )[ i + j ][ dimension - 1 - i ] = currNum++; + + // do bottom side + for ( j = sideLen - 2; j > -1; j-- ) + ( *spiralArrayPtr )[ dimension - 1 - i ][ i + j ] = currNum++; + + // do left side + for ( j = sideLen - 2; j > 0; j-- ) + ( *spiralArrayPtr )[ i + j ][ i ] = currNum++; + + sideLen -= 2; + } + + return spiralArrayPtr; +} + +void printSpiralArray( const auto_ptr< IntTable >& spiralArrayPtr ) +{ + size_t dimension = spiralArrayPtr->size(); + + int fieldWidth = static_cast< int >( floor( log10( + static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; + + size_t col; + for ( size_t row = 0; row < dimension; row++ ) + { + for ( col = 0; col < dimension; col++ ) + cout << setw( fieldWidth ) << ( *spiralArrayPtr )[ row ][ col ]; + cout << endl; + } +} + +int main() +{ + printSpiralArray( getSpiralArray( 5 ) ); +} diff --git a/Task/Spiral-matrix/C/spiral-matrix.c b/Task/Spiral-matrix/C/spiral-matrix.c new file mode 100644 index 0000000000..1763ef720d --- /dev/null +++ b/Task/Spiral-matrix/C/spiral-matrix.c @@ -0,0 +1,35 @@ +#include <stdio.h> +#include <stdlib.h> + +#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j] +int main(int c, char **v) +{ + int i, j, m = 0, n = 0; + + /* default size: 5 */ + if (c >= 2) m = atoi(v[1]); + if (c >= 3) n = atoi(v[2]); + if (m <= 0) m = 5; + if (n <= 0) n = m; + + int **s = calloc(1, sizeof(int *) * m + sizeof(int) * m * n); + s[0] = (int*)(s + m); + for (i = 1; i < m; i++) s[i] = s[i - 1] + n; + + int dx = 1, dy = 0, val = 0, t; + for (i = j = 0; valid(i, j); i += dy, j += dx ) { + for (; valid(i, j); j += dx, i += dy) + s[i][j] = ++val; + + j -= dx; i -= dy; + t = dy; dy = dx; dx = -t; + } + + for (t = 2; val /= 10; t++); + + for(i = 0; i < m; i++) + for(j = 0; j < n || !putchar('\n'); j++) + printf("%*d", t, s[i][j]); + + return 0; +} diff --git a/Task/Spiral-matrix/Clojure/spiral-matrix.clj b/Task/Spiral-matrix/Clojure/spiral-matrix.clj new file mode 100644 index 0000000000..f4dc7fb303 --- /dev/null +++ b/Task/Spiral-matrix/Clojure/spiral-matrix.clj @@ -0,0 +1,8 @@ +(defn spiral [n] + (let [fmt (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%") + counts (cons n (mapcat #(repeat 2 %) (range (dec n) 0 -1))) + ones-and-ns (mapcat #(repeat %1 %2) counts (cycle [1 n -1 (- n)]))] + (->> (map vector (range 0 (* n n)) (reductions + ones-and-ns)) + (sort-by second) + (map first) + (clojure.pprint/cl-format true fmt)))) diff --git a/Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffeescript b/Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffeescript new file mode 100644 index 0000000000..e8764641aa --- /dev/null +++ b/Task/Spiral-matrix/CoffeeScript/spiral-matrix-1.coffeescript @@ -0,0 +1,46 @@ +# Let's say you want to arrange the first N-squared natural numbers +# in a spiral, where you fill in the numbers clockwise, starting from +# the upper left corner. This code computes the values for each x/y +# coordinate of the square. (Of course, you could precompute the values +# iteratively, but what fun is that?) + +spiral_value = (x, y, n) -> + prior_legs = + N: 0 + E: 1 + S: 2 + W: 3 + + edge_run = (edge_offset) -> + N: -> edge_offset.W - edge_offset.N + E: -> edge_offset.N - edge_offset.E + S: -> edge_offset.E - edge_offset.S + W: -> edge_offset.S - edge_offset.W + + edge_offset = + N: y + E: n - 1 - x + S: n - 1 - y + W: x + + min_edge_offset = n + for dir of edge_offset + if edge_offset[dir] < min_edge_offset + min_edge_offset = edge_offset[dir] + border = dir + + inner_square_edge = n - 2 * min_edge_offset + corner_offset = n * n - inner_square_edge * inner_square_edge + corner_offset += prior_legs[border] * (inner_square_edge - 1) + corner_offset + edge_run(edge_offset)[border]() + +spiral_matrix = (n) -> + # return a nested array expression + for y in [0...n] + for x in [0...n] + spiral_value x, y, n + +do -> + for n in [6, 7] + console.log "\n----Spiral n=#{n}" + console.log spiral_matrix n diff --git a/Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffeescript b/Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffeescript new file mode 100644 index 0000000000..2fd11dff8b --- /dev/null +++ b/Task/Spiral-matrix/CoffeeScript/spiral-matrix-2.coffeescript @@ -0,0 +1,18 @@ +> coffee spiral.coffee + +----Spiral n=6 +[ [ 0, 1, 2, 3, 4, 5 ], + [ 19, 20, 21, 22, 23, 6 ], + [ 18, 31, 32, 33, 24, 7 ], + [ 17, 30, 35, 34, 25, 8 ], + [ 16, 29, 28, 27, 26, 9 ], + [ 15, 14, 13, 12, 11, 10 ] ] + +----Spiral n=7 +[ [ 0, 1, 2, 3, 4, 5, 6 ], + [ 23, 24, 25, 26, 27, 28, 7 ], + [ 22, 39, 40, 41, 42, 29, 8 ], + [ 21, 38, 47, 48, 43, 30, 9 ], + [ 20, 37, 46, 45, 44, 31, 10 ], + [ 19, 36, 35, 34, 33, 32, 11 ], + [ 18, 17, 16, 15, 14, 13, 12 ] ] diff --git a/Task/Spiral-matrix/Common-Lisp/spiral-matrix-1.lisp b/Task/Spiral-matrix/Common-Lisp/spiral-matrix-1.lisp new file mode 100644 index 0000000000..3a858a31cf --- /dev/null +++ b/Task/Spiral-matrix/Common-Lisp/spiral-matrix-1.lisp @@ -0,0 +1,18 @@ +(defun spiral (rows columns) + (do ((N (* rows columns)) + (spiral (make-array (list rows columns) :initial-element nil)) + (dx 1) (dy 0) (x 0) (y 0) + (i 0 (1+ i))) + ((= i N) spiral) + (setf (aref spiral y x) i) + (let ((nx (+ x dx)) (ny (+ y dy))) + (cond + ((and (< -1 nx columns) + (< -1 ny rows) + (null (aref spiral ny nx))) + (setf x nx + y ny)) + (t (psetf dx (- dy) + dy dx) + (setf x (+ x dx) + y (+ y dy))))))) diff --git a/Task/Spiral-matrix/Common-Lisp/spiral-matrix-2.lisp b/Task/Spiral-matrix/Common-Lisp/spiral-matrix-2.lisp new file mode 100644 index 0000000000..cc5eccc331 --- /dev/null +++ b/Task/Spiral-matrix/Common-Lisp/spiral-matrix-2.lisp @@ -0,0 +1,11 @@ +(defun spiral (m n &optional (start 1)) + (let ((row (list (loop for x from 0 to (1- m) collect (+ x start))))) + (if (= 1 n) row + ;; first row, plus (n-1) x m spiral rotated 90 degrees + (append row (map 'list #'reverse + (apply #'mapcar #'list + (spiral (1- n) m (+ start m)))))))) + +;; test +(loop for row in (spiral 4 3) do + (format t "~{~4d~^~}~%" row)) diff --git a/Task/Spiral-matrix/D/spiral-matrix-1.d b/Task/Spiral-matrix/D/spiral-matrix-1.d new file mode 100644 index 0000000000..c3313830f4 --- /dev/null +++ b/Task/Spiral-matrix/D/spiral-matrix-1.d @@ -0,0 +1,20 @@ +void main() { + import std.stdio; + enum n = 5; + int[n][n] M; + int pos, side = n; + + foreach (i; 0 .. (n / 2 + n % 2)) { + foreach (j; 0 .. side) + M[i][i + j] = pos++; + foreach (j; 1 .. side) + M[i + j][n - 1 - i] = pos++; + foreach_reverse (j; 0 .. side - 1) + M[n - 1 - i][i + j] = pos++; + foreach_reverse (j; 1 .. side - 1) + M[i + j][i] = pos++; + side -= 2; + } + + writefln("%(%(%2d %)\n%)", M); +} diff --git a/Task/Spiral-matrix/D/spiral-matrix-2.d b/Task/Spiral-matrix/D/spiral-matrix-2.d new file mode 100644 index 0000000000..eee548e001 --- /dev/null +++ b/Task/Spiral-matrix/D/spiral-matrix-2.d @@ -0,0 +1,52 @@ +import std.stdio; + +/// 2D spiral generator +const struct Spiral { + int w, h; + + int opApply(int delegate(ref int, ref int, ref int) dg) { + int idx, x, y, xy, dx = 1, dy; + int[] subLen = [w, h-1]; + + void turn() { + auto t = -dy; + dy = dx; + dx = t; + xy = 1 - xy; + } + + void forward(int d = 1) { + x += d * dx; + y += d * dy; + idx += d; + } + + Bye: + while (true) { + if (subLen[xy] == 0) + break; + foreach (_; 0 .. subLen[xy]--) + if (dg(idx, x, y)) + break Bye; + else + forward(); + forward(-1); + turn(); + forward(); + } + + return 0; + } +} + +int[][] spiralMatrix(int w, int h) { + auto m = new typeof(return)(h, w); + foreach (value, x, y; Spiral(w, h)) + m[y][x] = value; + return m; +} + +void main() { + foreach (r; spiralMatrix(9, 4)) + writefln("%(%2d %)", r); +} diff --git a/Task/Spiral-matrix/E/spiral-matrix-1.e b/Task/Spiral-matrix/E/spiral-matrix-1.e new file mode 100644 index 0000000000..1d79682bf2 --- /dev/null +++ b/Task/Spiral-matrix/E/spiral-matrix-1.e @@ -0,0 +1,25 @@ +def spiral(size) { + def array := makeFlex2DArray(size, size) + var i := -1 # Counter of numbers to fill + var p := makeVector2(0, 0) # "Position" + var dp := makeVector2(1, 0) # "Velocity" + + # If the cell we were to fill next (even after turning) is full, we're done. + while (array[p.y(), p.x()] == null) { + + array[p.y(), p.x()] := (i += 1) # Fill cell + def next := p + dp # Look forward + + # If the cell we were to fill next is already full, then turn clockwise. + # Gimmick: If we hit the edges of the array, by the modulo we wrap around + # and see the already-filled cell on the opposite edge. + if (array[next.y() %% size, next.x() %% size] != null) { + dp := dp.clockwise() + } + + # Move forward + p += dp + } + + return array +} diff --git a/Task/Spiral-matrix/E/spiral-matrix-2.e b/Task/Spiral-matrix/E/spiral-matrix-2.e new file mode 100644 index 0000000000..a008fe76f0 --- /dev/null +++ b/Task/Spiral-matrix/E/spiral-matrix-2.e @@ -0,0 +1,6 @@ +? print(spiral(5)) + 0 1 2 3 4 +15 16 17 18 5 +14 23 24 19 6 +13 22 21 20 7 +12 11 10 9 8 diff --git a/Task/Spiral-matrix/Euphoria/spiral-matrix.euphoria b/Task/Spiral-matrix/Euphoria/spiral-matrix.euphoria new file mode 100644 index 0000000000..9a9bf115cc --- /dev/null +++ b/Task/Spiral-matrix/Euphoria/spiral-matrix.euphoria @@ -0,0 +1,29 @@ +function spiral(integer dimension) + integer side, curr, curr2 + sequence s + s = repeat(repeat(0,dimension),dimension) + side = dimension + curr = 0 + for i = 0 to floor(dimension/2) do + for j = 1 to side-1 do + s[i+1][i+j] = curr -- top + curr2 = curr + side-1 + s[i+j][i+side] = curr2 -- right + curr2 += side-1 + s[i+side][i+side-j+1] = curr2 -- bottom + curr2 += side-1 + s[i+side-j+1][i+1] = curr2 -- left + curr += 1 + end for + curr = curr2 + 1 + side -= 2 + end for + + if remainder(dimension,2) then + s[floor(dimension/2)+1][floor(dimension/2)+1] = curr + end if + + return s +end function + +? spiral(5) diff --git a/Task/Spiral-matrix/Fortran/spiral-matrix.f b/Task/Spiral-matrix/Fortran/spiral-matrix.f new file mode 100644 index 0000000000..ffa1d09465 --- /dev/null +++ b/Task/Spiral-matrix/Fortran/spiral-matrix.f @@ -0,0 +1,49 @@ +PROGRAM SPIRAL + + IMPLICIT NONE + + INTEGER, PARAMETER :: size = 5 + INTEGER :: i, x = 0, y = 1, count = size, n = 0 + INTEGER :: array(size,size) + + DO i = 1, count + x = x + 1 + array(x,y) = n + n = n + 1 + END DO + + DO + count = count - 1 + DO i = 1, count + y = y + 1 + array(x,y) = n + n = n + 1 + END DO + DO i = 1, count + x = x - 1 + array(x,y) = n + n = n + 1 + END DO + IF (n > size*size-1) EXIT + count = count - 1 + DO i = 1, count + y = y - 1 + array(x,y) = n + n = n + 1 + END DO + DO i = 1, count + x = x + 1 + array(x,y) = n + n = n + 1 + END DO + IF (n > size*size-1) EXIT + END DO + + DO y = 1, size + DO x = 1, size + WRITE (*, "(I4)", ADVANCE="NO") array (x, y) + END DO + WRITE (*,*) + END DO + +END PROGRAM SPIRAL diff --git a/Task/Spiral-matrix/GAP/spiral-matrix.gap b/Task/Spiral-matrix/GAP/spiral-matrix.gap new file mode 100644 index 0000000000..279eb660a9 --- /dev/null +++ b/Task/Spiral-matrix/GAP/spiral-matrix.gap @@ -0,0 +1,47 @@ +# Spiral matrix with numbers 1 .. n<sup>2</sup>, more natural in GAP +SpiralMatrix := function(n) + local i, j, k, di, dj, p, vi, vj, imin, imax, jmin, jmax; + a := NullMat(n, n); + vi := [ 1, 0, -1, 0 ]; + vj := [ 0, 1, 0, -1 ]; + imin := 0; + imax := n; + jmin := 1; + jmax := n + 1; + p := 1; + di := vi[p]; + dj := vj[p]; + i := 1; + j := 1; + for k in [1 .. n*n] do + a[j][i] := k; + i := i + di; + j := j + dj; + if i < imin or i > imax or j < jmin or j > jmax then + i := i - di; + j := j - dj; + p := RemInt(p, 4) + 1; + di := vi[p]; + dj := vj[p]; + i := i + di; + j := j + dj; + if p = 1 then + imax := imax - 1; + elif p = 2 then + jmax := jmax - 1; + elif p = 3 then + imin := imin + 1; + else + jmin := jmin + 1; + fi; + fi; + od; + return a; +end; + +PrintArray(SpiralMatrix(5)); +# [ [ 1, 2, 3, 4, 5 ], +# [ 16, 17, 18, 19, 6 ], +# [ 15, 24, 25, 20, 7 ], +# [ 14, 23, 22, 21, 8 ], +# [ 13, 12, 11, 10, 9 ] ] diff --git a/Task/Spiral-matrix/Go/spiral-matrix.go b/Task/Spiral-matrix/Go/spiral-matrix.go new file mode 100644 index 0000000000..cf16af59ca --- /dev/null +++ b/Task/Spiral-matrix/Go/spiral-matrix.go @@ -0,0 +1,58 @@ +package main + +import ( + "fmt" + "strconv" +) + +var n = 5 + +func main() { + if n < 1 { + return + } + top, left, bottom, right := 0, 0, n-1, n-1 + sz := n * n + a := make([]int, sz) + i := 0 + for left < right { + // work right, along top + for c := left; c <= right; c++ { + a[top*n+c] = i + i++ + } + top++ + // work down right side + for r := top; r <= bottom; r++ { + a[r*n+right] = i + i++ + } + right-- + if top == bottom { + break + } + // work left, along bottom + for c := right; c >= left; c-- { + a[bottom*n+c] = i + i++ + } + bottom-- + // work up left side + for r := bottom; r >= top; r-- { + a[r*n+left] = i + i++ + } + left++ + } + // center (last) element + a[top*n+left] = i + + // print + w := len(strconv.Itoa(n*n - 1)) + for i, e := range a { + fmt.Printf("%*d ", w, e) + if i%n == n-1 { + fmt.Println("") + } + } +} diff --git a/Task/Spiral-matrix/Groovy/spiral-matrix-1.groovy b/Task/Spiral-matrix/Groovy/spiral-matrix-1.groovy new file mode 100644 index 0000000000..edf01f4ae1 --- /dev/null +++ b/Task/Spiral-matrix/Groovy/spiral-matrix-1.groovy @@ -0,0 +1,54 @@ +enum Direction { + East([0,1]), South([1,0]), West([0,-1]), North([-1,0]); + private static _n + private final stepDelta + private bound + + private Direction(delta) { + stepDelta = delta + } + + public static setN(int n) { + Direction._n = n + North.bound = 0 + South.bound = n-1 + West.bound = 0 + East.bound = n-1 + } + + public List move(i, j) { + def dir = this + def newIJDir = [[i,j],stepDelta].transpose().collect { it.sum() } + dir + if (((North.bound)..(South.bound)).contains(newIJDir[0]) + && ((West.bound)..(East.bound)).contains(newIJDir[1])) { + newIJDir + } else { + (++dir).move(i, j) + } + } + + public Object next() { + switch (this) { + case North: West.bound++; return East; + case East: North.bound++; return South; + case South: East.bound--; return West; + case West: South.bound--; return North; + } + } +} + +def spiralMatrix = { n -> + if (n < 1) return [] + def M = (0..<n).collect { [0]*n } + def i = 0 + def j = 0 + Direction.n = n + def dir = Direction.East + (0..<(n**2)).each { k -> + M[i][j] = k + (i,j,dir) = (k < (n**2 - 1)) \ + ? dir.move(i,j) \ + : [i,j,dir] + } + M +} diff --git a/Task/Spiral-matrix/Groovy/spiral-matrix-2.groovy b/Task/Spiral-matrix/Groovy/spiral-matrix-2.groovy new file mode 100644 index 0000000000..c5aa251e70 --- /dev/null +++ b/Task/Spiral-matrix/Groovy/spiral-matrix-2.groovy @@ -0,0 +1,7 @@ +(1..10).each { n -> + spiralMatrix(n).each { row -> + row.each { printf "%5d", it } + println() + } + println () +} diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix.hs b/Task/Spiral-matrix/Haskell/spiral-matrix.hs new file mode 100644 index 0000000000..a2c752b8bb --- /dev/null +++ b/Task/Spiral-matrix/Haskell/spiral-matrix.hs @@ -0,0 +1,12 @@ +module Spiral where + +import Data.List +import Control.Monad +import Control.Monad.Instances + +grade xs = map snd. sort $ zip xs [0..] +values n = cycle [1,n,-1,-n] +counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1] +reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs)) + +spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n) diff --git a/Task/Spiral-matrix/Icon/spiral-matrix.icon b/Task/Spiral-matrix/Icon/spiral-matrix.icon new file mode 100644 index 0000000000..1074a1d1f7 --- /dev/null +++ b/Task/Spiral-matrix/Icon/spiral-matrix.icon @@ -0,0 +1,28 @@ +procedure main(A) # spiral matrix +N := 0 < integer(\A[1]|5) # N=1... (dfeault 5) +WriteMatrix(SpiralMatrix(N)) +end + +procedure WriteMatrix(M) #: write the matrix +every x := M[r := 1 to *M, c := 1 to *M[r]] do + writes(right(\x|"-", 3), if c = *M[r] then "\n" else "") +return +end + +procedure SpiralMatrix(N) #: create spiral matrix +every (!(M := list(N))):= list(N) # build empty matrix NxN + # setup before starting first turn +corner := 0 # . corner we're at +i := -1 # . cell contents +r:= 1 ; c :=0 # . row & col +cincr := integer(sin(0)) # . column incr + +until i > N^2 do { + rincr := cincr # row incr follows col + cincr := integer(sin(&pi/2*(corner+:=1))) # col incr at each corner + if (run := N-corner/2) = 0 then break # shorten run to 0 at U/R & L/L + every run to 1 by -1 do + M[r +:= rincr,c +:= cincr] := i +:= 1 # move, count, and fill + } +return M +end diff --git a/Task/Spiral-matrix/J/spiral-matrix.j b/Task/Spiral-matrix/J/spiral-matrix.j new file mode 100644 index 0000000000..1c13caeecf --- /dev/null +++ b/Task/Spiral-matrix/J/spiral-matrix.j @@ -0,0 +1,8 @@ +spiral =. ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,) + + spiral 5 + 0 1 2 3 4 +15 16 17 18 5 +14 23 24 19 6 +13 22 21 20 7 +12 11 10 9 8 diff --git a/Task/Spiral-matrix/Java/spiral-matrix.java b/Task/Spiral-matrix/Java/spiral-matrix.java new file mode 100644 index 0000000000..5a265bb8d7 --- /dev/null +++ b/Task/Spiral-matrix/Java/spiral-matrix.java @@ -0,0 +1,51 @@ +public class Blah { + + public static void main(String[] args) { + print2dArray(getSpiralArray(5)); + } + + public static int[][] getSpiralArray(int dimension) { + int[][] spiralArray = new int[dimension][dimension]; + + int numConcentricSquares = (int) Math.ceil((dimension) / 2.0); + + int j; + int sideLen = dimension; + int currNum = 0; + + for (int i = 0; i < numConcentricSquares; i++) { + // do top side + for (j = 0; j < sideLen; j++) { + spiralArray[i][i + j] = currNum++; + } + + // do right side + for (j = 1; j < sideLen; j++) { + spiralArray[i + j][dimension - 1 - i] = currNum++; + } + + // do bottom side + for (j = sideLen - 2; j > -1; j--) { + spiralArray[dimension - 1 - i][i + j] = currNum++; + } + + // do left side + for (j = sideLen - 2; j > 0; j--) { + spiralArray[i + j][i] = currNum++; + } + + sideLen -= 2; + } + + return spiralArray; + } + + public static void print2dArray(int[][] array) { + for (int[] row : array) { + for (int elem : row) { + System.out.printf("%3d", elem); + } + System.out.println(); + } + } +} diff --git a/Task/Spiral-matrix/JavaScript/spiral-matrix.js b/Task/Spiral-matrix/JavaScript/spiral-matrix.js new file mode 100644 index 0000000000..a51b23cad8 --- /dev/null +++ b/Task/Spiral-matrix/JavaScript/spiral-matrix.js @@ -0,0 +1,21 @@ +spiralArray = function (edge) { + var arr = Array(edge), + x = 0, y = edge, + total = edge * edge--, + dx = 1, dy = 0, + i = 0, j = 0; + while (y) arr[--y] = []; + while (i < total) { + arr[y][x] = i++; + x += dx; y += dy; + if (++j == edge) { + if (dy < 0) {x++; y++; edge -= 2} + j = dx; dx = -dy; dy = j; j = 0; + } + } + return arr; +} + +// T E S T: +arr = spiralArray(edge = 5); +for (y= 0; y < edge; y++) console.log(arr[y].join(" ")); diff --git a/Task/Spiral-matrix/Liberty-BASIC/spiral-matrix.liberty b/Task/Spiral-matrix/Liberty-BASIC/spiral-matrix.liberty new file mode 100644 index 0000000000..5e9bb89837 --- /dev/null +++ b/Task/Spiral-matrix/Liberty-BASIC/spiral-matrix.liberty @@ -0,0 +1,76 @@ +nomainwin + +UpperLeftX = 50 +UpperLeftY = 50 +WindowWidth =900 +WindowHeight =930 + +statictext #w.st, "", 10, 850, 870, 40 + +open "Spiral matrix" for graphics_nsb_nf as #w + +#w "trapclose [quit]" +#w "backcolor darkblue; color cyan; fill darkblue" + +for N =2 to 50 + + #w.st "!font courier_new "; int( 60 /N); " bold" + #w "down; font arial "; int( 240 /N); " bold" + + g$ ="ruld" ' direction sequence + if N/2 =int( N/2) then pg =2 else pg =0 ' pointer to current direction + ' last move is left or right depending on N even/odd + d$ ="" + + for i =1 to N -1 ' calculate direction to move + d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$ + pg =( pg +1) mod 4 + d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$ + pg =( pg +1) mod 4 + next i + + d$ =nChar$( N -1, "r") +d$ ' first row + + #w.st " N ="; N; " "; d$ + + xp =60 +250 /N + yp =80 +250 /N + + stp =int( 750 /N) + + for i =0 to N^2 -1 + dir$ =mid$( d$, i, 1) + select case dir$ + case "r" + xp =xp +stp + case "d" + yp =yp +stp + case "l" + xp =xp -stp + case "u" + yp =yp -stp + end select + + #w "place "; xp; " "; yp + #w "\"; i + next i + + timer 3000, [on] + wait + [on] + timer 0 + #w "cls" + scan +next N + +wait + +function nChar$( n, i$) + for i =1 to n + nChar$ =nChar$ +i$ + next i +end function + +[quit] +close #w +end diff --git a/Task/Spiral-matrix/Lua/spiral-matrix.lua b/Task/Spiral-matrix/Lua/spiral-matrix.lua new file mode 100644 index 0000000000..a5caa44d42 --- /dev/null +++ b/Task/Spiral-matrix/Lua/spiral-matrix.lua @@ -0,0 +1,19 @@ +av, sn = math.abs, function(s) return s~=0 and s/av(s) or 0 end +function sindex(y, x) -- returns the value at (x, y) in a spiral that starts at 1 and goes outwards + if y == -x and y >= x then return (2*y+1)^2 end + local l = math.max(av(y), av(x)) + return (2*l-1)^2+4*l+2*l*sn(x+y)+sn(y^2-x^2)*(l-(av(y)==l and sn(y)*x or sn(x)*y)) -- OH GOD WHAT +end + +function spiralt(side) + local ret, start, stop = {}, math.floor((-side+1)/2), math.floor((side-1)/2) + for i = 1, side do + ret[i] = {} + for j = 1, side do + ret[i][j] = side^2 - sindex(stop - i + 1,start + j - 1) --moves the coordinates so (0,0) is at the center of the spiral + end + end + return ret +end + +for i,v in ipairs(spiralt(8)) do for j, u in ipairs(v) do io.write(u .. " ") end print() end diff --git a/Task/Spiral-matrix/MATLAB/spiral-matrix-1.m b/Task/Spiral-matrix/MATLAB/spiral-matrix-1.m new file mode 100644 index 0000000000..265946a7b8 --- /dev/null +++ b/Task/Spiral-matrix/MATLAB/spiral-matrix-1.m @@ -0,0 +1,11 @@ +function matrix = reverseSpiral(n) + + matrix = (-spiral(n))+n^2; + + if mod(n,2)==0 + matrix = flipud(matrix); + else + matrix = fliplr(matrix); + end + +end %reverseSpiral diff --git a/Task/Spiral-matrix/MATLAB/spiral-matrix-2.m b/Task/Spiral-matrix/MATLAB/spiral-matrix-2.m new file mode 100644 index 0000000000..23740e7a8d --- /dev/null +++ b/Task/Spiral-matrix/MATLAB/spiral-matrix-2.m @@ -0,0 +1,9 @@ +>> reverseSpiral(5) + +ans = + + 0 1 2 3 4 + 15 16 17 18 5 + 14 23 24 19 6 + 13 22 21 20 7 + 12 11 10 9 8 diff --git a/Task/Spiral-matrix/Mathematica/spiral-matrix-1.math b/Task/Spiral-matrix/Mathematica/spiral-matrix-1.math new file mode 100644 index 0000000000..5dd82704b0 --- /dev/null +++ b/Task/Spiral-matrix/Mathematica/spiral-matrix-1.math @@ -0,0 +1,16 @@ +AddSquareRing[x_List/;Equal@@Dimensions[x] && Length[Dimensions[x]]==2]:=Module[{new=x,size,smallest}, + size=Length[x]; + smallest=x[[1,1]]; + Do[ + new[[i]]=Prepend[new[[i]],smallest-i]; + new[[i]]=Append[new[[i]],smallest-3 size+i-3] + ,{i,size}]; + PrependTo[new,Range[smallest-3size-3-size-1,smallest-3size-3]]; + AppendTo[new,Range[smallest-size-1,smallest-size-size-2,-1]]; + new +] +MakeSquareSpiral[size_Integer/;size>0]:=Module[{largest,start,times}, + start=size^2+If[Mod[size,2]==0,{{-4,-3},{-1,-2}},{{-1}}]; + times=If[Mod[size,2]==0,size/2-1,(size-1)/2]; + Nest[AddSquareRing,start,times] +] diff --git a/Task/Spiral-matrix/Mathematica/spiral-matrix-2.math b/Task/Spiral-matrix/Mathematica/spiral-matrix-2.math new file mode 100644 index 0000000000..b8a07000f7 --- /dev/null +++ b/Task/Spiral-matrix/Mathematica/spiral-matrix-2.math @@ -0,0 +1,2 @@ +MakeSquareSpiral[2] // MatrixForm +MakeSquareSpiral[7] // MatrixForm diff --git a/Task/Spiral-matrix/Maxima/spiral-matrix.maxima b/Task/Spiral-matrix/Maxima/spiral-matrix.maxima new file mode 100644 index 0000000000..0ba2a05406 --- /dev/null +++ b/Task/Spiral-matrix/Maxima/spiral-matrix.maxima @@ -0,0 +1,40 @@ +spiral(n) := block([a, i, j, k, p, di, dj, vi, vj, imin, imax, jmin, jmax], +a: zeromatrix(n, n), +vi: [1, 0, -1, 0], +vj: [0, 1, 0, -1], +imin: 0, +imax: n, +jmin: 1, +jmax: n + 1, +p: 1, +di: vi[p], +dj: vj[p], +i: 1, +j: 1, +for k from 1 thru n*n do ( + a[j, i]: k, + i: i + di, + j: j + dj, + if i < imin or i > imax or j < jmin or j > jmax then ( + i: i - di, + j: j - dj, + p: mod(p, 4) + 1, + di: vi[p], + dj: vj[p], + i: i + di, + j: j + dj, + if p = 1 then imax: imax - 1 + elseif p = 2 then jmax: jmax - 1 + elseif p = 3 then imin: imin + 1 + else jmin: jmin + 1 + ) +), +a +)$ + +spiral(5); +/* matrix([ 1, 2, 3, 4, 5], + [16, 17, 18, 19, 6], + [15, 24, 25, 20, 7], + [14, 23, 22, 21, 8], + [13, 12, 11, 10, 9]) */ diff --git a/Task/Spiral-matrix/NetRexx/spiral-matrix.netrexx b/Task/Spiral-matrix/NetRexx/spiral-matrix.netrexx new file mode 100644 index 0000000000..ce76811587 --- /dev/null +++ b/Task/Spiral-matrix/NetRexx/spiral-matrix.netrexx @@ -0,0 +1,91 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +parse arg size . + +if \size.datatype('W') then do + printArray(generateArray(3)) + say + printArray(generateArray(4)) + say + printArray(generateArray(5)) + say + end +else do + printArray(generateArray(size)) + say + end + +return + +-- ----------------------------------------------------------------------------- +method generateArray(dimension = int) private static returns int[,] + + -- the output array + array = int[dimension, dimension] + + -- get the number of squares, including the center one if + -- the dimension is odd + + squares = dimension % 2 + dimension // 2 + + -- length of a side for the current square + sidelength = dimension + current = 0 + + loop i_ = 0 to squares - 1 + + -- do each side of the current square + -- top side + loop j_ = 0 to sidelength - 1 + array[i_, i_ + j_] = current + current = current + 1 + end j_ + + -- down the right side + loop j_ = 1 to sidelength - 1 + array[i_ + j_, dimension - 1 - i_] = current + current = current + 1 + end j_ + + -- across the bottom + loop j_ = sidelength - 2 to 0 by -1 + array[dimension - 1 - i_, i_ + j_] = current + current = current + 1 + end j_ + + -- and up the left side + loop j_ = sidelength - 2 to 1 by -1 + array[i_ + j_, i_] = current + current = current + 1 + end j_ + + -- reduce the length of the side by two rows + sidelength = sidelength - 2 + end i_ + + return array + +-- ----------------------------------------------------------------------------- +method printArray(array = int[,]) private static + + dimension = array[1].length + rl = formatSize(array) + loop i_ = 0 to dimension - 1 + line = Rexx("|") + loop j_ = 0 to dimension - 1 + line = line Rexx(array[i_, j_]).right(rl) + end j_ + line = line "|" + say line + end i_ + + return + +-- ----------------------------------------------------------------------------- +method formatSize(array = int[,]) private static returns Rexx + + dim = array[1].length + maxNum = Rexx(dim * dim - 1).length() + + return maxNum diff --git a/Task/Spiral-matrix/OCaml/spiral-matrix-1.ocaml b/Task/Spiral-matrix/OCaml/spiral-matrix-1.ocaml new file mode 100644 index 0000000000..b357e237b0 --- /dev/null +++ b/Task/Spiral-matrix/OCaml/spiral-matrix-1.ocaml @@ -0,0 +1,39 @@ +let next_dir = function + | 1, 0 -> 0, -1 + | 0, 1 -> 1, 0 + | -1, 0 -> 0, 1 + | 0, -1 -> -1, 0 + | _ -> assert false + +let next_pos ~pos:(x,y) ~dir:(nx,ny) = (x+nx, y+ny) + +let next_cell ar ~pos:(x,y) ~dir:(nx,ny) = + try ar.(x+nx).(y+ny) + with _ -> -2 + +let for_loop n init fn = + let rec aux i v = + if i < n then aux (i+1) (fn i v) + in + aux 0 init + +let spiral ~n = + let ar = Array.make_matrix n n (-1) in + let pos = 0, 0 in + let dir = 0, 1 in + let set (x, y) i = ar.(x).(y) <- i in + let step (pos, dir) = + match next_cell ar pos dir with + | -1 -> (next_pos pos dir, dir) + | _ -> let dir = next_dir dir in (next_pos pos dir, dir) + in + for_loop (n*n) (pos, dir) + (fun i (pos, dir) -> set pos i; step (pos, dir)); + (ar) + +let print = + Array.iter (fun line -> + Array.iter (Printf.printf " %2d") line; + print_newline()) + +let () = print(spiral 5) diff --git a/Task/Spiral-matrix/OCaml/spiral-matrix-2.ocaml b/Task/Spiral-matrix/OCaml/spiral-matrix-2.ocaml new file mode 100644 index 0000000000..fbb57c8040 --- /dev/null +++ b/Task/Spiral-matrix/OCaml/spiral-matrix-2.ocaml @@ -0,0 +1,17 @@ +let spiral n = + let ar = Array.make_matrix n n (-1) in + let out i = i < 0 || i >= n in + let too_far (x,y) = out x || out y || ar.(x).(y) >= 0 in + let step x y (dx,dy) = (x+dx,y+dy) in + let turn (i,j) = (j,-i) in + let rec iter (x,y) d i = + ar.(x).(y) <- i; + if i < n*n-1 then + let d' = if too_far (step x y d) then turn d else d in + iter (step x y d') d' (i+1) in + (iter (0,0) (0,1) 0; ar) + +let show = + Array.iter (fun v -> Array.iter (Printf.printf " %2d") v; print_newline()) + +let _ = show (spiral 5) diff --git a/Task/Spiral-matrix/Octave/spiral-matrix.octave b/Task/Spiral-matrix/Octave/spiral-matrix.octave new file mode 100644 index 0000000000..9cc86877b0 --- /dev/null +++ b/Task/Spiral-matrix/Octave/spiral-matrix.octave @@ -0,0 +1,27 @@ +function rs = runsum(v) + for i = 1:numel(v) + rs(i) = sum(v(1:i)); + endfor +endfunction + +function g = grade(v) + for i = 1:numel(v) + g(v(i)+1) = i-1; + endfor +endfunction + +function spiral = make_spiral(spirald) + series = ones(1,spirald^2); + l = spirald-1; p = spirald+1; + s = 1; + while(l>0) + series(p:p+l-1) *= spirald*s; + series(p+l:p+l*2-1) *= -s; + p += l*2; + l--; s *= -1; + endwhile + series(1) = 0; + spiral = reshape(grade(runsum(series)), spirald, spirald)'; +endfunction + +make_spiral(5) diff --git a/Task/Spiral-matrix/Oz/spiral-matrix.oz b/Task/Spiral-matrix/Oz/spiral-matrix.oz new file mode 100644 index 0000000000..8eefd84154 --- /dev/null +++ b/Task/Spiral-matrix/Oz/spiral-matrix.oz @@ -0,0 +1,42 @@ +declare + fun {Spiral N} + %% create nested array + Arr = {Array.new 1 N unit} + for Y in 1..N do Arr.Y := {Array.new 1 N 0} end + %% fill it recursively with increasing numbers + C = {Counter 0} + in + {Fill Arr 1 N C} + Arr + end + + proc {Fill Arr S E C} + %% go right + for X in S..E do + Arr.S.X := {C} + end + %% go down + for Y in S+1..E do + Arr.Y.E := {C} + end + %% go left + for X in E-1..S;~1 do + Arr.E.X := {C} + end + %% go up + for Y in E-1..S+1;~1 do + Arr.Y.S := {C} + end + %% fill the inner rectangle + if E - S > 1 then {Fill Arr S+1 E-1 C} end + end + + fun {Counter N} + C = {NewCell N} + in + fun {$} + C := @C + 1 + end + end +in + {Inspect {Spiral 5}} diff --git a/Task/Spiral-matrix/PL-I/spiral-matrix.pli b/Task/Spiral-matrix/PL-I/spiral-matrix.pli new file mode 100644 index 0000000000..52117efe71 --- /dev/null +++ b/Task/Spiral-matrix/PL-I/spiral-matrix.pli @@ -0,0 +1,55 @@ +/* Generates a square matrix containing the integers from 0 to N**2-1, */ +/* where N is the length of one side of the square. */ +/* Written 22 February 2010. */ + declare n fixed binary; + +put skip list ('Please type the size of the square:'); +get list (n); + +begin; + declare A(n,n) fixed binary; + declare (i, j, iinc, jinc, q) fixed binary; + + A = -1; + + i, j = 1; iinc = 0; jinc = 1; + do q = 0 to n**2-1; + if a(i,j) < 0 then + a(i,j) = q; + else + do; + /* back up */ + j = j -jinc; i = i - iinc; + /* change direction */ + if iinc = 0 & jinc = 1 then do; iinc = 1; jinc = 0; end; + else if iinc = 1 & jinc = 0 then do; iinc = 0; jinc = -1; end; + else if iinc = 0 & jinc = -1 then do; iinc = -1; jinc = 0; end; + else if iinc = -1 & jinc = 0 then do; iinc = 0; jinc = 1; end; + /* Take one step in the new direction */ + i = i + iinc; j = j + jinc; + a(i,j) = q; + end; + if i+iinc > n | i+iinc < 1 then + do; + iinc = 0; jinc = 1; + if j+1 > n then jinc = -1; else if j-1 < 1 then jinc = 1; + if a(i+iinc,j+jinc) >= 0 then jinc = -jinc; + /* j = j + jinc; /* to move on from the present (filled) position */ + end; + else i = i + iinc; + if j+jinc > n | j+jinc < 1 then + do; + jinc = 0; iinc = 1; + if i+1 > n then iinc = -1; else if i-1 < 1 then iinc = 1; + if a(i+iinc,j+jinc) >= 0 then iinc = -iinc; + i = i + iinc; /* to move on from the present (filled) position */ + end; + else j = j + jinc; + end; + + /* Display the square. */ + do i = 1 to n; + put skip edit (A(i,*)) (F(4)); + end; + +end; diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 new file mode 100644 index 0000000000..21220b6829 --- /dev/null +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 @@ -0,0 +1,47 @@ +enum Dir < north northeast east southeast south southwest west northwest >; +my $debug = 0; + +class Turtle { + has @.loc = 0,0; + has Dir $.dir = north; + + my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; + my @num-to-dir = Dir.invert.sort».value; + my $points = +Dir; + + my %world; + my $maxegg; + my $range-x; + my $range-y; + + method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; } + method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; } + + method lay-egg($egg) { + %world{~@!loc} = $egg; + $maxegg max= $egg; + $range-x minmax= @!loc[0]; + $range-y minmax= @!loc[1]; + } + + method look($ahead = 1) { + my $there = @!loc »+« (@dv[$!dir] X* $ahead); + say "looking @num-to-dir[$!dir] to $there" if $debug; + %world{~$there}; + } + + method forward($ahead = 1) { + my $there = @!loc »+« (@dv[$!dir] X* $ahead); + @!loc = @($there); + say " moving @num-to-dir[$!dir] to @!loc[]" if $debug; + } + + method showmap() { + my $form = "%{$maxegg.chars}s"; + my $endx = $range-x.max; + for $range-y.list X $range-x.list -> $y, $x { + print (%world{"$x $y"} // '').fmt($form); + print $x == $endx ?? "\n" !! ' '; + } + } +} diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 new file mode 100644 index 0000000000..8d331f59dd --- /dev/null +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 @@ -0,0 +1,16 @@ +sub MAIN($size as Int) { + my $t = Turtle.new(dir => east); + my $counter = 0; + $t.forward(-1); + for 0..^ $size -> $ { + $t.forward; + $t.lay-egg($counter++); + } + for $size-1 ... 1 -> $run { + $t.turn-right; + $t.forward, $t.lay-egg($counter++) for 0..^$run; + $t.turn-right; + $t.forward, $t.lay-egg($counter++) for 0..^$run; + } + $t.showmap; +} diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 new file mode 100644 index 0000000000..5d5f42f80e --- /dev/null +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 @@ -0,0 +1,11 @@ +sub MAIN($size as Int) { + my $t = Turtle.new(dir => ($size %% 2 ?? south !! north)); + my $counter = $size * $size; + while $counter { + $t.lay-egg(--$counter); + $t.turn-left; + $t.turn-right if $t.look; + $t.forward; + } + $t.showmap; +} diff --git a/Task/Spiral-matrix/Perl-6/spiral-matrix-4.pl6 b/Task/Spiral-matrix/Perl-6/spiral-matrix-4.pl6 new file mode 100644 index 0000000000..e06e6573ee --- /dev/null +++ b/Task/Spiral-matrix/Perl-6/spiral-matrix-4.pl6 @@ -0,0 +1,19 @@ +sub spiral_matrix ( $n ) { + my @sm; + my $len = $n; + my $pos = 0; + + for ^($n/2).ceiling -> $i { + my $j = $i + 1; + my $e = $n - $j; + + @sm[$i ][$i + $_] = $pos++ for ^( $len); # Top + @sm[$j + $_][$e ] = $pos++ for ^(--$len); # Right + @sm[$e ][$i + $_] = $pos++ for reverse ^( $len); # Bottom + @sm[$j + $_][$i ] = $pos++ for reverse ^(--$len); # Left + } + + return @sm; +} + +say .fmt('%3d') for spiral_matrix(5); diff --git a/Task/Spiral-matrix/Perl/spiral-matrix.pl b/Task/Spiral-matrix/Perl/spiral-matrix.pl new file mode 100644 index 0000000000..b237b91296 --- /dev/null +++ b/Task/Spiral-matrix/Perl/spiral-matrix.pl @@ -0,0 +1,21 @@ +sub spiral + {my ($n, $x, $y, $dx, $dy, @a) = (shift, 0, 0, 1, 0); + foreach (0 .. $n**2 - 1) + {$a[$y][$x] = $_; + my ($nx, $ny) = ($x + $dx, $y + $dy); + ($dx, $dy) = + $dx == 1 && ($nx == $n || defined $a[$ny][$nx]) + ? ( 0, 1) + : $dy == 1 && ($ny == $n || defined $a[$ny][$nx]) + ? (-1, 0) + : $dx == -1 && ($nx < 0 || defined $a[$ny][$nx]) + ? ( 0, -1) + : $dy == -1 && ($ny < 0 || defined $a[$ny][$nx]) + ? ( 1, 0) + : ($dx, $dy); + ($x, $y) = ($x + $dx, $y + $dy);} + return @a;} + +foreach (spiral 5) + {printf "%3d", $_ foreach @$_; + print "\n";} diff --git a/Task/Spiral-matrix/PicoLisp/spiral-matrix.l b/Task/Spiral-matrix/PicoLisp/spiral-matrix.l new file mode 100644 index 0000000000..bfc3f4291b --- /dev/null +++ b/Task/Spiral-matrix/PicoLisp/spiral-matrix.l @@ -0,0 +1,19 @@ +(load "@lib/simul.l") + +(de spiral (N) + (prog1 (grid N N) + (let (Dir '(north east south west .) This 'a1) + (for Val (* N N) + (=: val Val) + (setq This + (or + (with ((car Dir) This) + (unless (: val) This) ) + (with ((car (setq Dir (cdr Dir))) This) + (unless (: val) This) ) ) ) ) ) ) ) + +(mapc + '((L) + (for This L (prin (align 3 (: val)))) + (prinl) ) + (spiral 5) ) diff --git a/Task/Spiral-matrix/PureBasic/spiral-matrix.purebasic b/Task/Spiral-matrix/PureBasic/spiral-matrix.purebasic new file mode 100644 index 0000000000..a47ef19a34 --- /dev/null +++ b/Task/Spiral-matrix/PureBasic/spiral-matrix.purebasic @@ -0,0 +1,57 @@ +Procedure spiralMatrix(size = 1) + Protected i, x = -1, y, count = size, n + Dim a(size - 1,size - 1) + + For i = 1 To count + x + 1 + a(x,y) = n + n + 1 + Next + + Repeat + count - 1 + For i = 1 To count + y + 1 + a(x,y) = n + n + 1 + Next + For i = 1 To count + x - 1 + a(x,y) = n + n + 1 + Next + + count - 1 + For i = 1 To count + y - 1 + a(x,y) = n + n + 1 + Next + For i = 1 To count + x + 1 + a(x,y) = n + n + 1 + Next + Until count < 1 + + PrintN("Spiral: " + Str(Size) + #CRLF$) + Protected colWidth = Len(Str(size * size - 1)) + 1 + For y = 0 To size - 1 + For x = 0 To size - 1 + Print("" + LSet(Str(a(x, y)), colWidth, " ") + "") + Next + PrintN("") + Next + PrintN("") +EndProcedure + +If OpenConsole() + spiralMatrix(2) + PrintN("") + spiralMatrix(5) + + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Spiral-matrix/Python/spiral-matrix-1.py b/Task/Spiral-matrix/Python/spiral-matrix-1.py new file mode 100644 index 0000000000..46ff3b8e69 --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-1.py @@ -0,0 +1,22 @@ +def spiral(n): + dx,dy = 1,0 # Starting increments + x,y = 0,0 # Starting location + myarray = [[None]* n for j in range(n)] + for i in xrange(n**2): + myarray[x][y] = i + nx,ny = x+dx, y+dy + if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None: + x,y = nx,ny + else: + dx,dy = -dy,dx + x,y = x+dx, y+dy + return myarray + +def printspiral(myarray): + n = range(len(myarray)) + for y in n: + for x in n: + print "%2i" % myarray[x][y], + print + +printspiral(spiral(5)) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-2.py b/Task/Spiral-matrix/Python/spiral-matrix-2.py new file mode 100644 index 0000000000..6424f1ca4c --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-2.py @@ -0,0 +1,23 @@ +def spiral(n): + def spiral_part(x, y, n): + if x == -1 and y == 0: + return -1 + if y == (x+1) and x < (n // 2): + return spiral_part(x-1, y-1, n-1) + 4*(n-y) + if x < (n-y) and y <= x: + return spiral_part(y-1, y, n) + (x-y) + 1 + if x >= (n-y) and y <= x: + return spiral_part(x, y-1, n) + 1 + if x >= (n-y) and y > x: + return spiral_part(x+1, y, n) + 1 + if x < (n-y) and y > x: + return spiral_part(x, y-1, n) - 1 + + array = [[0] * n for j in xrange(n)] + for x in xrange(n): + for y in xrange(n): + array[x][y] = spiral_part(y, x, n) + return array + +for row in spiral(5): + print " ".join("%2s" % x for x in row) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-3.py b/Task/Spiral-matrix/Python/spiral-matrix-3.py new file mode 100644 index 0000000000..1446ba9429 --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-3.py @@ -0,0 +1,16 @@ +def spiral(n): + dat = [[None] * n for i in range(n)] + le = [[i + 1, i + 1] for i in reversed(range(n))] + le = sum(le, [])[1:] # for n = 5 le will be [5, 4, 4, 3, 3, 2, 2, 1, 1] + dxdy = [[1, 0], [0, 1], [-1, 0], [0, -1]] * ((len(le) + 4) / 4) # long enough + x, y, val = -1, 0, -1 + for steps, (dx, dy) in zip(le, dxdy): + x, y, val = x + dx, y + dy, val + 1 + for j in range(steps): + dat[y][x] = val + if j != steps-1: + x, y, val = x + dx, y + dy, val + 1 + return dat + +for row in spiral(5): # calc spiral and print it + print ' '.join('%3s' % x for x in row) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-4.py b/Task/Spiral-matrix/Python/spiral-matrix-4.py new file mode 100644 index 0000000000..f1e525cb2a --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-4.py @@ -0,0 +1,19 @@ +import itertools + +concat = itertools.chain.from_iterable +def partial_sums(items): + s = 0 + for x in items: + s += x + yield s + +grade = lambda xs: sorted(range(len(xs)), key=xs.__getitem__) +values = lambda n: itertools.cycle([1,n,-1,-n]) +counts = lambda n: concat([i,i-1] for i in range(n,0,-1)) +reshape = lambda n, xs: zip(*([iter(xs)] * n)) + +spiral = lambda n: reshape(n, grade(list(partial_sums(concat( + [v]*c for c,v in zip(counts(n), values(n))))))) + +for row in spiral(5): + print(' '.join('%3s' % x for x in row)) diff --git a/Task/Spiral-matrix/R/spiral-matrix-1.r b/Task/Spiral-matrix/R/spiral-matrix-1.r new file mode 100644 index 0000000000..c09c940dd4 --- /dev/null +++ b/Task/Spiral-matrix/R/spiral-matrix-1.r @@ -0,0 +1,32 @@ +runsum <- function(v) { + rs <- c() + for(i in 1:length(v)) { + rs <- c(rs, sum(v[1:i])) + } + rs +} + +grade <- function(v) { + g <- vector("numeric", length(v)) + for(i in 1:length(v)) { + g[v[i]] <- i-1 + } + g +} + +makespiral <- function(spirald) { + series <- vector("numeric", spirald^2) + series[] <- 1 + l <- spirald-1; p <- spirald+1 + s <- 1 + while(l > 0) { + series[p:(p+l-1)] <- series[p:(p+l-1)] * spirald*s + series[(p+l):(p+l*2-1)] <- -s*series[(p+l):(p+l*2-1)] + p <- p + l*2 + l <- l - 1; s <- -s + } + matrix(grade(runsum(series)), spirald, spirald, byrow=TRUE) + +} + +print(makespiral(5)) diff --git a/Task/Spiral-matrix/R/spiral-matrix-2.r b/Task/Spiral-matrix/R/spiral-matrix-2.r new file mode 100644 index 0000000000..68574c2a75 --- /dev/null +++ b/Task/Spiral-matrix/R/spiral-matrix-2.r @@ -0,0 +1,13 @@ +#more general function, v is assumed to be a vector +spiralv<-function(v){ + n<-sqrt(length(v)) + if(n!=floor(n)) stop(simpleError("length of v should be a square of an integer")) + if(n==0) stop(simpleError("v should be of positive length")) + if(n==1) M<-matrix(v,1,1) + else M<-rbind(v[1:n],cbind(spiralv(v[(2*n):(n^2)])[(n-1):1,(n-1):1],v[(n+1):(2*n-1)])) + M +} +#wrapper +spiral<-function(n){spiralv(0:(n^2-1))} +#check: +spiral(5) diff --git a/Task/Spiral-matrix/REXX/spiral-matrix.rexx b/Task/Spiral-matrix/REXX/spiral-matrix.rexx new file mode 100644 index 0000000000..db9b22b59c --- /dev/null +++ b/Task/Spiral-matrix/REXX/spiral-matrix.rexx @@ -0,0 +1,28 @@ +/*REXX program to show a spiral in a square array (of any size). */ + +arg size . /*get the array size from arg. */ +if size=='' then size=5 /*if no argument, use the default*/ +tot=size**2 /*total # of elements in spiral. */ +k=size /*K is the counter for the sprial*/ +row=1 /*start with row one. */ +col=0 /*start with col zero. */ +n=0 /*start the sprial at 0 (zero).*/ + +/*─────────────────────────────────────build the spiral─────────────────*/ + do n=0 for k; col=col+1; @.col.row=n; end + do until n>=tot + k=k-1 + do n=n for k; row=row+1; @.col.row=n; end + do n=n for k; col=col-1; @.col.row=n; end + if n>=tot then leave + k=k-1 + do n=n for k; row=row-1; @.col.row=n; end + do n=n for k; col=col+1; @.col.row=n; end + end +/*─────────────────────────────────────display the spiral───────────────*/ + do col=1 for size; _='' + do row=1 for size + _=_ right(@.row.col,length(tot)) + end + say substr(_,2) + end diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix.rb b/Task/Spiral-matrix/Ruby/spiral-matrix.rb new file mode 100644 index 0000000000..71bf1f53c7 --- /dev/null +++ b/Task/Spiral-matrix/Ruby/spiral-matrix.rb @@ -0,0 +1,23 @@ +def spiral(n) + spiral = Array.new(n) {Array.new(n, nil)} # n x n array of nils + runs = n.downto(0).each_cons(2).to_a.flatten # n==5; [5,4,4,3,3,2,2,1,1,0] + delta = [[1,0], [0,1], [-1,0], [0,-1]].each + x, y, value = -1, 0, -1 + for run in runs + dx,dy = begin + delta.next + rescue StopIteration + delta.rewind + retry + end + run.times do |i| + x += dx + y += dy + value += 1 + spiral[y][x] = value + end + end + spiral +end + +print_matrix spiral(5) diff --git a/Task/Spiral-matrix/Scala/spiral-matrix.scala b/Task/Spiral-matrix/Scala/spiral-matrix.scala new file mode 100644 index 0000000000..b60c5c942e --- /dev/null +++ b/Task/Spiral-matrix/Scala/spiral-matrix.scala @@ -0,0 +1,22 @@ +class Folder(){ + var dir = (1,0) + var pos = (-1,0) + def apply(l:List[Int], a:Array[Array[Int]]) = { + var (x,y) = pos //start position + var (dx,dy) = dir //direction + l.foreach {e => x = x + dx; y = y + dy; a(y)(x) = e } //copy l elements to array using current direction + pos = (x,y) + dir = (-dy, dx) //turn + } +} +def spiral(n:Int) = { + def dup(n:Int) = (1 to n).flatMap(i=>List(i,i)).toList + val folds = n :: dup(n-1).reverse //define fold part lengths + + var array = new Array[Array[Int]](n,n) + val fold = new Folder() + + var seq = (0 until n*n).toList //sequence to fold + folds.foreach {len => fold(seq.take(len),array); seq = seq.drop(len)} + array +} diff --git a/Task/Spiral-matrix/Seed7/spiral-matrix.seed7 b/Task/Spiral-matrix/Seed7/spiral-matrix.seed7 new file mode 100644 index 0000000000..4ea8dc9007 --- /dev/null +++ b/Task/Spiral-matrix/Seed7/spiral-matrix.seed7 @@ -0,0 +1,52 @@ +$ include "seed7_05.s7i"; + +const type: matrix is array array integer; + +const func matrix: spiral (in integer: n) is func + result + var matrix: myArray is matrix.value; + local + var integer: i is 0; + var integer: dx is 1; + var integer: dy is 0; + var integer: x is 1; + var integer: y is 1; + var integer: nx is 0; + var integer: ny is 0; + var integer: swap is 0; + begin + myArray := n times n times 0; + for i range 1 to n**2 do + myArray[x][y] := i; + nx := x + dx; + ny := y + dy; + if nx >= 1 and nx <= n and ny >= 1 and ny <= n and myArray[nx][ny] = 0 then + x := nx; + y := ny; + else + swap := dx; + dx := -dy; + dy := swap; + x +:= dx; + y +:= dy; + end if; + end for; + end func; + +const proc: writeMatrix (in matrix: myArray) is func + local + var integer: x is 0; + var integer: y is 0; + begin + for key y range myArray do + for key x range myArray[y] do + write(myArray[x][y] lpad 4); + end for; + writeln; + end for; + end func; + +const proc: main is func + begin + writeMatrix(spiral(5)); + end func; diff --git a/Task/Spiral-matrix/TSE-SAL/spiral-matrix.tse b/Task/Spiral-matrix/TSE-SAL/spiral-matrix.tse new file mode 100644 index 0000000000..d00fcf8fd7 --- /dev/null +++ b/Task/Spiral-matrix/TSE-SAL/spiral-matrix.tse @@ -0,0 +1,126 @@ +// library: math: create: array: spiral: inwards <description></description> <version control></version control> <version>1.0.0.0.15</version> (filenamemacro=creamasi.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 01:15:43] +PROC PROCMathCreateArraySpiralInwards( INTEGER nI ) + // e.g. PROC Main() + // e.g. STRING s1[255] = "5" + // e.g. IF ( NOT ( Ask( "math: create: array: spiral: inwards: nI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF + // e.g. PROCMathCreateArraySpiralInwards( Val( s1 ) ) + // e.g. END + // e.g. + // e.g. <F12> Main() + // + INTEGER columnEndI = 0 + // + INTEGER columnBeginI = nI - 1 + // + INTEGER rowEndI = 0 + // + INTEGER rowBeginI = nI - 1 + // + INTEGER columnI = 0 + // + INTEGER rowI = 0 + // + INTEGER minI = 0 + INTEGER maxI = nI * nI - 1 + INTEGER I = 0 + // + INTEGER columnWidthI = Length( Str( nI * nI - 1 ) ) + 1 + // + INTEGER directionRightI = 0 + INTEGER directionLeftI = 1 + INTEGER directionDownI = 2 + INTEGER directionUpI = 3 + // + INTEGER directionI = directionRightI + // + FOR I = minI TO maxI + // + SetGlobalInt( Format( "MatrixS", columnI, ",", rowI ), I ) + // SetGlobalInt( Format( "MatrixS", columnI, ",", rowI ), I ) + // + PutStrXY( ( Query( ScreenCols ) / 8 ) + columnI * columnWidthI, ( Query( ScreenRows ) / 8 ) + rowI, Str( I ), Color( BRIGHT RED ON WHITE ) ) + // PutStrXY( ( Query( ScreenCols ) / 8 ) + columnI * columnWidthI, ( Query( ScreenRows ) / 8 ) + rowI, Str( I + 1 ), Color( BRIGHT RED ON WHITE ) ) + // + CASE directionI + // + WHEN directionRightI + // + IF ( columnI < columnBeginI ) + // + columnI = columnI + 1 + // + ELSE + // + directionI = directionDownI + // + rowI = rowI + 1 + // + rowEndI = rowEndI + 1 + // + ENDIF + // + WHEN directionDownI + // + IF ( rowI < rowBeginI ) + // + rowI = rowI + 1 + // + ELSE + // + directionI = directionLeftI + // + columnI = columnI - 1 + // + columnBeginI = columnBeginI - 1 + // + ENDIF + // + WHEN directionLeftI + // + IF ( columnI > columnEndI ) + // + columnI = columnI - 1 + // + ELSE + // + directionI = directionUpI + // + rowI = rowI - 1 + // + rowBeginI = rowBeginI - 1 + // + ENDIF + // + WHEN directionUpI + // + IF ( rowI > rowEndI ) + // + rowI = rowI - 1 + // + ELSE + // + directionI = directionRightI + // + columnI = columnI + 1 + // + columnEndI = columnEndI + 1 + // + ENDIF + // + OTHERWISE + // + Warn( Format( "PROCMathCreateArraySpiralInwards(", " ", "case", " ", ":", " ", Str( directionI ), ": not known" ) ) + // + RETURN() + // + ENDCASE + // + ENDFOR + // +END + +PROC Main() +STRING s1[255] = "5" +IF ( NOT ( Ask( "math: create: array: spiral: inwards: nI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF + PROCMathCreateArraySpiralInwards( Val( s1 ) ) +END diff --git a/Task/Spiral-matrix/Tcl/spiral-matrix.tcl b/Task/Spiral-matrix/Tcl/spiral-matrix.tcl new file mode 100644 index 0000000000..460f64d559 --- /dev/null +++ b/Task/Spiral-matrix/Tcl/spiral-matrix.tcl @@ -0,0 +1,34 @@ +package require Tcl 8.5 +namespace path {::tcl::mathop} +proc spiral size { + set m [lrepeat $size [lrepeat $size .]] + set x 0; set dx 0 + set y -1; set dy 1 + set i -1 + while {$i < $size ** 2 - 1} { + if {$dy == 0} { + incr x $dx + if {0 <= $x && $x < $size && [lindex $m $x $y] eq "."} { + lset m $x $y [incr i] + } else { + # back up and change direction + incr x [- $dx] + set dy [- $dx] + set dx 0 + } + } else { + incr y $dy + if {0 <= $y && $y < $size && [lindex $m $x $y] eq "."} { + lset m $x $y [incr i] + } else { + # back up and change direction + incr y [- $dy] + set dx $dy + set dy 0 + } + } + } + return $m +} + +print_matrix [spiral 5] diff --git a/Task/Spiral-matrix/Ursala/spiral-matrix.ursala b/Task/Spiral-matrix/Ursala/spiral-matrix.ursala new file mode 100644 index 0000000000..d6e590b630 --- /dev/null +++ b/Task/Spiral-matrix/Ursala/spiral-matrix.ursala @@ -0,0 +1,13 @@ +#import std +#import nat +#import int + +spiral = + +^H/block nleq-<lS&r+ -+ + num@NiC+ sum:-0*yK33x+ (|\LL negation**)+ rlc ~&lh==1, + ~&rNNXNXSPlrDlSPK32^lrtxiiNCCSLhiC5D/~& iota*+ iota+- + +#cast %nLLL + +examples = spiral* <5,6,7> diff --git a/Task/Spiral-matrix/Visual-Basic/spiral-matrix-1.vb b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-1.vb new file mode 100644 index 0000000000..644bc19011 --- /dev/null +++ b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-1.vb @@ -0,0 +1,58 @@ +Option Explicit + +Sub Main() + print2dArray getSpiralArray(5) +End Sub + +Function getSpiralArray(dimension As Integer) As Integer() + ReDim spiralArray(dimension - 1, dimension - 1) As Integer + + Dim numConcentricSquares As Integer + numConcentricSquares = dimension \ 2 + If (dimension Mod 2) Then numConcentricSquares = numConcentricSquares + 1 + + + Dim j As Integer, sideLen As Integer, currNum As Integer + sideLen = dimension + + Dim i As Integer + For i = 0 To numConcentricSquares - 1 + ' do top side + For j = 0 To sideLen - 1 + spiralArray(i, i + j) = currNum + currNum = currNum + 1 + Next + + ' do right side + For j = 1 To sideLen - 1 + spiralArray(i + j, dimension - 1 - i) = currNum + currNum = currNum + 1 + Next + + ' do bottom side + For j = sideLen - 2 To 0 Step -1 + spiralArray(dimension - 1 - i, i + j) = currNum + currNum = currNum + 1 + Next + + ' do left side + For j = sideLen - 2 To 1 Step -1 + spiralArray(i + j, i) = currNum + currNum = currNum + 1 + Next + + sideLen = sideLen - 2 + Next + + getSpiralArray = spiralArray() +End Function + +Sub print2dArray(arr() As Integer) + Dim row As Integer, col As Integer + For row = 0 To UBound(arr, 1) + For col = 0 To UBound(arr, 2) - 1 + Debug.Print arr(row, col), + Next + Debug.Print arr(row, UBound(arr, 2)) + Next +End Sub diff --git a/Task/Spiral-matrix/Visual-Basic/spiral-matrix-2.vb b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-2.vb new file mode 100644 index 0000000000..0b3dc2c285 --- /dev/null +++ b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-2.vb @@ -0,0 +1,51 @@ +Sub spiral() + Dim n As Integer, a As Integer, b As Integer + Dim numCsquares As Integer, sideLen As Integer, currNum As Integer + Dim j As Integer, i As Integer + Dim j1 As Integer, j2 As Integer, j3 As Integer + + n = 5 + + Dim spiralArr(9, 9) As Integer + numCsquares = CInt(Application.WorksheetFunction.Ceiling(n / 2, 1)) + sideLen = n + currNum = 0 + For i = 0 To numCsquares - 1 + 'do top side + For j = 0 To sideLen - 1 + currNum = currNum + 1 + spiralArr(i, i + j) = currNum + Next j + + 'do right side + For j1 = 1 To sideLen - 1 + currNum = currNum + 1 + spiralArr(i + j1, n - 1 - i) = currNum + Next j1 + + 'do bottom side + j2 = sideLen - 2 + Do While j2 > -1 + currNum = currNum + 1 + spiralArr(n - 1 - i, i + j2) = currNum + j2 = j2 - 1 + Loop + + 'do left side + j3 = sideLen - 2 + Do While j3 > 0 + currNum = currNum + 1 + spiralArr(i + j3, i) = currNum + j3 = j3 - 1 + Loop + + sideLen = sideLen - 2 + Next i + + For a = 0 To n - 1 + For b = 0 To n - 1 + Cells(a + 1, b + 1).Select + ActiveCell.Value = spiralArr(a, b) + Next b + Next a +End Sub diff --git a/Task/Spiral-matrix/Visual-Basic/spiral-matrix-3.vb b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-3.vb new file mode 100644 index 0000000000..1f3f204df1 --- /dev/null +++ b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-3.vb @@ -0,0 +1,68 @@ +Sub spiral(n As Integer) + Const FREE = -9 'negative number indicates unoccupied cell + Dim A() As Integer + Dim rowdelta(3) As Integer + Dim coldelta(3) As Integer + + 'initialize A to a matrix with an extra "border" of occupied cells + 'this avoids having to test if we've reached the edge of the matrix + + ReDim A(0 To n + 1, 0 To n + 1) + + 'Since A is initialized with zeros, setting A(1 to n,1 to n) to "FREE" + 'leaves a "border" around it occupied with zeroes + + For i = 1 To n: For j = 1 To n: A(i, j) = FREE: Next: Next + + 'set amount to move in directions "right", "down", "left", "up" + + rowdelta(0) = 0: coldelta(0) = 1 + rowdelta(1) = 1: coldelta(1) = 0 + rowdelta(2) = 0: coldelta(2) = -1 + rowdelta(3) = -1: coldelta(3) = 0 + + curnum = 0 + + 'set current cell position + col = 1 + row = 1 + + 'set current direction + theDir = 0 'theDir = 1 will fill the matrix counterclockwise + + 'ok will be true as long as there is a free cell left + ok = True + + Do While ok + + 'occupy current FREE cell and increase curnum + A(row, col) = curnum + curnum = curnum + 1 + + 'check if next cell in current direction is free + 'if not, try another direction in clockwise fashion + 'if all directions lead to occupied cells then we are finished! + + ok = False + For i = 0 To 3 + newdir = (theDir + i) Mod 4 + If A(row + rowdelta(newdir), col + coldelta(newdir)) = FREE Then + 'yes, move to it and change direction if necessary + theDir = newdir + row = row + rowdelta(theDir) + col = col + coldelta(theDir) + ok = True + Exit For + End If + Next i + Loop + + 'print result + For i = 1 To n + For j = 1 To n + Debug.Print A(i, j), + Next + Debug.Print + Next + +End Sub diff --git a/Task/Spiral-matrix/XPL0/spiral-matrix.xpl0 b/Task/Spiral-matrix/XPL0/spiral-matrix.xpl0 new file mode 100644 index 0000000000..05804bc01a --- /dev/null +++ b/Task/Spiral-matrix/XPL0/spiral-matrix.xpl0 @@ -0,0 +1,22 @@ +def N=5; +int A(N,N); +int I, J, X, Y, Steps, Dir; +include c:\cxpl\codes; +[Clear; +I:= 0; X:= -1; Y:= 0; Steps:= N; Dir:= 0; +repeat for J:= 1 to Steps do + [case Dir&3 of + 0: X:= X+1; + 1: Y:= Y+1; + 2: X:= X-1; + 3: Y:= Y-1 + other []; + A(X,Y):= I; + Cursor(X*3,Y); IntOut(0,I); + I:= I+1; + ]; + Dir:= Dir+1; + if Dir&1 then Steps:= Steps-1; +until Steps = 0; +Cursor(0,N); +] diff --git a/Task/Stable-marriage-problem/0DESCRIPTION b/Task/Stable-marriage-problem/0DESCRIPTION new file mode 100644 index 0000000000..0ddfbc8498 --- /dev/null +++ b/Task/Stable-marriage-problem/0DESCRIPTION @@ -0,0 +1,45 @@ +Solve the [[wp:Stable marriage problem|Stable marriage problem]] using the Gale/Shapley algorithm. + +'''Problem description'''<br> +Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each women ranks all the men in order of her preference. + +A stable set of engagements for marriage is one where no man prefers a women over the one he is engaged to, where that other woman ''also'' prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change. + +Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements. + +'''Task Specifics'''<br> +Given ten males: + abe, bob, col, dan, ed, fred, gav, hal, ian, jon +And ten females: + abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan + +And a complete list of ranked preferences, where the most liked is to the left: + abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay + bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay + col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan + dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi + ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay + fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay + gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay + hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee + ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve + jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope + + abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal + bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal + cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon + dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed + eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob + fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal + gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian + hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred + ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan + jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan + +# Use the Gale Shapley algorithm to find a stable set of engagements +# Perturb this set of engagements to form an unstable set of engagements then check this new set for stability. + +'''References''' +# [http://www.cs.columbia.edu/~evs/intro/stable/writeup.html The Stable Marriage Problem]. (Eloquent description and background information). +# [http://sephlietz.com/gale-shapley/ Gale-Shapley Algorithm Demonstration]. +# [http://mathsite.math.berkeley.edu/smp/smp.html Another Gale-Shapley Algorithm Demonstration]. diff --git a/Task/Stable-marriage-problem/1META.yaml b/Task/Stable-marriage-problem/1META.yaml new file mode 100644 index 0000000000..f407ff9d83 --- /dev/null +++ b/Task/Stable-marriage-problem/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Classic CS problems and programs diff --git a/Task/Stable-marriage-problem/BBC-BASIC/stable-marriage-problem.bbc b/Task/Stable-marriage-problem/BBC-BASIC/stable-marriage-problem.bbc new file mode 100644 index 0000000000..792b367eee --- /dev/null +++ b/Task/Stable-marriage-problem/BBC-BASIC/stable-marriage-problem.bbc @@ -0,0 +1,68 @@ + N = 10 + DIM mname$(N), wname$(N), mpref$(N), wpref$(N), mpartner%(N), wpartner%(N) + DIM proposed&(N,N) + mname$() = "", "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon" + wname$() = "", "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan" + mpref$() = "", "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG",\ + \ "BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH" + wpref$() = "", "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB",\ + \ "BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD" + + REM The Gale-Shapley algorithm: + REPEAT + FOR m% = 1 TO N + REPEAT + IF mpartner%(m%) EXIT REPEAT + FOR i% = 1 TO N + w% = ASCMID$(mpref$(m%),i%) - 64 + IF proposed&(m%,w%) = 0 EXIT FOR + NEXT i% + IF i% > N EXIT REPEAT + proposed&(m%,w%) = 1 + IF wpartner%(w%) = 0 THEN + mpartner%(m%) = w% : REM Get engaged + wpartner%(w%) = m% + ELSE + o% = wpartner%(w%) + IF INSTR(wpref$(w%), LEFT$(mname$(m%),1)) < \ + \ INSTR(wpref$(w%), LEFT$(mname$(o%),1)) THEN + mpartner%(o%) = 0 : REM Split up + mpartner%(m%) = w% : REM Get engaged + wpartner%(w%) = m% + ENDIF + ENDIF + UNTIL TRUE + NEXT m% + UNTIL SUM(mpartner%()) = (N*(N+1))/2 + + FOR m% = 1 TO N + PRINT mname$(m%) " is engaged to " wname$(mpartner%(m%)) + NEXT + PRINT "Relationships are "; + IF FNstable PRINT "stable." ELSE PRINT "unstable." + + a% = RND(N) + REPEAT b% = RND(N) : UNTIL b%<>a% + PRINT '"Now swapping " mname$(a%) "'s and " mname$(b%) "'s partners:" + SWAP mpartner%(a%), mpartner%(b%) + PRINT mname$(a%) " is engaged to " wname$(mpartner%(a%)) + PRINT mname$(b%) " is engaged to " wname$(mpartner%(b%)) + PRINT "Relationships are "; + IF FNstable PRINT "stable." ELSE PRINT "unstable." + END + + DEF FNstable + LOCAL m%, w%, o%, p% + FOR m% = 1 TO N + w% = mpartner%(m%) + FOR o% = 1 TO N + p% = wpartner%(o%) + IF INSTR(mpref$(m%), LEFT$(wname$(o%),1)) < \ + \ INSTR(mpref$(m%), LEFT$(wname$(w%),1)) AND \ + \ INSTR(wpref$(o%), LEFT$(mname$(m%),1)) < \ + \ INSTR(wpref$(o%), LEFT$(mname$(p%),1)) THEN + = FALSE + ENDIF + NEXT o% + NEXT m% + = TRUE diff --git a/Task/Stable-marriage-problem/Bracmat/stable-marriage-problem.bracmat b/Task/Stable-marriage-problem/Bracmat/stable-marriage-problem.bracmat new file mode 100644 index 0000000000..81315bf8ba --- /dev/null +++ b/Task/Stable-marriage-problem/Bracmat/stable-marriage-problem.bracmat @@ -0,0 +1,66 @@ +( (abe.abi eve cath ivy jan dee fay bea hope gay) + (bob.cath hope abi dee eve fay bea jan ivy gay) + (col.hope eve abi dee bea fay ivy gay cath jan) + (dan.ivy fay dee gay hope eve jan bea cath abi) + (ed.jan dee bea cath fay eve abi ivy hope gay) + (fred.bea abi dee gay eve ivy cath jan hope fay) + (gav.gay eve ivy bea cath abi dee hope jan fay) + (hal.abi eve hope fay ivy cath jan bea gay dee) + (ian.hope cath dee gay bea abi fay ivy jan eve) + (jon.abi fay jan gay eve bea dee cath ivy hope) + : ?Mplan + : ?M +& (abi.bob fred jon gav ian abe dan ed col hal) + (bea.bob abe col fred gav dan ian ed jon hal) + (cath.fred bob ed gav hal col ian abe dan jon) + (dee.fred jon col abe ian hal gav dan bob ed) + (eve.jon hal fred dan abe gav col ed ian bob) + (fay.bob abe ed ian jon dan fred gav col hal) + (gay.jon gav hal fred bob abe col ed dan ian) + (hope.gav jon bob abe ian dan hal ed col fred) + (ivy.ian col hal gav fred bob abe ed jon dan) + (jan.ed hal gav abe bob jon col ian fred dan) + : ?W +& :?engaged +& whl + ' ( !Mplan + : ?A + (?m&~(!engaged:? (!m.?) ?).%?w ?ws) + ( ?Z + & ( ( ~(!engaged:?a (?m`.!w) ?z) + & (!m.!w) !engaged + | !W:? (!w.? !m ? !m` ?) ? + & !a (!m.!w) !z + ) + : ?engaged + | + ) + & !Z !A (!m.!ws):?Mplan + ) + ) +& ( unstable + = m1 m2 w1 w2 + . !arg + : ? + (?m1.?w1) + ? + (?m2.?w2) + ( ? + & ( !M:? (!m1.? !w2 ? !w1 ?) ? + & !W:? (!w2.? !m1 ? !m2 ?) ? + | !M:? (!m2.? !w1 ? !w2 ?) ? + & !W:? (!w1.? !m2 ? !m1 ?) ? + ) + ) + ) +& ( unstable$!engaged&out$unstable + | out$stable + ) +& out$!engaged +& !engaged:(?m1.?w1) (?m2.?w2) ?others +& out$(swap !w1 for !w2) +& ( unstable$((!m1.!w2) (!m2.!w1) !others) + & out$unstable + | out$stable + ) +); diff --git a/Task/Stable-marriage-problem/C++/stable-marriage-problem.cpp b/Task/Stable-marriage-problem/C++/stable-marriage-problem.cpp new file mode 100644 index 0000000000..8bd48cfc46 --- /dev/null +++ b/Task/Stable-marriage-problem/C++/stable-marriage-problem.cpp @@ -0,0 +1,141 @@ +#include <algorithm> +#include <iostream> +#include <map> +#include <queue> +#include <string> +#include <vector> +using namespace std; + +const char *men_data[][11] = { + { "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" }, + { "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" }, + { "col", "hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan" }, + { "dan", "ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi" }, + { "ed", "jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay" }, + { "fred", "bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay" }, + { "gav", "gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay" }, + { "hal", "abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee" }, + { "ian", "hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve" }, + { "jon", "abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope" } +}; + +const char *women_data[][11] = { + { "abi", "bob","fred","jon","gav","ian","abe","dan","ed","col","hal" }, + { "bea", "bob","abe","col","fred","gav","dan","ian","ed","jon","hal" }, + { "cath", "fred","bob","ed","gav","hal","col","ian","abe","dan","jon" }, + { "dee", "fred","jon","col","abe","ian","hal","gav","dan","bob","ed" }, + { "eve", "jon","hal","fred","dan","abe","gav","col","ed","ian","bob" }, + { "fay", "bob","abe","ed","ian","jon","dan","fred","gav","col","hal" }, + { "gay", "jon","gav","hal","fred","bob","abe","col","ed","dan","ian" }, + { "hope", "gav","jon","bob","abe","ian","dan","hal","ed","col","fred" }, + { "ivy", "ian","col","hal","gav","fred","bob","abe","ed","jon","dan" }, + { "jan", "ed","hal","gav","abe","bob","jon","col","ian","fred","dan" } +}; + +typedef vector<string> PrefList; +typedef map<string, PrefList> PrefMap; +typedef map<string, string> Couples; + +// Does 'first' appear before 'second' in preference list? +bool prefers(const PrefList &prefer, const string &first, const string &second) +{ + for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it) + { + if (*it == first) return true; + if (*it == second) return false; + } + return false; // no preference +} + +void check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref) +{ + cout << "Stablility:\n"; + bool stable = true; + for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it) + { + const string &bride = it->first; + const string &groom = it->second; + const PrefList &preflist = men_pref.at(groom); + + for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it) + { + if (*it == bride) // he prefers his bride + break; + if (prefers(preflist, *it, bride) && // he prefers another woman + prefers(women_pref.at(*it), groom, engaged.at(*it))) // other woman prefers him + { + cout << "\t" << *it << + " prefers " << groom << + " over " << engaged.at(*it) << + " and " << groom << + " prefers " << *it << + " over " << bride << "\n"; + stable = false; + } + } + } + if (stable) cout << "\t(all marriages stable)\n"; +} + +int main() +{ + PrefMap men_pref, women_pref; + queue<string> bachelors; + + // init data structures + for (int i = 0; i < 10; ++i) // person + { + for (int j = 1; j < 11; ++j) // preference + { + men_pref[ men_data[i][0]].push_back( men_data[i][j]); + women_pref[women_data[i][0]].push_back(women_data[i][j]); + } + bachelors.push(men_data[i][0]); + } + + Couples engaged; // <woman,man> + + cout << "Matchmaking:\n"; + while (!bachelors.empty()) + { + const string &suitor = bachelors.front(); + const PrefList &preflist = men_pref[suitor]; + + for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it) + { + const string &bride = *it; + + if (engaged.find(bride) == engaged.end()) // she's available + { + cout << "\t" << bride << " and " << suitor << "\n"; + engaged[bride] = suitor; // hook up + break; + } + + const string &groom = engaged[bride]; + + if (prefers(women_pref[bride], suitor, groom)) + { + cout << "\t" << bride << " dumped " << groom << " for " << suitor << "\n"; + bachelors.push(groom); // dump that zero + engaged[bride] = suitor; // get a hero + break; + } + } + bachelors.pop(); // pop at the end to not invalidate suitor reference + } + + cout << "Engagements:\n"; + for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it) + { + cout << "\t" << it->first << " and " << it->second << "\n"; + } + + check_stability(engaged, men_pref, women_pref); + + cout << "Perturb:\n"; + std::swap(engaged["abi"], engaged["bea"]); + cout << "\tengage abi with " << engaged["abi"] << " and bea with " << engaged["bea"] << "\n"; + + check_stability(engaged, men_pref, women_pref); +} diff --git a/Task/Stable-marriage-problem/C/stable-marriage-problem.c b/Task/Stable-marriage-problem/C/stable-marriage-problem.c new file mode 100644 index 0000000000..6e721a5132 --- /dev/null +++ b/Task/Stable-marriage-problem/C/stable-marriage-problem.c @@ -0,0 +1,134 @@ +#include <stdio.h> + +int verbose = 0; +enum { + clown = -1, + abe, bob, col, dan, ed, fred, gav, hal, ian, jon, + abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan, +}; +const char *name[] = { + "Abe", "Bob", "Col", "Dan", "Ed", "Fred", "Gav", "Hal", "Ian", "Jon", + "Abi", "Bea", "Cath", "Dee", "Eve", "Fay", "Gay", "Hope", "Ivy", "Jan" +}; +int pref[jan + 1][jon + 1] = { + { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay }, + { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay }, + { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan }, + { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi }, + { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay }, + { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay }, + { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay }, + { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee }, + { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve }, + { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope }, + + { bob, fred, jon, gav, ian, abe, dan, ed, col, hal }, + { bob, abe, col, fred, gav, dan, ian, ed, jon, hal }, + { fred, bob, ed, gav, hal, col, ian, abe, dan, jon }, + { fred, jon, col, abe, ian, hal, gav, dan, bob, ed }, + { jon, hal, fred, dan, abe, gav, col, ed, ian, bob }, + { bob, abe, ed, ian, jon, dan, fred, gav, col, hal }, + { jon, gav, hal, fred, bob, abe, col, ed, dan, ian }, + { gav, jon, bob, abe, ian, dan, hal, ed, col, fred }, + { ian, col, hal, gav, fred, bob, abe, ed, jon, dan }, + { ed, hal, gav, abe, bob, jon, col, ian, fred, dan }, +}; +int pairs[jan + 1], proposed[jan + 1]; + +void engage(int man, int woman) +{ + pairs[man] = woman; + pairs[woman] = man; + if (verbose) printf("%4s is engaged to %4s\n", name[man], name[woman]); +} + +void dump(int woman, int man) +{ + pairs[man] = pairs[woman] = clown; + if (verbose) printf("%4s dumps %4s\n", name[woman], name[man]); +} + +/* how high this person ranks that: lower is more preferred */ +int rank(int this, int that) +{ + int i; + for (i = abe; i <= jon && pref[this][i] != that; i++); + return i; +} + +void propose(int man, int woman) +{ + int fiance = pairs[woman]; + if (verbose) printf("%4s proposes to %4s\n", name[man], name[woman]); + + if (fiance == clown) { + engage(man, woman); + } else if (rank(woman, man) < rank(woman, fiance)) { + dump(woman, fiance); + engage(man, woman); + } +} + +int covet(int man1, int wife2) +{ + if (rank(man1, wife2) < rank(man1, pairs[man1]) && + rank(wife2, man1) < rank(wife2, pairs[wife2])) { + printf( " %4s (w/ %4s) and %4s (w/ %4s) prefer each other" + " over current pairing.\n", + name[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]] + ); + return 1; + } + return 0; +} + +int thy_neighbors_wife(int man1, int man2) +{ /* +: force checking all pairs; "||" would shortcircuit */ + return covet(man1, pairs[man2]) + covet(man2, pairs[man1]); +} + +int unstable() +{ + int i, j, bad = 0; + for (i = abe; i < jon; i++) { + for (j = i + 1; j <= jon; j++) + if (thy_neighbors_wife(i, j)) bad = 1; + } + return bad; +} + +int main() +{ + int i, unengaged; + /* init: everyone marries the clown */ + for (i = abe; i <= jan; i++) + pairs[i] = proposed[i] = clown; + + /* rounds */ + do { + unengaged = 0; + for (i = abe; i <= jon; i++) { + //for (i = abi; i <= jan; i++) { /* could let women propose */ + if (pairs[i] != clown) continue; + unengaged = 1; + propose(i, pref[i][++proposed[i]]); + } + } while (unengaged); + + printf("Pairing:\n"); + for (i = abe; i <= jon; i++) + printf(" %4s - %s\n", name[i], + pairs[i] == clown ? "clown" : name[pairs[i]]); + + printf(unstable() + ? "Marriages not stable\n" /* draw sad face here */ + : "Stable matchup\n"); + + printf("\nBut if Bob and Fred were to swap:\n"); + i = pairs[bob]; + engage(bob, pairs[fred]); + engage(fred, i); + printf(unstable() ? "Marriages not stable\n" : "Stable matchup\n"); + + return 0; +} diff --git a/Task/Stable-marriage-problem/CoffeeScript/stable-marriage-problem.coffeescript b/Task/Stable-marriage-problem/CoffeeScript/stable-marriage-problem.coffeescript new file mode 100644 index 0000000000..ad585c3643 --- /dev/null +++ b/Task/Stable-marriage-problem/CoffeeScript/stable-marriage-problem.coffeescript @@ -0,0 +1,128 @@ +class Person + constructor: (@name, @preferences) -> + @mate = null + @best_mate_rank = 0 + @rank = {} + for preference, i in @preferences + @rank[preference] = i + + preferred_mate_name: => + @preferences[@best_mate_rank] + + reject: => + @best_mate_rank += 1 + + set_mate: (mate) => + @mate = mate + + offer_mate: (free_mate, reject_mate_cb) => + if @mate + if @covets(free_mate) + console.log "#{free_mate.name} steals #{@name} from #{@mate.name}" + reject_mate_cb @mate + free_mate.set_mate @ + @set_mate free_mate + else + console.log "#{free_mate.name} cannot steal #{@name} from #{@mate.name}" + reject_mate_cb free_mate + else + console.log "#{free_mate.name} gets #{@name} first" + free_mate.set_mate @ + @set_mate free_mate + + happiness: => + @rank[@mate.name] + + covets: (other_mate) => + @rank[other_mate.name] <= @rank[@mate.name] + +persons_by_name = (persons) -> + hsh = {} + for person in persons + hsh[person.name] = person + hsh + +mate_off = (guys, gals) -> + free_pursuers = (guy for guy in guys) + guys_by_name = persons_by_name guys + gals_by_name = persons_by_name gals + + while free_pursuers.length > 0 + free_pursuer = free_pursuers.shift() + gal_name = free_pursuer.preferred_mate_name() + gal = gals_by_name[gal_name] + reject_mate_cb = (guy) -> + guy.reject() + free_pursuers.push guy + gal.offer_mate free_pursuer, reject_mate_cb + + +report_on_mates = (guys) -> + console.log "\n----Marriage Report" + for guy, i in guys + throw Error("illegal marriage") if guy.mate.mate isnt guy + console.log guy.name, guy.mate.name, \ + "(his choice #{guy.happiness()}, her choice #{guy.mate.happiness()} )" + +report_potential_adulteries = (guys) -> + for guy1, i in guys + gal1 = guy1.mate + for j in [0...i] + guy2 = guys[j] + gal2 = guy2.mate + if guy1.covets(gal2) and gal2.covets(guy1) + console.log "#{guy1.name} and #{gal2.name} would stray" + if guy2.covets(gal1) and gal1.covets(guy2) + console.log "#{guy2.name} and #{gal1.name} would stray" + +perturb = (guys) -> + # mess up marriages by swapping two couples...this is mainly to drive + # out that report_potential_adulteries will actually work + guy0 = guys[0] + guy1 = guys[1] + gal0 = guy0.mate + gal1 = guy1.mate + console.log "\nPerturbing with #{guy0.name}, #{gal0.name}, #{guy1.name}, #{gal1.name}" + guy0.set_mate gal1 + guy1.set_mate gal0 + gal1.set_mate guy0 + gal0.set_mate guy1 + + +Population = -> + guy_preferences = + abe: ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'] + bob: ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'] + col: ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'] + dan: ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'] + ed: ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'] + fred: ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'] + gav: ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'] + hal: ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'] + ian: ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'] + jon: ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope'] + + gal_preferences = + abi: ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'] + bea: ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'] + cath: ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'] + dee: ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'] + eve: ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'] + fay: ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'] + gay: ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'] + hope: ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'] + ivy: ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'] + jan: ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan'] + + guys = (new Person(name, preferences) for name, preferences of guy_preferences) + gals = (new Person(name, preferences) for name, preferences of gal_preferences) + [guys, gals] + +do -> + [guys, gals] = Population() + mate_off guys, gals + report_on_mates guys + report_potential_adulteries guys + perturb guys + report_on_mates guys + report_potential_adulteries guys diff --git a/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d b/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d new file mode 100644 index 0000000000..4f6cd57c49 --- /dev/null +++ b/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d @@ -0,0 +1,130 @@ +import std.stdio, std.array, std.algorithm, std.string; + + +string[string] matchmaker(string[][string] guyPrefers, + string[][string] girlPrefers) { + string[string] engagedTo; + string[] freeGuys = guyPrefers.keys; + + while (freeGuys.length) { + const string thisGuy = freeGuys[0]; + freeGuys.popFront(); + const auto thisGuyPrefers = guyPrefers[thisGuy]; + foreach (girl; thisGuyPrefers) { + if (girl !in engagedTo) { // girl is free + engagedTo[girl] = thisGuy; + break; + } else { + string otherGuy = engagedTo[girl]; + string[] thisGirlPrefers = girlPrefers[girl]; + if (thisGirlPrefers.countUntil(thisGuy) < + thisGirlPrefers.countUntil(otherGuy)) { + // this girl prefers this guy to + // the guy she's engagedTo to. + engagedTo[girl] = thisGuy; + freeGuys ~= otherGuy; + break; + } + // else no change, keep looking for this guy + } + } + } + + return engagedTo; +} + + +bool check(bool doPrint=false)(string[string] engagedTo, + string[][string] guyPrefers, + string[][string] galPrefers) { + enum MSG = "%s likes %s better than %s and %s " ~ + "likes %s better than their current partner"; + string[string] inverseEngaged; + foreach (k, v; engagedTo) + inverseEngaged[v] = k; + + foreach (she, he; engagedTo) { + auto sheLikes = galPrefers[she]; + auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)]; + auto heLikes = guyPrefers[he]; + auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)]; + foreach (guy; sheLikesBetter) { + auto guysGirl = inverseEngaged[guy]; + auto guyLikes = guyPrefers[guy]; + + if (guyLikes.countUntil(guysGirl) > + guyLikes.countUntil(she)) { + static if (doPrint) + writefln(MSG, she, guy, he, guy, she); + return false; + } + } + + foreach (gal; heLikesBetter) { + auto girlsGuy = engagedTo[gal]; + auto galLikes = galPrefers[gal]; + + if (galLikes.countUntil(girlsGuy) > + galLikes.countUntil(he)) { + static if (doPrint) + writefln(MSG, he, gal, she, gal, he); + return false; + } + } + } + + return true; +} + + +void main() { + auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay + bob cath hope abi dee eve fay bea jan ivy gay + col hope eve abi dee bea fay ivy gay cath jan + dan ivy fay dee gay hope eve jan bea cath abi + ed jan dee bea cath fay eve abi ivy hope gay + fred bea abi dee gay eve ivy cath jan hope fay + gav gay eve ivy bea cath abi dee hope jan fay + hal abi eve hope fay ivy cath jan bea gay dee + ian hope cath dee gay bea abi fay ivy jan eve + jon abi fay jan gay eve bea dee cath ivy hope"; + + auto galData = "abi bob fred jon gav ian abe dan ed col hal + bea bob abe col fred gav dan ian ed jon hal + cath fred bob ed gav hal col ian abe dan jon + dee fred jon col abe ian hal gav dan bob ed + eve jon hal fred dan abe gav col ed ian bob + fay bob abe ed ian jon dan fred gav col hal + gay jon gav hal fred bob abe col ed dan ian + hope gav jon bob abe ian dan hal ed col fred + ivy ian col hal gav fred bob abe ed jon dan + jan ed hal gav abe bob jon col ian fred dan"; + + string[][string] guyPrefers, galPrefers; + foreach (line; guyData.splitLines()) + guyPrefers[split(line)[0]] = split(line)[1..$]; + foreach (line; galData.splitLines()) + galPrefers[split(line)[0]] = split(line)[1..$]; + + writeln("Engagements:"); + auto engagedTo = matchmaker(guyPrefers, galPrefers); + + writeln("\nCouples:"); + string[] parts; + foreach (k; engagedTo.keys.sort) + writefln("%s is engagedTo to %s", k, engagedTo[k]); + writeln(); + + bool c = check!(true)(engagedTo, guyPrefers, galPrefers); + writeln("Marriages are ", c ? "stable" : "unstable"); + + writeln("\n\nSwapping two fiances to introduce an error"); + auto gals = galPrefers.keys.sort; + swap(engagedTo[gals[0]], engagedTo[gals[1]]); + foreach (gal; gals[0 .. 2]) + writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]); + writeln(); + + c = check!(true)(engagedTo, guyPrefers, galPrefers); + writeln("Marriages are ", c ? "stable" : "unstable"); +} diff --git a/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d new file mode 100644 index 0000000000..6dcefac149 --- /dev/null +++ b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d @@ -0,0 +1,120 @@ +import std.stdio, std.algorithm, std.array; + +enum F { abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan } +enum M { abe, bob, col, dan, ed, fred, gav, hal, ian, jon } + +alias M[][F] PrefMapF; +alias F[][M] PrefMapM; +alias M[F] Couples; + +immutable PrefMapF womenPref; +immutable PrefMapM menPref; + +pure nothrow static this() { + with (F) with (M) { + womenPref = [ + abi: [bob, fred, jon, gav, ian, abe, dan, ed, col, hal], + bea: [bob, abe, col, fred, gav, dan, ian, ed, jon, hal], + cath: [fred, bob, ed, gav, hal, col, ian, abe, dan, jon], + dee: [fred, jon, col, abe, ian, hal, gav, dan, bob, ed], + eve: [jon, hal, fred, dan, abe, gav, col, ed, ian, bob], + fay: [bob, abe, ed, ian, jon, dan, fred, gav, col, hal], + gay: [jon, gav, hal, fred, bob, abe, col, ed, dan, ian], + hope: [gav, jon, bob, abe, ian, dan, hal, ed, col, fred], + ivy: [ian, col, hal, gav, fred, bob, abe, ed, jon, dan], + jan: [ed, hal, gav, abe, bob, jon, col, ian, fred, dan] + ]; + + menPref = [ + abe: [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay], + bob: [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay], + col: [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan], + dan: [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi], + ed: [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay], + fred: [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay], + gav: [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay], + hal: [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee], + ian: [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve], + jon: [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope] + ]; + } +} + +/// Does 'first' appear before 'second' in preference list? +bool prefers(T)(in T[] prefer, in T first, in T second) +pure nothrow if (is(T == F) || is(T == M)) { + foreach (p; prefer) { + if (p == first) return true; + if (p == second) return false; + } + return false; // no preference +} + +void checkStability(in Couples engaged, in PrefMapM menPref, + in PrefMapF womenPref) { + writeln("Stablility:"); + bool stable = true; + foreach (bride, groom; engaged) { + const prefList = menPref[groom]; + + foreach (pr; prefList) { + if (pr == bride) // he prefers his bride + break; + + if (prefers(prefList, pr, bride) && + // he prefers another woman + prefers(womenPref[pr], groom, engaged[pr])) { + // other woman prefers him + writeln("\t", pr, " prefers ", groom, " over ", + engaged[pr], " and ", groom, " prefers ", + pr, " over ", bride); + stable = false; + } + } + } + + if (stable) + writeln("\t(all marriages stable)"); +} + +void main() { + M[] bachelors = menPref.keys.sort().release();// No queue in Phobos + Couples engaged; + + writeln("Matchmaking:"); + while (!bachelors.empty) { + immutable suitor = bachelors[0]; + bachelors.popFront(); + immutable prefList = menPref[suitor]; + + foreach (bride; prefList) { + if (bride !in engaged) { // she's available + writeln("\t", bride, " and ", suitor); + engaged[bride] = suitor; // hook up + break; + } + + immutable groom = engaged[bride]; + if (prefers(womenPref[bride], suitor, groom)) { + writeln("\t", bride, " dumped ", groom, + " for ", suitor); + bachelors ~= groom; // dump that zero + engaged[bride] = suitor; // get a hero + break; + } + } + } + + writeln("Engagements:"); + foreach (first, second; engaged) + writeln("\t", first, " and ", second); + + checkStability(engaged, menPref, womenPref); + + writeln("Perturb:"); + swap(engaged[F.abi], engaged[F.bea]); + writeln("\tengage abi with ", engaged[F.abi], + " and bea with ", engaged[F.bea]); + + checkStability(engaged, menPref, womenPref); +} diff --git a/Task/Stable-marriage-problem/Go/stable-marriage-problem.go b/Task/Stable-marriage-problem/Go/stable-marriage-problem.go new file mode 100644 index 0000000000..76acdc602c --- /dev/null +++ b/Task/Stable-marriage-problem/Go/stable-marriage-problem.go @@ -0,0 +1,204 @@ +package main + +import "fmt" + +// Asymetry in the algorithm suggests different data structures for the +// map value types of the proposers and the recipients. Proposers go down +// their list of preferences in order, and do not need random access. +// Recipients on the other hand must compare their preferences to arbitrary +// proposers. A slice is adequate for proposers, but a map allows direct +// lookups for recipients and avoids looping code. +type proposers map[string][]string + +var mPref = proposers{ + "abe": []string{ + "abi", "eve", "cath", "ivy", "jan", + "dee", "fay", "bea", "hope", "gay"}, + "bob": []string{ + "cath", "hope", "abi", "dee", "eve", + "fay", "bea", "jan", "ivy", "gay"}, + "col": []string{ + "hope", "eve", "abi", "dee", "bea", + "fay", "ivy", "gay", "cath", "jan"}, + "dan": []string{ + "ivy", "fay", "dee", "gay", "hope", + "eve", "jan", "bea", "cath", "abi"}, + "ed": []string{ + "jan", "dee", "bea", "cath", "fay", + "eve", "abi", "ivy", "hope", "gay"}, + "fred": []string{ + "bea", "abi", "dee", "gay", "eve", + "ivy", "cath", "jan", "hope", "fay"}, + "gav": []string{ + "gay", "eve", "ivy", "bea", "cath", + "abi", "dee", "hope", "jan", "fay"}, + "hal": []string{ + "abi", "eve", "hope", "fay", "ivy", + "cath", "jan", "bea", "gay", "dee"}, + "ian": []string{ + "hope", "cath", "dee", "gay", "bea", + "abi", "fay", "ivy", "jan", "eve"}, + "jon": []string{ + "abi", "fay", "jan", "gay", "eve", + "bea", "dee", "cath", "ivy", "hope"}, +} + +type recipients map[string]map[string]int + +var wPref = recipients{ + "abi": map[string]int{ + "bob": 1, "fred": 2, "jon": 3, "gav": 4, "ian": 5, + "abe": 6, "dan": 7, "ed": 8, "col": 9, "hal": 10}, + "bea": map[string]int{ + "bob": 1, "abe": 2, "col": 3, "fred": 4, "gav": 5, + "dan": 6, "ian": 7, "ed": 8, "jon": 9, "hal": 10}, + "cath": map[string]int{ + "fred": 1, "bob": 2, "ed": 3, "gav": 4, "hal": 5, + "col": 6, "ian": 7, "abe": 8, "dan": 9, "jon": 10}, + "dee": map[string]int{ + "fred": 1, "jon": 2, "col": 3, "abe": 4, "ian": 5, + "hal": 6, "gav": 7, "dan": 8, "bob": 9, "ed": 10}, + "eve": map[string]int{ + "jon": 1, "hal": 2, "fred": 3, "dan": 4, "abe": 5, + "gav": 6, "col": 7, "ed": 8, "ian": 9, "bob": 10}, + "fay": map[string]int{ + "bob": 1, "abe": 2, "ed": 3, "ian": 4, "jon": 5, + "dan": 6, "fred": 7, "gav": 8, "col": 9, "hal": 10}, + "gay": map[string]int{ + "jon": 1, "gav": 2, "hal": 3, "fred": 4, "bob": 5, + "abe": 6, "col": 7, "ed": 8, "dan": 9, "ian": 10}, + "hope": map[string]int{ + "gav": 1, "jon": 2, "bob": 3, "abe": 4, "ian": 5, + "dan": 6, "hal": 7, "ed": 8, "col": 9, "fred": 10}, + "ivy": map[string]int{ + "ian": 1, "col": 2, "hal": 3, "gav": 4, "fred": 5, + "bob": 6, "abe": 7, "ed": 8, "jon": 9, "dan": 10}, + "jan": map[string]int{ + "ed": 1, "hal": 2, "gav": 3, "abe": 4, "bob": 5, + "jon": 6, "col": 7, "ian": 8, "fred": 9, "dan": 10}, +} + +func main() { + // get parings by Gale/Shapley algorithm + ps := pair(mPref, wPref) + // show results + fmt.Println("\nresult:") + if !validateStable(ps, mPref, wPref) { + return + } + // perturb + for { + i := 0 + var w2, m2 [2]string + for w, m := range ps { + w2[i] = w + m2[i] = m + if i == 1 { + break + } + i++ + } + fmt.Println("\nexchanging partners of", m2[0], "and", m2[1]) + ps[w2[0]] = m2[1] + ps[w2[1]] = m2[0] + // validate perturbed parings + if !validateStable(ps, mPref, wPref) { + return + } + // if those happened to be stable as well, perturb more + } +} + +type parings map[string]string // map[recipient]proposer (or map[w]m) + +// Pair implements the Gale/Shapley algorithm. +func pair(pPref proposers, rPref recipients) parings { + // code is destructive on the maps, so work with copies + pFree := proposers{} + for k, v := range pPref { + pFree[k] = append([]string{}, v...) + } + rFree := recipients{} + for k, v := range rPref { + rFree[k] = v + } + // struct only used in this function. + // preferences must be saved in case engagement is broken. + type save struct { + proposer string + pPref []string + rPref map[string]int + } + proposals := map[string]save{} // key is recipient (w) + + // WP pseudocode comments prefaced with WP: m is proposer, w is recipient. + // WP: while ∃ free man m who still has a woman w to propose to + for len(pFree) > 0 { // while there is a free proposer, + var proposer string + var ppref []string + for proposer, ppref = range pFree { + break // pick a proposer at random, whatever range delivers first. + } + if len(ppref) == 0 { + continue // if proposer has no possible recipients, skip + } + // WP: w = m's highest ranked such woman to whom he has not yet proposed + recipient := ppref[0] // highest ranged is first in list. + ppref = ppref[1:] // pop from list + var rpref map[string]int + var ok bool + // WP: if w is free + if rpref, ok = rFree[recipient]; ok { + // WP: (m, w) become engaged + // (common code follows if statement) + } else { + // WP: else some pair (m', w) already exists + s := proposals[recipient] // get proposal saved preferences + // WP: if w prefers m to m' + if s.rPref[proposer] < s.rPref[s.proposer] { + fmt.Println("engagement broken:", recipient, s.proposer) + // WP: m' becomes free + pFree[s.proposer] = s.pPref // return proposer to the map + // WP: (m, w) become engaged + rpref = s.rPref + // (common code follows if statement) + } else { + // WP: else (m', w) remain engaged + pFree[proposer] = ppref // update preferences in map + continue + } + } + fmt.Println("engagement:", recipient, proposer) + proposals[recipient] = save{proposer, ppref, rpref} + delete(pFree, proposer) + delete(rFree, recipient) + } + // construct return value + ps := parings{} + for recipient, s := range proposals { + ps[recipient] = s.proposer + } + return ps +} + +func validateStable(ps parings, pPref proposers, rPref recipients) bool { + for r, p := range ps { + fmt.Println(r, p) + } + for r, p := range ps { + for _, rp := range pPref[p] { + if rp == r { + break + } + rprefs := rPref[rp] + if rprefs[p] < rprefs[ps[rp]] { + fmt.Println("unstable.") + fmt.Printf("%s and %s would prefer each other over"+ + " their current pairings.\n", p, rp) + return false + } + } + } + fmt.Println("stable.") + return true +} diff --git a/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-1.groovy b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-1.groovy new file mode 100644 index 0000000000..9f3854aca8 --- /dev/null +++ b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-1.groovy @@ -0,0 +1,26 @@ +import static Man.* +import static Woman.* + +Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) { + Map<Woman,Man> engagedTo = new TreeMap() + List<Man> freeGuys = (Man.values()).clone() + while(freeGuys) { + Man thisGuy = freeGuys[0] + freeGuys -= thisGuy + List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] } + for(Woman girl in guyChoices) { + if(! engagedTo[girl]) { + engagedTo[girl] = thisGuy + break + } else { + Man thatGuy = engagedTo[girl] + if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) { + engagedTo[girl] = thisGuy + freeGuys << thatGuy + break + } + } + } + } + engagedTo +} diff --git a/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-2.groovy b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-2.groovy new file mode 100644 index 0000000000..cd07909275 --- /dev/null +++ b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-2.groovy @@ -0,0 +1,26 @@ +boolean isStable(Map<Woman,Man> matches, Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) { + matches.collect{ girl, guy -> + int guysRank = galsGuyRanking[girl][guy] + List<Man> sheLikesBetter = Man.values().findAll{ he -> galsGuyRanking[girl][he] > guysRank } + for(Man otherGuy : sheLikesBetter) { + Woman otherGuyFiancee = matches.find{ pair -> pair.value == otherGuy }.key + if(guysGalRanking[otherGuy][girl] > guysGalRanking[otherGuy][otherGuyFiancee]) { + println """O. M. G. ... ${otherGuy} likes ${girl} better than ${otherGuyFiancee}, and ${girl} likes ${otherGuy} better than ${guy}! + I am TOTALLY 'shipping ${girl} and ${otherGuy} now!""" + return false + } + } + + int galsRank = guysGalRanking[guy][girl] + List<Woman> heLikesBetter = Woman.values().findAll{ she -> guysGalRanking[guy][she] > galsRank } + for(Woman otherGal : heLikesBetter) { + Man otherGalFiance = matches[otherGal] + if(galsGuyRanking[otherGal][guy] > galsGuyRanking[otherGal][otherGalFiance]) { + println """O. M. G. ... ${otherGal} likes ${guy} better than ${otherGalFiance}, and ${guy} likes ${otherGal} better than ${girl}! + I am TOTALLY 'shipping ${guy} and ${otherGal} now!""" + return false + } + } + true + }.every() +} diff --git a/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-3.groovy b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-3.groovy new file mode 100644 index 0000000000..5fff3d00fa --- /dev/null +++ b/Task/Stable-marriage-problem/Groovy/stable-marriage-problem-3.groovy @@ -0,0 +1,56 @@ +enum Man { + abe, bob, col, dan, ed, fred, gav, hal, ian, jon +} + +enum Woman { + abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan +} + +Map<Man,Map<Woman,Integer>> mansWomanRanking = [ + (abe): [(abi):10, (eve):9, (cath):8, (ivy):7, (jan):6, (dee):5, (fay):4, (bea):3, (hope):2, (gay):1], + (bob): [(cath):10, (hope):9, (abi):8, (dee):7, (eve):6, (fay):5, (bea):4, (jan):3, (ivy):2, (gay):1], + (col): [(hope):10, (eve):9, (abi):8, (dee):7, (bea):6, (fay):5, (ivy):4, (gay):3, (cath):2, (jan):1], + (dan): [(ivy):10, (fay):9, (dee):8, (gay):7, (hope):6, (eve):5, (jan):4, (bea):3, (cath):2, (abi):1], + (ed): [(jan):10, (dee):9, (bea):8, (cath):7, (fay):6, (eve):5, (abi):4, (ivy):3, (hope):2, (gay):1], + (fred):[(bea):10, (abi):9, (dee):8, (gay):7, (eve):6, (ivy):5, (cath):4, (jan):3, (hope):2, (fay):1], + (gav): [(gay):10, (eve):9, (ivy):8, (bea):7, (cath):6, (abi):5, (dee):4, (hope):3, (jan):2, (fay):1], + (hal): [(abi):10, (eve):9, (hope):8, (fay):7, (ivy):6, (cath):5, (jan):4, (bea):3, (gay):2, (dee):1], + (ian): [(hope):10, (cath):9, (dee):8, (gay):7, (bea):6, (abi):5, (fay):4, (ivy):3, (jan):2, (eve):1], + (jon): [(abi):10, (fay):9, (jan):8, (gay):7, (eve):6, (bea):5, (dee):4, (cath):3, (ivy):2, (hope):1], +] + +Map<Woman,List<Man>> womansManRanking = [ + (abi): [(bob):10, (fred):9, (jon):8, (gav):7, (ian):6, (abe):5, (dan):4, (ed):3, (col):2, (hal):1], + (bea): [(bob):10, (abe):9, (col):8, (fred):7, (gav):6, (dan):5, (ian):4, (ed):3, (jon):2, (hal):1], + (cath):[(fred):10, (bob):9, (ed):8, (gav):7, (hal):6, (col):5, (ian):4, (abe):3, (dan):2, (jon):1], + (dee): [(fred):10, (jon):9, (col):8, (abe):7, (ian):6, (hal):5, (gav):4, (dan):3, (bob):2, (ed):1], + (eve): [(jon):10, (hal):9, (fred):8, (dan):7, (abe):6, (gav):5, (col):4, (ed):3, (ian):2, (bob):1], + (fay): [(bob):10, (abe):9, (ed):8, (ian):7, (jon):6, (dan):5, (fred):4, (gav):3, (col):2, (hal):1], + (gay): [(jon):10, (gav):9, (hal):8, (fred):7, (bob):6, (abe):5, (col):4, (ed):3, (dan):2, (ian):1], + (hope):[(gav):10, (jon):9, (bob):8, (abe):7, (ian):6, (dan):5, (hal):4, (ed):3, (col):2, (fred):1], + (ivy): [(ian):10, (col):9, (hal):8, (gav):7, (fred):6, (bob):5, (abe):4, (ed):3, (jon):2, (dan):1], + (jan): [(ed):10, (hal):9, (gav):8, (abe):7, (bob):6, (jon):5, (col):4, (ian):3, (fred):2, (dan):1], +] + +// STABLE test +Map<Woman,Man> matches = match(mansWomanRanking, womansManRanking) +matches.each { w, m -> + println "${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)" +} +assert matches.keySet() == Woman.values() as Set +assert matches.values() as Set == Man.values() as Set +println '' + +assert isStable(matches, mansWomanRanking, womansManRanking) + +// PERTURBED test +println 'Swapping partners now ...' +def temp = matches[abi] +matches[abi] = matches[bea] +matches[bea] = temp +matches.each { w, m -> + println "${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)" +} +println '' + +assert ! isStable(matches, mansWomanRanking, womansManRanking) diff --git a/Task/Stable-marriage-problem/Haskell/stable-marriage-problem.hs b/Task/Stable-marriage-problem/Haskell/stable-marriage-problem.hs new file mode 100644 index 0000000000..e0ea2d13be --- /dev/null +++ b/Task/Stable-marriage-problem/Haskell/stable-marriage-problem.hs @@ -0,0 +1,99 @@ +import Data.List +import Control.Monad +import Control.Arrow +import Data.Maybe + +mp = map ((head &&& tail). splitNames) + ["abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay", + "bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay", + "col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan", + "dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi", + "ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay", + "fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay", + "gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay", + "hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee", + "ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve", + "jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope"] + +fp = map ((head &&& tail). splitNames) + ["abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal", + "bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal", + "cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon", + "dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed", + "eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob", + "fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal", + "gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian", + "hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred", + "ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan", + "jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan"] + +splitNames = map (takeWhile(`notElem`",:")). words + +pref x y xs = fromJust (elemIndex x xs) < fromJust (elemIndex y xs) + +task ms fs = do + let + jos = fst $ unzip ms + + runGS es js ms = do + let (m:js') = js + (v:vm') = case lookup m ms of + Just xs -> xs + _ -> [] + vv = fromJust $ lookup v fs + m2 = case lookup v es of + Just e -> e + _ -> "" + ms1 = insert (m,vm') $ delete (m,v:vm') ms + + if null js then do + putStrLn "" + putStrLn "=== Couples ===" + return es + + else if null m2 then + do putStrLn $ v ++ " with " ++ m + runGS ( insert (v,m) es ) js' ms1 + + else if pref m m2 vv then + do putStrLn $ v ++ " dumped " ++ m2 ++ " for " ++ m + runGS ( insert (v,m) $ delete (v,m2) es ) (if not $ null vm' then js'++[m2] else js') ms1 + + else runGS es (if not $ null js' then js'++[m] else js') ms1 + + cs <- runGS [] jos ms + + mapM_ (\(f,m) -> putStrLn $ f ++ " with " ++ m ) cs + putStrLn "" + checkStab cs + + putStrLn "" + putStrLn "Introducing error: " + let [r1@(a,b), r2@(p,q)] = take 2 cs + r3 = (a,q) + r4 = (p,b) + errcs = insert r4. insert r3. delete r2 $ delete r1 cs + putStrLn $ "\tSwapping partners of " ++ a ++ " and " ++ p + putStrLn $ (\((a,b),(p,q)) -> "\t" ++ a ++ " is now with " ++ b ++ " and " ++ p ++ " with " ++ q) (r3,r4) + putStrLn "" + checkStab errcs + +checkStab es = do + let + fmt (a,b,c,d) = a ++ " and " ++ b ++ " like each other better than their current partners " ++ c ++ " and " ++ d + ies = uncurry(flip zip) $ unzip es -- es = [(fem,m)] & ies = [(m,fem)] + slb = map (\(f,m)-> (f,m, map (id &&& fromJust. flip lookup ies). fst.break(==m). fromJust $ lookup f fp) ) es + hlb = map (\(f,m)-> (m,f, map (id &&& fromJust. flip lookup es ). fst.break(==f). fromJust $ lookup m mp) ) es + tslb = concatMap (filter snd. (\(f,m,ls) -> + map (\(m2,f2) -> + ((f,m2,f2,m), pref f f2 $ fromJust $ lookup m2 mp)) ls)) slb + thlb = concatMap (filter snd. (\(m,f,ls) -> + map (\(f2,m2) -> + ((m,f2,m2,f), pref m m2 $ fromJust $ lookup f2 fp)) ls)) hlb + res = tslb ++ thlb + + if not $ null res then do + putStrLn "Marriages are unstable, e.g.:" + putStrLn.fmt.fst $ head res + + else putStrLn "Marriages are stable" diff --git a/Task/Stable-marriage-problem/Icon/stable-marriage-problem.icon b/Task/Stable-marriage-problem/Icon/stable-marriage-problem.icon new file mode 100644 index 0000000000..da21f75968 --- /dev/null +++ b/Task/Stable-marriage-problem/Icon/stable-marriage-problem.icon @@ -0,0 +1,113 @@ +link printf + +procedure main() + smd := IsStable(ShowEngaged(StableMatching(setup()))) + IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2]))) +end + +procedure index(L,x) #: return index of value or fail + return ( L[i := 1 to *L] === x, i) +end + +procedure ShowEngaged(smd) #: Show who's hooked up + printf("\nEngagements:\n") + every w := !smd.women do + printf("%s is engaged to %s\n",w,smd.engaged[w]) + return smd +end + +procedure Swap(smd,x0,x1) #: swap two couples by m or w + printf("\nSwapping %s and %s\n",x0,x1) + e := smd.engaged + e[x0] :=: e[x1] # swap partners + e[e[x0]] := e[e[x1]] + return smd +end + +procedure IsStable(smd) #: validate stability + stable := 1 # assumption + printf("\n") + every mp := smd.prefs[m := !smd.men] & # man & pref + w := mp[index(mp,smd.engaged[m])-1 to 1 by -1] do { # better choices + wp := smd.prefs[w] # her choices + if index(wp,smd.engaged[w]) > index(wp,m) then { + printf("Engagement of %s to %s is unstable.\n",w,m) + stable := &null # broken + } + } + if \stable then { + printf("Engagments are all stable.\n") + return smd + } +end + +procedure StableMatching(smd) #: match making + freemen := copy(smd.men) # Initialize all m memberof M + freewomen := set(smd.women) # ... and w memberof W to free + every (prefmen := table())[m := !freemen] := copy(smd.prefs[m]) + smd.engaged := engaged := table() + printf("\nMatching:\n") + while m := get(freemen) do { # next freeman + while w := get(prefmen[m]) do { # . with prpoposals left + if member(freewomen,w) then { # . . is she free? + engaged[m] := w # . . . (m, w) + engaged[w] := m + delete(freewomen,w) + printf("%s accepted %s's proposal\n",w,m) + break + } + else { # . . no, she's engaged + m0 := engaged[w] # to m0 + if index(smd.prefs[w],m) < index(smd.prefs[w],m0) then { + engaged[m] := w # (m, w) become engaged + engaged[w] := m + delete(freewomen,w) + engaged[m0] := &null # m' becomes free + put(freemen,m0) + printf("%s chose %s over %s\n",w,m,m0) + break + } + else next # she's happier as is + } + } + } + return smd +end + +record sm_data(men,women,prefs,engaged) #: everyones data + +procedure setup() #: setup everyones data + X := sm_data() + X.men := ["abe","bob","col","dan","ed","fred","gav","hal","ian","jon"] + X.women := ["abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"] + + if *X.men ~= *(M := set(X.men)) then runerr(500,X.men) # duplicate? + if *X.women ~= *(W := set(X.women)) then runerr(500,X.women) # duplicate? + if *(B := M**W) ~= 0 then runerr(500,B) # intersect? + + X.prefs := p := table() + + p["abe"] := ["abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay"] + p["bob"] := ["cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay"] + p["col"] := ["hope","eve","abi","dee","bea","fay","ivy","gay","cath","jan"] + p["dan"] := ["ivy","fay","dee","gay","hope","eve","jan","bea","cath","abi"] + p["ed"] := ["jan","dee","bea","cath","fay","eve","abi","ivy","hope","gay"] + p["fred"] := ["bea","abi","dee","gay","eve","ivy","cath","jan","hope","fay"] + p["gav"] := ["gay","eve","ivy","bea","cath","abi","dee","hope","jan","fay"] + p["hal"] := ["abi","eve","hope","fay","ivy","cath","jan","bea","gay","dee"] + p["ian"] := ["hope","cath","dee","gay","bea","abi","fay","ivy","jan","eve"] + p["jon"] := ["abi","fay","jan","gay","eve","bea","dee","cath","ivy","hope"] + + p["abi"] := ["bob","fred","jon","gav","ian","abe","dan","ed","col","hal"] + p["bea"] := ["bob","abe","col","fred","gav","dan","ian","ed","jon","hal"] + p["cath"] := ["fred","bob","ed","gav","hal","col","ian","abe","dan","jon"] + p["dee"] := ["fred","jon","col","abe","ian","hal","gav","dan","bob","ed"] + p["eve"] := ["jon","hal","fred","dan","abe","gav","col","ed","ian","bob"] + p["fay"] := ["bob","abe","ed","ian","jon","dan","fred","gav","col","hal"] + p["gay"] := ["jon","gav","hal","fred","bob","abe","col","ed","dan","ian"] + p["hope"] := ["gav","jon","bob","abe","ian","dan","hal","ed","col","fred"] + p["ivy"] := ["ian","col","hal","gav","fred","bob","abe","ed","jon","dan"] + p["jan"] := ["ed","hal","gav","abe","bob","jon","col","ian","fred","dan"] + + return X +end diff --git a/Task/Stable-marriage-problem/J/stable-marriage-problem-1.j b/Task/Stable-marriage-problem/J/stable-marriage-problem-1.j new file mode 100644 index 0000000000..cd90d54676 --- /dev/null +++ b/Task/Stable-marriage-problem/J/stable-marriage-problem-1.j @@ -0,0 +1,72 @@ +Mraw=: ;: ;._2 noun define -. ':,' + abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay + bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay + col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan + dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi + ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay + fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay + gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay + hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee + ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve + jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope +) + +Fraw=: ;: ;._2 noun define -. ':,' + abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal + bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal + cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon + dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed + eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob + fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal + gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian + hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred + ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan + jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan +) + +GuyNames=: {."1 Mraw +GalNames=: {."1 Fraw + +Mprefs=: GalNames i. }."1 Mraw +Fprefs=: GuyNames i. }."1 Fraw + +propose=: dyad define + engaged=. x + 'guy gal'=. y + if. gal e. engaged do. + fiance=. engaged i. gal + if. guy <&((gal{Fprefs)&i.) fiance do. + engaged=. gal guy} _ fiance} engaged + end. + else. + engaged=. gal guy} engaged + end. + engaged +) + +matchMake=: monad define + engaged=. _"0 GuyNames NB. initially no one is engaged + fallback=. 0"0 engaged NB. and each guy will first propose to his favorite + whilst. _ e. engaged do. + for_guy. I. _ = engaged do. + next=. guy{fallback + gal=. (<guy,next){Mprefs + engaged=. engaged propose guy,gal + fallback=. (next+1) guy} fallback + end. + end. + GuyNames,:engaged{GalNames +) + +checkStable=: monad define + 'guys gals'=. (GuyNames,:GalNames) i."1 y + satisfied=. ] >: (<0 1) |: ] + guyshappy=. satisfied (guys{Mprefs) i."1 0/ gals + galshappy=. satisfied (gals{Fprefs) i."1 0/ guys + unstable=. 4$.$.-. guyshappy +. |:galshappy + if. bad=. 0 < #unstable do. + smoutput 'Engagements preferred by both members to their current ones:' + smoutput y {~"1 0"2 1 unstable + end. + assert-.bad +) diff --git a/Task/Stable-marriage-problem/J/stable-marriage-problem-2.j b/Task/Stable-marriage-problem/J/stable-marriage-problem-2.j new file mode 100644 index 0000000000..1ade16bd69 --- /dev/null +++ b/Task/Stable-marriage-problem/J/stable-marriage-problem-2.j @@ -0,0 +1,6 @@ + matchMake '' +┌───┬────┬───┬───┬───┬────┬───┬───┬────┬───┐ +│abe│bob │col│dan│ed │fred│gav│hal│ian │jon│ +├───┼────┼───┼───┼───┼────┼───┼───┼────┼───┤ +│ivy│cath│dee│fay│jan│bea │gay│eve│hope│abi│ +└───┴────┴───┴───┴───┴────┴───┴───┴────┴───┘ diff --git a/Task/Stable-marriage-problem/J/stable-marriage-problem-3.j b/Task/Stable-marriage-problem/J/stable-marriage-problem-3.j new file mode 100644 index 0000000000..dc63ead7fe --- /dev/null +++ b/Task/Stable-marriage-problem/J/stable-marriage-problem-3.j @@ -0,0 +1,19 @@ + 0 105 A."_1 matchMake '' NB. swap abi and bea +┌───┬────┬───┬───┬───┬────┬───┬───┬────┬───┐ +│abe│bob │col│dan│ed │fred│gav│hal│ian │jon│ +├───┼────┼───┼───┼───┼────┼───┼───┼────┼───┤ +│ivy│cath│dee│fay│jan│abi │gay│eve│hope│bea│ +└───┴────┴───┴───┴───┴────┴───┴───┴────┴───┘ + checkStable 0 105 A."_1 matchMake '' +Engagements preferred by both members to their current ones: +┌────┬───┐ +│fred│bea│ +├────┼───┤ +│jon │fay│ +├────┼───┤ +│jon │gay│ +├────┼───┤ +│jon │eve│ +└────┴───┘ +|assertion failure: assert +| assert-.bad diff --git a/Task/Stable-marriage-problem/Java/stable-marriage-problem.java b/Task/Stable-marriage-problem/Java/stable-marriage-problem.java new file mode 100644 index 0000000000..107372d15b --- /dev/null +++ b/Task/Stable-marriage-problem/Java/stable-marriage-problem.java @@ -0,0 +1,180 @@ +import java.util.*; + +public class Stable { + static List<String> guys = Arrays.asList( + new String[]{ + "abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"}); + static List<String> girls = Arrays.asList( + new String[]{ + "abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"}); + static Map<String, List<String>> guyPrefers = + new HashMap<String, List<String>>(){{ + put("abe", + Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay", + "bea", "hope", "gay")); + put("bob", + Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea", + "jan", "ivy", "gay")); + put("col", + Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy", + "gay", "cath", "jan")); + put("dan", + Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan", + "bea", "cath", "abi")); + put("ed", + Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi", + "ivy", "hope", "gay")); + put("fred", + Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath", + "jan", "hope", "fay")); + put("gav", + Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee", + "hope", "jan", "fay")); + put("hal", + Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan", + "bea", "gay", "dee")); + put("ian", + Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay", + "ivy", "jan", "eve")); + put("jon", + Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee", + "cath", "ivy", "hope")); + }}; + static Map<String, List<String>> girlPrefers = + new HashMap<String, List<String>>(){{ + put("abi", + Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan", + "ed", "col", "hal")); + put("bea", + Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian", + "ed", "jon", "hal")); + put("cath", + Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian", + "abe", "dan", "jon")); + put("dee", + Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav", + "dan", "bob", "ed")); + put("eve", + Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col", + "ed", "ian", "bob")); + put("fay", + Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred", + "gav", "col", "hal")); + put("gay", + Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col", + "ed", "dan", "ian")); + put("hope", + Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal", + "ed", "col", "fred")); + put("ivy", + Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe", + "ed", "jon", "dan")); + put("jan", + Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col", + "ian", "fred", "dan")); + }}; + public static void main(String[] args){ + Map<String, String> matches = match(guys, guyPrefers, girlPrefers); + for(Map.Entry<String, String> couple:matches.entrySet()){ + System.out.println( + couple.getKey() + " is engaged to " + couple.getValue()); + } + if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){ + System.out.println("Marriages are stable"); + }else{ + System.out.println("Marriages are unstable"); + } + String tmp = matches.get(girls.get(0)); + matches.put(girls.get(0), matches.get(girls.get(1))); + matches.put(girls.get(1), tmp); + System.out.println( + girls.get(0) +" and " + girls.get(1) + " have switched partners"); + if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){ + System.out.println("Marriages are stable"); + }else{ + System.out.println("Marriages are unstable"); + } + } + + private static Map<String, String> match(List<String> guys, + Map<String, List<String>> guyPrefers, + Map<String, List<String>> girlPrefers){ + Map<String, String> engagedTo = new TreeMap<String, String>(); + List<String> freeGuys = new LinkedList<String>(); + freeGuys.addAll(guys); + while(!freeGuys.isEmpty()){ + String thisGuy = freeGuys.remove(0); //get a load of THIS guy + List<String> thisGuyPrefers = guyPrefers.get(thisGuy); + for(String girl:thisGuyPrefers){ + if(engagedTo.get(girl) == null){//girl is free + engagedTo.put(girl, thisGuy); //awww + break; + }else{ + String otherGuy = engagedTo.get(girl); + List<String> thisGirlPrefers = girlPrefers.get(girl); + if(thisGirlPrefers.indexOf(thisGuy) < + thisGirlPrefers.indexOf(otherGuy)){ + //this girl prefers this guy to the guy she's engaged to + engagedTo.put(girl, thisGuy); + freeGuys.add(otherGuy); + break; + }//else no change...keep looking for this guy + } + } + } + return engagedTo; + } + + private static boolean checkMatches(List<String> guys, List<String> girls, + Map<String, String> matches, Map<String, List<String>> guyPrefers, + Map<String, List<String>> girlPrefers) { + if(!matches.keySet().containsAll(girls)){ + return false; + } + + if(!matches.values().containsAll(guys)){ + return false; + } + + Map<String, String> invertedMatches = new TreeMap<String, String>(); + for(Map.Entry<String, String> couple:matches.entrySet()){ + invertedMatches.put(couple.getValue(), couple.getKey()); + } + + for(Map.Entry<String, String> couple:matches.entrySet()){ + List<String> shePrefers = girlPrefers.get(couple.getKey()); + List<String> sheLikesBetter = new LinkedList<String>(); + sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue()))); + List<String> hePrefers = guyPrefers.get(couple.getValue()); + List<String> heLikesBetter = new LinkedList<String>(); + heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey()))); + + for(String guy : sheLikesBetter){ + String guysFinace = invertedMatches.get(guy); + List<String> thisGuyPrefers = guyPrefers.get(guy); + if(thisGuyPrefers.indexOf(guysFinace) > + thisGuyPrefers.indexOf(couple.getKey())){ + System.out.printf("%s likes %s better than %s and %s" + + " likes %s better than their current partner\n", + couple.getKey(), guy, couple.getValue(), + guy, couple.getKey()); + return false; + } + } + + for(String girl : heLikesBetter){ + String girlsFinace = matches.get(girl); + List<String> thisGirlPrefers = girlPrefers.get(girl); + if(thisGirlPrefers.indexOf(girlsFinace) > + thisGirlPrefers.indexOf(couple.getValue())){ + System.out.printf("%s likes %s better than %s and %s" + + " likes %s better than their current partner\n", + couple.getValue(), girl, couple.getKey(), + girl, couple.getValue()); + return false; + } + } + } + return true; + } +} diff --git a/Task/Stable-marriage-problem/JavaScript/stable-marriage-problem.js b/Task/Stable-marriage-problem/JavaScript/stable-marriage-problem.js new file mode 100644 index 0000000000..a0d82b5f5f --- /dev/null +++ b/Task/Stable-marriage-problem/JavaScript/stable-marriage-problem.js @@ -0,0 +1,121 @@ +function Person(name) { + + var candidateIndex = 0; + + this.name = name; + this.fiance = null; + this.candidates = []; + + this.rank = function(p) { + for (i = 0; i < this.candidates.length; i++) + if (this.candidates[i] === p) return i; + return this.candidates.length + 1; + } + + this.prefers = function(p) { + return this.rank(p) < this.rank(this.fiance); + } + + this.nextCandidate = function() { + if (candidateIndex >= this.candidates.length) return null; + return this.candidates[candidateIndex++]; + } + + this.engageTo = function(p) { + if (p.fiance) p.fiance.fiance = null; + p.fiance = this; + if (this.fiance) this.fiance.fiance = null; + this.fiance = p; + } + + this.swapWith = function(p) { + console.log("%s & %s swap partners", this.name, p.name); + var thisFiance = this.fiance; + var pFiance = p.fiance; + this.engageTo(pFiance); + p.engageTo(thisFiance); + } +} + +function isStable(guys, gals) { + for (var i = 0; i < guys.length; i++) + for (var j = 0; j < gals.length; j++) + if (guys[i].prefers(gals[j]) && gals[j].prefers(guys[i])) + return false; + return true; +} + +function engageEveryone(guys) { + var done; + do { + done = true; + for (var i = 0; i < guys.length; i++) { + var guy = guys[i]; + if (!guy.fiance) { + done = false; + var gal = guy.nextCandidate(); + if (!gal.fiance || gal.prefers(guy)) + guy.engageTo(gal); + } + } + } while (!done); +} + +function doMarriage() { + + var abe = new Person("Abe"); + var bob = new Person("Bob"); + var col = new Person("Col"); + var dan = new Person("Dan"); + var ed = new Person("Ed"); + var fred = new Person("Fred"); + var gav = new Person("Gav"); + var hal = new Person("Hal"); + var ian = new Person("Ian"); + var jon = new Person("Jon"); + var abi = new Person("Abi"); + var bea = new Person("Bea"); + var cath = new Person("Cath"); + var dee = new Person("Dee"); + var eve = new Person("Eve"); + var fay = new Person("Fay"); + var gay = new Person("Gay"); + var hope = new Person("Hope"); + var ivy = new Person("Ivy"); + var jan = new Person("Jan"); + + abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]; + bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]; + col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]; + dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]; + ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]; + fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]; + gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]; + hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]; + ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]; + jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]; + abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]; + bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]; + cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]; + dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]; + eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]; + fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]; + gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]; + hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]; + ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]; + jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]; + + var guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]; + var gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]; + + engageEveryone(guys); + + for (var i = 0; i < guys.length; i++) { + console.log("%s is engaged to %s", guys[i].name, guys[i].fiance.name); + } + console.log("Stable = %s", isStable(guys, gals) ? "Yes" : "No"); + jon.swapWith(fred); + console.log("Stable = %s", isStable(guys, gals) ? "Yes" : "No"); +} + +doMarriage(); diff --git a/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua b/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua new file mode 100644 index 0000000000..a4fbe45a2a --- /dev/null +++ b/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua @@ -0,0 +1,106 @@ +local men = +{ +abe={'abi','eve','cath','ivy','jan','dee','fay','bea','hope','gay'}, +bob={'cath','hope','abi','dee','eve','fay','bea','jan','ivy','gay'}, +col={'hope','eve','abi','dee','bea','fay','ivy','gay','cath','jan'}, +dan={'ivy','fay','dee','gay','hope','eve','jan','bea','cath','abi'}, +ed={'jan','dee','bea','cath','fay','eve','abi','ivy','hope','gay'}, +fred={'bea','abi','dee','gay','eve','ivy','cath','jan','hope','fay'}, +gav={'gay','eve','ivy','bea','cath','abi','dee','hope','jan','fay'}, +hal={'abi','eve','hope','fay','ivy','cath','jan','bea','gay','dee'}, +ian={'hope','cath','dee','gay','bea','abi','fay','ivy','jan','eve'}, +jon={'abi','fay','jan','gay','eve','bea','dee','cath','ivy','hope'} +} + +local women = +{ +abi={'bob','fred','jon','gav','ian','abe','dan','ed','col','hal'}, +bea={'bob','abe','col','fred','gav','dan','ian','ed','jon','hal'}, +cath={'fred','bob','ed','gav','hal','col','ian','abe','dan','jon'}, +dee={'fred','jon','col','abe','ian','hal','gav','dan','bob','ed'}, +eve={'jon','hal','fred','dan','abe','gav','col','ed','ian','bob'}, +fay={'bob','abe','ed','ian','jon','dan','fred','gav','col','hal'}, +gay={'jon','gav','hal','fred','bob','abe','col','ed','dan','ian'}, +hope={'gav','jon','bob','abe','ian','dan','hal','ed','col','fred'}, +ivy={'ian','col','hal','gav','fred','bob','abe','ed','jon','dan'} +} + +local engagements = {} + +local singlemen = 0 + +local function single(name) + + local partner = engagements[name] + + if partner then + engagements[name] = nil + engagements[partner] = nil + end + + + if men[name] then + singlemen = singlemen + 1 + end +end + +for guys,_ in pairs(men) do single(guys) end +for ladies,_ in pairs(women) do single(ladies) end --that is, ahem, ALL the single ladies. + + +local function engage(man,woman) + engagements[man] = woman + engagements[woman] = man + singlemen = singlemen - 1 +end + + +local attemptedEngagementsByMan = {} +for name,list in pairs(men) do + attemptedEngagementsByMan[name] = {} +end + + +while singlemen > 0 do + local man + local woman + + --get a single man + for singleman,prefs in pairs(men) do + if not engagements[singleman] then + man = singleman; break + end + end + + + --get his most preferred untried lady + local myAttempts = attemptedEngagementsByMan[man] + for i,lady in ipairs(men[man]) do + if not myAttempts[lady] then + woman = lady; break + end + end + + + --propose + myAttempts[woman] = true + local totalJerk = engagements[woman] + if not totalJerk then + engage(man,woman) + else + for i,herPreference in ipairs(women[woman]) do + if herPreference == man then + single(totalJerk) + single(woman) + engage(man,woman) + break --leaves the jerk at the altar! + elseif herPreference == totalJerk then + break --shot down + end + end + end +end + +for name,_ in pairs(men) do + print(name, " liked it so he put a ring on ", engagements[name]) +end diff --git a/Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ocaml b/Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ocaml new file mode 100644 index 0000000000..948a22deb3 --- /dev/null +++ b/Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ocaml @@ -0,0 +1,158 @@ +let men = [ + "abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"]; + "bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"]; + "col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"]; + "dan", ["ivy";"fay";"dee";"gay";"hope";"eve";"jan";"bea";"cath";"abi"]; + "ed", ["jan";"dee";"bea";"cath";"fay";"eve";"abi";"ivy";"hope";"gay"]; + "fred", ["bea";"abi";"dee";"gay";"eve";"ivy";"cath";"jan";"hope";"fay"]; + "gav", ["gay";"eve";"ivy";"bea";"cath";"abi";"dee";"hope";"jan";"fay"]; + "hal", ["abi";"eve";"hope";"fay";"ivy";"cath";"jan";"bea";"gay";"dee"]; + "ian", ["hope";"cath";"dee";"gay";"bea";"abi";"fay";"ivy";"jan";"eve"]; + "jon", ["abi";"fay";"jan";"gay";"eve";"bea";"dee";"cath";"ivy";"hope"]; +] + +let women = [ + "abi", ["bob";"fred";"jon";"gav";"ian";"abe";"dan";"ed";"col";"hal"]; + "bea", ["bob";"abe";"col";"fred";"gav";"dan";"ian";"ed";"jon";"hal"]; + "cath", ["fred";"bob";"ed";"gav";"hal";"col";"ian";"abe";"dan";"jon"]; + "dee", ["fred";"jon";"col";"abe";"ian";"hal";"gav";"dan";"bob";"ed"]; + "eve", ["jon";"hal";"fred";"dan";"abe";"gav";"col";"ed";"ian";"bob"]; + "fay", ["bob";"abe";"ed";"ian";"jon";"dan";"fred";"gav";"col";"hal"]; + "gay", ["jon";"gav";"hal";"fred";"bob";"abe";"col";"ed";"dan";"ian"]; + "hope", ["gav";"jon";"bob";"abe";"ian";"dan";"hal";"ed";"col";"fred"]; + "ivy", ["ian";"col";"hal";"gav";"fred";"bob";"abe";"ed";"jon";"dan"]; + "jan", ["ed";"hal";"gav";"abe";"bob";"jon";"col";"ian";"fred";"dan"]; +] + +type woman_name = string +type man_name = string + +type man = + { m_name: man_name; + mutable free: bool; + women_rank: woman_name list; + has_proposed: (woman_name, unit) Hashtbl.t (* a set *) + } + +type woman = + { w_name: woman_name; + men_rank: man_name list; + mutable engaged: man_name option + } + + +let prefers w m1 m2 = + (* returns true if w has a lower (better) rank for m1 than m2 *) + let rec aux = function + | [] -> invalid_arg "rank_cmp" + | x::_ when x = m1 -> true + | x::_ when x = m2 -> false + | _::xs -> aux xs + in + aux w.men_rank + +let take_while f lst = + let rec aux acc = function + | x::xs when f x -> aux (x::acc) xs + | _ -> List.rev acc + in + aux [] lst + +let more_ranked_than name = + take_while ((<>) name) + +let build_structs ~men ~women = + List.map (fun (name, rank) -> + { m_name = name; + women_rank = rank; + free = true; + has_proposed = Hashtbl.create 42 } + ) men, + List.map (fun (name, rank) -> + { w_name = name; + men_rank = rank; + engaged = None } + ) women + + +let _stable_matching ms ws = + let men_by_name = Hashtbl.create 42 in + List.iter (fun m -> Hashtbl.add men_by_name m.m_name m) ms; + let women_by_name = Hashtbl.create 42 in + List.iter (fun w -> Hashtbl.add women_by_name w.w_name w) ws; + try + while true do + (*TODO free men who still has some w to propose to *) + let m = List.find (fun m -> m.free) ms in + (* highest ranked woman who the man has not proposed to yet *) + let w_name = + List.find (fun w -> not (Hashtbl.mem m.has_proposed w)) m.women_rank in + Hashtbl.add m.has_proposed w_name (); + let w = Hashtbl.find women_by_name w_name in + match w.engaged with + | None -> (* w is free *) + (* (m, w) become engaged *) + w.engaged <- Some m.m_name; + m.free <- false + | Some m'_name -> (* some pair (m', w) already exists *) + if prefers w m.m_name m'_name + then begin (* w prefers m to m' *) + w.engaged <- Some m.m_name; + let m' = Hashtbl.find men_by_name m'_name in + m'.free <- true; + m.free <- false + end + done; + assert false + with Not_found -> () + + +let stable_matching ~men ~women = + let ms, ws = build_structs ~men ~women in + _stable_matching ms ws; + let some = function Some v -> v | None -> "" in + List.map (fun w -> w.w_name, some w.engaged) ws + + +let is_stable ~men ~women eng = + let ms, ws = build_structs ~men ~women in + not (List.exists (fun (wn, mn) -> + let m = List.find (fun m -> m.m_name = mn) ms in + let prefered_women = more_ranked_than wn m.women_rank in + List.exists (fun pref_w -> + let w = List.find (fun w -> w.w_name = pref_w) ws in + let eng_m = List.assoc pref_w eng in + let prefered_men = more_ranked_than eng_m w.men_rank in + List.mem m.m_name prefered_men (* exists unstable engagement *) + ) prefered_women + ) eng) + + +let perturb_engagements eng = + Random.self_init(); + let eng = Array.of_list eng in + let len = Array.length eng in + for n = 1 to 3 do + let i = Random.int len + and j = Random.int len in + let w1, m1 = eng.(i) + and w2, m2 = eng.(j) in + eng.(i) <- (w1, m2); + eng.(j) <- (w2, m1); + done; + Array.to_list eng + + +let print engs = + List.iter (fun (w,m) -> + Printf.printf " %4s is engaged with %s\n" w m) engs; + Printf.printf "# Engagements %s stable\n" + (if is_stable ~men ~women engs then "are" else "are not") + +let () = + let engagements = stable_matching ~men ~women in + print engagements; + print_endline "========================"; + let engagements = perturb_engagements engagements in + print engagements; +;; diff --git a/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m b/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m new file mode 100644 index 0000000000..5183b06232 --- /dev/null +++ b/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m @@ -0,0 +1,137 @@ +//-------------------------------------------------------------------- +// Person class + +@interface Person : NSObject { + NSUInteger _candidateIndex; +} +@property (nonatomic, strong) NSString* name; +@property (nonatomic, strong) NSArray* prefs; +@property (nonatomic, weak) Person* fiance; +@end + +@implementation Person ++ (Person *)named:(NSString *)name { + return [[Person alloc] initWithName:name]; +} +- (id)initWithName:(NSString *)name { + if ((self = [super init])) { + _name = name; + _prefs = nil; + _fiance = nil; + _candidateIndex = 0; + } + return self; +} +- (BOOL)prefers:(Person *)p { + return [_prefs indexOfObject:p] < [_prefs indexOfObject:_fiance]; +} +- (Person *)nextCandidateNotYetProposedTo { + if (_candidateIndex >= _prefs.count) return nil; + return _prefs[_candidateIndex++]; +} +- (void)engageTo:(Person *)p { + if (p.fiance) p.fiance.fiance = nil; + p.fiance = self; + if (self.fiance) self.fiance.fiance = nil; + self.fiance = p; +} +- (NSString *)description { + return _name; +} +@end + +//-------------------------------------------------------------------- + +BOOL isStable(NSArray *men) { + NSArray *women = ((Person *)men[0]).prefs; + for (Person *guy in men) { + for (Person *gal in women) { + if ([guy prefers:gal] && [gal prefers:guy]) + return NO; + } + } + return YES; +} + +//-------------------------------------------------------------------- + +void doMarriage() { + Person *abe = [Person named:@"abe"]; + Person *bob = [Person named:@"bob"]; + Person *col = [Person named:@"col"]; + Person *dan = [Person named:@"dan"]; + Person *ed = [Person named:@"ed"]; + Person *fred = [Person named:@"fred"]; + Person *gav = [Person named:@"gav"]; + Person *hal = [Person named:@"hal"]; + Person *ian = [Person named:@"ian"]; + Person *jon = [Person named:@"jon"]; + Person *abi = [Person named:@"abi"]; + Person *bea = [Person named:@"bea"]; + Person *cath = [Person named:@"cath"]; + Person *dee = [Person named:@"dee"]; + Person *eve = [Person named:@"eve"]; + Person *fay = [Person named:@"fay"]; + Person *gay = [Person named:@"gay"]; + Person *hope = [Person named:@"hope"]; + Person *ivy = [Person named:@"ivy"]; + Person *jan = [Person named:@"jan"]; + + abe.prefs = @[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ]; + bob.prefs = @[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ]; + col.prefs = @[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ]; + dan.prefs = @[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ]; + ed.prefs = @[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ]; + fred.prefs = @[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ]; + gav.prefs = @[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ]; + hal.prefs = @[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ]; + ian.prefs = @[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ]; + jon.prefs = @[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ]; + abi.prefs = @[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ]; + bea.prefs = @[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ]; + cath.prefs = @[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ]; + dee.prefs = @[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ]; + eve.prefs = @[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ]; + fay.prefs = @[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ]; + gay.prefs = @[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ]; + hope.prefs = @[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ]; + ivy.prefs = @[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ]; + jan.prefs = @[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ]; + + NSArray *men = [NSArray arrayWithArray:abi.prefs]; + + NSUInteger freeMenCount = men.count; + while (freeMenCount > 0) { + for (Person *guy in men) { + if (guy.fiance == nil) { + Person *gal = [guy nextCandidateNotYetProposedTo]; + if (gal.fiance == nil) { + [guy engageTo:gal]; + freeMenCount--; + } else if ([gal prefers:guy]) { + [guy engageTo:gal]; + } + } + } + } + + for (Person *guy in men) { + printf("%s is engaged to %s\n", [guy.name UTF8String], [guy.fiance.name UTF8String]); + } + printf("Stable = %d\n", (int)isStable(men)); + + printf("\nSwitching fred & jon's partners\n"); + [fred engageTo:abi]; + [jon engageTo:bea]; + printf("Stable = %d\n", (int)isStable(men)); +} + +//-------------------------------------------------------------------- + +int main(int argc, const char * argv[]) +{ + @autoreleasepool { + doMarriage(); + } + return 0; +} diff --git a/Task/Stable-marriage-problem/Perl/stable-marriage-problem.pl b/Task/Stable-marriage-problem/Perl/stable-marriage-problem.pl new file mode 100644 index 0000000000..1873331de4 --- /dev/null +++ b/Task/Stable-marriage-problem/Perl/stable-marriage-problem.pl @@ -0,0 +1,117 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use feature qw/say/; +use List::Util qw(first); + +my %Likes = ( + M => { + abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /], + bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /], + col => [qw/ hope eve abi dee bea fay ivy gay cath jan /], + dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /], + ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /], + fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /], + gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /], + hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /], + ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /], + jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /], + }, + + W => { + abi => [qw/ bob fred jon gav ian abe dan ed col hal /], + bea => [qw/ bob abe col fred gav dan ian ed jon hal /], + cath => [qw/ fred bob ed gav hal col ian abe dan jon /], + dee => [qw/ fred jon col abe ian hal gav dan bob ed /], + eve => [qw/ jon hal fred dan abe gav col ed ian bob /], + fay => [qw/ bob abe ed ian jon dan fred gav col hal /], + gay => [qw/ jon gav hal fred bob abe col ed dan ian /], + hope => [qw/ gav jon bob abe ian dan hal ed col fred /], + ivy => [qw/ ian col hal gav fred bob abe ed jon dan /], + jan => [qw/ ed hal gav abe bob jon col ian fred dan /], + }, +); + +my %Engaged; +my %Proposed; + +match_them(); +check_stability(); +perturb(); +check_stability(); + +sub match_them { + say 'Matchmaking:'; + while(my $man = unmatched_man()) { + my $woman = preferred_choice($man); + $Proposed{$man}{$woman} = 1; + if(! $Engaged{W}{$woman}) { + engage($man, $woman); + say "\t$woman and $man"; + } + else { + if(woman_prefers($woman, $man)) { + my $engaged_man = $Engaged{W}{$woman}; + engage($man, $woman); + undef $Engaged{M}{$engaged_man}; + say "\t$woman dumped $engaged_man for $man"; + } + } + } +} + +sub check_stability { + say 'Stablility:'; + my $stable = 1; + foreach my $m (men()) { + foreach my $w (women()) { + if(man_prefers($m, $w) && woman_prefers($w, $m)) { + say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}"; + $stable = 0; + } + } + } + if($stable) { + say "\t(all marriages stable)"; + } +} + +sub unmatched_man { + return first { ! $Engaged{M}{$_} } men(); +} + +sub preferred_choice { + my $man = shift; + return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} }; +} + +sub engage { + my ($man, $woman) = @_; + $Engaged{W}{$woman} = $man; + $Engaged{M}{$man} = $woman; +} + +sub prefers { + my $sex = shift; + return sub { + my ($person, $prospect) = @_; + + my $choices = join ' ', @{ $Likes{$sex}{$person} }; + return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person}); + } +} + +BEGIN { + *woman_prefers = prefers('W'); + *man_prefers = prefers('M'); +} + +sub perturb { + say 'Perturb:'; + say "\tengage abi with fred and bea with jon"; + engage('fred' => 'abi'); + engage('jon' => 'bea'); +} + +sub men { keys %{ $Likes{M} } } +sub women { keys %{ $Likes{W} } } diff --git a/Task/Stable-marriage-problem/PicoLisp/stable-marriage-problem.l b/Task/Stable-marriage-problem/PicoLisp/stable-marriage-problem.l new file mode 100644 index 0000000000..d52d8b161d --- /dev/null +++ b/Task/Stable-marriage-problem/PicoLisp/stable-marriage-problem.l @@ -0,0 +1,65 @@ +(setq + *Boys (list + (de abe abi eve cath ivy jan dee fay bea hope gay) + (de bob cath hope abi dee eve fay bea jan ivy gay) + (de col hope eve abi dee bea fay ivy gay cath jan) + (de dan ivy fay dee gay hope eve jan bea cath abi) + (de ed jan dee bea cath fay eve abi ivy hope gay) + (de fred bea abi dee gay eve ivy cath jan hope fay) + (de gav gay eve ivy bea cath abi dee hope jan fay) + (de hal abi eve hope fay ivy cath jan bea gay dee) + (de ian hope cath dee gay bea abi fay ivy jan eve) + (de jon abi fay jan gay eve bea dee cath ivy hope) ) + *Girls (list + (de bi bob fred jon gav ian abe dan ed col hal) + (de bea bob abe col fred gav dan ian ed jon hal) + (de cath fred bob ed gav hal col ian abe dan jon) + (de dee fred jon col abe ian hal gav dan bob ed) + (de eve jon hal fred dan abe gav col ed ian bob) + (de fay bob abe ed ian jon dan fred gav col hal) + (de gay jon gav hal fred bob abe col ed dan ian) + (de hope gav jon bob abe ian dan hal ed col fred) + (de ivy ian col hal gav fred bob abe ed jon dan) + (de jan ed hal gav abe bob jon col ian fred dan) ) + *Couples NIL ) + +(bind *Boys + (while + (find + '((Boy) (and (val Boy) (not (asoq Boy *Couples)))) + *Boys ) + (let (Boy @ Girl (pop Boy) Pair (find '((P) (== Girl (cdr P))) *Couples)) + (nond + (Pair (push '*Couples (cons Boy Girl))) # Girl is free + ((memq Boy (memq (car Pair) (val Girl))) # Girl prefers Boy + (set Pair Boy) ) ) ) ) ) + +(for Pair *Couples + (prinl (cdr Pair) " is engaged to " (car Pair)) ) + +(de checkCouples () + (unless + (filter + '((Pair) + (let (Boy (car Pair) Girl (cdr Pair)) + (find + '((B) + (and + (memq Boy (cdr (memq B (val Girl)))) # Girl prefers B + (memq + (cdr (asoq B *Couples)) # and B prefers Girl + (cdr (memq Girl (val B))) ) + (prinl + Girl " likes " B " better than " Boy " and " + B " likes " Girl " better than " + (cdr (asoq B *Couples)) ) ) ) + (val Girl) ) ) ) + *Couples ) + (prinl "All marriages are stable") ) ) + +(checkCouples) +(prinl) +(prinl "Engage fred with abi and jon with bea") +(con (asoq 'fred *Couples) 'abi) +(con (asoq 'jon *Couples) 'bea) +(checkCouples) diff --git a/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-1.pro b/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-1.pro new file mode 100644 index 0000000000..013fc4bb60 --- /dev/null +++ b/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-1.pro @@ -0,0 +1,273 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% facts +prefere(abe,[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]). +prefere( bob,[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]). +prefere( col,[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]). +prefere( dan,[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]). +prefere( ed,[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]). +prefere( fred,[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]). +prefere( gav,[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]). +prefere( hal,[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]). +prefere( ian,[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]). +prefere( jon,[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]). + +prefere( abi,[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal]). +prefere( bea,[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal]). +prefere( cath,[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon]). +prefere( dee,[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed]). +prefere( eve,[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob]). +prefere( fay,[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal]). +prefere( gay,[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian]). +prefere( hope,[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred]). +prefere( ivy,[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan]). +prefere( jan,[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan]). + + +man(abe). +man(bob). +man(col). +man(dan). +man(ed). +man(fred). +man(gav). +man(hal). +man(ian). +man(jon). + +woman(abi). +woman(bea). +woman(cath). +woman(dee). +woman(eve). +woman(fay). +woman(gay). +woman(hope). +woman(ivy). +woman(jan). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% rules + +stable_mariage :- + new(LstMan, chain), + forall(man(X), + ( prefere(X, Lst), + new(P, man(X, Lst)), + send(LstMan, append, P))), + + new(LstWoman, chain), + forall(woman(X), + ( prefere(X, Lst), + new(P, woman(X, Lst)), + send(LstWoman, append, P))), + send(LstMan, for_all, message(@arg1, init_liste, LstWoman)), + send(LstWoman, for_all, message(@arg1, init_liste, LstMan)), + + round(LstMan, LstWoman), + new(LstCouple, chain), + % creation of the couple. + send(LstWoman, for_all, and(message(@prolog, create_couple, @arg1, LstCouple), + message(@pce, write_ln, @arg1?name, with, @arg1?elu?name))), + + nl, + + % test of the stability of couples + stability(LstCouple), + nl, + + % Perturbation of couples + get(LstCouple, size, Len), + get_two_random_couples(Len, V1, V2), + + get(LstCouple, nth0, V1, C1), + get(LstCouple, nth0, V2, C2), + new(NC1, tuple(C1?first, C2?second)), + new(NC2, tuple(C2?first, C1?second)), + send(LstCouple, nth0, V1, NC1), + send(LstCouple, nth0, V2, NC2), + + send(@pce, write_ln, 'perturbation of couples'), + send(@pce, write_ln, NC1?second, with, NC1?first), + send(@pce, write_ln, NC2?second, with, NC2?first), + nl, + + stability(LstCouple). + +get_two_random_couples(Len, C1, C2) :- + C1 is random(Len), + repeat, + C2 is random(Len), + C1 \= C2. + +create_couple(Woman, LstCouple ) :- + send(LstCouple, append, new(_, tuple(Woman?elu?name, Woman?name))). + +% iterations of the algorithm +round(LstMan, LstWoman) :- + send(LstMan, for_some, message(@arg1, propose)), + send(LstWoman, for_some, message(@arg1, dispose)), + ( \+send(LstWoman, for_all, @arg1?status == maybe) + -> + round(LstMan, LstWoman) + ; + true + ). + +:-pce_begin_class(person, object, "description of a person"). +variable(name, object, both, "name of the person"). +variable(preference, chain, both, "list of priority"). +variable(status, object, both, "statut of engagement : maybe / free"). + +initialise(P, Name, Pref) :-> + send(P, send_super, initialise), + send(P, slot, name, Name), + send(P, slot, preference, Pref), + send(P, slot, status, free). + +% reception of the list of partners +init_liste(P, Lst) :-> + % we replace the list of name of partners + % with the list of persons partners. + new(NLP, chain), + get(P, slot, preference, LP), + send(LP, for_all, message(@prolog, find_person,@arg1, Lst, NLP)), + send(P, slot, preference, NLP). + +:- pce_end_class(person). + + + +find_person(Name, LstPerson, LstPref) :- + get(LstPerson, find, @arg1?name == Name, Elem), + send(LstPref, append, Elem). + +:-pce_begin_class(man, person, "description of a man"). + +initialise(P, Name, Pref) :-> + send(P, send_super, initialise, Name, Pref). + +% a man propose "la botte" to a woman +propose(P) :-> + get(P, slot, status, free), + get(P, slot, preference, XPref), + get(XPref, delete_head, Pref), + send(P, slot, preference, XPref), + send(Pref, proposition, P). + +refuse(P) :-> + send(P, slot, status, free). + +accept(P) :-> + send(P, slot, status, maybe). + +:- pce_end_class(man). + +:-pce_begin_class(woman, person, "description of a woman"). +variable(elu, object, both, "name of the elu"). +variable(contact, chain, both, "men that have contact this woman"). + +initialise(P, Name, Pref) :-> + send(P, send_super, initialise, Name, Pref), + send(P, slot, contact, new(_, chain)), + send(P, slot, elu, @nil). + +% a woman decide Maybe/No +dispose(P) :-> + get(P, slot, contact, Contact), + get(P, slot, elu, Elu), + + ( Elu \= @nil + -> + send(Contact, append, Elu) + ; + true), + + new(R, chain), + send(Contact, for_all, message(P, fetch, @arg1, R)), + send(R, sort, ?(@arg1?first, compare, @arg2?first)), + get(R, delete_head, Tete), + send(Tete?second, accept), + send(P, slot, status, maybe), + send(P, slot, elu, Tete?second), + send(R, for_some, message(@arg1?second, refuse)), + send(P, slot, contact, new(_, chain)) . + + +% looking for the person of the given name Contact +% Adding it in the chain Chain +fetch(P, Contact, Chain) :-> + get(P, slot, preference, Lst), + get(Lst, find, @arg1?name == Contact?name, Elem), + get(Lst, index, Elem, Ind), + send(Chain, append, new(_, tuple(Ind, Contact))). + +% a woman receive a proposition from a man +proposition(P, Name) :-> + get(P, slot, contact, C), + send(C, append, Name), + send(P, slot, contact, C). + +:- pce_end_class(woman). + +% computation of the stability od couple +stability(LstCouple) :- + chain_list(LstCouple, LstPceCouple), + maplist(transform, LstPceCouple, PrologLstCouple), + study_couples(PrologLstCouple, [], UnstableCouple), + ( UnstableCouple = [] + -> + writeln('Couples are stable') + ; + sort(UnstableCouple, SortUnstableCouple), + writeln('Unstable couples are'), + maplist(print_unstable_couple, SortUnstableCouple), + nl + ). + + +print_unstable_couple((C1, C2)) :- + format('~w and ~w~n', [C1, C2]). + +transform(PceCouple, couple(First, Second)):- + get(PceCouple?first, value, First), + get(PceCouple?second, value, Second). + +study_couples([], UnstableCouple, UnstableCouple). + +study_couples([H | T], CurrentUnstableCouple, UnstableCouple):- + include(unstable_couple(H), T, Lst), + ( Lst \= [] + -> + maplist(build_one_couple(H), Lst, Lst1), + append(CurrentUnstableCouple, Lst1,CurrentUnstableCouple1) + ; + CurrentUnstableCouple1 = CurrentUnstableCouple + ), + study_couples(T, CurrentUnstableCouple1, UnstableCouple). + + +build_one_couple(C1, C2, (C1, C2)). + +unstable_couple(couple(X1, Y1), couple(X2, Y2)) :- + prefere(X1, PX1), + prefere(X2, PX2), + prefere(Y1, PY1), + prefere(Y2, PY2), + + % index of women for X1 + nth0(IY12, PX1, Y2), + nth0(IY11, PX1, Y1), + % index of men for Y2 + nth0(IX21, PY2, X1), + nth0(IX22, PY2, X2), + + % index of women for X2 + nth0(IY21, PX2, Y1), + nth0(IY22, PX2, Y2), + % index of men for Y1 + nth0(IX11, PY1, X1), + nth0(IX12, PY1, X2), + + % A couple is unstable + ( (IY12 < IY11 , IX21 < IX22); + (IY21 < IY22 , IX12 < IX11)). diff --git a/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-2.pro b/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-2.pro new file mode 100644 index 0000000000..c5172624a3 --- /dev/null +++ b/Task/Stable-marriage-problem/Prolog/stable-marriage-problem-2.pro @@ -0,0 +1,214 @@ +:- dynamic person/4, prop/2. +% person(Name, Preference, Status, Candidate) +% prop(Name, List_of_Candidates) (for a woman) + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% facts +prefere(abe,[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]). +prefere( bob,[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]). +prefere( col,[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]). +prefere( dan,[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]). +prefere( ed,[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]). +prefere( fred,[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]). +prefere( gav,[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]). +prefere( hal,[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]). +prefere( ian,[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]). +prefere( jon,[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]). + +prefere( abi,[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal]). +prefere( bea,[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal]). +prefere( cath,[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon]). +prefere( dee,[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed]). +prefere( eve,[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob]). +prefere( fay,[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal]). +prefere( gay,[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian]). +prefere( hope,[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred]). +prefere( ivy,[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan]). +prefere( jan,[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan]). + + +man(abe). +man(bob). +man(col). +man(dan). +man(ed). +man(fred). +man(gav). +man(hal). +man(ian). +man(jon). + +woman(abi). +woman(bea). +woman(cath). +woman(dee). +woman(eve). +woman(fay). +woman(gay). +woman(hope). +woman(ivy). +woman(jan). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% rules +stable_mariage :- + %initialization + retractall(person(_,_,_,_)), + retractall(prop(_,_)), + forall(prefere(P, Pref), assert(person(P, Pref, free, none))), + bagof(X, man(X), LstMen), + bagof(Y, woman(Y), LstWomen), + forall(member(Z, LstWomen), assert(prop(Z, []))), + + % compute the mariages + iteration(LstMen, LstWomen, LstCouple), + maplist(print_couple,LstCouple), + nl, + + % test of the stability of couples + stability(LstCouple), + nl, + + % Perturbation of couples + length(LstCouple, Len), + get_two_random_couples(Len, V1, V2), + + nth0(V1, LstCouple, C1), + select(C1, LstCouple, Lst1), + ( V2 > 0 -> V22 is V2 - 1; V22 = V2), + nth0(V22, Lst1, C2), + select(C2, Lst1, Lst2), + C1 = couple(M1, W1), + C2 = couple(M2, W2), + + writeln('perturbation of couples'), + format('~w with ~w~n', [W1, M2]), + format('~w with ~w~n', [W2, M1]), + nl, + stability([couple(M1, W2), couple(M2, W1)| Lst2]). + + +% the algorithm +iteration(Men, Women, LstCouples) :- + % Men propose + bagof(M, X^Y^(member(M, Men),person(M, X, free, Y)), LM), + forall(member(X, LM), + ( retract(person(X, [W|Pref], free, Elu)), + assert(person(X, Pref, free, Elu)), + retract(prop(W, Prop)), + assert(prop(W, [X| Prop])))), + + % women dispose + bagof(W, L^(prop(W, L), L \= []), LW), + forall(member(W, LW), + ( retract(prop(W, Prop)), + retract(person(W, Pref, _, Elu)), + ( Elu = none -> Prop1 = Prop; Prop1 = [Elu|Prop]), + order_prop(Pref, Prop1, [M | Prop2]), + retract(person(M, PrefM, _, _)), + assert(person(M, PrefM, maybe, W)), + forall(member(Y, Prop2), + ( retract(person(Y, Pref1, _, _TE)), + assert(person(Y, Pref1, free, none)))), + assert(prop(W, [])), + assert(person(W, Pref, maybe, M)) + )), + + % finished ? + ( bagof(X, T^Z^(member(X, Women), person(X, T, free, Z)), _LW1) -> + iteration(Men, Women, LstCouples) + ; + make_couple(Women, LstCouples) + ). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% compute order preference of candidates. +order_prop(Pref, Prop, Res) :- + maplist(index(Pref), Prop, Rtemp), + sort(Rtemp, Rtemp1), + maplist(simplifie,Rtemp1, Res). + +index(Lst, Value, [Ind, Value]) :- + nth0(Ind, Lst, Value). + +simplifie([_, V], V). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +print_couple(couple(M, W)) :- + format('~w with ~w~n', [W, M]). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% creation of couples +make_couple([], []). + +make_couple([W | LW], [couple(M, W) | LC]) :- + make_couple(LW, LC), + person(W, _, _, M). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% miscellaneous +get_two_random_couples(Len, C1, C2) :- + C1 is random(Len), + repeat, + C2 is random(Len), + C1 \= C2. + +print_unstable_couple((C1, C2)) :- + format('~w and ~w~n', [C1, C2]). + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% test the stability of couples +stability(LstCouple) :- + study_couples(LstCouple, [], CoupleInstable), + ( CoupleInstable = [] + -> + writeln('Couples are stable') + ; + sort(CoupleInstable, SortCoupleInstable), + writeln('Unstable couples are'), + maplist(print_unstable_couple, SortCoupleInstable), + nl + ). + + +% compute the stability od couple +study_couples([], UnstableCouple, UnstableCouple). + +study_couples([H | T], CurrentUnstableCouple, UnstableCouple):- + include(unstable_couple(H), T, Lst), + ( Lst \= [] + -> + maplist(build_one_couple(H), Lst, Lst1), + append(CurrentUnstableCouple, Lst1,CurrentUnstableCouple1) + ; + CurrentUnstableCouple1 = CurrentUnstableCouple + ), + study_couples(T, CurrentUnstableCouple1, UnstableCouple). + + +build_one_couple(C1, C2, (C1, C2)). + +unstable_couple(couple(X1, Y1), couple(X2, Y2)) :- + prefere(X1, PX1), + prefere(X2, PX2), + prefere(Y1, PY1), + prefere(Y2, PY2), + + % index of women for X1 + nth0(IY12, PX1, Y2), + nth0(IY11, PX1, Y1), + % index of men for Y2 + nth0(IX21, PY2, X1), + nth0(IX22, PY2, X2), + + % index of women for X2 + nth0(IY21, PX2, Y1), + nth0(IY22, PX2, Y2), + % index of men for Y1 + nth0(IX11, PY1, X1), + nth0(IX12, PY1, X2), + + % A couple is unstable + ( (IY12 < IY11 , IX21 < IX22); + (IY21 < IY22 , IX12 < IX11)). diff --git a/Task/Stable-marriage-problem/PureBasic/stable-marriage-problem.purebasic b/Task/Stable-marriage-problem/PureBasic/stable-marriage-problem.purebasic new file mode 100644 index 0000000000..29719d9069 --- /dev/null +++ b/Task/Stable-marriage-problem/PureBasic/stable-marriage-problem.purebasic @@ -0,0 +1,174 @@ +#coupleCount = 10 + +DataSection + ;guys + Data.s "abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay" + Data.s "bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay" + Data.s "col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan" + Data.s "dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi" + Data.s "ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay" + Data.s "fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay" + Data.s "gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay" + Data.s "hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee" + Data.s "ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve" + Data.s "jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope" + ;gals + Data.s "abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal" + Data.s "bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal" + Data.s "cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon" + Data.s "dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed" + Data.s "eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob" + Data.s "fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal" + Data.s "gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian" + Data.s "hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred" + Data.s "ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan" + Data.s "jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan" +EndDataSection + +Structure message + source.s ;person that message is from + dest.s ;person that message is for + action.s ;{'P', 'A', 'D', 'B'} for proposal, accept, decline, break-up +EndStructure + +Structure person + name.s + isEngagedTo.s + List prefs.s() +EndStructure + +Global NewList messages.message() + +Procedure setupPersons(List persons.person(), count) + Protected i, j, start, pref$ + For i = 1 To count + Read.s pref$ + pref$ = LCase(pref$) + start = FindString(pref$, ":", 1) + AddElement(persons()) + persons()\name = Left(pref$, start - 1) + pref$ = Trim(Right(pref$, Len(pref$) - start)) + For j = 1 To count + AddElement(persons()\prefs()) + persons()\prefs() = Trim(StringField(pref$, j, ",")) + Next + Next +EndProcedure + +Procedure sendMessage(source.s, dest.s, action.s) + LastElement(messages()) + AddElement(messages()) + With messages() + \source = source + \dest = dest + \action = action + EndWith + ResetList(messages()) +EndProcedure + +Procedure selectPerson(name.s, List persons.person()) + ForEach persons() + If persons()\name = name + Break + EndIf + Next +EndProcedure + +Procedure rankPerson(name.s, List prefs.s()) + ForEach prefs() + If prefs() = name + ProcedureReturn #coupleCount - ListIndex(prefs()) ;higher is better + EndIf + Next + ProcedureReturn -1 ;no rank, shouldn't occur +EndProcedure + +Procedure stabilityCheck(List guys.person(), List gals.person()) + Protected isStable = #True + ForEach guys() + rankPerson(guys()\isEngagedTo, guys()\prefs()) + While PreviousElement(guys()\prefs()) + selectPerson(guys()\prefs(), gals()) + If rankPerson(guys()\name, gals()\prefs()) > rankPerson(gals()\isEngagedTo, gals()\prefs()) + Print(" " + gals()\name + " loves " + guys()\name + " more than " + gals()\isEngagedTo + ",") + PrintN(" And " + guys()\name + " loves " + gals()\name + " more than " + guys()\isEngagedTo + ".") + isStable = #False + EndIf + Wend + Next + If isStable + PrintN(#CRLF$ + "Marriage stability check PASSED.") + Else + PrintN(#CRLF$ + "Marriage stability check FAILED.") + EndIf +EndProcedure + +NewList guys.person() +NewList gals.person() +setupPersons(guys(), #coupleCount) +setupPersons(gals(), #coupleCount) + +;make initial round of proposals +ForEach guys() + FirstElement(guys()\prefs()) + sendMessage(guys()\name, guys()\prefs(), "P") +Next + +;dispatch messages +Define source.s, dest.s, action.s +ForEach messages() + source = messages()\source + dest = messages()\dest + action = messages()\action + + DeleteElement(messages()) + Select action + Case "P" ;propose ;only message received by gals + selectPerson(dest, gals()) + selectPerson(source, guys()) + If rankPerson(guys()\name, gals()\prefs()) < rankPerson(gals()\isEngagedTo, gals()\prefs()) + sendMessage(dest, source, "D") ;decline proposal + ElseIf rankPerson(guys()\name, gals()\prefs()) > rankPerson(gals()\isEngagedTo, gals()\prefs()) + If gals()\isEngagedTo + sendMessage(dest, gals()\isEngagedTo, "B") ;break-up engagement + EndIf + gals()\isEngagedTo = source + sendMessage(dest, source, "A") ;accept proposal + EndIf + Case "A", "D", "B" ;messages received by guys + selectPerson(dest, guys()) + If action = "A" ;proposal accepted + guys()\isEngagedTo = source + Else + If action = "B" ;broke-up + guys()\isEngagedTo = "" + EndIf + NextElement(guys()\prefs()) + sendMessage(dest, guys()\prefs(),"P") ;propose to next pref + EndIf + EndSelect +Next + +If OpenConsole() + PrintN("Marriages:") + ForEach guys() + PrintN(" " + guys()\name + " And " + guys()\isEngagedTo + ".") + Next + stabilityCheck(guys(), gals()) + + Define *person_1.person, *person_2.person + PrintN(#CRLF$ + "Introducing an error by swapping partners of abi and bea.") + selectPerson("abi", gals()): *person_1 = @gals() + selectPerson("bea", gals()): *person_2 = @gals() + Swap *person_1\isEngagedTo, *person_2\isEngagedTo + selectPerson(*person_1\isEngagedTo, guys()): *person_1 = @guys() + selectPerson(*person_1\isEngagedTo, guys()): *person_2 = @guys() + Swap *person_1\isEngagedTo, *person_2\isEngagedTo + PrintN(" " + *person_1\name + " is now with " + *person_1\isEngagedTo + ".") + PrintN(" " + *person_2\name + " is now with " + *person_2\isEngagedTo + ".") + PrintN("") + stabilityCheck(guys(), gals()) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Stable-marriage-problem/Python/stable-marriage-problem.py b/Task/Stable-marriage-problem/Python/stable-marriage-problem.py new file mode 100644 index 0000000000..e50dcd426b --- /dev/null +++ b/Task/Stable-marriage-problem/Python/stable-marriage-problem.py @@ -0,0 +1,103 @@ +import copy + +guyprefers = { + 'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'], + 'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'], + 'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'], + 'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'], + 'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'], + 'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'], + 'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'], + 'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'], + 'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'], + 'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']} +galprefers = { + 'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'], + 'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'], + 'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'], + 'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'], + 'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'], + 'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'], + 'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'], + 'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'], + 'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'], + 'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']} + +guys = sorted(guyprefers.keys()) +gals = sorted(galprefers.keys()) + + +def check(engaged): + inverseengaged = dict((v,k) for k,v in engaged.items()) + for she, he in engaged.items(): + shelikes = galprefers[she] + shelikesbetter = shelikes[:shelikes.index(he)] + helikes = guyprefers[he] + helikesbetter = helikes[:helikes.index(she)] + for guy in shelikesbetter: + guysgirl = inverseengaged[guy] + guylikes = guyprefers[guy] + if guylikes.index(guysgirl) > guylikes.index(she): + print("%s and %s like each other better than " + "their present partners: %s and %s, respectively" + % (she, guy, he, guysgirl)) + return False + for gal in helikesbetter: + girlsguy = engaged[gal] + gallikes = galprefers[gal] + if gallikes.index(girlsguy) > gallikes.index(he): + print("%s and %s like each other better than " + "their present partners: %s and %s, respectively" + % (he, gal, she, girlsguy)) + return False + return True + +def matchmaker(): + guysfree = guys[:] + engaged = {} + guyprefers2 = copy.deepcopy(guyprefers) + galprefers2 = copy.deepcopy(galprefers) + while guysfree: + guy = guysfree.pop(0) + guyslist = guyprefers2[guy] + gal = guyslist.pop(0) + fiance = engaged.get(gal) + if not fiance: + # She's free + engaged[gal] = guy + print(" %s and %s" % (guy, gal)) + else: + # The bounder proposes to an engaged lass! + galslist = galprefers2[gal] + if galslist.index(fiance) > galslist.index(guy): + # She prefers new guy + engaged[gal] = guy + print(" %s dumped %s for %s" % (gal, fiance, guy)) + if guyprefers2[fiance]: + # Ex has more girls to try + guysfree.append(fiance) + else: + # She is faithful to old fiance + if guyslist: + # Look again + guysfree.append(guy) + return engaged + + +print('\nEngagements:') +engaged = matchmaker() + +print('\nCouples:') +print(' ' + ',\n '.join('%s is engaged to %s' % couple + for couple in sorted(engaged.items()))) +print() +print('Engagement stability check PASSED' + if check(engaged) else 'Engagement stability check FAILED') + +print('\n\nSwapping two fiances to introduce an error') +engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]] +for gal in gals[:2]: + print(' %s is now engaged to %s' % (gal, engaged[gal])) +print() +print('Engagement stability check PASSED' + if check(engaged) else 'Engagement stability check FAILED') diff --git a/Task/Stable-marriage-problem/Ruby/stable-marriage-problem.rb b/Task/Stable-marriage-problem/Ruby/stable-marriage-problem.rb new file mode 100644 index 0000000000..aa71111440 --- /dev/null +++ b/Task/Stable-marriage-problem/Ruby/stable-marriage-problem.rb @@ -0,0 +1,171 @@ +class Person + def initialize(name) + @name = name + @fiance = nil + @preferences = [] + @proposals = [] + end + attr_reader :name, :proposals + attr_accessor :fiance, :preferences + + def to_s + @name + end + + def free + @fiance = nil + end + + def single? + @fiance == nil + end + + def engage(person) + self.fiance = person + person.fiance = self + end + + def better_choice?(person) + @preferences.index(person) < @preferences.index(@fiance) + end + + def propose_to(person) + puts "#{self} proposes to #{person}" if $DEBUG + @proposals << person + person.respond_to_proposal_from(self) + end + + def respond_to_proposal_from(person) + if single? + puts "#{self} accepts proposal from #{person}" if $DEBUG + engage(person) + elsif better_choice?(person) + puts "#{self} dumps #{@fiance} for #{person}" if $DEBUG + @fiance.free + engage(person) + else + puts "#{self} rejects proposal from #{person}" if $DEBUG + end + end +end + +######################################################################## +# initialize data + +prefs = { + 'abe' => %w[abi eve cath ivy jan dee fay bea hope gay], + 'bob' => %w[cath hope abi dee eve fay bea jan ivy gay], + 'col' => %w[hope eve abi dee bea fay ivy gay cath jan], + 'dan' => %w[ivy fay dee gay hope eve jan bea cath abi], + 'ed' => %w[jan dee bea cath fay eve abi ivy hope gay], + 'fred' => %w[bea abi dee gay eve ivy cath jan hope fay], + 'gav' => %w[gay eve ivy bea cath abi dee hope jan fay], + 'hal' => %w[abi eve hope fay ivy cath jan bea gay dee], + 'ian' => %w[hope cath dee gay bea abi fay ivy jan eve], + 'jon' => %w[abi fay jan gay eve bea dee cath ivy hope], + 'abi' => %w[bob fred jon gav ian abe dan ed col hal], + 'bea' => %w[bob abe col fred gav dan ian ed jon hal], + 'cath' => %w[fred bob ed gav hal col ian abe dan jon], + 'dee' => %w[fred jon col abe ian hal gav dan bob ed], + 'eve' => %w[jon hal fred dan abe gav col ed ian bob], + 'fay' => %w[bob abe ed ian jon dan fred gav col hal], + 'gay' => %w[jon gav hal fred bob abe col ed dan ian], + 'hope' => %w[gav jon bob abe ian dan hal ed col fred], + 'ivy' => %w[ian col hal gav fred bob abe ed jon dan], + 'jan' => %w[ed hal gav abe bob jon col ian fred dan], +} + +@men = Hash[ + %w[abe bob col dan ed fred gav hal ian jon].collect do |name| + [name, Person.new(name)] + end +] + +@women = Hash[ + %w[abi bea cath dee eve fay gay hope ivy jan].collect do |name| + [name, Person.new(name)] + end +] + +@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])} +@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])} + +######################################################################## +# perform the matching + +def match_couples(men, women) + men.each_value {|man| man.free} + women.each_value {|woman| woman.free} + + while m = men.values.find {|man| man.single?} do + puts "considering single man #{m}" if $DEBUG + w = m.preferences.find {|woman| not m.proposals.include?(woman)} + m.propose_to(w) + end +end + +match_couples @men, @women + +@men.each_value.collect {|man| puts "#{man} + #{man.fiance}"} + +######################################################################## +# check for stability + +class Person + def more_preferable_people + ( @preferences.partition {|p| better_choice?(p)} ).first + end +end + +require 'set' + +def stability(men) + unstable = Set.new + men.each_value do |man| + woman = man.fiance + puts "considering #{man} and #{woman}" if $DEBUG + + man.more_preferable_people.each do |other_woman| + if other_woman.more_preferable_people.include?(man) + puts "an unstable pairing: #{man} and #{other_woman}" if $DEBUG + unstable << [man, other_woman] + end + end + woman.more_preferable_people.each do |other_man| + if other_man.more_preferable_people.include?(woman) + puts "an unstable pairing: #{woman} and #{other_man}" if $DEBUG + unstable << [other_man, woman] + end + end + end + + if unstable.empty? + puts "these couples are stable" + else + puts "uh oh" + unstable.each do |a,b| + puts "#{a} is engaged to #{a.fiance} but would prefer #{b}, and #{b} is engaged to #{b.fiance} but would prefer #{a}" + end + end +end + +stability @men + +######################################################################## +# perturb + +puts "\nwhat if abe and bob swap..." + +def swap(m1, m2) + w1 = m1.fiance + w2 = m2.fiance + m1.fiance = w2 + w1.fiance = m2 + m2.fiance = w1 + w2.fiance = m1 +end + +swap *@men.values_at('abe','bob') + +@men.each_value.collect {|man| puts "#{man} + #{man.fiance}"} +stability @men diff --git a/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-1.spark b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-1.spark new file mode 100644 index 0000000000..c686ec6686 --- /dev/null +++ b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-1.spark @@ -0,0 +1,43 @@ +package Preferences +is + + type Guy_X is (no_guy, abe, bob, col, dan, ed, fred, gav, hal, ian, jon); + subtype Guy is Guy_X range Guy_X'Succ(Guy_X'First) .. Guy_X'Last; + + type Girl_X is (no_girl, abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan); + subtype Girl is Girl_X range Girl_X'Succ(Girl_X'First) .. Girl_X'Last; + + type Extended_Rank is range 0 .. 10; + subtype Rank is Extended_Rank range 1 .. Extended_Rank'Last; + + type His_Rank is array (Rank) of Girl; + type He_Prefers is array (Guy) of His_Rank; + + Guys_Like : constant He_Prefers := He_Prefers'( + abe => His_Rank'(abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay), + bob => His_Rank'(cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay), + col => His_Rank'(hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan), + dan => His_Rank'(ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi), + ed => His_Rank'(jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay), + fred => His_Rank'(bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay), + gav => His_Rank'(gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay), + hal => His_Rank'(abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee), + ian => His_Rank'(hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve), + jon => His_Rank'(abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope)); + + type Her_Rank is array(Rank) of Guy; + type She_Prefers is array (Girl) of Her_Rank; + + Girls_Like : constant She_Prefers := She_Prefers'( + abi => Her_Rank'(bob, fred, jon, gav, ian, abe, dan, ed, col, hal), + bea => Her_Rank'(bob, abe, col, fred, gav, dan, ian, ed, jon, hal), + cath => Her_Rank'(fred, bob, ed, gav, hal, col, ian, abe, dan, jon), + dee => Her_Rank'(fred, jon, col, abe, ian, hal, gav, dan, bob, ed), + eve => Her_Rank'(jon, hal, fred, dan, abe, gav, col, ed, ian, bob), + fay => Her_Rank'(bob, abe, ed, ian, jon, dan, fred, gav, col, hal), + gay => Her_Rank'(jon, gav, hal, fred, bob, abe, col, ed, dan, ian), + hope => Her_Rank'(gav, jon, bob, abe, ian, dan, hal, ed, col, fred), + ivy => Her_Rank'(ian, col, hal, gav, fred, bob, abe, ed, jon, dan), + jan => Her_Rank'(ed, hal, gav, abe, bob, jon, col, ian, fred, dan)); + +end Preferences; diff --git a/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-2.spark b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-2.spark new file mode 100644 index 0000000000..6cc091382c --- /dev/null +++ b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-2.spark @@ -0,0 +1,19 @@ +with Preferences; +--# inherit Preferences; +package Propose +is + + type Engagements is array (Preferences.Girl) of Preferences.Guy_X; + + procedure Engage (Pairs : out Engagements); + --# derives Pairs from ; + + procedure Check_Stable (Pairs : in Engagements; + OK : out Boolean; + Other_Girl : out Preferences.Girl_X; + Other_Guy : out Preferences.Guy_X); + --# derives OK, + --# Other_Girl, + --# Other_Guy from Pairs; + +end Propose; diff --git a/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-3.spark b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-3.spark new file mode 100644 index 0000000000..cdcff48f91 --- /dev/null +++ b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-3.spark @@ -0,0 +1,138 @@ +with Preferences; +use type Preferences.Extended_Rank; +use type Preferences.Girl; +use type Preferences.Guy; +package body Propose +is + + -- renaming subtypes: + subtype Guy is Preferences.Guy; + subtype Girl is Preferences.Girl; + + function Her_Rank_Of_Him (Her : Girl; + Him : Guy) return Preferences.Rank + is + R : Preferences.Rank; + begin + R := Preferences.Rank'First; + while Preferences.Girls_Like(Her)(R) /= Him + and R /= Preferences.Rank'Last + loop + R := Preferences.Rank'Succ(R); + end loop; + return R; + end Her_Rank_Of_Him; + + function His_Rank_Of_Her (Him : Guy; + Her : Girl) return Preferences.Rank + is + R : Preferences.Rank; + begin + R := Preferences.Rank'First; + while Preferences.Guys_Like(Him)(R) /= Her + and R /= Preferences.Rank'Last + loop + R := Preferences.Rank'Succ(R); + end loop; + return R; + end His_Rank_Of_Her; + + procedure Engage (Pairs : out Engagements) + is + type Free_Guy is array (Guy) of Boolean; + type Free_Girl is array (Girl) of Boolean; + type Last_Proposals is array (Guy) of Preferences.Extended_Rank; + + -- Initialize all M in M_Free and W in W_Free to free. + M_Free : Free_Guy := Free_Guy'(others => True); + W_Free : Free_Girl := Free_Girl'(others => True); + Last_Proposal : Last_Proposals := + Last_Proposals'(others => Preferences.Extended_Rank'First); + + All_Paired : Boolean := False; + W : Girl; + M1 : Preferences.Guy_X; + + begin + -- Initially set all engagements to null. + Pairs := Engagements'(others => Preferences.No_Guy); + -- while there is a free man M who still has a woman W to propose to + while not All_Paired loop + All_Paired := True; + for M in Guy loop + if M_Free(M) and Last_Proposal(M) < Preferences.Rank'Last then + All_Paired := False; + -- W = M's highest ranked such woman who he has not + -- proposed to yet + Last_Proposal(M) := Preferences.Rank'Succ(Last_Proposal(M)); + W := Preferences.Guys_Like(M)(Last_Proposal(M)); + -- if W is free + if W_Free(W) then + -- (M, W) become engaged + M_Free(M) := False; + W_Free(W) := False; + Pairs(W) := M; + else + -- else some pair (M1, W) already exists + M1 := Pairs(W); + if M1 > Preferences.no_guy and then + -- if W prefers M to M1 + Her_Rank_Of_Him (Her => W, Him => M) + < Her_Rank_Of_Him (Her => W, Him => M1) + then + -- (M, W) become engaged + M_Free(M) := False; + Pairs(W) := M; + -- M1 becomes free + M_Free(M1) := True; + else + -- (M1, W) remain engaged + null; + end if; + end if; + end if; + end loop; + end loop; + end Engage; + + procedure Check_Stable (Pairs : in Engagements; + OK : out Boolean; + Other_Girl : out Preferences.Girl_X; + Other_Guy : out Preferences.Guy_X) + is + M : Preferences.Guy_X; + W_Rank : Preferences.Rank; + begin + OK := True; + Other_Girl := Preferences.No_Girl; + Other_Guy := Preferences.No_Guy; + -- Loop over all girls. + for W in Girl loop + if Pairs(W) > Preferences.no_guy then + W_Rank := Her_Rank_Of_Him (W, Pairs(W)); + -- Loop over all guys she prefers to her current guy. + for WR in Preferences.Rank range 1 .. W_Rank - 1 loop + M := Preferences.Girls_Like(W)(WR); + if M > Preferences.no_guy then + -- Loop over all girls for this guy in preference order. + for MR in Preferences.Rank + --# assert M > Preferences.no_guy; + loop + -- Exit if his current girl found before this girl. + exit when M = Pairs(Preferences.Guys_Like(M)(MR)); + -- Unstable if this girl found before his current girl. + if Preferences.Guys_Like(M)(MR) = W then + OK := False; + Other_Girl := W; + Other_Guy := M; + end if; + end loop; + end if; + exit when not OK; + end loop; + end if; + exit when not OK; + end loop; + end Check_Stable; + +end Propose; diff --git a/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-4.spark b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-4.spark new file mode 100644 index 0000000000..370b615fbb --- /dev/null +++ b/Task/Stable-marriage-problem/SPARK/stable-marriage-problem-4.spark @@ -0,0 +1,66 @@ +------------------------------------ +-- Test program. +-- +-- This is Ada, it is not SPARK. +------------------------------------ + +with Ada.Text_IO; +with Preferences; +with Propose; +procedure Matchmaker +is + -- renaming subtypes: + subtype Guy is Preferences.Guy; + subtype Girl is Preferences.Girl; + + Marriages : Propose.Engagements; + Stable : Boolean; + Him : Preferences.Guy_X; + Her : Preferences.Girl_X; + Stable_Marriages : Propose.Engagements; + + procedure Report_Stable + is + begin + if Stable then + Ada.Text_IO.Put_Line ("Pairs are Stable"); + else + Ada.Text_IO.Put ("Pairs are Unstable: "); + Ada.Text_IO.Put_Line + (Guy'Image(Him) & " and " & Girl'Image(Her) & " prefer each other."); + end if; + end Report_Stable; + +begin + + Propose.Engage(Pairs => Marriages); + for W in Girl loop + Ada.Text_IO.Put_Line (Girl'Image(W) & + " marries " & + Guy'Image(Marriages(W))); + end loop; + Propose.Check_Stable (Pairs => Marriages, + OK => Stable, + Other_Girl => Her, + Other_Guy => Him); + Report_Stable; + Stable_Marriages := Marriages; + + for W1 in Girl range Girl'First .. Girl'Pred(Girl'Last) loop + for W2 in Girl range Girl'Succ(W1) .. Girl'Last loop + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line ("Exchange " & Guy'Image(Marriages(W1)) & + " with " & Guy'Image(Marriages(W2))); + Him := Marriages(W1); + Marriages(W1) := Marriages(W2); + Marriages(W2) := Him; + Propose.Check_Stable (Pairs => Marriages, + OK => Stable, + Other_Girl => Her, + Other_Guy => Him); + Report_Stable; + Marriages := Stable_Marriages; + end loop; + end loop; + +end MatchMaker; diff --git a/Task/Stable-marriage-problem/Seed7/stable-marriage-problem.seed7 b/Task/Stable-marriage-problem/Seed7/stable-marriage-problem.seed7 new file mode 100644 index 0000000000..9e97c419f2 --- /dev/null +++ b/Task/Stable-marriage-problem/Seed7/stable-marriage-problem.seed7 @@ -0,0 +1,150 @@ +$ include "seed7_05.s7i"; + +const type: preferences is hash [string] array string; +const type: engaged is hash [string] string; + +const func integer: pos (in array string: area, in string: searched) is func + result + var integer: pos is 1; + begin + while pos <= length(area) and area[pos] <> searched do + incr(pos); + end while; + if pos > length(area) then + pos := 0; + end if; + end func; + +const func engaged: matchmaker (in preferences: guyPrefers, in preferences: girlPrefers) is func + result + var engaged: engagedTo is engaged.value; + local + var array string: freeGuys is 0 times ""; + var string: guy is ""; + var string: girl is ""; + var string: fiance is ""; + var array string: guyPreferencList is 0 times ""; + var array string: girlPreferenceList is 0 times ""; + var boolean: searching is TRUE; + begin + freeGuys := sort(keys(guyPrefers)); + while length(freeGuys) <> 0 do + guy := freeGuys[1]; + freeGuys := freeGuys[2 ..]; + guyPreferencList := guyPrefers[guy]; + searching := TRUE; + while searching and length(guyPreferencList) <> 0 do + girl := guyPreferencList[1]; + guyPreferencList := guyPreferencList[2 ..]; + if girl not in engagedTo then + engagedTo @:= [girl] guy; + writeln(" " <& girl <& " and " <& guy); + searching := FALSE; + else + fiance := engagedTo[girl]; + girlPreferenceList := girlPrefers[girl]; + if pos(girlPreferenceList, guy) < pos(girlPreferenceList, fiance) then + # She prefers new guy + engagedTo @:= [girl] guy; + freeGuys &:= fiance; + writeln(" " <& girl <& " dumped " <& fiance <& " for " <& guy); + searching := FALSE; + end if; + end if; + end while; + end while; + end func; + +const func boolean: check (in engaged: engagedTo, + in preferences: guyPrefers, in preferences: girlPrefers) is func + result + var boolean: stable is TRUE; + local + var string: he is ""; + var string: she is ""; + var string: guy is ""; + var string: girl is ""; + var engaged: inverseEngaged is engaged.value; + var array string: sheLikes is 0 times ""; + var array string: sheLikesBetter is 0 times ""; + var array string: heLikes is 0 times ""; + var array string: heLikesBetter is 0 times ""; + var string: guysGirl is ""; + var array string: guyLikes is 0 times ""; + var string: girlsGuy is ""; + var array string: girlLikes is 0 times ""; + begin + for he key she range engagedTo do + inverseEngaged @:= [he] she; + end for; + for he key she range engagedTo do + sheLikes := girlPrefers[she]; + sheLikesBetter := sheLikes[.. pred(pos(sheLikes, he))]; + heLikes := guyPrefers[he]; + heLikesBetter := heLikes[.. pred(pos(heLikes, she))]; + for guy range sheLikesBetter do + guysGirl := inverseEngaged[guy]; + guyLikes := guyPrefers[guy]; + if pos(guyLikes, guysGirl) > pos(guyLikes, she) and stable then + writeln(she <& " likes " <& guy <& " better than " <& he <& " and " <& + guy <& " likes " <& she <& " better than their current partner"); + stable := FALSE; + end if; + end for; + for girl range heLikesBetter do + girlsGuy := engagedTo[girl]; + girlLikes := girlPrefers[girl]; + if pos(girlLikes, girlsGuy) > pos(girlLikes, he) and stable then + writeln(he <& " likes " <& girl <& " better than " <& she <& " and " <& + girl <& " likes " <& he <& " better than their current partner"); + stable := FALSE; + end if; + end for; + end for; + end func; + +var preferences: guyPrefers is preferences.value; +var preferences: girlPrefers is preferences.value; +guyPrefers @:= ["abe"] [] ("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"); +guyPrefers @:= ["bob"] [] ("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"); +guyPrefers @:= ["col"] [] ("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"); +guyPrefers @:= ["dan"] [] ("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"); +guyPrefers @:= ["ed"] [] ("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"); +guyPrefers @:= ["fred"] [] ("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"); +guyPrefers @:= ["gav"] [] ("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"); +guyPrefers @:= ["hal"] [] ("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"); +guyPrefers @:= ["ian"] [] ("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"); +guyPrefers @:= ["jon"] [] ("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"); +girlPrefers @:= ["abi"] [] ("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"); +girlPrefers @:= ["bea"] [] ("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"); +girlPrefers @:= ["cath"] [] ("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"); +girlPrefers @:= ["dee"] [] ("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"); +girlPrefers @:= ["eve"] [] ("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"); +girlPrefers @:= ["fay"] [] ("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"); +girlPrefers @:= ["gay"] [] ("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"); +girlPrefers @:= ["hope"] [] ("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"); +girlPrefers @:= ["ivy"] [] ("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"); +girlPrefers @:= ["jan"] [] ("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"); + +const proc: main is func + local + var engaged: engagedTo is engaged.value; + var string: girl is ""; + begin + writeln("Matchmaking:"); + engagedTo := matchmaker(guyPrefers, girlPrefers); + writeln; + writeln("Engagements:"); + for girl range sort(keys(engagedTo)) do + writeln(" " <& girl <& " and " <& engagedTo[girl]); + end for; + writeln; + writeln("Marriages are " <& [] ("unstable", "stable") [succ(ord(check(engagedTo, guyPrefers, girlPrefers)))]); + writeln; + writeln("Perturb:"); + engagedTo @:= ["abi"] "fred"; + engagedTo @:= ["bea"] "jon"; + writeln("engage abi with fred and bea with jon"); + writeln; + writeln("Marriages are " <& [] ("unstable", "stable") [succ(ord(check(engagedTo, guyPrefers, girlPrefers)))]); + end func; diff --git a/Task/Stable-marriage-problem/Tcl/stable-marriage-problem.tcl b/Task/Stable-marriage-problem/Tcl/stable-marriage-problem.tcl new file mode 100644 index 0000000000..9d6a86dd0e --- /dev/null +++ b/Task/Stable-marriage-problem/Tcl/stable-marriage-problem.tcl @@ -0,0 +1,116 @@ +package require Tcl 8.5 + +# Functions as aliases to standard commands +interp alias {} tcl::mathfunc::pos {} ::lsearch -exact +interp alias {} tcl::mathfunc::nonempty {} ::llength + +# The stability check +proc check engaged { + global preferences + set inverse [lreverse $engaged] + set errmsg "%s and %s like each other better than their present partners,\ + %s and %s respectively" + dict for {she he} $engaged { + set shelikes [dict get $preferences $she] + set shelikesbetter [lrange $shelikes 0 [expr {pos($shelikes,$he)}]] + set helikes [dict get $preferences $he] + set helikesbetter [lrange $helikes 0 [expr {pos($helikes,$she)}]] + foreach guy $shelikesbetter { + set guysgirl [dict get $inverse $guy] + set guylikes [dict get $preferences $guy] + if {pos($guylikes,$guysgirl) > pos($guylikes,$she)} { + puts [format $errmsg $she $guy $he $guysgirl] + return 0 + } + } + foreach gal $helikesbetter { + set galsguy [dict get $engaged $gal] + set gallikes [dict get $preferences $gal] + if {pos($gallikes,$galsguy) > pos($gallikes,$he)} { + puts [format $errmsg $he $gal $she $galsguy] + return 0 + } + } + } + return 1 +} + +# The match-making algorithm +proc matchmaker {} { + global guys gals preferences + set guysfree $guys + set engaged {} + array set p $preferences + while {nonempty($guysfree)} { + set guysfree [lassign $guysfree guy] + set p($guy) [set guyslist [lassign $p($guy) gal]] + if {![dict exists $engaged $gal]} { + # She's free + dict set engaged $gal $guy + puts " $guy and $gal" + continue + } + # The bounder proposes to an engaged lass! + set fiance [dict get $engaged $gal] + if {pos($p($gal), $fiance) > pos($p($gal), $guy)} { + # She prefers the new guy + dict set engaged $gal $guy + puts " $gal dumped $fiance for $guy" + set guy $fiance + } + if {nonempty($p($guy))} { + lappend guysfree $guy + } + } + return $engaged +} + +# Problem dataset; preferences unified since all names distinct +set guys {abe bob col dan ed fred gav hal ian jon} +set gals {abi bea cath dee eve fay gay hope ivy jan} +set preferences { + abe {abi eve cath ivy jan dee fay bea hope gay} + bob {cath hope abi dee eve fay bea jan ivy gay} + col {hope eve abi dee bea fay ivy gay cath jan} + dan {ivy fay dee gay hope eve jan bea cath abi} + ed {jan dee bea cath fay eve abi ivy hope gay} + fred {bea abi dee gay eve ivy cath jan hope fay} + gav {gay eve ivy bea cath abi dee hope jan fay} + hal {abi eve hope fay ivy cath jan bea gay dee} + ian {hope cath dee gay bea abi fay ivy jan eve} + jon {abi fay jan gay eve bea dee cath ivy hope} + + abi {bob fred jon gav ian abe dan ed col hal} + bea {bob abe col fred gav dan ian ed jon hal} + cath {fred bob ed gav hal col ian abe dan jon} + dee {fred jon col abe ian hal gav dan bob ed} + eve {jon hal fred dan abe gav col ed ian bob} + fay {bob abe ed ian jon dan fred gav col hal} + gay {jon gav hal fred bob abe col ed dan ian} + hope {gav jon bob abe ian dan hal ed col fred} + ivy {ian col hal gav fred bob abe ed jon dan} + jan {ed hal gav abe bob jon col ian fred dan} +} + +# The demonstration code +puts "Engagements:" +set engaged [matchmaker] + +puts "\nCouples:" +set pfx "" +foreach gal $gals { + puts -nonewline "$pfx $gal is engaged to [dict get $engaged $gal]" + set pfx ",\n" +} +puts "\n" +puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]" + +puts "\n\nSwapping two fiances to introduce an error" +set tmp [dict get $engaged [lindex $gals 0]] +dict set engaged [lindex $gals 0] [dict get $engaged [lindex $gals 1]] +dict set engaged [lindex $gals 1] $tmp +foreach gal [lrange $gals 0 1] { + puts " $gal is now engaged to [dict get $engaged $gal]" +} +puts "" +puts "Engagement stability check [lindex {FAILED PASSED} [check $engaged]]" diff --git a/Task/Stable-marriage-problem/Ursala/stable-marriage-problem.ursala b/Task/Stable-marriage-problem/Ursala/stable-marriage-problem.ursala new file mode 100644 index 0000000000..1acd6af3b3 --- /dev/null +++ b/Task/Stable-marriage-problem/Ursala/stable-marriage-problem.ursala @@ -0,0 +1,48 @@ +men = + +{ + 'abe': <'abi','eve','cath','ivy','jan','dee','fay','bea','hope','gay'>, + 'bob': <'cath','hope','abi','dee','eve','fay','bea','jan','ivy','gay'>, + 'col': <'hope','eve','abi','dee','bea','fay','ivy','gay','cath','jan'>, + 'dan': <'ivy','fay','dee','gay','hope','eve','jan','bea','cath','abi'>, + 'ed': <'jan','dee','bea','cath','fay','eve','abi','ivy','hope','gay'>, + 'fred': <'bea','abi','dee','gay','eve','ivy','cath','jan','hope','fay'>, + 'gav': <'gay','eve','ivy','bea','cath','abi','dee','hope','jan','fay'>, + 'hal': <'abi','eve','hope','fay','ivy','cath','jan','bea','gay','dee'>, + 'ian': <'hope','cath','dee','gay','bea','abi','fay','ivy','jan','eve'>, + 'jon': <'abi','fay','jan','gay','eve','bea','dee','cath','ivy','hope'>} + +women = + +{ + 'abi': <'bob','fred','jon','gav','ian','abe','dan','ed','col','hal'>, + 'bea': <'bob','abe','col','fred','gav','dan','ian','ed','jon','hal'>, + 'cath': <'fred','bob','ed','gav','hal','col','ian','abe','dan','jon'>, + 'dee': <'fred','jon','col','abe','ian','hal','gav','dan','bob','ed'>, + 'eve': <'jon','hal','fred','dan','abe','gav','col','ed','ian','bob'>, + 'fay': <'bob','abe','ed','ian','jon','dan','fred','gav','col','hal'>, + 'gay': <'jon','gav','hal','fred','bob','abe','col','ed','dan','ian'>, + 'hope': <'gav','jon','bob','abe','ian','dan','hal','ed','col','fred'>, + 'ivy': <'ian','col','hal','gav','fred','bob','abe','ed','jon','dan'>, + 'jan': <'ed','hal','gav','abe','bob','jon','col','ian','fred','dan'>} + +match = # finds a stable list of engagements from data as given above + +-+ + ^=rrmhPnXS ^/~&l ^/~&rl ^|DlrHSs/~& ^TlK2hlPrSLPAS\~&r -+ + ~&lK2hlPrSXS, + *=rnmihBPK12D ~&mmhPnXNCB^rnPrmPllSPcA\~&r ~&lrrPwZK17@rnPlX+-, + ^|rrPlrlPXX/~& ^/~&nNAS ^/~&l+ ^|H\~&+ -:+ * ^|/~& -<+ \/-=+ ~&DSL@tK33+- + +preferred = # finds non-couples that would prefer each other to their betrothed + +~&lSLPrSLrlXS2c^|DlrHS\~& ~~irlXX+ ^D/~&l+ ^|H\~&+ -:+ *T ^|/~& //~=;+ -~l;+ \/~&H + +#cast %sWLm + +main = # stable, perturbed, and preferred alternatives to the perturbed + +< + 'stable': match/men women, + 'perturbed': ~&lSrSxPp match/men women, + 'preferred': preferred/(men,women) ~&lSrSxPp match/men women> diff --git a/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-1.xslt b/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-1.xslt new file mode 100644 index 0000000000..66a46eea16 --- /dev/null +++ b/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-1.xslt @@ -0,0 +1,136 @@ +<xsl:stylesheet version="2.0" + xmlns:xsl="http://www.w3.org/1999/XSL/Transform" + xmlns:fn="http://www.w3.org/2005/xpath-functions" + xmlns:xs="http://www.w3.org/2001/XMLSchema" + xmlns:m="http://rosettacode.org/wiki/Stable_marriage_problem" + xmlns:t="http://rosettacode.org/wiki/Stable_marriage_problem/temp" + exclude-result-prefixes="xsl xs fn t m"> +<xsl:output indent="yes" encoding="UTF-8" omit-xml-declaration="yes" /> +<xsl:strip-space elements="*" /> + +<xsl:template match="*"> + <xsl:copy> + <xsl:apply-templates select="@*,node()" /> + </xsl:copy> +</xsl:template> + +<xsl:template match="@*|comment()|processing-instruction()"> + <xsl:copy /> +</xsl:template> + +<xsl:template match="m:interest" mode="match-making"> + <m:engagement> + <m:dude name="{../@name}" /><m:maid name="{.}" /> + </m:engagement> +</xsl:template> + +<xsl:template match="m:dude" mode="match-making"> + <!-- 3. Reject suitors cross-off the maids that spurned them. --> + <xsl:param name="eliminations" select="()" /> + <m:dude name="{@name}"> + <xsl:copy-of select="for $b in @name return + m:interest[not(. = $eliminations[m:dude/@name=$b]/m:maid/@name)]" /> + </m:dude> +</xsl:template> + +<xsl:template match="*" mode="perturbation"> + <xsl:copy> + <xsl:apply-templates select="@*,node()" mode="perturbation"/> + </xsl:copy> +</xsl:template> + +<xsl:template match="@*" mode="perturbation"> + <xsl:copy /> +</xsl:template> + +<xsl:template match="m:engagement[position() lt 3]/m:maid/@name" mode="perturbation"> + <!-- Swap maids 1 and 2. --> + <xsl:copy-of select="for $c in count(../../preceding-sibling::m:engagement) + return ../../../m:engagement[2 - $c]/m:maid/@name" /> +</xsl:template> + +<xsl:template match="m:stable-marriage-problem"> + <xsl:variable name="population" select="m:dude|m:maid" /> + <xsl:variable name="solution"> + <xsl:call-template name="solve-it"> + <xsl:with-param name="dudes" select="m:dude" /> + <xsl:with-param name="maids" select="m:maid" tunnel="yes" /> + </xsl:call-template> + </xsl:variable> + <xsl:variable name="perturbed"> + <xsl:apply-templates select="$solution/*" mode="perturbation" /> + </xsl:variable> + <m:stable-marriage-problem-result> + <m:solution is-stable="{t:is-stable( $population, $solution/*)}"> + <xsl:copy-of select="$solution/*" /> + </m:solution> + <m:message>Perturbing the matches! Swapping <xsl:value-of select="$solution/*[1]/m:maid/@name" /> for <xsl:value-of select="$solution/*[2]/m:maid/@name" /></m:message> + <m:message><xsl:choose> + <xsl:when test="t:is-stable( $population, $perturbed/*)"> + <xsl:text>The perturbed configuration is stable.</xsl:text> + </xsl:when> + <xsl:otherwise>The perturbed configuration is unstable.</xsl:otherwise> + </xsl:choose></m:message> + </m:stable-marriage-problem-result> +</xsl:template> + +<xsl:template name="solve-it"> + <xsl:param name="dudes" as="element()*" /> <!-- Sequence of m:dude --> + <xsl:param name="maids" as="element()*" tunnel="yes" /> <!-- Sequence of m:maid --> + <xsl:param name="engagements" as="element()*" select="()" /> <!-- Sequence of m:engagement --> + + <!-- 1. For each dude not yet engaged, and has a preference, propose to his top preference. --> + <xsl:variable name="fresh-proposals"> + <xsl:apply-templates select="$dudes[not(@name = $engagements/m:dude/@name)]/m:interest[1]" mode="match-making" /> + </xsl:variable> + <xsl:variable name="proposals" select="$engagements | $fresh-proposals/m:engagement" /> + + <!-- 2. For each maid with conflicting suitors, reject all but the most attractive (for her) proposal. --> + <xsl:variable name="acceptable" select="$proposals[ + for $g in m:maid/@name, $b in m:dude/@name, $this-interest in $maids[@name=$g]/m:interest[.=$b] + return every + $interest + in + for $other-b in $proposals[m:maid[@name=$g]]/m:dude/@name[. ne $b] + return $maids[@name=$g]/m:interest[.=$other-b] + satisfies + $interest >> $this-interest + ]" /> + + <!-- 3. Reject suitors cross-off the maids that spurned them. --> + <xsl:variable name="new-dudes"> + <xsl:apply-templates select="$dudes" mode="match-making"> + <xsl:with-param name="eliminations" select="$fresh-proposals/m:engagement" /> + </xsl:apply-templates> + </xsl:variable> + + <!-- 4. Test for finish. If not, loop back for another round of proposals. --> + <xsl:choose> + <xsl:when test="$dudes[not(for $b in @name return $acceptable[m:dude/@name=$b])]"> + <xsl:call-template name="solve-it"> + <xsl:with-param name="dudes" select="$new-dudes/m:dude" /> + <xsl:with-param name="engagements" select="$acceptable" /> + </xsl:call-template> + </xsl:when> + <xsl:otherwise> + <xsl:copy-of select="$acceptable" /> + </xsl:otherwise> + </xsl:choose> +</xsl:template> + +<xsl:function name="t:is-stable" as="xs:boolean"> + <xsl:param name="population" as="element()*" /> + <xsl:param name="engagements" as="element()*" /> + <xsl:sequence select=" + every $e in $engagements, + $b in string($e/m:dude/@name), $g in string($e/m:maid/@name), + $desired-g in $population/self::m:dude[@name=$b]/m:interest[$g=following-sibling::m:interest], + $desired-maid in $population/self::m:maid[@name=$desired-g] + satisfies + not( + $desired-maid/m:interest[.=$b] << + $desired-maid/m:interest[.=$engagements[m:maid[@name=$desired-g]]/m:dude/@name]) + " /> +</xsl:function> + +</xsl:stylesheet> diff --git a/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-2.xslt b/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-2.xslt new file mode 100644 index 0000000000..268871d06b --- /dev/null +++ b/Task/Stable-marriage-problem/XSLT-2.0/stable-marriage-problem-2.xslt @@ -0,0 +1,48 @@ +<t> + <m:stable-marriage-problem-result xmlns:m="http://rosettacode.org/wiki/Stable_marriage_problem"> + <m:solution is-stable="true"> + <m:engagement> + <m:dude name="bob"/> + <m:maid name="cath"/> + </m:engagement> + <m:engagement> + <m:dude name="ed"/> + <m:maid name="jan"/> + </m:engagement> + <m:engagement> + <m:dude name="fred"/> + <m:maid name="bea"/> + </m:engagement> + <m:engagement> + <m:dude name="gav"/> + <m:maid name="gay"/> + </m:engagement> + <m:engagement> + <m:dude name="ian"/> + <m:maid name="hope"/> + </m:engagement> + <m:engagement> + <m:dude name="jon"/> + <m:maid name="abi"/> + </m:engagement> + <m:engagement> + <m:dude name="hal"/> + <m:maid name="eve"/> + </m:engagement> + <m:engagement> + <m:dude name="abe"/> + <m:maid name="ivy"/> + </m:engagement> + <m:engagement> + <m:dude name="col"/> + <m:maid name="dee"/> + </m:engagement> + <m:engagement> + <m:dude name="dan"/> + <m:maid name="fay"/> + </m:engagement> + </m:solution> + <m:message>Perturbing the matches! Swapping cath for jan</m:message> + <m:message>The perturbed configuration is unstable.</m:message> + </m:stable-marriage-problem-result> +</t> diff --git a/Task/Stack-traces/0DESCRIPTION b/Task/Stack-traces/0DESCRIPTION new file mode 100644 index 0000000000..b32491d6e0 --- /dev/null +++ b/Task/Stack-traces/0DESCRIPTION @@ -0,0 +1,6 @@ +Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. + +This task calls for you to print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination. + +The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program. +<br clear=all> diff --git a/Task/Stack-traces/1META.yaml b/Task/Stack-traces/1META.yaml new file mode 100644 index 0000000000..f6d82c59ad --- /dev/null +++ b/Task/Stack-traces/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming environment operations diff --git a/Task/Stack-traces/Ada/stack-traces.ada b/Task/Stack-traces/Ada/stack-traces.ada new file mode 100644 index 0000000000..11d46e94b1 --- /dev/null +++ b/Task/Stack-traces/Ada/stack-traces.ada @@ -0,0 +1,31 @@ +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.Traceback; use GNAT.Traceback; +with GNAT.Traceback.Symbolic; use GNAT.Traceback.Symbolic; + +procedure Test_Stack_Trace is + procedure Call_Stack is + Trace : Tracebacks_Array (1..1_000); + Length : Natural; + begin + Call_Chain (Trace, Length); + Put_Line (Symbolic_Traceback (Trace (1..Length))); + end Call_Stack; + + procedure Inner (K : Integer) is + begin + Call_Stack; + end Inner; + + procedure Middle (X, Y : Integer) is + begin + Inner (X * Y); + end Middle; + + procedure Outer (A, B, C : Integer) is + begin + Middle (A + B, B + C); + end Outer; + +begin + Outer (2,3,5); +end Test_Stack_Trace; diff --git a/Task/Stack-traces/AutoHotkey/stack-traces-1.ahk b/Task/Stack-traces/AutoHotkey/stack-traces-1.ahk new file mode 100644 index 0000000000..03dcfcc853 --- /dev/null +++ b/Task/Stack-traces/AutoHotkey/stack-traces-1.ahk @@ -0,0 +1,17 @@ +f() +return + +f() +{ +return g() +} + +g() +{ +ListLines +msgbox, lines recently executed +x = local to g +ListVars +msgbox, variable bindings +} +#Persistent diff --git a/Task/Stack-traces/AutoHotkey/stack-traces-2.ahk b/Task/Stack-traces/AutoHotkey/stack-traces-2.ahk new file mode 100644 index 0000000000..7903e2511d --- /dev/null +++ b/Task/Stack-traces/AutoHotkey/stack-traces-2.ahk @@ -0,0 +1,14 @@ +001: f() +006: Return,g() +011: ListLines (0.05) +012: MsgBox,lines recently executed (3.81) +013: x = local to g +014: ListVars +015: MsgBox,variable bindings (3.94) +016: } +002: Return (181.66) + +Global Variables (alphabetical) +-------------------------------------------------- +0[1 of 3]: 0 +ErrorLevel[1 of 3]: 0 diff --git a/Task/Stack-traces/C/stack-traces-1.c b/Task/Stack-traces/C/stack-traces-1.c new file mode 100644 index 0000000000..b8790bee1c --- /dev/null +++ b/Task/Stack-traces/C/stack-traces-1.c @@ -0,0 +1,39 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#include <execinfo.h> + +#define MAX_BT 200 + +void print_stack_trace() +{ + void *buffer[MAX_BT]; + int n; + + n = backtrace(buffer, MAX_BT); + fprintf(stderr, "--- (depth %d) ---\n", n); + backtrace_symbols_fd(buffer, n, STDERR_FILENO); +} + + +void inner(int k) +{ + print_stack_trace(); +} + +void middle(int x, int y) +{ + inner(x*y); +} + +void outer(int a, int b, int c) +{ + middle(a+b, b+c); +} + +int main() +{ + outer(2,3,5); + return EXIT_SUCCESS; +} diff --git a/Task/Stack-traces/C/stack-traces-2.c b/Task/Stack-traces/C/stack-traces-2.c new file mode 100644 index 0000000000..689d093b1e --- /dev/null +++ b/Task/Stack-traces/C/stack-traces-2.c @@ -0,0 +1,79 @@ +/* stack_trace.c - macros for hinting/tracing where a program crashed + on a system _without_ any form of debugger. + +Simple goodbye_cruel_world.c example: + +#include <stdio.h> +#include <stdlib.h> + +#define STACK_TRACE_ON // compile in these "stack_trace" routines +#include "stack_trace.h" + +void goodbye_cruel_world() +BEGIN(goodbye_cruel_world) + print_stack_trace(); + for(;;){} +END + +int main() +BEGIN(main) + stack_trace.on = TRUE; // turn on runtime tracing + goodbye_cruel_world(); + stack_trace.on = FALSE; + RETURN(EXIT_SUCCESS); +END + +Output: +goodbye_cruel_world.c:8: BEGIN goodbye_cruel_world[0x80486a8], stack(depth:1, size:60) +goodbye_cruel_world.c:8: goodbye_cruel_world[0x80486a8] --- stack(depth:2, size:60) --- +goodbye_cruel_world.c:14: main[0x80486f4] --- stack(depth:1, size:0) --- +goodbye_cruel_world.c:8: --- (depth 2) --- + +*/ +#ifndef _LINUX_STDDEF_H +#include <stddef.h> +#endif + +typedef struct stack_trace_frame_s { + const char *file_name; + int file_line; + const char *proc_name; + void *proc_addr; + struct stack_trace_frame_s *down, *up; +} stack_trace_frame_t; + +#define SKIP +typedef enum {TRUE=1, FALSE=0} bool_t; + +typedef struct { + bool_t on; + struct { const char *_begin, *_print, *_return, *_exit, *_end; } fmt; + struct { int depth; stack_trace_frame_t *lwb, *upb; } stack; + struct { int lwb, by, upb; const char *prefix; } indent; +} stack_trace_t; + +extern stack_trace_t stack_trace; + +void stack_trace_begin(char *SKIP, stack_trace_frame_t *SKIP); +void stack_trace_end(char *SKIP, int SKIP); +void print_stack_trace(); + + +#ifdef STACK_TRACE_ON + +/* Many ThanX to Steve R Bourne for inspiring the following macros ;-) */ +#define BEGIN(x) { auto stack_trace_frame_t this = {__FILE__, __LINE__, #x, &x, NULL, NULL}; \ + stack_trace_begin(stack_trace.fmt._begin, &this); { +#define RETURN(x) { stack_trace_end(stack_trace.fmt._return, __LINE__); return(x); } +#define EXIT(x) { stack_trace_end(stack_trace.fmt._exit, __LINE__); exit(x); } +#define END } stack_trace_end(stack_trace.fmt._end, __LINE__); } + +#else + +/* Apologies to Landon Curt Noll and Larry Bassel for the following macros :-) */ +#define BEGIN(x) { +#define RETURN(x) return(x) +#define EXIT(x) exit(x) +#define END } + +#endif diff --git a/Task/Stack-traces/C/stack-traces-3.c b/Task/Stack-traces/C/stack-traces-3.c new file mode 100644 index 0000000000..1005751baf --- /dev/null +++ b/Task/Stack-traces/C/stack-traces-3.c @@ -0,0 +1,85 @@ +#include <stdio.h> +#include <stddef.h> + +#define STACK_TRACE_ON +#include "stack_trace.h" + +#define indent_fmt "%s" +#define std_cc_diag_fmt "%s:%d: " +#define stack_trace_diag_fmt " %s[0x%x], stack(depth:%d, size:%u)\n" +#define stack_trace_fmt "%s:%d:\t%s[0x%x]\t--- stack(depth:%d, size:%u) ---\n" + +stack_trace_t stack_trace = { + FALSE, /* default: stack_trace.on == FALSE */ + { std_cc_diag_fmt""indent_fmt"BEGIN"stack_trace_diag_fmt, + stack_trace_fmt, + std_cc_diag_fmt""indent_fmt"RETURN"stack_trace_diag_fmt, + std_cc_diag_fmt""indent_fmt"EXIT"stack_trace_diag_fmt, + std_cc_diag_fmt""indent_fmt"END"stack_trace_diag_fmt }, + { 0, (stack_trace_frame_t*)NULL, (stack_trace_frame_t*)NULL }, /* stack */ + { 19, 2, 20, " " } /* indent wrap */ + }; + +void stack_trace_begin(const char *fmt, stack_trace_frame_t *this){ + if(stack_trace.on){ + fprintf(stderr, fmt, + this->file_name, this->file_line, /* file details */ + stack_trace.indent.prefix+stack_trace.indent.lwb, + this->proc_name, this->proc_addr, /* procedure details */ + stack_trace.stack.depth, (unsigned)stack_trace.stack.lwb-(unsigned)this); + stack_trace.indent.lwb = + ( stack_trace.indent.lwb - stack_trace.indent.by ) % stack_trace.indent.upb; + } + + if(!stack_trace.stack.upb){ /* this IS the stack !! */ + stack_trace.stack.lwb = stack_trace.stack.upb = this; + } else { + this -> down = stack_trace.stack.upb; + stack_trace.stack.upb -> up = this; + stack_trace.stack.upb = this; + } + stack_trace.stack.depth++; +} + +void stack_trace_end(const char *fmt, int line){ + stack_trace.stack.depth--; + if(stack_trace.on){ + stack_trace.indent.lwb = + ( stack_trace.indent.lwb + stack_trace.indent.by ) % stack_trace.indent.upb; + stack_trace_frame_t *this = stack_trace.stack.upb; + fprintf(stderr, fmt, + this->file_name, this->file_line, /* file details */ + stack_trace.indent.prefix+stack_trace.indent.lwb, + this->proc_name, this->proc_addr, /* procedure details */ + stack_trace.stack.depth, (unsigned)stack_trace.stack.lwb-(unsigned)this); + } + stack_trace.stack.upb = stack_trace.stack.upb -> down; +} + +void print_indent(){ + if(!stack_trace.stack.upb){ + /* fprintf(stderr, "STACK_TRACE_ON not #defined during compilation\n"); */ + } else { + stack_trace_frame_t *this = stack_trace.stack.upb; + fprintf(stderr, std_cc_diag_fmt""indent_fmt, + this->file_name, this->file_line, /* file details */ + stack_trace.indent.prefix+stack_trace.indent.lwb + ); + } +} + +void print_stack_trace() { + if(!stack_trace.stack.upb){ + /* fprintf(stderr, "STACK_TRACE_ON not #defined during compilation\n"); */ + } else { + int depth = stack_trace.stack.depth; + stack_trace_frame_t *this = stack_trace.stack.upb; + for(this = stack_trace.stack.upb; this; this = this->down, depth--){ + fprintf(stderr, stack_trace.fmt._print, + this->file_name, this->file_line, /* file details */ + this->proc_name, this->proc_addr, /* procedure details */ + depth, (unsigned)stack_trace.stack.lwb-(unsigned)this); + } + print_indent(); fprintf(stderr, "--- (depth %d) ---\n", stack_trace.stack.depth); + } +} diff --git a/Task/Stack-traces/C/stack-traces-4.c b/Task/Stack-traces/C/stack-traces-4.c new file mode 100644 index 0000000000..7559689ab6 --- /dev/null +++ b/Task/Stack-traces/C/stack-traces-4.c @@ -0,0 +1,29 @@ +#include <stdio.h> +#include <stdlib.h> + +#define STACK_TRACE_ON /* compile in these "stack_trace" routines */ +#include "stack_trace.h" + +void inner(int k) +BEGIN(inner) + print_indent(); printf("*** Now dump the stack ***\n"); + print_stack_trace(); +END + +void middle(int x, int y) +BEGIN(middle) + inner(x*y); +END + +void outer(int a, int b, int c) +BEGIN(outer) + middle(a+b, b+c); +END + +int main() +BEGIN(main) + stack_trace.on = TRUE; /* turn on runtime tracing */ + outer(2,3,5); + stack_trace.on = FALSE; + RETURN(EXIT_SUCCESS); +END diff --git a/Task/Stack-traces/Common-Lisp/stack-traces-1.lisp b/Task/Stack-traces/Common-Lisp/stack-traces-1.lisp new file mode 100644 index 0000000000..598787962a --- /dev/null +++ b/Task/Stack-traces/Common-Lisp/stack-traces-1.lisp @@ -0,0 +1,3 @@ +(swank-backend:call-with-debugging-environment + (lambda () + (swank:backtrace 0 nil))) diff --git a/Task/Stack-traces/Common-Lisp/stack-traces-2.lisp b/Task/Stack-traces/Common-Lisp/stack-traces-2.lisp new file mode 100644 index 0000000000..b1fc8cfca4 --- /dev/null +++ b/Task/Stack-traces/Common-Lisp/stack-traces-2.lisp @@ -0,0 +1,4 @@ +((0 "((LAMBDA (SWANK-BACKEND::DEBUGGER-LOOP-FN)) #<FUNCTION (LAMBDA #) {100459BBC9}>)") + (1 "(SB-INT:SIMPLE-EVAL-IN-LEXENV (SWANK-BACKEND:CALL-WITH-DEBUGGING-ENVIRONMENT (LAMBDA () (SWANK:BACKTRACE 0 NIL))) #<NULL-LEXENV>)") + (2 "(SWANK::EVAL-REGION \"(swank-backend:call-with-debugging-environment\\n (lambda ()\\n (swank:backtrace 0 nil)))\\n\\n\")") + (3 "((LAMBDA ()))") ...) diff --git a/Task/Stack-traces/Common-Lisp/stack-traces-3.lisp b/Task/Stack-traces/Common-Lisp/stack-traces-3.lisp new file mode 100644 index 0000000000..277316493a --- /dev/null +++ b/Task/Stack-traces/Common-Lisp/stack-traces-3.lisp @@ -0,0 +1,17 @@ +CL-USER> (sb-debug:backtrace 7) +0: (SB-DEBUG::MAP-BACKTRACE + #<CLOSURE (LAMBDA (SB-DEBUG::FRAME)) {1193EFCD}>)[:EXTERNAL] +1: (BACKTRACE + 7 + #<TWO-WAY-STREAM + :INPUT-STREAM #<SWANK-BACKEND::SLIME-INPUT-STREAM {120F6519}> + :OUTPUT-STREAM #<SWANK-BACKEND::SLIME-OUTPUT-STREAM {1208F3E1}>>) +2: (SB-INT:SIMPLE-EVAL-IN-LEXENV (BACKTRACE 7) #<NULL-LEXENV>) +3: (SWANK::EVAL-REGION + "(sb-debug:backtrace 7) +") +4: ((LAMBDA ())) +5: (SWANK::TRACK-PACKAGE #<CLOSURE (LAMBDA ()) {1193ECBD}>) +6: (SWANK::CALL-WITH-RETRY-RESTART + "Retry SLIME REPL evaluation request." + #<CLOSURE (LAMBDA ()) {1193EC4D}>) diff --git a/Task/Stack-traces/D/stack-traces.d b/Task/Stack-traces/D/stack-traces.d new file mode 100644 index 0000000000..29487329b2 --- /dev/null +++ b/Task/Stack-traces/D/stack-traces.d @@ -0,0 +1,22 @@ +import std.stdio; + +void inner() { + try + throw new Exception(null); + catch (Exception e) + writeln(e); + + writeln("running"); +} + +void middle() { + inner(); +} + +void outer() { + middle(); +} + +void main() { + outer(); +} diff --git a/Task/Stack-traces/DWScript/stack-traces.dwscript b/Task/Stack-traces/DWScript/stack-traces.dwscript new file mode 100644 index 0000000000..39808e60bd --- /dev/null +++ b/Task/Stack-traces/DWScript/stack-traces.dwscript @@ -0,0 +1,21 @@ +procedure Inner; +begin + try + raise Exception.Create(''); + except + on E: Exception do + PrintLn(E.StackTrace); + end; +end; + +procedure Middle; +begin + Inner; +end; + +procedure Outer; +begin + Middle; +end; + +Outer; diff --git a/Task/Stack-traces/Forth/stack-traces.fth b/Task/Stack-traces/Forth/stack-traces.fth new file mode 100644 index 0000000000..173d655fd3 --- /dev/null +++ b/Task/Stack-traces/Forth/stack-traces.fth @@ -0,0 +1,14 @@ +[UNDEFINED] R.S [IF] +\ Return stack counterpart of DEPTH +\ Note the STACK-CELLS correction is there to hide RDEPTH itself + ( -- n) +: RDEPTH STACK-CELLS -2 [+] CELLS RP@ - ; + +\ Return stack counterpart of .S +\ Note the : R.S R> .. >R ; sequence is there to hide R.S itself + ( --) +: R.S R> CR RDEPTH DUP 0> IF DUP + BEGIN DUP WHILE R> -ROT 1- REPEAT DROP DUP + BEGIN DUP WHILE ROT DUP . >R 1- REPEAT DROP + THEN ." (TORS) " DROP >R ; +[THEN] diff --git a/Task/Stack-traces/Go/stack-traces.go b/Task/Stack-traces/Go/stack-traces.go new file mode 100644 index 0000000000..e7400efc7c --- /dev/null +++ b/Task/Stack-traces/Go/stack-traces.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "runtime/debug" +) + +func main() { + // to print it to standard error + debug.PrintStack() + // alternately to get it in a variable: + stackTrace := debug.Stack() + fmt.Printf("(%d bytes)\n", len(stackTrace)) +} diff --git a/Task/Stack-traces/Groovy/stack-traces-1.groovy b/Task/Stack-traces/Groovy/stack-traces-1.groovy new file mode 100644 index 0000000000..e11e5d4994 --- /dev/null +++ b/Task/Stack-traces/Groovy/stack-traces-1.groovy @@ -0,0 +1 @@ +def rawTrace = { Thread.currentThread().stackTrace } diff --git a/Task/Stack-traces/Groovy/stack-traces-2.groovy b/Task/Stack-traces/Groovy/stack-traces-2.groovy new file mode 100644 index 0000000000..e0b6bb43ef --- /dev/null +++ b/Task/Stack-traces/Groovy/stack-traces-2.groovy @@ -0,0 +1,14 @@ +def trace = rawTrace().collect { + def props = it.properties + def keys = (it.properties.keySet() - (new Object().properties.keySet())) + props.findAll{ k, v -> k in keys } +} + +def propNames = trace[0].keySet().sort() +def propWidths = propNames.collect { name -> [name, trace.collect{ it[name].toString() }].flatten()*.size().max() } + +propNames.eachWithIndex{ name, i -> printf("%-${propWidths[i]}s ", name) }; println '' +propWidths.each{ width -> print('-' * width + ' ') }; println '' +trace.each { + propNames.eachWithIndex{ name, i -> printf("%-${propWidths[i]}s ", it[name].toString()) }; println '' +} diff --git a/Task/Stack-traces/Groovy/stack-traces-3.groovy b/Task/Stack-traces/Groovy/stack-traces-3.groovy new file mode 100644 index 0000000000..4921f9e78f --- /dev/null +++ b/Task/Stack-traces/Groovy/stack-traces-3.groovy @@ -0,0 +1,16 @@ +import Utils # for buildStackTrace + +procedure main() + g() + write() + f() +end + +procedure f() + g() +end + +procedure g() + # Using 1 as argument omits the trace of buildStackTrace itself + every write("\t",!buildStackTrace(1)) +end diff --git a/Task/Stack-traces/Groovy/stack-traces-4.groovy b/Task/Stack-traces/Groovy/stack-traces-4.groovy new file mode 100644 index 0000000000..4066187a61 --- /dev/null +++ b/Task/Stack-traces/Groovy/stack-traces-4.groovy @@ -0,0 +1,22 @@ +#<p> +# Compute the current stack trace. Starting at level <i>n</i> above +# the current procedure. Here, <i>n</i> defaults to 0, which will +# include this procedure in the stack trace. +# <i>ce</i> defaults to ¤t. +# <i>This only works with newer versions of Unicon!</i> +# <[generates the stacktrace from current call back to first +# in the co-expression]> +#</p> +procedure buildStackTrace(n:0, # starting distance from this call + ce # co-expr to trace stack in [¤t] + ) + local L + /ce := ¤t + L := []; n -:= 1 + while pName := image(proc(ce, n+:=1)) do { + fName := keyword("&file",ce,n) | "no file name" + fLine := keyword("&line",ce,n) | "no line number" + put(L, pName||" ["||fName||":"||fLine||"]" ) + } + return L +end diff --git a/Task/Stack-traces/J/stack-traces-1.j b/Task/Stack-traces/J/stack-traces-1.j new file mode 100644 index 0000000000..7595fb04ff --- /dev/null +++ b/Task/Stack-traces/J/stack-traces-1.j @@ -0,0 +1 @@ + 13!:0]1 diff --git a/Task/Stack-traces/J/stack-traces-2.j b/Task/Stack-traces/J/stack-traces-2.j new file mode 100644 index 0000000000..ca0382f76b --- /dev/null +++ b/Task/Stack-traces/J/stack-traces-2.j @@ -0,0 +1 @@ + 13!:13'' diff --git a/Task/Stack-traces/J/stack-traces-3.j b/Task/Stack-traces/J/stack-traces-3.j new file mode 100644 index 0000000000..f0b47df421 --- /dev/null +++ b/Task/Stack-traces/J/stack-traces-3.j @@ -0,0 +1,14 @@ + f=:g + g=:13!:13 bind '' + f 7 NB. empty stack trace because debugging has not been enabled + 13!:0]1 + f 7 +┌─┬─┬─┬─┬─────────────┬┬───┬──┬─┐ +│g│0│0│3│13!:13@(''"_)││┌─┐│ │ │ +│ │ │ │ │ │││7││ │ │ +│ │ │ │ │ ││└─┘│ │ │ +├─┼─┼─┼─┼─────────────┼┼───┼──┼─┤ +│f│0│0│3│g ││┌─┐│ │ │ +│ │ │ │ │ │││7││ │ │ +│ │ │ │ │ ││└─┘│ │ │ +└─┴─┴─┴─┴─────────────┴┴───┴──┴─┘ diff --git a/Task/Stack-traces/Java/stack-traces-1.java b/Task/Stack-traces/Java/stack-traces-1.java new file mode 100644 index 0000000000..5aa037f195 --- /dev/null +++ b/Task/Stack-traces/Java/stack-traces-1.java @@ -0,0 +1,11 @@ +public class StackTracer { + public static void printStackTrace() { + StackTraceElement[] elems = Thread.currentThread().getStackTrace(); + + System.out.println("Stack trace:"); + for (int i = elems.length-1, j = 2 ; i >= 3 ; i--, j+=2) { + System.out.printf("%" + j + "s%s.%s%n", "", + elems[i].getClassName(), elems[i].getMethodName()); + } + } +} diff --git a/Task/Stack-traces/Java/stack-traces-2.java b/Task/Stack-traces/Java/stack-traces-2.java new file mode 100644 index 0000000000..6503575069 --- /dev/null +++ b/Task/Stack-traces/Java/stack-traces-2.java @@ -0,0 +1,14 @@ +public class StackTraceDemo { + static void inner() { + StackTracer.printStackTrace(); + } + static void middle() { + inner(); + } + static void outer() { + middle(); + } + public static void main(String[] args) { + outer(); + } +} diff --git a/Task/Stack-traces/JavaScript/stack-traces-1.js b/Task/Stack-traces/JavaScript/stack-traces-1.js new file mode 100644 index 0000000000..d8eeeb3f2a --- /dev/null +++ b/Task/Stack-traces/JavaScript/stack-traces-1.js @@ -0,0 +1,5 @@ +try { + throw new Error; +} catch(e) { + alert(e.stack); +} diff --git a/Task/Stack-traces/JavaScript/stack-traces-2.js b/Task/Stack-traces/JavaScript/stack-traces-2.js new file mode 100644 index 0000000000..784c140ef8 --- /dev/null +++ b/Task/Stack-traces/JavaScript/stack-traces-2.js @@ -0,0 +1,9 @@ +function foo () { + var stack = "Stack trace:"; + for (var f = arguments.callee // current function + ; f; f = f.caller) { + stack += "\n" + f.name; + } + alert(stack); +} +foo(); diff --git a/Task/Stack-traces/Lua/stack-traces.lua b/Task/Stack-traces/Lua/stack-traces.lua new file mode 100644 index 0000000000..426fad9580 --- /dev/null +++ b/Task/Stack-traces/Lua/stack-traces.lua @@ -0,0 +1,14 @@ +function Inner( k ) + print( debug.traceback() ) + print "Program continues..." +end + +function Middle( x, y ) + Inner( x+y ) +end + +function Outer( a, b, c ) + Middle( a*b, c ) +end + +Outer( 2, 3, 5 ) diff --git a/Task/Stack-traces/Mathematica/stack-traces-1.math b/Task/Stack-traces/Mathematica/stack-traces-1.math new file mode 100644 index 0000000000..68d0a0f768 --- /dev/null +++ b/Task/Stack-traces/Mathematica/stack-traces-1.math @@ -0,0 +1 @@ +f[g[1, Print[Stack[]]; 2]] diff --git a/Task/Stack-traces/Mathematica/stack-traces-2.math b/Task/Stack-traces/Mathematica/stack-traces-2.math new file mode 100644 index 0000000000..d35d21889e --- /dev/null +++ b/Task/Stack-traces/Mathematica/stack-traces-2.math @@ -0,0 +1,2 @@ +{f,g,CompoundExpression,Print} +f[g[1, 2]] diff --git a/Task/Stack-traces/Mathematica/stack-traces-3.math b/Task/Stack-traces/Mathematica/stack-traces-3.math new file mode 100644 index 0000000000..cf86d87582 --- /dev/null +++ b/Task/Stack-traces/Mathematica/stack-traces-3.math @@ -0,0 +1 @@ +f[g[1, Print[Stack[_]]; 2]] diff --git a/Task/Stack-traces/Mathematica/stack-traces-4.math b/Task/Stack-traces/Mathematica/stack-traces-4.math new file mode 100644 index 0000000000..2c57647e60 --- /dev/null +++ b/Task/Stack-traces/Mathematica/stack-traces-4.math @@ -0,0 +1,2 @@ +{f[g[1,Print[Stack[_]];2]],g[1,Print[Stack[_]];2],Print[Stack[_]];2,Print[Stack[_]]} +f[g[1, 2]] diff --git a/Task/Stack-traces/NetRexx/stack-traces.netrexx b/Task/Stack-traces/NetRexx/stack-traces.netrexx new file mode 100644 index 0000000000..799c1cc96e --- /dev/null +++ b/Task/Stack-traces/NetRexx/stack-traces.netrexx @@ -0,0 +1,22 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +class RStackTraces + method inner() static + StackTracer.printStackTrace() + method middle() static + inner() + method outer() static + middle() + method main(args = String[]) public static + outer() + +class RStackTraces.StackTracer + method printStackTrace() public static + elems = Thread.currentThread().getStackTrace() + say 'Stack trace:' + j_ = 2 + loop i_ = elems.length - 1 to 2 by -1 + say ''.left(j_) || elems[i_].getClassName()'.'elems[i_].getMethodName() + j_ = j_ + 2 + end i_ diff --git a/Task/Stack-traces/OCaml/stack-traces-1.ocaml b/Task/Stack-traces/OCaml/stack-traces-1.ocaml new file mode 100644 index 0000000000..43f4f34924 --- /dev/null +++ b/Task/Stack-traces/OCaml/stack-traces-1.ocaml @@ -0,0 +1,8 @@ +let div a b = a / b + +let () = + try let _ = div 3 0 in () + with e -> + prerr_endline(Printexc.to_string e); + Printexc.print_backtrace stderr; +;; diff --git a/Task/Stack-traces/OCaml/stack-traces-2.ocaml b/Task/Stack-traces/OCaml/stack-traces-2.ocaml new file mode 100644 index 0000000000..d86076a6c1 --- /dev/null +++ b/Task/Stack-traces/OCaml/stack-traces-2.ocaml @@ -0,0 +1,5 @@ +let div a b = a / b + +let () = + let _ = div 3 0 in () +;; diff --git a/Task/Stack-traces/Objective-C/stack-traces-1.m b/Task/Stack-traces/Objective-C/stack-traces-1.m new file mode 100644 index 0000000000..69d5cd1c92 --- /dev/null +++ b/Task/Stack-traces/Objective-C/stack-traces-1.m @@ -0,0 +1,9 @@ +#include <execinfo.h> + +void *frames[128]; +int len = backtrace(frames, 128); +char **symbols = backtrace_symbols(frames, len); +for (int i = 0; i < len; ++i) { + NSLog(@"%s", symbols[i]); +} +free(symbols); diff --git a/Task/Stack-traces/Objective-C/stack-traces-2.m b/Task/Stack-traces/Objective-C/stack-traces-2.m new file mode 100644 index 0000000000..188ff9958e --- /dev/null +++ b/Task/Stack-traces/Objective-C/stack-traces-2.m @@ -0,0 +1,4 @@ +NSArray *symbols = [NSThread callStackSymbols]; +for (NSString *symbol in symbols) { + NSLog(@"%@", symbol); +} diff --git a/Task/Stack-traces/OxygenBasic/stack-traces.oxy b/Task/Stack-traces/OxygenBasic/stack-traces.oxy new file mode 100644 index 0000000000..3370cdd975 --- /dev/null +++ b/Task/Stack-traces/OxygenBasic/stack-traces.oxy @@ -0,0 +1,80 @@ +'32bit x86 + +static string Report + + +macro ReportStack(n) +'=================== + + ' + scope + ' + static sys stack[0X100],stackptr,e + ' + 'CAPTURE IMAGE OF UP TO 256 ENTRIES + ' + ' + mov eax,n + cmp eax,0x100 + ( + jle exit + mov eax,0x100 'UPPER LIMIT + ) + mov e,eax + mov stackptr,esp + lea edx,stack + mov ecx,e + mov esi,esp + ( + mov eax,[esi] + mov [edx],eax + add esi,4 + add edx,4 + dec ecx + jg repeat + ) + sys i + string cr=chr(13)+chr(10), tab=chr(9) + ' + for i=1 to e + report+=hex(stackptr+(i-1)*4,8) tab hex(i-1,2) tab hex(stack[i],8) cr + next + ' + end scope + ' +end macro + +'==== +'TEST +'==== + + function foo() + '============= + + push 0x44556677 + push 0x33445566 + push 0x22334455 + push 0x11223344 + ReportStack(8) + + end function + +Report+="Trace inside foo +" +foo() +print report +'putfile "s.txt",Report + +/* +RESULT: + +Trace inside foo +0017FE00 00 11223344 +0017FE04 01 22334455 +0017FE08 02 33445566 +0017FE0C 03 44556677 +0017FE10 04 005EAB1C +0017FE14 05 0017FE40 +0017FE18 06 10002D5F +0017FE1C 07 00000000 +*/ diff --git a/Task/Stack-traces/Oz/stack-traces-1.oz b/Task/Stack-traces/Oz/stack-traces-1.oz new file mode 100644 index 0000000000..6bdcb0456c --- /dev/null +++ b/Task/Stack-traces/Oz/stack-traces-1.oz @@ -0,0 +1,10 @@ +declare + proc {Test} + _ = 1 div 0 + end +in + try + {Test} + catch E then + {Inspect E} + end diff --git a/Task/Stack-traces/Oz/stack-traces-2.oz b/Task/Stack-traces/Oz/stack-traces-2.oz new file mode 100644 index 0000000000..432f7fd1a4 --- /dev/null +++ b/Task/Stack-traces/Oz/stack-traces-2.oz @@ -0,0 +1,15 @@ +%% make sure that simple function calls are not optimized away +\switch +controlflowinfo + +declare + [Debug] = {Link ['x-oz://boot/Debug']} + + proc {F} {G} end + + proc {G} {H} end + + proc {H} + {Inspect {Debug.getTaskStack {Thread.this} 100 true}} + end +in + {F} diff --git a/Task/Stack-traces/PHP/stack-traces.php b/Task/Stack-traces/PHP/stack-traces.php new file mode 100644 index 0000000000..37ae3bc8fd --- /dev/null +++ b/Task/Stack-traces/PHP/stack-traces.php @@ -0,0 +1,15 @@ +<?php +class StackTraceDemo { + static function inner() { + debug_print_backtrace(); + } + static function middle() { + self::inner(); + } + static function outer() { + self::middle(); + } +} + +StackTraceDemo::outer(); +?> diff --git a/Task/Stack-traces/PL-I/stack-traces.pli b/Task/Stack-traces/PL-I/stack-traces.pli new file mode 100644 index 0000000000..c86ce032c2 --- /dev/null +++ b/Task/Stack-traces/PL-I/stack-traces.pli @@ -0,0 +1,7 @@ +/* The SNAP option in the ON statement is sufficient to obtain */ +/* a traceback. The SYSTEM option specifies that standard */ +/* system action is to occur, which resume execution after the */ +/* SIGNAL statement. */ +on condition(traceback) snap system; +... +signal condition(traceback); diff --git a/Task/Stack-traces/Perl-6/stack-traces.pl6 b/Task/Stack-traces/Perl-6/stack-traces.pl6 new file mode 100644 index 0000000000..cc75217c27 --- /dev/null +++ b/Task/Stack-traces/Perl-6/stack-traces.pl6 @@ -0,0 +1,3 @@ +sub g { say Backtrace.new.concise } +sub f { g } +sub MAIN { f } diff --git a/Task/Stack-traces/Perl/stack-traces.pl b/Task/Stack-traces/Perl/stack-traces.pl new file mode 100644 index 0000000000..d3d4d833af --- /dev/null +++ b/Task/Stack-traces/Perl/stack-traces.pl @@ -0,0 +1,6 @@ +use Carp 'cluck'; + +sub g {cluck 'Hello from &g';} +sub f {g;} + +f; diff --git a/Task/Stack-traces/PicoLisp/stack-traces-1.l b/Task/Stack-traces/PicoLisp/stack-traces-1.l new file mode 100644 index 0000000000..63de793d97 --- /dev/null +++ b/Task/Stack-traces/PicoLisp/stack-traces-1.l @@ -0,0 +1,36 @@ +(off "Stack") + +(de $$ "Prg" + (let "Stack" (cons (cons (car "Prg") (env)) "Stack") # Build stack frame + (set "Stack" + (delq (asoq '"Stack" (car "Stack")) # Remove self-created entries + (delq (asoq '"Prg" (car "Stack")) + (car "Stack") ) ) ) + (run (cdr "Prg")) ) ) # Run body + +(de stackAll (Excl) + (let *Dbg NIL + (for "X" (all) + (or + (memq "X" Excl) + (memq "X" '($$ @ @@ @@@)) + (= `(char "*") (char "X")) + (cond + ((= `(char "+") (char "X")) + (for "Y" (pair (val "X")) + (and + (pair "Y") + (fun? (cdr "Y")) + (unless (== '$$ (caaddr "Y")) + (con (cdr "Y") + (list + (cons '$$ (cons (car "Y" "X") (cddr "Y"))) ) ) ) ) ) ) + ((pair (getd "X")) + (let "Y" @ + (unless (== '$$ (caadr "Y")) + (con "Y" + (list (cons '$$ "X" (cdr "Y"))) ) ) ) ) ) ) ) ) ) + +(de dumpStack () + (more (reverse (cdr "Stack"))) + T ) diff --git a/Task/Stack-traces/PicoLisp/stack-traces-2.l b/Task/Stack-traces/PicoLisp/stack-traces-2.l new file mode 100644 index 0000000000..d7af5aa889 --- /dev/null +++ b/Task/Stack-traces/PicoLisp/stack-traces-2.l @@ -0,0 +1,9 @@ +(de foo (A B) + (let C 3 + (bar (inc 'A) (inc 'B) (inc 'C)) ) ) + +(de bar (A D E) + (let (A 7 B 8 C 9) + (! println A B C) ) ) # Set a breakpoint before (println A B C) + +(stackAll) diff --git a/Task/Stack-traces/PureBasic/stack-traces.purebasic b/Task/Stack-traces/PureBasic/stack-traces.purebasic new file mode 100644 index 0000000000..61c44cef0a --- /dev/null +++ b/Task/Stack-traces/PureBasic/stack-traces.purebasic @@ -0,0 +1,17 @@ +Procedure Three() + a=7 + ShowCallstack() + CallDebugger +EndProcedure + +Procedure Two() + a=4 + Three() +EndProcedure + +Procedure One() + a=2 + Two() +EndProcedure + +One() diff --git a/Task/Stack-traces/Python/stack-traces.py b/Task/Stack-traces/Python/stack-traces.py new file mode 100644 index 0000000000..c6dd9377a8 --- /dev/null +++ b/Task/Stack-traces/Python/stack-traces.py @@ -0,0 +1,6 @@ +import traceback + +def f(): return g() +def g(): traceback.print_stack() + +f() diff --git a/Task/Stack-traces/R/stack-traces-1.r b/Task/Stack-traces/R/stack-traces-1.r new file mode 100644 index 0000000000..71ef582d24 --- /dev/null +++ b/Task/Stack-traces/R/stack-traces-1.r @@ -0,0 +1,10 @@ +foo <- function() +{ + bar <- function() + { + sys.calls() + } + bar() +} + +foo() diff --git a/Task/Stack-traces/R/stack-traces-2.r b/Task/Stack-traces/R/stack-traces-2.r new file mode 100644 index 0000000000..17df66c8c7 --- /dev/null +++ b/Task/Stack-traces/R/stack-traces-2.r @@ -0,0 +1,2 @@ +trace("foo", recover) +foo() diff --git a/Task/Stack-traces/Ruby/stack-traces-1.rb b/Task/Stack-traces/Ruby/stack-traces-1.rb new file mode 100644 index 0000000000..7418351cb7 --- /dev/null +++ b/Task/Stack-traces/Ruby/stack-traces-1.rb @@ -0,0 +1,14 @@ +def outer(a,b,c) + middle a+b, b+c +end + +def middle(d,e) + inner d+e +end + +def inner(f) + puts caller(0) + puts "continuing... my arg is #{f}" +end + +outer 2,3,5 diff --git a/Task/Stack-traces/Ruby/stack-traces-2.rb b/Task/Stack-traces/Ruby/stack-traces-2.rb new file mode 100644 index 0000000000..ef41d36f57 --- /dev/null +++ b/Task/Stack-traces/Ruby/stack-traces-2.rb @@ -0,0 +1,19 @@ +def outer(a,b,c) + middle a+b, b+c +end + +def middle(d,e) + inner d+e +end + +def inner(f) + raise + puts "this will not be printed" +end + +begin + outer 2,3,5 +rescue Exception => e + puts e.backtrace +end +puts "continuing after the rescue..." diff --git a/Task/Stack-traces/Scala/stack-traces.scala b/Task/Stack-traces/Scala/stack-traces.scala new file mode 100644 index 0000000000..78a1955b10 --- /dev/null +++ b/Task/Stack-traces/Scala/stack-traces.scala @@ -0,0 +1,3 @@ +def callStack = try { error("exception") } catch { case ex => ex.getStackTrace drop 2 } + +def printStackTrace = callStack drop 1 /* don't print ourselves! */ foreach println diff --git a/Task/Stack-traces/Slate/stack-traces-1.slate b/Task/Stack-traces/Slate/stack-traces-1.slate new file mode 100644 index 0000000000..9d9d6b7ce8 --- /dev/null +++ b/Task/Stack-traces/Slate/stack-traces-1.slate @@ -0,0 +1,8 @@ +slate[1]> d@(Debugger traits) printCurrentStack &limit: limit &stream: out &showLocation: showLocation +[ + d clone `>> [baseFramePointer: (d interpreter framePointerOf: #printCurrentStack). + buildFrames. + printBacktrace &limit: limit &stream: out &showLocation: showLocation ] +]. +Defining function 'printCurrentStack' on: 'Debugger traits' +[printCurrentStack &limit: &stream: &showLocation:] diff --git a/Task/Stack-traces/Slate/stack-traces-2.slate b/Task/Stack-traces/Slate/stack-traces-2.slate new file mode 100644 index 0000000000..295f3310b2 --- /dev/null +++ b/Task/Stack-traces/Slate/stack-traces-2.slate @@ -0,0 +1,14 @@ +slate[2]> Debugger printCurrentStack. +Backtrace (method @ source): +frame: 0 [printCurrentStack &limit: &stream: &showLocation:] @ stdin:0 +frame: 1 [evaluateIn: &optionals:] @ src/mobius/syntax.slate:180 +frame: 2 [(arity: 0)] @ src/lib/repl.slate:155 +frame: 3 [on:do:] @ src/core/condition.slate:43 +frame: 4 [(arity: 0)] @ src/lib/repl.slate:147 +frame: 5 [handlingCases:] @ src/core/condition.slate:64 +frame: 6 [interpretHook:] @ src/lib/repl.slate:42 +frame: 7 [(arity: 0)] @ src/lib/repl.slate:139 +frame: 8 [enter] @ src/lib/repl.slate:135 +frame: 9 [start &resource:] @ src/lib/repl.slate:185 +frame: 10 [start] @ src/mobius/prelude.slate:38 +Nil diff --git a/Task/Stack-traces/Smalltalk/stack-traces.st b/Task/Stack-traces/Smalltalk/stack-traces.st new file mode 100644 index 0000000000..5a3b0b21cd --- /dev/null +++ b/Task/Stack-traces/Smalltalk/stack-traces.st @@ -0,0 +1,15 @@ +Object subclass: Container [ + Container class >> outer: a and: b and: c [ + self middle: (a+b) and: (b+c) + ] + Container class >> middle: x and: y [ + self inner: (x*y) + ] + Container class >> inner: k [ + Smalltalk backtrace + ] +]. + +Container outer: 2 and: 3 and: 5. + +'Anyway, we continue with it' displayNl. diff --git a/Task/Stack-traces/Tcl/stack-traces-1.tcl b/Task/Stack-traces/Tcl/stack-traces-1.tcl new file mode 100644 index 0000000000..1529d7e556 --- /dev/null +++ b/Task/Stack-traces/Tcl/stack-traces-1.tcl @@ -0,0 +1,6 @@ +proc printStackTrace {} { + puts "Stack trace:" + for {set i 1} {$i < [info level]} {incr i} { + puts [string repeat " " $i][info level $i] + } +} diff --git a/Task/Stack-traces/Tcl/stack-traces-2.tcl b/Task/Stack-traces/Tcl/stack-traces-2.tcl new file mode 100644 index 0000000000..ea70b560d6 --- /dev/null +++ b/Task/Stack-traces/Tcl/stack-traces-2.tcl @@ -0,0 +1,10 @@ +proc outer {a b c} { + middle [expr {$a+$b}] [expr {$b+$c}] +} +proc middle {x y} { + inner [expr {$x*$y}] +} +proc inner k { + printStackTrace +} +outer 2 3 5 diff --git a/Task/Stack/0DESCRIPTION b/Task/Stack/0DESCRIPTION new file mode 100644 index 0000000000..218071fc5d --- /dev/null +++ b/Task/Stack/0DESCRIPTION @@ -0,0 +1,14 @@ +{{data structure}}[[Category:Classic CS problems and programs]] +A '''stack''' is a container of elements with last in, first out access policy. Sometimes it also called '''LIFO'''. The stack is accessed through its '''top'''. The basic stack operations are: + +* ''push'' stores a new element onto the stack top; +* ''pop'' returns the last pushed stack element, while removing it from the stack; +* ''empty'' tests if the stack contains no elements. + +Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write): + +* ''top'' (sometimes called ''peek'' to keep with the ''p'' theme) returns the topmost element without modifying the stack. + +Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming stacks are also very popular for their way ('''LIFO''') of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a reentrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See [[wp:Stack_automaton|stack machine]]. Many algorithms in pattern matching, compiler construction (e.g. [[wp:Recursive_descent|recursive descent parsers]]), and machine learning (e.g. based on [[wp:Tree_traversal|tree traversal]]) have a natural representation in terms of stacks. + +Create a stack supporting the basic operations: push, pop, empty. diff --git a/Task/Stack/1META.yaml b/Task/Stack/1META.yaml new file mode 100644 index 0000000000..b948cd0d8b --- /dev/null +++ b/Task/Stack/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Encyclopedia +note: Data Structures diff --git a/Task/Stack/ALGOL-68/stack.alg b/Task/Stack/ALGOL-68/stack.alg new file mode 100644 index 0000000000..f57c3e2552 --- /dev/null +++ b/Task/Stack/ALGOL-68/stack.alg @@ -0,0 +1,56 @@ +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/ActionScript/stack.as b/Task/Stack/ActionScript/stack.as new file mode 100644 index 0000000000..d970aa4d9c --- /dev/null +++ b/Task/Stack/ActionScript/stack.as @@ -0,0 +1,5 @@ +var stack:Array = new Array(); +stack.push(1); +stack.push(2); +trace(stack.pop()); // outputs "2" +trace(stack.pop()); // outputs "1" diff --git a/Task/Stack/Ada/stack-1.ada b/Task/Stack/Ada/stack-1.ada new file mode 100644 index 0000000000..156951b693 --- /dev/null +++ b/Task/Stack/Ada/stack-1.ada @@ -0,0 +1,16 @@ +generic + type Element_Type is private; +package Generic_Stack is + type Stack is private; + procedure Push (Item : Element_Type; Onto : in out Stack); + procedure Pop (Item : out Element_Type; From : in out Stack); + function Create return Stack; + Stack_Empty_Error : exception; +private + type Node; + type Stack is access Node; + type Node is record + Element : Element_Type; + Next : Stack := null; + end record; +end Generic_Stack; diff --git a/Task/Stack/Ada/stack-2.ada b/Task/Stack/Ada/stack-2.ada new file mode 100644 index 0000000000..628f998b00 --- /dev/null +++ b/Task/Stack/Ada/stack-2.ada @@ -0,0 +1,42 @@ +with Ada.Unchecked_Deallocation; + +package body Generic_Stack is + + ------------ + -- Create -- + ------------ + + function Create return Stack is + begin + return (null); + end Create; + + ---------- + -- Push -- + ---------- + + procedure Push(Item : Element_Type; Onto : in out Stack) is + Temp : Stack := new Node; + begin + Temp.Element := Item; + Temp.Next := Onto; + Onto := Temp; + end Push; + + --------- + -- Pop -- + --------- + + procedure Pop(Item : out Element_Type; From : in out Stack) is + procedure Free is new Ada.Unchecked_Deallocation(Node, Stack); + Temp : Stack := From; + begin + if Temp = null then + raise Stack_Empty_Error; + end if; + Item := Temp.Element; + From := Temp.Next; + Free(Temp); + end Pop; + +end Generic_Stack; diff --git a/Task/Stack/Applesoft-BASIC/stack.applesoft b/Task/Stack/Applesoft-BASIC/stack.applesoft new file mode 100644 index 0000000000..56fac7343d --- /dev/null +++ b/Task/Stack/Applesoft-BASIC/stack.applesoft @@ -0,0 +1,39 @@ +100 DIM STACK$(1000) +110 DATA "(2*A)","PI","","TO BE OR","NOT TO BE" +120 FOR I = 1 TO 5 +130 READ ELEMENT$ +140 GOSUB 500_PUSH +150 NEXT +200 GOSUB 400 POP AND PRINT +210 GOSUB 300_EMPTY AND PRINT +220 FOR I = 1 TO 4 +230 GOSUB 400 POP AND PRINT +240 NEXT +250 GOSUB 300_EMPTY AND PRINT +260 END +300 GOSUB 700_EMPTY +310 PRINT "STACK IS "; +320 IF NOT EMPTY THEN PRINT "NOT "; +330 PRINT "EMPTY" +340 RETURN +400 GOSUB 600 POP +410 PRINT ELEMENT$ +420 RETURN +500 REM +510 REM PUSH +520 REM +530 LET STACK$(SP) = ELEMENT$ +540 LET SP = SP + 1 +550 RETURN +600 REM +610 REM POP +620 REM +630 IF SP THEN SP = SP - 1 +640 LET ELEMENT$ = STACK$(SP) +650 LET STACK$(SP) = "" +660 RETURN +700 REM +710 REM EMPTY +720 REM +730 LET EMPTY = SP = 0 +740 RETURN diff --git a/Task/Stack/AutoHotkey/stack.ahk b/Task/Stack/AutoHotkey/stack.ahk new file mode 100644 index 0000000000..22aed7a28d --- /dev/null +++ b/Task/Stack/AutoHotkey/stack.ahk @@ -0,0 +1,39 @@ +msgbox % stack("push", 4) +msgbox % stack("push", 5) +msgbox % stack("peek") +msgbox % stack("pop") +msgbox % stack("peek") +msgbox % stack("empty") +msgbox % stack("pop") +msgbox % stack("empty") +return + +stack(command, value = 0) +{ + static +if !pointer +pointer = 10000 + if (command = "push") + { + _p%pointer% := value + pointer -= 1 + return value + } + if (command = "pop") + { + pointer += 1 + return _p%pointer% + } + if (command = "peek") +{ +next := pointer + 1 +return _p%next% +} + if (command = "empty") + { + if (pointer == 10000) + return "empty" +else +return 0 + } +} diff --git a/Task/Stack/BBC-BASIC/stack.bbc b/Task/Stack/BBC-BASIC/stack.bbc new file mode 100644 index 0000000000..ec36d0c895 --- /dev/null +++ b/Task/Stack/BBC-BASIC/stack.bbc @@ -0,0 +1,31 @@ + STACKSIZE = 1000 + + FOR n = 3 TO 5 + PRINT "Push ";n : PROCpush(n) + NEXT + PRINT "Pop " ; FNpop + PRINT "Push 6" : PROCpush(6) + REPEAT + PRINT "Pop " ; FNpop + UNTIL FNisempty + PRINT "Pop " ; FNpop + END + + DEF PROCpush(n) : LOCAL f% + DEF FNpop : LOCAL f% : f% = 1 + DEF FNisempty : LOCAL f% : f% = 2 + PRIVATE stack(), sptr% + DIM stack(STACKSIZE-1) + CASE f% OF + WHEN 0: + IF sptr% = DIM(stack(),1) ERROR 100, "Error: stack overflowed" + stack(sptr%) = n + sptr% += 1 + WHEN 1: + IF sptr% = 0 ERROR 101, "Error: stack empty" + sptr% -= 1 + = stack(sptr%) + WHEN 2: + = (sptr% = 0) + ENDCASE + ENDPROC diff --git a/Task/Stack/Babel/stack.pb b/Task/Stack/Babel/stack.pb new file mode 100644 index 0000000000..a4063c1adb --- /dev/null +++ b/Task/Stack/Babel/stack.pb @@ -0,0 +1,21 @@ +main : + { (1 2 3) foo set -- foo = (1 2 3) + 4 foo push -- foo = (1 2 3 4) + 0 foo unshift -- foo = (0 1 2 3 4) + foo pop -- foo = (0 1 2 3) + foo shift -- foo = (1 2 3) + check_foo + { foo pop } 4 times -- Pops too many times, but this is OK and Babel won't complain + check_foo } + +empty? : nil? -- just aliases 'empty?' to the built-in operator 'nil?' + +check_foo! : + { "foo is " + {foo empty?) {nil} {"not " .} ifte + "empty" . + cr << } + +Output: +foo is not empty +foo is empty diff --git a/Task/Stack/Batch-File/stack.bat b/Task/Stack/Batch-File/stack.bat new file mode 100644 index 0000000000..99f8f80f57 --- /dev/null +++ b/Task/Stack/Batch-File/stack.bat @@ -0,0 +1,69 @@ +@echo off +setlocal enableDelayedExpansion + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: LIFO stack usage + +:: Define the stack +call :newStack myStack + +:: Push some values onto the stack +for %%A in (value1 value2 value3) do call :pushStack myStack %%A + +:: Test if stack is empty by examining the top "attribute" +if myStack.top==0 (echo myStack is empty) else (echo myStack is NOT empty) + +:: Peek at the top stack value +call:peekStack myStack val && echo a peek at the top of myStack shows !val! + +:: Pop the top stack value +call :popStack myStack val && echo popped myStack value=!val! + +:: Push some more values onto the stack +for %%A in (value4 value5 value6) do call :pushStack myStack %%A + +:: Process the remainder of the stack +:processStack +call :popStack myStack val || goto :stackEmpty +echo popped myStack value=!val! +goto :processStack +:stackEmpty + +:: Test if stack is empty using the empty "method"/"macro". Use of the +:: second IF statement serves to demonstrate the negation of the empty +:: "method". A single IF could have been used with an ELSE clause instead. +if %myStack.empty% echo myStack is empty +if not %myStack.empty% echo myStack is NOT empty +exit /b + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: LIFO stack definition + +:newStack stackName +set /a %~1.top=0 +:: Define an empty "method" for this stack as a sort of macro +set "%~1.empty=^!%~1.top^! == 0" +exit /b + +:pushStack stackName value +set /a %~1.top+=1 +set %~1.!%~1.top!=%2 +exit /b + +:popStack stackName returnVar +:: Sets errorlevel to 0 if success +:: Sets errorlevel to 1 if failure because stack was empty +if !%~1.top! equ 0 exit /b 1 +for %%N in (!%~1.top!) do ( + set %~2=!%~1.%%N! + set %~1.%%N= +) +set /a %~1.top-=1 +exit /b 0 + +:peekStack stackName returnVar +:: Sets errorlevel to 0 if success +:: Sets errorlevel to 1 if failure because stack was empty +if !%~1.top! equ 0 exit /b 1 +for %%N in (!%~1.top!) do set %~2=!%~1.%%N! +exit /b 0 diff --git a/Task/Stack/Bracmat/stack.bracmat b/Task/Stack/Bracmat/stack.bracmat new file mode 100644 index 0000000000..984dd10fec --- /dev/null +++ b/Task/Stack/Bracmat/stack.bracmat @@ -0,0 +1,32 @@ +( ( stack + = (S=) + (push=.(!arg.!(its.S)):?(its.S)) + ( pop + = top.!(its.S):(%?top.?(its.S))&!top + ) + (top=top.!(its.S):(%?top.?)&!top) + (empty=.!(its.S):) + ) +& new$stack:?Stack +& (Stack..push)$(2*a) +& (Stack..push)$pi +& (Stack..push)$ +& (Stack..push)$"to be or" +& (Stack..push)$"not to be" +& out$((Stack..pop)$|"Cannot pop (a)") +& out$((Stack..top)$|"Cannot pop (b)") +& out$((Stack..pop)$|"Cannot pop (c)") +& out$((Stack..pop)$|"Cannot pop (d)") +& out$((Stack..pop)$|"Cannot pop (e)") +& out$((Stack..pop)$|"Cannot pop (f)") +& out$((Stack..pop)$|"Cannot pop (g)") +& out$((Stack..pop)$|"Cannot pop (h)") +& out + $ ( str + $ ( "Stack is " + ((Stack..empty)$&|not) + " empty" + ) + ) +& +); diff --git a/Task/Stack/Brat/stack.brat b/Task/Stack/Brat/stack.brat new file mode 100644 index 0000000000..52684d119d --- /dev/null +++ b/Task/Stack/Brat/stack.brat @@ -0,0 +1,6 @@ +stack = [] +stack.push 1 +stack.push 2 +stack.push 3 + +until { stack.empty? } { p stack.pop } diff --git a/Task/Stack/C++/stack-1.cpp b/Task/Stack/C++/stack-1.cpp new file mode 100644 index 0000000000..d414a5c25f --- /dev/null +++ b/Task/Stack/C++/stack-1.cpp @@ -0,0 +1 @@ +#include <stack> diff --git a/Task/Stack/C++/stack-2.cpp b/Task/Stack/C++/stack-2.cpp new file mode 100644 index 0000000000..ffffe16750 --- /dev/null +++ b/Task/Stack/C++/stack-2.cpp @@ -0,0 +1,55 @@ +#include <deque> +template <class T, class Sequence = std::deque<T> > +class stack { + friend bool operator== (const stack&, const stack&); + friend bool operator< (const stack&, const stack&); +public: + typedef typename Sequence::value_type value_type; + typedef typename Sequence::size_type size_type; + typedef Sequence container_type; + typedef typename Sequence::reference reference; + typedef typename Sequence::const_reference const_reference; +protected: + Sequence seq; +public: + stack() : seq() {} + explicit stack(const Sequence& s0) : seq(s0) {} + bool empty() const { return seq.empty(); } + size_type size() const { return seq.size(); } + reference top() { return seq.back(); } + const_reference top() const { return seq.back(); } + void push(const value_type& x) { seq.push_back(x); } + void pop() { seq.pop_back(); } +}; + +template <class T, class Sequence> +bool operator==(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return x.seq == y.seq; +} +template <class T, class Sequence> +bool operator<(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return x.seq < y.seq; +} + +template <class T, class Sequence> +bool operator!=(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return !(x == y); +} +template <class T, class Sequence> +bool operator>(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return y < x; +} +template <class T, class Sequence> +bool operator<=(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return !(y < x); +} +template <class T, class Sequence> +bool operator>=(const stack<T,Sequence>& x, const stack<T,Sequence>& y) +{ + return !(x < y); +} diff --git a/Task/Stack/C++/stack-3.cpp b/Task/Stack/C++/stack-3.cpp new file mode 100644 index 0000000000..a2ee1d0d45 --- /dev/null +++ b/Task/Stack/C++/stack-3.cpp @@ -0,0 +1,20 @@ +(deftype Stack [elements]) + +(def stack (Stack (ref ()))) + +(defn push-stack + "Pushes an item to the top of the stack." + [x] (dosync (alter (:elements stack) conj x))) + +(defn pop-stack + "Pops an item from the top of the stack." + [] (let [fst (first (deref (:elements stack)))] + (dosync (alter (:elements stack) rest)) fst)) + +(defn top-stack + "Shows what's on the top of the stack." + [] (first (deref (:elements stack)))) + +(defn empty-stack? + "Tests whether or not the stack is empty." + [] (= () (deref (:elements stack)))) diff --git a/Task/Stack/C++/stack-4.cpp b/Task/Stack/C++/stack-4.cpp new file mode 100644 index 0000000000..d99e990ad8 --- /dev/null +++ b/Task/Stack/C++/stack-4.cpp @@ -0,0 +1,14 @@ +(defprotocol StackOps + (push-stack [this x] "Pushes an item to the top of the stack.") + (pop-stack [this] "Pops an item from the top of the stack.") + (top-stack [this] "Shows what's on the top of the stack.") + (empty-stack? [this] "Tests whether or not the stack is empty.")) +(deftype Stack [elements] + StackOps + (push-stack [x] (dosync (alter elements conj x))) + (pop-stack [] (let [fst (first (deref elements))] + (dosync (alter elements rest)) fst)) + (top-stack [] (first (deref elements))) + (empty-stack? [] (= () (deref elements)))) + +(def stack (Stack (ref ()))) diff --git a/Task/Stack/C/stack-1.c b/Task/Stack/C/stack-1.c new file mode 100644 index 0000000000..a8e4a1dd7c --- /dev/null +++ b/Task/Stack/C/stack-1.c @@ -0,0 +1,62 @@ +#include <stdio.h> +#include <stdlib.h> + +/* to read expanded code, run through cpp | indent -st */ +#define DECL_STACK_TYPE(type, name) \ +typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ +stk_##name stk_##name##_create(size_t init_size) { \ + stk_##name s; if (!init_size) init_size = 4; \ + s = malloc(sizeof(struct stk_##name##_t)); \ + if (!s) return 0; \ + s->buf = malloc(sizeof(type) * init_size); \ + if (!s->buf) { free(s); return 0; } \ + s->len = 0, s->alloc = init_size; \ + return s; } \ +int stk_##name##_push(stk_##name s, type item) { \ + type *tmp; \ + if (s->len >= s->alloc) { \ + tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ + if (!tmp) return -1; s->buf = tmp; \ + s->alloc *= 2; } \ + s->buf[s->len++] = item; \ + return s->len; } \ +type stk_##name##_pop(stk_##name s) { \ + type tmp; \ + if (!s->len) abort(); \ + tmp = s->buf[--s->len]; \ + if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ + s->alloc /= 2; \ + s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ + return tmp; } \ +void stk_##name##_delete(stk_##name s) { \ + free(s->buf); free(s); } + +#define stk_empty(s) (!(s)->len) +#define stk_size(s) ((s)->len) + +DECL_STACK_TYPE(int, int) + +int main(void) +{ + int i; + stk_int stk = stk_int_create(0); + + printf("pushing: "); + for (i = 'a'; i <= 'z'; i++) { + printf(" %c", i); + stk_int_push(stk, i); + } + + printf("\nsize now: %d", stk_size(stk)); + printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); + + printf("\npoppoing:"); + while (stk_size(stk)) + printf(" %c", stk_int_pop(stk)); + printf("\nsize now: %d", stk_size(stk)); + printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not"); + + /* stk_int_pop(stk); <-- will abort() */ + stk_int_delete(stk); + return 0; +} diff --git a/Task/Stack/C/stack-2.c b/Task/Stack/C/stack-2.c new file mode 100644 index 0000000000..8fabb3e1e6 --- /dev/null +++ b/Task/Stack/C/stack-2.c @@ -0,0 +1,71 @@ +#include <stdio.h> +#include <stdlib.h> +#include <stddef.h> +#include <stdbool.h> + +#define check_pointer(p) if (!p) {puts("Out of memory."); exit(EXIT_FAILURE);} + +#define MINIMUM_SIZE 1 + /* Minimal stack size (expressed in number of elements) for which + space is allocated. It should be at least 1. */ +#define GROWTH_FACTOR 2 + /* How much more memory is allocated each time a stack grows + out of its allocated segment. */ +typedef int T; + // The type of the stack elements. + +typedef struct + {T *bottom; + T *top; + T *allocated_top;} stack; + +stack * new(void) +/* Creates a new stack. */ + {stack *s = malloc(sizeof(stack)); + check_pointer(s); + s->bottom = malloc(MINIMUM_SIZE * sizeof(T)); + check_pointer(s->bottom); + s->top = s->bottom - 1; + s->allocated_top = s->bottom + MINIMUM_SIZE - 1; + return s;} + +void destroy(stack *s) +/* Frees all the memory used for a stack. */ + {free(s->bottom); + free(s);} + +bool empty(stack *s) +/* Returns true iff there are no elements on the stack. This +is different from the stack not having enough memory reserved +for even one element, which case is never allowed to arise. */ + {return s->top < s->bottom ? true : false;} + +void push(stack *s, T x) +/* Puts a new element on the stack, enlarging the latter's +memory allowance if necessary. */ + {if (s->top == s->allocated_top) + {ptrdiff_t qtty = s->top - s->bottom + 1; + ptrdiff_t new_qtty = GROWTH_FACTOR * qtty; + s->bottom = realloc(s->bottom, new_qtty * sizeof(T)); + check_pointer(s->bottom); + s->top = s->bottom + qtty - 1; + s->allocated_top = s->bottom + new_qtty - 1;} + *(++s->top) = x;} + +T pop(stack *s) +/* Removes and returns the topmost element. The result of popping +an empty stack is undefined. */ + {return *(s->top--);} + +void compress(stack *s) +/* Frees any memory the stack isn't actually using. The +allocated portion still isn't allowed to shrink smaller than +MINIMUM_SIZE. If all the stack's memory is in use, nothing +happens. */ + {if (s->top == s->allocated_top) return; + ptrdiff_t qtty = s->top - s->bottom + 1; + if (qtty < MINIMUM_SIZE) qtty = MINIMUM_SIZE; + size_t new_size = qtty * sizeof(T); + s->bottom = realloc(s->bottom, new_size); + check_pointer(s->bottom); + s->allocated_top = s->bottom + qtty - 1;} diff --git a/Task/Stack/COBOL/stack-1.cobol b/Task/Stack/COBOL/stack-1.cobol new file mode 100644 index 0000000000..55ba57711f --- /dev/null +++ b/Task/Stack/COBOL/stack-1.cobol @@ -0,0 +1,2 @@ + 01 stack. + 05 head USAGE IS POINTER VALUE NULL. diff --git a/Task/Stack/COBOL/stack-2.cobol b/Task/Stack/COBOL/stack-2.cobol new file mode 100644 index 0000000000..56bfae0a1c --- /dev/null +++ b/Task/Stack/COBOL/stack-2.cobol @@ -0,0 +1,5 @@ + 01 node BASED. + COPY node-info REPLACING + 01 BY 05 + node-info BY info. + 05 link USAGE IS POINTER VALUE NULL. diff --git a/Task/Stack/COBOL/stack-3.cobol b/Task/Stack/COBOL/stack-3.cobol new file mode 100644 index 0000000000..5f8f3d29ec --- /dev/null +++ b/Task/Stack/COBOL/stack-3.cobol @@ -0,0 +1 @@ + 01 node-info PICTURE X(10) VALUE SPACES. diff --git a/Task/Stack/COBOL/stack-4.cobol b/Task/Stack/COBOL/stack-4.cobol new file mode 100644 index 0000000000..2da7f657c6 --- /dev/null +++ b/Task/Stack/COBOL/stack-4.cobol @@ -0,0 +1,3 @@ + 01 p PICTURE 9. + 88 nil VALUE ZERO WHEN SET TO FALSE IS 1. + 88 t VALUE 1 WHEN SET TO FALSE IS ZERO. diff --git a/Task/Stack/COBOL/stack-5.cobol b/Task/Stack/COBOL/stack-5.cobol new file mode 100644 index 0000000000..65feb75713 --- /dev/null +++ b/Task/Stack/COBOL/stack-5.cobol @@ -0,0 +1,247 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. push. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + 01 node-info-any PICTURE X ANY LENGTH. + PROCEDURE DIVISION USING stack node-info-any. + ALLOCATE node + CALL "pointerp" USING + BY REFERENCE ADDRESS OF node + BY REFERENCE p + END-CALL + IF nil + CALL "stack-overflow-error" END-CALL + ELSE + MOVE node-info-any TO info OF node + SET link OF node TO head OF stack + SET head OF stack TO ADDRESS OF node + END-IF + GOBACK. + END PROGRAM push. + + IDENTIFICATION DIVISION. + PROGRAM-ID. pop. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF t + CALL "stack-underflow-error" END-CALL + ELSE + SET ADDRESS OF node TO head OF stack + SET head OF stack TO link OF node + MOVE info OF node TO node-info + END-IF + FREE ADDRESS OF node + GOBACK. + END PROGRAM pop. + + IDENTIFICATION DIVISION. + PROGRAM-ID. empty. + DATA DIVISION. + LOCAL-STORAGE SECTION. + LINKAGE SECTION. + COPY stack. + COPY p. + PROCEDURE DIVISION USING stack p. + CALL "pointerp" USING + BY CONTENT head OF stack + BY REFERENCE p + END-CALL + IF t + SET t TO FALSE + ELSE + SET t TO TRUE + END-IF + GOBACK. + END PROGRAM empty. + + IDENTIFICATION DIVISION. + PROGRAM-ID. head. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF t + CALL "stack-underflow-error" END-CALL + ELSE + SET ADDRESS OF node TO head OF stack + MOVE info OF node TO node-info + END-IF + GOBACK. + END PROGRAM head. + + IDENTIFICATION DIVISION. + PROGRAM-ID. peek. + DATA DIVISION. + LOCAL-STORAGE SECTION. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "head" USING + BY CONTENT stack + BY REFERENCE node-info + END-CALL + GOBACK. + END PROGRAM peek. + + IDENTIFICATION DIVISION. + PROGRAM-ID. pointerp. + DATA DIVISION. + LINKAGE SECTION. + 01 test-pointer USAGE IS POINTER. + COPY p. + PROCEDURE DIVISION USING test-pointer p. + IF test-pointer EQUAL NULL + SET nil TO TRUE + ELSE + SET t TO TRUE + END-IF + GOBACK. + END PROGRAM pointerp. + + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-overflow-error. + PROCEDURE DIVISION. + DISPLAY "stack-overflow-error" END-DISPLAY + STOP RUN. + END PROGRAM stack-overflow-error. + + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-underflow-error. + PROCEDURE DIVISION. + DISPLAY "stack-underflow-error" END-DISPLAY + STOP RUN. + END PROGRAM stack-underflow-error. + + IDENTIFICATION DIVISION. + PROGRAM-ID. copy-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + LINKAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION USING stack new-stack. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF nil + CALL "pop" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "copy-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "push" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "push" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + END-IF + GOBACK. + END PROGRAM copy-stack. + + IDENTIFICATION DIVISION. + PROGRAM-ID. reverse-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + LINKAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION USING stack new-stack. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF nil + CALL "pop" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "push" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + CALL "reverse-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "push" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + END-IF + GOBACK. + END PROGRAM reverse-stack. + + IDENTIFICATION DIVISION. + PROGRAM-ID. traverse-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + COPY stack REPLACING stack BY new-stack. + LINKAGE SECTION. + COPY stack. + PROCEDURE DIVISION USING stack. + CALL "copy-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "empty" USING + BY REFERENCE new-stack + BY REFERENCE p + END-CALL + IF nil + CALL "head" USING + BY CONTENT new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "peek" USING + BY CONTENT new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "pop" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "traverse-stack" USING + BY REFERENCE new-stack + END-CALL + END-IF + GOBACK. + END PROGRAM traverse-stack. diff --git a/Task/Stack/COBOL/stack-6.cobol b/Task/Stack/COBOL/stack-6.cobol new file mode 100644 index 0000000000..e3059b6834 --- /dev/null +++ b/Task/Stack/COBOL/stack-6.cobol @@ -0,0 +1,37 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-test. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION. + CALL "push" USING + BY REFERENCE stack + BY CONTENT "daleth" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "gimel" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "beth" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "aleph" + END-CALL + CALL "traverse-stack" USING + BY REFERENCE stack + END-CALL + CALL "reverse-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "traverse-stack" USING + BY REFERENCE new-stack + END-CALL + STOP RUN. + END PROGRAM stack-test. + + COPY stack-utilities. diff --git a/Task/Stack/CoffeeScript/stack-1.coffeescript b/Task/Stack/CoffeeScript/stack-1.coffeescript new file mode 100644 index 0000000000..135765717c --- /dev/null +++ b/Task/Stack/CoffeeScript/stack-1.coffeescript @@ -0,0 +1,6 @@ +stack = [] +stack.push 1 +stack.push 2 +console.log stack +console.log stack.pop() +console.log stack diff --git a/Task/Stack/CoffeeScript/stack-2.coffeescript b/Task/Stack/CoffeeScript/stack-2.coffeescript new file mode 100644 index 0000000000..9c797ccd5a --- /dev/null +++ b/Task/Stack/CoffeeScript/stack-2.coffeescript @@ -0,0 +1,16 @@ +(defstruct stack + elements) + +(defun stack-push (element stack) + (push element (stack-elements stack))) + +(defun stack-pop (stack)(deftype Stack [elements]) + +(defun stack-empty (stack) + (endp (stack-elements stack))) + +(defun stack-top (stack) + (first (stack-elements stack))) + +(defun stack-peek (stack) + (stack-top stack)) diff --git a/Task/Stack/D/stack.d b/Task/Stack/D/stack.d new file mode 100644 index 0000000000..8c89ef8126 --- /dev/null +++ b/Task/Stack/D/stack.d @@ -0,0 +1,26 @@ +import std.array; + +class Stack(T) { + private T[] items; + + @property bool empty() { return items.empty(); } + + void push(T top) { items ~= top; } + + T pop() { + if (this.empty) + throw new Exception("Empty Stack."); + auto top = items.back; + items.popBack(); + return top; + } +} + +void main() { + auto s = new Stack!int(); + s.push(10); + s.push(20); + assert(s.pop() == 20); + assert(s.pop() == 10); + assert(s.empty()); +} diff --git a/Task/Stack/DWScript/stack.dwscript b/Task/Stack/DWScript/stack.dwscript new file mode 100644 index 0000000000..6c04540503 --- /dev/null +++ b/Task/Stack/DWScript/stack.dwscript @@ -0,0 +1,11 @@ +var stack: array of Integer; + +stack.Push(1); +stack.Push(2); +stack.Push(3); + +PrintLn(stack.Pop); // 3 +PrintLn(stack.Pop); // 2 +PrintLn(stack.Pop); // 1 + +Assert(stack.Length = 0); // assert empty diff --git a/Task/Stack/Delphi/stack.delphi b/Task/Stack/Delphi/stack.delphi new file mode 100644 index 0000000000..78a9040250 --- /dev/null +++ b/Task/Stack/Delphi/stack.delphi @@ -0,0 +1,24 @@ +program Stack; + +{$APPTYPE CONSOLE} + +uses Generics.Collections; + +var + lStack: TStack<Integer>; +begin + lStack := TStack<Integer>.Create; + try + lStack.Push(1); + lStack.Push(2); + lStack.Push(3); + Assert(lStack.Peek = 3); // 3 should be at the top of the stack + + Writeln(lStack.Pop); // 3 + Writeln(lStack.Pop); // 2 + Writeln(lStack.Pop); // 1 + Assert(lStack.Count = 0); // should be empty + finally + lStack.Free; + end; +end. diff --git a/Task/Stack/E/stack-1.e b/Task/Stack/E/stack-1.e new file mode 100644 index 0000000000..d2186b7391 --- /dev/null +++ b/Task/Stack/E/stack-1.e @@ -0,0 +1,22 @@ +? def l := [].diverge() +# value: [].diverge() + +? l.push(1) +? l.push(2) +? l +# value: [1, 2].diverge() + +? l.pop() +# value: 2 + +? l.size().aboveZero() +# value: true + +? l.last() +# value: 1 + +? l.pop() +# value: 1 + +? l.size().aboveZero() +# value: false diff --git a/Task/Stack/E/stack-2.e b/Task/Stack/E/stack-2.e new file mode 100644 index 0000000000..747e522cb9 --- /dev/null +++ b/Task/Stack/E/stack-2.e @@ -0,0 +1,30 @@ +def makeStack() { + var store := null + def stack { + to push(x) { store := [x, store] } + to pop() { def [x, next] := store; store := next; return x } + to last() { return store[0] } + to empty() { return (store == null) } + } + return stack +} + +? def s := makeStack() +# value: <stack> + +? s.push(1) +? s.push(2) +? s.last() +# value: 2 + +? s.pop() +# value: 2 + +? s.empty() +# value: false + +? s.pop() +# value: 1 + +? s.empty() +# value: true diff --git a/Task/Stack/Elisa/stack-1.elisa b/Task/Stack/Elisa/stack-1.elisa new file mode 100644 index 0000000000..8de28f9606 --- /dev/null +++ b/Task/Stack/Elisa/stack-1.elisa @@ -0,0 +1,21 @@ + component GenericStack ( Stack, Element ); + type Stack; + Stack (MaxSize = integer) -> Stack; + Empty ( Stack ) -> boolean; + Full ( Stack ) -> boolean; + Push ( Stack, Element) -> nothing; + Pull ( Stack ) -> Element; +begin + Stack(MaxSize) = + Stack:[ MaxSize; index:=0; area=array (Element, MaxSize) ]; + Empty( stack ) = (stack.index <= 0); + Full ( stack ) = (stack.index >= stack.MaxSize); + Push ( stack, element ) = + [ exception (Full (stack), "Stack Overflow"); + stack.index:=stack.index + 1; + stack.area[stack.index]:=element ]; + Pull ( stack ) = + [ exception (Empty (stack), "Stack Underflow"); + stack.index:=stack.index - 1; + stack.area[stack.index + 1] ]; +end component GenericStack; diff --git a/Task/Stack/Elisa/stack-2.elisa b/Task/Stack/Elisa/stack-2.elisa new file mode 100644 index 0000000000..42159dabd6 --- /dev/null +++ b/Task/Stack/Elisa/stack-2.elisa @@ -0,0 +1,25 @@ +component GenericStack ( Stack, ElementType ); + type Stack; + Stack(MaxSize = integer) -> Stack; + Empty( Stack ) -> boolean; + Full ( Stack ) -> boolean; + Push ( Stack, ElementType)-> nothing; + Pull ( Stack ) -> ElementType; +begin + type sequence = term; + ElementType & sequence => sequence; + nil = null (sequence); + + head (sequence) -> ElementType; + head (X & Y) = ElementType:X; + + tail (sequence) -> sequence; + tail (X & Y) = Y; + + Stack (Size) = Stack:[ list = nil ]; + Empty ( stack ) = (stack.list == nil); + Full ( stack ) = false; + Push ( stack, ElementType ) = [ stack.list:= ElementType & stack.list ]; + Pull ( stack ) = [ exception (Empty (stack), "Stack Underflow"); + Head = head(stack.list); stack.list:=tail(stack.list); Head]; +end component GenericStack; diff --git a/Task/Stack/Elisa/stack-3.elisa b/Task/Stack/Elisa/stack-3.elisa new file mode 100644 index 0000000000..e4f29f61bb --- /dev/null +++ b/Task/Stack/Elisa/stack-3.elisa @@ -0,0 +1,15 @@ +use GenericStack (StackofBooks, Book); +type Book = text; +BookStack = StackofBooks(50); + +Push (BookStack, "Peter Pan"); +Push (BookStack, "Alice in Wonderland"); + +Pull (BookStack)? +"Alice in Wonderland" + +Pull (BookStack)? +"Peter Pan" + +Pull (BookStack)? +***** Exception: Stack Underflow diff --git a/Task/Stack/Erlang/stack-1.erl b/Task/Stack/Erlang/stack-1.erl new file mode 100644 index 0000000000..b16e59ff3c --- /dev/null +++ b/Task/Stack/Erlang/stack-1.erl @@ -0,0 +1,13 @@ +-module(stack). +-export([empty/1, new/0, pop/1, push/2, top/1]). + +new() -> []. + +empty([]) -> true; +empty(_) -> false. + +pop([H|T]) -> {H,T}. + +push(H,T) -> [H|T]. + +top([H|_]) -> H. diff --git a/Task/Stack/Erlang/stack-2.erl b/Task/Stack/Erlang/stack-2.erl new file mode 100644 index 0000000000..43507ad154 --- /dev/null +++ b/Task/Stack/Erlang/stack-2.erl @@ -0,0 +1,14 @@ +1> c(stack). +{ok,stack} +2> Stack = stack:new(). +[] +3> NewStack = lists:foldl(fun stack:push/2, Stack, [1,2,3,4,5]). +[5,4,3,2,1] +4> stack:top(NewStack). +5 +5> {Popped, PoppedStack} = stack:pop(NewStack). +{5,[4,3,2,1]} +6> stack:empty(NewStack). +false +7> stack:empty(stack:new()). +true diff --git a/Task/Stack/Factor/stack.factor b/Task/Stack/Factor/stack.factor new file mode 100644 index 0000000000..5da7be1ea6 --- /dev/null +++ b/Task/Stack/Factor/stack.factor @@ -0,0 +1,12 @@ + V{ 1 2 3 } { + [ 6 swap push ] + [ "hi" swap push ] + [ "Vector is now: " write . ] + [ "Let's pop it: " write pop . ] + [ "Vector is now: " write . ] + [ "Top is: " write last . ] } cleave + + Vector is now: V{ 1 2 3 6 "hi" } + Let's pop it: "hi" + Vector is now: V{ 1 2 3 6 } + Top is: 6 diff --git a/Task/Stack/Forth/stack.fth b/Task/Stack/Forth/stack.fth new file mode 100644 index 0000000000..19e19b57c4 --- /dev/null +++ b/Task/Stack/Forth/stack.fth @@ -0,0 +1,15 @@ +: stack ( size -- ) + create here cell+ , cells allot ; + +: push ( n st -- ) tuck @ ! cell swap +! ; +: pop ( st -- n ) -cell over +! @ @ ; +: empty? ( st -- ? ) dup @ - cell+ 0= ; + +10 stack st + +1 st push +2 st push +3 st push +st empty? . \ 0 (false) +st pop . st pop . st pop . \ 3 2 1 +st empty? . \ -1 (true) diff --git a/Task/Stack/Fortran/stack.f b/Task/Stack/Fortran/stack.f new file mode 100644 index 0000000000..49de7fc85f --- /dev/null +++ b/Task/Stack/Fortran/stack.f @@ -0,0 +1,84 @@ +module stack + + public + + ! Define the data-structure to hold the data + type stack_var + integer, allocatable :: data(:) + integer :: size = 0 + end type stack_var + + ! Set the size of allocated memory blocks + integer, parameter, private :: block_size = 10 + +contains + + ! Push ---------------------------------------------------------------------- + subroutine push(s, e) + type(stack_var), intent(inout) :: s + integer, intent(in) :: e + integer, allocatable :: wk(:) + if (.not. allocated(s%data)) then + ! Allocate space if not yet done + allocate(s%data(block_size)) + + elseif (s%size == size(s%data)) then + ! Grow the allocated space + allocate(wk(size(s%data)+block_size)) + wk(1:s%size) = s%data + call move_alloc(wk,s%data) + + end if + + ! Store the data in the stack + s%size = s%size + 1 + s%data(s%size) = e + end subroutine push + + ! Pop ----------------------------------------------------------------------- + function pop(s) + integer :: pop + type(stack_var), intent(inout) :: s + if (s%size == 0 .or. .not. allocated(s%data)) then + pop = 0 + return + end if + pop = s%data(s%size) + s%size = s%size - 1 + end function pop + + ! Peek ---------------------------------------------------------------------- + integer function peek(s) + type(stack_var), intent(inout) :: s + if (s%size == 0 .or. .not. allocated(s%data)) then + peek = 0 + return + end if + peek = s%data(s%size) + end function peek + + ! Empty --------------------------------------------------------------------- + logical function empty(s) + type(stack_var), intent(inout) :: s + empty = (s%size == 0 .or. .not. allocated(s%data)) + end function empty + +end module stack + +program tstack + use stack + implicit none + type(stack_var) :: s + integer :: v + + call push(s,1) + call push(s,2) + call push(s,3) + call push(s,4) + + do + if (empty(s)) exit + v = pop(s) + write(*,'(a,i0)') 'Popped value off stack = ',v + end do +end program tstack diff --git a/Task/Stack/Go/stack-1.go b/Task/Stack/Go/stack-1.go new file mode 100644 index 0000000000..ce9ca6cc15 --- /dev/null +++ b/Task/Stack/Go/stack-1.go @@ -0,0 +1 @@ +var intStack []int diff --git a/Task/Stack/Go/stack-2.go b/Task/Stack/Go/stack-2.go new file mode 100644 index 0000000000..45086bbe8a --- /dev/null +++ b/Task/Stack/Go/stack-2.go @@ -0,0 +1 @@ +intStack = append(intStack, 7) diff --git a/Task/Stack/Go/stack-3.go b/Task/Stack/Go/stack-3.go new file mode 100644 index 0000000000..765ec6bde1 --- /dev/null +++ b/Task/Stack/Go/stack-3.go @@ -0,0 +1 @@ +popped, intStack = intStack[len(intStack)-1], intStack[:len(intStack)-1] diff --git a/Task/Stack/Go/stack-4.go b/Task/Stack/Go/stack-4.go new file mode 100644 index 0000000000..7e396e3fa9 --- /dev/null +++ b/Task/Stack/Go/stack-4.go @@ -0,0 +1 @@ +len(intStack) == 0 diff --git a/Task/Stack/Go/stack-5.go b/Task/Stack/Go/stack-5.go new file mode 100644 index 0000000000..ed6c08eef1 --- /dev/null +++ b/Task/Stack/Go/stack-5.go @@ -0,0 +1 @@ +intStack[len(intStack)-1] diff --git a/Task/Stack/Go/stack-6.go b/Task/Stack/Go/stack-6.go new file mode 100644 index 0000000000..19ef8333dd --- /dev/null +++ b/Task/Stack/Go/stack-6.go @@ -0,0 +1,53 @@ +package main + +import "fmt" + +type stack []interface{} + +func (k *stack) push(s interface{}) { + *k = append(*k, s) +} + +func (k *stack) pop() (s interface{}, ok bool) { + if k.empty() { + return + } + last := len(*k) - 1 + s = (*k)[last] + *k = (*k)[:last] + return s, true +} + +func (k *stack) peek() (s interface{}, ok bool) { + if k.empty() { + return + } + last := len(*k) - 1 + s = (*k)[last] + return s, true +} + +func (k *stack) empty() bool { + return len(*k) == 0 +} + +func main() { + var s stack + fmt.Println("new stack:", s) + fmt.Println("empty?", s.empty()) + s.push(3) + fmt.Println("push 3. stack:", s) + fmt.Println("empty?", s.empty()) + s.push("four") + fmt.Println(`push "four" stack:`, s) + if top, ok := s.peek(); ok { + fmt.Println("top value:", top) + } else { + fmt.Println("nothing on stack") + } + if popped, ok := s.pop(); ok { + fmt.Println(popped, "popped. stack:", s) + } else { + fmt.Println("nothing to pop") + } +} diff --git a/Task/Stack/Groovy/stack.groovy b/Task/Stack/Groovy/stack.groovy new file mode 100644 index 0000000000..0b9d05147e --- /dev/null +++ b/Task/Stack/Groovy/stack.groovy @@ -0,0 +1,37 @@ +def stack = [] +assert stack.empty + +stack.push(55) +stack.push(21) +stack.push('kittens') +assert stack.last() == 'kittens' +assert stack.size() == 3 +assert ! stack.empty + +println stack + +assert stack.pop() == "kittens" +assert stack.size() == 2 + +println stack + +stack.push(-20) + +println stack + +stack.push( stack.pop() * stack.pop() ) +assert stack.last() == -420 +assert stack.size() == 2 + +println stack + +stack.push(stack.pop() / stack.pop()) +assert stack.size() == 1 + +println stack + +println stack.pop() +assert stack.size() == 0 +assert stack.empty + +try { stack.pop() } catch (NoSuchElementException e) { println e.message } diff --git a/Task/Stack/Haskell/stack-1.hs b/Task/Stack/Haskell/stack-1.hs new file mode 100644 index 0000000000..2e3a971b27 --- /dev/null +++ b/Task/Stack/Haskell/stack-1.hs @@ -0,0 +1,18 @@ +type Stack a = [a] + +create :: Stack a +create = [] + +push :: a -> Stack a -> Stack a +push = (:) + +pop :: Stack a -> (a, Stack a) +pop [] = error "Stack empty" +pop (x:xs) = (x,xs) + +empty :: Stack a -> Bool +empty = null + +peek :: Stack a -> a +peek [] = error "Stack empty" +peek (x:_) = x diff --git a/Task/Stack/Haskell/stack-2.hs b/Task/Stack/Haskell/stack-2.hs new file mode 100644 index 0000000000..f6cbb58551 --- /dev/null +++ b/Task/Stack/Haskell/stack-2.hs @@ -0,0 +1,22 @@ +import Control.Monad.State + +type Stack a b = State [a] b + +push :: a -> Stack a () +push = modify . (:) + +pop :: Stack a a +pop = do + nonEmpty + x <- peek + modify tail + return x + +empty :: Stack a Bool +empty = gets null + +peek :: Stack a a +peek = nonEmpty >> gets head + +nonEmpty :: Stack a () +nonEmpty = empty >>= flip when (fail "Stack empty") diff --git a/Task/Stack/Icon/stack.icon b/Task/Stack/Icon/stack.icon new file mode 100644 index 0000000000..b585626564 --- /dev/null +++ b/Task/Stack/Icon/stack.icon @@ -0,0 +1,16 @@ +procedure main() +stack := [] # new empty stack +push(stack,1) # add item +push(stack,"hello",table(),set(),[],5) # add more items of mixed types in order left to right +y := top(stack) # peek +x := pop(stack) # remove item +write("The stack is ",if isempty(stack) then "empty" else "not empty") +end + +procedure isempty(x) #: test if a datum is empty, return the datum or fail (task requirement) +if *x = 0 then return x # in practice just write *x = 0 or *x ~= 0 for is/isn't empty +end + +procedure top(x) #: return top element w/o changing stack +return x[1] # in practice, just use x[1] +end diff --git a/Task/Stack/Io/stack.io b/Task/Stack/Io/stack.io new file mode 100644 index 0000000000..3df81e96d2 --- /dev/null +++ b/Task/Stack/Io/stack.io @@ -0,0 +1,21 @@ +Node := Object clone do( + next := nil + obj := nil +) + +Stack := Object clone do( + node := nil + + pop := method( + obj := node obj + node = node next + obj + ) + + push := method(obj, + nn := Node clone + nn obj = obj + nn next = self node + self node = nn + ) +) diff --git a/Task/Stack/Ioke/stack.ioke b/Task/Stack/Ioke/stack.ioke new file mode 100644 index 0000000000..308b2c069f --- /dev/null +++ b/Task/Stack/Ioke/stack.ioke @@ -0,0 +1,6 @@ +Stack = Origin mimic do( + initialize = method(@elements = []) + pop = method(@elements pop!) + empty = method(@elements empty?) + push = method(element, @elements push!(element)) +) diff --git a/Task/Stack/J/stack-1.j b/Task/Stack/J/stack-1.j new file mode 100644 index 0000000000..3777afea29 --- /dev/null +++ b/Task/Stack/J/stack-1.j @@ -0,0 +1,4 @@ +stack=: '' +push=: monad def '0$stack=:stack,y' +pop=: monad def 'r[ stack=:}:stack[ r=.{:stack' +empty=: monad def '0=#stack' diff --git a/Task/Stack/J/stack-2.j b/Task/Stack/J/stack-2.j new file mode 100644 index 0000000000..d5d1521c12 --- /dev/null +++ b/Task/Stack/J/stack-2.j @@ -0,0 +1,6 @@ + push 9 + + pop '' +9 + empty '' +1 diff --git a/Task/Stack/Java/stack-1.java b/Task/Stack/Java/stack-1.java new file mode 100644 index 0000000000..ccab120716 --- /dev/null +++ b/Task/Stack/Java/stack-1.java @@ -0,0 +1,29 @@ +public class Stack{ + private Node first = null; + public boolean isEmpty(){ + return first == null; + } + public Object Pop(){ + if(isEmpty()) + throw new Exception("Can't Pop from an empty Stack."); + else{ + Object temp = first.value; + first = first.next; + return temp; + } + } + public void Push(Object o){ + first = new Node(o, first); + } + class Node{ + public Node next; + public Object value; + public Node(Object value){ + this(value, null); + } + public Node(Object value, Node next){ + this.next = next; + this.value = value; + } + } +} diff --git a/Task/Stack/Java/stack-2.java b/Task/Stack/Java/stack-2.java new file mode 100644 index 0000000000..cf3740bc04 --- /dev/null +++ b/Task/Stack/Java/stack-2.java @@ -0,0 +1,29 @@ +public class Stack<T>{ + private Node first = null; + public boolean isEmpty(){ + return first == null; + } + public T Pop(){ + if(isEmpty()) + throw new Exception("Can't Pop from an empty Stack."); + else{ + T temp = first.value; + first = first.next; + return temp; + } + } + public void Push(T o){ + first = new Node(o, first); + } + class Node{ + public Node next; + public T value; + public Node(T value){ + this(value, null); + } + public Node(T value, Node next){ + this.next = next; + this.value = value; + } + } +} diff --git a/Task/Stack/JavaScript/stack-1.js b/Task/Stack/JavaScript/stack-1.js new file mode 100644 index 0000000000..a925ec833e --- /dev/null +++ b/Task/Stack/JavaScript/stack-1.js @@ -0,0 +1,5 @@ +var stack = []; +stack.push(1) +stack.push(2,3); +print(stack.pop()); // 3 +print(stack.length); // 2, stack empty if 0 diff --git a/Task/Stack/JavaScript/stack-2.js b/Task/Stack/JavaScript/stack-2.js new file mode 100644 index 0000000000..02c2e04d0b --- /dev/null +++ b/Task/Stack/JavaScript/stack-2.js @@ -0,0 +1,8 @@ +function Stack() { + this.data = new Array(); + + this.push = function(element) {this.data.push(element)} + this.pop = function() {return this.data.pop()} + this.empty = function() {return this.data.length == 0} + this.peek = function() {return this.data[0]} +} diff --git a/Task/Stack/Liberty-BASIC/stack.liberty b/Task/Stack/Liberty-BASIC/stack.liberty new file mode 100644 index 0000000000..2c7a2dd172 --- /dev/null +++ b/Task/Stack/Liberty-BASIC/stack.liberty @@ -0,0 +1,38 @@ +global stack$ +stack$="" + +randomize .51 +for i = 1 to 10 + if rnd(1)>0.5 then + print "pop => ";pop$() + else + j=j+1 + s$ = chr$(j + 64) + print "push ";s$ + call push s$ + end if +next + +print +print "Clean-up" +do + print "pop => ";pop$() +loop while not(empty()) +print "Stack is empty" + +end + +'------------------------------------ +sub push s$ + stack$=s$+"|"+stack$ 'stack +end sub + +function pop$() + if stack$="" then pop$="*EMPTY*": exit function + pop$=word$(stack$,1,"|") + stack$=mid$(stack$,instr(stack$,"|")+1) +end function + +function empty() + empty =(stack$="") +end function diff --git a/Task/Stack/Logo/stack.logo b/Task/Stack/Logo/stack.logo new file mode 100644 index 0000000000..08139b6ce4 --- /dev/null +++ b/Task/Stack/Logo/stack.logo @@ -0,0 +1,6 @@ +make "stack [] +push "stack 1 +push "stack 2 +push "stack 3 +print pop "stack ; 3 +print empty? :stack ; false diff --git a/Task/Stack/Lua/stack.lua b/Task/Stack/Lua/stack.lua new file mode 100644 index 0000000000..40a4d2e36c --- /dev/null +++ b/Task/Stack/Lua/stack.lua @@ -0,0 +1,3 @@ +stack = {} +table.insert(stack,3) +print(table.remove(stack)) --> 3 diff --git a/Task/Stack/MATLAB/stack-1.m b/Task/Stack/MATLAB/stack-1.m new file mode 100644 index 0000000000..3ac6d038f2 --- /dev/null +++ b/Task/Stack/MATLAB/stack-1.m @@ -0,0 +1,13 @@ +mystack = {}; + +% push +mystack{end+1} = x; + +%pop +x = mystack{end}; mystack{end} = []; + +%peek,top +x = mystack{end}; + +% empty +isempty(mystack) diff --git a/Task/Stack/MATLAB/stack-2.m b/Task/Stack/MATLAB/stack-2.m new file mode 100644 index 0000000000..cb3ae4b01f --- /dev/null +++ b/Task/Stack/MATLAB/stack-2.m @@ -0,0 +1,82 @@ +%This class impliments a standard LIFO queue. +classdef LIFOQueue + + properties + queue + end + + methods + + %Class constructor + function theQueue = LIFOQueue(varargin) + + if isempty(varargin) %No input arguments + + %Initialize the queue state as empty + theQueue.queue = {}; + elseif (numel(varargin) > 1) %More than 1 input arg + + %Make the queue the list of input args + theQueue.queue = varargin; + elseif iscell(varargin{:}) %If the only input is a cell array + + %Make the contents of the cell array the elements in the queue + theQueue.queue = varargin{:}; + else %There is one input argument that is not a cell + + %Make that one arg the only element in the queue + theQueue.queue = varargin; + end + + end + + %push() - pushes a new element to the end of the queue + function push(theQueue,varargin) + + if isempty(varargin) + theQueue.queue(end+1) = {[]}; + elseif (numel(varargin) > 1) %More than 1 input arg + + %Make the queue the list of input args + theQueue.queue( end+1:end+numel(varargin) ) = varargin; + elseif iscell(varargin{:}) %If the only input is a cell array + + %Make the contents of the cell array the elements in the queue + theQueue.queue( end+1:end+numel(varargin{:}) ) = varargin{:}; + else %There is one input argument that is not a cell + + %Make that one arg the only element in the queue + theQueue.queue{end+1} = varargin{:}; + end + + %Makes changes to the queue permanent + assignin('caller',inputname(1),theQueue); + + end + + %pop() - pops the first element off the queue + function element = pop(theQueue) + + if empty(theQueue) + error 'The queue is empty' + else + %Returns the first element in the queue + element = theQueue.queue{end}; + + %Removes the first element from the queue + theQueue.queue(end) = []; + + %Makes changes to the queue permanent + assignin('caller',inputname(1),theQueue); + end + end + + %empty() - Returns true if the queue is empty + function trueFalse = empty(theQueue) + + trueFalse = isempty(theQueue.queue); + + end + + end %methods +end diff --git a/Task/Stack/MATLAB/stack-3.m b/Task/Stack/MATLAB/stack-3.m new file mode 100644 index 0000000000..afca4dfaa5 --- /dev/null +++ b/Task/Stack/MATLAB/stack-3.m @@ -0,0 +1,30 @@ +>> myLIFO = LIFOQueue(1,'fish',2,'fish','red fish','blue fish') + +myLIFO = + + LIFOQueue + +>> myLIFO.pop() + +ans = + +blue fish + +>> myLIFO.push('Cat Fish') +>> myLIFO.pop() + +ans = + +Cat Fish + +>> myLIFO.pop() + +ans = + +red fish + +>> empty(myLIFO) + +ans = + + 0 diff --git a/Task/Stack/Mathematica/stack.math b/Task/Stack/Mathematica/stack.math new file mode 100644 index 0000000000..36f8478060 --- /dev/null +++ b/Task/Stack/Mathematica/stack.math @@ -0,0 +1,14 @@ +EmptyQ[a_] := If[Length[a] == 0, True, False] +SetAttributes[Push, HoldAll];[a_, elem_] := AppendTo[a, elem] +SetAttributes[Pop, HoldAllComplete]; +Pop[a_] := If[EmptyQ[a], False, b = Last[a]; Set[a, Most[a]]; b] +Peek[a_] := If[EmptyQ[a], False, Last[a]] + +Example use: +stack = {};Push[stack, 1]; Push[stack, 2]; Push[stack, 3]; Push[stack, 4]; +Peek[stack] +->4 +Pop[stack] +->4 +Peek[stack] +->3 diff --git a/Task/Stack/Maxima/stack.maxima b/Task/Stack/Maxima/stack.maxima new file mode 100644 index 0000000000..010dd78f76 --- /dev/null +++ b/Task/Stack/Maxima/stack.maxima @@ -0,0 +1,11 @@ +/* lists can be used as stacks; Maxima provides pop and push */ + +load(basic)$ + +a: []$ +push(25, a)$ +push(7, a)$ +pop(a); + +emptyp(a); +length(a); diff --git a/Task/Stack/OCaml/stack.ocaml b/Task/Stack/OCaml/stack.ocaml new file mode 100644 index 0000000000..d121fbc395 --- /dev/null +++ b/Task/Stack/OCaml/stack.ocaml @@ -0,0 +1,18 @@ +exception Stack_empty + +class ['a] stack = + object (self) + val mutable lst : 'a list = [] + + method push x = + lst <- x::lst + + method pop = + match lst with + [] -> raise Stack_empty + | x::xs -> lst <- xs; + x + + method is_empty = + lst = [] + end diff --git a/Task/Stack/Objeck/stack.objeck b/Task/Stack/Objeck/stack.objeck new file mode 100644 index 0000000000..fe6896502b --- /dev/null +++ b/Task/Stack/Objeck/stack.objeck @@ -0,0 +1,5 @@ +stack := IntStack->New(); +stack->Push(13); +stack->Push(7); +(stack->Pop() + stack->Pop())->PrintLine(); +stack->IsEmpty()->PrintLine(); diff --git a/Task/Stack/Objective-C/stack.m b/Task/Stack/Objective-C/stack.m new file mode 100644 index 0000000000..25abeb6058 --- /dev/null +++ b/Task/Stack/Objective-C/stack.m @@ -0,0 +1,8 @@ +NSMutableArray *stack = [NSMutableArray array]; // creating + +[stack addObject:value]; // pushing + +id value = [stack lastObject]; +[stack removeLastObject]; // popping + +[stack count] == 0 // is empty? diff --git a/Task/Stack/OxygenBasic/stack.oxy b/Task/Stack/OxygenBasic/stack.oxy new file mode 100644 index 0000000000..5e0305e131 --- /dev/null +++ b/Task/Stack/OxygenBasic/stack.oxy @@ -0,0 +1,20 @@ +function f() + sys a=1,b=2,c=3,d=4 + push a + push b + push c + push d + print a "," b "," c "," d 'result 1,2,3,4 + a=10 + b=20 + c=30 + d=40 + print a "," b "," c "," d 'result 10,20,30,40 + pop a + pop b + pop c + pop d + print a "," b "," c "," d 'result 4,3,2,1 +end function + +f diff --git a/Task/Stack/Oz/stack.oz b/Task/Stack/Oz/stack.oz new file mode 100644 index 0000000000..46651d8d32 --- /dev/null +++ b/Task/Stack/Oz/stack.oz @@ -0,0 +1,31 @@ +functor +export + New + Push + Pop + Empty +define + fun {New} + {NewCell nil} + end + + proc {Push Stack Element} + NewStack + %% Use atomic swap for thread safety + OldStack = Stack := NewStack + in + NewStack = Element|OldStack + end + + proc {Pop Stack ?Result} + NewStack + %% Use atomic swap for thread safety + OldStack = Stack := NewStack + in + Result|NewStack = OldStack + end + + fun {Empty Stack} + @Stack == nil + end +end diff --git a/Task/Stack/PARI-GP/stack.pari b/Task/Stack/PARI-GP/stack.pari new file mode 100644 index 0000000000..7f1e76c7e2 --- /dev/null +++ b/Task/Stack/PARI-GP/stack.pari @@ -0,0 +1,18 @@ +push(x)=v=concat(v,[x]);; +pop()={ + if(#v, + my(x=v[#v]); + v=vecextract(v,1<<(#v-1)-1); + x + , + error("Stack underflow") + ) +}; +empty()=v==[]; +peek()={ + if(#v, + v[#v] + , + error("Stack underflow") + ) +}; diff --git a/Task/Stack/PHP/stack.php b/Task/Stack/PHP/stack.php new file mode 100644 index 0000000000..94f52979bd --- /dev/null +++ b/Task/Stack/PHP/stack.php @@ -0,0 +1,11 @@ +$stack = array(); + +empty( $stack ); // true + +array_push( $stack, 1 ); // or $stack[] = 1; +array_push( $stack, 2 ); // or $stack[] = 2; + +empty( $stack ); // false + +echo array_pop( $stack ); // outputs "2" +echo array_pop( $stack ); // outputs "1" diff --git a/Task/Stack/PL-I/stack.pli b/Task/Stack/PL-I/stack.pli new file mode 100644 index 0000000000..a526f9e2fa --- /dev/null +++ b/Task/Stack/PL-I/stack.pli @@ -0,0 +1,39 @@ +/* Any controlled variable may behave as a stack. */ + +declare s float controlled; + +/* to push a value on the stack. */ +allocate s; +s = 10; + +/* To pop a value from the stack. */ +put (s); +free s; + +/* to peek at the top of stack> */ +put (s); + +/* To see whether the stack is empty */ +if allocation(s) = 0 then ... + +/* Note: popping a value from the stack, or peeking, */ +/* would usually require a check that the stack is not empty. */ + +/* Note: The above is a simple stack for S. */ +/* S can be any kind of data structure, an array, etc. */ + +/* Example to push ten values onto the stack, and then to */ +/* remove them. */ + +/* Push ten values, obtained from the input, onto the stack: */ +declare S float controlled; +do i = 1 to 10; + allocate s; + get list (s); +end; +/* To pop those values from the stack: */ +do while (allocation(s) > 0); + put skip list (s); + free s; +end; +/* The values are printed in the reverse order, of course. */ diff --git a/Task/Stack/Pascal/stack.pascal b/Task/Stack/Pascal/stack.pascal new file mode 100644 index 0000000000..bb3555cbc4 --- /dev/null +++ b/Task/Stack/Pascal/stack.pascal @@ -0,0 +1,55 @@ +{ tStack is the actual stack type, tStackNode a helper type } +type + pStackNode = ^tStackNode; + tStackNode = record + next: pStackNode; + data: integer; + end; + tStack = record + top: pStackNode; + end; + +{ Always call InitStack before using a stack } +procedure InitStack(var stack: tStack); + begin + stack.top := nil + end; + +{ This function removes all content from a stack; call before disposing, or before a local stack variable goes out of scope } +procedure ClearStack(var stack: tStack); + var + node: pStackNode; + begin + while stack.top <> nil do + begin + node := stack.top; + stack.top := stack.top^.next; + dispose(node); + end + end; + +function StackIsEmpty(stack: tStack):Boolean; + begin + StackIsEmpty := stack.top = nil + end; + +procedure PushToStack(var stack: tStack; value: integer); + var + node: pStackNode; + begin + new(node); + node^.next := stack.top; + node^.data := value; + stack.top := node + end; + +{ may only be called on a non-empty stack! } +function PopFromStack(var stack: tStack): integer; + var + node: pStackNode; + begin + node := stack.top; + stack.top := node^.next; + PopFromStack := node^.data; + dispose(node); + end; diff --git a/Task/Stack/Perl-6/stack.pl6 b/Task/Stack/Perl-6/stack.pl6 new file mode 100644 index 0000000000..feb0e53f05 --- /dev/null +++ b/Task/Stack/Perl-6/stack.pl6 @@ -0,0 +1,5 @@ +my @stack; # just a array +@stack.push($elem); # add $elem to the end of @stack +$elem = @stack.pop; # get the last element back +@stack.elems == 0 # true, because the stack is empty +not @stack # also true because @stack is false diff --git a/Task/Stack/Perl/stack.pl b/Task/Stack/Perl/stack.pl new file mode 100644 index 0000000000..bf9398ee42 --- /dev/null +++ b/Task/Stack/Perl/stack.pl @@ -0,0 +1 @@ +sub empty{ not @_ } diff --git a/Task/Stack/PicoLisp/stack.l b/Task/Stack/PicoLisp/stack.l new file mode 100644 index 0000000000..8c83109527 --- /dev/null +++ b/Task/Stack/PicoLisp/stack.l @@ -0,0 +1,3 @@ +(push 'Stack 3) +(push 'Stack 2) +(push 'Stack 1) diff --git a/Task/Stack/PostScript/stack.ps b/Task/Stack/PostScript/stack.ps new file mode 100644 index 0000000000..68f56da7c5 --- /dev/null +++ b/Task/Stack/PostScript/stack.ps @@ -0,0 +1,11 @@ +% empty? is already defined. +/push {exch cons}. +/pop {uncons exch pop}. +[2 3 4 5 6] 1 push += [1 2 3 4 5 6] +[1 2 3 4 5 6] pop +=[2 3 4 5 6] +[2 3 4 5 6] empty? +=false +[] empty? +=true diff --git a/Task/Stack/Prolog/stack.pro b/Task/Stack/Prolog/stack.pro new file mode 100644 index 0000000000..d7940de6a4 --- /dev/null +++ b/Task/Stack/Prolog/stack.pro @@ -0,0 +1,11 @@ +% push( ELEMENT, STACK, NEW ) +% True if NEW is [ELEMENT|STACK] +push(ELEMENT,STACK,[ELEMENT|STACK]). + +% pop( STACK, TOP, NEW ) +% True if TOP and NEW are head and tail, respectively, of STACK +pop([TOP|STACK],TOP,STACK). + +% empty( STACK ) +% True if STACK is empty +empty([]). diff --git a/Task/Stack/PureBasic/stack.purebasic b/Task/Stack/PureBasic/stack.purebasic new file mode 100644 index 0000000000..dfc85db751 --- /dev/null +++ b/Task/Stack/PureBasic/stack.purebasic @@ -0,0 +1,38 @@ +Global NewList MyStack() + +Procedure Push_LIFO(n) + FirstElement(MyStack()) + InsertElement(MyStack()) + MyStack() = n +EndProcedure + +Procedure Pop_LIFO() + If FirstElement(MyStack()) + Topmost = MyStack() + DeleteElement(MyStack()) + EndIf + ProcedureReturn Topmost +EndProcedure + +Procedure Empty_LIFO() + Protected Result + If ListSize(MyStack())=0 + Result = #True + EndIf + ProcedureReturn Result +EndProcedure + +Procedure Peek_LIFO() + If FirstElement(MyStack()) + Topmost = MyStack() + EndIf + ProcedureReturn Topmost +EndProcedure + +;---- Example of implementation ---- +Push_LIFO(3) +Push_LIFO(1) +Push_LIFO(4) +While Not Empty_LIFO() + Debug Pop_LIFO() +Wend diff --git a/Task/Stack/Python/stack-1.py b/Task/Stack/Python/stack-1.py new file mode 100644 index 0000000000..ca20f965bd --- /dev/null +++ b/Task/Stack/Python/stack-1.py @@ -0,0 +1,5 @@ +from collections import deque +stack = deque() +stack.append(value) # pushing +value = stack.pop() +not stack # is empty? diff --git a/Task/Stack/Python/stack-2.py b/Task/Stack/Python/stack-2.py new file mode 100644 index 0000000000..dae90167a6 --- /dev/null +++ b/Task/Stack/Python/stack-2.py @@ -0,0 +1,11 @@ +from collections import deque + +class Stack: + def __init__(self): + self._items = deque() + def append(self, item): + self._items.append(item) + def pop(self): + return self._items.pop() + def __nonzero__(self): + return bool(self._items) diff --git a/Task/Stack/Python/stack-3.py b/Task/Stack/Python/stack-3.py new file mode 100644 index 0000000000..2730b97cdc --- /dev/null +++ b/Task/Stack/Python/stack-3.py @@ -0,0 +1,12 @@ +class Stack: + def __init__(self): + self._first = None + def __nonzero__(self): + return self._first is not None + def append(self, value): + self._first = (value, self._first) + def pop(self): + if self._first is None: + raise IndexError, "pop from empty stack" + value, self._first = self._first + return value diff --git a/Task/Stack/Python/stack-4.py b/Task/Stack/Python/stack-4.py new file mode 100644 index 0000000000..3be5a605da --- /dev/null +++ b/Task/Stack/Python/stack-4.py @@ -0,0 +1 @@ +while not stack.empty(): diff --git a/Task/Stack/Python/stack-5.py b/Task/Stack/Python/stack-5.py new file mode 100644 index 0000000000..e017e6ef39 --- /dev/null +++ b/Task/Stack/Python/stack-5.py @@ -0,0 +1 @@ +while stack: diff --git a/Task/Stack/R/stack.r b/Task/Stack/R/stack.r new file mode 100644 index 0000000000..eead51db7c --- /dev/null +++ b/Task/Stack/R/stack.r @@ -0,0 +1,54 @@ +library(proto) + +stack <- proto(expr = { + l <- list() + empty <- function(.) length(.$l) == 0 + push <- function(., x) + { + .$l <- c(list(x), .$l) + print(.$l) + invisible() + } + pop <- function(.) + { + if(.$empty()) stop("can't pop from an empty list") + .$l[[1]] <- NULL + print(.$l) + invisible() + } +}) + +stack$empty() +# [1] TRUE +stack$push(3) +# [[1]] +# [1] 3 +stack$push("abc") +# [[1]] +# [1] "abc" +# [[2]] +# [1] 3 +stack$push(matrix(1:6, nrow=2)) +# [[1]] +# [,1] [,2] [,3] +# [1,] 1 3 5 +# [2,] 2 4 6 +# [[2]] +# [1] "abc" +# [[3]] +# [1] 3 +stack$empty() +# [1] FALSE +stack$pop() +# [[1]] +[1] "abc" +# [[2]] +# [1] 3 +stack$pop() +# [[1]] +# [1] 3 +stack$pop() +# list() +stack$pop() +# Error in get("pop", env = stack, inherits = TRUE)(stack, ...) : +# can't pop from an empty list diff --git a/Task/Stack/REBOL/stack.rebol b/Task/Stack/REBOL/stack.rebol new file mode 100644 index 0000000000..5003141bb3 --- /dev/null +++ b/Task/Stack/REBOL/stack.rebol @@ -0,0 +1,36 @@ +REBOL [ + Title: "Stack" + Author: oofoe + Date: 2010-10-04 + URL: http://rosettacode.org/wiki/Stack +] + +stack: make object! [ + data: copy [] + + push: func [x][append data x] + pop: func [/local x][x: last data remove back tail data x] + empty: does [empty? data] + + peek: does [last data] +] + +; Teeny Tiny Test Suite + +assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] + +print "Simple integers:" +s: make stack [] s/push 1 s/push 2 ; Initialize. + +assert [2 = s/peek] +assert [2 = s/pop] +assert [1 = s/pop] +assert [s/empty] + +print [lf "Symbolic data on stack:"] +v: make stack [data: [this is a test]] ; Initialize on instance. + +assert ['test = v/peek] +assert ['test = v/pop] +assert ['a = v/pop] +assert [not v/empty] diff --git a/Task/Stack/REXX/stack.rexx b/Task/Stack/REXX/stack.rexx new file mode 100644 index 0000000000..1b85ae47de --- /dev/null +++ b/Task/Stack/REXX/stack.rexx @@ -0,0 +1,7 @@ +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/Racket/stack-1.rkt b/Task/Stack/Racket/stack-1.rkt new file mode 100644 index 0000000000..e38fca828c --- /dev/null +++ b/Task/Stack/Racket/stack-1.rkt @@ -0,0 +1,5 @@ +#lang racket +(define (stack) '()) +(define (push x stack) (cons x stack)) +(define (pop stack) (values (car stack) (cdr stack))) +(define (empty? stack) (null? stack)) diff --git a/Task/Stack/Racket/stack-2.rkt b/Task/Stack/Racket/stack-2.rkt new file mode 100644 index 0000000000..663f8b604c --- /dev/null +++ b/Task/Stack/Racket/stack-2.rkt @@ -0,0 +1,8 @@ +(struct stack ([items #:auto]) #:mutable #:auto-value '()) +(define (push! x stack) + (set-stack-items! stack (cons x (stack-items stack)))) +(define (pop! stack) + (begin0 (car (stack-items stack)) + (set-stack-items! stack (cdr (stack-items stack))))) +(define (empty? stack) + (null? (stack-items stack))) diff --git a/Task/Stack/Raven/stack-1.raven b/Task/Stack/Raven/stack-1.raven new file mode 100644 index 0000000000..ee27e237fa --- /dev/null +++ b/Task/Stack/Raven/stack-1.raven @@ -0,0 +1,3 @@ +new stack as s +1 s push +s pop diff --git a/Task/Stack/Raven/stack-2.raven b/Task/Stack/Raven/stack-2.raven new file mode 100644 index 0000000000..5b00a68169 --- /dev/null +++ b/Task/Stack/Raven/stack-2.raven @@ -0,0 +1 @@ +s empty if 'stack is empty' print diff --git a/Task/Stack/Retro/stack.retro b/Task/Stack/Retro/stack.retro new file mode 100644 index 0000000000..3422296f6a --- /dev/null +++ b/Task/Stack/Retro/stack.retro @@ -0,0 +1,15 @@ +: stack ( n"- ) create 0 , allot ; +: push ( na- ) dup ++ dup @ + ! ; +: pop ( a-n ) dup @ over -- + @ ; +: top ( a-n ) dup @ + @ ; +: empty? ( a-f ) @ 0 = ; + +10 stack st + +1 st push +2 st push +3 st push +st empty? putn +st top putn +st pop putn st pop putn st pop putn +st empty? putn diff --git a/Task/Stack/Ruby/stack-1.rb b/Task/Stack/Ruby/stack-1.rb new file mode 100644 index 0000000000..a3edc8826f --- /dev/null +++ b/Task/Stack/Ruby/stack-1.rb @@ -0,0 +1,4 @@ +stack = [] +stack.push(value) # pushing +value = stack.pop # popping +stack.empty? # is empty? diff --git a/Task/Stack/Ruby/stack-2.rb b/Task/Stack/Ruby/stack-2.rb new file mode 100644 index 0000000000..e97db478a9 --- /dev/null +++ b/Task/Stack/Ruby/stack-2.rb @@ -0,0 +1,80 @@ +require 'forwardable' + +# A stack contains elements in last-in, first-out order. +# Stack#push adds new elements to the top of the stack; +# Stack#pop removes elements from the top. +class Stack + extend Forwardable + + # Creates a Stack containing _objects_. + def self.[](*objects) + new.push(*objects) + end + + # Creates an empty Stack. + def initialize + @ary = [] + end + + # Duplicates a Stack. + def initialize_copy(obj) + super + @ary = @ary.dup + end + + # Adds each object to the top of this Stack. Returns self. + def push(*objects) + @ary.push(*objects) + self + end + alias << push + + ## + # :method: pop + # :call-seq: + # pop -> obj or nil + # pop(n) -> ary + # + # Removes an element from the top of this Stack, and returns it. + # Returns nil if the Stack is empty. + # + # If passing a number _n_, removes the top _n_ elements, and returns + # an Array of them. If this Stack contains fewer than _n_ elements, + # returns them all. If this Stack is empty, returns an empty Array. + nil + + if ([].pop(0) rescue false) + # Ruby >= 1.8.7 + def_delegator :@ary, :pop + else + # Ruby < 1.8.7 + def pop(*args) # :nodoc: + case len = args.length + when 0 + @ary.pop + when 1 + n = [@ary.length, args.first].min + @ary.slice!(-n, n) + else + raise ArgumentError, "wrong number of arguments (#{len} for 0..1)" + end + end + end + + ## + # :method: empty? + # Returns true if this Stack contains no elements. + def_delegator :@ary, :empty? + + ## + # :method: size + # Returns the number of elements in this Stack. + def_delegator :@ary, :size + alias length size + + # Converts this Stack to a String. + def to_s + "#{self.class}#{@ary.inspect}" + end + alias inspect to_s +end diff --git a/Task/Stack/Ruby/stack-3.rb b/Task/Stack/Ruby/stack-3.rb new file mode 100644 index 0000000000..06634e1a75 --- /dev/null +++ b/Task/Stack/Ruby/stack-3.rb @@ -0,0 +1,12 @@ +s = Stack.new +s.empty? # => true +s.pop # => nil +s.pop(1) # => [] +s.push(1) # => Stack[1] +s.push(2, 3) # => Stack[1, 2, 3] +s.pop # => 3 +s.pop(1) # => [2] +s.empty? # => false + +s = Stack[:a, :b, :c] +s.pop # => :c diff --git a/Task/Stack/Run-BASIC/stack.run b/Task/Stack/Run-BASIC/stack.run new file mode 100644 index 0000000000..88708a59c4 --- /dev/null +++ b/Task/Stack/Run-BASIC/stack.run @@ -0,0 +1,41 @@ +dim stack$(10) ' stack of ten +global stack$ +global stackEnd + +for i = 1 to 5 ' push 5 values to the stack + a$ = push$(chr$(i + 64)) + print "Pushed ";chr$(i + 64);" stack has ";stackEnd +next i + +print "Pop Value:";pop$();" stack has ";stackEnd ' pop last in +print "Pop Value:";pop$();" stack has ";stackEnd ' pop last in + +e$ = mt$() ' MT the stack +print "Empty stack. stack has ";stackEnd + +' ------ PUSH the stack +FUNCTION push$(val$) +stackEnd = stackEnd + 1 ' if more than 10 then lose the oldest +if stackEnd > 10 then + for i = 0 to 9 + stack$(i) = stack$(i+1) + next i + stackEnd = 10 +end if +stack$(stackEnd) = val$ +END FUNCTION + +' ------ POP the stack ----- +FUNCTION pop$() +if stackEnd = 0 then + pop$ = "Stack is MT" + else + pop$ = stack$(stackEnd) ' pop last in + stackEnd = max(stackEnd - 1,0) +end if +END FUNCTION + +' ------ MT the stack ------ +FUNCTION mt$() + stackEnd = 0 +END FUNCTION diff --git a/Task/Stack/Sather/stack-1.sa b/Task/Stack/Sather/stack-1.sa new file mode 100644 index 0000000000..fe4f64c60a --- /dev/null +++ b/Task/Stack/Sather/stack-1.sa @@ -0,0 +1,33 @@ +class STACK{T} is + private attr stack :LLIST{T}; + + create:SAME is + res ::= new; + res.stack := #LLIST{T}; + return res; + end; + + push(elt: T) is + stack.insert_front(elt); + end; + + pop: T is + if ~stack.is_empty then + stack.rewind; + r ::= stack.current; + stack.delete; + return r; + else + raise "stack empty!\n"; + end; + end; + + top: T is + stack.rewind; + return stack.current; + end; + + is_empty: BOOL is + return stack.is_empty; + end; +end; diff --git a/Task/Stack/Sather/stack-2.sa b/Task/Stack/Sather/stack-2.sa new file mode 100644 index 0000000000..bb2c9068e1 --- /dev/null +++ b/Task/Stack/Sather/stack-2.sa @@ -0,0 +1,14 @@ +class MAIN is + main is + s ::= #STACK{INT}; + #OUT + "push values...\n"; + s.push(3); + s.push(2); + s.push(1); + s.push(0); + #OUT + "retrieving them...\n"; + loop + #OUT + s.pop + "\n"; + until!(s.is_empty); end; + end; +end; diff --git a/Task/Stack/Scala/stack.scala b/Task/Stack/Scala/stack.scala new file mode 100644 index 0000000000..f015306057 --- /dev/null +++ b/Task/Stack/Scala/stack.scala @@ -0,0 +1,18 @@ +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/Stack/Scheme/stack.ss b/Task/Stack/Scheme/stack.ss new file mode 100644 index 0000000000..0bcc9d31fa --- /dev/null +++ b/Task/Stack/Scheme/stack.ss @@ -0,0 +1,15 @@ +(define (make-stack) + (let ((st '())) + (lambda (message . args) + (case message + ((empty?) (null? st)) + ((top) (if (null? st) + 'empty + (car st))) + ((push) (set! st (cons (car args) st))) + ((pop) (if (null? st) + 'empty + (let ((result (car st))) + (set! st (cdr st)) + result))) + (else 'badmsg))))) diff --git a/Task/Stack/Seed7/stack.seed7 b/Task/Stack/Seed7/stack.seed7 new file mode 100644 index 0000000000..ea9ffaf117 --- /dev/null +++ b/Task/Stack/Seed7/stack.seed7 @@ -0,0 +1,41 @@ +$ include "seed7_05.s7i"; + +const func type: stack (in type: baseType) is func + result + var type: stackType is void; + begin + stackType := array baseType; + + const proc: push (inout stackType: aStack, in baseType: top) is func + begin + aStack := [] (top) & aStack; + end func; + + const func baseType: pop (inout stackType: aStack) is func + result + var baseType: top is baseType.value; + begin + if length(aStack) = 0 then + raise RANGE_ERROR; + else + top := aStack[1]; + aStack := aStack[2 ..]; + end if; + end func; + + const func boolean: empty (in stackType: aStack) is + return length(aStack) = 0; + end func; + +const type: intStack is stack(integer); + +const proc: main is func + local + var intStack: s is intStack.value; + begin + push(s, 10); + push(s, 20); + writeln(pop(s) = 20); + writeln(pop(s) = 10); + writeln(empty(s)); + end func; diff --git a/Task/Stack/Slate/stack.slate b/Task/Stack/Slate/stack.slate new file mode 100644 index 0000000000..104e9316fc --- /dev/null +++ b/Task/Stack/Slate/stack.slate @@ -0,0 +1,22 @@ +collections define: #Stack &parents: {ExtensibleArray}. +"An abstraction over ExtensibleArray implementations to follow the stack +protocol. The convention is that the Sequence indices run least-to-greatest +from bottom to top." + +s@(Stack traits) push: obj +[s addLast: obj]. + +s@(Stack traits) pop +[s removeLast]. + +s@(Stack traits) pop: n +[s removeLast: n]. + +s@(Stack traits) top +[s last]. + +s@(Stack traits) top: n +[s last: n]. + +s@(Stack traits) bottom +[s first]. diff --git a/Task/Stack/Tcl/stack-1.tcl b/Task/Stack/Tcl/stack-1.tcl new file mode 100644 index 0000000000..d800524d5c --- /dev/null +++ b/Task/Stack/Tcl/stack-1.tcl @@ -0,0 +1,31 @@ +proc push {stackvar value} { + upvar 1 $stackvar stack + lappend stack $value +} +proc pop {stackvar} { + upvar 1 $stackvar stack + set value [lindex $stack end] + set stack [lrange $stack 0 end-1] + return $value +} +proc size {stackvar} { + upvar 1 $stackvar stack + llength $stack +} +proc empty {stackvar} { + upvar 1 $stackvar stack + expr {[size stack] == 0} +} +proc peek {stackvar} { + upvar 1 $stackvar stack + lindex $stack end +} + +set S [list] +empty S ;# ==> 1 (true) +push S foo +empty S ;# ==> 0 (false) +push S bar +peek S ;# ==> bar +pop S ;# ==> bar +peek S ;# ==> foo diff --git a/Task/Stack/Tcl/stack-2.tcl b/Task/Stack/Tcl/stack-2.tcl new file mode 100644 index 0000000000..692ff49f40 --- /dev/null +++ b/Task/Stack/Tcl/stack-2.tcl @@ -0,0 +1,10 @@ +package require struct::stack +struct::stack S +S size ;# ==> 0 +S push a b c d e +S size ;# ==> 5 +S peek ;# ==> e +S pop ;# ==> e +S peek ;# ==> d +S pop 4 ;# ==> d c b a +S size ;# ==> 0 diff --git a/Task/Stack/UnixPipes/stack-1.unixpipes b/Task/Stack/UnixPipes/stack-1.unixpipes new file mode 100644 index 0000000000..fbbbee91bd --- /dev/null +++ b/Task/Stack/UnixPipes/stack-1.unixpipes @@ -0,0 +1,11 @@ +init() { if [ -e stack ]; then rm stack; fi } # force pop to blow up if empty +push() { echo $1 >> stack; } +pop() { + tail -1 stack; + x=`head -n -1 stack | wc -c` + if [ $x -eq '0' ]; then rm stack; else + truncate -s `head -n -1 stack | wc -c` stack + fi +} +empty() { head -n -1 stack |wc -l; } +stack_top() { tail -1 stack; } diff --git a/Task/Stack/UnixPipes/stack-2.unixpipes b/Task/Stack/UnixPipes/stack-2.unixpipes new file mode 100644 index 0000000000..017d5e91f7 --- /dev/null +++ b/Task/Stack/UnixPipes/stack-2.unixpipes @@ -0,0 +1,6 @@ +% push me; push you; push us; push them +% pop;pop;pop;pop +them +us +you +me diff --git a/Task/Stack/VBA/stack-1.vba b/Task/Stack/VBA/stack-1.vba new file mode 100644 index 0000000000..4d87dda847 --- /dev/null +++ b/Task/Stack/VBA/stack-1.vba @@ -0,0 +1,37 @@ +'Simple Stack class + +'uses a dynamic array of Variants to stack the values +'has read-only property "Size" +'and methods "Push", "Pop", "IsEmpty" + +Private myStack() +Private myStackHeight As Integer + +'method Push +Public Function Push(aValue) + 'increase stack height + myStackHeight = myStackHeight + 1 + ReDim Preserve myStack(myStackHeight) + myStack(myStackHeight) = aValue +End Function + +'method Pop +Public Function Pop() + 'check for nonempty stack + If myStackHeight > 0 Then + Pop = myStack(myStackHeight) + myStackHeight = myStackHeight - 1 + Else + MsgBox "Pop: stack is empty!" + End If +End Function + +'method IsEmpty +Public Function IsEmpty() As Boolean + IsEmpty = (myStackHeight = 0) +End Function + +'property Size +Property Get Size() As Integer + Size = myStackHeight +End Property diff --git a/Task/Stack/VBA/stack-2.vba b/Task/Stack/VBA/stack-2.vba new file mode 100644 index 0000000000..1831e1cc36 --- /dev/null +++ b/Task/Stack/VBA/stack-2.vba @@ -0,0 +1,21 @@ +'stack test +Public Sub stacktest() + Dim aStack As New Stack + With aStack + 'push and pop some value + .Push 45 + .Push 123.45 + .Pop + .Push "a string" + .Push "another string" + .Pop + .Push Cos(0.75) + Debug.Print "stack size is "; .Size + While Not .IsEmpty + Debug.Print "pop: "; .Pop + Wend + Debug.Print "stack size is "; .Size + 'try to continue popping + .Pop + End With +End Sub diff --git a/Task/Stack/VBScript/stack.vbscript b/Task/Stack/VBScript/stack.vbscript new file mode 100644 index 0000000000..d775f8912a --- /dev/null +++ b/Task/Stack/VBScript/stack.vbscript @@ -0,0 +1,56 @@ +class stack + dim tos + dim stack() + dim stacksize + + private sub class_initialize + stacksize = 100 + redim stack( stacksize ) + tos = 0 + end sub + + public sub push( x ) + stack(tos) = x + tos = tos + 1 + end sub + + public property get stackempty + stackempty = ( tos = 0 ) + end property + + public property get stackfull + stackfull = ( tos > stacksize ) + end property + + public property get stackroom + stackroom = stacksize - tos + end property + + public function pop() + pop = stack( tos - 1 ) + tos = tos - 1 + end function + + public sub resizestack( n ) + redim preserve stack( n ) + stacksize = n + if tos > stacksize then + tos = stacksize + end if + end sub +end class + +dim s +set s = new stack +s.resizestack 10 +wscript.echo s.stackempty +dim i +for i = 1 to 10 + s.push rnd + wscript.echo s.stackroom + if s.stackroom = 0 then exit for +next +for i = 1 to 10 + wscript.echo s.pop + if s.stackempty then exit for +next diff --git a/Task/Stack/XPL0/stack.xpl0 b/Task/Stack/XPL0/stack.xpl0 new file mode 100644 index 0000000000..05370c87e8 --- /dev/null +++ b/Task/Stack/XPL0/stack.xpl0 @@ -0,0 +1,29 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +int Stack(100), SP; + +proc Push(I); \Push an integer onto the Stack +int I; +[SP:= SP+1; +Stack(SP):= I; +]; \Push + +func Pop; \Pop an integer from the Stack +int I; +[I:= Stack(SP); +SP:= SP-1; +return I; +]; \Pop + +func Empty; \Return 'true' if Stack is empty +return SP<0; + +func Top; \Return the integer at top of Stack +return Stack(SP); + +int I; +[SP:= -1; \initialize stack pointer +for I:= 0 to 10 do Push(I*I); +IntOut(0, Top); CrLf(0); +while not Empty do [IntOut(0, Pop); ChOut(0, ^ )]; +CrLf(0); +] diff --git a/Task/Stair-climbing-puzzle/0DESCRIPTION b/Task/Stair-climbing-puzzle/0DESCRIPTION new file mode 100644 index 0000000000..2531df1021 --- /dev/null +++ b/Task/Stair-climbing-puzzle/0DESCRIPTION @@ -0,0 +1,27 @@ +From [http://lambda-the-ultimate.org/node/1872 Chung-Chieh Shan] (LtU): + +Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? + +Here's a pseudocode of a simple recursive solution without using variables: +<pre> +func step_up() +{ + if not step() { + step_up(); + step_up(); + } +} +</pre> +Inductive proof that step_up() steps up one step, if it terminates: +* Base case (if the step() call returns true): it stepped up one step. QED +* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED + +The second (tail) recursion above can be turned into an iteration, as follows: +<pre> +func step_up() +{ + while not step() { + step_up(); + } +} +</pre> diff --git a/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-1.alg b/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-1.alg new file mode 100644 index 0000000000..2a961ea345 --- /dev/null +++ b/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-1.alg @@ -0,0 +1,6 @@ + PROC step up = VOID: + BEGIN + WHILE NOT step DO + step up + OD + END # step up #; diff --git a/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-2.alg b/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-2.alg new file mode 100644 index 0000000000..42dbdcd2bb --- /dev/null +++ b/Task/Stair-climbing-puzzle/ALGOL-68/stair-climbing-puzzle-2.alg @@ -0,0 +1,28 @@ +PROC scaffolding = VOID: +BEGIN + INT level := 0; + + PROC step = BOOL: + BEGIN + IF random > 0.5 THEN + level +:= 1; + print(("Climbed up to",level, new line)); + TRUE + ELSE + level -:= 1; + print(("Fell down to",level, new line)); + FALSE + FI + END # step #; + + PROC step up = VOID: + BEGIN + WHILE NOT step DO + step up + OD + END # step up #; + + step up +END # scaffolding #; + +scaffolding diff --git a/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-1.as b/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-1.as new file mode 100644 index 0000000000..8db52037fb --- /dev/null +++ b/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-1.as @@ -0,0 +1,7 @@ +function stepUp() +{ + var i:int = 0; + while(i < 1) + if(step())i++; + else i--; +} diff --git a/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-2.as b/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-2.as new file mode 100644 index 0000000000..3f70cd9cb9 --- /dev/null +++ b/Task/Stair-climbing-puzzle/ActionScript/stair-climbing-puzzle-2.as @@ -0,0 +1,8 @@ +function stepUp() +{ + if(!step()) + { + stepUp(); + stepUp(); + } +} diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada new file mode 100644 index 0000000000..5550b287c3 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada @@ -0,0 +1,6 @@ +procedure Step_Up is +begin + while not Step loop + Step_Up; + end loop; +end Step_Up; diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada new file mode 100644 index 0000000000..dca8a1471f --- /dev/null +++ b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada @@ -0,0 +1,32 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; + +procedure Scaffolding is + package Try is new Ada.Numerics.Discrete_Random (Boolean); + use Try; + Dice : Generator; + Level : Integer := 0; + + function Step return Boolean is + begin + if Random (Dice) then + Level := Level + 1; + Ada.Text_IO.Put_Line ("Climbed up to" & Integer'Image (Level)); + return True; + else + Level := Level - 1; + Ada.Text_IO.Put_Line ("Fell down to" & Integer'Image (Level)); + return False; + end if; + end Step; + + procedure Step_Up is + begin + while not Step loop + Step_Up; + end loop; + end Step_Up; +begin + Reset (Dice); + Step_Up; +end Scaffolding; diff --git a/Task/Stair-climbing-puzzle/AutoHotkey/stair-climbing-puzzle.ahk b/Task/Stair-climbing-puzzle/AutoHotkey/stair-climbing-puzzle.ahk new file mode 100644 index 0000000000..765a68f504 --- /dev/null +++ b/Task/Stair-climbing-puzzle/AutoHotkey/stair-climbing-puzzle.ahk @@ -0,0 +1,5 @@ +step_up() +{ + While !step() + step_up() +} diff --git a/Task/Stair-climbing-puzzle/BASIC/stair-climbing-puzzle.basic b/Task/Stair-climbing-puzzle/BASIC/stair-climbing-puzzle.basic new file mode 100644 index 0000000000..56b04b2cce --- /dev/null +++ b/Task/Stair-climbing-puzzle/BASIC/stair-climbing-puzzle.basic @@ -0,0 +1,3 @@ +SUB stepup + IF NOT step1 THEN stepup: stepup +END SUB diff --git a/Task/Stair-climbing-puzzle/BBC-BASIC/stair-climbing-puzzle.bbc b/Task/Stair-climbing-puzzle/BBC-BASIC/stair-climbing-puzzle.bbc new file mode 100644 index 0000000000..30e1b12617 --- /dev/null +++ b/Task/Stair-climbing-puzzle/BBC-BASIC/stair-climbing-puzzle.bbc @@ -0,0 +1,3 @@ + DEF PROCstepup + IF NOT FNstep PROCstepup : PROCstepup + ENDPROC diff --git a/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-1.cpp b/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-1.cpp new file mode 100644 index 0000000000..4a12746119 --- /dev/null +++ b/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-1.cpp @@ -0,0 +1,4 @@ +void step_up() +{ + while (!step()) step_up(); +} diff --git a/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-2.cpp b/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-2.cpp new file mode 100644 index 0000000000..bb558c5b8a --- /dev/null +++ b/Task/Stair-climbing-puzzle/C++/stair-climbing-puzzle-2.cpp @@ -0,0 +1,4 @@ +void step_up() +{ + for (int i = 0; i < 1; step()? ++i : --i); +} diff --git a/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-1.c b/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-1.c new file mode 100644 index 0000000000..3fb4212891 --- /dev/null +++ b/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-1.c @@ -0,0 +1,6 @@ +void step_up(void) +{ + while (!step()) { + step_up(); + } +} diff --git a/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-2.c b/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-2.c new file mode 100644 index 0000000000..9dffa349dd --- /dev/null +++ b/Task/Stair-climbing-puzzle/C/stair-climbing-puzzle-2.c @@ -0,0 +1,12 @@ +void step_up(void) +{ + int i = 0; + + while (i < 1) { + if (step()) { + ++i; + } else { + --i; + } + } +} diff --git a/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-1.clj b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-1.clj new file mode 100644 index 0000000000..e12e1ea0ea --- /dev/null +++ b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-1.clj @@ -0,0 +1,12 @@ +;; the initial level +(def level (atom 41)) + +;; the probability of success +(def prob 0.5001) + + +(defn step + [] + (let [success (< (rand) prob)] + (swap! level (if success inc dec)) + success) ) diff --git a/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-2.clj b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-2.clj new file mode 100644 index 0000000000..42f2bf968d --- /dev/null +++ b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-2.clj @@ -0,0 +1,8 @@ +(defn step-up1 + "Straightforward implementation: keep track of how many level we + need to ascend, and stop when this count is zero." + [] + (loop [deficit 1] + (or (zero? deficit) + (recur (if (step) (dec deficit) + (inc deficit)))) ) ) diff --git a/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-3.clj b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-3.clj new file mode 100644 index 0000000000..03e930112b --- /dev/null +++ b/Task/Stair-climbing-puzzle/Clojure/stair-climbing-puzzle-3.clj @@ -0,0 +1,8 @@ +(defn step-up2 + "Non-tail-recursive. No numbers." + [] + (if (not (step)) + (do (step-up2) ;; undo the fall + (step-up2) ;; try again + ) + true)) diff --git a/Task/Stair-climbing-puzzle/Common-Lisp/stair-climbing-puzzle.lisp b/Task/Stair-climbing-puzzle/Common-Lisp/stair-climbing-puzzle.lisp new file mode 100644 index 0000000000..c2d7da839c --- /dev/null +++ b/Task/Stair-climbing-puzzle/Common-Lisp/stair-climbing-puzzle.lisp @@ -0,0 +1,2 @@ +(defun step-up () + (unless (step) (step-up) (step-up))) diff --git a/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-1.d b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-1.d new file mode 100644 index 0000000000..5bbf050d5b --- /dev/null +++ b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-1.d @@ -0,0 +1,5 @@ +void step_up() +{ + while(!step) + step_up; +} diff --git a/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-2.d b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-2.d new file mode 100644 index 0000000000..03dc58a5d0 --- /dev/null +++ b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-2.d @@ -0,0 +1,4 @@ +void step_up_nr() +{ + for(uint i = 0; i < 1; step ? ++i : --i) {}; +} diff --git a/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-3.d b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-3.d new file mode 100644 index 0000000000..c9678bc405 --- /dev/null +++ b/Task/Stair-climbing-puzzle/D/stair-climbing-puzzle-3.d @@ -0,0 +1,25 @@ +import std.stdio; +import std.random; + +int position; +bool step() +{ + bool r = rand() > (uint.max / 2); + if(r) + writefln("Climbed up to %d", ++position); + else + writefln("Fell down to %d", --position); + return r; +} + +void step_up() +{ + while(!step) + step_up; +} + +void main() +{ + rand_seed(0, 0); // to make it somewhat repeatable + step_up; +} diff --git a/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-1.e b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-1.e new file mode 100644 index 0000000000..d9076b9e42 --- /dev/null +++ b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-1.e @@ -0,0 +1,8 @@ +var level := 41 +var prob := 0.5001 + +def step() { + def success := entropy.nextDouble() < prob + level += success.pick(1, -1) + return success +} diff --git a/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-2.e b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-2.e new file mode 100644 index 0000000000..b3c4ae4ec0 --- /dev/null +++ b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-2.e @@ -0,0 +1,6 @@ +def stepUpCounting() { + var deficit := 1 + while (deficit > 0) { + deficit += step().pick(-1, 1) + } +} diff --git a/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-3.e b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-3.e new file mode 100644 index 0000000000..9f7ea5b68c --- /dev/null +++ b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-3.e @@ -0,0 +1,6 @@ +def stepUpRecur() { + if (!step()) { + stepUpRecur() + stepUpRecur() + } +} diff --git a/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-4.e b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-4.e new file mode 100644 index 0000000000..54f9c4aec4 --- /dev/null +++ b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-4.e @@ -0,0 +1,6 @@ +def stepUpEventualRecur() { + if (!step()) { + return when (stepUpEventualRecur <- (), + stepUpEventualRecur <- ()) -> {} + } +} diff --git a/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-5.e b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-5.e new file mode 100644 index 0000000000..1b678447b3 --- /dev/null +++ b/Task/Stair-climbing-puzzle/E/stair-climbing-puzzle-5.e @@ -0,0 +1,13 @@ +def stepUpEventual() { + # This general structure (tail-recursive def{if{when}}) is rather common + # and probably ought to be defined in a library. + + def loop(deficit) { + if (deficit > 0) { + return when (def success := step()) -> { + loop(deficit + success.pick(-1, 1)) + } + } + } + return loop(1) +} diff --git a/Task/Stair-climbing-puzzle/Erlang/stair-climbing-puzzle.erl b/Task/Stair-climbing-puzzle/Erlang/stair-climbing-puzzle.erl new file mode 100644 index 0000000000..8ae5d6e682 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Erlang/stair-climbing-puzzle.erl @@ -0,0 +1,14 @@ +-module(stair). +-compile(export_all). + +step() -> + 1 == random:uniform(2). + +step_up(true) -> + ok; +step_up(false) -> + step_up(step()), + step_up(step()). + +step_up() -> + step_up(step()). diff --git a/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.euphoria b/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.euphoria new file mode 100644 index 0000000000..7f6e4646a7 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.euphoria @@ -0,0 +1,6 @@ +procedure step_up() + if not step() then + step_up() + step_up() + end if +end procedure diff --git a/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-1.fth b/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-1.fth new file mode 100644 index 0000000000..a44dc66bbd --- /dev/null +++ b/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-1.fth @@ -0,0 +1 @@ +: step-up begin step 0= while recurse repeat ; diff --git a/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-2.fth b/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-2.fth new file mode 100644 index 0000000000..347a95b83e --- /dev/null +++ b/Task/Stair-climbing-puzzle/Forth/stair-climbing-puzzle-2.fth @@ -0,0 +1 @@ +: step-up -1 begin step if 1+ else 1- then ?dup 0= until ; diff --git a/Task/Stair-climbing-puzzle/Fortran/stair-climbing-puzzle.f b/Task/Stair-climbing-puzzle/Fortran/stair-climbing-puzzle.f new file mode 100644 index 0000000000..c73cdc23d6 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Fortran/stair-climbing-puzzle.f @@ -0,0 +1,28 @@ +module StairRobot + implicit none + +contains + + logical function step() + ! try to climb up and return true or false + step = .true. ! to avoid compiler warning + end function step + + recursive subroutine step_up_rec + do while ( .not. step() ) + call step_up_rec + end do + end subroutine step_up_rec + + subroutine step_up_iter + integer :: i = 0 + do while ( i < 1 ) + if ( step() ) then + i = i + 1 + else + i = i - 1 + end if + end do + end subroutine step_up_iter + +end module StairRobot diff --git a/Task/Stair-climbing-puzzle/Go/stair-climbing-puzzle.go b/Task/Stair-climbing-puzzle/Go/stair-climbing-puzzle.go new file mode 100644 index 0000000000..ab14e4ac9f --- /dev/null +++ b/Task/Stair-climbing-puzzle/Go/stair-climbing-puzzle.go @@ -0,0 +1 @@ +func step_up(){for !step(){step_up()}} diff --git a/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-1.hs b/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-1.hs new file mode 100644 index 0000000000..3a9ee5577c --- /dev/null +++ b/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-1.hs @@ -0,0 +1,7 @@ +stepUp :: Robot () +stepUp = untilM step stepUp + +untilM :: Monad m => m Bool -> m () -> m () +untilM test action = do + result <- test + if result then return () else action >> untilM test action diff --git a/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-2.hs b/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-2.hs new file mode 100644 index 0000000000..e9aa1f3f22 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Haskell/stair-climbing-puzzle-2.hs @@ -0,0 +1,19 @@ +import Control.Monad.State +import System.Random (StdGen, getStdGen, random) + +type Robot = State (Int, StdGen) + +step :: Robot Bool +step = do + (i, g) <- get + let (succeeded, g') = random g + put (if succeeded then i + 1 else i - 1, g') + return succeeded + +startingPos = 20 :: Int + +main = do + g <- getStdGen + putStrLn $ "The robot is at step #" ++ show startingPos ++ "." + let (endingPos, _) = execState stepUp (startingPos, g) + putStrLn $ "The robot is at step #" ++ show endingPos ++ "." diff --git a/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-1.icon b/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-1.icon new file mode 100644 index 0000000000..176ecbe864 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-1.icon @@ -0,0 +1,3 @@ +procedure step_up() + return step() | (step_up(),step_up()) +end diff --git a/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-2.icon b/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-2.icon new file mode 100644 index 0000000000..f712c74d98 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Icon/stair-climbing-puzzle-2.icon @@ -0,0 +1,3 @@ +procedure step_up() + (|not step(), step_up()) +end diff --git a/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-1.j b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-1.j new file mode 100644 index 0000000000..3eb3d32744 --- /dev/null +++ b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-1.j @@ -0,0 +1,5 @@ +step =: 0.6 > ?@0: +attemptClimb =: [: <:`>:@.step 0: +isNotUpOne =: -.@(+/@]) + +step_up=: (] , attemptClimb)^:isNotUpOne^:_ diff --git a/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-2.j b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-2.j new file mode 100644 index 0000000000..55b9c1bab3 --- /dev/null +++ b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-2.j @@ -0,0 +1,7 @@ +step_upX=: monad define NB. iterative + while. -. +/y do. y=. y , _1 1 {~ step 0 end. +) + +step_upR=: monad define NB. recursive (stack overflow possible!) + while. -. step'' do. step_upR'' end. +) diff --git a/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-3.j b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-3.j new file mode 100644 index 0000000000..f6cf599531 --- /dev/null +++ b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-3.j @@ -0,0 +1,6 @@ + step_up '' NB. output is sequence of falls & climbs required to climb one step. +_1 1 _1 _1 1 1 1 + +/\ _1 1 _1 _1 1 1 1 NB. running sum of output (current step relative to start) +_1 0 _1 _2 _1 0 1 + +/\ step_up '' NB. another example +_1 _2 _3 _2 _3 _2 _1 _2 _3 _4 _3 _2 _3 _2 _3 _2 _3 _2 _1 _2 _1 _2 _1 0 1 diff --git a/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-4.j b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-4.j new file mode 100644 index 0000000000..c78d5992dd --- /dev/null +++ b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-4.j @@ -0,0 +1 @@ +keepTrying=: (, {: - _1 ^ step)^:({. >: {:)^:_ diff --git a/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-5.j b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-5.j new file mode 100644 index 0000000000..9acd28ffe0 --- /dev/null +++ b/Task/Stair-climbing-puzzle/J/stair-climbing-puzzle-5.j @@ -0,0 +1,6 @@ + keepTrying 2 +2 1 0 1 2 3 + keepTrying 3 +3 2 3 2 3 2 3 4 + keepTrying 4 +4 5 diff --git a/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-1.java b/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-1.java new file mode 100644 index 0000000000..7946230e29 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-1.java @@ -0,0 +1,3 @@ +public void stepUp() { + while (!step()) stepUp(); +} diff --git a/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-2.java b/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-2.java new file mode 100644 index 0000000000..63d66e112e --- /dev/null +++ b/Task/Stair-climbing-puzzle/Java/stair-climbing-puzzle-2.java @@ -0,0 +1,3 @@ +public void stepUp(){ + for (int i = 0; i < 1; step() ? ++i : --i); +} diff --git a/Task/Stair-climbing-puzzle/Liberty-BASIC/stair-climbing-puzzle.liberty b/Task/Stair-climbing-puzzle/Liberty-BASIC/stair-climbing-puzzle.liberty new file mode 100644 index 0000000000..6afd1c0831 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Liberty-BASIC/stair-climbing-puzzle.liberty @@ -0,0 +1,21 @@ +'This demo will try to get the robot to step up +'Run it several times to see the differences; sometimes the robot falls +'quite a ways before making it to the next step up, but sometimes he makes it +'on the first try + +result = Stepp.Up() + +Function Stepp.Up() + While Not(Stepp()) + result = Stepp.Up() + Wend +End Function + +Function Stepp() + Stepp = Int((Rnd(1) * 2)) + If Stepp Then + Print "Robot stepped up" + Else + Print "Robot fell down" + End If +End Function diff --git a/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-1.logo b/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-1.logo new file mode 100644 index 0000000000..115064f089 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-1.logo @@ -0,0 +1,3 @@ +to step.up + if not step [step.up step.up] +end diff --git a/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-2.logo b/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-2.logo new file mode 100644 index 0000000000..1d048d3900 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Logo/stair-climbing-puzzle-2.logo @@ -0,0 +1,4 @@ +to step.up [:n 1] + if :n=0 [stop] + (step.up ifelse step [:n-1] [:n+1]) +end diff --git a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua new file mode 100644 index 0000000000..e216637294 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-1.lua @@ -0,0 +1,3 @@ +function step_up() + while !step() do step_up() end +end diff --git a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua new file mode 100644 index 0000000000..23ebeb7f70 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle-2.lua @@ -0,0 +1,7 @@ +-- since lua does not have ! for negation, the example above is wrong. +--Lua uses the ~ instead of the !, but in this case we have to use the not + + +function step_up() + while not step() do step_up() end +end diff --git a/Task/Stair-climbing-puzzle/MATLAB/stair-climbing-puzzle.m b/Task/Stair-climbing-puzzle/MATLAB/stair-climbing-puzzle.m new file mode 100644 index 0000000000..ab36bceff1 --- /dev/null +++ b/Task/Stair-climbing-puzzle/MATLAB/stair-climbing-puzzle.m @@ -0,0 +1,4 @@ +function step_up() + while ~step() + step_up(); + end diff --git a/Task/Stair-climbing-puzzle/Mathematica/stair-climbing-puzzle.math b/Task/Stair-climbing-puzzle/Mathematica/stair-climbing-puzzle.math new file mode 100644 index 0000000000..150f60445a --- /dev/null +++ b/Task/Stair-climbing-puzzle/Mathematica/stair-climbing-puzzle.math @@ -0,0 +1 @@ +StepUp[] := If[!Step[], StepUp[]; StepUp[]] diff --git a/Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ocaml b/Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ocaml new file mode 100644 index 0000000000..0e2393b7eb --- /dev/null +++ b/Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ocaml @@ -0,0 +1,5 @@ +let rec step_up() = + while not(step()) do + step_up() + done +;; diff --git a/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-1.oz b/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-1.oz new file mode 100644 index 0000000000..0437d24f60 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-1.oz @@ -0,0 +1,6 @@ +proc {StepUp} + if {Not {Step}} then + {StepUp} %% make up for the fall + {StepUp} %% repeat original attempt + end +end diff --git a/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-2.oz b/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-2.oz new file mode 100644 index 0000000000..4c509c60c7 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Oz/stair-climbing-puzzle-2.oz @@ -0,0 +1,9 @@ +proc {StepUp} + Level = {NewCell 0} +in + for until:@Level == 1 do + if {Step} then Level := @Level + 1 + else Level := @Level - 1 + end + end +end diff --git a/Task/Stair-climbing-puzzle/PARI-GP/stair-climbing-puzzle.pari b/Task/Stair-climbing-puzzle/PARI-GP/stair-climbing-puzzle.pari new file mode 100644 index 0000000000..6aad5adf45 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PARI-GP/stair-climbing-puzzle.pari @@ -0,0 +1 @@ +step_up()=while(!step(),step_up()) diff --git a/Task/Stair-climbing-puzzle/Pascal/stair-climbing-puzzle.pascal b/Task/Stair-climbing-puzzle/Pascal/stair-climbing-puzzle.pascal new file mode 100644 index 0000000000..f03571b2fd --- /dev/null +++ b/Task/Stair-climbing-puzzle/Pascal/stair-climbing-puzzle.pascal @@ -0,0 +1,5 @@ +procedure stepUp; +begin + while not step do + stepUp; +end; diff --git a/Task/Stair-climbing-puzzle/Perl-6/stair-climbing-puzzle.pl6 b/Task/Stair-climbing-puzzle/Perl-6/stair-climbing-puzzle.pl6 new file mode 100644 index 0000000000..8991efc339 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Perl-6/stair-climbing-puzzle.pl6 @@ -0,0 +1 @@ +sub step_up { step_up until step; } diff --git a/Task/Stair-climbing-puzzle/Perl/stair-climbing-puzzle.pl b/Task/Stair-climbing-puzzle/Perl/stair-climbing-puzzle.pl new file mode 100644 index 0000000000..8991efc339 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Perl/stair-climbing-puzzle.pl @@ -0,0 +1 @@ +sub step_up { step_up until step; } diff --git a/Task/Stair-climbing-puzzle/PicoLisp/stair-climbing-puzzle.l b/Task/Stair-climbing-puzzle/PicoLisp/stair-climbing-puzzle.l new file mode 100644 index 0000000000..ab9661b662 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PicoLisp/stair-climbing-puzzle.l @@ -0,0 +1,3 @@ +(de stepUp () + (until (step1) # ('step1', because 'step' is a system function) + (stepUp) ) ) diff --git a/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-1.purebasic b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-1.purebasic new file mode 100644 index 0000000000..d3faf4cbc2 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-1.purebasic @@ -0,0 +1,4 @@ +Procedure step_up() + Protected i + Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1 +EndProcedure diff --git a/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-2.purebasic b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-2.purebasic new file mode 100644 index 0000000000..cf1ec9eaf9 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-2.purebasic @@ -0,0 +1,5 @@ +Procedure step_up() + While Not _step() + step_up() + Wend +EndProcedure diff --git a/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-3.purebasic b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-3.purebasic new file mode 100644 index 0000000000..83c7d67b76 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PureBasic/stair-climbing-puzzle-3.purebasic @@ -0,0 +1,30 @@ +Global level + +Procedure _step() + If Random(1) ;equal chance of stepping up or falling down + level + 1 + PrintN("Climbed up to " + Str(level)) + ProcedureReturn #True + Else + level - 1 + PrintN("Fell down to " + Str(level)) + ProcedureReturn #False + EndIf +EndProcedure + +;recursive +Procedure step_up() + While Not _step() + step_up() + Wend +EndProcedure + +If OpenConsole() + PrintN("Begin at level: " + Str(level)) + step_up() + PrintN("*** Now at level: " + Str(level)) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-1.py b/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-1.py new file mode 100644 index 0000000000..0b113e8126 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-1.py @@ -0,0 +1,9 @@ +def step_up1() + "Straightforward implementation: keep track of how many level we + need to ascend, and stop when this count is zero." + deficit = 1 + while deficit > 0: + if step(): + deficit -= 1 + else: + deficit += 1 diff --git a/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-2.py b/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-2.py new file mode 100644 index 0000000000..98f5f273ab --- /dev/null +++ b/Task/Stair-climbing-puzzle/Python/stair-climbing-puzzle-2.py @@ -0,0 +1,4 @@ +def step_up2(): + "No numbers." + while not step(): + step_up2() # undo the fall diff --git a/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-1.r b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-1.r new file mode 100644 index 0000000000..96209cc16b --- /dev/null +++ b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-1.r @@ -0,0 +1,6 @@ +step <- function() { + success <- runif(1) > p + ## Requires that the "robot" is a variable named "level" + level <<- level - 1 + (2 * success) + success +} diff --git a/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-2.r b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-2.r new file mode 100644 index 0000000000..cff46fdc5f --- /dev/null +++ b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-2.r @@ -0,0 +1,5 @@ +stepUp <- function() { + while(! step()) { + stepUp() + } +} diff --git a/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-3.r b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-3.r new file mode 100644 index 0000000000..f1618c1c87 --- /dev/null +++ b/Task/Stair-climbing-puzzle/R/stair-climbing-puzzle-3.r @@ -0,0 +1,6 @@ +stepUpIter <- function() { + i <- 0 + while ( ! i) { + i <- i - 1 + (2 * step()) + } +} diff --git a/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol b/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol new file mode 100644 index 0000000000..8f60d1984b --- /dev/null +++ b/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol @@ -0,0 +1,41 @@ +REBOL [ + Title: "Stair Climber" + Date: 2009-12-14 + Author: oofoe + URL: http://rosettacode.org/wiki/Stair_Climbing +] + +random/seed now + +step: does [random/only reduce [yes no]] + +; Iterative solution with symbol stack. No numbers, draws a nifty +; diagram of number of steps to go. This is intended more to +; demonstrate a correct solution: + +step_up: func [/steps s] [ + either not steps [ + print "Starting up..." + step_up/steps copy [|] + ][ + while [not empty? s][ + print [" Steps left:" s] + either step [remove s][append s '|] + ] + ] +] + +step_up print ["Success!" crlf] + +; Recursive solution. No numbers, no variables. "R" means a recover +; step, "+" means a step up. + +step_upr: does [if not step [prin "R " step_upr prin "+ " step_upr]] + +step_upr print ["Success!" crlf] + +; Small recursive solution, no monitoring: + +step_upt: does [if not step [step_upt step_upt]] + +step_upt print "Success!" diff --git a/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx new file mode 100644 index 0000000000..f3e3055369 --- /dev/null +++ b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx @@ -0,0 +1,6 @@ +step_up: do while \step() + call step_up + end +return + +step_up: return random(0,1) /*randomly step up or fail to step up.*/ diff --git a/Task/Stair-climbing-puzzle/Ruby/stair-climbing-puzzle.rb b/Task/Stair-climbing-puzzle/Ruby/stair-climbing-puzzle.rb new file mode 100644 index 0000000000..51d53b3dcf --- /dev/null +++ b/Task/Stair-climbing-puzzle/Ruby/stair-climbing-puzzle.rb @@ -0,0 +1,22 @@ +def step_up + start_position = $position + step until ($position == start_position + 1) +end + +# assumptions about the step function: +# - it maintains the current position of the robot "as a side effect" +# - the robot is equally likely to step back as to step up +def step + if rand < 0.5 + $position -= 1 + p "fall (#$position)" if $DEBUG + return false + else + $position += 1 + p "rise (#$position)" if $DEBUG + return true + end +end + +$position = 0 +step_up diff --git a/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-1.scala b/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-1.scala new file mode 100644 index 0000000000..8f8c8cf260 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-1.scala @@ -0,0 +1 @@ +def stepUp { while (! step) stepUp } diff --git a/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-2.scala b/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-2.scala new file mode 100644 index 0000000000..5703445cdd --- /dev/null +++ b/Task/Stair-climbing-puzzle/Scala/stair-climbing-puzzle-2.scala @@ -0,0 +1,8 @@ +def stepUp { + def rec: List[Boolean] => Boolean = step :: (_: List[Boolean]) match { + case true :: Nil => true + case true :: false :: rest => rec(rest) + case other => rec(other) + } + rec(Nil) +} diff --git a/Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.ss b/Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.ss new file mode 100644 index 0000000000..33f3ed7e8f --- /dev/null +++ b/Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.ss @@ -0,0 +1,4 @@ +(define (step-up n-steps) + (cond ((zero? n-steps) 'done) + ((step) (step-up (- n-steps 1))) + (else (step-up (+ n-steps 1))))) diff --git a/Task/Stair-climbing-puzzle/Seed7/stair-climbing-puzzle.seed7 b/Task/Stair-climbing-puzzle/Seed7/stair-climbing-puzzle.seed7 new file mode 100644 index 0000000000..f7af4fe4ca --- /dev/null +++ b/Task/Stair-climbing-puzzle/Seed7/stair-climbing-puzzle.seed7 @@ -0,0 +1,6 @@ +const proc: step_up is func + begin + while not doStep do + step_up; + end while; + end func; diff --git a/Task/Stair-climbing-puzzle/Smalltalk/stair-climbing-puzzle.st b/Task/Stair-climbing-puzzle/Smalltalk/stair-climbing-puzzle.st new file mode 100644 index 0000000000..5a6cacef3a --- /dev/null +++ b/Task/Stair-climbing-puzzle/Smalltalk/stair-climbing-puzzle.st @@ -0,0 +1,2 @@ +Smalltalk at: #stepUp put: 0. +stepUp := [ [ step value ] whileFalse: [ stepUp value ] ]. diff --git a/Task/Stair-climbing-puzzle/Standard-ML/stair-climbing-puzzle.ml b/Task/Stair-climbing-puzzle/Standard-ML/stair-climbing-puzzle.ml new file mode 100644 index 0000000000..5b6bd28536 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Standard-ML/stair-climbing-puzzle.ml @@ -0,0 +1,10 @@ +(* + * val step : unit -> bool + * This is a stub for a function which returns true if successfully climb a step or false otherwise. + *) +fun step() = true + +(* + * val step_up : unit -> bool + *) +fun step_up() = step() orelse (step_up() andalso step_up()) diff --git a/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-1.ti-83 b/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-1.ti-83 new file mode 100644 index 0000000000..7ee83bc59f --- /dev/null +++ b/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-1.ti-83 @@ -0,0 +1,17 @@ +If rand>.5:Then +0→C +Disp "FALL" +If A=1:Then +D-1→D +Disp D +End +Else +1→C +Disp "CLIMB" +If A=1:Then +D+1→D +Disp D +End +End +If B=1 +Pause diff --git a/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-2.ti-83 b/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-2.ti-83 new file mode 100644 index 0000000000..874b2379a9 --- /dev/null +++ b/Task/Stair-climbing-puzzle/TI-83-BASIC/stair-climbing-puzzle-2.ti-83 @@ -0,0 +1,5 @@ +prgmSTEP +While C=0 +prgmSTEPUP +prgmSTEP +End diff --git a/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-1.tcl b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-1.tcl new file mode 100644 index 0000000000..bce7cd7402 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-1.tcl @@ -0,0 +1,13 @@ +set level 41 +set prob 0.5001 +proc step {} { + global level prob steps + incr steps + if {rand() < $prob} { + incr level 1 + return 1 + } else { + incr level -1 + return 0 + } +} diff --git a/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-2.tcl b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-2.tcl new file mode 100644 index 0000000000..556a104965 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-2.tcl @@ -0,0 +1,5 @@ +proc step-up-iter {} { + for {incr d} {$d} {incr d} { + incr d [set s -[step]]; incr d $s + } +} diff --git a/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-3.tcl b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-3.tcl new file mode 100644 index 0000000000..ddbe3c1832 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Tcl/stair-climbing-puzzle-3.tcl @@ -0,0 +1,3 @@ +proc step-up-rec {} { + while {![step]} step-up-rec +} diff --git a/Task/Stair-climbing-puzzle/XPL0/stair-climbing-puzzle.xpl0 b/Task/Stair-climbing-puzzle/XPL0/stair-climbing-puzzle.xpl0 new file mode 100644 index 0000000000..f6b8513823 --- /dev/null +++ b/Task/Stair-climbing-puzzle/XPL0/stair-climbing-puzzle.xpl0 @@ -0,0 +1,10 @@ +proc Step_up; \Iterative version +int I; +[I:= 0; +while I<1 do + if Step then I:= I+1 + else I:= I-1; +]; + +proc Step_up; \Recursive version +while not Step do Step_up; diff --git a/Task/Standard-deviation/0DESCRIPTION b/Task/Standard-deviation/0DESCRIPTION new file mode 100644 index 0000000000..2ca0f3aca6 --- /dev/null +++ b/Task/Standard-deviation/0DESCRIPTION @@ -0,0 +1,5 @@ +Write a stateful function, class, generator or coroutine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population. + +Use this to compute the standard deviation of this demonstration set, <math>\{2, 4, 4, 4, 5, 5, 7, 9\}</math>, which is <math>2</math>. + +See also: [[Moving Average]] diff --git a/Task/Standard-deviation/1META.yaml b/Task/Standard-deviation/1META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Standard-deviation/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg new file mode 100644 index 0000000000..1aaff5438d --- /dev/null +++ b/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg @@ -0,0 +1,52 @@ +MODE VALUE = STRUCT(CHAR value), + STDDEV = STRUCT(CHAR stddev), + MEAN = STRUCT(CHAR mean), + VAR = STRUCT(CHAR var), + COUNT = STRUCT(CHAR count), + RESET = STRUCT(CHAR reset); + +MODE ACTION = UNION ( VALUE, STDDEV, MEAN, VAR, COUNT, RESET ); + +LONG REAL sum := 0; +LONG REAL sum2 := 0; +INT num := 0; + +PROC stat object = (LONG REAL v, ACTION action)LONG REAL: +( + + LONG REAL m; + + CASE action IN + (VALUE):( + num +:= 1; + sum +:= v; + sum2 +:= v*v; + stat object(0, LOC STDDEV) + ), + (STDDEV): + long sqrt(stat object(0, LOC VAR)), + (MEAN): + IF num>0 THEN sum/LONG REAL(num) ELSE 0 FI, + (VAR):( + m := stat object(0, LOC MEAN); + IF num>0 THEN sum2/LONG REAL(num)-m*m ELSE 0 FI + ), + (COUNT): + num, + (RESET): + sum := sum2 := num := 0 + ESAC +); + +[]LONG REAL v = ( 2,4,4,4,5,5,7,9 ); + +main: +( + LONG REAL sd; + + FOR i FROM LWB v TO UPB v DO + sd := stat object(v[i], LOC VALUE) + OD; + + printf(($"standard dev := "g(0,6)l$, sd)) +) diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg new file mode 100644 index 0000000000..55561bfc45 --- /dev/null +++ b/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg @@ -0,0 +1,70 @@ +MODE STAT = STRUCT( + LONG REAL sum, + LONG REAL sum2, + INT num +); + +OP INIT = (REF STAT new)REF STAT: + (init OF class stat)(new); + +MODE CLASSSTAT = STRUCT( + PROC (REF STAT, LONG REAL #value#)VOID plusab, + PROC (REF STAT)LONG REAL stddev, mean, variance, count, + PROC (REF STAT)REF STAT init +); + +CLASSSTAT class stat; + +plusab OF class stat := (REF STAT self, LONG REAL value)VOID:( + num OF self +:= 1; + sum OF self +:= value; + sum2 OF self +:= value*value + ); + +OP +:= = (REF STAT lhs, LONG REAL rhs)VOID: # some syntatic sugar # + (plusab OF class stat)(lhs, rhs); + +stddev OF class stat := (REF STAT self)LONG REAL: + long sqrt((variance OF class stat)(self)); + +OP STDDEV = ([]LONG REAL value)LONG REAL: ( # more syntatic sugar # + REF STAT stat = INIT LOC STAT; + FOR i FROM LWB value TO UPB value DO + stat +:= value[i] + OD; + (stddev OF class stat)(stat) +); + +mean OF class stat := (REF STAT self)LONG REAL: + sum OF self/LONG REAL(num OF self); + +variance OF class stat := (REF STAT self)LONG REAL:( + LONG REAL m = (mean OF class stat)(self); + sum2 OF self/LONG REAL(num OF self)-m*m + ); + +count OF class stat := (REF STAT self)LONG REAL: + num OF self; + +init OF class stat := (REF STAT self)REF STAT:( + sum OF self := sum2 OF self := num OF self := 0; + self + ); + +[]LONG REAL value = ( 2,4,4,4,5,5,7,9 ); + +main: +( + printf(($"standard deviation operator = "g(0,6)l$, STDDEV value)); + + REF STAT stat = INIT LOC STAT; + + FOR i FROM LWB value TO UPB value DO + stat +:= value[i] + OD; + + printf(($"standard deviation = "g(0,6)l$, (stddev OF class stat)(stat))); + printf(($"mean = "g(0,6)l$, (mean OF class stat)(stat))); + printf(($"variance = "g(0,6)l$, (variance OF class stat)(stat))); + printf(($"count = "g(0,6)l$, (count OF class stat)(stat))) +) diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg new file mode 100644 index 0000000000..d66a54776d --- /dev/null +++ b/Task/Standard-deviation/ALGOL-68/standard-deviation-3.alg @@ -0,0 +1,16 @@ +LONG REAL sum, sum2; +INT n; + +PROC sd = (LONG REAL x)LONG REAL:( + sum +:= x; + sum2 +:= x*x; + n +:= 1; + IF n = 0 THEN 0 ELSE long sqrt(sum2/n - sum*sum/n/n) FI +); + +sum := sum2 := n := 0; +[]LONG REAL values = (2,4,4,4,5,5,7,9); +FOR i TO UPB values DO + LONG REAL value = values[i]; + printf(($2(xg(0,6))l$, value, sd(value))) +OD diff --git a/Task/Standard-deviation/Ada/standard-deviation.ada b/Task/Standard-deviation/Ada/standard-deviation.ada new file mode 100644 index 0000000000..25a924438a --- /dev/null +++ b/Task/Standard-deviation/Ada/standard-deviation.ada @@ -0,0 +1,28 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Deviation is + type Sample is record + N : Natural := 0; + Mean : Float := 0.0; + Squares : Float := 0.0; + end record; + procedure Add (Data : in out Sample; Point : Float) is + begin + Data.N := Data.N + 1; + Data.Mean := Data.Mean + Point; + Data.Squares := Data.Squares + Point ** 2; + end Add; + function Deviation (Data : Sample) return Float is + begin + return Sqrt (Data.Squares / Float (Data.N) - (Data.Mean / Float (Data.N)) ** 2); + end Deviation; + + Data : Sample; + Test : array (1..8) of Float := (2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0); +begin + for Item in Test'Range loop + Add (Data, Test (Item)); + end loop; + Put_Line ("Deviation" & Float'Image (Deviation (Data))); +end Test_Deviation; diff --git a/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk b/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk new file mode 100644 index 0000000000..624d017b53 --- /dev/null +++ b/Task/Standard-deviation/AutoHotkey/standard-deviation.ahk @@ -0,0 +1,11 @@ +std(2),std(4),std(4),std(4),std(5),std(5),std(7) +MsgBox % std(9) ; 2 + +std(x="") { + Static sum:=0, sqr:=0, n:=0 + If (x="") ; blank parameter: reset + sum := 0, sqr := 0, n := 0 + Else + sum += x, sqr += x*x, n++ ; update state + Return sqrt((sqr-sum*sum/n)/n) +} diff --git a/Task/Standard-deviation/Axiom/standard-deviation-1.axiom b/Task/Standard-deviation/Axiom/standard-deviation-1.axiom new file mode 100644 index 0000000000..f14ef43ecf --- /dev/null +++ b/Task/Standard-deviation/Axiom/standard-deviation-1.axiom @@ -0,0 +1,17 @@ +)abbrev package TESTD TestDomain +TestDomain(T : Join(Field,RadicalCategory)): Exports == Implementation where + R ==> Record(n : Integer, sum : T, ssq : T) + Exports == AbelianMonoid with + _+ : (%,T) -> % + _+ : (T,%) -> % + sd : % -> T + Implementation == R add + Rep := R -- similar representation and implementation + obj : % + 0 == [0,0,0] + obj + (obj2:%) == [obj.n + obj2.n, obj.sum + obj2.sum, obj.ssq + obj2.ssq] + obj + (x:T) == obj + [1, x, x*x] + (x:T) + obj == obj + x + sd obj == + mean : T := obj.sum / (obj.n::T) + sqrt(obj.ssq / (obj.n::T) - mean*mean) diff --git a/Task/Standard-deviation/Axiom/standard-deviation-2.axiom b/Task/Standard-deviation/Axiom/standard-deviation-2.axiom new file mode 100644 index 0000000000..67f0b31752 --- /dev/null +++ b/Task/Standard-deviation/Axiom/standard-deviation-2.axiom @@ -0,0 +1,14 @@ +T ==> Expression Integer +D ==> TestDomain(T) +items := [2,4,4,4,5,5,7,9+x] :: List T; +map(sd, scan(+, items, 0$D)) + +---------------+ + +-+ +-+ +-+ +-+ | 2 + 2\|2 \|3 2\|6 4\|6 \|7x + 64x + 256 + (1) [0,1,-----,----,-----,1,-----,------------------] + 3 2 5 7 8 + Type: List(Expression(Integer)) +eval subst(last %,x=0) + + (2) 2 + Type: Expression(Integer) diff --git a/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc b/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc new file mode 100644 index 0000000000..8d5beb1a04 --- /dev/null +++ b/Task/Standard-deviation/BBC-BASIC/standard-deviation.bbc @@ -0,0 +1,15 @@ + MAXITEMS = 100 + FOR i% = 1 TO 8 + READ n + PRINT "Value = "; n ", running SD = " FNrunningsd(n) + NEXT + END + + DATA 2,4,4,4,5,5,7,9 + + DEF FNrunningsd(n) + PRIVATE list(), i% + DIM list(MAXITEMS) + i% += 1 + list(i%) = n + = SQR(MOD(list())^2/i% - (SUM(list())/i%)^2) diff --git a/Task/Standard-deviation/C++/standard-deviation.cpp b/Task/Standard-deviation/C++/standard-deviation.cpp new file mode 100644 index 0000000000..03bd5512cb --- /dev/null +++ b/Task/Standard-deviation/C++/standard-deviation.cpp @@ -0,0 +1,25 @@ +#include <algorithm> +#include <iostream> +#include <iterator> +#include <cmath> +#include <vector> +#include <iterator> +#include <numeric> + +template <typename Iterator> +double standard_dev( Iterator begin , Iterator end ) { + double mean = std::accumulate( begin , end , 0 ) / std::distance( begin , end ) ; + std::vector<double> squares ; + for( Iterator vdi = begin ; vdi != end ; vdi++ ) + squares.push_back( std::pow( *vdi - mean , 2 ) ) ; + return std::sqrt( std::accumulate( squares.begin( ) , squares.end( ) , 0 ) / squares.size( ) ) ; +} + +int main( ) { + double demoset[] = { 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 } ; + int demosize = sizeof demoset / sizeof *demoset ; + std::cout << "The standard deviation of\n" ; + std::copy( demoset , demoset + demosize , std::ostream_iterator<double>( std::cout, " " ) ) ; + std::cout << "\nis " << standard_dev( demoset , demoset + demosize ) << " !\n" ; + return 0 ; +} diff --git a/Task/Standard-deviation/C/standard-deviation-1.c b/Task/Standard-deviation/C/standard-deviation-1.c new file mode 100644 index 0000000000..3db6021a43 --- /dev/null +++ b/Task/Standard-deviation/C/standard-deviation-1.c @@ -0,0 +1,46 @@ +#include <stdio.h> +#include <stdlib.h> +#include <math.h> + +enum Action { STDDEV, MEAN, VAR, COUNT }; + +typedef struct stat_obj_struct { + double sum, sum2; + size_t num; + Action action; +} sStatObject, *StatObject; + +StatObject NewStatObject( Action action ) +{ + so = malloc(sizeof(sStatObject)); + so->sum = 0.0; + so->sum2 = 0.0; + so->num = 0; + so->action = action; + return so; +} +#define FREE_STAT_OBJECT(so) \ + free(so); so = NULL +double stat_obj_value(StatObject so, Action action) +{ + double num, mean, var, stddev; + + if (so->num == 0.0) return 0.0; + num = so->num; + if (action==COUNT) return num; + mean = so->sum/num; + if (action==MEAN) return mean; + var = so->sum2/num - mean*mean; + if (action==VAR) return var; + stddev = sqrt(var); + if (action==STDDEV) return stddev; + return 0; +} + +double stat_object_add(StatObject so, double v) +{ + so->num++; + so->sum += v; + so->sum2 += v*v; + return stat_obj_value(so->action); +} diff --git a/Task/Standard-deviation/C/standard-deviation-2.c b/Task/Standard-deviation/C/standard-deviation-2.c new file mode 100644 index 0000000000..54f1a96935 --- /dev/null +++ b/Task/Standard-deviation/C/standard-deviation-2.c @@ -0,0 +1,13 @@ +double v[] = { 2,4,4,4,5,5,7,9 }; + +int main() +{ + int i; + StatObject so = NewStatObject( STDDEV ); + + for(i=0; i < sizeof(v)/sizeof(double) ; i++) + printf("val: %lf std dev: %lf\n", v[i], stat_object_add(so, v[i])); + + FREE_STAT_OBJECT(so); + return 0; +} diff --git a/Task/Standard-deviation/Clojure/standard-deviation.clj b/Task/Standard-deviation/Clojure/standard-deviation.clj new file mode 100644 index 0000000000..baf5efb257 --- /dev/null +++ b/Task/Standard-deviation/Clojure/standard-deviation.clj @@ -0,0 +1,9 @@ +(defn std-dev [samples] + (let [n (count samples) + mean (/ (reduce + samples) n) + intermediate (map #(Math/pow (- %1 mean) 2) samples)] + (Math/sqrt + (/ (reduce + intermediate) n)))) + + +(println (std-dev [2 4 4 4 5 5 7 9])) ;;2.0 diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp new file mode 100644 index 0000000000..79385886c9 --- /dev/null +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp @@ -0,0 +1,7 @@ +(defun std-dev (samples) + (let* ((n (length samples)) + (mean (/ (reduce #'+ samples) n)) + (tmp (mapcar (lambda (x) (sqr (- x mean))) samples))) + (sqrt (/ (reduce #'+ tmp) n)))) + +(format t "~a" (std-dev '(2 4 4 4 5 5 7 9))) diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp new file mode 100644 index 0000000000..5e7339b6af --- /dev/null +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp @@ -0,0 +1,16 @@ +(defun arithmetic-average (samples) + (/ (reduce #'+ samples) + (length samples))) + +(defun standard-deviation (samples) + (let ((mean (arithmetic-average samples))) + (sqrt (* (/ 1.0d0 (length samples)) + (reduce #'+ samples + :key (lambda (x) + (expt (- x mean) 2))))))) + +(defun make-deviator () + (let ((numbers '())) + (lambda (x) + (push x numbers) + (standard-deviation numbers)))) diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp new file mode 100644 index 0000000000..a0d5837503 --- /dev/null +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-3.lisp @@ -0,0 +1,11 @@ +CL-USER> (loop with deviator = (make-deviator) + for i in '(2 4 4 4 5 5 7 9) + collect (list i (funcall deviator i))) ==> +((2 0.0d0) + (4 1.0d0) + (4 0.9428090415820634d0) + (4 0.8660254037844386d0) + (5 0.9797958971132713d0) + (5 1.0d0) + (7 1.3997084244475304d0) + (9 2.0d0)) diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp new file mode 100644 index 0000000000..760c32cfef --- /dev/null +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-4.lisp @@ -0,0 +1,8 @@ +(defun running-stddev () + (let ((sum 0) (sq 0) (n 0)) + (lambda (x) + (incf sum x) (incf sq (* x x)) (incf n) + (/ (sqrt (- (* n sq) (* sum sum))) n)))) + +(loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do + (format t "~a ~a~%" i (funcall f i))) diff --git a/Task/Standard-deviation/D/standard-deviation.d b/Task/Standard-deviation/D/standard-deviation.d new file mode 100644 index 0000000000..8b8caf294b --- /dev/null +++ b/Task/Standard-deviation/D/standard-deviation.d @@ -0,0 +1,28 @@ +import std.stdio, std.math; + +struct StdDev { + real sum = 0.0, sqSum = 0.0; + long nvalues; + + void addNumber(in real input) pure nothrow { + nvalues++; + sum += input; + sqSum += input ^^ 2; + } + + real getStdDev() const pure nothrow { + if (nvalues == 0) + return 0.0; + immutable real mean = sum / nvalues; + return sqrt(sqSum / nvalues - mean ^^ 2); + } +} + +void main() { + StdDev stdev; + + foreach (el; [2.0, 4, 4, 4, 5, 5, 7, 9]) { + stdev.addNumber(el); + writefln("%e", stdev.getStdDev()); + } +} diff --git a/Task/Standard-deviation/Delphi/standard-deviation.delphi b/Task/Standard-deviation/Delphi/standard-deviation.delphi new file mode 100644 index 0000000000..43112d63ca --- /dev/null +++ b/Task/Standard-deviation/Delphi/standard-deviation.delphi @@ -0,0 +1,11 @@ +program StdDevTest; + +{$APPTYPE CONSOLE} + +uses + Math; + +begin + Writeln(PopnStdDev([2,4,4,4,5,5,7,9])); + Readln; +end. diff --git a/Task/Standard-deviation/E/standard-deviation-1.e b/Task/Standard-deviation/E/standard-deviation-1.e new file mode 100644 index 0000000000..4061991bf4 --- /dev/null +++ b/Task/Standard-deviation/E/standard-deviation-1.e @@ -0,0 +1,24 @@ +def makeRunningStdDev() { + var sum := 0.0 + var sumSquares := 0.0 + var count := 0.0 + + def insert(v) { + sum += v + sumSquares += v ** 2 + count += 1 + } + + /** Returns the standard deviation of the inputs so far, or null if there + have been no inputs. */ + def stddev() { + if (count > 0) { + def meanSquares := sumSquares/count + def mean := sum/count + def variance := meanSquares - mean**2 + return variance.sqrt() + } + } + + return [insert, stddev] +} diff --git a/Task/Standard-deviation/E/standard-deviation-2.e b/Task/Standard-deviation/E/standard-deviation-2.e new file mode 100644 index 0000000000..722430b6b2 --- /dev/null +++ b/Task/Standard-deviation/E/standard-deviation-2.e @@ -0,0 +1,18 @@ +? def [insert, stddev] := makeRunningStdDev() +# value: <insert>, <stddev> + +? [stddev()] +# value: [null] + +? for value in [2,4,4,4,5,5,7,9] { +> insert(value) +> println(stddev()) +> } +0.0 +1.0 +0.9428090415820626 +0.8660254037844386 +0.9797958971132716 +1.0 +1.3997084244475297 +2.0 diff --git a/Task/Standard-deviation/Factor/standard-deviation.factor b/Task/Standard-deviation/Factor/standard-deviation.factor new file mode 100644 index 0000000000..54bf02a6e8 --- /dev/null +++ b/Task/Standard-deviation/Factor/standard-deviation.factor @@ -0,0 +1,22 @@ +USING: accessors io kernel math math.functions math.parser +sequences ; +IN: standard-deviator + +TUPLE: standard-deviator sum sum^2 n ; + +: <standard-deviator> ( -- standard-deviator ) + 0.0 0.0 0 standard-deviator boa ; + +: current-std ( standard-deviator -- std ) + [ [ sum^2>> ] [ n>> ] bi / ] + [ [ sum>> ] [ n>> ] bi / sq ] bi - sqrt ; + +: add-value ( value standard-deviator -- ) + [ nip [ 1 + ] change-n drop ] + [ [ + ] change-sum drop ] + [ [ [ sq ] dip + ] change-sum^2 drop ] 2tri ; + +: main ( -- ) + { 2 4 4 4 5 5 7 9 } + <standard-deviator> [ [ add-value ] curry each ] keep + current-std number>string print ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-1.fth b/Task/Standard-deviation/Forth/standard-deviation-1.fth new file mode 100644 index 0000000000..27be9b2ff5 --- /dev/null +++ b/Task/Standard-deviation/Forth/standard-deviation-1.fth @@ -0,0 +1,21 @@ +: f+! ( x addr -- ) dup f@ f+ f! ; + +: st-count ( stats -- n ) f@ ; +: st-sum ( stats -- sum ) float+ f@ ; +: st-sumsq ( stats -- sum*sum ) 2 floats + f@ ; + +: st-add ( fnum stats -- ) + 1e dup f+! float+ + fdup dup f+! float+ + fdup f* f+! ; + +: st-mean ( stats -- mean ) + dup st-sum st-count f/ ; + +: st-variance ( stats -- var ) + dup st-sumsq + dup st-mean fdup f* dup st-count f* f- + st-count f/ ; + +: st-stddev ( stats -- stddev ) + st-variance fsqrt ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-2.fth b/Task/Standard-deviation/Forth/standard-deviation-2.fth new file mode 100644 index 0000000000..644715a9bd --- /dev/null +++ b/Task/Standard-deviation/Forth/standard-deviation-2.fth @@ -0,0 +1,16 @@ +: st-count ( stats -- n ) f@ ; +: st-mean ( stats -- mean ) float+ f@ ; +: st-nvar ( stats -- n*var ) 2 floats + f@ ; + +: st-variance ( stats -- var ) dup st-nvar st-count f/ ; +: st-stddev ( stats -- stddev ) st-variance fsqrt ; + +: st-add ( x stats -- ) + 1e dup f+! \ update count + fdup dup st-mean f- fswap + ( delta x ) + fover dup st-count f/ + ( delta x delta/n ) + float+ dup f+! \ update mean + ( delta x ) + dup f@ f- f* float+ f+! ; \ update nvar diff --git a/Task/Standard-deviation/Forth/standard-deviation-3.fth b/Task/Standard-deviation/Forth/standard-deviation-3.fth new file mode 100644 index 0000000000..2da097c3bf --- /dev/null +++ b/Task/Standard-deviation/Forth/standard-deviation-3.fth @@ -0,0 +1,12 @@ +create stats 0e f, 0e f, 0e f, + +2e stats st-add +4e stats st-add +4e stats st-add +4e stats st-add +5e stats st-add +5e stats st-add +7e stats st-add +9e stats st-add + +stats st-stddev f. \ 2. diff --git a/Task/Standard-deviation/Fortran/standard-deviation-1.f b/Task/Standard-deviation/Fortran/standard-deviation-1.f new file mode 100644 index 0000000000..bd4fe63369 --- /dev/null +++ b/Task/Standard-deviation/Fortran/standard-deviation-1.f @@ -0,0 +1,61 @@ +program Test_Stddev + implicit none + + real, dimension(8) :: v = (/ 2,4,4,4,5,5,7,9 /) + integer :: i + real :: sd + + do i = 1, size(v) + sd = stat_object(v(i)) + end do + + print *, "std dev = ", sd + +contains + + recursive function stat_object(a, cmd) result(stddev) + real :: stddev + real, intent(in) :: a + character(len=*), intent(in), optional :: cmd + + real, save :: summa = 0.0, summa2 = 0.0 + integer, save :: num = 0 + + real :: m + + if ( .not. present(cmd) ) then + num = num + 1 + summa = summa + a + summa2 = summa2 + a*a + stddev = stat_object(0.0, "stddev") + else + select case(cmd) + case("stddev") + stddev = sqrt(stat_object(0.0, "variance")) + case("variance") + m = stat_object(0.0, "mean") + if ( num > 0 ) then + stddev = summa2/real(num) - m*m + else + stddev = 0.0 + end if + case("count") + stddev = real(num) + case("mean") + if ( num > 0 ) then + stddev = summa/real(num) + else + stddev = 0.0 + end if + case("reset") + summa = 0.0 + summa2 = 0.0 + num = 0 + case default + stddev = 0.0 + end select + end if + + end function stat_object + +end program Test_Stddev diff --git a/Task/Standard-deviation/Fortran/standard-deviation-2.f b/Task/Standard-deviation/Fortran/standard-deviation-2.f new file mode 100644 index 0000000000..cf558c73c8 --- /dev/null +++ b/Task/Standard-deviation/Fortran/standard-deviation-2.f @@ -0,0 +1,28 @@ +program stats + implicit none + + integer, parameter :: N = 8 + integer :: data(N) + real(8) :: mean + real(8) :: std_dev1, std_dev2 + + ! Set the data + data = [2,4,4,4,5,5,7,9] ! Strictly this is a Fortran 2003 construct + + ! Use intrinsic function 'sum' to calculate the mean + mean = sum(data)/N + + ! Method1: + ! Calculate the standard deviation directly from the definition + std_dev1 = sqrt(sum((data - mean)**2)/N) + + ! Method 2: + ! Use the alternative version that is less susceptible to rounding error + std_dev2 = sqrt(sum(data**2)/N - mean**2) + + write(*,'(a,8i2)') 'Data = ',data + write(*,'(a,f3.1)') 'Mean = ',mean + write(*,'(a,f3.1)') 'Standard deviation (method 1) = ',std_dev1 + write(*,'(a,f3.1)') 'Standard deviation (method 2) = ',std_dev2 + +end program stats diff --git a/Task/Standard-deviation/Go/standard-deviation.go b/Task/Standard-deviation/Go/standard-deviation.go new file mode 100644 index 0000000000..c45d5a09c6 --- /dev/null +++ b/Task/Standard-deviation/Go/standard-deviation.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "math" +) + +func newRsdv() func(float64) float64 { + var n, a, q float64 + return func(x float64) float64 { + n++ + a1 := a+(x-a)/n + q, a = q+(x-a)*(x-a1), a1 + return math.Sqrt(q/n) + } +} + +func main() { + r := newRsdv() + for _, x := range []float64{2,4,4,4,5,5,7,9} { + fmt.Println(r(x)) + } +} diff --git a/Task/Standard-deviation/Groovy/standard-deviation.groovy b/Task/Standard-deviation/Groovy/standard-deviation.groovy new file mode 100644 index 0000000000..04ebe4ee61 --- /dev/null +++ b/Task/Standard-deviation/Groovy/standard-deviation.groovy @@ -0,0 +1,9 @@ +def sum = 0 +def sumSq = 0 +def count = 0 +[2,4,4,4,5,5,7,9].each { + sum += it + sumSq += it*it + count++ + println "running std.dev.: ${(sumSq/count - (sum/count)**2)**0.5}" +} diff --git a/Task/Standard-deviation/Haskell/standard-deviation.hs b/Task/Standard-deviation/Haskell/standard-deviation.hs new file mode 100644 index 0000000000..1db491a4f2 --- /dev/null +++ b/Task/Standard-deviation/Haskell/standard-deviation.hs @@ -0,0 +1,21 @@ +import Data.List (genericLength) +import Data.STRef +import Control.Monad.ST + +sd :: RealFloat a => [a] -> a +sd l = sqrt $ sum (map ((^2) . subtract mean) l) / n + where n = genericLength l + mean = sum l / n + +sdAccum :: RealFloat a => ST s (a -> ST s a) +sdAccum = do + accum <- newSTRef [] + return $ \x -> do + modifySTRef accum (x:) + list <- readSTRef accum + return $ sd list + +main = mapM_ print results + where results = runST $ do + runningSD <- sdAccum + mapM runningSD [2, 4, 4, 4, 5, 5, 7, 9] diff --git a/Task/Standard-deviation/Haxe/standard-deviation.haxe b/Task/Standard-deviation/Haxe/standard-deviation.haxe new file mode 100644 index 0000000000..47fe74bf6f --- /dev/null +++ b/Task/Standard-deviation/Haxe/standard-deviation.haxe @@ -0,0 +1,23 @@ +using Lambda; + +class Main { + static function main():Void { + var nums = [2, 4, 4, 4, 5, 5, 7, 9]; + for (i in 1...nums.length+1) + Sys.println(sdev(nums.slice(0, i))); + } + + static function average<T:Float>(nums:Array<T>):Float { + return nums.fold(function(n, t) return n + t, 0) / nums.length; + } + + static function sdev<T:Float>(nums:Array<T>):Float { + var store = []; + var avg = average(nums); + for (n in nums) { + store.push((n - avg) * (n - avg)); + } + + return Math.sqrt(average(store)); + } +} diff --git a/Task/Standard-deviation/HicEst/standard-deviation.hicest b/Task/Standard-deviation/HicEst/standard-deviation.hicest new file mode 100644 index 0000000000..0db9d3d144 --- /dev/null +++ b/Task/Standard-deviation/HicEst/standard-deviation.hicest @@ -0,0 +1,16 @@ +REAL :: n=8, set(n), sum=0, sum2=0 + +set = (2,4,4,4,5,5,7,9) + +DO k = 1, n + WRITE() 'Adding ' // set(k) // 'stdev = ' // stdev(set(k)) +ENDDO + +END ! end of "main" + +FUNCTION stdev(x) + USE : sum, sum2, k + sum = sum + x + sum2 = sum2 + x*x + stdev = ( sum2/k - (sum/k)^2) ^ 0.5 + END diff --git a/Task/Standard-deviation/Icon/standard-deviation.icon b/Task/Standard-deviation/Icon/standard-deviation.icon new file mode 100644 index 0000000000..887c0a3fcf --- /dev/null +++ b/Task/Standard-deviation/Icon/standard-deviation.icon @@ -0,0 +1,22 @@ +rocedure main() + +stddev() # reset state / empty +every s := stddev(![2,4,4,4,5,5,7,9]) do + write("stddev (so far) := ",s) + +end + +procedure stddev(x) /: running standard deviation +static X,sumX,sum2X + + if /x then { # reset state + X := [] + sumX := sum2X := 0. + } + else { # accumulate + put(X,x) + sumX +:= x + sum2X +:= x^2 + return sqrt( (sum2X / *X) - (sumX / *X)^2 ) + } +end diff --git a/Task/Standard-deviation/J/standard-deviation-1.j b/Task/Standard-deviation/J/standard-deviation-1.j new file mode 100644 index 0000000000..6e8c9b0503 --- /dev/null +++ b/Task/Standard-deviation/J/standard-deviation-1.j @@ -0,0 +1,9 @@ + mean=: +/ % # + dev=: - mean + stddevP=: [: %:@mean *:@dev NB. A) 3 equivalent defs for stddevP + stddevP=: [: mean&.:*: dev NB. B) uses Under (&.:) to apply inverse of *: after mean + stddevP=: %:@(mean@:*: - *:@mean) NB. C) sqrt of ((mean of squares) - (square of mean)) + + + stddevP\ 2 4 4 4 5 5 7 9 +0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/J/standard-deviation-2.j b/Task/Standard-deviation/J/standard-deviation-2.j new file mode 100644 index 0000000000..d26e207625 --- /dev/null +++ b/Task/Standard-deviation/J/standard-deviation-2.j @@ -0,0 +1,11 @@ + of =: @: + sqrt =: %: + sum =: +/ + squares=: *: + data =: ] + mean =: sum % # + + stddevP=: sqrt of mean of squares of (data-mean) + + stddevP\ 2 4 4 4 5 5 7 9 +0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/J/standard-deviation-3.j b/Task/Standard-deviation/J/standard-deviation-3.j new file mode 100644 index 0000000000..03ff69dd00 --- /dev/null +++ b/Task/Standard-deviation/J/standard-deviation-3.j @@ -0,0 +1,3 @@ + require'stats' + (%:@:(%~<:)@:# * stddev)\ 2 4 4 4 5 5 7 9 +0 1 0.942809 0.866025 0.979796 1 1.39971 2 diff --git a/Task/Standard-deviation/Java/standard-deviation.java b/Task/Standard-deviation/Java/standard-deviation.java new file mode 100644 index 0000000000..dc26e4a768 --- /dev/null +++ b/Task/Standard-deviation/Java/standard-deviation.java @@ -0,0 +1,39 @@ +import java.util.LinkedList; +public class StdDev { + LinkedList<Double> nums; + public StdDev() { + nums = new LinkedList<Double>(); + } + public static void main(String[] args) { + double[] testData = {2,4,4,4,5,5,7,9}; + StdDev sd = new StdDev(); + + for (double x : testData) { + sd.newNum(x); + System.out.println(sd.getSD()); + } + } + + public void newNum(double num) { + nums.add(num); + } + + public double getAvg() { + if (nums.isEmpty()) return 0; + double ret = 0; + double sum = 0; + for (double num : nums) { + sum += num; + } + return sum / nums.size(); + } + + public double getSD() { + double sqDiffs = 0; + double avg = getAvg(); + for (double num : nums) { + sqDiffs += (num - avg) * (num - avg); + } + return Math.sqrt(sqDiffs / nums.size()); + } +} diff --git a/Task/Standard-deviation/JavaScript/standard-deviation.js b/Task/Standard-deviation/JavaScript/standard-deviation.js new file mode 100644 index 0000000000..cb6c72a248 --- /dev/null +++ b/Task/Standard-deviation/JavaScript/standard-deviation.js @@ -0,0 +1,20 @@ +function running_stddev() { + var n = 0; + var sum = 0.0; + var sum_sq = 0.0; + return function(num) { + n++; + sum += num; + sum_sq += num*num; + return Math.sqrt( (sum_sq / n) - Math.pow(sum / n, 2) ); + } +} + +var sd = running_stddev(); +var nums = [2,4,4,4,5,5,7,9]; +var stddev = []; +for (var i in nums) + stddev.push( sd(nums[i]) ); + +// using WSH +WScript.Echo(stddev.join(', '); diff --git a/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty b/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty new file mode 100644 index 0000000000..7a23789fb3 --- /dev/null +++ b/Task/Standard-deviation/Liberty-BASIC/standard-deviation.liberty @@ -0,0 +1,26 @@ + dim SD.storage$( 100) ' can call up to 100 versions, using ID to identify.. arrays are global. + ' holds (space-separated) number of data items so far, current sum.of.values and current sum.of.squares + + for i =1 to 8 + read x + print "New data "; x; " so S.D. now = "; using( "###.######", standard.deviation( 1, x)) + next i + + end + +function standard.deviation( ID, in) + if SD.storage$( ID) ="" then SD.storage$( ID) ="0 0 0" + num.so.far =val( word$( SD.storage$( ID), 1)) + sum.vals =val( word$( SD.storage$( ID), 2)) + sum.sqs =val( word$( SD.storage$( ID), 3)) + num.so.far =num.so.far +1 + sum.vals =sum.vals +in + sum.sqs =sum.sqs +in^2 + + ' standard deviation = square root of (the average of the squares less the square of the average) + standard.deviation =( ( sum.sqs /num.so.far) - ( sum.vals /num.so.far)^2)^0.5 + + SD.storage$( ID) =str$( num.so.far) +" " +str$( sum.vals) +" " +str$( sum.sqs) +end function + + Data 2, 4, 4, 4, 5, 5, 7, 9 diff --git a/Task/Standard-deviation/Mathematica/standard-deviation.math b/Task/Standard-deviation/Mathematica/standard-deviation.math new file mode 100644 index 0000000000..befff63f36 --- /dev/null +++ b/Task/Standard-deviation/Mathematica/standard-deviation.math @@ -0,0 +1,2 @@ +runningSTDDev[n_] := (If[Not[ValueQ[$Data]], $Data = {}]; + StandardDeviation[AppendTo[$Data, n]]) diff --git a/Task/Standard-deviation/OCaml/standard-deviation.ocaml b/Task/Standard-deviation/OCaml/standard-deviation.ocaml new file mode 100644 index 0000000000..190b68203f --- /dev/null +++ b/Task/Standard-deviation/OCaml/standard-deviation.ocaml @@ -0,0 +1,15 @@ +let sqr x = x *. x + +let stddev l = + let n, sx, sx2 = + List.fold_left + (fun (n, sx, sx2) x -> succ n, sx +. x, sx2 +. sqr x) + (0, 0., 0.) l + in + sqrt ((sx2 -. sqr sx /. float n) /. float n) + +let _ = + let l = [ 2.;4.;4.;4.;5.;5.;7.;9. ] in + Printf.printf "List: "; + List.iter (Printf.printf "%g ") l; + Printf.printf "\nStandard deviation: %g\n" (stddev l) diff --git a/Task/Standard-deviation/Objeck/standard-deviation.objeck b/Task/Standard-deviation/Objeck/standard-deviation.objeck new file mode 100644 index 0000000000..156467ce5c --- /dev/null +++ b/Task/Standard-deviation/Objeck/standard-deviation.objeck @@ -0,0 +1,35 @@ +use Structure; + +bundle Default { + class StdDev { + nums : FloatVector; + + New() { + nums := FloatVector->New(); + } + + function : Main(args : String[]) ~ Nil { + sd := StdDev->New(); + test_data := [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]; + each(i : test_data) { + sd->AddNum(test_data[i]); + sd->GetSD()->PrintLine(); + }; + } + + method : public : AddNum(num : Float) ~ Nil { + nums->AddBack(num); + } + + method : public : native : GetSD() ~ Float { + sq_diffs := 0.0; + avg := nums->Average(); + each(i : nums) { + num := nums->Get(i); + sq_diffs += (num - avg) * (num - avg); + }; + + return (sq_diffs / nums->Size())->SquareRoot(); + } + } +} diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-1.m b/Task/Standard-deviation/Objective-C/standard-deviation-1.m new file mode 100644 index 0000000000..a17d06e645 --- /dev/null +++ b/Task/Standard-deviation/Objective-C/standard-deviation-1.m @@ -0,0 +1,54 @@ +#import <Foundation/Foundation.h> + +@interface SDAccum : NSObject +{ + double sum, sum2; + unsigned int num; +} +-(double)value: (double)v; +-(unsigned int)count; +-(double)mean; +-(double)variance; +-(double)stddev; +@end + +@implementation SDAccum +-(double)value: (double)v +{ + sum += v; + sum2 += v*v; + num++; + return [self stddev]; +} +-(unsigned int)count +{ + return num; +} +-(double)mean +{ + return (num>0) ? sum/(double)num : 0.0; +} +-(double)variance +{ + double m = [self mean]; + return (num>0) ? (sum2/(double)num - m*m) : 0.0; +} +-(double)stddev +{ + return sqrt([self variance]); +} +@end + +int main() +{ + double v[] = { 2,4,4,4,5,5,7,9 }; + + SDAccum *sdacc = [SDAccum new]; + + for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) + printf("adding %f\tstddev = %f\n", v[i], [sdacc value: v[i]]); + + [sdacc release]; + + return 0; +} diff --git a/Task/Standard-deviation/Objective-C/standard-deviation-2.m b/Task/Standard-deviation/Objective-C/standard-deviation-2.m new file mode 100644 index 0000000000..7f0b192d2a --- /dev/null +++ b/Task/Standard-deviation/Objective-C/standard-deviation-2.m @@ -0,0 +1,30 @@ +#import <Foundation/Foundation.h> + +typedef double (^Func)(double); // a block that takes a double and returns a double + +Func sdCreator() { + __block int n = 0; + __block double sum = 0; + __block double sum2 = 0; + return [[^(double x) { + sum += x; + sum2 += x*x; + n++; + return sqrt(sum2/n - sum*sum/n/n); + } copy] autorelease]; +} + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + + double v[] = { 2,4,4,4,5,5,7,9 }; + + Func sdacc = sdCreator(); + + for(int i=0; i < sizeof(v)/sizeof(*v) ; i++) + printf("adding %f\tstddev = %f\n", v[i], sdacc(v[i])); + + [pool release]; + return 0; +} diff --git a/Task/Standard-deviation/PARI-GP/standard-deviation.pari b/Task/Standard-deviation/PARI-GP/standard-deviation.pari new file mode 100644 index 0000000000..f48d01f05f --- /dev/null +++ b/Task/Standard-deviation/PARI-GP/standard-deviation.pari @@ -0,0 +1,19 @@ +newpoint(x)={ + myT=x; + myS=0; + myN=1; + [myT,myS]/myN +}; +addpoint(x)={ + myT+=x; + myN++; + myS+=(myN*x-myT)^2/myN/(myN-1); + [myT,myS]/myN +}; +addpoints(v)={ + print(newpoint(v[1])); + for(i=2,#v,print(addpoint(v[i]))); + print("Mean: ",myT/myN); + print("Standard deviation: ",sqrt(myS/myN)) +}; +addpoints([2,4,4,4,5,5,7,9]) diff --git a/Task/Standard-deviation/PL-I/standard-deviation.pli b/Task/Standard-deviation/PL-I/standard-deviation.pli new file mode 100644 index 0000000000..9fe3ce0216 --- /dev/null +++ b/Task/Standard-deviation/PL-I/standard-deviation.pli @@ -0,0 +1,23 @@ +declare A(200) float; +declare ap fixed binary; +declare i fixed binary; + +ap = 0; +do i = 1 to 10; + ap = ap + 1; + get list ( A(ap) ); + put skip list ( std_dev (a, ap) ); +end; + +std_dev: procedure (A, ap) returns (float); + declare A(*) float, ap fixed binary nonassignable; + declare i fixed binary; + declare B(ap) float, average float; + + do i = 1 to ap; + B(i) = A(i); + end; + average = sum(A) /ap; + + return ( sqrt (sum(B**2)/ap - average**2) ); +end std_dev; diff --git a/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 b/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 new file mode 100644 index 0000000000..a46491d833 --- /dev/null +++ b/Task/Standard-deviation/Perl-6/standard-deviation-1.pl6 @@ -0,0 +1,12 @@ +sub sd (@a) { + my $mean = @a R/ [+] @a; + sqrt @a R/ [+] map (* - $mean)**2, @a; +} +  +sub sdaccum { + my @a; + return { push @a, $^x; sd @a; }; +} +  +my &f = sdaccum; +say f $_ for 2, 4, 4, 4, 5, 5, 7, 9; diff --git a/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 b/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 new file mode 100644 index 0000000000..d94252b6d0 --- /dev/null +++ b/Task/Standard-deviation/Perl-6/standard-deviation-2.pl6 @@ -0,0 +1,9 @@ +# remember that <(x-<x>)²> = <x²> - <x>² +sub stddev($x) { + sqrt + (.[2] += $x**2) / ++.[0] - + ((.[1] += $x) / .[0])**2 + given state @; +} + +say stddev $_ for <2 4 4 4 5 5 7 9>; diff --git a/Task/Standard-deviation/Perl/standard-deviation-1.pl b/Task/Standard-deviation/Perl/standard-deviation-1.pl new file mode 100644 index 0000000000..c93b958631 --- /dev/null +++ b/Task/Standard-deviation/Perl/standard-deviation-1.pl @@ -0,0 +1,37 @@ +{ + package SDAccum; + sub new { + my $class = shift; + my $self = {}; + $self->{sum} = 0.0; + $self->{sum2} = 0.0; + $self->{num} = 0; + bless $self, $class; + return $self; + } + sub count { + my $self = shift; + return $self->{num}; + } + sub mean { + my $self = shift; + return ($self->{num}>0) ? $self->{sum}/$self->{num} : 0.0; + } + sub variance { + my $self = shift; + my $m = $self->mean; + return ($self->{num}>0) ? $self->{sum2}/$self->{num} - $m * $m : 0.0; + } + sub stddev { + my $self = shift; + return sqrt($self->variance); + } + sub value { + my $self = shift; + my $v = shift; + $self->{sum} += $v; + $self->{sum2} += $v * $v; + $self->{num}++; + return $self->stddev; + } +} diff --git a/Task/Standard-deviation/Perl/standard-deviation-2.pl b/Task/Standard-deviation/Perl/standard-deviation-2.pl new file mode 100644 index 0000000000..80301927ec --- /dev/null +++ b/Task/Standard-deviation/Perl/standard-deviation-2.pl @@ -0,0 +1,7 @@ +my $sdacc = SDAccum->new; +my $sd; + +foreach my $v ( 2,4,4,4,5,5,7,9 ) { + $sd = $sdacc->value($v); +} +print "std dev = $sd\n"; diff --git a/Task/Standard-deviation/Perl/standard-deviation-3.pl b/Task/Standard-deviation/Perl/standard-deviation-3.pl new file mode 100644 index 0000000000..26a5694795 --- /dev/null +++ b/Task/Standard-deviation/Perl/standard-deviation-3.pl @@ -0,0 +1,14 @@ +# <(x - <x>)²> = <x²> - <x>² +{ + my $num, $sum, $sum2; + sub stddev { + my $x = shift; + $num++; + return sqrt( + ($sum2 += $x**2) / $num - + (($sum += $x) / $num)**2 + ); + } +} + +print stddev($_), "\n" for qw(2 4 4 4 5 5 7 9); diff --git a/Task/Standard-deviation/PicoLisp/standard-deviation.l b/Task/Standard-deviation/PicoLisp/standard-deviation.l new file mode 100644 index 0000000000..16d9b927b2 --- /dev/null +++ b/Task/Standard-deviation/PicoLisp/standard-deviation.l @@ -0,0 +1,18 @@ +(scl 2) + +(de stdDev () + (curry ((Data)) (N) + (push 'Data N) + (let (Len (length Data) M (*/ (apply + Data) Len)) + (sqrt + (*/ + (sum + '((N) (*/ (- N M) (- N M) 1.0)) + Data ) + 1.0 + Len ) + T ) ) ) ) + +(let Fun (stdDev) + (for N (2.0 4.0 4.0 4.0 5.0 5.0 7.0 9.0) + (prinl (format N *Scl) " -> " (format (Fun N) *Scl)) ) ) diff --git a/Task/Standard-deviation/PowerShell/standard-deviation.psh b/Task/Standard-deviation/PowerShell/standard-deviation.psh new file mode 100644 index 0000000000..b95d6fffc2 --- /dev/null +++ b/Task/Standard-deviation/PowerShell/standard-deviation.psh @@ -0,0 +1,13 @@ +function Get-StandardDeviation { + begin { + $avg = 0 + $nums = @() + } + process { + $nums += $_ + $avg = ($nums | Measure-Object -Average).Average + $sum = 0; + $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) } + [Math]::Sqrt($sum / $nums.Length) + } +} diff --git a/Task/Standard-deviation/PureBasic/standard-deviation.purebasic b/Task/Standard-deviation/PureBasic/standard-deviation.purebasic new file mode 100644 index 0000000000..756b97c185 --- /dev/null +++ b/Task/Standard-deviation/PureBasic/standard-deviation.purebasic @@ -0,0 +1,29 @@ +;Define our Standard deviation function +Declare.d Standard_deviation(x) + +; Main program +If OpenConsole() + Define i, x + Restore MyList + For i=1 To 8 + Read.i x + PrintN(StrD(Standard_deviation(x))) + Next i + Print(#CRLF$+"Press ENTER to exit"): Input() +EndIf + +;Calculation procedure, with memory +Procedure.d Standard_deviation(In) + Static in_summa, antal + Static in_kvadrater.q + in_summa+in + in_kvadrater+in*in + antal+1 + ProcedureReturn Pow((in_kvadrater/antal)-Pow(in_summa/antal,2),0.50) +EndProcedure + +;data section +DataSection +MyList: + Data.i 2,4,4,4,5,5,7,9 +EndDataSection diff --git a/Task/Standard-deviation/Python/standard-deviation-1.py b/Task/Standard-deviation/Python/standard-deviation-1.py new file mode 100644 index 0000000000..be108e4de3 --- /dev/null +++ b/Task/Standard-deviation/Python/standard-deviation-1.py @@ -0,0 +1,22 @@ +>>> from math import sqrt +>>> def sd(x): + sd.sum += x + sd.sum2 += x*x + sd.n += 1.0 + sum, sum2, n = sd.sum, sd.sum2, sd.n + return sqrt(sum2/n - sum*sum/n/n) + +>>> sd.sum = sd.sum2 = sd.n = 0 +>>> for value in (2,4,4,4,5,5,7,9): + print (value, sd(value)) + + +(2, 0.0) +(4, 1.0) +(4, 0.94280904158206258) +(4, 0.8660254037844386) +(5, 0.97979589711327075) +(5, 1.0) +(7, 1.3997084244475311) +(9, 2.0) +>>> diff --git a/Task/Standard-deviation/Python/standard-deviation-2.py b/Task/Standard-deviation/Python/standard-deviation-2.py new file mode 100644 index 0000000000..b8a8fb9a28 --- /dev/null +++ b/Task/Standard-deviation/Python/standard-deviation-2.py @@ -0,0 +1,13 @@ +>>> class SD(object): # Plain () for python 3.x + def __init__(self): + self.sum, self.sum2, self.n = (0,0,0) + def sd(self, x): + self.sum += x + self.sum2 += x*x + self.n += 1.0 + sum, sum2, n = self.sum, self.sum2, self.n + return sqrt(sum2/n - sum*sum/n/n) + +>>> sd_inst = SD() +>>> for value in (2,4,4,4,5,5,7,9): + print (value, sd_inst.sd(value)) diff --git a/Task/Standard-deviation/Python/standard-deviation-3.py b/Task/Standard-deviation/Python/standard-deviation-3.py new file mode 100644 index 0000000000..0812c9b16c --- /dev/null +++ b/Task/Standard-deviation/Python/standard-deviation-3.py @@ -0,0 +1,25 @@ +>>> from math import sqrt +>>> def sdcreator(): + sum = sum2 = n = 0 + def sd(x): + nonlocal sum, sum2, n + + sum += x + sum2 += x*x + n += 1.0 + return sqrt(sum2/n - sum*sum/n/n) + return sd + +>>> sd = sdcreator() +>>> for value in (2,4,4,4,5,5,7,9): + print (value, sd(value)) + + +2 0.0 +4 1.0 +4 0.942809041582 +4 0.866025403784 +5 0.979795897113 +5 1.0 +7 1.39970842445 +9 2.0 diff --git a/Task/Standard-deviation/Python/standard-deviation-4.py b/Task/Standard-deviation/Python/standard-deviation-4.py new file mode 100644 index 0000000000..ac0708af6b --- /dev/null +++ b/Task/Standard-deviation/Python/standard-deviation-4.py @@ -0,0 +1,24 @@ +>>> from math import sqrt +>>> def sdcreator(): + sum = sum2 = n = 0 + while True: + x = yield sqrt(sum2/n - sum*sum/n/n) if n else None + + sum += x + sum2 += x*x + n += 1.0 + +>>> sd = sdcreator() +>>> sd.send(None) +>>> for value in (2,4,4,4,5,5,7,9): + print (value, sd.send(value)) + + +2 0.0 +4 1.0 +4 0.942809041582 +4 0.866025403784 +5 0.979795897113 +5 1.0 +7 1.39970842445 +9 2.0 diff --git a/Task/Standard-deviation/R/standard-deviation-1.r b/Task/Standard-deviation/R/standard-deviation-1.r new file mode 100644 index 0000000000..050ff0c212 --- /dev/null +++ b/Task/Standard-deviation/R/standard-deviation-1.r @@ -0,0 +1,11 @@ +#The built-in standard deviation function applies the Bessel correction. To reverse this, we can apply an uncorrection. +#If na.rm is true, missing data points (NA values) are removed. + reverseBesselCorrection <- function(x, na.rm=FALSE) + { + if(na.rm) x <- x[!is.na(x)] + len <- length(x) + if(len < 2) stop("2 or more data points required") + sqrt((len-1)/len) + } + testdata <- c(2,4,4,4,5,5,7,9) + reverseBesselCorrection(testdata)*sd(testdata) #2 diff --git a/Task/Standard-deviation/R/standard-deviation-2.r b/Task/Standard-deviation/R/standard-deviation-2.r new file mode 100644 index 0000000000..5d0229f9b4 --- /dev/null +++ b/Task/Standard-deviation/R/standard-deviation-2.r @@ -0,0 +1,11 @@ +#Again, if na.rm is true, missing data points (NA values) are removed. + uncorrectedsd <- function(x, na.rm=FALSE) + { + len <- length(x) + if(len < 2) stop("2 or more data points required") + mu <- mean(x, na.rm=na.rm) + ssq <- sum((x - mu)^2, na.rm=na.rm) + usd <- sqrt(ssq/len) + usd + } + uncorrectedsd(testdata) #2 diff --git a/Task/Standard-deviation/REXX/standard-deviation.rexx b/Task/Standard-deviation/REXX/standard-deviation.rexx new file mode 100644 index 0000000000..69da3a4d3a --- /dev/null +++ b/Task/Standard-deviation/REXX/standard-deviation.rexx @@ -0,0 +1,17 @@ +/*REXX program to find the standard deviation of a given set of numbers.*/ +parse arg # /*let the user specify numbers. */ +if #='' then #=2 4 4 4 5 5 7 9 /*None given? Then use default.*/ +w=words(#); s=0; ss=0 /*define: #items, a couple sums. */ + + do j=1 for w; _=word(#,j); s=s+_; ss=ss+_*_ + say ' item' right(j,length(w))":" right(_,4), + ' average=' left(s/j,12), + ' standard deviation=' left(sqrt( ss/j - (s/j)**2 ),15) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure;parse arg x; if x=0 then return 0; d=digits(); numeric digits 11; g=.sqrtGuess() + 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 +.sqrtGuess: 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/Standard-deviation/Ruby/standard-deviation-1.rb b/Task/Standard-deviation/Ruby/standard-deviation-1.rb new file mode 100644 index 0000000000..7a25c6e948 --- /dev/null +++ b/Task/Standard-deviation/Ruby/standard-deviation-1.rb @@ -0,0 +1,25 @@ +class StdDevAccumulator + def initialize + @n, @sum, @sumofsquares = 0, 0.0, 0.0 + end + + def <<(num) + # return self to make this possible: sd << 1 << 2 << 3 # => 0.816496580927726 + @n += 1 + @sum += num + @sumofsquares += num**2 + self + end + + def stddev + Math.sqrt( (@sumofsquares / @n) - (@sum / @n)**2 ) + end + + def to_s + stddev.to_s + end +end + +sd = StdDevAccumulator.new +i = 0 +[2,4,4,4,5,5,7,9].each {|n| puts "adding #{n}: stddev of #{i+=1} samples is #{sd << n}" } diff --git a/Task/Standard-deviation/Ruby/standard-deviation-2.rb b/Task/Standard-deviation/Ruby/standard-deviation-2.rb new file mode 100644 index 0000000000..a465fe5a73 --- /dev/null +++ b/Task/Standard-deviation/Ruby/standard-deviation-2.rb @@ -0,0 +1,12 @@ +def sdaccum + n, sum, sum2 = 0, 0.0, 0.0 + lambda do |num| + n += 1 + sum += num + sum2 += num**2 + Math.sqrt( (sum2 / n) - (sum / n)**2 ) + end +end + +sd = sdaccum +[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "} diff --git a/Task/Standard-deviation/Run-BASIC/standard-deviation.run b/Task/Standard-deviation/Run-BASIC/standard-deviation.run new file mode 100644 index 0000000000..629cea3d1f --- /dev/null +++ b/Task/Standard-deviation/Run-BASIC/standard-deviation.run @@ -0,0 +1,16 @@ +dim sdSave$(100) 'can call up to 100 versions + 'holds (space-separated) number of data , sum of values and sum of squares +sd$ = "2,4,4,4,5,5,7,9" + +for num = 1 to 8 + stdData = val(word$(sd$,num,",")) + sumVal = sumVal + stdData + sumSqs = sumSqs + stdData^2 + + ' standard deviation = square root of (the average of the squares less the square of the average) + standDev =((sumSqs / num) - (sumVal /num) ^ 2) ^ 0.5 + + sdSave$(num) = str$(num);" ";str$(sumVal);" ";str$(sumSqs) + print num;" value in = ";stdData; " Stand Dev = "; using("###.######", standDev) + +next num diff --git a/Task/Standard-deviation/Scheme/standard-deviation.ss b/Task/Standard-deviation/Scheme/standard-deviation.ss new file mode 100644 index 0000000000..66aef5aafb --- /dev/null +++ b/Task/Standard-deviation/Scheme/standard-deviation.ss @@ -0,0 +1,3 @@ +(define ((running-stddev . nums) num) + (set! nums (cons num nums)) + (sqrt (- (/ (apply + (map (lambda (i) (* i i)) nums)) (length nums)) (expt (/ (apply + nums) (length nums)) 2)))) diff --git a/Task/Standard-deviation/Smalltalk/standard-deviation-1.st b/Task/Standard-deviation/Smalltalk/standard-deviation-1.st new file mode 100644 index 0000000000..1cd4281431 --- /dev/null +++ b/Task/Standard-deviation/Smalltalk/standard-deviation-1.st @@ -0,0 +1,20 @@ +Object subclass: SDAccum [ + |sum sum2 num| + SDAccum class >> new [ |o| + o := super basicNew. + ^ o init. + ] + init [ sum := 0. sum2 := 0. num := 0 ] + value: aValue [ + sum := sum + aValue. + sum2 := sum2 + ( aValue * aValue ). + num := num + 1. + ^ self stddev + ] + count [ ^ num ] + mean [ num>0 ifTrue: [^ sum / num] ifFalse: [ ^ 0.0 ] ] + variance [ |m| m := self mean. + num>0 ifTrue: [^ (sum2/num) - (m*m) ] ifFalse: [ ^ 0.0 ] + ] + stddev [ ^ (self variance) sqrt ] +]. diff --git a/Task/Standard-deviation/Smalltalk/standard-deviation-2.st b/Task/Standard-deviation/Smalltalk/standard-deviation-2.st new file mode 100644 index 0000000000..7d85f70b18 --- /dev/null +++ b/Task/Standard-deviation/Smalltalk/standard-deviation-2.st @@ -0,0 +1,5 @@ +|sdacc sd| +sdacc := SDAccum new. + +#( 2 4 4 4 5 5 7 9 ) do: [ :v | sd := sdacc value: v ]. +('std dev = %1' % { sd }) displayNl. diff --git a/Task/Standard-deviation/Tcl/standard-deviation-1.tcl b/Task/Standard-deviation/Tcl/standard-deviation-1.tcl new file mode 100644 index 0000000000..d09f7b464e --- /dev/null +++ b/Task/Standard-deviation/Tcl/standard-deviation-1.tcl @@ -0,0 +1,33 @@ +oo::class create SDAccum { + variable sum sum2 num + constructor {} { + set sum 0.0 + set sum2 0.0 + set num 0 + } + method value {x} { + set sum2 [expr {$sum2 + $x**2}] + set sum [expr {$sum + $x}] + incr num + return [my stddev] + } + method count {} { + return $num + } + method mean {} { + expr {$sum / $num} + } + method variance {} { + expr {$sum2/$num - [my mean]**2} + } + method stddev {} { + expr {sqrt([my variance])} + } +} + +# Demonstration +set sdacc [SDAccum new] +foreach val {2 4 4 4 5 5 7 9} { + set sd [$sdacc value $val] +} +puts "the standard deviation is: $sd" diff --git a/Task/Standard-deviation/Tcl/standard-deviation-2.tcl b/Task/Standard-deviation/Tcl/standard-deviation-2.tcl new file mode 100644 index 0000000000..c64e787067 --- /dev/null +++ b/Task/Standard-deviation/Tcl/standard-deviation-2.tcl @@ -0,0 +1,20 @@ +# Make a coroutine out of a lambda application +coroutine sd apply {{} { + set sum 0.0 + set sum2 0.0 + set sd {} + # Keep processing argument values until told not to... + while {[set val [yield $sd]] ne "stop"} { + incr n + set sum [expr {$sum + $val}] + set sum2 [expr {$sum2 + $val**2}] + set sd [expr {sqrt($sum2/$n - ($sum/$n)**2)}] + } +}} + +# Demonstration +foreach val {2 4 4 4 5 5 7 9} { + set sd [sd $val] +} +sd stop +puts "the standard deviation is: $sd" diff --git a/Task/Standard-deviation/XPL0/standard-deviation.xpl0 b/Task/Standard-deviation/XPL0/standard-deviation.xpl0 new file mode 100644 index 0000000000..5b9d237da4 --- /dev/null +++ b/Task/Standard-deviation/XPL0/standard-deviation.xpl0 @@ -0,0 +1,13 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +int A, I; +real N, S, S2; +[A:= [2,4,4,4,5,5,7,9]; +N:= 0.0; S:= 0.0; S2:= 0.0; +for I:= 0 to 8-1 do + [N:= N + 1.0; + S:= S + float(A(I)); + S2:= S2 + float(sq(A(I))); + RlOut(0, sqrt((S2/N) - sq(S/N))); + ]; +CrLf(0); +] diff --git a/Task/Start-from-a-main-routine/0DESCRIPTION b/Task/Start-from-a-main-routine/0DESCRIPTION new file mode 100644 index 0000000000..c2558af192 --- /dev/null +++ b/Task/Start-from-a-main-routine/0DESCRIPTION @@ -0,0 +1,6 @@ +{{omit from|BBC BASIC}} +Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run. + +The task is to demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. + +Languages that always run from main() can be omitted from this task. diff --git a/Task/Start-from-a-main-routine/AWK/start-from-a-main-routine.awk b/Task/Start-from-a-main-routine/AWK/start-from-a-main-routine.awk new file mode 100644 index 0000000000..476b831614 --- /dev/null +++ b/Task/Start-from-a-main-routine/AWK/start-from-a-main-routine.awk @@ -0,0 +1,4 @@ +BEGIN { + # This is our main startup procedure + print "Hello World!" +} diff --git a/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada b/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada new file mode 100644 index 0000000000..b515644a80 --- /dev/null +++ b/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada @@ -0,0 +1,5 @@ +with Ada.Text_IO; +procedure Foo is +begin + Ada.Text_IO.Put_Line("Bar"); +end Foo; diff --git a/Task/Start-from-a-main-routine/Gambas/start-from-a-main-routine.gambas b/Task/Start-from-a-main-routine/Gambas/start-from-a-main-routine.gambas new file mode 100644 index 0000000000..1f5e8a48a0 --- /dev/null +++ b/Task/Start-from-a-main-routine/Gambas/start-from-a-main-routine.gambas @@ -0,0 +1,3 @@ +PUBLIC SUB Main() + ' This is the start of the program +END diff --git a/Task/Start-from-a-main-routine/Perl-6/start-from-a-main-routine.pl6 b/Task/Start-from-a-main-routine/Perl-6/start-from-a-main-routine.pl6 new file mode 100644 index 0000000000..6cf66a8f10 --- /dev/null +++ b/Task/Start-from-a-main-routine/Perl-6/start-from-a-main-routine.pl6 @@ -0,0 +1,4 @@ +BEGIN {...} # as soon as parsed +CHECK {...} # end of compile time +INIT {...} # beginning of run time +END {...} # end of run time diff --git a/Task/Start-from-a-main-routine/Perl/start-from-a-main-routine.pl b/Task/Start-from-a-main-routine/Perl/start-from-a-main-routine.pl new file mode 100644 index 0000000000..6cf66a8f10 --- /dev/null +++ b/Task/Start-from-a-main-routine/Perl/start-from-a-main-routine.pl @@ -0,0 +1,4 @@ +BEGIN {...} # as soon as parsed +CHECK {...} # end of compile time +INIT {...} # beginning of run time +END {...} # end of run time diff --git a/Task/Start-from-a-main-routine/REXX/start-from-a-main-routine.rexx b/Task/Start-from-a-main-routine/REXX/start-from-a-main-routine.rexx new file mode 100644 index 0000000000..8332bed974 --- /dev/null +++ b/Task/Start-from-a-main-routine/REXX/start-from-a-main-routine.rexx @@ -0,0 +1,9 @@ +/*REXX*/ +address 'XEDIT' + . + . + . +[XEDIT commands here.] + . + . + . diff --git a/Task/Start-from-a-main-routine/Racket/start-from-a-main-routine.rkt b/Task/Start-from-a-main-routine/Racket/start-from-a-main-routine.rkt new file mode 100644 index 0000000000..77c2f756c7 --- /dev/null +++ b/Task/Start-from-a-main-routine/Racket/start-from-a-main-routine.rkt @@ -0,0 +1,4 @@ +#lang racket +(provide main) +(define (main) + (displayln "Hello World!")) diff --git a/Task/Start-from-a-main-routine/Visual-Basic/start-from-a-main-routine.vb b/Task/Start-from-a-main-routine/Visual-Basic/start-from-a-main-routine.vb new file mode 100644 index 0000000000..39623d063d --- /dev/null +++ b/Task/Start-from-a-main-routine/Visual-Basic/start-from-a-main-routine.vb @@ -0,0 +1,3 @@ +SUB Main() + ' This is the start of the program +END diff --git a/Task/Start-from-a-main-routine/ZX-Spectrum-Basic/start-from-a-main-routine.zx b/Task/Start-from-a-main-routine/ZX-Spectrum-Basic/start-from-a-main-routine.zx new file mode 100644 index 0000000000..ba0557ce4a --- /dev/null +++ b/Task/Start-from-a-main-routine/ZX-Spectrum-Basic/start-from-a-main-routine.zx @@ -0,0 +1 @@ +SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500 diff --git a/Task/Stem-and-leaf-plot/0DESCRIPTION b/Task/Stem-and-leaf-plot/0DESCRIPTION new file mode 100644 index 0000000000..03476ccdd3 --- /dev/null +++ b/Task/Stem-and-leaf-plot/0DESCRIPTION @@ -0,0 +1,9 @@ +Create a well-formatted [[wp:Stem-and-leaf_plot|stem-and-leaf plot]] from the following data set, where the leaves are the last digits: + +<blockquote style="font-family: monospace; white-space: pre-wrap;"><small>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</small></blockquote> <!-- The data set generation parameters: humps at 0 and 80 of width 80, 60 elements, slopes 3 and 6. --> + +The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. + +If possible, the output should not be a bitmap image. <tt>Monospaced plain text</tt> is acceptable, but do better if you can. It may be a window, i.e. not a file. + +'''Note:''' If you wish to try multiple data sets, you might try [[Stem-and-leaf plot/Data generator|this generator]]. diff --git a/Task/Stem-and-leaf-plot/1META.yaml b/Task/Stem-and-leaf-plot/1META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Stem-and-leaf-plot/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Stem-and-leaf-plot/ACL2/stem-and-leaf-plot.acl2 b/Task/Stem-and-leaf-plot/ACL2/stem-and-leaf-plot.acl2 new file mode 100644 index 0000000000..0bb98c5931 --- /dev/null +++ b/Task/Stem-and-leaf-plot/ACL2/stem-and-leaf-plot.acl2 @@ -0,0 +1,41 @@ +(defun insert (x xs) + (cond ((endp xs) (list x)) + ((> x (first xs)) + (cons (first xs) (insert x (rest xs)))) + (t (cons x xs)))) + +(defun isort (xs) + (if (endp xs) + nil + (insert (first xs) (isort (rest xs))))) + +(defun stem-and-leaf-bins (xs bin curr) + (cond ((endp xs) (list curr)) + ((= (floor (first xs) 10) bin) + (stem-and-leaf-bins (rest xs) + bin + (cons (first xs) curr))) + (t (cons curr + (stem-and-leaf-bins (rest xs) + (floor (first xs) 10) + (list (first xs))))))) + +(defun print-bin (bin) + (if (endp bin) + nil + (progn$ (cw " ~x0" (mod (first bin) 10)) + (print-bin (rest bin))))) + +(defun stem-and-leaf-plot-r (bins) + (if (or (endp bins) (endp (first bins))) + nil + (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) + (print-bin (first bins)) + (cw "~%") + (stem-and-leaf-plot-r (rest bins))))) + +(defun stem-and-leaf-plot (xs) + (stem-and-leaf-plot-r + (reverse (stem-and-leaf-bins (reverse (isort xs)) + 0 + nil)))) diff --git a/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.ada b/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.ada new file mode 100644 index 0000000000..257817b3a5 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.ada @@ -0,0 +1,40 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Gnat.Heap_Sort_G; +procedure stemleaf is + data : array(Natural Range <>) of Integer := ( + 0,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); -- Position 0 is used for storage during sorting, initialized as 0 + + procedure Move (from, to : in Natural) is + begin data(to) := data(from); + end Move; + + function Cmp (p1, p2 : Natural) return Boolean is + begin return data(p1)<data(p2); + end Cmp; + + package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); + min,max,p,stemw: Integer; +begin + Sorty.Sort(data'Last); + min := data(1); + max := data(data'Last); + stemw := Integer'Image(max)'Length; + p := 1; + for stem in min/10..max/10 loop + put(stem,Width=>stemw); put(" |"); + Leaf_Loop: + while data(p)/10=stem loop + put(" "); put(data(p) mod 10,Width=>1); + exit Leaf_loop when p=data'Last; + p := p+1; + end loop Leaf_Loop; + new_line; + end loop; +end stemleaf; diff --git a/Task/Stem-and-leaf-plot/AutoHotkey/stem-and-leaf-plot.ahk b/Task/Stem-and-leaf-plot/AutoHotkey/stem-and-leaf-plot.ahk new file mode 100644 index 0000000000..48312ee08b --- /dev/null +++ b/Task/Stem-and-leaf-plot/AutoHotkey/stem-and-leaf-plot.ahk @@ -0,0 +1,39 @@ +SetWorkingDir %A_ScriptDir% +#NoEnv +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" + ; This loop removes the double/multiple spaces encountered when copying+pasting the given data set: +While (Instr(Data," ")) + StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All +; Sort the data numerically using a space as the separator: +Sort, Data,ND%A_Space% + +OldStem := 0 +; Parse the data using a space as the separator, storing each new string as A_LoopField and running the loop once per string: +Loop, parse, Data,%A_Space% +{ + NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1) ; AutoHotkey doesn't have a Left() function, so this does the trick. + If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) + { + While(OldStem+1<>NewStem) ; account for all stems which don't appear (in this example, 8) but are between the lowest and highest stems + OldStem++,ToPrint .= "`n" PadStem(oldStem) + ToPrint .= "`n" PadStem(NewStem) + OldStem := NewStem + } + Else If ( StrLen(A_LoopField)=1 and !FirstStem) + ToPrint .= PadStem(0),FirstStem := true + ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " " ; No Right() function either, so this returns the last character of A_LoopField (the string curently used by the parsing loop) +} + ; Delete the old stem and leaf file (if any), write our new contents to it, then show it: +FileDelete Stem and leaf.txt +FileAppend %ToPrint%, Stem and Leaf.txt +Run Stem and leaf.txt +return + +PadStem(Stem){ + Spaces = 0 + While ( 3 - StrLen(Stem) <> Spaces ) ; If the stems are more than 2 digits long, increase the number 3 to one more than the stem length. + ToReturn .= " ",Spaces++ + ToReturn .= Stem + ToReturn .= " | " + Return ToReturn +} diff --git a/Task/Stem-and-leaf-plot/BBC-BASIC/stem-and-leaf-plot.bbc b/Task/Stem-and-leaf-plot/BBC-BASIC/stem-and-leaf-plot.bbc new file mode 100644 index 0000000000..246fc2895d --- /dev/null +++ b/Task/Stem-and-leaf-plot/BBC-BASIC/stem-and-leaf-plot.bbc @@ -0,0 +1,37 @@ + INSTALL @lib$+"SORTLIB" + Sort% = FN_sortinit(0, 0) + + DIM Data%(120) + 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 + + PROCleafplot(Data%(), DIM(Data%(),1) + 1) + END + + DEF PROCleafplot(x%(), n%) + LOCAL @%, C%, i%, j%, d% + @% = 2 + + C% = n% + CALL Sort%, x%(0) + + i% = x%(0) DIV 10 - 1 + FOR j% = 0 TO n% - 1 + d% = x%(j%) DIV 10 + WHILE d% > i% + i% += 1 + IF j% PRINT + PRINT i% " |" ; + ENDWHILE + PRINT x%(j%) MOD 10 ; + NEXT + PRINT + ENDPROC diff --git a/Task/Stem-and-leaf-plot/C++/stem-and-leaf-plot.cpp b/Task/Stem-and-leaf-plot/C++/stem-and-leaf-plot.cpp new file mode 100644 index 0000000000..3ef512d5e0 --- /dev/null +++ b/Task/Stem-and-leaf-plot/C++/stem-and-leaf-plot.cpp @@ -0,0 +1,44 @@ +#include <algorithm> +#include <iomanip> +#include <iostream> +#include <vector> + +const int dataset[] = { + 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 +}; +const int datasize = sizeof(dataset) / sizeof(dataset[0]); + +int main() +{ + typedef std::pair<int,int> StemLeaf; + std::vector<StemLeaf> stemplot; + + for (int i = 0; i < datasize; ++i) + { + stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); + } + + std::sort(stemplot.begin(), stemplot.end()); // order stem/leaf pairs + + int lo = stemplot.front().first; // minimum stem value + int hi = stemplot.back().first; // maximum stem value + + for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) + { + std::cout << std::setw(2) << lo << " |"; // print stem + + // while (there are more stems) and (stem is equal to lo) + for ( ; itr != stemplot.end() && itr->first == lo; ++itr) + { + std::cout << " " << itr->second; // print leaf + } + + std::cout << std::endl; + } +} diff --git a/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-1.c b/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-1.c new file mode 100644 index 0000000000..c162b5eb03 --- /dev/null +++ b/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-1.c @@ -0,0 +1,39 @@ +#include <stdio.h> +#include <stdlib.h> + +int icmp(const void *a, const void *b) +{ + return *(int*)a < *(int*)b ? -1 : *(int*)a > *(int*)b; +} + +void leaf_plot(int *x, int len) +{ + int i, j, d; + + qsort(x, len, sizeof(int), icmp); + + i = x[0] / 10 - 1; + for (j = 0; j < len; j++) { + d = x[j] / 10; + while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); + printf(" %d", x[j] % 10); + } +} + +int main() +{ + 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 }; + + leaf_plot(data, sizeof(data)/sizeof(data[0])); + + return 0; +} diff --git a/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-2.c b/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-2.c new file mode 100644 index 0000000000..4d7f4f85a8 --- /dev/null +++ b/Task/Stem-and-leaf-plot/C/stem-and-leaf-plot-2.c @@ -0,0 +1,15 @@ + 0 | 7 7 + 1 | 2 3 8 8 + 2 | 3 5 7 7 7 7 7 7 8 8 9 9 + 3 | 0 1 1 1 1 2 3 4 5 6 7 7 7 8 9 + 4 | 0 0 1 2 2 2 2 3 3 3 4 4 4 5 6 7 8 8 + 5 | 2 3 7 8 8 + 6 | 1 3 8 + 7 | 1 + 8 | + 9 | 6 9 + 10 | 4 5 5 5 5 6 7 9 9 9 + 11 | 1 3 3 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 8 9 9 + 12 | 0 0 1 1 2 2 3 4 4 4 5 5 5 6 7 7 7 7 8 8 + 13 | 1 2 3 9 + 14 | 1 6 diff --git a/Task/Stem-and-leaf-plot/D/stem-and-leaf-plot.d b/Task/Stem-and-leaf-plot/D/stem-and-leaf-plot.d new file mode 100644 index 0000000000..9572425132 --- /dev/null +++ b/Task/Stem-and-leaf-plot/D/stem-and-leaf-plot.d @@ -0,0 +1,18 @@ +import std.stdio, std.algorithm; + +void main() { + enum 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]; + + int[][int] histo; + foreach (x; data) + histo[x / 10] ~= x % 10; + immutable loHi = reduce!(min, max)(data); + foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) + writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); +} diff --git a/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.euphoria b/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.euphoria new file mode 100644 index 0000000000..8d7f670418 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.euphoria @@ -0,0 +1,28 @@ +include sort.e + +procedure leaf_plot(sequence s) + sequence stem + s = sort(s) + stem = repeat({},floor(s[$]/10)+1) + for i = 1 to length(s) do + stem[floor(s[i]/10)+1] &= remainder(s[i],10) + end for + for i = 1 to length(stem) do + printf(1, "%3d | ", i-1) + for j = 1 to length(stem[i]) do + printf(1, "%d ", stem[i][j]) + end for + puts(1,'\n') + end for +end procedure + +constant 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 } + +leaf_plot(data) diff --git a/Task/Stem-and-leaf-plot/Forth/stem-and-leaf-plot.fth b/Task/Stem-and-leaf-plot/Forth/stem-and-leaf-plot.fth new file mode 100644 index 0000000000..ad6f76a1ca --- /dev/null +++ b/Task/Stem-and-leaf-plot/Forth/stem-and-leaf-plot.fth @@ -0,0 +1,35 @@ +create 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 , +here constant data-end + +: sort ( end start -- ) + over cell - swap do + dup i cell+ do + i @ j @ < if + i @ j @ i ! j ! + then + cell +loop + cell +loop drop ; + +: plot + data-end data sort + data + data-end cell - @ 10 / 1+ + data @ 10 / + do + cr i 2 u.r ." | " + begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then + loop + drop ; + +plot diff --git a/Task/Stem-and-leaf-plot/Go/stem-and-leaf-plot.go b/Task/Stem-and-leaf-plot/Go/stem-and-leaf-plot.go new file mode 100644 index 0000000000..8558fe3416 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Go/stem-and-leaf-plot.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "sort" + "strconv" + "strings" +) + +var data = `12 127 28 42` //...omitted...127 31 116 146` + +func main() { + // load data into map + m := make(map[int][]string) + for _, s := range strings.Fields(data) { + if len(s) == 1 { + m[0] = append(m[0], s) + } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { + m[i] = append(m[i], s[len(s)-1:]) + } else { + panic("non numeric data") + } + } + // sort stem + s := make([]int, len(m)) + var i int + for k := range m { + s[i] = k + i++ + } + sort.Ints(s) + // print + for k := s[0]; ; k++ { + v := m[k] + sort.Strings(v) + fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) + if k == s[len(s)-1] { + break + } + } +} diff --git a/Task/Stem-and-leaf-plot/Haskell/stem-and-leaf-plot.hs b/Task/Stem-and-leaf-plot/Haskell/stem-and-leaf-plot.hs new file mode 100644 index 0000000000..a463641600 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Haskell/stem-and-leaf-plot.hs @@ -0,0 +1,23 @@ +import Data.List +import Control.Arrow +import Control.Monad + +nlsRaw = "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" + +nls :: [Int] +nls = map read $ words nlsRaw + +groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) +justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' + +task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) + $ groupWith fst $ stems ++ map (second return) stemLeaf + where stemLeaf = map (`quotRem` 10) ds + stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf + showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b + fb = length $ show $ maximum $ map abs ds diff --git a/Task/Stem-and-leaf-plot/HicEst/stem-and-leaf-plot.hicest b/Task/Stem-and-leaf-plot/HicEst/stem-and-leaf-plot.hicest new file mode 100644 index 0000000000..dfd6feecb9 --- /dev/null +++ b/Task/Stem-and-leaf-plot/HicEst/stem-and-leaf-plot.hicest @@ -0,0 +1,28 @@ +REAL :: workspace(1000), base=16 + +DLG(CHeckbox=bitmap, NameEdit=base, DNum, MIn=1, MAx=16) ! 1 <= stem base <= 16 +READ(ClipBoard, ItemS=nData) workspace ! get raw data + +ALIAS(workspace,1, dataset,nData, stems,nData) +SORT(Vector=dataset, Sorted=dataset) +stems = (dataset - MOD(dataset,base)) / base +dataset = dataset - base*stems +max_stem = MAX(stems) + +IF( bitmap ) AXIS() +printed = 0 +DO stem = 0, max_stem + last = INDEX(stems, stem, 4) ! option 4: search backward + IF( last > printed ) THEN + nLeaves = last - printed + IF(bitmap) THEN + LINE(PenUp=1,W=8, x=0, y=stem, x=nLeaves, y=stem) + ELSE + ALIAS(dataset,printed+1, leaves,nLeaves) + WRITE(Format="i3, ':', 100Z2") stem, leaves + ENDIF + printed = printed + nLeaves + ELSE + WRITE(Format="i3, ':'") stem + ENDIF +ENDDO diff --git a/Task/Stem-and-leaf-plot/Icon/stem-and-leaf-plot.icon b/Task/Stem-and-leaf-plot/Icon/stem-and-leaf-plot.icon new file mode 100644 index 0000000000..96611fdc3e --- /dev/null +++ b/Task/Stem-and-leaf-plot/Icon/stem-and-leaf-plot.icon @@ -0,0 +1,12 @@ +procedure main(A) + prune := integer(\A[1]) | 10 # Boundary between leaf and stem + every put(data := [], integer(!&input)) + writes(right(oldStem := 0,5)," |") + every item := !sort(data) do { + leaf := item % prune + stem := item / prune + while (oldStem < stem) do writes("\n",right(oldStem +:= 1, 5)," |") + writes(" ",right(leaf,*prune-1,"0")) + } + write() +end diff --git a/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-1.j b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-1.j new file mode 100644 index 0000000000..23c3934942 --- /dev/null +++ b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-1.j @@ -0,0 +1,7 @@ +stem =: <.@(%&10) +leaf =: 10&| +stemleaf =: (stem@{. ; leaf)/.~ stem +expandStems =: <./ ([ + i.@>:@-~) >./ +expandLeaves=: (expandStems e. ])@[ #inv ] + +showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~ diff --git a/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-2.j b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-2.j new file mode 100644 index 0000000000..f2a2c1b593 --- /dev/null +++ b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-2.j @@ -0,0 +1,13 @@ +stemleafX=: monad define + leaves=. 10 | y + stems=. y <.@:% 10 + leaves=. stems </. leaves NB. group leaves by stem + (<"0 ~.stems),.leaves +) + +showStemLeafX=: monad define + 'stems leaves'=. (>@{. ; <@{:)@|: stemleafX /:~ y + xstems=. (<./ ([ + i.@>:@-~ ) >./) stems NB. stems including those with no leaves + xleaves=. (xstems e. stems) #inv leaves NB. expand leaves to match xstems + (": ,.xstems) ; ":&> xleaves +) diff --git a/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-3.j b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-3.j new file mode 100644 index 0000000000..6aba983666 --- /dev/null +++ b/Task/Stem-and-leaf-plot/J/stem-and-leaf-plot-3.j @@ -0,0 +1,39 @@ + nls =: ; <@(_&".);._2 noun define +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 +) + + stemleaf nls NB. display has been abbreviated +┌──┬─────────────────────────────────────────────┐ +│1 │2 8 3 8 │ +├──┼─────────────────────────────────────────────┤ +│12│7 4 7 5 3 2 8 1 5 7 1 6 4 8 2 4 0 5 0 7 │ +├──┼─────────────────────────────────────────────┤ +│2 │8 9 3 7 9 5 7 7 7 7 7 8 │ +... + + showStemLeaf nls +┌──┬─────────────────────────────────────────────┐ +│ 0│7 7 │ +│ 1│2 3 8 8 │ +│ 2│3 5 7 7 7 7 7 7 8 8 9 9 │ +│ 3│0 1 1 1 1 2 3 4 5 6 7 7 7 8 9 │ +│ 4│0 0 1 2 2 2 2 3 3 3 4 4 4 5 6 7 8 8 │ +│ 5│2 3 7 8 8 │ +│ 6│1 3 8 │ +│ 7│1 │ +│ 8│ │ +│ 9│6 9 │ +│10│4 5 5 5 5 6 7 9 9 9 │ +│11│1 3 3 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 8 9 9│ +│12│0 0 1 1 2 2 3 4 4 4 5 5 5 6 7 7 7 7 8 8 │ +│13│1 2 3 9 │ +│14│1 6 │ +└──┴─────────────────────────────────────────────┘ + + (showStemLeaf -: showStemLeafX) nls NB. both solutions give same result +1 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 new file mode 100644 index 0000000000..9c3b000902 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot.java @@ -0,0 +1,57 @@ +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<Integer, List<Integer>> createPlot(int... data){ + Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); + 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<Integer> list = new LinkedList<Integer>(); + 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<Integer> list = new LinkedList<Integer>(); + plot.put(i, list); + } + } + } + return plot; + } + + public static void printPlot(Map<Integer, List<Integer>> plot){ + for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ + Collections.sort(line.getValue()); + System.out.println(line.getKey() + " | " + line.getValue()); + } + } + + public static void main(String[] args){ + Map<Integer, List<Integer>> plot = createPlot(data); + printPlot(plot); + } +} diff --git a/Task/Stem-and-leaf-plot/JavaScript/stem-and-leaf-plot.js b/Task/Stem-and-leaf-plot/JavaScript/stem-and-leaf-plot.js new file mode 100644 index 0000000000..55137a1524 --- /dev/null +++ b/Task/Stem-and-leaf-plot/JavaScript/stem-and-leaf-plot.js @@ -0,0 +1,77 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<head> +<meta http-equiv="Content-Type" content="text/html;charset=utf-8" > +<title>stem and leaf plot + + + + + +
+ + + + + diff --git a/Task/Stem-and-leaf-plot/Lua/stem-and-leaf-plot.lua b/Task/Stem-and-leaf-plot/Lua/stem-and-leaf-plot.lua new file mode 100644 index 0000000000..f8877b8a15 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Lua/stem-and-leaf-plot.lua @@ -0,0 +1,24 @@ +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 + } + +table.sort( data ) + +min, max = data[1], data[#data] + +p = 1 +for stem = math.floor(min/10), math.floor(max/10) do + io.write( string.format( "%2d | ", stem ) ) + + while data[p] ~= nil and math.floor( data[p]/10 ) == stem do + io.write( string.format( "%2d ", data[p] % 10 ) ) + p = p + 1 + end + + print "" +end diff --git a/Task/Stem-and-leaf-plot/MATLAB/stem-and-leaf-plot.m b/Task/Stem-and-leaf-plot/MATLAB/stem-and-leaf-plot.m new file mode 100644 index 0000000000..4b5a55de9b --- /dev/null +++ b/Task/Stem-and-leaf-plot/MATLAB/stem-and-leaf-plot.m @@ -0,0 +1,23 @@ +function stem_and_leaf_plot(x,stem_unit,leaf_unit) + if nargin < 2, stem_unit = 10; end; + if nargin < 3, + leaf_unit = 1; + else + x = leaf_unit*round(x/leaf_unit); + end; + + stem = floor(x/stem_unit); + leaf = mod(x,stem_unit); + + for k = min(stem):max(stem) + printf('\n%d |',k) + printf(' %d' ,sort(leaf(k==stem))) + end; + printf('\nkey:6|3=63\n'); + printf('leaf unit: %.1f\n',leaf_unit); + printf('stem unit: %.1f\n',stem_unit); +end; + +x = [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]; + +stem_and_leaf_plot(x); diff --git a/Task/Stem-and-leaf-plot/Mathematica/stem-and-leaf-plot.math b/Task/Stem-and-leaf-plot/Mathematica/stem-and-leaf-plot.math new file mode 100644 index 0000000000..bec829259c --- /dev/null +++ b/Task/Stem-and-leaf-plot/Mathematica/stem-and-leaf-plot.math @@ -0,0 +1,6 @@ +len[n_] := RealDigits[n][[2]]; padding = len[Max@ Quotient[inputdata, 10]]; + +For[i = Min@ Quotient[inputdata, 10],i <= Max@ Quotient[inputdata, 10], i++, + (Print[i, If[(padding - len[i]) > 0, (padding - len[i])*" " <> " |", " |"] , + StringJoin[(" " <> #) & /@ Map[ToString, #]]])&@ + Select[{Quotient[#, 10], Mod[#, 10]} & /@ Sort[inputdata],Part[#, 1] == i &][[;; , 2]]] diff --git a/Task/Stem-and-leaf-plot/Maxima/stem-and-leaf-plot.maxima b/Task/Stem-and-leaf-plot/Maxima/stem-and-leaf-plot.maxima new file mode 100644 index 0000000000..7cef3a73ce --- /dev/null +++ b/Task/Stem-and-leaf-plot/Maxima/stem-and-leaf-plot.maxima @@ -0,0 +1,25 @@ +load(descrptive)$ + +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]$ + +stemplot(data); + 0|77 + 1|2388 + 2|357777778899 + 3|011112345677789 + 4|001222233344456788 + 5|23788 + 6|138 + 7|1 + 9|69 +10|4555567999 +11|13333444555666677778899 +12|00112234445556777788 +13|1239 +14|16 diff --git a/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-1.ocaml b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-1.ocaml new file mode 100644 index 0000000000..66d3464842 --- /dev/null +++ b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-1.ocaml @@ -0,0 +1,9 @@ +let unique li = + let rec aux acc = function + | [] -> (List.rev acc) + | x::xs -> + if List.mem x acc + then aux acc xs + else aux (x::acc) xs + in + aux [] li diff --git a/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml new file mode 100644 index 0000000000..76b463dca8 --- /dev/null +++ b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml @@ -0,0 +1,28 @@ +let 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 ] + +let data = + List.map (fun d -> + let a = d / 10 in + let b = d mod 10 in + (a, b) + ) data + +let keys = + List.sort compare (unique (List.map fst data)) + +let () = + List.iter (fun key -> + Printf.printf " %2d |" key; + let vs = List.filter (fun (a,_) -> a = key) data in + let vs = List.sort compare (List.map snd vs) in + List.iter (Printf.printf " %d") vs; + print_newline() + ) keys diff --git a/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-3.ocaml b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-3.ocaml new file mode 100644 index 0000000000..92f93f33ea --- /dev/null +++ b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-3.ocaml @@ -0,0 +1,18 @@ +let () = + print_endline "\ +\\documentclass{report} +\\usepackage{fullpage} +\\begin{document} + \\begin{tabular}{ r | *{120}{c} }"; + + List.iter (fun key -> + Printf.printf " %d" key; + let vs = List.filter (fun (a,_) -> a = key) data in + let vs = List.sort compare (List.map snd vs) in + List.iter (Printf.printf " & %d") vs; + print_endline " \\\\" + ) keys; + + print_endline "\ + \\end{tabular} +\\end{document}" diff --git a/Task/Stem-and-leaf-plot/Perl-6/stem-and-leaf-plot.pl6 b/Task/Stem-and-leaf-plot/Perl-6/stem-and-leaf-plot.pl6 new file mode 100644 index 0000000000..517318dc0c --- /dev/null +++ b/Task/Stem-and-leaf-plot/Perl-6/stem-and-leaf-plot.pl6 @@ -0,0 +1,24 @@ +my @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 +>».Int.sort; + +my Int $stem_unit = 10; +my %h = @data.classify: * div $stem_unit; + +my $range = [minmax] %h.keys».Int; +my $stem_format = "%{$range.from.chars max $range.to.chars}d"; + +for $range.list -> $stem { + my $leafs = %h{$stem} // []; + say $stem.fmt($stem_format), ' | ', ~$leafs.map: * % $stem_unit; +} diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl new file mode 100644 index 0000000000..0e1e2a7b76 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-1.pl @@ -0,0 +1,43 @@ +#!/usr/bin/perl -w + +my @data = sort {$a <=> $b} qw( 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 ); + +# FIXME: This should count the maximum number of leaves in any one stem; +# instead it takes the total number of data items, which is usually +# a massive overestimate. +my $columns = @data; + +print <<"EOT"; +\\documentclass{report} +\\usepackage{fullpage} +\\begin{document} + \\begin{tabular}{ r | *{$columns}{c} } +EOT + +my $laststem = undef; + +for my $value (@data) { + my $stem = int($value / 10); + my $leaf = $value % 10; + while (not defined $laststem or $stem > $laststem) { + if (not defined $laststem) { + $laststem = $stem - 1; + } else { + print " \\\\\n"; + } + $laststem++; + print " $laststem"; + } + printf " & $leaf"; +} +print <<'EOT'; + + \end{tabular} +\end{document} +EOT diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl new file mode 100644 index 0000000000..d15135f545 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-2.pl @@ -0,0 +1,12 @@ +\documentclass{report} +\usepackage{fullpage} +\begin{document} + \begin{tabular}{ r | *{120}{c} } + 0 & 7 & 7 \\ + 1 & 2 & 3 & 8 & 8 \\ + 2 & 3 & 5 & 7 & 7 & 7 & 7 & 7 & 7 & 8 & 8 & 9 & 9 \\ + ... + 13 & 1 & 2 & 3 & 9 \\ + 14 & 1 + \end{tabular} +\end{document} diff --git a/Task/Stem-and-leaf-plot/PicoLisp/stem-and-leaf-plot.l b/Task/Stem-and-leaf-plot/PicoLisp/stem-and-leaf-plot.l new file mode 100644 index 0000000000..115c1bba25 --- /dev/null +++ b/Task/Stem-and-leaf-plot/PicoLisp/stem-and-leaf-plot.l @@ -0,0 +1,19 @@ +(de *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 ) + +(let L + (group + (mapcar + '((N) + (cons + (or (format (head -1 (setq N (chop N)))) 0) + (last N) ) ) + (sort *Data) ) ) + (for I (range (caar L) (car (last L))) + (prinl (align 3 I) " | " (glue " " (cdr (assoc I L)))) ) ) diff --git a/Task/Stem-and-leaf-plot/PureBasic/stem-and-leaf-plot.purebasic b/Task/Stem-and-leaf-plot/PureBasic/stem-and-leaf-plot.purebasic new file mode 100644 index 0000000000..9fbc33ce53 --- /dev/null +++ b/Task/Stem-and-leaf-plot/PureBasic/stem-and-leaf-plot.purebasic @@ -0,0 +1,43 @@ +If OpenConsole() + Dim MyList(120) + Define i, j, StemMax, StemMin + Restore MyData ; Get the address of MyData, e.g. the data to print as a Stem-and-leaf plot + For a=0 To 120 + Read.i MyList(a) ; Read the data into the used Array + If MyList(a)>StemMax + StemMax=MyList(a) ; Find the largest Stem layer at the same time + EndIf + If MyList(a)=10*(i+1) ; Break current print if a new Stem layer is reached + Break + Else + Print(Str(MyList(j)%10)+" ") ; Print all Leafs on this current Stem layer + EndIf + Next j + PrintN("") + Next i + + Print(#CRLF$+#CRLF$+"Press ENTER to exit") + Input() + CloseConsole() +EndIf + +DataSection +MyData: + Data.i 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115 + Data.i 105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125 + Data.i 32, 61, 37,127, 29,113,121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116 + Data.i 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117,116,111, 40,119, 47,105 + Data.i 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 +EndDataSection diff --git a/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-1.py b/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-1.py new file mode 100644 index 0000000000..7cd29d544d --- /dev/null +++ b/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-1.py @@ -0,0 +1,39 @@ +from collections import namedtuple +from pprint import pprint as pp +from math import floor + +Stem = namedtuple('Stem', 'data, leafdigits') + +data0 = Stem((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), + 1.0) + +def stemplot(stem): + d = [] + interval = int(10**int(stem.leafdigits)) + for data in sorted(stem.data): + data = int(floor(data)) + stm, lf = divmod(data,interval) + d.append( (int(stm), int(lf)) ) + stems, leafs = list(zip(*d)) + stemwidth = max(len(str(x)) for x in stems) + leafwidth = max(len(str(x)) for x in leafs) + laststem, out = min(stems) - 1, [] + for s,l in d: + while laststem < s: + laststem += 1 + out.append('\n%*i |' % ( stemwidth, laststem)) + out.append(' %0*i' % (leafwidth, l)) + out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' + % (interval, interval)) + return ''.join(out) + +if __name__ == '__main__': + print( stemplot(data0) ) diff --git a/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-2.py b/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-2.py new file mode 100644 index 0000000000..e48205a84b --- /dev/null +++ b/Task/Stem-and-leaf-plot/Python/stem-and-leaf-plot-2.py @@ -0,0 +1,19 @@ +from collections import OrderedDict, Counter + +x= [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] + +def stemleaf(x): + d = OrderedDict((((str(v)[:-1],' ')[v<10], Counter()) for v in sorted(x))) + for s in ((str(v),' '+str(v))[v<10] for v in x) : d[s[:-1]][s[-1]]+=1 + m=max(len(s) for s in d) + for k in d: + print('%s%s | %s'%(' '*(m-len(k)),k,' '.join(sorted(d[k].elements())))) + +stemleaf(x) diff --git a/Task/Stem-and-leaf-plot/R/stem-and-leaf-plot.r b/Task/Stem-and-leaf-plot/R/stem-and-leaf-plot.r new file mode 100644 index 0000000000..07e0434735 --- /dev/null +++ b/Task/Stem-and-leaf-plot/R/stem-and-leaf-plot.r @@ -0,0 +1,9 @@ +x <- c(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) + +stem(x) diff --git a/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx new file mode 100644 index 0000000000..6742c2c399 --- /dev/null +++ b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx @@ -0,0 +1,26 @@ +/*REXX program displays a stem-and-leaf plot of real numbers [-, 0, +].*/ +min= /*This program handles negatives */ +max= /* ··· and decimal fractions. */ +parse arg data; if data='' then data=, /*Not specified? Then use default*/ + 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 +#.= + do j=1 for words(data); _=format(word(data,j),,0)/1 /*normalize*/ + stem=left(_, max(1, length(_)-1)) /*extract the stem from the num. */ + if length(_)==1 then stem=0 /*handle single-digit leaves. */ + if min=='' then min=stem; if max=='' then max=stem + min=min(min, stem*sign(_)); max=max(max, stem*sign(_)) + leaf=right(_,1) /*pick off the leaf from the num.*/ + #.stem.leaf=#.stem.leaf leaf /*construct a sorted stem-&-leaf.*/ + end /*j*/ + +w=max(length(min),length(max)) /*width: used to align the stems.*/ + + do k=min to max; _=; do m=0 for 10; _=_ #.k.m; end /*m*/ + say right(k,w) '│' space(_) + end /*k*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot.rb b/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot.rb new file mode 100644 index 0000000000..0e20b6d053 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Ruby/stem-and-leaf-plot.rb @@ -0,0 +1,114 @@ +class StemLeafPlot + def initialize(data, options = {}) + opts = {:leaf_digits => 1}.merge(options) + @leaf_digits = opts[:leaf_digits] + @multiplier = 10 ** @leaf_digits + @plot = generate_structure(data) + end + + private + + def generate_structure(data) + plot = Hash.new {|h,k| h[k] = []} + data.sort.each do |value| + stem, leaf = parse(value) + plot[stem] << leaf + end + plot + end + + def parse(value) + stem, leaf = value.abs.divmod(@multiplier) + [Stem.get(stem, value), leaf.round] + end + + public + + def print + stem_width = Math.log10(@plot.keys.max_by {|s| s.value}.value).ceil + 1 + Stem.get_range(@plot.keys).each do |stem| + leaves = @plot[stem].inject("") {|str,leaf| str << "%*d " % [@leaf_digits, leaf]} + puts "%*s | %s" % [stem_width, stem, leaves] + end + + puts "key: 5|4=#{5 * @multiplier + 4}" + puts "leaf unit: 1" + puts "stem unit: #@multiplier" + end +end + +class Stem + @@cache = {} + + def self.get(stem_value, datum) + sign = datum < 0 ? :- : :+ + cache(stem_value, sign) + end + + private + + def self.cache(value, sign) + if @@cache[[value, sign]].nil? + @@cache[[value, sign]] = self.new(value, sign) + end + @@cache[[value, sign]] + end + + def initialize(value, sign) + @value = value + @sign = sign + end + + public + + attr_accessor :value, :sign + + def negative? + @sign == :- + end + + def <=>(other) + if self.negative? + if other.negative? + other.value <=> self.value + else + -1 + end + else + if other.negative? + 1 + else + self.value <=> other.value + end + end + end + + def to_s + "%s%d" % [(self.negative? ? '-' : ' '), @value] + end + + def self.get_range(array_of_stems) + min, max = array_of_stems.minmax + if min.negative? + if max.negative? + min.value.downto(max.value).collect {|n| cache(n, :-)} + else + min.value.downto(0).collect {|n| cache(n, :-)} + 0.upto(max.value).collect {|n| cache(n, :+)} + end + else + min.value.upto(max.value).collect {|n| cache(n, :+)} + end + end + +end + +data = DATA.read.split.map {|s| Float(s)} +StemLeafPlot.new(data).print + +__END__ +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 diff --git a/Task/Stem-and-leaf-plot/Scala/stem-and-leaf-plot.scala b/Task/Stem-and-leaf-plot/Scala/stem-and-leaf-plot.scala new file mode 100644 index 0000000000..b7f4888b99 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Scala/stem-and-leaf-plot.scala @@ -0,0 +1,7 @@ +def stemAndLeaf(numbers: List[Int]) = { + val lineFormat = "%" + (numbers map (_.toString.length) max) + "d | %s" + val map = numbers groupBy (_ / 10) + for (stem <- numbers.min / 10 to numbers.max / 10) { + println(lineFormat format (stem, map.getOrElse(stem, Nil) map (_ % 10) sortBy identity mkString " ")) + } +} diff --git a/Task/Stem-and-leaf-plot/Seed7/stem-and-leaf-plot.seed7 b/Task/Stem-and-leaf-plot/Seed7/stem-and-leaf-plot.seed7 new file mode 100644 index 0000000000..e6149cb50b --- /dev/null +++ b/Task/Stem-and-leaf-plot/Seed7/stem-and-leaf-plot.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + +const proc: leafPlot (in var array integer: x) is func + local + var integer: i is 0; + var integer: j is 0; + var integer: d is 0; + begin + x := sort(x); + i := x[1] div 10 - 1; + for key j range x do + d := x[j] div 10; + while d > i do + if j <> 1 then + writeln; + end if; + incr(i); + write(i lpad 3 <& " |"); + end while; + write(" " <& x[j] rem 10); + end for; + writeln; + end func; + +const proc: main is func + local + const array integer: data is [] ( + 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); + begin + leafPlot(data); + end func; diff --git a/Task/Stem-and-leaf-plot/TUSCRIPT/stem-and-leaf-plot.tuscript b/Task/Stem-and-leaf-plot/TUSCRIPT/stem-and-leaf-plot.tuscript new file mode 100644 index 0000000000..f8c9ac7fbd --- /dev/null +++ b/Task/Stem-and-leaf-plot/TUSCRIPT/stem-and-leaf-plot.tuscript @@ -0,0 +1,29 @@ +$$ MODE TUSCRIPT +digits=* +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 +DATA 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 +DATA 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 +DATA 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 + +digits=SPLIT (digits,": :"), digitssort=DIGIT_SORT (digits) + +SECTION format +formatstem=CENTER (currentstem,5," ") +PRINT formatstem, leaves +ENDSECTION + +leaves="",currentstem=0 +LOOP d=digitssort +leaf=mod(d,10),stem=d/10 +IF (stem!=currentstem) THEN + DO format + IF (stem!=nextstem) THEN + currentstem=nextstem=nextstem+1,leaves="" + DO format + ENDIF +leaves=leaf, currentstem=stem +ELSE + leaves=APPEND (leaves,leaf), nextstem=stem+1 +ENDIF +ENDLOOP +DO format diff --git a/Task/Stem-and-leaf-plot/Tcl/stem-and-leaf-plot.tcl b/Task/Stem-and-leaf-plot/Tcl/stem-and-leaf-plot.tcl new file mode 100644 index 0000000000..6c12e96ce0 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Tcl/stem-and-leaf-plot.tcl @@ -0,0 +1,60 @@ +package require Tcl 8.5 + +# How to process a single value, adding it to the table mapping stems to +# leaves. +proc addSLValue {tblName value {splitFactor 10}} { + upvar 1 $tblName tbl + # Extract the stem and leaf + if {$value < 0} { + set value [expr {round(-$value)}] + set stem -[expr {$value / $splitFactor}] + } else { + set value [expr {round($value)}] + set stem [expr {$value / $splitFactor}] + } + if {![info exist tbl]} { + dict set tbl min $stem + } + dict set tbl max $stem + set leaf [expr {$value % $splitFactor}] + dict lappend tbl $stem $leaf +} + +# How to do the actual output of the stem-and-leaf table, given that we have +# already done the splitting into stems and leaves. +proc printSLTable {tblName} { + upvar 1 $tblName tbl + # Get the range of stems + set min [dict get $tbl min] + set max [dict get $tbl max] + # Work out how much width the stems take so everything lines up + set l [expr {max([string length $min], [string length $max])}] + # Print out the table + for {set i $min} {$i <= $max} {incr i} { + if {![dict exist $tbl $i]} { + puts [format " %*d |" $l $i] + } else { + puts [format " %*d | %s" $l $i [dict get $tbl $i]] + } + } +} + +# Assemble the parts into a full stem-and-leaf table printer. +proc printStemLeaf {dataList {splitFactor 10}} { + foreach value [lsort -real $dataList] { + addSLValue tbl $value $splitFactor + } + printSLTable tbl +} + +# Demo code +set 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 +} +printStemLeaf $data diff --git a/Task/Stem-and-leaf-plot/Ursala/stem-and-leaf-plot.ursala b/Task/Stem-and-leaf-plot/Ursala/stem-and-leaf-plot.ursala new file mode 100644 index 0000000000..7819dbadc6 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Ursala/stem-and-leaf-plot.ursala @@ -0,0 +1,22 @@ +#import std +#import nat + +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> + +stemleaf_plot = + +^|T(~&,' | '--)*+ -+ + ^p(pad` @hS; * ==` ~-rlT,mat` *tS)@hSS+ (%nP*)^|*H/~& ^lrNCT/iota ~&, + ^(*+ ^C/~&+ -:0!,~&zl)+ ^|(~&,nleq-<)*+ nleq-<&l@lK2hlPrSXS+ * division\10+- + +#show+ + +main = stemleaf_plot data diff --git a/Task/String-case/0DESCRIPTION b/Task/String-case/0DESCRIPTION new file mode 100644 index 0000000000..5c17e5da50 --- /dev/null +++ b/Task/String-case/0DESCRIPTION @@ -0,0 +1 @@ +Take the string "alphaBETA", and demonstrate how to convert it to UPPER-CASE and lower-case. Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Show any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language. diff --git a/Task/String-case/1META.yaml b/Task/String-case/1META.yaml new file mode 100644 index 0000000000..ae625822b7 --- /dev/null +++ b/Task/String-case/1META.yaml @@ -0,0 +1,2 @@ +--- +note: String manipulation diff --git a/Task/String-case/4D/string-case.4d b/Task/String-case/4D/string-case.4d new file mode 100644 index 0000000000..ee1b30c2ff --- /dev/null +++ b/Task/String-case/4D/string-case.4d @@ -0,0 +1,3 @@ +$string:="alphaBETA" +$uppercase:=Uppercase($string) +$lowercase:=Lowercase($string) diff --git a/Task/String-case/6502-Assembly/string-case.6502 b/Task/String-case/6502-Assembly/string-case.6502 new file mode 100644 index 0000000000..293777a338 --- /dev/null +++ b/Task/String-case/6502-Assembly/string-case.6502 @@ -0,0 +1,101 @@ + .lf case6502.lst + .cr 6502 + .tf case6502.obj,ap1 +;------------------------------------------------------ +; String Case for the 6502 by barrym95838 2013.04.07 +; Thanks to sbprojects.com for a very nice assembler! +; The target for this assembly is an Apple II with +; mixed-case output capabilities. Apple IIs like to +; work in '+128' ascii, so this version leaves bit 7 +; alone, and can be used with either flavor. +; 6502s work best with data structures < 256 bytes; +; several instructions would have to be added to +; properly deal with longer strings. +; Tested and verified on AppleWin 1.20.0.0 +;------------------------------------------------------ +; Constant Section +; +StrPtr = $6 0-page temp pointer (2 bytes) +Low = $8 0-page temp low bound +High = $9 0-page temp high bound +CharOut = $fded Specific to the Apple II +BigA = "A" 'A' for normal ascii +BigZ = "Z" 'Z' " " " +LittleA = "a" 'a' " " " +LittleZ = "z" 'z' " " " +;====================================================== + .or $0f00 +;------------------------------------------------------ +; The main program +; +main ldx #sTest Point to the test string + lda /sTest + jsr puts print it to stdout + jsr toUpper convert to UPPER-case + jsr puts print it + jsr toLower convert to lower-case + jmp puts print it and return to caller +;------------------------------------------------------ +toUpper pha save A + lda #LittleA + sta Low set up the flip range + lda #LittleZ + bne toLow2 return via toLower's tail +;------------------------------------------------------ +toLower pha save A + lda #BigA + sta Low set up the flip range + lda #BigZ +toLow2 sta High + pla restore A + ; return via fall-thru to flip +;------------------------------------------------------ +; Given a NUL-terminated string at A:X, flip the case +; of any chars in the range [Low..High], inclusive; +; only works on the first 256 bytes of a long string +; Uses: StrPtr, Low, High +; Preserves: A, X +; Trashes: Y +; +flip stx StrPtr init string pointer + sta StrPtr+1 + ldy #0 + pha save A +flip2 lda (StrPtr),y get string char + beq flip5 done if NUL + cmp Low + bcc flip4 if Low <= char <= High + cmp High + beq flip3 + bcs flip4 +flip3 eor #$20 then flip the case + sta (StrPtr),y +flip4 iny point to next char + bne flip2 loop up to 255 times +flip5 pla restore A + rts return +;------------------------------------------------------ +; Output NUL-terminated string @ A:X; strings longer +; than 256 bytes are truncated there +; Uses: StrPtr +; Preserves: A, X +; Trashes: Y +; +puts stx StrPtr init string pointer + sta StrPtr+1 + ldy #0 + pha save A +puts2 lda (StrPtr),y get string char + beq puts3 done if NUL + jsr CharOut output the char + iny point to next char + bne puts2 loop up to 255 times +puts3 pla restore A + rts return +;------------------------------------------------------ +; Test String (in '+128' ascii, Apple II style) +; +sTest .as -"Alpha, BETA, gamma, {[(<123@_>)]}." + .az -#13 +;------------------------------------------------------ + .en diff --git a/Task/String-case/ALGOL-68/string-case.alg b/Task/String-case/ALGOL-68/string-case.alg new file mode 100644 index 0000000000..eacf559cdc --- /dev/null +++ b/Task/String-case/ALGOL-68/string-case.alg @@ -0,0 +1,31 @@ +#!/usr/local/bin/a68g --script # + +# Demonstrate toupper and tolower for standard ALGOL 68 +strings. This does not work for multibyte character sets. # + +INT l2u = ABS "A" - ABS "a"; + +PROC to upper = (CHAR c)CHAR: + (ABS "a" > ABS c | c |: ABS c > ABS "z" | c | REPR ( ABS c + l2u )); + +PROC to lower = (CHAR c)CHAR: + (ABS "A" > ABS c | c |: ABS c > ABS "Z" | c | REPR ( ABS c - l2u )); + +# Operators can be defined in ALGOL 68 # +OP (CHAR)CHAR TOLOWER = to lower, TOUPPER = to upper; + +# upper-cases s in place # +PROC string to upper = (REF STRING s)VOID: + FOR i FROM LWB s TO UPB s DO s[i] := to upper(s[i]) OD; + +# lower-cases s in place # +PROC string to lower = (REF STRING s)VOID: + FOR i FROM LWB s TO UPB s DO s[i] := to lower(s[i]) OD; + +main: ( + STRING t := "alphaBETA"; + string to upper(t); + printf(($"uppercase: "gl$, t)); + string to lower(t); + printf(($"lowercase: "gl$, t)) +) diff --git a/Task/String-case/APL/string-case.apl b/Task/String-case/APL/string-case.apl new file mode 100644 index 0000000000..ad8730f704 --- /dev/null +++ b/Task/String-case/APL/string-case.apl @@ -0,0 +1,9 @@ + AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ' + AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ*' + AlphUpper[AlphLower⍳'I'm using APL!'] +I*M USING APL* + + AlphLower←'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ*' + AlphUpper←'ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ' + AlphLower[AlphUpper⍳'I'm using APL!'] +i*m using apl* diff --git a/Task/String-case/AWK/string-case-1.awk b/Task/String-case/AWK/string-case-1.awk new file mode 100644 index 0000000000..51c90fe07e --- /dev/null +++ b/Task/String-case/AWK/string-case-1.awk @@ -0,0 +1,4 @@ +BEGIN { + a = "alphaBETA"; + print toupper(a), tolower(a) +} diff --git a/Task/String-case/AWK/string-case-2.awk b/Task/String-case/AWK/string-case-2.awk new file mode 100644 index 0000000000..a653232008 --- /dev/null +++ b/Task/String-case/AWK/string-case-2.awk @@ -0,0 +1,4 @@ +BEGIN { + a = "alphaBETA"; + print toupper(substr(a, 1, 1)) tolower(substr(a, 2)) +} diff --git a/Task/String-case/ActionScript/string-case.as b/Task/String-case/ActionScript/string-case.as new file mode 100644 index 0000000000..dbd48d3aa7 --- /dev/null +++ b/Task/String-case/ActionScript/string-case.as @@ -0,0 +1,3 @@ +var string:String = 'alphaBETA'; +var upper:String = string.toUpperCase(); +var lower:String = string.toLowerCase(); diff --git a/Task/String-case/Ada/string-case.ada b/Task/String-case/Ada/string-case.ada new file mode 100644 index 0000000000..11ac1e10ec --- /dev/null +++ b/Task/String-case/Ada/string-case.ada @@ -0,0 +1,9 @@ +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Upper_Case_String is + S : String := "alphaBETA"; +begin + Put_Line(To_Upper(S)); + Put_Line(To_Lower(S)); +end Upper_Case_String; diff --git a/Task/String-case/Arbre/string-case.arbre b/Task/String-case/Arbre/string-case.arbre new file mode 100644 index 0000000000..808dd7a095 --- /dev/null +++ b/Task/String-case/Arbre/string-case.arbre @@ -0,0 +1,2 @@ +main(): + uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io diff --git a/Task/String-case/AutoHotkey/string-case.ahk b/Task/String-case/AutoHotkey/string-case.ahk new file mode 100644 index 0000000000..0eb39dcac4 --- /dev/null +++ b/Task/String-case/AutoHotkey/string-case.ahk @@ -0,0 +1,5 @@ +a := "alphaBETA" +StringLower, b, a ; alphabeta +StringUpper, c, a ; ALPHABETA + +StringUpper, d, a, T ; Alphabeta (T = title case) eg "alpha beta gamma" would become "Alpha Beta Gamma" diff --git a/Task/String-case/AutoIt/string-case.autoit b/Task/String-case/AutoIt/string-case.autoit new file mode 100644 index 0000000000..874adeedc6 --- /dev/null +++ b/Task/String-case/AutoIt/string-case.autoit @@ -0,0 +1,3 @@ +$sString = "alphaBETA" +$sUppercase = StringUpper($sString) ;"ALPHABETA" +$sLowercase = StringLower($sString) ;"alphabeta" diff --git a/Task/String-case/BASIC/string-case.basic b/Task/String-case/BASIC/string-case.basic new file mode 100644 index 0000000000..62aa48e671 --- /dev/null +++ b/Task/String-case/BASIC/string-case.basic @@ -0,0 +1,3 @@ +s$ = "alphaBETA" +PRINT UCASE$(s$) +PRINT LCASE$(s$) diff --git a/Task/String-case/BBC-BASIC/string-case.bbc b/Task/String-case/BBC-BASIC/string-case.bbc new file mode 100644 index 0000000000..6ee5644f87 --- /dev/null +++ b/Task/String-case/BBC-BASIC/string-case.bbc @@ -0,0 +1,7 @@ + INSTALL @lib$+"STRINGLIB" + + original$ = "alphaBETA" + PRINT "Original: " original$ + PRINT "Lower case: " FN_lower(original$) + PRINT "Upper case: " FN_upper(original$) + PRINT "Title case: " FN_title(original$) diff --git a/Task/String-case/Befunge/string-case.bf b/Task/String-case/Befunge/string-case.bf new file mode 100644 index 0000000000..31984e8857 --- /dev/null +++ b/Task/String-case/Befunge/string-case.bf @@ -0,0 +1,4 @@ +"ATEBahpla" > : #v_ 25* , @ >48*-v + > :: "`"` \"{"\` * | > , v + > ^ + ^ < diff --git a/Task/String-case/Bracmat/string-case.bracmat b/Task/String-case/Bracmat/string-case.bracmat new file mode 100644 index 0000000000..5f25255ba1 --- /dev/null +++ b/Task/String-case/Bracmat/string-case.bracmat @@ -0,0 +1,2 @@ + "alphaBETA":?s +& out$str$(upp$!s \n low$!s) diff --git a/Task/String-case/Burlesque/string-case.blq b/Task/String-case/Burlesque/string-case.blq new file mode 100644 index 0000000000..769e54b73f --- /dev/null +++ b/Task/String-case/Burlesque/string-case.blq @@ -0,0 +1,3 @@ +blsq ) "alphaBETA"^^zz\/ZZ +"ALPHABETA" +"alphabeta" diff --git a/Task/String-case/C++/string-case-1.cpp b/Task/String-case/C++/string-case-1.cpp new file mode 100644 index 0000000000..d39afc7ef9 --- /dev/null +++ b/Task/String-case/C++/string-case-1.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +/// \brief in-place convert string to upper case +/// \return ref to transformed string +void str_toupper(std::string &str) { + std::transform(str.begin(), + str.end(), + str.begin(), + (int(*)(int)) std::toupper); +} + +/// \brief in-place convert string to lower case +/// \return ref to transformed string +void str_tolower(std::string &str) { + std::transform(str.begin(), + str.end(), + str.begin(), + (int(*)(int)) std::tolower); +} diff --git a/Task/String-case/C++/string-case-2.cpp b/Task/String-case/C++/string-case-2.cpp new file mode 100644 index 0000000000..c8b6926eab --- /dev/null +++ b/Task/String-case/C++/string-case-2.cpp @@ -0,0 +1,12 @@ +#include +#include + +using namespace std; +int main() { + string foo("_upperCas3Me!!"); + str_toupper(foo); + cout << foo << endl; + str_tolower(foo); + cout << foo << endl; + return 0; +} diff --git a/Task/String-case/C/string-case.c b/Task/String-case/C/string-case.c new file mode 100644 index 0000000000..e3a25db928 --- /dev/null +++ b/Task/String-case/C/string-case.c @@ -0,0 +1,36 @@ +/* Demonstrate toupper and tolower for + standard C strings. + This does not work for multibyte character sets. */ +#include +#include + +/* upper-cases s in place */ +void str_toupper(char *s) +{ + while(*s) + { + *s=toupper(*s); + s++; + } +} + + +/* lower-cases s in place */ +void str_tolower(char *s) +{ + while(*s) + { + *s=tolower(*s); + s++; + } +} + +int main(int argc, char *argv[]) +{ + char t[255]="alphaBETA"; + str_toupper(t); + printf("uppercase: %s\n", t); + str_tolower(t); + printf("lowercase: %s\n", t); + return 0; +} diff --git a/Task/String-case/CMake/string-case.cmake b/Task/String-case/CMake/string-case.cmake new file mode 100644 index 0000000000..b217bf4eb7 --- /dev/null +++ b/Task/String-case/CMake/string-case.cmake @@ -0,0 +1,4 @@ +string(TOUPPER alphaBETA s) +message(STATUS "Uppercase: ${s}") +string(TOLOWER alphaBETA s) +message(STATUS "Lowercase: ${s}") diff --git a/Task/String-case/Clojure/string-case.clj b/Task/String-case/Clojure/string-case.clj new file mode 100644 index 0000000000..d00459a62b --- /dev/null +++ b/Task/String-case/Clojure/string-case.clj @@ -0,0 +1,3 @@ +(def string "alphaBETA") +(println (.toUpperCase string)) +(println (.toLowerCase string)) diff --git a/Task/String-case/ColdFusion/string-case-1.cfm b/Task/String-case/ColdFusion/string-case-1.cfm new file mode 100644 index 0000000000..ccb8d6dbfe --- /dev/null +++ b/Task/String-case/ColdFusion/string-case-1.cfm @@ -0,0 +1,2 @@ + + diff --git a/Task/String-case/ColdFusion/string-case-2.cfm b/Task/String-case/ColdFusion/string-case-2.cfm new file mode 100644 index 0000000000..99141b6451 --- /dev/null +++ b/Task/String-case/ColdFusion/string-case-2.cfm @@ -0,0 +1,3 @@ + + + diff --git a/Task/String-case/Common-Lisp/string-case-1.lisp b/Task/String-case/Common-Lisp/string-case-1.lisp new file mode 100644 index 0000000000..ae32b40b07 --- /dev/null +++ b/Task/String-case/Common-Lisp/string-case-1.lisp @@ -0,0 +1,2 @@ +CL-USER> (string-upcase "alphaBETA") +"ALPHABETA" diff --git a/Task/String-case/Common-Lisp/string-case-2.lisp b/Task/String-case/Common-Lisp/string-case-2.lisp new file mode 100644 index 0000000000..a459aa7b0e --- /dev/null +++ b/Task/String-case/Common-Lisp/string-case-2.lisp @@ -0,0 +1,2 @@ +CL-USER> (string-downcase "alphaBETA") +"alphabeta" diff --git a/Task/String-case/D/string-case.d b/Task/String-case/D/string-case.d new file mode 100644 index 0000000000..4ca6017c28 --- /dev/null +++ b/Task/String-case/D/string-case.d @@ -0,0 +1,7 @@ +import std.stdio, std.string; + +void main() { + auto s = "alphaBETA"; + writeln(s.toUpper()); + writeln(s.toLower()); +} diff --git a/Task/String-case/DWScript/string-case.dwscript b/Task/String-case/DWScript/string-case.dwscript new file mode 100644 index 0000000000..6ff8d040e6 --- /dev/null +++ b/Task/String-case/DWScript/string-case.dwscript @@ -0,0 +1,2 @@ +PrintLn(UpperCase('alphaBETA')); +PrintLn(LowerCase('alphaBETA')); diff --git a/Task/String-case/Delphi/string-case.delphi b/Task/String-case/Delphi/string-case.delphi new file mode 100644 index 0000000000..8b00c18785 --- /dev/null +++ b/Task/String-case/Delphi/string-case.delphi @@ -0,0 +1,2 @@ +writeln(uppercase('alphaBETA')); +writeln(lowercase('alphaBETA')); diff --git a/Task/String-case/E/string-case.e b/Task/String-case/E/string-case.e new file mode 100644 index 0000000000..a8f648ae8d --- /dev/null +++ b/Task/String-case/E/string-case.e @@ -0,0 +1,2 @@ +["alphaBETA".toUpperCase(), +"alphaBETA".toLowerCase()] diff --git a/Task/String-case/Erlang/string-case.erl b/Task/String-case/Erlang/string-case.erl new file mode 100644 index 0000000000..251fcc98c9 --- /dev/null +++ b/Task/String-case/Erlang/string-case.erl @@ -0,0 +1,2 @@ +string:to_upper("alphaBETA"). +string:to_lower("alphaBETA"). diff --git a/Task/String-case/Factor/string-case.factor b/Task/String-case/Factor/string-case.factor new file mode 100644 index 0000000000..608ebfda9a --- /dev/null +++ b/Task/String-case/Factor/string-case.factor @@ -0,0 +1,4 @@ +"alphaBETA" >lower ! "alphabeta" +"alphaBETA" >upper ! "ALPHABETA" +"alphaBETA" >title ! "Alphabeta" +"ß" >case-fold ! "ss" diff --git a/Task/String-case/Falcon/string-case.falcon b/Task/String-case/Falcon/string-case.falcon new file mode 100644 index 0000000000..97723831ab --- /dev/null +++ b/Task/String-case/Falcon/string-case.falcon @@ -0,0 +1,2 @@ +printl("alphaBETA".lower()) +printl("alphaBETA".upper()) diff --git a/Task/String-case/Fantom/string-case.fantom b/Task/String-case/Fantom/string-case.fantom new file mode 100644 index 0000000000..8b1d8b83df --- /dev/null +++ b/Task/String-case/Fantom/string-case.fantom @@ -0,0 +1,10 @@ +fansh> a := "alphaBETA" +alphaBETA +fansh> a.upper // convert whole string to upper case +ALPHABETA +fansh> a.lower // convert whole string to lower case +alphabeta +fansh> a.capitalize // make sure first letter is capital +AlphaBETA +fansh> "BETAalpha".decapitalize // make sure first letter is not capital +bETAalpha diff --git a/Task/String-case/Fortran/string-case.f b/Task/String-case/Fortran/string-case.f new file mode 100644 index 0000000000..e8ff9b70d2 --- /dev/null +++ b/Task/String-case/Fortran/string-case.f @@ -0,0 +1,38 @@ + program example + + implicit none + + character(9) :: teststring = "alphaBETA" + + call To_upper(teststring) + write(*,*) teststring + call To_lower(teststring) + write(*,*) teststring + + contains + + subroutine To_upper(str) + character(*), intent(in out) :: str + integer :: i + + do i = 1, len(str) + select case(str(i:i)) + case("a":"z") + str(i:i) = achar(iachar(str(i:i))-32) + end select + end do + end subroutine To_upper + + subroutine To_lower(str) + character(*), intent(in out) :: str + integer :: i + + do i = 1, len(str) + select case(str(i:i)) + case("A":"Z") + str(i:i) = achar(iachar(str(i:i))+32) + end select + end do + end subroutine To_Lower + + end program example diff --git a/Task/String-case/GML/string-case.gml b/Task/String-case/GML/string-case.gml new file mode 100644 index 0000000000..f737ed509c --- /dev/null +++ b/Task/String-case/GML/string-case.gml @@ -0,0 +1,8 @@ +#define cases +{ + x = 'alphaBETA'; + y = string_upper(x); // returns ALPHABETA + z = string_lower(x); // returns alphabeta + show_message(y); + show_message(z); +} diff --git a/Task/String-case/Go/string-case.go b/Task/String-case/Go/string-case.go new file mode 100644 index 0000000000..b687ce429c --- /dev/null +++ b/Task/String-case/Go/string-case.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +func main() { + show("alphaBETA") + show("alpha BETA") + show("DŽLjnj") // should render similar to DZLjnj +} + +func show(s string) { + fmt.Println("\nstring: ", s, "len:", utf8.RuneCountInString(s)) + fmt.Println("All upper case: ", strings.ToUpper(s)) // DZLJNJ + fmt.Println("All lower case: ", strings.ToLower(s)) // dzljnj + fmt.Println("All title case: ", strings.ToTitle(s)) // DzLjNj + // notice Title() only modifies first letters of words + // non-first letters keep their case. + fmt.Println("Title words: ", strings.Title(s)) // Dzljnj + fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) +} diff --git a/Task/String-case/Groovy/string-case.groovy b/Task/String-case/Groovy/string-case.groovy new file mode 100644 index 0000000000..3d7a5d3b89 --- /dev/null +++ b/Task/String-case/Groovy/string-case.groovy @@ -0,0 +1,4 @@ +def str = 'alphaBETA' + +println str.toUpperCase() +println str.toLowerCase() diff --git a/Task/String-case/Haskell/string-case.hs b/Task/String-case/Haskell/string-case.hs new file mode 100644 index 0000000000..4c6643059a --- /dev/null +++ b/Task/String-case/Haskell/string-case.hs @@ -0,0 +1,6 @@ +import Data.Char + +s = "alphaBETA" + +lower = map toLower s +upper = map toUpper s diff --git a/Task/String-case/HicEst/string-case.hicest b/Task/String-case/HicEst/string-case.hicest new file mode 100644 index 0000000000..8c96e12214 --- /dev/null +++ b/Task/String-case/HicEst/string-case.hicest @@ -0,0 +1,4 @@ +CHARACTER str = "alphaBETA" +EDIT(Text=str, UpperCase=LEN(str)) +EDIT(Text=str, LowerCase=LEN(str)) +EDIT(Text=str, UpperCase=1) diff --git a/Task/String-case/Icon/string-case.icon b/Task/String-case/Icon/string-case.icon new file mode 100644 index 0000000000..de3fe5a2f6 --- /dev/null +++ b/Task/String-case/Icon/string-case.icon @@ -0,0 +1,4 @@ +procedure main() + write(map("alphaBETA")) + write(map("alphaBETA",&lcase,&ucase)) +end diff --git a/Task/String-case/J/string-case-1.j b/Task/String-case/J/string-case-1.j new file mode 100644 index 0000000000..e43283fd99 --- /dev/null +++ b/Task/String-case/J/string-case-1.j @@ -0,0 +1,4 @@ + toupper 'alphaBETA' +ALPHABETA + tolower 'alphaBETA' +alphabeta diff --git a/Task/String-case/J/string-case-2.j b/Task/String-case/J/string-case-2.j new file mode 100644 index 0000000000..245e9f575d --- /dev/null +++ b/Task/String-case/J/string-case-2.j @@ -0,0 +1,2 @@ +upper=: {&((65+i.26) +&32@[} i.256)&.(a.&i.) +lower=: {&((97+i.26) -&32@[} i.256)&.(a.&i.) diff --git a/Task/String-case/J/string-case-3.j b/Task/String-case/J/string-case-3.j new file mode 100644 index 0000000000..687c7da29d --- /dev/null +++ b/Task/String-case/J/string-case-3.j @@ -0,0 +1,4 @@ + upper 'alphaBETA' +ALPHABETA + lower 'alphaBETA' +alphabeta diff --git a/Task/String-case/Java/string-case.java b/Task/String-case/Java/string-case.java new file mode 100644 index 0000000000..19c7e8414b --- /dev/null +++ b/Task/String-case/Java/string-case.java @@ -0,0 +1,6 @@ +String str = "alphaBETA"; +System.out.println(str.toUpperCase()); +System.out.println(str.toLowerCase()); +//Also works with non-English characters with no modification +System.out.println("äàâáçñßæεбế".toUpperCase()); +System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase()); //does not transalate "SS" to "ß" diff --git a/Task/String-case/JavaScript/string-case-1.js b/Task/String-case/JavaScript/string-case-1.js new file mode 100644 index 0000000000..a053cfd034 --- /dev/null +++ b/Task/String-case/JavaScript/string-case-1.js @@ -0,0 +1,2 @@ +alert( "alphaBETA".toUpperCase() ); +alert( "alphaBETA".toLowerCase() ); diff --git a/Task/String-case/JavaScript/string-case-2.js b/Task/String-case/JavaScript/string-case-2.js new file mode 100644 index 0000000000..4b7c760168 --- /dev/null +++ b/Task/String-case/JavaScript/string-case-2.js @@ -0,0 +1,3 @@ +var string = "alphaBETA"; +var uppercase = string.toUpperCase(); +var lowercase = string.toLowerCase(); diff --git a/Task/String-case/Liberty-BASIC/string-case.liberty b/Task/String-case/Liberty-BASIC/string-case.liberty new file mode 100644 index 0000000000..da9027da89 --- /dev/null +++ b/Task/String-case/Liberty-BASIC/string-case.liberty @@ -0,0 +1,7 @@ +input$ ="alphaBETA" + +print input$ +print upper$( input$) +print lower$( input$) + +end diff --git a/Task/String-case/Lua/string-case.lua b/Task/String-case/Lua/string-case.lua new file mode 100644 index 0000000000..93472e0316 --- /dev/null +++ b/Task/String-case/Lua/string-case.lua @@ -0,0 +1,3 @@ +str = "alphaBETA" +print( string.upper(str) ) +print( string.lower(str) ) diff --git a/Task/String-case/M4/string-case.m4 b/Task/String-case/M4/string-case.m4 new file mode 100644 index 0000000000..b59e238244 --- /dev/null +++ b/Task/String-case/M4/string-case.m4 @@ -0,0 +1,6 @@ +define(`upcase', `translit(`$*', `a-z', `A-Z')') +define(`downcase', `translit(`$*', `A-Z', `a-z')') + +define(`x',`alphaBETA') +upcase(x) +downcase(x) diff --git a/Task/String-case/MATLAB/string-case.m b/Task/String-case/MATLAB/string-case.m new file mode 100644 index 0000000000..c13a97f7f5 --- /dev/null +++ b/Task/String-case/MATLAB/string-case.m @@ -0,0 +1,11 @@ +>> upper('alphaBETA') + +ans = + +ALPHABETA + +>> lower('alphaBETA') + +ans = + +alphabeta diff --git a/Task/String-case/MAXScript/string-case.maxscript b/Task/String-case/MAXScript/string-case.maxscript new file mode 100644 index 0000000000..6834525231 --- /dev/null +++ b/Task/String-case/MAXScript/string-case.maxscript @@ -0,0 +1,3 @@ +str = "alphaBETA" +print (toUpper str) +print (toLower str) diff --git a/Task/String-case/MUMPS/string-case.mumps b/Task/String-case/MUMPS/string-case.mumps new file mode 100644 index 0000000000..fedf2f67b2 --- /dev/null +++ b/Task/String-case/MUMPS/string-case.mumps @@ -0,0 +1,7 @@ +STRCASE(S) + SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ" + SET LO="abcdefghijklmnopqrstuvwxyz" + WRITE !,"Given: "_S + WRITE !,"Upper: "_$TRANSLATE(S,LO,UP) + WRITE !,"Lower: "_$TRANSLATE(S,UP,LO) + QUIT diff --git a/Task/String-case/Mathematica/string-case.math b/Task/String-case/Mathematica/string-case.math new file mode 100644 index 0000000000..74c57b96c7 --- /dev/null +++ b/Task/String-case/Mathematica/string-case.math @@ -0,0 +1,3 @@ +str="alphaBETA"; +ToUpperCase[str] +ToLowerCase[str] diff --git a/Task/String-case/Mercury/string-case.mercury b/Task/String-case/Mercury/string-case.mercury new file mode 100644 index 0000000000..c82c58c00f --- /dev/null +++ b/Task/String-case/Mercury/string-case.mercury @@ -0,0 +1,16 @@ +:- module string_case. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module list, string. + +main(!IO) :- + S = "alphaBETA", + io.format("uppercase : %s\n", [s(to_upper(S))], !IO), + io.format("lowercase : %s\n", [s(to_lower(S))], !IO), + io.format("capitalize first: %s\n", [s(capitalize_first(S))], !IO). + % We can use uncaptitalize_first/1 to ensure the first character in a + % string is lower-case. diff --git a/Task/String-case/Metafont/string-case-1.metafont b/Task/String-case/Metafont/string-case-1.metafont new file mode 100644 index 0000000000..dd07a6dd62 --- /dev/null +++ b/Task/String-case/Metafont/string-case-1.metafont @@ -0,0 +1,34 @@ +vardef isbetween(expr a, i, f) = + if string a: + if (ASCII(a) >= ASCII(i)) and (ASCII(a) <= ASCII(f)): + true + else: + false + fi + else: + false + fi enddef; + +vardef toupper(expr s) = + save ?; string ?; ? := ""; d := ASCII"A" - ASCII"a"; + for i = 0 upto length(s)-1: + if isbetween(substring(i, i+1) of s, "a", "z"): + ? := ? & char(ASCII(substring(i,i+1) of s) + d) + else: + ? := ? & substring(i, i+1) of s + fi; + endfor + ? +enddef; + +vardef tolower(expr s) = + save ?; string ?; ? := ""; d := ASCII"a" - ASCII"A"; + for i = 0 upto length(s)-1: + if isbetween(substring(i, i+1) of s, "A", "Z"): + ? := ? & char(ASCII(substring(i,i+1) of s) + d) + else: + ? := ? & substring(i, i+1) of s + fi; + endfor + ? +enddef; diff --git a/Task/String-case/Metafont/string-case-2.metafont b/Task/String-case/Metafont/string-case-2.metafont new file mode 100644 index 0000000000..ecfb38aa67 --- /dev/null +++ b/Task/String-case/Metafont/string-case-2.metafont @@ -0,0 +1,4 @@ +message toupper("alphaBETA"); +message tolower("alphaBETA"); + +end diff --git a/Task/String-case/Modula-3/string-case.mod3 b/Task/String-case/Modula-3/string-case.mod3 new file mode 100644 index 0000000000..fae6fd8e42 --- /dev/null +++ b/Task/String-case/Modula-3/string-case.mod3 @@ -0,0 +1,30 @@ +MODULE TextCase EXPORTS Main; + +IMPORT IO, Text, ASCII; + +PROCEDURE Upper(txt: TEXT): TEXT = + VAR + len := Text.Length(txt); + res := ""; + BEGIN + FOR i := 0 TO len - 1 DO + res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)])); + END; + RETURN res; + END Upper; + +PROCEDURE Lower(txt: TEXT): TEXT = + VAR + len := Text.Length(txt); + res := ""; + BEGIN + FOR i := 0 TO len - 1 DO + res := Text.Cat(res, Text.FromChar(ASCII.Lower[Text.GetChar(txt, i)])); + END; + RETURN res; + END Lower; + +BEGIN + IO.Put(Upper("alphaBETA\n")); + IO.Put(Lower("alphaBETA\n")); +END TextCase. diff --git a/Task/String-case/Nemerle/string-case.nemerle b/Task/String-case/Nemerle/string-case.nemerle new file mode 100644 index 0000000000..3373354431 --- /dev/null +++ b/Task/String-case/Nemerle/string-case.nemerle @@ -0,0 +1,15 @@ +using System.Console; +using System.Globalization; + +module StringCase +{ + Main() : void + { + def alpha = "alphaBETA"; + WriteLine(alpha.ToUpper()); + WriteLine(alpha.ToLower()); + + WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase("exAmpLe sTrinG")); + + } +} diff --git a/Task/String-case/NetRexx/string-case.netrexx b/Task/String-case/NetRexx/string-case.netrexx new file mode 100644 index 0000000000..9eaddee0ee --- /dev/null +++ b/Task/String-case/NetRexx/string-case.netrexx @@ -0,0 +1,9 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols + +abc = 'alphaBETA' + +say abc.upper +say abc.lower +say abc.upper(1, 1) -- capitalize 1st character diff --git a/Task/String-case/NewLISP/string-case.newlisp b/Task/String-case/NewLISP/string-case.newlisp new file mode 100644 index 0000000000..5a912812a8 --- /dev/null +++ b/Task/String-case/NewLISP/string-case.newlisp @@ -0,0 +1,2 @@ +(upper-case "alphaBETA") +(lower-case "alphaBETA") diff --git a/Task/String-case/Nial/string-case.nial b/Task/String-case/Nial/string-case.nial new file mode 100644 index 0000000000..4fd3ef050e --- /dev/null +++ b/Task/String-case/Nial/string-case.nial @@ -0,0 +1,4 @@ +toupper 'alphaBETA' +=ALPHABETA +tolower 'alphaBETA' +=alphabeta diff --git a/Task/String-case/OCaml/string-case.ocaml b/Task/String-case/OCaml/string-case.ocaml new file mode 100644 index 0000000000..d5a1b817ca --- /dev/null +++ b/Task/String-case/OCaml/string-case.ocaml @@ -0,0 +1,7 @@ +let () = + let str = "alphaBETA" in + print_endline (String.uppercase str); (* ALPHABETA *) + print_endline (String.lowercase str); (* alphabeta *) + + print_endline (String.capitalize str); (* AlphaBETA *) +;; diff --git a/Task/String-case/Objeck/string-case.objeck b/Task/String-case/Objeck/string-case.objeck new file mode 100644 index 0000000000..027ffae27f --- /dev/null +++ b/Task/String-case/Objeck/string-case.objeck @@ -0,0 +1,3 @@ +string := "alphaBETA"; +string->ToUpper()->PrintLine(); +string->ToLower()->PrintLine(); diff --git a/Task/String-case/Objective-C/string-case.m b/Task/String-case/Objective-C/string-case.m new file mode 100644 index 0000000000..f07dfa3bd2 --- /dev/null +++ b/Task/String-case/Objective-C/string-case.m @@ -0,0 +1,4 @@ +NSLog(@"%@", [@"alphaBETA" uppercaseString]); +NSLog(@"%@", [@"alphaBETA" lowercaseString]); + +NSLog(@"%@", [@"foO BAr" capitalizedString]); // "Foo Bar" diff --git a/Task/String-case/Octave/string-case.octave b/Task/String-case/Octave/string-case.octave new file mode 100644 index 0000000000..4974ff64b9 --- /dev/null +++ b/Task/String-case/Octave/string-case.octave @@ -0,0 +1,5 @@ +s = "alphaBETA"; +slc = tolower(s); +suc = toupper(s); +disp(slc); +disp(suc); diff --git a/Task/String-case/OpenEdge-Progress/string-case.openedge b/Task/String-case/OpenEdge-Progress/string-case.openedge new file mode 100644 index 0000000000..f97e98ff02 --- /dev/null +++ b/Task/String-case/OpenEdge-Progress/string-case.openedge @@ -0,0 +1,2 @@ +caps("alphaBETA") +lc("alphaBETA") diff --git a/Task/String-case/OxygenBasic/string-case.oxy b/Task/String-case/OxygenBasic/string-case.oxy new file mode 100644 index 0000000000..e4c32a7e33 --- /dev/null +++ b/Task/String-case/OxygenBasic/string-case.oxy @@ -0,0 +1,5 @@ +string s="alphaBETA" + +print lcase(s) " "+ + ucase(s) " "+ + ucase(left(s,1))+mid(s,2) 'capitalised diff --git a/Task/String-case/Oz/string-case-1.oz b/Task/String-case/Oz/string-case-1.oz new file mode 100644 index 0000000000..877d39be7c --- /dev/null +++ b/Task/String-case/Oz/string-case-1.oz @@ -0,0 +1,5 @@ +declare + Str = "alphaBETA" +in + {System.showInfo {Map Str Char.toUpper}} + {System.showInfo {Map Str Char.toLower}} diff --git a/Task/String-case/Oz/string-case-2.oz b/Task/String-case/Oz/string-case-2.oz new file mode 100644 index 0000000000..c1c74a8639 --- /dev/null +++ b/Task/String-case/Oz/string-case-2.oz @@ -0,0 +1,4 @@ +declare + [StringX] = {Link ['x-oz://system/String.ozf']} +in + {System.showInfo {StringX.capitalize "alphaBETA"}} %% prints "AlphaBETA" diff --git a/Task/String-case/PHP/string-case.php b/Task/String-case/PHP/string-case.php new file mode 100644 index 0000000000..aa571180e3 --- /dev/null +++ b/Task/String-case/PHP/string-case.php @@ -0,0 +1,8 @@ +$str = "alphaBETA"; +echo strtoupper($str), "\n"; // ALPHABETA +echo strtolower($str), "\n"; // alphabeta + +echo ucfirst($str), "\n"; // AlphaBETA +echo lcfirst("FOObar"), "\n"; // fOObar +echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ +echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz diff --git a/Task/String-case/PL-I/string-case-1.pli b/Task/String-case/PL-I/string-case-1.pli new file mode 100644 index 0000000000..4da1defa20 --- /dev/null +++ b/Task/String-case/PL-I/string-case-1.pli @@ -0,0 +1,4 @@ +declare s character (20) varying initial ('alphaBETA'); + +put skip list (uppercase(s)); +put skip list (lowercase(s)); diff --git a/Task/String-case/PL-I/string-case-2.pli b/Task/String-case/PL-I/string-case-2.pli new file mode 100644 index 0000000000..399dc1e318 --- /dev/null +++ b/Task/String-case/PL-I/string-case-2.pli @@ -0,0 +1,5 @@ +/* An alternative to the above, which might be used if some */ +/* non-standard conversion is required, is shown for */ +/* converting to upper case: */ +put skip list ( translate(s, 'abcdefghijklmnopqrstuvwxyz', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') ); diff --git a/Task/String-case/PL-SQL/string-case.sql b/Task/String-case/PL-SQL/string-case.sql new file mode 100644 index 0000000000..7e29a4c96d --- /dev/null +++ b/Task/String-case/PL-SQL/string-case.sql @@ -0,0 +1,10 @@ +declare + vc VARCHAR2(40) := 'alphaBETA'; + ivc VARCHAR2(40); + lvc VARCHAR2(40); + uvc VARCHAR2(40); +begin + ivc := INITCAP(vc); -- 'Alphabeta' + lvc := LOWER(vc); -- 'alphabeta' + uvc := UPPER(vc); -- 'ALPHABETA' +end; diff --git a/Task/String-case/Perl-6/string-case.pl6 b/Task/String-case/Perl-6/string-case.pl6 new file mode 100644 index 0000000000..29b8127335 --- /dev/null +++ b/Task/String-case/Perl-6/string-case.pl6 @@ -0,0 +1,9 @@ +my $word = "alpha BETA" ; +say uc $word; # all uppercase (subroutine call) +say $word.uc; # all uppercase (method call) +# from now on we use only method calls as examples +say $word.lc; # all lowercase +say $word.tc; # first letter titlecase +say $word.tclc; # first letter titlecase, rest lowercase +say $word.tcuc; # first letter titlecase, rest uppercase +say $word.wordcase; # capitalize each word diff --git a/Task/String-case/Perl/string-case.pl b/Task/String-case/Perl/string-case.pl new file mode 100644 index 0000000000..4b04304dcf --- /dev/null +++ b/Task/String-case/Perl/string-case.pl @@ -0,0 +1,7 @@ +my $string = "alphaBETA"; +print uc($string), "\n"; # => "ALPHABETA" +print lc($string), "\n"; # => "alphabeta" +$string =~ tr/[a-z][A-Z]/[A-Z][a-z]/; print "$string\n"; # => ALPHAbeta + +print ucfirst($string), "\n"; # => "AlphaBETA" +print lcfirst("FOObar"), "\n"; # => "fOObar" diff --git a/Task/String-case/PicoLisp/string-case.l b/Task/String-case/PicoLisp/string-case.l new file mode 100644 index 0000000000..6c27e91ec1 --- /dev/null +++ b/Task/String-case/PicoLisp/string-case.l @@ -0,0 +1,3 @@ +(let Str "alphaBETA" + (prinl (uppc Str)) + (prinl (lowc Str)) ) diff --git a/Task/String-case/Pop11/string-case.pop11 b/Task/String-case/Pop11/string-case.pop11 new file mode 100644 index 0000000000..f852547d34 --- /dev/null +++ b/Task/String-case/Pop11/string-case.pop11 @@ -0,0 +1,3 @@ +lvars str = 'alphaBETA'; +lowertoupper(str) => +uppertolower(str) => diff --git a/Task/String-case/PowerShell/string-case.psh b/Task/String-case/PowerShell/string-case.psh new file mode 100644 index 0000000000..0dccfcfe52 --- /dev/null +++ b/Task/String-case/PowerShell/string-case.psh @@ -0,0 +1,3 @@ +$string = 'alphaBETA' +$lower = $string.ToLower() +$upper = $string.ToUpper() diff --git a/Task/String-case/Protium/string-case-1.protium b/Task/String-case/Protium/string-case-1.protium new file mode 100644 index 0000000000..0acddb029d --- /dev/null +++ b/Task/String-case/Protium/string-case-1.protium @@ -0,0 +1,5 @@ +<@ ENU$$$LSTPSTLITLIT>UPP| +[<@ SAYELTLST>...] <@ SAYHLPELTLST>...<@ DEFKEYELTLST>__SuperMacro|... +<@ SAY&&&LIT>alphaBETA + + diff --git a/Task/String-case/Protium/string-case-2.protium b/Task/String-case/Protium/string-case-2.protium new file mode 100644 index 0000000000..6f326a75d5 --- /dev/null +++ b/Task/String-case/Protium/string-case-2.protium @@ -0,0 +1,5 @@ +<# ENUMERATION LAMBDA LIST PEERSET LITERAL LITERAL>UPP| +[<# SAY ELEMENT LIST>...] <# SAY HELP ELEMENT LIST>...<# DEFINE KEYWORD ELEMENT LIST>__SuperMacro|... +<# SAY SUPERMACRO LITERAL>alphaBETA + + diff --git a/Task/String-case/PureBasic/string-case.purebasic b/Task/String-case/PureBasic/string-case.purebasic new file mode 100644 index 0000000000..c9d40658ff --- /dev/null +++ b/Task/String-case/PureBasic/string-case.purebasic @@ -0,0 +1,3 @@ +s$ = "alphaBETA" +upper$ = UCase(s$) ;uppercase +lower$ = LCase(s$) ;lowercase diff --git a/Task/String-case/Python/string-case-1.py b/Task/String-case/Python/string-case-1.py new file mode 100644 index 0000000000..70fbdce571 --- /dev/null +++ b/Task/String-case/Python/string-case-1.py @@ -0,0 +1,11 @@ +s = "alphaBETA" +print s.upper() # => "ALPHABETA" +print s.lower() # => "alphabeta" + +print s.swapcase() # => "ALPHAbeta" + +print "fOo bAR".capitalize() # => "Foo bar" +print "fOo bAR".title() # => "Foo Bar" + +import string +print string.capwords("fOo bAR") # => "Foo Bar" diff --git a/Task/String-case/Python/string-case-2.py b/Task/String-case/Python/string-case-2.py new file mode 100644 index 0000000000..f444c5a895 --- /dev/null +++ b/Task/String-case/Python/string-case-2.py @@ -0,0 +1,2 @@ +print "foo's bar".title() # => "Foo'S Bar" +print string.capwords("foo's bar") # => "Foo's Bar" diff --git a/Task/String-case/R/string-case.r b/Task/String-case/R/string-case.r new file mode 100644 index 0000000000..751eeca28c --- /dev/null +++ b/Task/String-case/R/string-case.r @@ -0,0 +1,3 @@ + str <- "alphaBETA" + toupper(str) + tolower(str) diff --git a/Task/String-case/REBOL/string-case.rebol b/Task/String-case/REBOL/string-case.rebol new file mode 100644 index 0000000000..12f3935da5 --- /dev/null +++ b/Task/String-case/REBOL/string-case.rebol @@ -0,0 +1,3 @@ +print ["Original: " original: "alphaBETA"] +print ["Uppercase:" uppercase original] +print ["Lowercase:" lowercase original] diff --git a/Task/String-case/REXX/string-case-1.rexx b/Task/String-case/REXX/string-case-1.rexx new file mode 100644 index 0000000000..aef5b33588 --- /dev/null +++ b/Task/String-case/REXX/string-case-1.rexx @@ -0,0 +1,6 @@ +abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters*/ +abcU = translate(abc) /* " " " uppercase " */ + +x = 'alphaBETA' /*define string to a REXX variable*/ +y = translate(x) /*uppercase X and store it───► Y*/ +z = translate(x, abc, abcU) /*tran uppercase──►lowercase chars*/ diff --git a/Task/String-case/REXX/string-case-2.rexx b/Task/String-case/REXX/string-case-2.rexx new file mode 100644 index 0000000000..bf06db629c --- /dev/null +++ b/Task/String-case/REXX/string-case-2.rexx @@ -0,0 +1,5 @@ +x = "alphaBETA" /*define string to a REXX variable*/ +parse upper var x y /*uppercase X and store it───► Y*/ +parse lower var x z /*lowercase X " " " ───► Z*/ + + /*Some REXXes don't support the LOWER option for the PARSE command.*/ diff --git a/Task/String-case/REXX/string-case-3.rexx b/Task/String-case/REXX/string-case-3.rexx new file mode 100644 index 0000000000..adc3e4f5f2 --- /dev/null +++ b/Task/String-case/REXX/string-case-3.rexx @@ -0,0 +1,6 @@ +x = 'alphaBETA' /*define string to a REXX variable*/ +y = upper(x) /*uppercase X and store it───► Y*/ +z = lower(x) /*lowercase X " " " ───► Z*/ + + /*Some REXXes don't support the UPPER and */ + /* LOWER BIFs (built-in functions). */ diff --git a/Task/String-case/REXX/string-case-4.rexx b/Task/String-case/REXX/string-case-4.rexx new file mode 100644 index 0000000000..e5e3f5cd20 --- /dev/null +++ b/Task/String-case/REXX/string-case-4.rexx @@ -0,0 +1,5 @@ +x = "alphaBETA" /*define string to a REXX variable*/ +y=x; upper y /*uppercase X and store it───► Y*/ +parse lower var x z /*lowercase Y " " " ───► Z*/ + + /*Some REXXes don't support the LOWER option for the PARSE command.*/ diff --git a/Task/String-case/REXX/string-case-5.rexx b/Task/String-case/REXX/string-case-5.rexx new file mode 100644 index 0000000000..c65fe4a1b0 --- /dev/null +++ b/Task/String-case/REXX/string-case-5.rexx @@ -0,0 +1,17 @@ +/*REXX pgm capitalizes each word in string, maintains imbedded blanks.*/ +x= "alef bet gimel dalet he vav zayin het tet yod kaf lamed mem nun samekh", + "ayin pe tzadi qof resh shin tav." /*"old" spelling Hebrew letters. */ +y= capitalize(x) /*capitalize each word in string.*/ +say x /*show original string of words. */ +say y /*show the capitalized words. */ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────CAPITALIZE subroutine──────────────*/ +capitalize: procedure; parse arg z; $=' 'z /*prefix with a blank.*/ +abc = "abcdefghijklmnopqrstuvwxyz" /*define all lowercase letters. */ + + do j=1 for 26 /*process each letter in alphabet*/ + _=' 'substr(abc,j,1); _U=_; upper _U /*get a lower and upper letter. */ + $ = changestr(_, $, _U) /*maybe capitalize some word(s). */ + end /*j*/ + +return substr($,2) /*capitalized words, -1st blank.*/ diff --git a/Task/String-case/REXX/string-case-6.rexx b/Task/String-case/REXX/string-case-6.rexx new file mode 100644 index 0000000000..4fa6939cb1 --- /dev/null +++ b/Task/String-case/REXX/string-case-6.rexx @@ -0,0 +1,9 @@ +/*REXX pgm swaps letter case of a string: lower──►upper & upper──►lower.*/ +abc = "abcdefghijklmnopqrstuvwxyz" /*define all the lowercase letters*/ +abcU = translate(abc) /* " " " uppercase " */ + +x = 'alphaBETA' /*define string to a REXX variable*/ +y = translate(x,abc||abcU,abcU||abc) /*swap case of X store it ───► Y*/ +say x +say y + /*stick a fork in it, we're done.*/ diff --git a/Task/String-case/REXX/string-case-7.rexx b/Task/String-case/REXX/string-case-7.rexx new file mode 100644 index 0000000000..f0b966c67f --- /dev/null +++ b/Task/String-case/REXX/string-case-7.rexx @@ -0,0 +1,11 @@ +x='alphaBETA'; Say ' x='||x + Say 'three ways to uppercase' +u1=translate(x); Say ' u1='u1 +u2=upper(x); Say ' u2='u2 +parse upper var x u3; Say ' u3='u3 + +abc ='abcdefghijklmnopqrstuvwxyz' +abcu=translate(abc); Say 'three ways to lowercase' +l1=translate(x,abc,abcu); Say ' l1='l1 +l2=lower(x); Say ' l2='l2 +parse lower var x l3; Say ' l3='l3 diff --git a/Task/String-case/REXX/string-case-8.rexx b/Task/String-case/REXX/string-case-8.rexx new file mode 100644 index 0000000000..ec10c3f5de --- /dev/null +++ b/Task/String-case/REXX/string-case-8.rexx @@ -0,0 +1,8 @@ +uppercase: /*courtesy Gerard Schildberger */ + return translate(changestr("ß",translate(arg(1),'ÄÖÜ',"äöü"),'SS')) + +uppercase2: Procedure +Parse Arg a + a=translate(arg(1),'ÄÖÜ',"äöü") /* translate lowercase umlaute */ + a=changestr("ß",a,'SS') /* replace ß with SS */ + return translate(a) /* translate lowercase letters */ diff --git a/Task/String-case/Raven/string-case.raven b/Task/String-case/Raven/string-case.raven new file mode 100644 index 0000000000..ec44f26822 --- /dev/null +++ b/Task/String-case/Raven/string-case.raven @@ -0,0 +1,2 @@ +'alphaBETA' upper +'alhpaBETA' lower diff --git a/Task/String-case/Retro/string-case.retro b/Task/String-case/Retro/string-case.retro new file mode 100644 index 0000000000..c3305ffb86 --- /dev/null +++ b/Task/String-case/Retro/string-case.retro @@ -0,0 +1,3 @@ +with strings' +"alphaBETA" toUpper puts +"alphaBETA" toLower puts diff --git a/Task/String-case/Ruby/string-case.rb b/Task/String-case/Ruby/string-case.rb new file mode 100644 index 0000000000..84d20a4877 --- /dev/null +++ b/Task/String-case/Ruby/string-case.rb @@ -0,0 +1,5 @@ +"alphaBETA".downcase # => "alphabeta" +"alphaBETA".upcase # => "ALPHABETA" + +"alphaBETA".swapcase # => "ALPHAbeta" +"alphaBETA".capitalize # => "Alphabeta" diff --git a/Task/String-case/Run-BASIC/string-case.run b/Task/String-case/Run-BASIC/string-case.run new file mode 100644 index 0000000000..623adb7125 --- /dev/null +++ b/Task/String-case/Run-BASIC/string-case.run @@ -0,0 +1,5 @@ +a$ ="alphaBETA" + +print a$ '=> alphaBETA +print upper$(a$) '=> ALPHABETA +print lower$(a$) '=> alphabeta diff --git a/Task/String-case/SNOBOL4/string-case.sno b/Task/String-case/SNOBOL4/string-case.sno new file mode 100644 index 0000000000..c432e915c5 --- /dev/null +++ b/Task/String-case/SNOBOL4/string-case.sno @@ -0,0 +1,26 @@ + define('uc(str)') :(uc_end) +uc uc = replace(str,&lcase,&ucase) :(return) +uc_end + + define('lc(str)') :(lc_end) +lc lc = replace(str,&ucase,&lcase) :(return) +lc_end + + define('ucfirst(str)ch') :(ucfirst_end) +ucfirst str len(1) . ch = uc(ch) + ucfirst = str :(return) +ucfirst_end + + define('swapc(str)') :(swapc_end) +swapc str = replace(str,&ucase &lcase, &lcase &ucase) + swapc = str :(return) +swapc_end + +* # Test and display + str = 'alphaBETA' + output = str + output = lc(str) + output = uc(str) + output = ucfirst(str) + output = swapc(str) +end diff --git a/Task/String-case/SQL/string-case.sql b/Task/String-case/SQL/string-case.sql new file mode 100644 index 0000000000..db46a2e1f7 --- /dev/null +++ b/Task/String-case/SQL/string-case.sql @@ -0,0 +1,4 @@ +declare @s varchar(10) +set @s = 'alphaBETA' +print upper(@s) +print lower(@s) diff --git a/Task/String-case/Scala/string-case.scala b/Task/String-case/Scala/string-case.scala new file mode 100644 index 0000000000..503ca47667 --- /dev/null +++ b/Task/String-case/Scala/string-case.scala @@ -0,0 +1,5 @@ +val s="alphaBETA" +println(s.toUpperCase) //-> ALPHABETA +println(s.toLowerCase) //-> alphabeta +println(s.capitalize) //-> AlphaBETA +println(s.reverse) //-> ATEBahpla diff --git a/Task/String-case/Scheme/string-case-1.ss b/Task/String-case/Scheme/string-case-1.ss new file mode 100644 index 0000000000..c3851fe6f0 --- /dev/null +++ b/Task/String-case/Scheme/string-case-1.ss @@ -0,0 +1,3 @@ +(define s "alphaBETA") +(list->string (map char-upcase (string->list s))) +(list->string (map char-downcase (string->list s))) diff --git a/Task/String-case/Scheme/string-case-2.ss b/Task/String-case/Scheme/string-case-2.ss new file mode 100644 index 0000000000..b3569ff1f5 --- /dev/null +++ b/Task/String-case/Scheme/string-case-2.ss @@ -0,0 +1,7 @@ +> (define s "alphaBETA gammaDELTA") +> (string-upcase s) ;; turn all into upper case +"ALPHABETA GAMMADELTA" +> (string-downcase s) ;; turn all into lower case +"alphabeta gammadelta" +> (string-titlecase s) ;; capitalise start of each word +"Alphabeta Gammadelta" diff --git a/Task/String-case/Sed/string-case-1.sed b/Task/String-case/Sed/string-case-1.sed new file mode 100644 index 0000000000..0eab0f8c75 --- /dev/null +++ b/Task/String-case/Sed/string-case-1.sed @@ -0,0 +1,2 @@ +echo "alphaBETA" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' +echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' diff --git a/Task/String-case/Sed/string-case-2.sed b/Task/String-case/Sed/string-case-2.sed new file mode 100644 index 0000000000..58838a9e10 --- /dev/null +++ b/Task/String-case/Sed/string-case-2.sed @@ -0,0 +1,2 @@ +# Invert case +echo "alphaBETA" | sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/' diff --git a/Task/String-case/Sed/string-case-3.sed b/Task/String-case/Sed/string-case-3.sed new file mode 100644 index 0000000000..212e8574c9 --- /dev/null +++ b/Task/String-case/Sed/string-case-3.sed @@ -0,0 +1,6 @@ +# to uppercase +$ echo alphaBETA | sed 's/.*/\U&/' +ALPHABETA +# to lowercase +$ echo alphaBETA | sed 's/.*/\L&/' +alphabeta diff --git a/Task/String-case/Slate/string-case.slate b/Task/String-case/Slate/string-case.slate new file mode 100644 index 0000000000..f89a6b59fe --- /dev/null +++ b/Task/String-case/Slate/string-case.slate @@ -0,0 +1,2 @@ +'alphaBETA' toLowercase. +'alphaBETA' toUppercase. diff --git a/Task/String-case/Smalltalk/string-case-1.st b/Task/String-case/Smalltalk/string-case-1.st new file mode 100644 index 0000000000..d3f81c6d8d --- /dev/null +++ b/Task/String-case/Smalltalk/string-case-1.st @@ -0,0 +1,2 @@ +'ALPHAbeta' asUppercase "->'ALPHABETA' " +'ALPHAbeta' asLowercase "-> 'alphabeta' " diff --git a/Task/String-case/Smalltalk/string-case-2.st b/Task/String-case/Smalltalk/string-case-2.st new file mode 100644 index 0000000000..cd4dd541af --- /dev/null +++ b/Task/String-case/Smalltalk/string-case-2.st @@ -0,0 +1 @@ +'alphabeta' asUppercaseFirst "-> 'Alphabeta' " diff --git a/Task/String-case/Smalltalk/string-case-3.st b/Task/String-case/Smalltalk/string-case-3.st new file mode 100644 index 0000000000..67c60d8d49 --- /dev/null +++ b/Task/String-case/Smalltalk/string-case-3.st @@ -0,0 +1 @@ +'ĥåçýджк' asUppercase "-> 'ĤÅÇÝДЖК' diff --git a/Task/String-case/Standard-ML/string-case.ml b/Task/String-case/Standard-ML/string-case.ml new file mode 100644 index 0000000000..81ce32d5a3 --- /dev/null +++ b/Task/String-case/Standard-ML/string-case.ml @@ -0,0 +1,2 @@ +val strupr = String.map Char.toUpper; +val strlwr = String.map Char.toLower; diff --git a/Task/String-case/TI-83-BASIC/string-case.ti-83 b/Task/String-case/TI-83-BASIC/string-case.ti-83 new file mode 100644 index 0000000000..7306e81b4b --- /dev/null +++ b/Task/String-case/TI-83-BASIC/string-case.ti-83 @@ -0,0 +1,18 @@ +:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"→Str9 +:"abcdefghijklmnopqrstuvwxyz"→Str0 +:Input ">",Str1 +:":"+Str1+":"→Str1 +:Prompt U +:If U:Then +:For(I,2,length(Str1)) +:If inString(Str0,sub(Str1,I,1)) and sub(Str1,I,1)≠":" +:sub(Str1,1,I-1)+sub(Str9,inString(Str0,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 +:End +:Else +:For(I,2,length(Str1)) +:If inString(Str9,sub(Str1,I,1)) and sub(Str1,I,1)≠":" +:sub(Str1,1,I-1)+sub(Str0,inString(Str9,sub(Str1,I,1)),1)+sub(Str1,I+1,length(Str1)-I)→Str1 +:End +:End +:sub(Str1,2,length(Str1)-2)→Str1 +:Pause Str1 diff --git a/Task/String-case/TUSCRIPT/string-case.tuscript b/Task/String-case/TUSCRIPT/string-case.tuscript new file mode 100644 index 0000000000..8efadeaaf6 --- /dev/null +++ b/Task/String-case/TUSCRIPT/string-case.tuscript @@ -0,0 +1,8 @@ +$$ MODE TUSCRIPT,{} +string="alphaBETA" +lowercase =EXCHANGE(string," {&a} {-0-} ") +uppercase1=EXCHANGE(string," {&a} {-0+} ") +uppercase2=CAPS (string) +PRINT lowercase +PRINT uppercase1 +PRINT uppercase2 diff --git a/Task/String-case/Tcl/string-case.tcl b/Task/String-case/Tcl/string-case.tcl new file mode 100644 index 0000000000..5ca974083c --- /dev/null +++ b/Task/String-case/Tcl/string-case.tcl @@ -0,0 +1,30 @@ +set string alphaBETA + +# three built-in case conversion commands +string toupper $string ;# ==> ALPHABETA +string tolower $string ;# ==> alphabeta +string totitle $string ;# ==> Alphabeta + +# not built-in +proc swapcase {s} { + foreach char [split $s ""] { + if {$char eq [set CHAR [string toupper $char]]} { + append new [string tolower $char] + } else { + append new $CHAR + } + } + return $new +} +swapcase $string ;# ==> ALPHAbeta + +# better performance, but English alphabet only +proc swapcase_en {s} { + string map { + a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z + A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z + } $s +} + +swapcase Père ;# ==> pÈRE +swapcase_en Père ;# ==> pèRE diff --git a/Task/String-case/UNIX-Shell/string-case-1.sh b/Task/String-case/UNIX-Shell/string-case-1.sh new file mode 100644 index 0000000000..75f645b9c2 --- /dev/null +++ b/Task/String-case/UNIX-Shell/string-case-1.sh @@ -0,0 +1,2 @@ +echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA +echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta diff --git a/Task/String-case/UNIX-Shell/string-case-2.sh b/Task/String-case/UNIX-Shell/string-case-2.sh new file mode 100644 index 0000000000..53e0ddb670 --- /dev/null +++ b/Task/String-case/UNIX-Shell/string-case-2.sh @@ -0,0 +1,2 @@ +echo alphaBETA | tr a-z A-Z # => ALPHABETA +echo alphaBETA | tr A-Z a-z # => alphabeta diff --git a/Task/String-case/UNIX-Shell/string-case-3.sh b/Task/String-case/UNIX-Shell/string-case-3.sh new file mode 100644 index 0000000000..3e20c5d3e7 --- /dev/null +++ b/Task/String-case/UNIX-Shell/string-case-3.sh @@ -0,0 +1,4 @@ +s="alphaBETA" +echo ${s^^} # => ALPHABETA +echo ${s,,} # => alphabeta +echo ${s^} # => AlphaBETA diff --git a/Task/String-case/UNIX-Shell/string-case-4.sh b/Task/String-case/UNIX-Shell/string-case-4.sh new file mode 100644 index 0000000000..7e9f4101ec --- /dev/null +++ b/Task/String-case/UNIX-Shell/string-case-4.sh @@ -0,0 +1,3 @@ +s="alphaBETA" +echo ${s:u} # => ALPHABETA +echo ${s:l} # => alphabeta diff --git a/Task/String-case/Ursala/string-case.ursala b/Task/String-case/Ursala/string-case.ursala new file mode 100644 index 0000000000..bd2c2e377e --- /dev/null +++ b/Task/String-case/Ursala/string-case.ursala @@ -0,0 +1,8 @@ +#import std + +to_upper = * -:~& ~=`A-~p letters +to_lower = * -:~& ~=`A-~rlp letters + +#show+ + +examples = diff --git a/Task/String-case/VBScript/string-case.vbscript b/Task/String-case/VBScript/string-case.vbscript new file mode 100644 index 0000000000..08da4b0b63 --- /dev/null +++ b/Task/String-case/VBScript/string-case.vbscript @@ -0,0 +1,3 @@ +Dim MyWord +MyWord = UCase("alphaBETA") ' Returns "ALPHABETA" +MyWord = LCase("alphaBETA") ' Returns "alphabeta" diff --git a/Task/String-case/Vala/string-case.vala b/Task/String-case/Vala/string-case.vala new file mode 100644 index 0000000000..0b34edbf8e --- /dev/null +++ b/Task/String-case/Vala/string-case.vala @@ -0,0 +1,5 @@ +string s = "alphaBeta"; +// stores ALPHABETA to string +string s_upper = s.up(); +// stores alphabeta to string +string s_lower = s.down(); diff --git a/Task/String-case/Vedit-macro-language/string-case.vedit b/Task/String-case/Vedit-macro-language/string-case.vedit new file mode 100644 index 0000000000..cf356ada80 --- /dev/null +++ b/Task/String-case/Vedit-macro-language/string-case.vedit @@ -0,0 +1,4 @@ +#1 = CP +IT("alphaBETA") +Case_Upper_Block(#1, CP) +Case_Lower_Block(#1, CP) diff --git a/Task/String-case/Visual-Basic-.NET/string-case.visual b/Task/String-case/Visual-Basic-.NET/string-case.visual new file mode 100644 index 0000000000..10cde0efea --- /dev/null +++ b/Task/String-case/Visual-Basic-.NET/string-case.visual @@ -0,0 +1,8 @@ +' Define 's' +Dim s AS String = "alphaBETA" + +' Change 's' to Upper Case. +s = s.ToUpper() + +' Change 's' to Lower Case. +s = s.ToLower() diff --git a/Task/String-case/XPL0/string-case.xpl0 b/Task/String-case/XPL0/string-case.xpl0 new file mode 100644 index 0000000000..176fd98011 --- /dev/null +++ b/Task/String-case/XPL0/string-case.xpl0 @@ -0,0 +1,18 @@ +string 0; \use zero-terminated string convention +include c:\cxpl\stdlib; \ToUpper, ToLower, and 'code' declarations + +proc StrToUpper(S); \Convert string to uppercase characters +char S; +while S(0) do [S(0):= ToUpper(S(0)); S:=S+1]; + +proc StrToLower(S); \Convert string to lowercase characters +char S; +while S(0) do [S(0):= ToLower(S(0)); S:=S+1]; + +char Str; +[Str:= "alphaBETA"; +StrToUpper(Str); +Text(0, Str); CrLf(0); +StrToLower(Str); +Text(0, Str); CrLf(0); +] diff --git a/Task/String-comparison/0DESCRIPTION b/Task/String-comparison/0DESCRIPTION new file mode 100644 index 0000000000..69ff9fc158 --- /dev/null +++ b/Task/String-comparison/0DESCRIPTION @@ -0,0 +1,15 @@ +{{basic data operation}}[[Category:Basic language learning]]The task is to demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: + +* Comparing two strings for exact equality +* Comparing two strings for inequality (i.e., the inverse of exact equality) +* Comparing two strings to see if one is lexically ordered before than the other +* Comparing two strings to see if one is lexically ordered after than the other +* How to achieve both case sensitive comparisons and case insensitive comparisons within the language +* How the language handles comparison of numeric strings if these are not treated lexically +* Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. + +Here "generic/polymorphic" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance. In contrast, a "coercive/allomorphic" comparison function or operator has fixed string-comparison semantics regardless of the argument type; instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can, and the operator simply fails if the arguments cannot be viewed somehow as strings. A language may have one or both of these kinds of operators; see the Perl 6 entry for an example of a language with both kinds of operators. + +'''See also:''' +* [[Integer comparison]] +* [[Character matching]] diff --git a/Task/String-comparison/1META.yaml b/Task/String-comparison/1META.yaml new file mode 100644 index 0000000000..a16ddc894f --- /dev/null +++ b/Task/String-comparison/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic Data Operations diff --git a/Task/String-comparison/AWK/string-comparison.awk b/Task/String-comparison/AWK/string-comparison.awk new file mode 100644 index 0000000000..d6c1bf8002 --- /dev/null +++ b/Task/String-comparison/AWK/string-comparison.awk @@ -0,0 +1,17 @@ +BEGIN { + a="BALL" + b="BELL" + + if (a == b) { print "The strings are equal" } + if (a != b) { print "The strings are not equal" } + if (a > b) { print "The first string is lexically after than the second" } + if (a < b) { print "The first string is lexically before than the second" } + if (a >= b) { print "The first string is not lexically before than the second" } + if (a <= b) { print "The first string is not lexically after than the second" } + + # to make a case insensitive comparison convert both strings to the same lettercase: + a="BALL" + b="ball" + if (tolower(a) == tolower(b)) { print "The first and second string are the same disregarding letter case" } + +} diff --git a/Task/String-comparison/BASIC/string-comparison-1.basic b/Task/String-comparison/BASIC/string-comparison-1.basic new file mode 100644 index 0000000000..a9a0e16784 --- /dev/null +++ b/Task/String-comparison/BASIC/string-comparison-1.basic @@ -0,0 +1,9 @@ +10 LET "A$="BELL" +20 LET B$="BELT" +30 IF A$ = B$ THEN PRINT "THE STRINGS ARE EQUAL": REM TEST FOR EQUALITY +40 IF A$ <> B$ THEN PRINT "THE STRINGS ARE NOT EQUAL": REM TEST FOR INEQUALITY +50 IF A$ > B$ THEN PRINT A$;" IS LEXICALLY HIGHER THAN ";B$: REM TEST FOR LEXICALLY HIGHER +60 IF A$ < B$ THEN PRINT A$;" IS LEXICALLY LOWER THAN ";B$: REM TEST FOR LEXICALLY LOWER +70 IF A$ <= B$ THEN PRINT A$;" IS NOT LEXICALLY HIGHER THAN ";B$ +80 IF A$ >= B$ THEN PRINT A$;" IS NOT LEXICALLY LOWER THAN ";B$ +90 END diff --git a/Task/String-comparison/BASIC/string-comparison-2.basic b/Task/String-comparison/BASIC/string-comparison-2.basic new file mode 100644 index 0000000000..098132dca3 --- /dev/null +++ b/Task/String-comparison/BASIC/string-comparison-2.basic @@ -0,0 +1,3 @@ +10 LET A$="BELT" +20 LET B$="belt" +30 IF UPPER$(A$)=UPPER$(B$) THEN PRINT "Disregarding lettercase, the strings are the same." diff --git a/Task/String-comparison/Burlesque/string-comparison.blq b/Task/String-comparison/Burlesque/string-comparison.blq new file mode 100644 index 0000000000..f93522638e --- /dev/null +++ b/Task/String-comparison/Burlesque/string-comparison.blq @@ -0,0 +1,8 @@ +blsq ) "abc""abc"== +1 +blsq ) "abc""abc"!= +0 +blsq ) "abc""Abc"cm +1 +blsq ) "ABC""Abc"cm +-1 diff --git a/Task/String-comparison/D/string-comparison.d b/Task/String-comparison/D/string-comparison.d new file mode 100644 index 0000000000..f969b9cc3f --- /dev/null +++ b/Task/String-comparison/D/string-comparison.d @@ -0,0 +1,23 @@ +import std.stdio, std.string, std.algorithm; + +void main() { + auto s = "abcd"; + + /* Comparing two strings for exact equality */ + assert (s == "abcd"); // same object + + /* Comparing two strings for inequality */ + assert(s != "ABCD"); // different objects + + /* Comparing the lexical order of two strings; + -1 means smaller, 0 means equal, 1 means larger */ + + assert(s.icmp("Bcde") == -1); // case insensitive + assert(s.cmp("Bcde") == 1); // case sensitive + + assert(s.icmp("Aabc") == 1); // case insensitive + assert(s.cmp("Aabc") == 1); // case sensitive + + assert(s.icmp("ABCD") == 0); // case insensitive + assert(s.cmp("ABCD") == 1); // case sensitive +} diff --git a/Task/String-comparison/J/string-comparison-1.j b/Task/String-comparison/J/string-comparison-1.j new file mode 100644 index 0000000000..a2d28f0edf --- /dev/null +++ b/Task/String-comparison/J/string-comparison-1.j @@ -0,0 +1,6 @@ +eq=: -: NB. equal +ne=: -.@-: NB. not equal +gt=: {.@/:@,&boxopen *. ne NB. lexically greater than +lt=: -.@{.@/:@,&boxopen *. ne NB. lexically less than +ge=: {.@/:@,&boxopen +. eq NB. lexically greater than or equal to +le=: -.@{.@/:@,&boxopen NB. lexically less than or equal to diff --git a/Task/String-comparison/J/string-comparison-2.j b/Task/String-comparison/J/string-comparison-2.j new file mode 100644 index 0000000000..2bff71785f --- /dev/null +++ b/Task/String-comparison/J/string-comparison-2.j @@ -0,0 +1,6 @@ + 'ball' (eq , ne , gt , lt , ge , le) 'bell' +0 1 0 1 0 1 + 'ball' (eq , ne , gt , lt , ge , le) 'ball' +1 0 0 0 1 1 + 'YUP' (eq , ne , gt , lt , ge , le) 'YEP' +0 1 1 0 1 0 diff --git a/Task/String-comparison/NetRexx/string-comparison.netrexx b/Task/String-comparison/NetRexx/string-comparison.netrexx new file mode 100644 index 0000000000..d2b3d6a8e8 --- /dev/null +++ b/Task/String-comparison/NetRexx/string-comparison.netrexx @@ -0,0 +1,23 @@ +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/Perl-6/string-comparison.pl6 b/Task/String-comparison/Perl-6/string-comparison.pl6 new file mode 100644 index 0000000000..97c797742b --- /dev/null +++ b/Task/String-comparison/Perl-6/string-comparison.pl6 @@ -0,0 +1,36 @@ +sub compare($a,$b) { + my $A = "{$a.WHAT.^name} '$a'"; + my $B = "{$b.WHAT.^name} '$b'"; + + if $a eq $b { say "$A and $B are lexically equal" } + if $a ne $b { say "$A and $B are not lexically equal" } + + if $a gt $b { say "$A is lexically after $B" } + if $a lt $b { say "$A is lexically before than $B" } + + if $a ge $b { say "$A is not lexically before $B" } + if $a le $b { say "$A is not lexically after $B" } + + if $a === $b { say "$A and $B are identical objects" } + if $a !=== $b { say "$A and $B are not identical objects" } + + if $a eqv $b { say "$A and $B are generically equal" } + if $a !eqv $b { say "$A and $B are not generically equal" } + + if $a before $b { say "$A is generically after $B" } + if $a after $b { say "$A is generically before $B" } + + if $a !after $b { say "$A is not generically before $B" } + if $a !before $b { say "$A is not generically after $B" } + + say "The lexical relationship of $A and $B is { $a leg $b }" if $a ~~ Stringy; + say "The generic relationship of $A and $B is { $a cmp $b }"; + say "The numeric relationship of $A and $B is { $a <=> $b }" if $a ~~ Numeric; + say ''; +} + +compare 'YUP', 'YUP'; +compare 'BALL', 'BELL'; +compare 24, 123; +compare 5.1, 5; +compare 5.1e0, 5 + 1/10; diff --git a/Task/String-comparison/Python/string-comparison.py b/Task/String-comparison/Python/string-comparison.py new file mode 100644 index 0000000000..44071cd6cb --- /dev/null +++ b/Task/String-comparison/Python/string-comparison.py @@ -0,0 +1,17 @@ +def compare(a, b): + print("\n%r is of type %r and %r is of type %r" + % (a, type(a), b, type(b))) + if a < b: print('%r is strictly less than %r' % (a, b)) + if a <= b: print('%r is less than or equal to %r' % (a, b)) + if a > b: print('%r is strictly greater than %r' % (a, b)) + if a >= b: print('%r is greater than or equal to %r' % (a, b)) + if a == b: print('%r is equal to %r' % (a, b)) + if a != b: print('%r is not equal to %r' % (a, b)) + if a is b: print('%r has object identity with %r' % (a, b)) + if a is not b: print('%r has negated object identity with %r' % (a, b)) + +compare('YUP', 'YUP') +compare('BALL', 'BELL') +compare('24', '123') +compare(24, 123) +compare(5.0, 5) diff --git a/Task/String-comparison/REXX/string-comparison.rexx b/Task/String-comparison/REXX/string-comparison.rexx new file mode 100644 index 0000000000..2ed44fa537 --- /dev/null +++ b/Task/String-comparison/REXX/string-comparison.rexx @@ -0,0 +1,23 @@ +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/Racket/string-comparison.rkt b/Task/String-comparison/Racket/string-comparison.rkt new file mode 100644 index 0000000000..ecfcd400ea --- /dev/null +++ b/Task/String-comparison/Racket/string-comparison.rkt @@ -0,0 +1,16 @@ +#lang racket + +;; Comparing two strings for exact equality +(string=? "foo" "foo") + +;; Comparing two strings for inequality +(not (string=? "foo" "bar")) + +;; Comparing two strings to see if one is lexically ordered before than the other +(string? "def" "abc") + +;; How to achieve both case sensitive comparisons and case insensitive comparisons within the language +(string-ci=? "foo" "FOO") diff --git a/Task/String-comparison/Run-BASIC/string-comparison.run b/Task/String-comparison/Run-BASIC/string-comparison.run new file mode 100644 index 0000000000..c6ee266e0b --- /dev/null +++ b/Task/String-comparison/Run-BASIC/string-comparison.run @@ -0,0 +1,9 @@ +a$ = "dog" +b$ = "cat" +if a$ = b$ then print "the strings are equal" ' test for equalitY +if a$ <> b$ then print "the strings are not equal" ' test for inequalitY +if a$ > b$ then print a$;" is lexicallY higher than ";b$ ' test for lexicallY higher +if a$ < b$ then print a$;" is lexicallY lower than ";b$ ' test for lexicallY lower +if a$ <= b$ then print a$;" is not lexicallY higher than ";b$ +if a$ >= b$ then print a$;" is not lexicallY lower than ";b$ +end diff --git a/Task/String-comparison/Tcl/string-comparison-1.tcl b/Task/String-comparison/Tcl/string-comparison-1.tcl new file mode 100644 index 0000000000..4d72291a76 --- /dev/null +++ b/Task/String-comparison/Tcl/string-comparison-1.tcl @@ -0,0 +1,6 @@ +if {$a eq $b} { + puts "the strings are equal" +} +if {$a ne $b} { + puts "the strings are not equal" +} diff --git a/Task/String-comparison/Tcl/string-comparison-2.tcl b/Task/String-comparison/Tcl/string-comparison-2.tcl new file mode 100644 index 0000000000..b86da6fa2a --- /dev/null +++ b/Task/String-comparison/Tcl/string-comparison-2.tcl @@ -0,0 +1,6 @@ +if {[string compare $a $b] < 0} { + puts "first string lower than second" +} +if {[string compare $a $b] > 0} { + puts "first string higher than second" +} diff --git a/Task/String-comparison/Tcl/string-comparison-3.tcl b/Task/String-comparison/Tcl/string-comparison-3.tcl new file mode 100644 index 0000000000..94624fed9c --- /dev/null +++ b/Task/String-comparison/Tcl/string-comparison-3.tcl @@ -0,0 +1,3 @@ +if {[string equal -length 3 $x "abc123"]} { + puts "first three characters are equal" +} diff --git a/Task/String-comparison/UNIX-Shell/string-comparison.sh b/Task/String-comparison/UNIX-Shell/string-comparison.sh new file mode 100644 index 0000000000..17dd300f52 --- /dev/null +++ b/Task/String-comparison/UNIX-Shell/string-comparison.sh @@ -0,0 +1,18 @@ +#!/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/0DESCRIPTION b/Task/String-concatenation/0DESCRIPTION new file mode 100644 index 0000000000..299c93fdd7 --- /dev/null +++ b/Task/String-concatenation/0DESCRIPTION @@ -0,0 +1,3 @@ +{{basic data operation}}Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. + +To illustrate the operation, show the content of the variables. diff --git a/Task/String-concatenation/1META.yaml b/Task/String-concatenation/1META.yaml new file mode 100644 index 0000000000..3bdc51ea57 --- /dev/null +++ b/Task/String-concatenation/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Basic language learning diff --git a/Task/String-concatenation/ALGOL-68/string-concatenation.alg b/Task/String-concatenation/ALGOL-68/string-concatenation.alg new file mode 100644 index 0000000000..11e2e42195 --- /dev/null +++ b/Task/String-concatenation/ALGOL-68/string-concatenation.alg @@ -0,0 +1,4 @@ +STRING s := "hello"; +print ((s + " literal", new line)); +STRING s1 := s + " literal"; +print ((s1, new line)) diff --git a/Task/String-concatenation/AWK/string-concatenation.awk b/Task/String-concatenation/AWK/string-concatenation.awk new file mode 100644 index 0000000000..004eb236b0 --- /dev/null +++ b/Task/String-concatenation/AWK/string-concatenation.awk @@ -0,0 +1,6 @@ +BEGIN { + s = "hello" + print s " literal" + s1 = s " literal" + print s1 +} diff --git a/Task/String-concatenation/ActionScript/string-concatenation.as b/Task/String-concatenation/ActionScript/string-concatenation.as new file mode 100644 index 0000000000..9c87e9d68a --- /dev/null +++ b/Task/String-concatenation/ActionScript/string-concatenation.as @@ -0,0 +1,13 @@ +package +{ + public class Str + { + public static function main():void + { + var s:String = "hello"; + trace(s + " literal"); + var s2:String = s + " literal"; + trace(s2); + } + } +} diff --git a/Task/String-concatenation/Ada/string-concatenation.ada b/Task/String-concatenation/Ada/string-concatenation.ada new file mode 100644 index 0000000000..5a73b77657 --- /dev/null +++ b/Task/String-concatenation/Ada/string-concatenation.ada @@ -0,0 +1,12 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure String_Concatenation is + S : String := "Hello"; +begin + Put_Line (S & " literal"); + declare + S1 : String := S & " literal"; + begin + Put_Line (S1); + end; +end String_Concatenation; diff --git a/Task/String-concatenation/AutoHotkey/string-concatenation.ahk b/Task/String-concatenation/AutoHotkey/string-concatenation.ahk new file mode 100644 index 0000000000..9d0a5ebccb --- /dev/null +++ b/Task/String-concatenation/AutoHotkey/string-concatenation.ahk @@ -0,0 +1,4 @@ +s := "hello" +Msgbox, %s% +s1 := s . " literal" ;the . is optional +Msgbox, %s1% diff --git a/Task/String-concatenation/BASIC/string-concatenation.basic b/Task/String-concatenation/BASIC/string-concatenation.basic new file mode 100644 index 0000000000..2d77564ffb --- /dev/null +++ b/Task/String-concatenation/BASIC/string-concatenation.basic @@ -0,0 +1,4 @@ +s$ = "hello" +print s$;" literal" 'or s$ + " literal" +s2$ = s$ + " literal" +print s2$ diff --git a/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc b/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc new file mode 100644 index 0000000000..43cff30ba9 --- /dev/null +++ b/Task/String-concatenation/BBC-BASIC/string-concatenation.bbc @@ -0,0 +1,4 @@ + stringvar1$ = "Hello," + stringvar2$ = stringvar1$ + " world!" + PRINT "Variable 1 is """ stringvar1$ """" + PRINT "Variable 2 is """ stringvar2$ """" diff --git a/Task/String-concatenation/Batch-File/string-concatenation.bat b/Task/String-concatenation/Batch-File/string-concatenation.bat new file mode 100644 index 0000000000..abc867b29a --- /dev/null +++ b/Task/String-concatenation/Batch-File/string-concatenation.bat @@ -0,0 +1,3 @@ +set string=Hello +echo %string% World +set string2=%string% World diff --git a/Task/String-concatenation/Bracmat/string-concatenation.bracmat b/Task/String-concatenation/Bracmat/string-concatenation.bracmat new file mode 100644 index 0000000000..ba2f73ed65 --- /dev/null +++ b/Task/String-concatenation/Bracmat/string-concatenation.bracmat @@ -0,0 +1,4 @@ +"Hello ":?var1 +& "World":?var2 +& str$(!var1 !var2):?var12 +& put$("var1=" !var1 ", var2=" !var2 ", var12=" !var12 "\n") diff --git a/Task/String-concatenation/Burlesque/string-concatenation.blq b/Task/String-concatenation/Burlesque/string-concatenation.blq new file mode 100644 index 0000000000..97f98b132a --- /dev/null +++ b/Task/String-concatenation/Burlesque/string-concatenation.blq @@ -0,0 +1,2 @@ +blsq ) "Hello, ""world!"?+ +"Hello, world!" diff --git a/Task/String-concatenation/C++/string-concatenation.cpp b/Task/String-concatenation/C++/string-concatenation.cpp new file mode 100644 index 0000000000..6468ca7e07 --- /dev/null +++ b/Task/String-concatenation/C++/string-concatenation.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main() { + std::string s = "hello"; + std::cout << s << " literal" << std::endl; + std::string s2 = s + " literal"; + std::cout << s2 << std::endl; + return 0; +} diff --git a/Task/String-concatenation/C/string-concatenation.c b/Task/String-concatenation/C/string-concatenation.c new file mode 100644 index 0000000000..213b6ef06d --- /dev/null +++ b/Task/String-concatenation/C/string-concatenation.c @@ -0,0 +1,25 @@ +#include +#include +#include + +char *sconcat(const char *s1, const char *s2) +{ + char *s0 = malloc(strlen(s1)+strlen(s2)+1); + strcpy(s0, s1); + strcat(s0, s2); + return s0; +} + +int main() +{ + const char *s = "hello"; + char *s2; + + printf("%s literal\n", s); + /* or */ + printf("%s%s\n", s, " literal"); + + s2 = sconcat(s, " literal"); + puts(s2); + free(s2); +} diff --git a/Task/String-concatenation/Clojure/string-concatenation.clj b/Task/String-concatenation/Clojure/string-concatenation.clj new file mode 100644 index 0000000000..40f1831153 --- /dev/null +++ b/Task/String-concatenation/Clojure/string-concatenation.clj @@ -0,0 +1,5 @@ +(def a-str "abcd") +(println (str a-str "efgh")) + +(def a-new-str (str a-str "efgh")) +(println a-new-str) diff --git a/Task/String-concatenation/Common-Lisp/string-concatenation-1.lisp b/Task/String-concatenation/Common-Lisp/string-concatenation-1.lisp new file mode 100644 index 0000000000..9039c26b80 --- /dev/null +++ b/Task/String-concatenation/Common-Lisp/string-concatenation-1.lisp @@ -0,0 +1,5 @@ +(let ((s "hello")) + (format t "~a there!~%" s) + (let* ((s2 " there!") + (s (concatenate 'string s s2))) + (format t "~a~%" s))) diff --git a/Task/String-concatenation/Common-Lisp/string-concatenation-2.lisp b/Task/String-concatenation/Common-Lisp/string-concatenation-2.lisp new file mode 100644 index 0000000000..db0d09fc28 --- /dev/null +++ b/Task/String-concatenation/Common-Lisp/string-concatenation-2.lisp @@ -0,0 +1,4 @@ +(defparameter *s* "hello") +(print (concatenate 'string *s* " literal")) +(defparameter *s1* (concatenate 'string *s* " literal")) +(print *s1*) diff --git a/Task/String-concatenation/D/string-concatenation.d b/Task/String-concatenation/D/string-concatenation.d new file mode 100644 index 0000000000..4fb50c00f7 --- /dev/null +++ b/Task/String-concatenation/D/string-concatenation.d @@ -0,0 +1,8 @@ +import std.stdio; + +void main() { + string s = "hello"; + writeln(s ~ " world"); + auto s2 = s ~ " world"; + writeln(s2); +} diff --git a/Task/String-concatenation/DWScript/string-concatenation.dwscript b/Task/String-concatenation/DWScript/string-concatenation.dwscript new file mode 100644 index 0000000000..e48d1cbcc8 --- /dev/null +++ b/Task/String-concatenation/DWScript/string-concatenation.dwscript @@ -0,0 +1,5 @@ +var s1 := 'Hello'; +var s2 := s1 + ' World'; + +PrintLn(s1); +PrintLn(s2); diff --git a/Task/String-concatenation/Delphi/string-concatenation.delphi b/Task/String-concatenation/Delphi/string-concatenation.delphi new file mode 100644 index 0000000000..506acc2979 --- /dev/null +++ b/Task/String-concatenation/Delphi/string-concatenation.delphi @@ -0,0 +1,12 @@ +program Concat; + +{$APPTYPE CONSOLE} + +var + s1, s2: string; +begin + s1 := 'Hello'; + s2 := s1 + ' literal'; + WriteLn(s1); + WriteLn(s2); +end. diff --git a/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net b/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net new file mode 100644 index 0000000000..5fc0ad7eb5 --- /dev/null +++ b/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net @@ -0,0 +1,19 @@ +//to be compiled using dylan.NET v. 11.3.1.3 or later. +#refstdasm mscorlib.dll + +import System + +assembly concatex exe +ver 1.3.0.0 + +class public auto ansi Module1 + + method public static void main() + var s as string = "hello" + Console::Write(s) + Console::WriteLine(" literal") + var s2 as string = s + " literal" + Console::WriteLine(s2) + end method + +end class diff --git a/Task/String-concatenation/Erlang/string-concatenation.erl b/Task/String-concatenation/Erlang/string-concatenation.erl new file mode 100644 index 0000000000..8f9bdb1653 --- /dev/null +++ b/Task/String-concatenation/Erlang/string-concatenation.erl @@ -0,0 +1,4 @@ +S = "hello", +S1 = S ++ " literal", +io:format ("~s literal~n",[S]), +io:format ("~s~n",[S1]) diff --git a/Task/String-concatenation/Euphoria/string-concatenation.euphoria b/Task/String-concatenation/Euphoria/string-concatenation.euphoria new file mode 100644 index 0000000000..173e5d301b --- /dev/null +++ b/Task/String-concatenation/Euphoria/string-concatenation.euphoria @@ -0,0 +1,7 @@ +sequence s, s1 +s = "hello" +puts(1, s & " literal") +puts(1,'\n') +s1 = s & " literal" +print (1, s1)) +puts(1,'\n') diff --git a/Task/String-concatenation/Factor/string-concatenation.factor b/Task/String-concatenation/Factor/string-concatenation.factor new file mode 100644 index 0000000000..69187dafb4 --- /dev/null +++ b/Task/String-concatenation/Factor/string-concatenation.factor @@ -0,0 +1 @@ +"wake up" [ " sheeple" append print ] [ ", you sheep" append ] bi print diff --git a/Task/String-concatenation/Fantom/string-concatenation.fantom b/Task/String-concatenation/Fantom/string-concatenation.fantom new file mode 100644 index 0000000000..93e35088ca --- /dev/null +++ b/Task/String-concatenation/Fantom/string-concatenation.fantom @@ -0,0 +1,8 @@ +fansh> a := "abc" +abc +fansh> b := a + "def" +abcdef +fansh> a +abc +fansh> b +abcdef diff --git a/Task/String-concatenation/Forth/string-concatenation.fth b/Task/String-concatenation/Forth/string-concatenation.fth new file mode 100644 index 0000000000..44f09bbb4c --- /dev/null +++ b/Task/String-concatenation/Forth/string-concatenation.fth @@ -0,0 +1,4 @@ +s" hello" pad place +pad count type +s" there!" pad +place \ +place is called "append" on some Forths +pad count type diff --git a/Task/String-concatenation/Fortran/string-concatenation.f b/Task/String-concatenation/Fortran/string-concatenation.f new file mode 100644 index 0000000000..be60c39949 --- /dev/null +++ b/Task/String-concatenation/Fortran/string-concatenation.f @@ -0,0 +1,10 @@ +program StringConcatenation + +integer, parameter :: maxstringlength = 64 +character (maxstringlength) :: s1, s = "hello" + +print *,s // " literal" +s1 = trim(s) // " literal" +print *,s1 + +end program diff --git a/Task/String-concatenation/Gambas/string-concatenation.gambas b/Task/String-concatenation/Gambas/string-concatenation.gambas new file mode 100644 index 0000000000..fe1b6b1b05 --- /dev/null +++ b/Task/String-concatenation/Gambas/string-concatenation.gambas @@ -0,0 +1,4 @@ +DIM bestclub AS String +DIM myconcat AS String +bestclub = "Liverpool" +myconcat = bestclub & " Football Club" diff --git a/Task/String-concatenation/Go/string-concatenation.go b/Task/String-concatenation/Go/string-concatenation.go new file mode 100644 index 0000000000..5dc3520e36 --- /dev/null +++ b/Task/String-concatenation/Go/string-concatenation.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + // text assigned to a string variable + s := "hello" + + // output string variable + fmt.Println(s) + + // this output requested by original task descrption, although + // not really required by current wording of task description. + fmt.Println(s + " literal") + + // concatenate variable and literal, assign result to another string variable + s2 := s + " literal" + + // output second string variable + fmt.Println(s2) +} diff --git a/Task/String-concatenation/Golfscript/string-concatenation.golfscript b/Task/String-concatenation/Golfscript/string-concatenation.golfscript new file mode 100644 index 0000000000..6ab2427c94 --- /dev/null +++ b/Task/String-concatenation/Golfscript/string-concatenation.golfscript @@ -0,0 +1,4 @@ +"Greetings ":s; +s"Earthlings"+puts +s"Earthlings"+:s1; +s1 puts diff --git a/Task/String-concatenation/Groovy/string-concatenation.groovy b/Task/String-concatenation/Groovy/string-concatenation.groovy new file mode 100644 index 0000000000..c3016122b9 --- /dev/null +++ b/Task/String-concatenation/Groovy/string-concatenation.groovy @@ -0,0 +1,5 @@ +def s = "Greetings " +println s + "Earthlings" + +def s1 = s + "Earthlings" +println s1 diff --git a/Task/String-concatenation/Haskell/string-concatenation.hs b/Task/String-concatenation/Haskell/string-concatenation.hs new file mode 100644 index 0000000000..fd76ad37e5 --- /dev/null +++ b/Task/String-concatenation/Haskell/string-concatenation.hs @@ -0,0 +1,5 @@ +import System.IO +s = "hello" +s1 = s ++ " literal" +main = do putStrLn (s ++ " literal") + putStrLn s1 diff --git a/Task/String-concatenation/HicEst/string-concatenation.hicest b/Task/String-concatenation/HicEst/string-concatenation.hicest new file mode 100644 index 0000000000..cba92ab618 --- /dev/null +++ b/Task/String-concatenation/HicEst/string-concatenation.hicest @@ -0,0 +1,5 @@ +CHARACTER s = "hello", sl*100 + +WRITE() s // " literal" +sl = s // " literal" +WRITE() sl diff --git a/Task/String-concatenation/IDL/string-concatenation.idl b/Task/String-concatenation/IDL/string-concatenation.idl new file mode 100644 index 0000000000..710b7cfdd9 --- /dev/null +++ b/Task/String-concatenation/IDL/string-concatenation.idl @@ -0,0 +1,4 @@ +s1='Hello' +print, s1 + ' literal' +s2=s1 + ' literal' +print, s2 diff --git a/Task/String-concatenation/Icon/string-concatenation.icon b/Task/String-concatenation/Icon/string-concatenation.icon new file mode 100644 index 0000000000..5e42629ce4 --- /dev/null +++ b/Task/String-concatenation/Icon/string-concatenation.icon @@ -0,0 +1,5 @@ +procedure main() +s1 := "hello" +write(s2 := s1 || " there.") # capture the reuslt for +write(s2) # ... the 2nd write +end diff --git a/Task/String-concatenation/J/string-concatenation.j b/Task/String-concatenation/J/string-concatenation.j new file mode 100644 index 0000000000..351395fa13 --- /dev/null +++ b/Task/String-concatenation/J/string-concatenation.j @@ -0,0 +1,5 @@ + s1 =. 'Some ' + ]s1, 'text ' +Some text + ]s2 =. s1 , 'more text!' +Some more text! diff --git a/Task/String-concatenation/Java/string-concatenation.java b/Task/String-concatenation/Java/string-concatenation.java new file mode 100644 index 0000000000..5808028aec --- /dev/null +++ b/Task/String-concatenation/Java/string-concatenation.java @@ -0,0 +1,8 @@ +public class Str{ + public static void main(String[] args){ + String s = "hello"; + System.out.println(s + " literal"); + String s2 = s + " literal"; + System.out.println(s2); + } +} diff --git a/Task/String-concatenation/JavaScript/string-concatenation.js b/Task/String-concatenation/JavaScript/string-concatenation.js new file mode 100644 index 0000000000..3763e92eb2 --- /dev/null +++ b/Task/String-concatenation/JavaScript/string-concatenation.js @@ -0,0 +1,2 @@ +var s = "hello" +print(s + " there!") diff --git a/Task/String-concatenation/Lang5/string-concatenation.lang5 b/Task/String-concatenation/Lang5/string-concatenation.lang5 new file mode 100644 index 0000000000..6be6a8d595 --- /dev/null +++ b/Task/String-concatenation/Lang5/string-concatenation.lang5 @@ -0,0 +1,2 @@ +: concat 2 compress "" join ; +'hello " literal" concat diff --git a/Task/String-concatenation/Lisaac/string-concatenation.lisaac b/Task/String-concatenation/Lisaac/string-concatenation.lisaac new file mode 100644 index 0000000000..7159f520e8 --- /dev/null +++ b/Task/String-concatenation/Lisaac/string-concatenation.lisaac @@ -0,0 +1,17 @@ +Section Header + ++ name := STRING_CONCATENATION; + +Section Public + +- main <- ( + + sc : STRING_CONSTANT; + + sv : STRING; + + sc := "Hello"; + (sc + " literal").println; + + sv := sc + " literal"; + sv.println; + +); diff --git a/Task/String-concatenation/Logo/string-concatenation.logo b/Task/String-concatenation/Logo/string-concatenation.logo new file mode 100644 index 0000000000..ebe7cce640 --- /dev/null +++ b/Task/String-concatenation/Logo/string-concatenation.logo @@ -0,0 +1,2 @@ +make "s "hello +print word :s "| there!| diff --git a/Task/String-concatenation/M4/string-concatenation.m4 b/Task/String-concatenation/M4/string-concatenation.m4 new file mode 100644 index 0000000000..fe496b7d47 --- /dev/null +++ b/Task/String-concatenation/M4/string-concatenation.m4 @@ -0,0 +1,5 @@ +define(`concat',`$1$2')dnl +define(`A',`any text value')dnl +concat(`A',` concatenated with string literal') +define(`B',`concat(`A',` and string literal')')dnl +B diff --git a/Task/String-concatenation/MATLAB/string-concatenation.m b/Task/String-concatenation/MATLAB/string-concatenation.m new file mode 100644 index 0000000000..5323c04009 --- /dev/null +++ b/Task/String-concatenation/MATLAB/string-concatenation.m @@ -0,0 +1,11 @@ +>> string1 = '1 Fish' + +string1 = + +1 Fish + +>> string2 = [string1 ', 2 Fish, Red Fish, Blue Fish'] + +string2 = + +1 Fish, 2 Fish, Red Fish, Blue Fish diff --git a/Task/String-concatenation/MAXScript/string-concatenation.maxscript b/Task/String-concatenation/MAXScript/string-concatenation.maxscript new file mode 100644 index 0000000000..51036de207 --- /dev/null +++ b/Task/String-concatenation/MAXScript/string-concatenation.maxscript @@ -0,0 +1,4 @@ +s = "hello" +print (s + " literal") +s1 = s + " literal" +print s1 diff --git a/Task/String-concatenation/MUMPS/string-concatenation.mumps b/Task/String-concatenation/MUMPS/string-concatenation.mumps new file mode 100644 index 0000000000..1cbe5ca2bd --- /dev/null +++ b/Task/String-concatenation/MUMPS/string-concatenation.mumps @@ -0,0 +1,6 @@ +STRCAT + SET S="STRING" + WRITE !,S + SET T=S_" LITERAL" + WRITE !,T + QUIT diff --git a/Task/String-concatenation/Mathematica/string-concatenation.math b/Task/String-concatenation/Mathematica/string-concatenation.math new file mode 100644 index 0000000000..355eb28e10 --- /dev/null +++ b/Task/String-concatenation/Mathematica/string-concatenation.math @@ -0,0 +1,2 @@ +str= "Hello "; +str<>"Literal" diff --git a/Task/String-concatenation/Maxima/string-concatenation.maxima b/Task/String-concatenation/Maxima/string-concatenation.maxima new file mode 100644 index 0000000000..7454c36c80 --- /dev/null +++ b/Task/String-concatenation/Maxima/string-concatenation.maxima @@ -0,0 +1,4 @@ +s: "the quick brown fox"; +t: "jumps over the lazy dog"; +sconcat(s, " ", t); +/* "the quick brown fox jumps over the lazy dog" */ diff --git a/Task/String-concatenation/Mercury/string-concatenation.mercury b/Task/String-concatenation/Mercury/string-concatenation.mercury new file mode 100644 index 0000000000..563ac0f8fa --- /dev/null +++ b/Task/String-concatenation/Mercury/string-concatenation.mercury @@ -0,0 +1,14 @@ +:- module string_concat. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module string. + +main(!IO) :- + S = "hello", + S1 = S ++ " world", + io.write_string(S, !IO), io.nl(!IO), + io.write_string(S1, !IO), io.nl(!IO). diff --git a/Task/String-concatenation/Metafont/string-concatenation.metafont b/Task/String-concatenation/Metafont/string-concatenation.metafont new file mode 100644 index 0000000000..9c63fe0710 --- /dev/null +++ b/Task/String-concatenation/Metafont/string-concatenation.metafont @@ -0,0 +1,5 @@ +string a, b; +a := "String"; +message a & " literal"; +b := a & " literal"; +message b; diff --git a/Task/String-concatenation/Modula-3/string-concatenation-1.mod3 b/Task/String-concatenation/Modula-3/string-concatenation-1.mod3 new file mode 100644 index 0000000000..1d65e2981d --- /dev/null +++ b/Task/String-concatenation/Modula-3/string-concatenation-1.mod3 @@ -0,0 +1,12 @@ +MODULE Concat EXPORTS Main; + +IMPORT IO; + +VAR string: TEXT := "String"; + string1: TEXT; + +BEGIN + IO.Put(string & " literal.\n"); + string1 := string & " literal.\n"; + IO.Put(string1); +END Concat. diff --git a/Task/String-concatenation/Modula-3/string-concatenation-2.mod3 b/Task/String-concatenation/Modula-3/string-concatenation-2.mod3 new file mode 100644 index 0000000000..0d1db592c9 --- /dev/null +++ b/Task/String-concatenation/Modula-3/string-concatenation-2.mod3 @@ -0,0 +1 @@ +string1 := Text.Concat(string, " literal.\n"); diff --git a/Task/String-concatenation/Nemerle/string-concatenation.nemerle b/Task/String-concatenation/Nemerle/string-concatenation.nemerle new file mode 100644 index 0000000000..d766cbdd28 --- /dev/null +++ b/Task/String-concatenation/Nemerle/string-concatenation.nemerle @@ -0,0 +1,14 @@ +using System; +using System.Console; +using Nemerle.Utility.NString; // contains method Concat() + +module Stringcat +{ + Main() : void + { + def text1 = "This string has"; + def cat1 = Concat( " ", [text, "been concatenated"]); + def cat2 = text1 + " also been concatenated"; + Write($"$cat1\n$cat2\n"); + } +} diff --git a/Task/String-concatenation/NetRexx/string-concatenation.netrexx b/Task/String-concatenation/NetRexx/string-concatenation.netrexx new file mode 100644 index 0000000000..3e0f39a6cc --- /dev/null +++ b/Task/String-concatenation/NetRexx/string-concatenation.netrexx @@ -0,0 +1,19 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols + +s1 = 'any text value' +s2 = 'another string literal' +s3 = s1 s2 -- concatenate variables with blank space (note that only one blank space is added) +s4 = s1 || s2 -- concatenate variables with abuttal (here, no blank spaces are added) +s5 = s1 'another string literal' -- concatenate a variable and a literal with blank space +s6 = s1'another string literal' -- concatenate a variable and a literal using abuttal +s7 = s1 || 'another string literal' -- ditto + +say 's1:' s1 -- concatenation with blank space is employed here too +say 's2:' s2 +say 's3:' s3 +say 's4:' s4 +say 's5:' s5 +say 's6:' s6 +say 's7:' s7 diff --git a/Task/String-concatenation/Nimrod/string-concatenation.nimrod b/Task/String-concatenation/Nimrod/string-concatenation.nimrod new file mode 100644 index 0000000000..4ba9455384 --- /dev/null +++ b/Task/String-concatenation/Nimrod/string-concatenation.nimrod @@ -0,0 +1,4 @@ +var str, str1 = "String" +echo(str & " literal.") +str1 = str1 & " literal." +echo(str1) diff --git a/Task/String-concatenation/OCaml/string-concatenation.ocaml b/Task/String-concatenation/OCaml/string-concatenation.ocaml new file mode 100644 index 0000000000..c77a21b5e7 --- /dev/null +++ b/Task/String-concatenation/OCaml/string-concatenation.ocaml @@ -0,0 +1,6 @@ +let s = "hello" +let s1 = s ^ " literal" +let () = + print_endline (s ^ " literal"); + (* or Printf.printf "%s literal\n" s; *) + print_endline s1 diff --git a/Task/String-concatenation/Objeck/string-concatenation.objeck b/Task/String-concatenation/Objeck/string-concatenation.objeck new file mode 100644 index 0000000000..6400f7001f --- /dev/null +++ b/Task/String-concatenation/Objeck/string-concatenation.objeck @@ -0,0 +1,11 @@ +bundle Default { + class Repeat { + function : Main(args : String[]) ~ Nil { + s := "hello"; + s->PrintLine(); + " literal"->PrintLine(); + s->Append(" literal"); + s->PrintLine(); + } + } +} diff --git a/Task/String-concatenation/Objective-C/string-concatenation.m b/Task/String-concatenation/Objective-C/string-concatenation.m new file mode 100644 index 0000000000..38ebc4bf09 --- /dev/null +++ b/Task/String-concatenation/Objective-C/string-concatenation.m @@ -0,0 +1,19 @@ +#import + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSString *s = @"hello"; + printf("%s%s\n", [s UTF8String], " literal"); + + NSString *s2 = [s stringByAppendingString:@" literal"]; + // or, NSString *s2 = [NSString stringWithFormat:@"%@%@", s, @" literal"]; + puts([s2 UTF8String]); + /* or */ + NSMutableString *s3 = [NSMutableString stringWithString: s]; + [s3 appendString: @" literal"]; + puts([s3 UTF8String]); + + [pool release]; + return 0; +} diff --git a/Task/String-concatenation/Openscad/string-concatenation.scad b/Task/String-concatenation/Openscad/string-concatenation.scad new file mode 100644 index 0000000000..b2f5f8f5a2 --- /dev/null +++ b/Task/String-concatenation/Openscad/string-concatenation.scad @@ -0,0 +1,4 @@ +a="straw"; +b="berry"; +c=str(a,b); /* Concatenate a and b */ +echo (c); diff --git a/Task/String-concatenation/Oz/string-concatenation.oz b/Task/String-concatenation/Oz/string-concatenation.oz new file mode 100644 index 0000000000..42b27547a4 --- /dev/null +++ b/Task/String-concatenation/Oz/string-concatenation.oz @@ -0,0 +1,5 @@ +declare +S = "hello" +{System.showInfo S#" literal"} %% virtual strings are constructed with "#" +S1 = {Append S " literal"} +{System.showInfo S1} diff --git a/Task/String-concatenation/PARI-GP/string-concatenation.pari b/Task/String-concatenation/PARI-GP/string-concatenation.pari new file mode 100644 index 0000000000..0d1d5a023c --- /dev/null +++ b/Task/String-concatenation/PARI-GP/string-concatenation.pari @@ -0,0 +1,5 @@ +s = "Hello "; +s = Str(s, "world"); +\\ Alternately, this could have been: +\\ s = concat(s, "world"); +print(s); diff --git a/Task/String-concatenation/PHP/string-concatenation.php b/Task/String-concatenation/PHP/string-concatenation.php new file mode 100644 index 0000000000..0f4003a64f --- /dev/null +++ b/Task/String-concatenation/PHP/string-concatenation.php @@ -0,0 +1,6 @@ + diff --git a/Task/String-concatenation/PL-I/string-concatenation.pli b/Task/String-concatenation/PL-I/string-concatenation.pli new file mode 100644 index 0000000000..fc1fe8a713 --- /dev/null +++ b/Task/String-concatenation/PL-I/string-concatenation.pli @@ -0,0 +1,6 @@ +declare (s, t) character (30) varying; + +s = 'hello from me'; +display (s || ' to you.' ); +t = s || ' to you all'; +display (t); diff --git a/Task/String-concatenation/Pascal/string-concatenation.pascal b/Task/String-concatenation/Pascal/string-concatenation.pascal new file mode 100644 index 0000000000..90195bc5ba --- /dev/null +++ b/Task/String-concatenation/Pascal/string-concatenation.pascal @@ -0,0 +1,11 @@ +Program StringConcat; + Var + s, s1 : String; + +Begin + s := 'hello'; + writeln(s + ' literal'); + s1 := concat(s, ' literal'); + { s1 := s + ' literal'; works too, with FreePascal } + writeln(s1); +End. diff --git a/Task/String-concatenation/Perl-6/string-concatenation-1.pl6 b/Task/String-concatenation/Perl-6/string-concatenation-1.pl6 new file mode 100644 index 0000000000..2bb5c13b09 --- /dev/null +++ b/Task/String-concatenation/Perl-6/string-concatenation-1.pl6 @@ -0,0 +1,4 @@ +my $s = 'hello'; +say $s ~ ' literal'; +my $s1 = $s ~ ' literal'; +say $s1; diff --git a/Task/String-concatenation/Perl-6/string-concatenation-2.pl6 b/Task/String-concatenation/Perl-6/string-concatenation-2.pl6 new file mode 100644 index 0000000000..13f9fda084 --- /dev/null +++ b/Task/String-concatenation/Perl-6/string-concatenation-2.pl6 @@ -0,0 +1,2 @@ +$s ~= ' literal'; +say $s; diff --git a/Task/String-concatenation/Perl/string-concatenation-1.pl b/Task/String-concatenation/Perl/string-concatenation-1.pl new file mode 100644 index 0000000000..e46d866de2 --- /dev/null +++ b/Task/String-concatenation/Perl/string-concatenation-1.pl @@ -0,0 +1,4 @@ +my $s = 'hello'; +print $s . ' literal', "\n"; +my $s1 = $s . ' literal'; +print $s1, "\n"; diff --git a/Task/String-concatenation/Perl/string-concatenation-2.pl b/Task/String-concatenation/Perl/string-concatenation-2.pl new file mode 100644 index 0000000000..141e6755bd --- /dev/null +++ b/Task/String-concatenation/Perl/string-concatenation-2.pl @@ -0,0 +1,2 @@ +$s .= ' literal'; +print $s, "\n"; diff --git a/Task/String-concatenation/PicoLisp/string-concatenation.l b/Task/String-concatenation/PicoLisp/string-concatenation.l new file mode 100644 index 0000000000..27842b2238 --- /dev/null +++ b/Task/String-concatenation/PicoLisp/string-concatenation.l @@ -0,0 +1,4 @@ +(let Str1 "First text" + (prinl Str1 " literal") + (let Str2 (pack Str1 " literal") + (prinl Str2) ) ) diff --git a/Task/String-concatenation/PowerShell/string-concatenation.psh b/Task/String-concatenation/PowerShell/string-concatenation.psh new file mode 100644 index 0000000000..75b4a227cf --- /dev/null +++ b/Task/String-concatenation/PowerShell/string-concatenation.psh @@ -0,0 +1,8 @@ +$s = "Hello" +Write-Host $s World. + +# alternative, using variable expansion in strings +Write-Host "$s World." + +$s2 = $s + " World." +Write-Host $s2 diff --git a/Task/String-concatenation/PureBasic/string-concatenation.purebasic b/Task/String-concatenation/PureBasic/string-concatenation.purebasic new file mode 100644 index 0000000000..e16e7a067b --- /dev/null +++ b/Task/String-concatenation/PureBasic/string-concatenation.purebasic @@ -0,0 +1,11 @@ +If OpenConsole() + + s$ = "hello" + PrintN( s$ + " literal") + s2$ = s$ + " literal" + PrintN(s2$) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/String-concatenation/Python/string-concatenation-1.py b/Task/String-concatenation/Python/string-concatenation-1.py new file mode 100644 index 0000000000..c221e4defe --- /dev/null +++ b/Task/String-concatenation/Python/string-concatenation-1.py @@ -0,0 +1,5 @@ +s1 = "hello" +print s1 + " world" + +s2 = s1 + " world" +print s2 diff --git a/Task/String-concatenation/Python/string-concatenation-2.py b/Task/String-concatenation/Python/string-concatenation-2.py new file mode 100644 index 0000000000..e5904e149b --- /dev/null +++ b/Task/String-concatenation/Python/string-concatenation-2.py @@ -0,0 +1,5 @@ +s1 = "hello" +print ", ".join([s1, "world", "mom"]) + +s2 = ", ".join([s1, "world", "mom"]) +print s2 diff --git a/Task/String-concatenation/R/string-concatenation.r b/Task/String-concatenation/R/string-concatenation.r new file mode 100644 index 0000000000..b4e24cca5b --- /dev/null +++ b/Task/String-concatenation/R/string-concatenation.r @@ -0,0 +1,4 @@ +hello <- "hello" +paste(hello, "literal") # "hello literal" +hl <- paste(hello, "literal") #saves concatenates string to a new variable +paste("no", "spaces", "between", "words", sep="") # "nospacesbetweenwords" diff --git a/Task/String-concatenation/REBOL/string-concatenation.rebol b/Task/String-concatenation/REBOL/string-concatenation.rebol new file mode 100644 index 0000000000..bb5ba06c41 --- /dev/null +++ b/Task/String-concatenation/REBOL/string-concatenation.rebol @@ -0,0 +1,3 @@ +s: "hello" +print s1: rejoin [s " literal"] +print s1 diff --git a/Task/String-concatenation/REXX/string-concatenation.rexx b/Task/String-concatenation/REXX/string-concatenation.rexx new file mode 100644 index 0000000000..aa2082cd96 --- /dev/null +++ b/Task/String-concatenation/REXX/string-concatenation.rexx @@ -0,0 +1,9 @@ +s = "hello" +say s "literal" +t = s "literal" /* Whitespace between the two strings causes a space in the output */ +say t + + /* The above method works without spaces too */ +genus="straw" +say genus"berry" /* This outputs strawberry */ +say genus || "berry" /* Concatenation using a doublepipe does not cause spaces */ diff --git a/Task/String-concatenation/Retro/string-concatenation.retro b/Task/String-concatenation/Retro/string-concatenation.retro new file mode 100644 index 0000000000..3555a25e1b --- /dev/null +++ b/Task/String-concatenation/Retro/string-concatenation.retro @@ -0,0 +1,2 @@ +with strings' +"hello" "literal" append puts diff --git a/Task/String-concatenation/Ruby/string-concatenation.rb b/Task/String-concatenation/Ruby/string-concatenation.rb new file mode 100644 index 0000000000..b12f3bb23c --- /dev/null +++ b/Task/String-concatenation/Ruby/string-concatenation.rb @@ -0,0 +1,5 @@ +s = "hello" +puts s + " literal" +s1 = s + " literal" +puts s1 +s1 << " another" # append to s1 diff --git a/Task/String-concatenation/SAS/string-concatenation.sas b/Task/String-concatenation/SAS/string-concatenation.sas new file mode 100644 index 0000000000..5c34dcf707 --- /dev/null +++ b/Task/String-concatenation/SAS/string-concatenation.sas @@ -0,0 +1,6 @@ +data _null_; + a="Hello,"; + b="World!"; + c=a !! " " !! b; + put c; +run; diff --git a/Task/String-concatenation/SNOBOL4/string-concatenation.sno b/Task/String-concatenation/SNOBOL4/string-concatenation.sno new file mode 100644 index 0000000000..4ccc6d3ea6 --- /dev/null +++ b/Task/String-concatenation/SNOBOL4/string-concatenation.sno @@ -0,0 +1,5 @@ + greet1 = "Hello, " + output = greet1 + greet2 = greet1 "World!" + output = greet2 +end diff --git a/Task/String-concatenation/Sather/string-concatenation.sa b/Task/String-concatenation/Sather/string-concatenation.sa new file mode 100644 index 0000000000..8ffb9b037d --- /dev/null +++ b/Task/String-concatenation/Sather/string-concatenation.sa @@ -0,0 +1,8 @@ +class MAIN is + main is + s ::= "hello"; + #OUT + s + " literal\n"; + s2 ::= s + " literal"; + #OUT + s2 + "\n"; + end; +end; diff --git a/Task/String-concatenation/Scala/string-concatenation.scala b/Task/String-concatenation/Scala/string-concatenation.scala new file mode 100644 index 0000000000..06438ffd27 --- /dev/null +++ b/Task/String-concatenation/Scala/string-concatenation.scala @@ -0,0 +1,3 @@ +val s = "hello" +val s2 = s + " world" +println(s2) diff --git a/Task/String-concatenation/Scheme/string-concatenation.ss b/Task/String-concatenation/Scheme/string-concatenation.ss new file mode 100644 index 0000000000..a9ece840de --- /dev/null +++ b/Task/String-concatenation/Scheme/string-concatenation.ss @@ -0,0 +1,6 @@ +(define s "hello") +(display (string-append s " literal")) +(newline) +(define s1 (string-append s " literal")) +(display s1) +(newline) diff --git a/Task/String-concatenation/Seed7/string-concatenation.seed7 b/Task/String-concatenation/Seed7/string-concatenation.seed7 new file mode 100644 index 0000000000..1550893a6e --- /dev/null +++ b/Task/String-concatenation/Seed7/string-concatenation.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: s is "hello"; + var string: s2 is ""; + begin + writeln(s <& " world"); + s2 := s & " world"; + writeln(s2); + end func; diff --git a/Task/String-concatenation/Slate/string-concatenation.slate b/Task/String-concatenation/Slate/string-concatenation.slate new file mode 100644 index 0000000000..af9dc374fd --- /dev/null +++ b/Task/String-concatenation/Slate/string-concatenation.slate @@ -0,0 +1,4 @@ +define: #s -> 'hello'. +inform: s ; ' literal'. +define: #s1 -> (s ; ' literal'). +inform: s1. diff --git a/Task/String-concatenation/Smalltalk/string-concatenation.st b/Task/String-concatenation/Smalltalk/string-concatenation.st new file mode 100644 index 0000000000..0f6f3e5bb1 --- /dev/null +++ b/Task/String-concatenation/Smalltalk/string-concatenation.st @@ -0,0 +1,4 @@ +|s s1| s := 'hello'. +(s,' literal') printNl. +s1 := s,' literal'. +s1 printNl. diff --git a/Task/String-concatenation/Standard-ML/string-concatenation.ml b/Task/String-concatenation/Standard-ML/string-concatenation.ml new file mode 100644 index 0000000000..5e93092ca4 --- /dev/null +++ b/Task/String-concatenation/Standard-ML/string-concatenation.ml @@ -0,0 +1,5 @@ +val s = "hello" +val s1 = s ^ " literal\n" +val () = + print (s ^ " literal\n"); + print s1 diff --git a/Task/String-concatenation/TI-89-BASIC/string-concatenation.ti-89 b/Task/String-concatenation/TI-89-BASIC/string-concatenation.ti-89 new file mode 100644 index 0000000000..d6b4838f3d --- /dev/null +++ b/Task/String-concatenation/TI-89-BASIC/string-concatenation.ti-89 @@ -0,0 +1,3 @@ +"aard" → sv +Disp sv & "vark" +sv & "wolf" → sv2 diff --git a/Task/String-concatenation/TUSCRIPT/string-concatenation.tuscript b/Task/String-concatenation/TUSCRIPT/string-concatenation.tuscript new file mode 100644 index 0000000000..bdafa01c93 --- /dev/null +++ b/Task/String-concatenation/TUSCRIPT/string-concatenation.tuscript @@ -0,0 +1,6 @@ +$$ MODE TUSCRIPT +s = "Hello " +print s, "literal" + +s1 = CONCAT (s,"literal") +print s1 diff --git a/Task/String-concatenation/Tcl/string-concatenation-1.tcl b/Task/String-concatenation/Tcl/string-concatenation-1.tcl new file mode 100644 index 0000000000..47ebef75b4 --- /dev/null +++ b/Task/String-concatenation/Tcl/string-concatenation-1.tcl @@ -0,0 +1,4 @@ +set s hello +puts "$s there!" +append s " there!" +puts $s diff --git a/Task/String-concatenation/Tcl/string-concatenation-2.tcl b/Task/String-concatenation/Tcl/string-concatenation-2.tcl new file mode 100644 index 0000000000..cead47af45 --- /dev/null +++ b/Task/String-concatenation/Tcl/string-concatenation-2.tcl @@ -0,0 +1,4 @@ +set s "Hello " +set t "World" +set u "!" +puts $s$t$u ;# There is nothing special here about using puts; just an example diff --git a/Task/String-concatenation/TorqueScript/string-concatenation.torquescript b/Task/String-concatenation/TorqueScript/string-concatenation.torquescript new file mode 100644 index 0000000000..e89e60600a --- /dev/null +++ b/Task/String-concatenation/TorqueScript/string-concatenation.torquescript @@ -0,0 +1,5 @@ +%string = "Hello"; +echo(%string); +%other = " world!"; +echo(%other); +echo(%string @ %other); diff --git a/Task/String-concatenation/UNIX-Shell/string-concatenation.sh b/Task/String-concatenation/UNIX-Shell/string-concatenation.sh new file mode 100644 index 0000000000..de864cfe9f --- /dev/null +++ b/Task/String-concatenation/UNIX-Shell/string-concatenation.sh @@ -0,0 +1,9 @@ +s="hello" +echo "$s literal" +s1="$s literal" # This method only works with a space between the strings +echo $s1 + +# To concatenate without the space we need squiggly brackets: +genus='straw' +fruit=${genus}berry # This outputs the word strawberry +echo $fruit diff --git a/Task/String-concatenation/UnixPipes/string-concatenation.unixpipes b/Task/String-concatenation/UnixPipes/string-concatenation.unixpipes new file mode 100644 index 0000000000..7c7c9e7a27 --- /dev/null +++ b/Task/String-concatenation/UnixPipes/string-concatenation.unixpipes @@ -0,0 +1,2 @@ +echo "hello" + | xargs -n1 -i echo {} literal diff --git a/Task/String-concatenation/Visual-Basic-.NET/string-concatenation.visual b/Task/String-concatenation/Visual-Basic-.NET/string-concatenation.visual new file mode 100644 index 0000000000..07ec7f0b5f --- /dev/null +++ b/Task/String-concatenation/Visual-Basic-.NET/string-concatenation.visual @@ -0,0 +1,4 @@ +s = "Hello" +Console.WriteLine(s & " literal") +s1 = s + " literal" +Console.WriteLine(s1) diff --git a/Task/String-concatenation/XPL0/string-concatenation.xpl0 b/Task/String-concatenation/XPL0/string-concatenation.xpl0 new file mode 100644 index 0000000000..ca74a0bb4c --- /dev/null +++ b/Task/String-concatenation/XPL0/string-concatenation.xpl0 @@ -0,0 +1,23 @@ +func Concat(S1, S2, S3); \Concatenate strings: S3:= S1 + S2 +char S1, S2, S3; +int C, I, J; +[I:= 0; +repeat C:= S1(I); + S3(I):= C & $7F; \remove MSb terminator from first string + I:= I+1; +until C >= $80; +J:= 0; +repeat C:= S2(J); + S3(I+J):= C; + J:= J+1; +until C >= $80; +return S3; +]; + +code Text=12; +char A, B, C(80); +[A:= "Hello"; + B:= " World!"; +Concat(A, B, C); +Text(0, C); +] diff --git a/Task/String-concatenation/Yorick/string-concatenation.yorick b/Task/String-concatenation/Yorick/string-concatenation.yorick new file mode 100644 index 0000000000..1af38a7c96 --- /dev/null +++ b/Task/String-concatenation/Yorick/string-concatenation.yorick @@ -0,0 +1,4 @@ +var1 = "Hello"; +var2 = var1 + ", world!"; +write, var1; +write, var2; diff --git a/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx b/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx new file mode 100644 index 0000000000..e71db46ad2 --- /dev/null +++ b/Task/String-concatenation/ZX-Spectrum-Basic/string-concatenation.zx @@ -0,0 +1,3 @@ +10 LET s$="Hello" +20 LET s$=s$+" World!" +30 PRINT s$ diff --git a/Task/String-interpolation--included-/0DESCRIPTION b/Task/String-interpolation--included-/0DESCRIPTION new file mode 100644 index 0000000000..5190bde245 --- /dev/null +++ b/Task/String-interpolation--included-/0DESCRIPTION @@ -0,0 +1,12 @@ +{{basic data operation}} +{{omit from|NSIS}}{{omit from|BBC BASIC}} +Given a string and defined variables or values, [[wp:String literal#Variable_interpolation|string interpolation]] is the replacement of defined character sequences in the string by values or variable values. +: For example, given an original string of "Mary had a X lamb.", a value of "big", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string "Mary had a big lamb". + +:(Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as "%", or "#" rather than "X"). + +The task is to: +# Use your languages inbuilt string interpolation abilities to interpolate a string missing the text "little" which is held in a variable, to produce the output string "Mary had a little lamb". +# If possible, give links to further documentation on your languages string interpolation features. + +Note: The task is not to create a string interpolation routine, but to show a language's built-in capability. diff --git a/Task/String-interpolation--included-/1META.yaml b/Task/String-interpolation--included-/1META.yaml new file mode 100644 index 0000000000..3bdc51ea57 --- /dev/null +++ b/Task/String-interpolation--included-/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Basic language learning diff --git a/Task/String-interpolation--included-/ALGOL-68/string-interpolation--included-.alg b/Task/String-interpolation--included-/ALGOL-68/string-interpolation--included-.alg new file mode 100644 index 0000000000..da49d32cf4 --- /dev/null +++ b/Task/String-interpolation--included-/ALGOL-68/string-interpolation--included-.alg @@ -0,0 +1,12 @@ +main:( +# as a STRING # + STRING extra = "little"; + printf(($"Mary had a "g" lamb."l$, extra)); + +# as a FORMAT # + FORMAT extraf = $"little"$; + printf($"Mary had a "f(extraf)" lamb."l$); + +# or: use simply use STRING concatenation # + print(("Mary had a "+extra+" lamb.", new line)) +) diff --git a/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada b/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada new file mode 100644 index 0000000000..c38c188a13 --- /dev/null +++ b/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada @@ -0,0 +1,11 @@ +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-/Aikido/string-interpolation--included-.aikido b/Task/String-interpolation--included-/Aikido/string-interpolation--included-.aikido new file mode 100644 index 0000000000..5edf57f997 --- /dev/null +++ b/Task/String-interpolation--included-/Aikido/string-interpolation--included-.aikido @@ -0,0 +1,5 @@ +const little = "little" +printf ("Mary had a %s lamb\n", little) + +// alternatively +println ("Mary had a " + little + " lamb") diff --git a/Task/String-interpolation--included-/AutoHotkey/string-interpolation--included-.ahk b/Task/String-interpolation--included-/AutoHotkey/string-interpolation--included-.ahk new file mode 100644 index 0000000000..a1d3fea691 --- /dev/null +++ b/Task/String-interpolation--included-/AutoHotkey/string-interpolation--included-.ahk @@ -0,0 +1,9 @@ +; Using the = operator +LIT = little +string = Mary had a %LIT% lamb. + +; Using the := operator +LIT := "little" +string := "Mary had a" LIT " lamb." + +MsgBox %string% diff --git a/Task/String-interpolation--included-/Batch-File/string-interpolation--included--1.bat b/Task/String-interpolation--included-/Batch-File/string-interpolation--included--1.bat new file mode 100644 index 0000000000..2031984790 --- /dev/null +++ b/Task/String-interpolation--included-/Batch-File/string-interpolation--included--1.bat @@ -0,0 +1,11 @@ +@echo off +setlocal enabledelayedexpansion +call :interpolate %1 %2 res +echo %res% +goto :eof + +:interpolate +set pat=%~1 +set str=%~2 +set %3=!pat:X=%str%! +goto :eof diff --git a/Task/String-interpolation--included-/Batch-File/string-interpolation--included--2.bat b/Task/String-interpolation--included-/Batch-File/string-interpolation--included--2.bat new file mode 100644 index 0000000000..c58956527e --- /dev/null +++ b/Task/String-interpolation--included-/Batch-File/string-interpolation--included--2.bat @@ -0,0 +1,2 @@ +>interpolate.cmd "Mary had a X lamb" little +Mary had a little lamb diff --git a/Task/String-interpolation--included-/Bracmat/string-interpolation--included-.bracmat b/Task/String-interpolation--included-/Bracmat/string-interpolation--included-.bracmat new file mode 100644 index 0000000000..035857dde1 --- /dev/null +++ b/Task/String-interpolation--included-/Bracmat/string-interpolation--included-.bracmat @@ -0,0 +1 @@ +@("Mary had a X lamb":?a X ?z) & str$(!a little !z) diff --git a/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp b/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp new file mode 100644 index 0000000000..2a2103967d --- /dev/null +++ b/Task/String-interpolation--included-/C++/string-interpolation--included-.cpp @@ -0,0 +1,11 @@ +#include +#include + +int main( ) { + std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , + replacement ( "little" ) ; + std::string newString = original.replace( original.find( "X" ) , + toBeReplaced.length( ) , replacement ) ; + std::cout << "String after replacement: " << newString << " \n" ; + return 0 ; +} diff --git a/Task/String-interpolation--included-/C/string-interpolation--included-.c b/Task/String-interpolation--included-/C/string-interpolation--included-.c new file mode 100644 index 0000000000..4a302994b3 --- /dev/null +++ b/Task/String-interpolation--included-/C/string-interpolation--included-.c @@ -0,0 +1,7 @@ +#include + +int main() { + const char *extra = "little"; + printf("Mary had a %s lamb.\n", extra); + return 0; +} diff --git a/Task/String-interpolation--included-/Clojure/string-interpolation--included-.clj b/Task/String-interpolation--included-/Clojure/string-interpolation--included-.clj new file mode 100644 index 0000000000..9bb4585bc9 --- /dev/null +++ b/Task/String-interpolation--included-/Clojure/string-interpolation--included-.clj @@ -0,0 +1,2 @@ +(let [little "little"] + (println (format "Mary had a %s lamb." little))) diff --git a/Task/String-interpolation--included-/CoffeeScript/string-interpolation--included-.coffeescript b/Task/String-interpolation--included-/CoffeeScript/string-interpolation--included-.coffeescript new file mode 100644 index 0000000000..aa8181c482 --- /dev/null +++ b/Task/String-interpolation--included-/CoffeeScript/string-interpolation--included-.coffeescript @@ -0,0 +1,9 @@ +size = 'little' +console.log "Mary had a #{size} lamb." # Mary had a little lamb. +console.log "Escaping: \#{}" # Escaping: #{} +console.log 'No #{ interpolation} with single quotes' # No #{ interpolation} with single quotes + +# Multi-line strings and arbtrary expressions work: 20 +console.log """ + Multi-line strings and arbtrary expressions work: #{ 5 * 4 } + """ diff --git a/Task/String-interpolation--included-/Common-Lisp/string-interpolation--included-.lisp b/Task/String-interpolation--included-/Common-Lisp/string-interpolation--included-.lisp new file mode 100644 index 0000000000..6000f5930b --- /dev/null +++ b/Task/String-interpolation--included-/Common-Lisp/string-interpolation--included-.lisp @@ -0,0 +1,2 @@ +(let ((extra "little")) + (format t "Mary had a ~A lamb.~%" extra)) diff --git a/Task/String-interpolation--included-/D/string-interpolation--included-.d b/Task/String-interpolation--included-/D/string-interpolation--included-.d new file mode 100644 index 0000000000..6148eb3a50 --- /dev/null +++ b/Task/String-interpolation--included-/D/string-interpolation--included-.d @@ -0,0 +1,9 @@ +import std.stdio: writeln; +import std.string: format; + +void main() { + auto original = "Mary had a %s lamb."; + auto extra = "little"; + auto modified = format(original, extra); + writeln(modified); +} diff --git a/Task/String-interpolation--included-/DWScript/string-interpolation--included-.dwscript b/Task/String-interpolation--included-/DWScript/string-interpolation--included-.dwscript new file mode 100644 index 0000000000..c828eee440 --- /dev/null +++ b/Task/String-interpolation--included-/DWScript/string-interpolation--included-.dwscript @@ -0,0 +1 @@ +PrintLn(Format('Mary had a %s lamb.', ['little'])) diff --git a/Task/String-interpolation--included-/E/string-interpolation--included--1.e b/Task/String-interpolation--included-/E/string-interpolation--included--1.e new file mode 100644 index 0000000000..4274f5bcc8 --- /dev/null +++ b/Task/String-interpolation--included-/E/string-interpolation--included--1.e @@ -0,0 +1,2 @@ +def adjective := "little" +`Mary had a $adjective lamb` diff --git a/Task/String-interpolation--included-/E/string-interpolation--included--2.e b/Task/String-interpolation--included-/E/string-interpolation--included--2.e new file mode 100644 index 0000000000..ad90e687e0 --- /dev/null +++ b/Task/String-interpolation--included-/E/string-interpolation--included--2.e @@ -0,0 +1,2 @@ +def adjective := "little" +simple__quasiParser.valueMaker("Mary had a ${0} lamb").substitute([adjective]) diff --git a/Task/String-interpolation--included-/Euphoria/string-interpolation--included-.euphoria b/Task/String-interpolation--included-/Euphoria/string-interpolation--included-.euphoria new file mode 100644 index 0000000000..e856013030 --- /dev/null +++ b/Task/String-interpolation--included-/Euphoria/string-interpolation--included-.euphoria @@ -0,0 +1,4 @@ +constant lambType = "little" +sequence s +s = sprintf("Mary had a %s lamb.",{lambType}) +puts(1,s) diff --git a/Task/String-interpolation--included-/Factor/string-interpolation--included--1.factor b/Task/String-interpolation--included-/Factor/string-interpolation--included--1.factor new file mode 100644 index 0000000000..b0545a4bd9 --- /dev/null +++ b/Task/String-interpolation--included-/Factor/string-interpolation--included--1.factor @@ -0,0 +1,7 @@ +USE: formatting + +SYMBOL: little + +"little" little set + +little get "Mary had a %s lamb" sprintf diff --git a/Task/String-interpolation--included-/Factor/string-interpolation--included--2.factor b/Task/String-interpolation--included-/Factor/string-interpolation--included--2.factor new file mode 100644 index 0000000000..28d2a1df1a --- /dev/null +++ b/Task/String-interpolation--included-/Factor/string-interpolation--included--2.factor @@ -0,0 +1,5 @@ +USE: formatting + +CONSTANT: little "little" + +little "Mary had a %s lamb" sprintf diff --git a/Task/String-interpolation--included-/Fantom/string-interpolation--included-.fantom b/Task/String-interpolation--included-/Fantom/string-interpolation--included-.fantom new file mode 100644 index 0000000000..3f7c28931f --- /dev/null +++ b/Task/String-interpolation--included-/Fantom/string-interpolation--included-.fantom @@ -0,0 +1,4 @@ +fansh> x := "little" +little +fansh> echo ("Mary had a $x lamb") +Mary had a little lamb diff --git a/Task/String-interpolation--included-/Fortran/string-interpolation--included-.f b/Task/String-interpolation--included-/Fortran/string-interpolation--included-.f new file mode 100644 index 0000000000..f069a37747 --- /dev/null +++ b/Task/String-interpolation--included-/Fortran/string-interpolation--included-.f @@ -0,0 +1,19 @@ +program interpolate + + write (*,*) trim(inter("Mary had a X lamb.","X","little")) + +contains + + elemental function inter(string,place,ins) result(new) + character(len=*), intent(in) :: string,place,ins + character(len=len(string)+max(0,len(ins)-len(place))) :: new + integer :: idx + idx = index(string,place) + if ( idx == 0 ) then + new = string + else + new = string(1:idx-1)//ins//string(idx+len(place):len(string)) + end if + end function inter + +end program interpolate diff --git a/Task/String-interpolation--included-/Go/string-interpolation--included-.go b/Task/String-interpolation--included-/Go/string-interpolation--included-.go new file mode 100644 index 0000000000..f93a9295b9 --- /dev/null +++ b/Task/String-interpolation--included-/Go/string-interpolation--included-.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" +) + +func main() { + str := "Mary had a %s lamb" + txt := "little" + out := fmt.Sprintf(str, txt) + fmt.Println(out) +} diff --git a/Task/String-interpolation--included-/Groovy/string-interpolation--included-.groovy b/Task/String-interpolation--included-/Groovy/string-interpolation--included-.groovy new file mode 100644 index 0000000000..a7d602dfa5 --- /dev/null +++ b/Task/String-interpolation--included-/Groovy/string-interpolation--included-.groovy @@ -0,0 +1,2 @@ +def adj = 'little' +assert 'Mary had a little lamb.' == "Mary had a ${adj} lamb." diff --git a/Task/String-interpolation--included-/Haskell/string-interpolation--included-.hs b/Task/String-interpolation--included-/Haskell/string-interpolation--included-.hs new file mode 100644 index 0000000000..c91a3b41ad --- /dev/null +++ b/Task/String-interpolation--included-/Haskell/string-interpolation--included-.hs @@ -0,0 +1,3 @@ +import Text.Printf + +main = printf "Mary had a %s lamb\n" "little" diff --git a/Task/String-interpolation--included-/HicEst/string-interpolation--included-.hicest b/Task/String-interpolation--included-/HicEst/string-interpolation--included-.hicest new file mode 100644 index 0000000000..fcbfe6dfa4 --- /dev/null +++ b/Task/String-interpolation--included-/HicEst/string-interpolation--included-.hicest @@ -0,0 +1,4 @@ +CHARACTER original="Mary had a X lamb", little = "little", output_string*100 + +output_string = original +EDIT(Text=output_string, Right='X', RePLaceby=little) diff --git a/Task/String-interpolation--included-/Icon/string-interpolation--included-.icon b/Task/String-interpolation--included-/Icon/string-interpolation--included-.icon new file mode 100644 index 0000000000..aa22b595f0 --- /dev/null +++ b/Task/String-interpolation--included-/Icon/string-interpolation--included-.icon @@ -0,0 +1,5 @@ + s2 := "humongous" + s3 := "little" + s1 := "Mary had a humongous lamb." + s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0) # replaces the first instance of s2 with s3 + while s1 ?:= tab(find(s2)) || (=s2,s3) || tab(0) # replaces all instances of s2 with s3, equivalent to replace diff --git a/Task/String-interpolation--included-/J/string-interpolation--included--1.j b/Task/String-interpolation--included-/J/string-interpolation--included--1.j new file mode 100644 index 0000000000..abbf2f38d9 --- /dev/null +++ b/Task/String-interpolation--included-/J/string-interpolation--included--1.j @@ -0,0 +1,9 @@ + require 'printf' + 'Mary had a %s lamb.' sprintf <'little' +Mary had a little lamb. + + require 'strings' + ('%s';'little') stringreplace 'Mary had a %s lamb.' +Mary had a little lamb. + 'Mary had a %s lamb.' rplc '%s';'little' +Mary had a little lamb. diff --git a/Task/String-interpolation--included-/J/string-interpolation--included--2.j b/Task/String-interpolation--included-/J/string-interpolation--included--2.j new file mode 100644 index 0000000000..2533a6f178 --- /dev/null +++ b/Task/String-interpolation--included-/J/string-interpolation--included--2.j @@ -0,0 +1 @@ + open'strings printf' diff --git a/Task/String-interpolation--included-/Java/string-interpolation--included-.java b/Task/String-interpolation--included-/Java/string-interpolation--included-.java new file mode 100644 index 0000000000..5fb2fc6ff8 --- /dev/null +++ b/Task/String-interpolation--included-/Java/string-interpolation--included-.java @@ -0,0 +1,9 @@ +String original = "Mary had a X lamb"; +String little = "little"; +String replaced = original.replace("X", little); //does not change the original String +System.out.println(replaced); +//Alternative: +System.out.printf("Mary had a %s lamb.", little); +//Alternative: +String formatted = String.format("Mary had a %s lamb.", little); +System.out.println(formatted); diff --git a/Task/String-interpolation--included-/JavaScript/string-interpolation--included-.js b/Task/String-interpolation--included-/JavaScript/string-interpolation--included-.js new file mode 100644 index 0000000000..50f68b54f3 --- /dev/null +++ b/Task/String-interpolation--included-/JavaScript/string-interpolation--included-.js @@ -0,0 +1,3 @@ +var original = "Mary had a X lamb"; +var little = "little"; +var replaced = original.replace("X", little); //does not change the original string diff --git a/Task/String-interpolation--included-/Lua/string-interpolation--included--1.lua b/Task/String-interpolation--included-/Lua/string-interpolation--included--1.lua new file mode 100644 index 0000000000..e83b29b66a --- /dev/null +++ b/Task/String-interpolation--included-/Lua/string-interpolation--included--1.lua @@ -0,0 +1,2 @@ +str = string.gsub( "Mary had a X lamb.", "X", "little" ) +print( str ) diff --git a/Task/String-interpolation--included-/Lua/string-interpolation--included--2.lua b/Task/String-interpolation--included-/Lua/string-interpolation--included--2.lua new file mode 100644 index 0000000000..08cc08b456 --- /dev/null +++ b/Task/String-interpolation--included-/Lua/string-interpolation--included--2.lua @@ -0,0 +1 @@ +print "Mary had a \n lamb" -- The \n is interpreted as an escape sequence for a newline diff --git a/Task/String-interpolation--included-/Mathematica/string-interpolation--included-.math b/Task/String-interpolation--included-/Mathematica/string-interpolation--included-.math new file mode 100644 index 0000000000..c85e9e2f47 --- /dev/null +++ b/Task/String-interpolation--included-/Mathematica/string-interpolation--included-.math @@ -0,0 +1,3 @@ +Extra = "little"; +StringReplace["Mary had a X lamb.", {"X" -> Extra}] +->"Mary had a little lamb." diff --git a/Task/String-interpolation--included-/Maxima/string-interpolation--included-.maxima b/Task/String-interpolation--included-/Maxima/string-interpolation--included-.maxima new file mode 100644 index 0000000000..b0a78c1d3a --- /dev/null +++ b/Task/String-interpolation--included-/Maxima/string-interpolation--included-.maxima @@ -0,0 +1 @@ +printf(true, "Mary had a ~a lamb", "little"); diff --git a/Task/String-interpolation--included-/Nemerle/string-interpolation--included-.nemerle b/Task/String-interpolation--included-/Nemerle/string-interpolation--included-.nemerle new file mode 100644 index 0000000000..8cc923f47b --- /dev/null +++ b/Task/String-interpolation--included-/Nemerle/string-interpolation--included-.nemerle @@ -0,0 +1,14 @@ +using System; +using System.Console; +using Nemerle.IO; // contains printf() and print() + +module Stringy +{ + Main() : void + { + def extra = "little"; + printf("Mary had a %s lamb.\n", extra); + print("Mary had a $extra lamb.\n"); + WriteLine($"Mary had a $extra lamb."); + } +} diff --git a/Task/String-interpolation--included-/NetRexx/string-interpolation--included-.netrexx b/Task/String-interpolation--included-/NetRexx/string-interpolation--included-.netrexx new file mode 100644 index 0000000000..dc27a14d5b --- /dev/null +++ b/Task/String-interpolation--included-/NetRexx/string-interpolation--included-.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols + +import java.text.MessageFormat +import java.text.FieldPosition + +useBif() +useMessageFormat() + +return + +method useBif public static + + st = "Mary had a %1$ lamb." + si = 'little' + + say st.changestr('%1$', si) + + return + +method useMessageFormat public static + + result = StringBuffer('') + + args = Object [ - + Object Integer(7), - + Object Date(), - + Object 'a disturbance in the Force' - + ] + msgfmt = MessageFormat('At {1, time} on {1, date}, there was {2} on planet {0, number, integer}.') + result = msgfmt.format(args, result, FieldPosition(0)) + say result + + return diff --git a/Task/String-interpolation--included-/OCaml/string-interpolation--included-.ocaml b/Task/String-interpolation--included-/OCaml/string-interpolation--included-.ocaml new file mode 100644 index 0000000000..d63335aa22 --- /dev/null +++ b/Task/String-interpolation--included-/OCaml/string-interpolation--included-.ocaml @@ -0,0 +1,2 @@ +let extra = "little" in +Printf.printf "Mary had a %s lamb." extra diff --git a/Task/String-interpolation--included-/Oz/string-interpolation--included-.oz b/Task/String-interpolation--included-/Oz/string-interpolation--included-.oz new file mode 100644 index 0000000000..3a187e946e --- /dev/null +++ b/Task/String-interpolation--included-/Oz/string-interpolation--included-.oz @@ -0,0 +1,4 @@ +declare + X = "little" +in + {System.showInfo "Mary had a "#X#" lamb"} diff --git a/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--1.pari b/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--1.pari new file mode 100644 index 0000000000..b35840c555 --- /dev/null +++ b/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--1.pari @@ -0,0 +1,6 @@ +GEN +string_interpolate(GEN n) +{ + pari_printf("The value was: %Ps.\n", n); + GEN s = pari_sprintf("Storing %Ps in a string", n); +} diff --git a/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--2.pari b/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--2.pari new file mode 100644 index 0000000000..02f545c44d --- /dev/null +++ b/Task/String-interpolation--included-/PARI-GP/string-interpolation--included--2.pari @@ -0,0 +1,2 @@ +s=Strprintf("The value was: %Ps", 1<<20); +printf("The value was: %Ps", 1<<20); diff --git a/Task/String-interpolation--included-/PHP/string-interpolation--included-.php b/Task/String-interpolation--included-/PHP/string-interpolation--included-.php new file mode 100644 index 0000000000..a1cd3f6051 --- /dev/null +++ b/Task/String-interpolation--included-/PHP/string-interpolation--included-.php @@ -0,0 +1,5 @@ + diff --git a/Task/String-interpolation--included-/Perl-6/string-interpolation--included-.pl6 b/Task/String-interpolation--included-/Perl-6/string-interpolation--included-.pl6 new file mode 100644 index 0000000000..63d43b06b8 --- /dev/null +++ b/Task/String-interpolation--included-/Perl-6/string-interpolation--included-.pl6 @@ -0,0 +1,5 @@ +my $extra = "little"; +say "Mary had a $extra lamb"; # variable interpolation +say "Mary had a { $extra } lamb"; # expression interpolation +printf "Mary had a %s lamb.\n", $extra; # standard printf +say $extra.fmt("Mary had a %s lamb"); # inside-out printf diff --git a/Task/String-interpolation--included-/Perl/string-interpolation--included-.pl b/Task/String-interpolation--included-/Perl/string-interpolation--included-.pl new file mode 100644 index 0000000000..856b9c7deb --- /dev/null +++ b/Task/String-interpolation--included-/Perl/string-interpolation--included-.pl @@ -0,0 +1,3 @@ +$extra = "little"; +print "Mary had a $extra lamb.\n"; +printf "Mary had a %s lamb.\n", $extra; diff --git a/Task/String-interpolation--included-/PicoLisp/string-interpolation--included-.l b/Task/String-interpolation--included-/PicoLisp/string-interpolation--included-.l new file mode 100644 index 0000000000..b03d97e005 --- /dev/null +++ b/Task/String-interpolation--included-/PicoLisp/string-interpolation--included-.l @@ -0,0 +1,2 @@ +(let Extra "little" + (prinl (text "Mary had a @1 lamb." Extra)) ) diff --git a/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro b/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro new file mode 100644 index 0000000000..3ae9464f96 --- /dev/null +++ b/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro @@ -0,0 +1,3 @@ +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-interpolation--included-/PureBasic/string-interpolation--included--1.purebasic b/Task/String-interpolation--included-/PureBasic/string-interpolation--included--1.purebasic new file mode 100644 index 0000000000..fa17fae525 --- /dev/null +++ b/Task/String-interpolation--included-/PureBasic/string-interpolation--included--1.purebasic @@ -0,0 +1 @@ +ReplaceString("Mary had a X lamb.","X","little") diff --git a/Task/String-interpolation--included-/PureBasic/string-interpolation--included--2.purebasic b/Task/String-interpolation--included-/PureBasic/string-interpolation--included--2.purebasic new file mode 100644 index 0000000000..68adba517c --- /dev/null +++ b/Task/String-interpolation--included-/PureBasic/string-interpolation--included--2.purebasic @@ -0,0 +1,16 @@ +; String variable can be defined by appending .s to its name during definition or by appending and using $ as a part of its name. +Define txt$, txtvar.s="little" + +;Load datasegment into variable txt$ +Restore Mary +Read.s txt$ + +; Replace X with "little" and store result in txt$ +txt$=ReplaceString(txt$,"X",txtvar) + +OpenConsole(): Print(txt$) + +DataSection: + Mary: + Data.s "Mary had a X lamb." +EndDataSection diff --git a/Task/String-interpolation--included-/Python/string-interpolation--included--1.py b/Task/String-interpolation--included-/Python/string-interpolation--included--1.py new file mode 100644 index 0000000000..58fe0068f4 --- /dev/null +++ b/Task/String-interpolation--included-/Python/string-interpolation--included--1.py @@ -0,0 +1,4 @@ +>>> original = 'Mary had a %s lamb.' +>>> extra = 'little' +>>> original % extra +'Mary had a little lamb.' diff --git a/Task/String-interpolation--included-/Python/string-interpolation--included--2.py b/Task/String-interpolation--included-/Python/string-interpolation--included--2.py new file mode 100644 index 0000000000..f6ad368fc7 --- /dev/null +++ b/Task/String-interpolation--included-/Python/string-interpolation--included--2.py @@ -0,0 +1,4 @@ +>>> original = 'Mary had a {extra} lamb.' +>>> extra = 'little' +>>> original.format(**locals()) +'Mary had a little lamb.' diff --git a/Task/String-interpolation--included-/Python/string-interpolation--included--3.py b/Task/String-interpolation--included-/Python/string-interpolation--included--3.py new file mode 100644 index 0000000000..b5c4b755e3 --- /dev/null +++ b/Task/String-interpolation--included-/Python/string-interpolation--included--3.py @@ -0,0 +1,4 @@ +>>> original = 'Mary had a {0} lamb.' +>>> extra = 'little' +>>> original.format(extra) +'Mary had a little lamb.' diff --git a/Task/String-interpolation--included-/Python/string-interpolation--included--4.py b/Task/String-interpolation--included-/Python/string-interpolation--included--4.py new file mode 100644 index 0000000000..ec6c3a151e --- /dev/null +++ b/Task/String-interpolation--included-/Python/string-interpolation--included--4.py @@ -0,0 +1,5 @@ +>>> from string import Template +>>> original = Template('Mary had a $extra lamb.') +>>> extra = 'little' +>>> original.substitute(**locals()) +'Mary had a little lamb.' diff --git a/Task/String-interpolation--included-/REBOL/string-interpolation--included-.rebol b/Task/String-interpolation--included-/REBOL/string-interpolation--included-.rebol new file mode 100644 index 0000000000..a9b2d64a29 --- /dev/null +++ b/Task/String-interpolation--included-/REBOL/string-interpolation--included-.rebol @@ -0,0 +1,7 @@ +str: "Mary had a <%size%> lamb" +size: "little" +build-markup str + +;REBOL3 also has the REWORD function +str: "Mary had a $size lamb" +reword str [size "little"] diff --git a/Task/String-interpolation--included-/REXX/string-interpolation--included-.rexx b/Task/String-interpolation--included-/REXX/string-interpolation--included-.rexx new file mode 100644 index 0000000000..287b14cf15 --- /dev/null +++ b/Task/String-interpolation--included-/REXX/string-interpolation--included-.rexx @@ -0,0 +1,27 @@ +/*REXX program to demonstrate string interpolation (string replacement).*/ + /*the string to be replaced is */ +replace = "little" /*usually a unique character(s) */ + /*string and is case sensative.*/ +original1 = "Mary had a X lamb." +new1 = changestr('X', original1, replace) +say 'original1 =' original1 +say 'replaced =' new1 +say + +original2 = "Mary had a % lamb." +new2 = changestr('%', original2, replace) +say 'original2 =' original2 +say 'replaced =' new2 +say + +original3 = "Mary had a $$$ lamb." +new3 = changestr('$$$',original3,replace) +say 'original3 =' original3 +say 'replaced3 =' new3 +say + +original4 = "Mary had a someKindOf lamb." +new3 = changestr('someKindOf', original4, "little") +say 'original4 =' original4 +say 'replaced4 =' new3 + /*stick a fork in it, we're done.*/ diff --git a/Task/String-interpolation--included-/Racket/string-interpolation--included-.rkt b/Task/String-interpolation--included-/Racket/string-interpolation--included-.rkt new file mode 100644 index 0000000000..b9652aa196 --- /dev/null +++ b/Task/String-interpolation--included-/Racket/string-interpolation--included-.rkt @@ -0,0 +1,3 @@ +#lang racket + +(format "Mary had a ~a lamb" "little") diff --git a/Task/String-interpolation--included-/Ruby/string-interpolation--included-.rb b/Task/String-interpolation--included-/Ruby/string-interpolation--included-.rb new file mode 100644 index 0000000000..0fefa8467b --- /dev/null +++ b/Task/String-interpolation--included-/Ruby/string-interpolation--included-.rb @@ -0,0 +1,6 @@ +irb(main):001:0> extra = 'little' +=> "little" +irb(main):002:0> "Mary had a #{extra} lamb." +=> "Mary had a little lamb." +irb(main):003:0> "Mary had a %s lamb." % extra +=> "Mary had a little lamb." diff --git a/Task/String-interpolation--included-/Run-BASIC/string-interpolation--included-.run b/Task/String-interpolation--included-/Run-BASIC/string-interpolation--included-.run new file mode 100644 index 0000000000..05ecfce12d --- /dev/null +++ b/Task/String-interpolation--included-/Run-BASIC/string-interpolation--included-.run @@ -0,0 +1,2 @@ +a$ = Mary had a X lamb." +a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X") diff --git a/Task/String-interpolation--included-/SNOBOL4/string-interpolation--included-.sno b/Task/String-interpolation--included-/SNOBOL4/string-interpolation--included-.sno new file mode 100644 index 0000000000..59cbd90337 --- /dev/null +++ b/Task/String-interpolation--included-/SNOBOL4/string-interpolation--included-.sno @@ -0,0 +1,5 @@ + s1 = "Mary had a humongous lamb." + s2 = "humongous" + s3 = "little" + s1 s2 = s3 +end diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala new file mode 100644 index 0000000000..29f25d0f84 --- /dev/null +++ b/Task/String-interpolation--included-/Scala/string-interpolation--included--1.scala @@ -0,0 +1,2 @@ +val extra = "little" +val result = s"Mary had a $extra lamb." diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala new file mode 100644 index 0000000000..477c3e68fa --- /dev/null +++ b/Task/String-interpolation--included-/Scala/string-interpolation--included--2.scala @@ -0,0 +1 @@ +Mary had a little lamb. diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala new file mode 100644 index 0000000000..7a0238fb46 --- /dev/null +++ b/Task/String-interpolation--included-/Scala/string-interpolation--included--3.scala @@ -0,0 +1,3 @@ +val original = "Mary had a %s lamb." +val extra = "little" +original format extra diff --git a/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala b/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala new file mode 100644 index 0000000000..477c3e68fa --- /dev/null +++ b/Task/String-interpolation--included-/Scala/string-interpolation--included--4.scala @@ -0,0 +1 @@ +Mary had a little lamb. diff --git a/Task/String-interpolation--included-/Sed/string-interpolation--included-.sed b/Task/String-interpolation--included-/Sed/string-interpolation--included-.sed new file mode 100644 index 0000000000..d693c06908 --- /dev/null +++ b/Task/String-interpolation--included-/Sed/string-interpolation--included-.sed @@ -0,0 +1,3 @@ +#!/bin/bash +# Usage example: . interpolate "Mary has a X lamb" "quite annoying" +echo "$1" | sed "s/ X / $2 /g" diff --git a/Task/String-interpolation--included-/Seed7/string-interpolation--included-.seed7 b/Task/String-interpolation--included-/Seed7/string-interpolation--included-.seed7 new file mode 100644 index 0000000000..7367a1fe63 --- /dev/null +++ b/Task/String-interpolation--included-/Seed7/string-interpolation--included-.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const string: original is "Mary had a X lamb"; + const string: little is "little"; + var string: replaced is ""; + begin + replaced := replace(original, "X", little); + writeln(replaced); + end func; diff --git a/Task/String-interpolation--included-/TUSCRIPT/string-interpolation--included-.tuscript b/Task/String-interpolation--included-/TUSCRIPT/string-interpolation--included-.tuscript new file mode 100644 index 0000000000..8005d75ad2 --- /dev/null +++ b/Task/String-interpolation--included-/TUSCRIPT/string-interpolation--included-.tuscript @@ -0,0 +1,11 @@ +$$ MODE TUSCRIPT + +sentence_old="Mary had a X lamb." + +values=* +DATA little +DATA big + +sentence_new=SUBSTITUTE (sentence_old,":X:",0,0,values) +PRINT sentence_old +PRINT sentence_new diff --git a/Task/String-interpolation--included-/Tcl/string-interpolation--included--1.tcl b/Task/String-interpolation--included-/Tcl/string-interpolation--included--1.tcl new file mode 100644 index 0000000000..d80d6c8875 --- /dev/null +++ b/Task/String-interpolation--included-/Tcl/string-interpolation--included--1.tcl @@ -0,0 +1,7 @@ +set size "little" +puts "Mary had a $size lamb." + +proc RandomWord {args} { + lindex $args [expr {int(rand()*[llength $args])}] +} +puts "Mary had a [RandomWord little big] lamb." diff --git a/Task/String-interpolation--included-/Tcl/string-interpolation--included--2.tcl b/Task/String-interpolation--included-/Tcl/string-interpolation--included--2.tcl new file mode 100644 index 0000000000..414cabc774 --- /dev/null +++ b/Task/String-interpolation--included-/Tcl/string-interpolation--included--2.tcl @@ -0,0 +1 @@ +puts [format "Mary had a %s %s." [RandomWord little big] [RandomWord lamb piglet calf]] diff --git a/Task/String-interpolation--included-/Tcl/string-interpolation--included--3.tcl b/Task/String-interpolation--included-/Tcl/string-interpolation--included--3.tcl new file mode 100644 index 0000000000..a0a164d6ab --- /dev/null +++ b/Task/String-interpolation--included-/Tcl/string-interpolation--included--3.tcl @@ -0,0 +1,2 @@ +set s "Mary had a @SIZE@ lamb." +puts [string map {@SIZE@ "miniscule"} $s] diff --git a/Task/String-interpolation--included-/Tcl/string-interpolation--included--4.tcl b/Task/String-interpolation--included-/Tcl/string-interpolation--included--4.tcl new file mode 100644 index 0000000000..67c0b0461f --- /dev/null +++ b/Task/String-interpolation--included-/Tcl/string-interpolation--included--4.tcl @@ -0,0 +1,8 @@ +set grandpa {$daddy}; set grandma \$mommy +set daddy myself; set mommy {lil' bro} +set fun1 \[string\ to +set fun2 lower +set lower middle +set middle upper +set fun3 {aNd]} +puts [subst "$grandpa $fun1$[subst $$fun2] $fun3 $grandma"] diff --git a/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--1.sh b/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--1.sh new file mode 100644 index 0000000000..19042e6272 --- /dev/null +++ b/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--1.sh @@ -0,0 +1,4 @@ +extra='little' +echo Mary had a $extra lamb. +echo "Mary had a $extra lamb." +printf "Mary had a %s lamb.\n" $extra diff --git a/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--2.sh b/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--2.sh new file mode 100644 index 0000000000..72cc78f16a --- /dev/null +++ b/Task/String-interpolation--included-/UNIX-Shell/string-interpolation--included--2.sh @@ -0,0 +1,4 @@ +set extra='little' +echo Mary had a $extra lamb. +echo "Mary had a $extra lamb." +printf "Mary had a %s lamb.\n" $extra diff --git a/Task/String-interpolation--included-/Ursala/string-interpolation--included--1.ursala b/Task/String-interpolation--included-/Ursala/string-interpolation--included--1.ursala new file mode 100644 index 0000000000..89ad0417f1 --- /dev/null +++ b/Task/String-interpolation--included-/Ursala/string-interpolation--included--1.ursala @@ -0,0 +1 @@ +-[foo-[ x ]-bar]- diff --git a/Task/String-interpolation--included-/Ursala/string-interpolation--included--2.ursala b/Task/String-interpolation--included-/Ursala/string-interpolation--included--2.ursala new file mode 100644 index 0000000000..710b15caf9 --- /dev/null +++ b/Task/String-interpolation--included-/Ursala/string-interpolation--included--2.ursala @@ -0,0 +1 @@ +-[foo-[. f ]-bar]- diff --git a/Task/String-interpolation--included-/Ursala/string-interpolation--included--3.ursala b/Task/String-interpolation--included-/Ursala/string-interpolation--included--3.ursala new file mode 100644 index 0000000000..d79a63cf9b --- /dev/null +++ b/Task/String-interpolation--included-/Ursala/string-interpolation--included--3.ursala @@ -0,0 +1,5 @@ +x = <'little'> + +#show+ + +main = -[Mary had a -[. ~& ]- lamb.]- x diff --git a/Task/String-length/0DESCRIPTION b/Task/String-length/0DESCRIPTION new file mode 100644 index 0000000000..2702bb034a --- /dev/null +++ b/Task/String-length/0DESCRIPTION @@ -0,0 +1,5 @@ +In this task, the goal is to find the character and byte length of a string. This means encodings like [[UTF-8]] need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By ''character'', we mean an individual Unicode ''code point'', not a user-visible ''grapheme'' containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. + +Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, '''not''' 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. + +Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. diff --git a/Task/String-length/1META.yaml b/Task/String-length/1META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/String-length/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/String-length/4D/string-length.4d b/Task/String-length/4D/string-length.4d new file mode 100644 index 0000000000..ff53586457 --- /dev/null +++ b/Task/String-length/4D/string-length.4d @@ -0,0 +1 @@ +$length:=Length("Hello, world!") diff --git a/Task/String-length/ALGOL-68/string-length-1.alg b/Task/String-length/ALGOL-68/string-length-1.alg new file mode 100644 index 0000000000..aa5ea0e982 --- /dev/null +++ b/Task/String-length/ALGOL-68/string-length-1.alg @@ -0,0 +1,7 @@ +BITS bits := bits pack((TRUE, TRUE, FALSE, FALSE)); # packed array of BOOL # +BYTES bytes := bytes pack("Hello, world"); # packed array of CHAR # +print(( + "BITS and BYTES are fixed width:", new line, + "bits width:", bits width, ", max bits: ", max bits, ", bits:", bits, new line, + "bytes width: ",bytes width, ", UPB:",UPB STRING(bytes), ", string:", STRING(bytes),"!", new line +)) diff --git a/Task/String-length/ALGOL-68/string-length-2.alg b/Task/String-length/ALGOL-68/string-length-2.alg new file mode 100644 index 0000000000..520f7c053f --- /dev/null +++ b/Task/String-length/ALGOL-68/string-length-2.alg @@ -0,0 +1,7 @@ +STRING str := "hello, world"; +INT length := UPB str; +printf(($"Length of """g""" is "g(3)l$,str,length)); + +printf(($l"STRINGS can start at -1, in which case LWB must be used:"l$)); +STRING s := "abcd"[@-1]; +print(("s:",s, ", LWB:", LWB s, ", UPB:",UPB s, ", LEN:",UPB s - LWB s + 1)) diff --git a/Task/String-length/AWK/string-length-1.awk b/Task/String-length/AWK/string-length-1.awk new file mode 100644 index 0000000000..6389f1fcd6 --- /dev/null +++ b/Task/String-length/AWK/string-length-1.awk @@ -0,0 +1,4 @@ +w=length("Hello, world!") # static string example +x=length("Hello," s " world!") # dynamic string example +y=length($1) # input field example +z=length(s) # variable name example diff --git a/Task/String-length/AWK/string-length-2.awk b/Task/String-length/AWK/string-length-2.awk new file mode 100644 index 0000000000..0b96ecb3a1 --- /dev/null +++ b/Task/String-length/AWK/string-length-2.awk @@ -0,0 +1,2 @@ +#!/usr/bin/awk -f +{print"The length of this line is "length($0)} diff --git a/Task/String-length/ActionScript/string-length.as b/Task/String-length/ActionScript/string-length.as new file mode 100644 index 0000000000..ec9270ff1f --- /dev/null +++ b/Task/String-length/ActionScript/string-length.as @@ -0,0 +1 @@ +myStrVar.length() diff --git a/Task/String-length/Ada/string-length-1.ada b/Task/String-length/Ada/string-length-1.ada new file mode 100644 index 0000000000..a6926d9537 --- /dev/null +++ b/Task/String-length/Ada/string-length-1.ada @@ -0,0 +1,2 @@ +Str : String := "Hello World"; +Length : constant Natural := Str'Size / 8; diff --git a/Task/String-length/Ada/string-length-2.ada b/Task/String-length/Ada/string-length-2.ada new file mode 100644 index 0000000000..0fc57729a6 --- /dev/null +++ b/Task/String-length/Ada/string-length-2.ada @@ -0,0 +1,6 @@ +Latin_1_Str : String := "Hello World"; +UCS_16_Str : Wide_String := "Hello World"; +Unicode_Str : Wide_Wide_String := "Hello World"; +Latin_1_Length : constant Natural := Latin_1_Str'Length; +UCS_16_Length : constant Natural := UCS_16_Str'Length; +Unicode_Length : constant Natural := Unicode_Str'Length; diff --git a/Task/String-length/AppleScript/string-length-1.applescript b/Task/String-length/AppleScript/string-length-1.applescript new file mode 100644 index 0000000000..f8de43ad5a --- /dev/null +++ b/Task/String-length/AppleScript/string-length-1.applescript @@ -0,0 +1 @@ +count of "Hello World" diff --git a/Task/String-length/AppleScript/string-length-2.applescript b/Task/String-length/AppleScript/string-length-2.applescript new file mode 100644 index 0000000000..1a8df2aea2 --- /dev/null +++ b/Task/String-length/AppleScript/string-length-2.applescript @@ -0,0 +1,12 @@ +set inString to "Hello World" as Unicode text +set byteCount to 0 +set idList to id of inString + +repeat with incr in idList + set byteCount to byteCount + 2 + if incr as integer > 65535 then + set byteCount to byteCount + 2 + end if +end repeat + +byteCount diff --git a/Task/String-length/AppleScript/string-length-3.applescript b/Task/String-length/AppleScript/string-length-3.applescript new file mode 100644 index 0000000000..f8de43ad5a --- /dev/null +++ b/Task/String-length/AppleScript/string-length-3.applescript @@ -0,0 +1 @@ +count of "Hello World" diff --git a/Task/String-length/AppleScript/string-length-4.applescript b/Task/String-length/AppleScript/string-length-4.applescript new file mode 100644 index 0000000000..303cf82597 --- /dev/null +++ b/Task/String-length/AppleScript/string-length-4.applescript @@ -0,0 +1 @@ +count "Hello World" diff --git a/Task/String-length/AutoHotkey/string-length-1.ahk b/Task/String-length/AutoHotkey/string-length-1.ahk new file mode 100644 index 0000000000..ad0fcf53a8 --- /dev/null +++ b/Task/String-length/AutoHotkey/string-length-1.ahk @@ -0,0 +1 @@ +Msgbox % StrLen("Hello World") diff --git a/Task/String-length/AutoHotkey/string-length-2.ahk b/Task/String-length/AutoHotkey/string-length-2.ahk new file mode 100644 index 0000000000..3098fe7279 --- /dev/null +++ b/Task/String-length/AutoHotkey/string-length-2.ahk @@ -0,0 +1,3 @@ +String := "Hello World" +StringLen, Length, String +Msgbox % Length diff --git a/Task/String-length/BASIC/string-length-1.basic b/Task/String-length/BASIC/string-length-1.basic new file mode 100644 index 0000000000..2fe83d66ef --- /dev/null +++ b/Task/String-length/BASIC/string-length-1.basic @@ -0,0 +1,2 @@ + INPUT a$ + PRINT LEN(a$) diff --git a/Task/String-length/BASIC/string-length-2.basic b/Task/String-length/BASIC/string-length-2.basic new file mode 100644 index 0000000000..5ee6e5673c --- /dev/null +++ b/Task/String-length/BASIC/string-length-2.basic @@ -0,0 +1,2 @@ +10 INPUT a$ +20 PRINT LEN(a$) diff --git a/Task/String-length/BBC-BASIC/string-length-1.bbc b/Task/String-length/BBC-BASIC/string-length-1.bbc new file mode 100644 index 0000000000..8f15146cef --- /dev/null +++ b/Task/String-length/BBC-BASIC/string-length-1.bbc @@ -0,0 +1,2 @@ + INPUT text$ + PRINT LEN(text$) diff --git a/Task/String-length/BBC-BASIC/string-length-2.bbc b/Task/String-length/BBC-BASIC/string-length-2.bbc new file mode 100644 index 0000000000..46fabc4370 --- /dev/null +++ b/Task/String-length/BBC-BASIC/string-length-2.bbc @@ -0,0 +1,12 @@ + CP_ACP = 0 + CP_UTF8 = &FDE9 + + textA$ = "møøse" + textW$ = " " + textU$ = " " + + SYS "MultiByteToWideChar", CP_ACP, 0, textA$, -1, !^textW$, LEN(textW$)/2 TO nW% + SYS "WideCharToMultiByte", CP_UTF8, 0, textW$, -1, !^textU$, LEN(textU$), 0, 0 + PRINT "Length in bytes (ANSI encoding) = " ; LEN(textA$) + PRINT "Length in bytes (UTF-16 encoding) = " ; 2*(nW%-1) + PRINT "Length in bytes (UTF-8 encoding) = " ; LEN($$!^textU$) diff --git a/Task/String-length/Batch-File/string-length.bat b/Task/String-length/Batch-File/string-length.bat new file mode 100644 index 0000000000..fc7d71e9a6 --- /dev/null +++ b/Task/String-length/Batch-File/string-length.bat @@ -0,0 +1,17 @@ +@echo off +setlocal enabledelayedexpansion +call :length %1 res +echo length of %1 is %res% +goto :eof + +:length +set str=%~1 +set cnt=0 +:loop +if "%str%" equ "" ( + set %2=%cnt% + goto :eof + ) +set str=!str:~1! +set /a cnt = cnt + 1 +goto loop diff --git a/Task/String-length/Bracmat/string-length-1.bracmat b/Task/String-length/Bracmat/string-length-1.bracmat new file mode 100644 index 0000000000..b5c1316a1b --- /dev/null +++ b/Task/String-length/Bracmat/string-length-1.bracmat @@ -0,0 +1,7 @@ +(ByteLength= + length +. @(!arg:? [?length) + & !length +); + +out$ByteLength$𝔘𝔫𝔦𝔠𝔬𝔡𝔢 diff --git a/Task/String-length/Bracmat/string-length-2.bracmat b/Task/String-length/Bracmat/string-length-2.bracmat new file mode 100644 index 0000000000..7f627d2850 --- /dev/null +++ b/Task/String-length/Bracmat/string-length-2.bracmat @@ -0,0 +1,16 @@ +(CharacterLength= + length c +. 0:?length + & @( !arg + : ? + ( %?c + & utf$!c:?k + & 1+!length:?length + & ~ + ) + ? + ) + | !length +); + +out$CharacterLength$𝔘𝔫𝔦𝔠𝔬𝔡𝔢 diff --git a/Task/String-length/Bracmat/string-length-3.bracmat b/Task/String-length/Bracmat/string-length-3.bracmat new file mode 100644 index 0000000000..8ab082c6bd --- /dev/null +++ b/Task/String-length/Bracmat/string-length-3.bracmat @@ -0,0 +1,14 @@ +(CharacterLength= + length c p +. 0:?length:?p + & @( !arg + : ? + ( [!p %?c + & utf$!c:?k + & 1+!length:?length + ) + ([?p&~) + ? + ) + | !length +); diff --git a/Task/String-length/C++/string-length-1.cpp b/Task/String-length/C++/string-length-1.cpp new file mode 100644 index 0000000000..b1622b81ea --- /dev/null +++ b/Task/String-length/C++/string-length-1.cpp @@ -0,0 +1,11 @@ +#include // (not !) +using std::string; + +int main() +{ + string s = "Hello, world!"; + string::size_type length = s.length(); // option 1: In Characters/Bytes + string::size_type size = s.size(); // option 2: In Characters/Bytes + // In bytes same as above since sizeof(char) == 1 + string::size_type bytes = s.length() * sizeof(string::value_type); +} diff --git a/Task/String-length/C++/string-length-2.cpp b/Task/String-length/C++/string-length-2.cpp new file mode 100644 index 0000000000..129cb49e5f --- /dev/null +++ b/Task/String-length/C++/string-length-2.cpp @@ -0,0 +1,8 @@ +#include +using std::wstring; + +int main() +{ + wstring s = L"\u304A\u306F\u3088\u3046"; + wstring::size_type length = s.length() * sizeof(wstring::value_type); // in bytes +} diff --git a/Task/String-length/C++/string-length-3.cpp b/Task/String-length/C++/string-length-3.cpp new file mode 100644 index 0000000000..63cabd8739 --- /dev/null +++ b/Task/String-length/C++/string-length-3.cpp @@ -0,0 +1,8 @@ +#include +using std::wstring; + +int main() +{ + wstring s = L"\u304A\u306F\u3088\u3046"; + wstring::size_type length = s.length(); +} diff --git a/Task/String-length/C++/string-length-4.cpp b/Task/String-length/C++/string-length-4.cpp new file mode 100644 index 0000000000..c24fb4aea1 --- /dev/null +++ b/Task/String-length/C++/string-length-4.cpp @@ -0,0 +1,9 @@ +#include +#include +int main() +{ + std::string utf8 = "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // U+007a, U+00df, U+6c34, U+1d10b + std::cout << "Byte length: " << utf8.size() << '\n'; + std::wstring_convert, char32_t> conv; + std::cout << "Character length: " << conv.from_bytes(utf8).size() << '\n'; +} diff --git a/Task/String-length/C++/string-length-5.cpp b/Task/String-length/C++/string-length-5.cpp new file mode 100644 index 0000000000..3e7c176fc1 --- /dev/null +++ b/Task/String-length/C++/string-length-5.cpp @@ -0,0 +1,37 @@ +#include // for mbstate_t +#include + +// give the character length for a given named locale +std::size_t char_length(std::string const& text, char const* locale_name) +{ + // locales work on pointers; get length and data from string and + // then don't touch the original string any more, to avoid + // invalidating the data pointer + std::size_t len = text.length(); + char const* input = text.data(); + + // get the named locale + std::locale loc(locale_name); + + // get the conversion facet of the locale + typedef std::codecvt cvt_type; + cvt_type const& cvt = std::use_facet(loc); + + // allocate buffer for conversion destination + std::size_t bufsize = cvt.max_length()*len; + wchar_t* destbuf = new wchar_t[bufsize]; + wchar_t* dest_end; + + // do the conversion + mbstate_t state = mbstate_t(); + cvt.in(state, input, input+len, input, destbuf, destbuf+bufsize, dest_end); + + // determine the length of the converted sequence + std::size_t length = dest_end - destbuf; + + // get rid of the buffer + delete[] destbuf; + + // return the result + return length; +} diff --git a/Task/String-length/C++/string-length-6.cpp b/Task/String-length/C++/string-length-6.cpp new file mode 100644 index 0000000000..d046ebad57 --- /dev/null +++ b/Task/String-length/C++/string-length-6.cpp @@ -0,0 +1,10 @@ +#include + +int main() +{ + // Tür (German for door) in UTF8 + std::cout << char_length("\x54\xc3\xbc\x72", "de_DE.utf8") << "\n"; // outputs 3 + + // Tür in ISO-8859-1 + std::cout << char_length("\x54\xfc\x72", "de_DE") << "\n"; // outputs 3 +} diff --git a/Task/String-length/C/string-length-1.c b/Task/String-length/C/string-length-1.c new file mode 100644 index 0000000000..9877b13004 --- /dev/null +++ b/Task/String-length/C/string-length-1.c @@ -0,0 +1,9 @@ +#include + +int main(void) +{ + const char *string = "Hello, world!"; + size_t length = strlen(string); + + return 0; +} diff --git a/Task/String-length/C/string-length-2.c b/Task/String-length/C/string-length-2.c new file mode 100644 index 0000000000..994675f611 --- /dev/null +++ b/Task/String-length/C/string-length-2.c @@ -0,0 +1,10 @@ +int main(void) +{ + const char *string = "Hello, world!"; + size_t length = 0; + + const char *p = string; + while (*p++ != '\0') length++; + + return 0; +} diff --git a/Task/String-length/C/string-length-3.c b/Task/String-length/C/string-length-3.c new file mode 100644 index 0000000000..ea910b8648 --- /dev/null +++ b/Task/String-length/C/string-length-3.c @@ -0,0 +1,9 @@ +#include + +int main(void) +{ + char s[] = "Hello, world!"; + size_t length = sizeof s - 1; + + return 0; +} diff --git a/Task/String-length/C/string-length-4.c b/Task/String-length/C/string-length-4.c new file mode 100644 index 0000000000..250f9ab865 --- /dev/null +++ b/Task/String-length/C/string-length-4.c @@ -0,0 +1,14 @@ +#include +#include + +int main(void) +{ + wchar_t *s = L"\x304A\x306F\x3088\x3046"; /* Japanese hiragana ohayou */ + size_t length; + + length = wcslen(s); + printf("Length in characters = %d\n", length); + printf("Length in bytes = %d\n", sizeof(s) * sizeof(wchar_t)); + + return 0; +} diff --git a/Task/String-length/C/string-length-5.c b/Task/String-length/C/string-length-5.c new file mode 100644 index 0000000000..183fc8161b --- /dev/null +++ b/Task/String-length/C/string-length-5.c @@ -0,0 +1,13 @@ +#include +#include +#include + +int main() +{ + setlocale(LC_CTYPE, ""); + char moose[] = "møøse"; + printf("bytes: %d\n", sizeof(moose) - 1); + printf("chars: %d\n", (int)mbstowcs(0, moose, 0)); + + return 0; +} diff --git a/Task/String-length/Clean/string-length.clean b/Task/String-length/Clean/string-length.clean new file mode 100644 index 0000000000..f955d509e5 --- /dev/null +++ b/Task/String-length/Clean/string-length.clean @@ -0,0 +1,6 @@ +import StdEnv + +strlen :: String -> Int +strlen string = size string + +Start = strlen "Hello, world!" diff --git a/Task/String-length/Clojure/string-length-1.clj b/Task/String-length/Clojure/string-length-1.clj new file mode 100644 index 0000000000..6388a4f936 --- /dev/null +++ b/Task/String-length/Clojure/string-length-1.clj @@ -0,0 +1,2 @@ +(count (.getBytes "Hello, world!")) ; 13 bytes +(count (.getBytes "π")) ; two bytes diff --git a/Task/String-length/Clojure/string-length-2.clj b/Task/String-length/Clojure/string-length-2.clj new file mode 100644 index 0000000000..a7fa06fd2a --- /dev/null +++ b/Task/String-length/Clojure/string-length-2.clj @@ -0,0 +1 @@ +(count "Hello, world!") diff --git a/Task/String-length/ColdFusion/string-length-1.cfm b/Task/String-length/ColdFusion/string-length-1.cfm new file mode 100644 index 0000000000..1dca5aafb7 --- /dev/null +++ b/Task/String-length/ColdFusion/string-length-1.cfm @@ -0,0 +1 @@ +#len("Hello World")# diff --git a/Task/String-length/ColdFusion/string-length-2.cfm b/Task/String-length/ColdFusion/string-length-2.cfm new file mode 100644 index 0000000000..1dca5aafb7 --- /dev/null +++ b/Task/String-length/ColdFusion/string-length-2.cfm @@ -0,0 +1 @@ +#len("Hello World")# diff --git a/Task/String-length/Common-Lisp/string-length-1.lisp b/Task/String-length/Common-Lisp/string-length-1.lisp new file mode 100644 index 0000000000..4a14efc5f2 --- /dev/null +++ b/Task/String-length/Common-Lisp/string-length-1.lisp @@ -0,0 +1 @@ +(length (sb-ext:string-to-octets "Hello Wørld")) diff --git a/Task/String-length/Common-Lisp/string-length-2.lisp b/Task/String-length/Common-Lisp/string-length-2.lisp new file mode 100644 index 0000000000..7b04bbe832 --- /dev/null +++ b/Task/String-length/Common-Lisp/string-length-2.lisp @@ -0,0 +1 @@ +(length "Hello World") diff --git a/Task/String-length/Component-Pascal/string-length-1.component b/Task/String-length/Component-Pascal/string-length-1.component new file mode 100644 index 0000000000..df2f7ce921 --- /dev/null +++ b/Task/String-length/Component-Pascal/string-length-1.component @@ -0,0 +1,14 @@ +MODULE TestLen; + + IMPORT Out; + + PROCEDURE DoCharLength*; + VAR s: ARRAY 16 OF CHAR; len: INTEGER; + BEGIN + s := "møøse"; + len := LEN(s$); + Out.String("s: "); Out.String(s); Out.Ln; + Out.String("Length of characters: "); Out.Int(len, 0); Out.Ln + END DoCharLength; + +END TestLen. diff --git a/Task/String-length/Component-Pascal/string-length-2.component b/Task/String-length/Component-Pascal/string-length-2.component new file mode 100644 index 0000000000..c5adc37289 --- /dev/null +++ b/Task/String-length/Component-Pascal/string-length-2.component @@ -0,0 +1,15 @@ +MODULE TestLen; + + IMPORT Out; + + PROCEDURE DoByteLength*; + VAR s: ARRAY 16 OF CHAR; len, v: INTEGER; + BEGIN + s := "møøse"; + len := LEN(s$); + v := SIZE(CHAR) * len; + Out.String("s: "); Out.String(s); Out.Ln; + Out.String("Length of characters in bytes: "); Out.Int(v, 0); Out.Ln + END DoByteLength; + +END TestLen. diff --git a/Task/String-length/D/string-length-1.d b/Task/String-length/D/string-length-1.d new file mode 100644 index 0000000000..40d3ef37c3 --- /dev/null +++ b/Task/String-length/D/string-length-1.d @@ -0,0 +1,31 @@ +import std.stdio; + +void showByteLen(T)(T[] str) { + writefln("Byte length: %2d - %(%02x%)", + str.length * T.sizeof, cast(ubyte[])str); +} + +void main() { + string s1a = "møøse"; // UTF-8 + showByteLen(s1a); + wstring s1b = "møøse"; // UTF-16 + showByteLen(s1b); + dstring s1c = "møøse"; // UTF-32 + showByteLen(s1c); + writeln(); + + string s2a = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showByteLen(s2a); + wstring s2b = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showByteLen(s2b); + dstring s2c = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showByteLen(s2c); + writeln(); + + string s3a = "J̲o̲s̲é̲"; + showByteLen(s3a); + wstring s3b = "J̲o̲s̲é̲"; + showByteLen(s3b); + dstring s3c = "J̲o̲s̲é̲"; + showByteLen(s3c); +} diff --git a/Task/String-length/D/string-length-2.d b/Task/String-length/D/string-length-2.d new file mode 100644 index 0000000000..ef108e496e --- /dev/null +++ b/Task/String-length/D/string-length-2.d @@ -0,0 +1,31 @@ +import std.stdio, std.range, std.conv; + +void showCodePointsLen(T)(T[] str) { + writefln("Character length: %2d - %(%x %)", + str.walkLength(), cast(uint[])to!(dchar[])(str)); +} + +void main() { + string s1a = "møøse"; // UTF-8 + showCodePointsLen(s1a); + wstring s1b = "møøse"; // UTF-16 + showCodePointsLen(s1b); + dstring s1c = "møøse"; // UTF-32 + showCodePointsLen(s1c); + writeln(); + + string s2a = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showCodePointsLen(s2a); + wstring s2b = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showCodePointsLen(s2b); + dstring s2c = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢"; + showCodePointsLen(s2c); + writeln(); + + string s3a = "J̲o̲s̲é̲"; + showCodePointsLen(s3a); + wstring s3b = "J̲o̲s̲é̲"; + showCodePointsLen(s3b); + dstring s3c = "J̲o̲s̲é̲"; + showCodePointsLen(s3c); +} diff --git a/Task/String-length/Dc/string-length.dc b/Task/String-length/Dc/string-length.dc new file mode 100644 index 0000000000..1b656110de --- /dev/null +++ b/Task/String-length/Dc/string-length.dc @@ -0,0 +1 @@ +[abcde]Zp diff --git a/Task/String-length/E/string-length.e b/Task/String-length/E/string-length.e new file mode 100644 index 0000000000..88895317bc --- /dev/null +++ b/Task/String-length/E/string-length.e @@ -0,0 +1 @@ +"Hello World".size() diff --git a/Task/String-length/Euphoria/string-length.euphoria b/Task/String-length/Euphoria/string-length.euphoria new file mode 100644 index 0000000000..bf4e4ba651 --- /dev/null +++ b/Task/String-length/Euphoria/string-length.euphoria @@ -0,0 +1 @@ +print(1,length("Hello World")) diff --git a/Task/String-length/Factor/string-length-1.factor b/Task/String-length/Factor/string-length-1.factor new file mode 100644 index 0000000000..6d90253531 --- /dev/null +++ b/Task/String-length/Factor/string-length-1.factor @@ -0,0 +1,2 @@ +: string-byte-length ( string -- n ) [ code-point-length ] map-sum ; +: string-byte-length-2 ( string -- n ) utf8 encode length ; diff --git a/Task/String-length/Factor/string-length-2.factor b/Task/String-length/Factor/string-length-2.factor new file mode 100644 index 0000000000..7f5e3b64da --- /dev/null +++ b/Task/String-length/Factor/string-length-2.factor @@ -0,0 +1 @@ +length diff --git a/Task/String-length/Fantom/string-length-1.fantom b/Task/String-length/Fantom/string-length-1.fantom new file mode 100644 index 0000000000..e7cc182a57 --- /dev/null +++ b/Task/String-length/Fantom/string-length-1.fantom @@ -0,0 +1,14 @@ +fansh> c := "møøse" +møøse +fansh> c.toBuf.size // find the byte length of the string in default (UTF8) encoding +7 +fansh> c.toBuf.toHex // display UTF8 representation +6dc3b8c3b87365 +fansh> c.toBuf(Charset.utf16LE).size // byte length in UTF16 little-endian +10 +fansh> c.toBuf(Charset.utf16LE).toHex // display as UTF16 little-endian +6d00f800f80073006500 +fansh> c.toBuf(Charset.utf16BE).size // byte length in UTF16 big-endian +10 +fansh> c.toBuf(Charset.utf16BE).toHex // display as UTF16 big-endian +006d00f800f800730065 diff --git a/Task/String-length/Fantom/string-length-2.fantom b/Task/String-length/Fantom/string-length-2.fantom new file mode 100644 index 0000000000..f45e6b1b8f --- /dev/null +++ b/Task/String-length/Fantom/string-length-2.fantom @@ -0,0 +1,4 @@ +fansh> c := "møøse" +møøse +fansh> c.size +5 diff --git a/Task/String-length/Forth/string-length-1.fth b/Task/String-length/Forth/string-length-1.fth new file mode 100644 index 0000000000..f6da60a616 --- /dev/null +++ b/Task/String-length/Forth/string-length-1.fth @@ -0,0 +1,3 @@ +CREATE s ," Hello world" \ create string "s" +s C@ ( -- length=11 ) +s COUNT ( addr len ) \ convert to a stack string, described below diff --git a/Task/String-length/Forth/string-length-2.fth b/Task/String-length/Forth/string-length-2.fth new file mode 100644 index 0000000000..3b2b331dc3 --- /dev/null +++ b/Task/String-length/Forth/string-length-2.fth @@ -0,0 +1,2 @@ +S" string" ( addr len) +DUP . \ 6 diff --git a/Task/String-length/Forth/string-length-3.fth b/Task/String-length/Forth/string-length-3.fth new file mode 100644 index 0000000000..56bf842075 --- /dev/null +++ b/Task/String-length/Forth/string-length-3.fth @@ -0,0 +1,9 @@ +2 base ! +: utf8+ ( str -- str ) + begin + char+ + dup c@ + 11000000 and + 10000000 <> + until ; +decimal diff --git a/Task/String-length/Forth/string-length-4.fth b/Task/String-length/Forth/string-length-4.fth new file mode 100644 index 0000000000..93e7f23574 --- /dev/null +++ b/Task/String-length/Forth/string-length-4.fth @@ -0,0 +1,8 @@ +: count-utf8 ( zstr -- n ) + 0 + begin + swap dup c@ + while + utf8+ + swap 1+ + repeat drop ; diff --git a/Task/String-length/GAP/string-length.gap b/Task/String-length/GAP/string-length.gap new file mode 100644 index 0000000000..89020652d8 --- /dev/null +++ b/Task/String-length/GAP/string-length.gap @@ -0,0 +1,3 @@ +Length("abc"); +# or same result with +Size("abc"); diff --git a/Task/String-length/GW-BASIC/string-length.gw-basic b/Task/String-length/GW-BASIC/string-length.gw-basic new file mode 100644 index 0000000000..7c19a50691 --- /dev/null +++ b/Task/String-length/GW-BASIC/string-length.gw-basic @@ -0,0 +1,2 @@ +10 INPUT A$ +20 PRINT LEN(A$) diff --git a/Task/String-length/Go/string-length-1.go b/Task/String-length/Go/string-length-1.go new file mode 100644 index 0000000000..c34d9f8d7d --- /dev/null +++ b/Task/String-length/Go/string-length-1.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + m := "møøse" + u := "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" + j := "J̲o̲s̲é̲" + fmt.Printf("%d %s % x\n", len(m), m, m) + fmt.Printf("%d %s %x\n", len(u), u, u) + fmt.Printf("%d %s % x\n", len(j), j, j) +} diff --git a/Task/String-length/Go/string-length-2.go b/Task/String-length/Go/string-length-2.go new file mode 100644 index 0000000000..c5298d4405 --- /dev/null +++ b/Task/String-length/Go/string-length-2.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "unicode/utf8" +) + +func main() { + m := "møøse" + u := "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" + j := "J̲o̲s̲é̲" + fmt.Printf("%d %s %x\n", utf8.RuneCountInString(m), m, []rune(m)) + fmt.Printf("%d %s %x\n", utf8.RuneCountInString(u), u, []rune(u)) + fmt.Printf("%d %s %x\n", utf8.RuneCountInString(j), j, []rune(j)) +} diff --git a/Task/String-length/Go/string-length-3.go b/Task/String-length/Go/string-length-3.go new file mode 100644 index 0000000000..0eeb037b72 --- /dev/null +++ b/Task/String-length/Go/string-length-3.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "unicode" + "unicode/utf8" +) + +func main() { + m := "møøse" + u := "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" + j := "J̲o̲s̲é̲" + fmt.Printf("%d %s %x\n", grLen(m), m, []rune(m)) + fmt.Printf("%d %s %x\n", grLen(u), u, []rune(u)) + fmt.Printf("%d %s %x\n", grLen(j), j, []rune(j)) +} + +func grLen(s string) int { + if len(s) == 0 { + return 0 + } + gr := 1 + _, s1 := utf8.DecodeRuneInString(s) + for _, r := range s[s1:] { + if !unicode.Is(unicode.Mn, r) { + gr++ + } + } + return gr +} diff --git a/Task/String-length/Groovy/string-length.groovy b/Task/String-length/Groovy/string-length.groovy new file mode 100644 index 0000000000..cadb24805f --- /dev/null +++ b/Task/String-length/Groovy/string-length.groovy @@ -0,0 +1 @@ +println "Hello World!".size() diff --git a/Task/String-length/Haskell/string-length-1.hs b/Task/String-length/Haskell/string-length-1.hs new file mode 100644 index 0000000000..d102be45d5 --- /dev/null +++ b/Task/String-length/Haskell/string-length-1.hs @@ -0,0 +1,11 @@ +import Data.Encoding +import Data.ByteString as B + +strUTF8 :: ByteString +strUTF8 = encode UTF8 "Hello World!" + +strUTF32 :: ByteString +strUTF32 = encode UTF32 "Hello World!" + +strlenUTF8 = B.length strUTF8 +strlenUTF32 = B.length strUTF32 diff --git a/Task/String-length/Haskell/string-length-2.hs b/Task/String-length/Haskell/string-length-2.hs new file mode 100644 index 0000000000..0e881a891a --- /dev/null +++ b/Task/String-length/Haskell/string-length-2.hs @@ -0,0 +1 @@ +strlen = length "Hello, world!" diff --git a/Task/String-length/HicEst/string-length.hicest b/Task/String-length/HicEst/string-length.hicest new file mode 100644 index 0000000000..524c4d50d6 --- /dev/null +++ b/Task/String-length/HicEst/string-length.hicest @@ -0,0 +1 @@ +LEN("1 character == 1 byte") ! 21 diff --git a/Task/String-length/IDL/string-length-1.idl b/Task/String-length/IDL/string-length-1.idl new file mode 100644 index 0000000000..9599d71c28 --- /dev/null +++ b/Task/String-length/IDL/string-length-1.idl @@ -0,0 +1 @@ +length = strlen("Hello, world!") diff --git a/Task/String-length/IDL/string-length-2.idl b/Task/String-length/IDL/string-length-2.idl new file mode 100644 index 0000000000..9599d71c28 --- /dev/null +++ b/Task/String-length/IDL/string-length-2.idl @@ -0,0 +1 @@ +length = strlen("Hello, world!") diff --git a/Task/String-length/Icon/string-length.icon b/Task/String-length/Icon/string-length.icon new file mode 100644 index 0000000000..1823ca1e7a --- /dev/null +++ b/Task/String-length/Icon/string-length.icon @@ -0,0 +1 @@ + length := *s diff --git a/Task/String-length/Io/string-length-1.io b/Task/String-length/Io/string-length-1.io new file mode 100644 index 0000000000..33b3cc9afc --- /dev/null +++ b/Task/String-length/Io/string-length-1.io @@ -0,0 +1 @@ +"møøse" sizeInBytes diff --git a/Task/String-length/Io/string-length-2.io b/Task/String-length/Io/string-length-2.io new file mode 100644 index 0000000000..9eb9ce57dc --- /dev/null +++ b/Task/String-length/Io/string-length-2.io @@ -0,0 +1 @@ +"møøse" size diff --git a/Task/String-length/J/string-length-1.j b/Task/String-length/J/string-length-1.j new file mode 100644 index 0000000000..228e8c8050 --- /dev/null +++ b/Task/String-length/J/string-length-1.j @@ -0,0 +1,2 @@ + # 'møøse' +7 diff --git a/Task/String-length/J/string-length-2.j b/Task/String-length/J/string-length-2.j new file mode 100644 index 0000000000..3fe8d3ee96 --- /dev/null +++ b/Task/String-length/J/string-length-2.j @@ -0,0 +1,2 @@ + #7 u: 'møøse' +5 diff --git a/Task/String-length/Java/string-length-1.java b/Task/String-length/Java/string-length-1.java new file mode 100644 index 0000000000..b364ae4694 --- /dev/null +++ b/Task/String-length/Java/string-length-1.java @@ -0,0 +1,2 @@ +String s = "Hello, world!"; +int byteCount = s.length() * 2; diff --git a/Task/String-length/Java/string-length-2.java b/Task/String-length/Java/string-length-2.java new file mode 100644 index 0000000000..c09e71acd4 --- /dev/null +++ b/Task/String-length/Java/string-length-2.java @@ -0,0 +1,3 @@ +String s = "Hello, world!"; +int byteCountUTF16 = s.getBytes("UTF-16").length; +int byteCountUTF8 = s.getBytes("UTF-8").length; diff --git a/Task/String-length/Java/string-length-3.java b/Task/String-length/Java/string-length-3.java new file mode 100644 index 0000000000..e2a72b8e97 --- /dev/null +++ b/Task/String-length/Java/string-length-3.java @@ -0,0 +1,2 @@ +String s = "Hello, world!"; +int not_really_the_length = s.length(); // XXX: does not (always) count Unicode characters (code points)! diff --git a/Task/String-length/Java/string-length-4.java b/Task/String-length/Java/string-length-4.java new file mode 100644 index 0000000000..32c0f6985f --- /dev/null +++ b/Task/String-length/Java/string-length-4.java @@ -0,0 +1,3 @@ +String str = "\uD834\uDD2A"; //U+1D12A +int not_really__the_length = str.length(); // value is 2, which is not the length in characters +int actual_length = str.codePointCount(0, str.length()); // value is 1, which is the length in characters diff --git a/Task/String-length/Java/string-length-5.java b/Task/String-length/Java/string-length-5.java new file mode 100644 index 0000000000..a67526ecb5 --- /dev/null +++ b/Task/String-length/Java/string-length-5.java @@ -0,0 +1,19 @@ +import java.text.BreakIterator; + +public class Grapheme { + public static void main(String[] args) { + printLength("møøse"); + printLength("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"); + printLength("J̲o̲s̲é̲"); + } + + public static void printLength(String s) { + BreakIterator it = BreakIterator.getCharacterInstance(); + it.setText(s); + int count = 0; + while (it.next() != BreakIterator.DONE) { + count++; + } + System.out.println("Grapheme length: " + count+ " " + s); + } +} diff --git a/Task/String-length/JavaScript/string-length-1.js b/Task/String-length/JavaScript/string-length-1.js new file mode 100644 index 0000000000..905bd1b65c --- /dev/null +++ b/Task/String-length/JavaScript/string-length-1.js @@ -0,0 +1,2 @@ +var s = "Hello, world!"; +var byteCount = s.length * 2; //26 diff --git a/Task/String-length/JavaScript/string-length-2.js b/Task/String-length/JavaScript/string-length-2.js new file mode 100644 index 0000000000..debf9637eb --- /dev/null +++ b/Task/String-length/JavaScript/string-length-2.js @@ -0,0 +1,5 @@ +var str1 = "Hello, world!"; +var len1 = str1.length; //13 + +var str2 = "\uD834\uDD2A"; //U+1D12A represented by a UTF-16 surrogate pair +var len2 = str2.length; //2 diff --git a/Task/String-length/JudoScript/string-length-1.judoscript b/Task/String-length/JudoScript/string-length-1.judoscript new file mode 100644 index 0000000000..d1847bc0e9 --- /dev/null +++ b/Task/String-length/JudoScript/string-length-1.judoscript @@ -0,0 +1,2 @@ +//Store length of hello world in length and print it +. length = "Hello World".length(); diff --git a/Task/String-length/JudoScript/string-length-2.judoscript b/Task/String-length/JudoScript/string-length-2.judoscript new file mode 100644 index 0000000000..41f6164f30 --- /dev/null +++ b/Task/String-length/JudoScript/string-length-2.judoscript @@ -0,0 +1,2 @@ +//Store length of hello world in length and print it +. length = "Hello World".length() diff --git a/Task/String-length/LSE64/string-length-1.lse64 b/Task/String-length/LSE64/string-length-1.lse64 new file mode 100644 index 0000000000..5ee8eaac3a --- /dev/null +++ b/Task/String-length/LSE64/string-length-1.lse64 @@ -0,0 +1 @@ +" Hello world" @ 1 + 8 * , # 96 = (11+1)*(size of a cell) = 12*8 diff --git a/Task/String-length/LSE64/string-length-2.lse64 b/Task/String-length/LSE64/string-length-2.lse64 new file mode 100644 index 0000000000..2a74dd3b01 --- /dev/null +++ b/Task/String-length/LSE64/string-length-2.lse64 @@ -0,0 +1 @@ +" Hello world" @ , # 11 diff --git a/Task/String-length/Logo/string-length.logo b/Task/String-length/Logo/string-length.logo new file mode 100644 index 0000000000..21bd57f730 --- /dev/null +++ b/Task/String-length/Logo/string-length.logo @@ -0,0 +1,3 @@ +print count "|Hello World| ; 11 +print count "møøse ; 5 +print char 248 ; ø - implies ISO-Latin character set diff --git a/Task/String-length/Lua/string-length-1.lua b/Task/String-length/Lua/string-length-1.lua new file mode 100644 index 0000000000..32b1fcd5c9 --- /dev/null +++ b/Task/String-length/Lua/string-length-1.lua @@ -0,0 +1,2 @@ +str = "Hello world" +length = #str diff --git a/Task/String-length/Lua/string-length-2.lua b/Task/String-length/Lua/string-length-2.lua new file mode 100644 index 0000000000..0e650f960d --- /dev/null +++ b/Task/String-length/Lua/string-length-2.lua @@ -0,0 +1,2 @@ +str = "Hello world" +length = string.len(str) diff --git a/Task/String-length/Lua/string-length-3.lua b/Task/String-length/Lua/string-length-3.lua new file mode 100644 index 0000000000..32b1fcd5c9 --- /dev/null +++ b/Task/String-length/Lua/string-length-3.lua @@ -0,0 +1,2 @@ +str = "Hello world" +length = #str diff --git a/Task/String-length/Lua/string-length-4.lua b/Task/String-length/Lua/string-length-4.lua new file mode 100644 index 0000000000..0e650f960d --- /dev/null +++ b/Task/String-length/Lua/string-length-4.lua @@ -0,0 +1,2 @@ +str = "Hello world" +length = string.len(str) diff --git a/Task/String-length/MATLAB/string-length-1.m b/Task/String-length/MATLAB/string-length-1.m new file mode 100644 index 0000000000..e97b678373 --- /dev/null +++ b/Task/String-length/MATLAB/string-length-1.m @@ -0,0 +1,5 @@ +>> length('møøse') + +ans = + + 5 diff --git a/Task/String-length/MATLAB/string-length-2.m b/Task/String-length/MATLAB/string-length-2.m new file mode 100644 index 0000000000..afe677f3cf --- /dev/null +++ b/Task/String-length/MATLAB/string-length-2.m @@ -0,0 +1,5 @@ +>> numel(dec2hex('møøse')) + +ans = + + 10 diff --git a/Task/String-length/MAXScript/string-length.maxscript b/Task/String-length/MAXScript/string-length.maxscript new file mode 100644 index 0000000000..3945803cbd --- /dev/null +++ b/Task/String-length/MAXScript/string-length.maxscript @@ -0,0 +1 @@ +"Hello world".count diff --git a/Task/String-length/Mathematica/string-length-1.math b/Task/String-length/Mathematica/string-length-1.math new file mode 100644 index 0000000000..fea9fb94df --- /dev/null +++ b/Task/String-length/Mathematica/string-length-1.math @@ -0,0 +1 @@ +StringLength["Hello world"] diff --git a/Task/String-length/Mathematica/string-length-2.math b/Task/String-length/Mathematica/string-length-2.math new file mode 100644 index 0000000000..0d08a03d2a --- /dev/null +++ b/Task/String-length/Mathematica/string-length-2.math @@ -0,0 +1 @@ +StringByteCount["Hello world"] diff --git a/Task/String-length/Maxima/string-length.maxima b/Task/String-length/Maxima/string-length.maxima new file mode 100644 index 0000000000..7901d09507 --- /dev/null +++ b/Task/String-length/Maxima/string-length.maxima @@ -0,0 +1,3 @@ +s: "the quick brown fox jumps over the lazy dog"; +slength(s); +/* 43 */ diff --git a/Task/String-length/Metafont/string-length.metafont b/Task/String-length/Metafont/string-length.metafont new file mode 100644 index 0000000000..cad8ee689f --- /dev/null +++ b/Task/String-length/Metafont/string-length.metafont @@ -0,0 +1,6 @@ +string s; +s := "Hello Moose"; +show length(s); % 11 (ok) +s := "Hello Møøse"; +show length(s); % 13 (number of bytes when the string is UTF-8 encoded, + % since ø takes two bytes) diff --git a/Task/String-length/Modula-3/string-length-1.mod3 b/Task/String-length/Modula-3/string-length-1.mod3 new file mode 100644 index 0000000000..9909f78d1b --- /dev/null +++ b/Task/String-length/Modula-3/string-length-1.mod3 @@ -0,0 +1,9 @@ +MODULE ByteLength EXPORTS Main; + +IMPORT IO, Fmt, Text; + +VAR s: TEXT := "Foo bar baz"; + +BEGIN + IO.Put("Byte length of s: " & Fmt.Int((Text.Length(s) * BYTESIZE(s))) & "\n"); +END ByteLength. diff --git a/Task/String-length/Modula-3/string-length-2.mod3 b/Task/String-length/Modula-3/string-length-2.mod3 new file mode 100644 index 0000000000..a96f5720df --- /dev/null +++ b/Task/String-length/Modula-3/string-length-2.mod3 @@ -0,0 +1,9 @@ +MODULE StringLength EXPORTS Main; + +IMPORT IO, Fmt, Text; + +VAR s: TEXT := "Foo bar baz"; + +BEGIN + IO.Put("String length of s: " & Fmt.Int(Text.Length(s)) & "\n"); +END StringLength. diff --git a/Task/String-length/Nemerle/string-length-1.nemerle b/Task/String-length/Nemerle/string-length-1.nemerle new file mode 100644 index 0000000000..ed72dfaf54 --- /dev/null +++ b/Task/String-length/Nemerle/string-length-1.nemerle @@ -0,0 +1,2 @@ +def message = "How long am I anyways?"; +def charlength = message.Length; diff --git a/Task/String-length/Nemerle/string-length-2.nemerle b/Task/String-length/Nemerle/string-length-2.nemerle new file mode 100644 index 0000000000..709e48769a --- /dev/null +++ b/Task/String-length/Nemerle/string-length-2.nemerle @@ -0,0 +1,4 @@ +using System.Text; + +def message = "How long am I anyways?"; +def bytelength = Encoding.Unicode.GetByteCount(message); diff --git a/Task/String-length/NewLISP/string-length.newlisp b/Task/String-length/NewLISP/string-length.newlisp new file mode 100644 index 0000000000..ae24aced7f --- /dev/null +++ b/Task/String-length/NewLISP/string-length.newlisp @@ -0,0 +1,2 @@ +(set 'Str "møøse") +(println Str " is " (length Str) " characters long") diff --git a/Task/String-length/OCaml/string-length-1.ocaml b/Task/String-length/OCaml/string-length-1.ocaml new file mode 100644 index 0000000000..886b18a0ed --- /dev/null +++ b/Task/String-length/OCaml/string-length-1.ocaml @@ -0,0 +1 @@ +String.length "Hello world" ;; diff --git a/Task/String-length/OCaml/string-length-2.ocaml b/Task/String-length/OCaml/string-length-2.ocaml new file mode 100644 index 0000000000..4fea8953d7 --- /dev/null +++ b/Task/String-length/OCaml/string-length-2.ocaml @@ -0,0 +1,2 @@ +String.length "møøse" +UTF8.length "møøse" diff --git a/Task/String-length/Oberon-2/string-length-1.oberon-2 b/Task/String-length/Oberon-2/string-length-1.oberon-2 new file mode 100644 index 0000000000..0ba3428af6 --- /dev/null +++ b/Task/String-length/Oberon-2/string-length-1.oberon-2 @@ -0,0 +1,14 @@ +MODULE Size; + + IMPORT Out; + + VAR s: LONGINT; + string: ARRAY 5 OF CHAR; + +BEGIN + string := "Foo"; + s := LEN(string); + Out.String("Size: "); + Out.LongInt(s,0); + Out.Ln; +END Size. diff --git a/Task/String-length/Oberon-2/string-length-2.oberon-2 b/Task/String-length/Oberon-2/string-length-2.oberon-2 new file mode 100644 index 0000000000..802fd290de --- /dev/null +++ b/Task/String-length/Oberon-2/string-length-2.oberon-2 @@ -0,0 +1,14 @@ +MODULE Length; + + IMPORT Out, Strings; + + VAR l: INTEGER; + string: ARRAY 5 OF CHAR; + +BEGIN + string := "Foo"; + l := Strings.Length(string); + Out.String("Length: "); + Out.Int(l,0); + Out.Ln; +END Length. diff --git a/Task/String-length/Objeck/string-length-1.objeck b/Task/String-length/Objeck/string-length-1.objeck new file mode 100644 index 0000000000..074e116acc --- /dev/null +++ b/Task/String-length/Objeck/string-length-1.objeck @@ -0,0 +1 @@ +"Foo"->Size()->PrintLine(); diff --git a/Task/String-length/Objeck/string-length-2.objeck b/Task/String-length/Objeck/string-length-2.objeck new file mode 100644 index 0000000000..074e116acc --- /dev/null +++ b/Task/String-length/Objeck/string-length-2.objeck @@ -0,0 +1 @@ +"Foo"->Size()->PrintLine(); diff --git a/Task/String-length/Objective-C/string-length-1.m b/Task/String-length/Objective-C/string-length-1.m new file mode 100644 index 0000000000..5605f28485 --- /dev/null +++ b/Task/String-length/Objective-C/string-length-1.m @@ -0,0 +1,3 @@ +// Return the length in characters +// XXX: does not (always) count Unicode characters (code points)! +unsigned int numberOfCharacters = [@"møøse" length]; // 5 diff --git a/Task/String-length/Objective-C/string-length-2.m b/Task/String-length/Objective-C/string-length-2.m new file mode 100644 index 0000000000..85583cfa39 --- /dev/null +++ b/Task/String-length/Objective-C/string-length-2.m @@ -0,0 +1 @@ +int realCharacterCount = [s lengthOfBytesUsingEncoding: NSUTF32StringEncoding] / 4; diff --git a/Task/String-length/Objective-C/string-length-3.m b/Task/String-length/Objective-C/string-length-3.m new file mode 100644 index 0000000000..96c0023bb3 --- /dev/null +++ b/Task/String-length/Objective-C/string-length-3.m @@ -0,0 +1 @@ +int byteCount = [@"møøse" length] * 2; // 10 diff --git a/Task/String-length/Objective-C/string-length-4.m b/Task/String-length/Objective-C/string-length-4.m new file mode 100644 index 0000000000..293a7bf4ed --- /dev/null +++ b/Task/String-length/Objective-C/string-length-4.m @@ -0,0 +1,4 @@ +// Return the number of bytes depending on the encoding, +// here explicitly UTF-8 +unsigned numberOfBytes = + [@"møøse" lengthOfBytesUsingEncoding: NSUTF8StringEncoding]; // 7 diff --git a/Task/String-length/Octave/string-length.octave b/Task/String-length/Octave/string-length.octave new file mode 100644 index 0000000000..2c1148f5b2 --- /dev/null +++ b/Task/String-length/Octave/string-length.octave @@ -0,0 +1,2 @@ +s = "string"; +stringlen = length(s) diff --git a/Task/String-length/OpenEdge-Progress/string-length-1.openedge b/Task/String-length/OpenEdge-Progress/string-length-1.openedge new file mode 100644 index 0000000000..eac39340b3 --- /dev/null +++ b/Task/String-length/OpenEdge-Progress/string-length-1.openedge @@ -0,0 +1,6 @@ +DEF VAR lcc AS LONGCHAR. + +FIX-CODEPAGE( lcc ) = "UTF-8". +lcc = "møøse". + +MESSAGE LENGTH( lcc ) VIEW-AS ALERT-BOX. diff --git a/Task/String-length/OpenEdge-Progress/string-length-2.openedge b/Task/String-length/OpenEdge-Progress/string-length-2.openedge new file mode 100644 index 0000000000..6608b4c39f --- /dev/null +++ b/Task/String-length/OpenEdge-Progress/string-length-2.openedge @@ -0,0 +1,6 @@ +DEF VAR lcc AS LONGCHAR. + +FIX-CODEPAGE( lcc ) = "UTF-8". +lcc = "møøse". + +MESSAGE LENGTH( lcc, "RAW" ) VIEW-AS ALERT-BOX. diff --git a/Task/String-length/Oz/string-length.oz b/Task/String-length/Oz/string-length.oz new file mode 100644 index 0000000000..5b2fb7cc44 --- /dev/null +++ b/Task/String-length/Oz/string-length.oz @@ -0,0 +1 @@ +{Show {Length "Hello World"}} diff --git a/Task/String-length/PARI-GP/string-length-1.pari b/Task/String-length/PARI-GP/string-length-1.pari new file mode 100644 index 0000000000..e73f5e8323 --- /dev/null +++ b/Task/String-length/PARI-GP/string-length-1.pari @@ -0,0 +1 @@ +len(s)=#s; \\ Alternately, len(s)=length(s); or even len=length; diff --git a/Task/String-length/PARI-GP/string-length-2.pari b/Task/String-length/PARI-GP/string-length-2.pari new file mode 100644 index 0000000000..1aecdd338b --- /dev/null +++ b/Task/String-length/PARI-GP/string-length-2.pari @@ -0,0 +1 @@ +len(s)=sizebyte(s); diff --git a/Task/String-length/PHP/string-length-1.php b/Task/String-length/PHP/string-length-1.php new file mode 100644 index 0000000000..fd5a516940 --- /dev/null +++ b/Task/String-length/PHP/string-length-1.php @@ -0,0 +1 @@ +$length = strlen('Hello, world!'); diff --git a/Task/String-length/PHP/string-length-2.php b/Task/String-length/PHP/string-length-2.php new file mode 100644 index 0000000000..e80055a735 --- /dev/null +++ b/Task/String-length/PHP/string-length-2.php @@ -0,0 +1 @@ +$length = mb_strlen('Hello, world!', 'UTF-8'); // or whatever encoding diff --git a/Task/String-length/PHP/string-length-3.php b/Task/String-length/PHP/string-length-3.php new file mode 100644 index 0000000000..ab80c16d2d --- /dev/null +++ b/Task/String-length/PHP/string-length-3.php @@ -0,0 +1 @@ +$length = grapheme_strlen('Hello, world!'); // UTF-8 encoding required diff --git a/Task/String-length/PL-I/string-length.pli b/Task/String-length/PL-I/string-length.pli new file mode 100644 index 0000000000..7f440f0205 --- /dev/null +++ b/Task/String-length/PL-I/string-length.pli @@ -0,0 +1,7 @@ +declare WS widechar (13) initial ('Hello world.'); +put ('Character length=', length (WS)); +put skip list ('Byte length=', size(WS)); + +declare SM graphic (13) initial ('Hello world'); +put ('Character length=', length(SM)); +put skip list ('Byte length=', size(trim(SM)); diff --git a/Task/String-length/PL-SQL/string-length-1.sql b/Task/String-length/PL-SQL/string-length-1.sql new file mode 100644 index 0000000000..bff086461e --- /dev/null +++ b/Task/String-length/PL-SQL/string-length-1.sql @@ -0,0 +1,6 @@ +DECLARE + string VARCHAR2(50) := 'Hello, world!'; + stringlength NUMBER; +BEGIN + stringlength := LENGTHB(string); +END; diff --git a/Task/String-length/PL-SQL/string-length-2.sql b/Task/String-length/PL-SQL/string-length-2.sql new file mode 100644 index 0000000000..eb53474f4c --- /dev/null +++ b/Task/String-length/PL-SQL/string-length-2.sql @@ -0,0 +1,12 @@ +DECLARE + string VARCHAR2(50) := 'Hello, world!'; + stringlength NUMBER; + unicodelength NUMBER; + ucs2length NUMBER; + ucs4length NUMBER; +BEGIN + stringlength := LENGTH(string); + unicodelength := LENGTHC(string); + ucs2length := LENGTH2(string); + ucs4length := LENGTH4(string); +END; diff --git a/Task/String-length/Pascal/string-length.pascal b/Task/String-length/Pascal/string-length.pascal new file mode 100644 index 0000000000..e180e5cae1 --- /dev/null +++ b/Task/String-length/Pascal/string-length.pascal @@ -0,0 +1,5 @@ +const + s = 'abcdef'; +begin + writeln (length(s)) +end. diff --git a/Task/String-length/Perl-6/string-length-1.pl6 b/Task/String-length/Perl-6/string-length-1.pl6 new file mode 100644 index 0000000000..eece7dc6f6 --- /dev/null +++ b/Task/String-length/Perl-6/string-length-1.pl6 @@ -0,0 +1 @@ +say 'møøse'.encode('UTF-8').bytes; diff --git a/Task/String-length/Perl-6/string-length-2.pl6 b/Task/String-length/Perl-6/string-length-2.pl6 new file mode 100644 index 0000000000..4abff328c8 --- /dev/null +++ b/Task/String-length/Perl-6/string-length-2.pl6 @@ -0,0 +1 @@ +say 'møøse'.codes; diff --git a/Task/String-length/Perl-6/string-length-3.pl6 b/Task/String-length/Perl-6/string-length-3.pl6 new file mode 100644 index 0000000000..a4002d836c --- /dev/null +++ b/Task/String-length/Perl-6/string-length-3.pl6 @@ -0,0 +1 @@ +say 'møøse'.graphs; diff --git a/Task/String-length/Perl/string-length-1.pl b/Task/String-length/Perl/string-length-1.pl new file mode 100644 index 0000000000..56f460164e --- /dev/null +++ b/Task/String-length/Perl/string-length-1.pl @@ -0,0 +1,8 @@ +use utf8; # so we can use literal characters like ☺ in source +use Encode qw(encode); + +print length encode 'UTF-8', "Hello, world! ☺"; +# 17. The last character takes 3 bytes, the others 1 byte each. + +print length encode 'UTF-16', "Hello, world! ☺"; +# 32. 2 bytes for the BOM, then 15 byte pairs for each character. diff --git a/Task/String-length/Perl/string-length-2.pl b/Task/String-length/Perl/string-length-2.pl new file mode 100644 index 0000000000..063342d78f --- /dev/null +++ b/Task/String-length/Perl/string-length-2.pl @@ -0,0 +1 @@ +my $length = length "Hello, world!"; diff --git a/Task/String-length/Perl/string-length-3.pl b/Task/String-length/Perl/string-length-3.pl new file mode 100644 index 0000000000..bf10e9f4ae --- /dev/null +++ b/Task/String-length/Perl/string-length-3.pl @@ -0,0 +1,5 @@ +use v5.12; +my $string = "\x{1112}\x{1161}\x{11ab}\x{1100}\x{1173}\x{11af}"; # 한글 +my $len; +$len++ while ($string =~ /\X/g); +printf "Grapheme length: %d\n", $len; diff --git a/Task/String-length/PicoLisp/string-length.l b/Task/String-length/PicoLisp/string-length.l new file mode 100644 index 0000000000..3f41815607 --- /dev/null +++ b/Task/String-length/PicoLisp/string-length.l @@ -0,0 +1,3 @@ +(let Str "møøse" + (prinl "Character Length of \"" Str "\" is " (length Str)) + (prinl "Byte Length of \"" Str "\" is " (size Str)) ) diff --git a/Task/String-length/Pop11/string-length.pop11 b/Task/String-length/Pop11/string-length.pop11 new file mode 100644 index 0000000000..719f19ac76 --- /dev/null +++ b/Task/String-length/Pop11/string-length.pop11 @@ -0,0 +1,2 @@ +lvars str = 'Hello, world!'; +lvars len = length(str); diff --git a/Task/String-length/PostScript/string-length.ps b/Task/String-length/PostScript/string-length.ps new file mode 100644 index 0000000000..d7c67a2dad --- /dev/null +++ b/Task/String-length/PostScript/string-length.ps @@ -0,0 +1,2 @@ +(Hello World) length = +11 diff --git a/Task/String-length/PowerShell/string-length-1.psh b/Task/String-length/PowerShell/string-length-1.psh new file mode 100644 index 0000000000..22d79228aa --- /dev/null +++ b/Task/String-length/PowerShell/string-length-1.psh @@ -0,0 +1,2 @@ +$s = "Hëlló Wørłð" +$s.Length diff --git a/Task/String-length/PowerShell/string-length-2.psh b/Task/String-length/PowerShell/string-length-2.psh new file mode 100644 index 0000000000..e80243730b --- /dev/null +++ b/Task/String-length/PowerShell/string-length-2.psh @@ -0,0 +1,2 @@ +$s = "Hëlló Wørłð" +[System.Text.Encoding]::Unicode.GetByteCount($s) diff --git a/Task/String-length/PowerShell/string-length-3.psh b/Task/String-length/PowerShell/string-length-3.psh new file mode 100644 index 0000000000..3525924c98 --- /dev/null +++ b/Task/String-length/PowerShell/string-length-3.psh @@ -0,0 +1 @@ +[System.Text.Encoding]::UTF8.GetByteCount($s) diff --git a/Task/String-length/PureBasic/string-length-1.purebasic b/Task/String-length/PureBasic/string-length-1.purebasic new file mode 100644 index 0000000000..69f5268327 --- /dev/null +++ b/Task/String-length/PureBasic/string-length-1.purebasic @@ -0,0 +1 @@ + a = Len("Hello World") ;a will be 11 diff --git a/Task/String-length/PureBasic/string-length-2.purebasic b/Task/String-length/PureBasic/string-length-2.purebasic new file mode 100644 index 0000000000..8d174e548d --- /dev/null +++ b/Task/String-length/PureBasic/string-length-2.purebasic @@ -0,0 +1,3 @@ +a = StringByteLength("ä", #PB_UTF8) ;a will be 2 +b = StringByteLength("ä", #PB_Ascii) ;b will be 1 +c = StringByteLength("ä", #PB_Unicode) ;c will be 2 diff --git a/Task/String-length/Python/string-length-1.py b/Task/String-length/Python/string-length-1.py new file mode 100644 index 0000000000..374ea95e04 --- /dev/null +++ b/Task/String-length/Python/string-length-1.py @@ -0,0 +1,6 @@ +#!/bin/env python +# -*- coding: UTF-8 -*- +s = u"møøse" +assert len(s) == 5 +assert len(s.encode('UTF-8')) == 7 +assert len(s.encode('UTF-16')) == 12 # The extra character is probably a leading Unicode byte-order mark (BOM). diff --git a/Task/String-length/Python/string-length-2.py b/Task/String-length/Python/string-length-2.py new file mode 100644 index 0000000000..e33b1cec01 --- /dev/null +++ b/Task/String-length/Python/string-length-2.py @@ -0,0 +1,6 @@ +#!/bin/env python +# -*- coding: UTF-8 -*- +s = "møøse" +assert len(s) == 5 +assert len(s.encode('UTF-8')) == 7 +assert len(s.encode('UTF-16')) == 12 # The extra character is probably a leading Unicode byte-order mark (BOM). diff --git a/Task/String-length/R/string-length-1.r b/Task/String-length/R/string-length-1.r new file mode 100644 index 0000000000..035ab1370c --- /dev/null +++ b/Task/String-length/R/string-length-1.r @@ -0,0 +1,2 @@ +a <- "m\u00f8\u00f8se" +print(nchar(a, type="bytes")) # print 7 diff --git a/Task/String-length/R/string-length-2.r b/Task/String-length/R/string-length-2.r new file mode 100644 index 0000000000..e32bf11800 --- /dev/null +++ b/Task/String-length/R/string-length-2.r @@ -0,0 +1 @@ +print(nchar(a, type="chars")) # print 5 diff --git a/Task/String-length/REBOL/string-length.rebol b/Task/String-length/REBOL/string-length.rebol new file mode 100644 index 0000000000..ca0a77c2a5 --- /dev/null +++ b/Task/String-length/REBOL/string-length.rebol @@ -0,0 +1,2 @@ +text: "møøse" +print rejoin ["Byte length for '" text "': " length? text] diff --git a/Task/String-length/REXX/string-length.rexx b/Task/String-length/REXX/string-length.rexx new file mode 100644 index 0000000000..90dd1d9b13 --- /dev/null +++ b/Task/String-length/REXX/string-length.rexx @@ -0,0 +1,10 @@ +/*REXX program to show lengths (in bytes/characters) for various strings*/ + /* 1 */ /*a handy over/under scale.*/ + /* 123456789012345 */ +hello = 'Hello, world!' ; say 'length of HELLO is ' length(hello) +happy = 'Hello, world! ☺' ; say 'length of HAPPY is ' length(happy) +jose = 'José' ; say 'length of JOSE is ' length(jose) +nill = '' ; say 'length of NILL is ' length(nill) +null = ; say 'length of NULL is ' length(null) +sum = 5+1 ; say 'length of SUM is ' length(sum) + /*stick a fork in it, we're done.*/ diff --git a/Task/String-length/Retro/string-length-1.retro b/Task/String-length/Retro/string-length-1.retro new file mode 100644 index 0000000000..9d44323344 --- /dev/null +++ b/Task/String-length/Retro/string-length-1.retro @@ -0,0 +1 @@ +"møøse" getLength putn diff --git a/Task/String-length/Retro/string-length-2.retro b/Task/String-length/Retro/string-length-2.retro new file mode 100644 index 0000000000..42abc84837 --- /dev/null +++ b/Task/String-length/Retro/string-length-2.retro @@ -0,0 +1,15 @@ +chain: UTF8' +{{ + : utf+ ( $-$ ) + [ 1+ dup @ %11000000 and %10000000 = ] while ; + + : count ( $-$ ) + 0 !here + repeat dup @ 0; drop utf+ here ++ again ; +---reveal--- + : getLength ( $-n ) + count drop @here ; +}} +;chain + +"møøse" ^UTF8'getLength putn diff --git a/Task/String-length/Ruby/string-length.rb b/Task/String-length/Ruby/string-length.rb new file mode 100644 index 0000000000..a1e56ed2df --- /dev/null +++ b/Task/String-length/Ruby/string-length.rb @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- + +puts "あいうえお".bytesize +# => 15 diff --git a/Task/String-length/Run-BASIC/string-length-1.run b/Task/String-length/Run-BASIC/string-length-1.run new file mode 100644 index 0000000000..16a5f26bfc --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-1.run @@ -0,0 +1,2 @@ +input a$ +print len(a$) diff --git a/Task/String-length/Run-BASIC/string-length-2.run b/Task/String-length/Run-BASIC/string-length-2.run new file mode 100644 index 0000000000..47fcaa7776 --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-2.run @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- + +puts "あいうえお".length +# => 5 + +puts "あいうえお".size # alias for length +# => 5 diff --git a/Task/String-length/Run-BASIC/string-length-3.run b/Task/String-length/Run-BASIC/string-length-3.run new file mode 100644 index 0000000000..2a53b6cdfc --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-3.run @@ -0,0 +1,4 @@ +# -*- coding: iso-8859-1 -*- +s = "møøse" +puts "Byte length: %d" % s.bytesize +puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-4.run b/Task/String-length/Run-BASIC/string-length-4.run new file mode 100644 index 0000000000..af1ce7cb7f --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-4.run @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +s = "møøse" +puts "Byte length: %d" % s.bytesize +puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-5.run b/Task/String-length/Run-BASIC/string-length-5.run new file mode 100644 index 0000000000..108634387d --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-5.run @@ -0,0 +1,4 @@ +# -*- coding: gb18030 -*- +s = "møøse" +puts "Byte length: %d" % s.bytesize +puts "Character length: %d" % s.length diff --git a/Task/String-length/Run-BASIC/string-length-6.run b/Task/String-length/Run-BASIC/string-length-6.run new file mode 100644 index 0000000000..ac153f7564 --- /dev/null +++ b/Task/String-length/Run-BASIC/string-length-6.run @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- + +class String + # Define String#bytesize for Ruby 1.8.6. + unless method_defined?(:bytesize) + alias bytesize length + end +end + +s = "文字化け" +puts "Byte length: %d" % s.bytesize +puts "Character length: %d" % s.gsub(/./u, ' ').size diff --git a/Task/String-length/SAS/string-length.sas b/Task/String-length/SAS/string-length.sas new file mode 100644 index 0000000000..dba198cb41 --- /dev/null +++ b/Task/String-length/SAS/string-length.sas @@ -0,0 +1,5 @@ +data _null_; + a="Hello, World!"; + b=length(c); + put _all_; +run; diff --git a/Task/String-length/SNOBOL4/string-length-1.sno b/Task/String-length/SNOBOL4/string-length-1.sno new file mode 100644 index 0000000000..4e81cdfdfb --- /dev/null +++ b/Task/String-length/SNOBOL4/string-length-1.sno @@ -0,0 +1,2 @@ + output = "Byte length: " size(trim(input)) +end diff --git a/Task/String-length/SNOBOL4/string-length-2.sno b/Task/String-length/SNOBOL4/string-length-2.sno new file mode 100644 index 0000000000..2bf719e417 --- /dev/null +++ b/Task/String-length/SNOBOL4/string-length-2.sno @@ -0,0 +1,3 @@ +-include "utf.sno" + output = "Char length: " utfsize(trim(input)) +end diff --git a/Task/String-length/Scheme/string-length-1.ss b/Task/String-length/Scheme/string-length-1.ss new file mode 100644 index 0000000000..ddd2497d6a --- /dev/null +++ b/Task/String-length/Scheme/string-length-1.ss @@ -0,0 +1 @@ +(string-size "Hello world") diff --git a/Task/String-length/Scheme/string-length-2.ss b/Task/String-length/Scheme/string-length-2.ss new file mode 100644 index 0000000000..fc25fa2c3d --- /dev/null +++ b/Task/String-length/Scheme/string-length-2.ss @@ -0,0 +1 @@ +(bytes-length #"Hello world") diff --git a/Task/String-length/Scheme/string-length-3.ss b/Task/String-length/Scheme/string-length-3.ss new file mode 100644 index 0000000000..574970fc5e --- /dev/null +++ b/Task/String-length/Scheme/string-length-3.ss @@ -0,0 +1 @@ + (string-length "Hello world") diff --git a/Task/String-length/Seed7/string-length.seed7 b/Task/String-length/Seed7/string-length.seed7 new file mode 100644 index 0000000000..7001ac4edf --- /dev/null +++ b/Task/String-length/Seed7/string-length.seed7 @@ -0,0 +1 @@ +length("Hello, world!") diff --git a/Task/String-length/Slate/string-length.slate b/Task/String-length/Slate/string-length.slate new file mode 100644 index 0000000000..ad9235408d --- /dev/null +++ b/Task/String-length/Slate/string-length.slate @@ -0,0 +1 @@ +'Hello, world!' length. diff --git a/Task/String-length/Smalltalk/string-length-1.st b/Task/String-length/Smalltalk/string-length-1.st new file mode 100644 index 0000000000..1fb87b81d3 --- /dev/null +++ b/Task/String-length/Smalltalk/string-length-1.st @@ -0,0 +1,2 @@ +string := 'Hello, world!'. +string size. diff --git a/Task/String-length/Smalltalk/string-length-2.st b/Task/String-length/Smalltalk/string-length-2.st new file mode 100644 index 0000000000..cf1f2ebbc8 --- /dev/null +++ b/Task/String-length/Smalltalk/string-length-2.st @@ -0,0 +1,2 @@ +string := 'Hello, world!'. +string numberOfCharacters. diff --git a/Task/String-length/Smalltalk/string-length-3.st b/Task/String-length/Smalltalk/string-length-3.st new file mode 100644 index 0000000000..f861929e6e --- /dev/null +++ b/Task/String-length/Smalltalk/string-length-3.st @@ -0,0 +1 @@ +PackageLoader fileInPackage: 'Iconv' diff --git a/Task/String-length/Standard-ML/string-length-1.ml b/Task/String-length/Standard-ML/string-length-1.ml new file mode 100644 index 0000000000..b9f028a6f4 --- /dev/null +++ b/Task/String-length/Standard-ML/string-length-1.ml @@ -0,0 +1 @@ +val strlen = size "Hello, world!"; diff --git a/Task/String-length/Standard-ML/string-length-2.ml b/Task/String-length/Standard-ML/string-length-2.ml new file mode 100644 index 0000000000..12eb2521c4 --- /dev/null +++ b/Task/String-length/Standard-ML/string-length-2.ml @@ -0,0 +1 @@ +val strlen = UTF8.size "Hello, world!"; diff --git a/Task/String-length/TI-89-BASIC/string-length.ti-89 b/Task/String-length/TI-89-BASIC/string-length.ti-89 new file mode 100644 index 0000000000..e0207736fe --- /dev/null +++ b/Task/String-length/TI-89-BASIC/string-length.ti-89 @@ -0,0 +1 @@ +■ dim("møøse") 5 diff --git a/Task/String-length/TUSCRIPT/string-length.tuscript b/Task/String-length/TUSCRIPT/string-length.tuscript new file mode 100644 index 0000000000..3c0afb7121 --- /dev/null +++ b/Task/String-length/TUSCRIPT/string-length.tuscript @@ -0,0 +1,4 @@ +$$ MODE TUSCRIPT +string="hello, world" +l=LENGTH (string) +PRINT "character length of string '",string,"': ",l diff --git a/Task/String-length/Tcl/string-length-1.tcl b/Task/String-length/Tcl/string-length-1.tcl new file mode 100644 index 0000000000..8f4ddfe842 --- /dev/null +++ b/Task/String-length/Tcl/string-length-1.tcl @@ -0,0 +1 @@ +string length [encoding convertto utf-8 $theString] diff --git a/Task/String-length/Tcl/string-length-2.tcl b/Task/String-length/Tcl/string-length-2.tcl new file mode 100644 index 0000000000..b63d256992 --- /dev/null +++ b/Task/String-length/Tcl/string-length-2.tcl @@ -0,0 +1,7 @@ +set s1 "hello, world" +set s2 "\u304A\u306F\u3088\u3046" +set enc utf-8 +puts [format "length of \"%s\" in bytes is %d" \ + $s1 [string length [encoding convertto $enc $s1]]] +puts [format "length of \"%s\" in bytes is %d" \ + $s2 [string length [encoding convertto $enc $s2]]] diff --git a/Task/String-length/Tcl/string-length-3.tcl b/Task/String-length/Tcl/string-length-3.tcl new file mode 100644 index 0000000000..eef6df5898 --- /dev/null +++ b/Task/String-length/Tcl/string-length-3.tcl @@ -0,0 +1 @@ +string length "Hello, world!" diff --git a/Task/String-length/Tcl/string-length-4.tcl b/Task/String-length/Tcl/string-length-4.tcl new file mode 100644 index 0000000000..0cfde2a652 --- /dev/null +++ b/Task/String-length/Tcl/string-length-4.tcl @@ -0,0 +1,5 @@ +fconfigure stdout -encoding utf-8; #So that Unicode string will print correctly +set s1 "hello, world" +set s2 "\u304A\u306F\u3088\u3046" +puts [format "length of \"%s\" in characters is %d" $s1 [string length $s1]] +puts [format "length of \"%s\" in characters is %d" $s2 [string length $s2]] diff --git a/Task/String-length/Toka/string-length.toka b/Task/String-length/Toka/string-length.toka new file mode 100644 index 0000000000..77a3dbd050 --- /dev/null +++ b/Task/String-length/Toka/string-length.toka @@ -0,0 +1 @@ +" hello, world!" string.getLength diff --git a/Task/String-length/Trith/string-length-1.trith b/Task/String-length/Trith/string-length-1.trith new file mode 100644 index 0000000000..99249f67e6 --- /dev/null +++ b/Task/String-length/Trith/string-length-1.trith @@ -0,0 +1 @@ +"møøse" length diff --git a/Task/String-length/Trith/string-length-2.trith b/Task/String-length/Trith/string-length-2.trith new file mode 100644 index 0000000000..9eb9ce57dc --- /dev/null +++ b/Task/String-length/Trith/string-length-2.trith @@ -0,0 +1 @@ +"møøse" size diff --git a/Task/String-length/UNIX-Shell/string-length-1.sh b/Task/String-length/UNIX-Shell/string-length-1.sh new file mode 100644 index 0000000000..13f49789e5 --- /dev/null +++ b/Task/String-length/UNIX-Shell/string-length-1.sh @@ -0,0 +1,3 @@ +string='Hello, world!' +length=`expr "x$string" : '.*' - 1` +echo $length # if you want it printed to the terminal diff --git a/Task/String-length/UNIX-Shell/string-length-2.sh b/Task/String-length/UNIX-Shell/string-length-2.sh new file mode 100644 index 0000000000..6648f3fd9a --- /dev/null +++ b/Task/String-length/UNIX-Shell/string-length-2.sh @@ -0,0 +1,3 @@ +string='Hello, world!' +length="${#string}" +echo $length # if you want it printed to the terminal diff --git a/Task/String-length/VBScript/string-length-1.vbscript b/Task/String-length/VBScript/string-length-1.vbscript new file mode 100644 index 0000000000..9785a4df61 --- /dev/null +++ b/Task/String-length/VBScript/string-length-1.vbscript @@ -0,0 +1 @@ +LenB(string|varname) diff --git a/Task/String-length/VBScript/string-length-2.vbscript b/Task/String-length/VBScript/string-length-2.vbscript new file mode 100644 index 0000000000..6a30083885 --- /dev/null +++ b/Task/String-length/VBScript/string-length-2.vbscript @@ -0,0 +1 @@ +Len(string|varname) diff --git a/Task/String-length/Vala/string-length.vala b/Task/String-length/Vala/string-length.vala new file mode 100644 index 0000000000..e9fa9776bb --- /dev/null +++ b/Task/String-length/Vala/string-length.vala @@ -0,0 +1,2 @@ +string s = "Hello, world!"; +int characterLength = s.length; diff --git a/Task/String-length/XPL0/string-length.xpl0 b/Task/String-length/XPL0/string-length.xpl0 new file mode 100644 index 0000000000..ca71b2685e --- /dev/null +++ b/Task/String-length/XPL0/string-length.xpl0 @@ -0,0 +1,2 @@ +include c:\cxpl\stdlib; +IntOut(0, StrLen("Character length = Byte length = String length = ")) diff --git a/Task/String-length/XSLT/string-length-1.xslt b/Task/String-length/XSLT/string-length-1.xslt new file mode 100644 index 0000000000..12bbf745ce --- /dev/null +++ b/Task/String-length/XSLT/string-length-1.xslt @@ -0,0 +1 @@ + diff --git a/Task/String-length/XSLT/string-length-2.xslt b/Task/String-length/XSLT/string-length-2.xslt new file mode 100644 index 0000000000..64818fa2a1 --- /dev/null +++ b/Task/String-length/XSLT/string-length-2.xslt @@ -0,0 +1 @@ + diff --git a/Task/String-length/Yorick/string-length.yorick b/Task/String-length/Yorick/string-length.yorick new file mode 100644 index 0000000000..50627b8530 --- /dev/null +++ b/Task/String-length/Yorick/string-length.yorick @@ -0,0 +1 @@ +strlen("Hello, world!") diff --git a/Task/Strip-a-set-of-characters-from-a-string/0DESCRIPTION b/Task/Strip-a-set-of-characters-from-a-string/0DESCRIPTION new file mode 100644 index 0000000000..c592357fbd --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/0DESCRIPTION @@ -0,0 +1,4 @@ +The task is to create a function that strips a set of characters from a string. The function should take two arguments: the first argument being a string to stripped and the second, a string containing the set of characters to be stripped. The returned string should contain the first string, stripped of any characters in the second argument: + + print stripchars("She was a soul stripper. She took my heart!","aei") +Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/1META.yaml b/Task/Strip-a-set-of-characters-from-a-string/1META.yaml new file mode 100644 index 0000000000..ae625822b7 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/1META.yaml @@ -0,0 +1,2 @@ +--- +note: String manipulation diff --git a/Task/Strip-a-set-of-characters-from-a-string/ALGOL-68/strip-a-set-of-characters-from-a-string.alg b/Task/Strip-a-set-of-characters-from-a-string/ALGOL-68/strip-a-set-of-characters-from-a-string.alg new file mode 100644 index 0000000000..2fab8f3056 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/ALGOL-68/strip-a-set-of-characters-from-a-string.alg @@ -0,0 +1,13 @@ +#!/usr/local/bin/a68g --script # + +PROC strip chars = (STRING mine, ore)STRING: ( + STRING out := ""; + FOR i FROM LWB mine TO UPB mine DO + IF NOT char in string(mine[i], LOC INT, ore) THEN + out +:= mine[i] + FI + OD; + out[@LWB mine] +); + +printf(($gl$,stripchars("She was a soul stripper. She took my heart!","aei"))) diff --git a/Task/Strip-a-set-of-characters-from-a-string/AWK/strip-a-set-of-characters-from-a-string.awk b/Task/Strip-a-set-of-characters-from-a-string/AWK/strip-a-set-of-characters-from-a-string.awk new file mode 100644 index 0000000000..67dee72d94 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/AWK/strip-a-set-of-characters-from-a-string.awk @@ -0,0 +1,7 @@ +#!/usr/bin/awk -f +BEGIN { + x = "She was a soul stripper. She took my heart!"; + print x; + gsub(/[aei]/,"",x); + print x; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.ada b/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.ada new file mode 100644 index 0000000000..663ac8921a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO; + +procedure Strip_Characters_From_String is + + function Strip(The_String: String; The_Characters: String) + return String is + Keep: array (Character) of Boolean := (others => True); + Result: String(The_String'Range); + Last: Natural := Result'First-1; + begin + for I in The_Characters'Range loop + Keep(The_Characters(I)) := False; + end loop; + for J in The_String'Range loop + if Keep(The_String(J)) then + Last := Last+1; + Result(Last) := The_String(J); + end if; + end loop; + return Result(Result'First .. Last); + end Strip; + + S: String := "She was a soul stripper. She took my heart!"; + +begin -- main + Ada.Text_IO.Put_Line(Strip(S, "aei")); +end Strip_Characters_From_String; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Applesoft-BASIC/strip-a-set-of-characters-from-a-string.applesoft b/Task/Strip-a-set-of-characters-from-a-string/Applesoft-BASIC/strip-a-set-of-characters-from-a-string.applesoft new file mode 100644 index 0000000000..de2be7ad26 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Applesoft-BASIC/strip-a-set-of-characters-from-a-string.applesoft @@ -0,0 +1,20 @@ +100 LET S$ = "SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART!" +110 LET RM$ = "AEI" +120 GOSUB 200STRIPCHARS +130 PRINT SC$ +190 END +200 REM +210 REM STRIPCHARS +220 REM +230 LET SC$ = "" +240 LET SL = LEN (S$) +250 IF SL = 0 THEN RETURN +260 FOR SI = 1 TO SL +270 LET SM$ = MID$ (S$,SI,1) +280 FOR SJ = 1 TO LEN (RM$) +290 LET SR$ = MID$ (RM$,SJ,1) +300 LET ST = SR$ < > SM$ +310 IF ST THEN NEXT SJ +320 IF ST THEN SC$ = SC$ + SM$ +330 NEXT SI +340 RETURN diff --git a/Task/Strip-a-set-of-characters-from-a-string/AutoHotkey/strip-a-set-of-characters-from-a-string.ahk b/Task/Strip-a-set-of-characters-from-a-string/AutoHotkey/strip-a-set-of-characters-from-a-string.ahk new file mode 100644 index 0000000000..f02082b38a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/AutoHotkey/strip-a-set-of-characters-from-a-string.ahk @@ -0,0 +1,7 @@ +MsgBox % stripchars("She was a soul stripper. She took my heart!","aei") + +StripChars(string, charsToStrip){ + Loop Parse, charsToStrip + StringReplace, string, string, % A_LoopField, , All + return string +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string.basic b/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string.basic new file mode 100644 index 0000000000..3b9ed869fc --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/BASIC/strip-a-set-of-characters-from-a-string.basic @@ -0,0 +1,19 @@ +DECLARE FUNCTION stripchars$(src AS STRING, remove AS STRING) + +PRINT stripchars$("She was a soul stripper. She took my heart!", "aei") + +FUNCTION stripchars$(src AS STRING, remove AS STRING) + DIM l0 AS LONG, t AS LONG, s AS STRING + s = src + FOR l0 = 1 TO LEN(remove) + DO + t = INSTR(s, MID$(remove, l0, 1)) + IF t THEN + s = LEFT$(s, t - 1) + MID$(s, t + 1) + ELSE + EXIT DO + END IF + LOOP + NEXT + stripchars$ = s +END FUNCTION diff --git a/Task/Strip-a-set-of-characters-from-a-string/BBC-BASIC/strip-a-set-of-characters-from-a-string.bbc b/Task/Strip-a-set-of-characters-from-a-string/BBC-BASIC/strip-a-set-of-characters-from-a-string.bbc new file mode 100644 index 0000000000..4863ef14ac --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/BBC-BASIC/strip-a-set-of-characters-from-a-string.bbc @@ -0,0 +1,13 @@ + PRINT FNstripchars("She was a soul stripper. She took my heart!", "aei") + END + + DEF FNstripchars(A$, S$) + LOCAL I%, C%, C$ + FOR I% = 1 TO LEN(S$) + C$ = MID$(S$, I%, 1) + REPEAT + C% = INSTR(A$, C$) + IF C% A$ = LEFT$(A$, C%-1) + MID$(A$, C%+1) + UNTIL C% = 0 + NEXT + = A$ diff --git a/Task/Strip-a-set-of-characters-from-a-string/Bracmat/strip-a-set-of-characters-from-a-string.bracmat b/Task/Strip-a-set-of-characters-from-a-string/Bracmat/strip-a-set-of-characters-from-a-string.bracmat new file mode 100644 index 0000000000..ad24eb8c78 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Bracmat/strip-a-set-of-characters-from-a-string.bracmat @@ -0,0 +1,23 @@ +( ( strip + = string chars s pat + . !arg:(?string.?chars) + & :?s + & + ' ( ? + ( % + : [%( utf$!sjt + & ( @($chars:? !sjt ?) + | rev$!sjt !s:?s + ) + & ~ + ) + ) + ? + ) + : (=?pat) + & @(!string:!pat) + | rev$(str$!s) + ) +& out + $ (strip$("Аппетит приходит во время еды".веп) +); diff --git a/Task/Strip-a-set-of-characters-from-a-string/Burlesque/strip-a-set-of-characters-from-a-string.blq b/Task/Strip-a-set-of-characters-from-a-string/Burlesque/strip-a-set-of-characters-from-a-string.blq new file mode 100644 index 0000000000..26a55d04f8 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Burlesque/strip-a-set-of-characters-from-a-string.blq @@ -0,0 +1,2 @@ +blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[ +"Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Strip-a-set-of-characters-from-a-string/C++/strip-a-set-of-characters-from-a-string.cpp b/Task/Strip-a-set-of-characters-from-a-string/C++/strip-a-set-of-characters-from-a-string.cpp new file mode 100644 index 0000000000..eba23fbc5e --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C++/strip-a-set-of-characters-from-a-string.cpp @@ -0,0 +1,20 @@ +#include +#include +#include + +std::string stripchars(std::string str, const std::string &chars) +{ + str.erase( + std::remove_if(str.begin(), str.end(), [&](char c){ + return chars.find(c) != std::string::npos; + }), + str.end() + ); + return str; +} + +int main() +{ + std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; + return 0; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-1.cs b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-1.cs new file mode 100644 index 0000000000..793db1761a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-1.cs @@ -0,0 +1,15 @@ +using System; + +public static string RemoveCharactersFromString(string testString, string removeChars) +{ + char[] charAry = removeChars.ToCharArray(); + string returnString = testString; + foreach (char c in charAry) + { + while (returnString.IndexOf(c) > -1) + { + returnString = returnString.Remove(returnString.IndexOf(c), 1); + } + } + return returnString; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-2.cs b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-2.cs new file mode 100644 index 0000000000..9c9ce7f033 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-2.cs @@ -0,0 +1,11 @@ +using System; + +class Program +{ + static void Main(string[] args) + { + string testString = "She was a soul stripper. She took my heart!"; + string removeChars = "aei"; + Console.WriteLine(RemoveCharactersFromString(testString, removeChars)); + } +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-3.cs b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-3.cs new file mode 100644 index 0000000000..34f0250255 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C-sharp/strip-a-set-of-characters-from-a-string-3.cs @@ -0,0 +1,8 @@ +using System; +using System.Text.RegularExpressions; + +private static string RegexRemoveCharactersFromString(string testString, string removeChars) +{ + string pattern = "[" + removeChars + "]"; + return Regex.Replace(testString, pattern, ""); +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-1.c b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-1.c new file mode 100644 index 0000000000..6b08a3f7f8 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-1.c @@ -0,0 +1,29 @@ +#include +#include +#include + + /* removes all chars from string */ +char *strip_chars(const char *string, const char *chars) +{ + char * newstr = malloc(strlen(string) + 1); + int counter = 0; + + for ( ; *string; string++) { + if (!strchr(chars, *string)) { + newstr[ counter ] = *string; + ++ counter; + } + } + + newstr[counter] = 0; + return newstr; +} + +int main(void) +{ + char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); + printf("%s\n", new); + + free(new); + return 0; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c new file mode 100644 index 0000000000..a6ec361cd2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c @@ -0,0 +1,38 @@ +#include +#include +#include + +char *strip(const char * str, const char *pat) +{ + /* char replacement is typically done with lookup tables if + * the replacement set can be large: it turns O(m n) into + * O(m + n). + * If same replacement pattern is going to be applied to many + * strings, it's better to build a table beforehand and reuse it. + * If charset is big like unicode, table needs to be implemented + * more efficiently, say using bit field or hash table -- it + * all depends on the application. + */ + int i = 0, tbl[128] = {0}; + while (*pat != '\0') tbl[(int)*(pat++)] = 1; + + char *ret = malloc(strlen(str)); + do { + if (!tbl[(int)*str]) + ret[i++] = *str; + } while (*(str++) != '\0'); + + /* assuming realloc is efficient and succeeds; if not, we could + * do a two-pass, count first, alloc and strip second + */ + return realloc(ret, i); +} + +int main() +{ + char * x = strip("She was a soul stripper. She took my heart!", "aei"); + printf(x); + free(x); + + return 0; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Clojure/strip-a-set-of-characters-from-a-string.clj b/Task/Strip-a-set-of-characters-from-a-string/Clojure/strip-a-set-of-characters-from-a-string.clj new file mode 100644 index 0000000000..286573e4e1 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Clojure/strip-a-set-of-characters-from-a-string.clj @@ -0,0 +1,5 @@ +(defn strip [coll chars] + (apply str (remove #((set chars) %) coll))) + +(strip "She was a soul stripper. She took my heart!" "aei") +;; => "Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp b/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp new file mode 100644 index 0000000000..4b3bf7f639 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Common-Lisp/strip-a-set-of-characters-from-a-string.lisp @@ -0,0 +1,5 @@ +(defun strip-chars (str chars) + (remove-if (lambda (ch) (find ch chars)) str)) + +(strip-chars "She was a soul stripper. She took my heart!" "aei") +;; => "Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Strip-a-set-of-characters-from-a-string/D/strip-a-set-of-characters-from-a-string.d b/Task/Strip-a-set-of-characters-from-a-string/D/strip-a-set-of-characters-from-a-string.d new file mode 100644 index 0000000000..f6eacbb5a5 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/D/strip-a-set-of-characters-from-a-string.d @@ -0,0 +1,7 @@ +import std.stdio, std.string; + +void main() { + auto s = "She was a soul stripper. She took my heart!"; + auto ss = "Sh ws soul strppr. Sh took my hrt!"; + assert(s.removechars("aei") == ss); +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.delphi b/Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.delphi new file mode 100644 index 0000000000..f50a04ea06 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.delphi @@ -0,0 +1,21 @@ +program StripCharacters; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +function StripChars(const aSrc, aCharsToStrip: string): string; +var + c: Char; +begin + Result := aSrc; + for c in aCharsToStrip do + Result := StringReplace(Result, c, '', [rfReplaceAll, rfIgnoreCase]); +end; + +const + TEST_STRING = 'She was a soul stripper. She took my heart!'; +begin + Writeln(TEST_STRING); + Writeln(StripChars(TEST_STRING, 'aei')); +end. diff --git a/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.euphoria b/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.euphoria new file mode 100644 index 0000000000..a64060a9db --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.euphoria @@ -0,0 +1,8 @@ +include std\sequence.e +include std\console.e + +sequence originalString = "She was a soul stripper. She took my heart!" +puts(1,"Before : " & originalString & "\n") +originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""}) +puts(1,"After : " & originalString & "\n") +any_key() diff --git a/Task/Strip-a-set-of-characters-from-a-string/Fortran/strip-a-set-of-characters-from-a-string.f b/Task/Strip-a-set-of-characters-from-a-string/Fortran/strip-a-set-of-characters-from-a-string.f new file mode 100644 index 0000000000..7cfee90446 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Fortran/strip-a-set-of-characters-from-a-string.f @@ -0,0 +1,17 @@ +elemental subroutine strip(string,set) + character(len=*), intent(inout) :: string + character(len=*), intent(in) :: set + integer :: old, new, stride + old = 1; new = 1 + do + stride = scan( string( old : ), set ) + if ( stride > 0 ) then + string( new : new+stride-2 ) = string( old : old+stride-2 ) + old = old+stride + new = new+stride-1 + else + string( new : ) = string( old : ) + return + end if + end do +end subroutine strip diff --git a/Task/Strip-a-set-of-characters-from-a-string/Go/strip-a-set-of-characters-from-a-string.go b/Task/Strip-a-set-of-characters-from-a-string/Go/strip-a-set-of-characters-from-a-string.go new file mode 100644 index 0000000000..11dad919c6 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Go/strip-a-set-of-characters-from-a-string.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" + "strings" +) + +func stripchars(str, chr string) string { + return strings.Map(func(r rune) rune { + if strings.IndexRune(chr, r) < 0 { + return r + } + return -1 + }, str) +} + +func main() { + fmt.Println(stripchars("She was a soul stripper. She took my heart!", + "aei")) +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-1.groovy b/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-1.groovy new file mode 100644 index 0000000000..bd4eda2333 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-1.groovy @@ -0,0 +1,5 @@ +def stripChars = { string, stripChars -> + def list = string as List + list.removeAll(stripChars as List) + list.join() +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-2.groovy b/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-2.groovy new file mode 100644 index 0000000000..be62e3093e --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Groovy/strip-a-set-of-characters-from-a-string-2.groovy @@ -0,0 +1 @@ +println (stripChars('She was a soul stripper. She took my heart!', 'aei')) diff --git a/Task/Strip-a-set-of-characters-from-a-string/Haskell/strip-a-set-of-characters-from-a-string.hs b/Task/Strip-a-set-of-characters-from-a-string/Haskell/strip-a-set-of-characters-from-a-string.hs new file mode 100644 index 0000000000..cb8ec16acc --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Haskell/strip-a-set-of-characters-from-a-string.hs @@ -0,0 +1,2 @@ +stripChars :: String -> String -> String +stripChars = filter . flip notElem diff --git a/Task/Strip-a-set-of-characters-from-a-string/Icon/strip-a-set-of-characters-from-a-string.icon b/Task/Strip-a-set-of-characters-from-a-string/Icon/strip-a-set-of-characters-from-a-string.icon new file mode 100644 index 0000000000..2def163fee --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Icon/strip-a-set-of-characters-from-a-string.icon @@ -0,0 +1,10 @@ +procedure main(A) + cs := \A[1] | 'aei' # argument is set of characters to strip + every write(stripChars(!&input, cs)) # strip all input lines +end + +procedure stripChars(s,cs) + ns := "" + s ? while ns ||:= (not pos(0), tab(upto(cs)|0)) do tab(many(cs))) + return ns +end diff --git a/Task/Strip-a-set-of-characters-from-a-string/J/strip-a-set-of-characters-from-a-string.j b/Task/Strip-a-set-of-characters-from-a-string/J/strip-a-set-of-characters-from-a-string.j new file mode 100644 index 0000000000..d58cb2a0ea --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/J/strip-a-set-of-characters-from-a-string.j @@ -0,0 +1,2 @@ + 'She was a soul stripper. She took my heart!' -. 'aei' +Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string.java b/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string.java new file mode 100644 index 0000000000..9c89d91dc8 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string.java @@ -0,0 +1,13 @@ +class StripChars { + public static String stripChars(String inString, String toStrip) { + return inString.replaceAll("[" + toStrip + "]", ""); + } + + public static void main(String[] args) { + String sentence = "She was a soul stripper. She took my heart!"; + String chars = "aei"; + System.out.println("sentence: " + sentence); + System.out.println("to strip: " + chars); + System.out.println("stripped: " + stripChars(sentence, chars)); + } +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string.js b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string.js new file mode 100644 index 0000000000..5a0484e923 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/JavaScript/strip-a-set-of-characters-from-a-string.js @@ -0,0 +1,3 @@ +function stripchars(string, chars) { + return string.replace(RegExp('['+chars+']','g'), ''); +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Liberty-BASIC/strip-a-set-of-characters-from-a-string.liberty b/Task/Strip-a-set-of-characters-from-a-string/Liberty-BASIC/strip-a-set-of-characters-from-a-string.liberty new file mode 100644 index 0000000000..9b87cc411e --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Liberty-BASIC/strip-a-set-of-characters-from-a-string.liberty @@ -0,0 +1,11 @@ +Print stripchars$("She was a soul stripper. She took my heart!", "aei", 1) +End + +Function stripchars$(strip$, chars$, num) + For i = 1 To Len(strip$) + If Mid$(strip$, i, 1) <> Mid$(chars$, num, 1) Then + stripchars$ = (stripchars$ + Mid$(strip$, i, 1)) + End If + Next i + If (num <= Len(chars$)) Then stripchars$ = stripchars$(stripchars$, chars$, (num + 1)) +End Function diff --git a/Task/Strip-a-set-of-characters-from-a-string/Logo/strip-a-set-of-characters-from-a-string.logo b/Task/Strip-a-set-of-characters-from-a-string/Logo/strip-a-set-of-characters-from-a-string.logo new file mode 100644 index 0000000000..e830966dfe --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Logo/strip-a-set-of-characters-from-a-string.logo @@ -0,0 +1,7 @@ +to strip :string :chars + output filter [not substringp ? :chars] :string +end + +print strip "She\ was\ a\ soul\ stripper.\ She\ took\ my\ heart! "aei + +bye diff --git a/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua new file mode 100644 index 0000000000..1069a548cf --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua @@ -0,0 +1,9 @@ +function stripchars( str, chr ) + local s = "" + for g in str:gmatch( "[^"..chr.."]" ) do + s = s .. g + end + return s +end + +print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) ) diff --git a/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m b/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m new file mode 100644 index 0000000000..24427e7f74 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/MATLAB/strip-a-set-of-characters-from-a-string.m @@ -0,0 +1,6 @@ + function str = stripchars(str, charlist) + charlist = unique(charlist); + for k=1:length(charlist) + str(str==charlist(k)) = []; + end; + end; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Mathematica/strip-a-set-of-characters-from-a-string.math b/Task/Strip-a-set-of-characters-from-a-string/Mathematica/strip-a-set-of-characters-from-a-string.math new file mode 100644 index 0000000000..b4313ccc36 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Mathematica/strip-a-set-of-characters-from-a-string.math @@ -0,0 +1,3 @@ +stripchars[a_,b_]:=StringReplace[a,(#->"")&/@Characters[b]] +stripchars["She was a soul stripper. She took my heart!","aei"] +->Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Nemerle/strip-a-set-of-characters-from-a-string.nemerle b/Task/Strip-a-set-of-characters-from-a-string/Nemerle/strip-a-set-of-characters-from-a-string.nemerle new file mode 100644 index 0000000000..dc980586a6 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Nemerle/strip-a-set-of-characters-from-a-string.nemerle @@ -0,0 +1,5 @@ +StripChars( text : string, remove : string ) : string +{ + def chuck = Explode(remove); + Concat( "", Split(text, chuck)) +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/NetRexx/strip-a-set-of-characters-from-a-string.netrexx b/Task/Strip-a-set-of-characters-from-a-string/NetRexx/strip-a-set-of-characters-from-a-string.netrexx new file mode 100644 index 0000000000..4135d38124 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/NetRexx/strip-a-set-of-characters-from-a-string.netrexx @@ -0,0 +1,16 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols + +say stripchars("She was a soul stripper. She took my heart!", "aei") + +return + +method stripchars(haystack, chs) public static + + loop c_ = 1 to chs.length + needle = chs.substr(c_, 1) + haystack = haystack.changestr(needle, '') + end c_ + + return haystack diff --git a/Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ocaml b/Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ocaml new file mode 100644 index 0000000000..935c06f22b --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ocaml @@ -0,0 +1,13 @@ +let stripchars s cs = + let len = String.length s in + let res = String.create len in + let rec aux i j = + if i >= len then String.sub res 0 j + else if String.contains cs s.[i] then + aux (succ i) (j) + else begin + res.[j] <- s.[i]; + aux (succ i) (succ j) + end + in + aux 0 0 diff --git a/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-1.m b/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-1.m new file mode 100644 index 0000000000..18f3ef01f1 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-1.m @@ -0,0 +1,9 @@ +@interface NSString (StripCharacters) +- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars; +@end + +@implementation NSString (StripCharacters) +- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars { + return [[self componentsSeparatedByCharactersInSet:chars] componentsJoinedByString:@""]; +} +@end diff --git a/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-2.m b/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-2.m new file mode 100644 index 0000000000..6eac1492eb --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Objective-C/strip-a-set-of-characters-from-a-string-2.m @@ -0,0 +1,5 @@ + NSString *aString = @"She was a soul stripper. She took my heart!"; + NSCharacterSet* chars = [NSCharacterSet characterSetWithCharactersInString:@"aei"]; + + // Display the NSString. + NSLog(@"%@", [aString stripCharactersInSet:chars]); diff --git a/Task/Strip-a-set-of-characters-from-a-string/PARI-GP/strip-a-set-of-characters-from-a-string.pari b/Task/Strip-a-set-of-characters-from-a-string/PARI-GP/strip-a-set-of-characters-from-a-string.pari new file mode 100644 index 0000000000..c58b89915e --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PARI-GP/strip-a-set-of-characters-from-a-string.pari @@ -0,0 +1,8 @@ +stripchars(s, bad)={ + bad=Set(Vec(Vecsmall(bad))); + s=Vecsmall(s); + my(v=[]); + for(i=1,#s,if(!setsearch(bad,s[i]),v=concat(v,s[i]))); + Strchr(v) +}; +stripchars("She was a soul stripper. She took my heart!","aei") diff --git a/Task/Strip-a-set-of-characters-from-a-string/PHP/strip-a-set-of-characters-from-a-string.php b/Task/Strip-a-set-of-characters-from-a-string/PHP/strip-a-set-of-characters-from-a-string.php new file mode 100644 index 0000000000..d539468590 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PHP/strip-a-set-of-characters-from-a-string.php @@ -0,0 +1,7 @@ + diff --git a/Task/Strip-a-set-of-characters-from-a-string/PL-I/strip-a-set-of-characters-from-a-string.pli b/Task/Strip-a-set-of-characters-from-a-string/PL-I/strip-a-set-of-characters-from-a-string.pli new file mode 100644 index 0000000000..8c8e47adcf --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PL-I/strip-a-set-of-characters-from-a-string.pli @@ -0,0 +1,14 @@ +strip_chars: procedure (text, chars) returns (character (100) varying); + declare text character (*) varying, chars character (*) varying; + declare out_text character (100); + declare ch character (1); + declare (i, j) fixed binary; + + j = 0; + do i = 1 to length(text); + ch = substr(text, i, 1); + if index(chars, ch) = 0 then + do; j = j + 1; substr(out_text, j, 1) = ch; end; + end; + return (substr(out_text, 1, j) ); +end strip_chars; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Perl-6/strip-a-set-of-characters-from-a-string.pl6 b/Task/Strip-a-set-of-characters-from-a-string/Perl-6/strip-a-set-of-characters-from-a-string.pl6 new file mode 100644 index 0000000000..1555e435b2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Perl-6/strip-a-set-of-characters-from-a-string.pl6 @@ -0,0 +1,5 @@ +sub strip_chars ( $s, $chars ) { + return $s.trans( $chars.comb X=> '' ); +} + +say strip_chars( 'She was a soul stripper. She took my heart!', 'aei' ); diff --git a/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-1.pl b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-1.pl new file mode 100644 index 0000000000..62383a76e5 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-1.pl @@ -0,0 +1,7 @@ +sub stripchars { + my ($s, $chars) = @_; + $s =~ s/[$chars]//g; + return $s; +} + +print stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-2.pl b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-2.pl new file mode 100644 index 0000000000..1f13c51858 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-2.pl @@ -0,0 +1 @@ +$str =~ tr/aei//d; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-3.pl b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-3.pl new file mode 100644 index 0000000000..30285091ad --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Perl/strip-a-set-of-characters-from-a-string-3.pl @@ -0,0 +1,5 @@ +sub stripchars { + my ($s, $chars) = @_; + eval("\$s =~ tr/$chars//d;"); + return $s; +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/PicoLisp/strip-a-set-of-characters-from-a-string.l b/Task/Strip-a-set-of-characters-from-a-string/PicoLisp/strip-a-set-of-characters-from-a-string.l new file mode 100644 index 0000000000..88a69bb7bf --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PicoLisp/strip-a-set-of-characters-from-a-string.l @@ -0,0 +1,2 @@ +(de strDiff (Str1 Str2) + (pack (diff (chop Str1) (chop Str2))) ) diff --git a/Task/Strip-a-set-of-characters-from-a-string/Prolog/strip-a-set-of-characters-from-a-string.pro b/Task/Strip-a-set-of-characters-from-a-string/Prolog/strip-a-set-of-characters-from-a-string.pro new file mode 100644 index 0000000000..c209fae3d2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Prolog/strip-a-set-of-characters-from-a-string.pro @@ -0,0 +1,5 @@ +:- use_module(library(lambda)). + +stripchars(String, Exclude, Result) :- + exclude(\X^(member(X, Exclude)), String, Result1), + string_to_list(Result, Result1). diff --git a/Task/Strip-a-set-of-characters-from-a-string/PureBasic/strip-a-set-of-characters-from-a-string.purebasic b/Task/Strip-a-set-of-characters-from-a-string/PureBasic/strip-a-set-of-characters-from-a-string.purebasic new file mode 100644 index 0000000000..b628a0b70c --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PureBasic/strip-a-set-of-characters-from-a-string.purebasic @@ -0,0 +1,18 @@ +Procedure.s stripChars(source.s, charsToStrip.s) + Protected i, *ptrChar.Character, length = Len(source), result.s + *ptrChar = @source + For i = 1 To length + If Not FindString(charsToStrip, Chr(*ptrChar\c)) + result + Chr(*ptrChar\c) + EndIf + *ptrChar + SizeOf(Character) + Next + ProcedureReturn result +EndProcedure + +If OpenConsole() + PrintN(stripChars("She was a soul stripper. She took my heart!", "aei")) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-1.py b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-1.py new file mode 100644 index 0000000000..d1f9c7e74f --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-1.py @@ -0,0 +1,5 @@ +>>> def stripchars(s, chars): +... return s.translate(None, chars) +... +>>> stripchars("She was a soul stripper. She took my heart!", "aei") +'Sh ws soul strppr. Sh took my hrt!' diff --git a/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-2.py b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-2.py new file mode 100644 index 0000000000..91c5e87c3d --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-2.py @@ -0,0 +1,6 @@ +>>> import string +>>> def stripchars(s, chars): +... return s.translate(string.maketrans("", ""), chars) +... +>>> stripchars("She was a soul stripper. She took my heart!", "aei") +'Sh ws soul strppr. Sh took my hrt!' diff --git a/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-3.py b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-3.py new file mode 100644 index 0000000000..b8e4960e10 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-3.py @@ -0,0 +1,5 @@ +>>> def stripchars(s, chars): +... return "".join(c for c in s if c not in chars) +... +>>> stripchars("She was a soul stripper. She took my heart!", "aei") +'Sh ws soul strppr. Sh took my hrt!' diff --git a/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-4.py b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-4.py new file mode 100644 index 0000000000..0846ee7310 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Python/strip-a-set-of-characters-from-a-string-4.py @@ -0,0 +1,7 @@ +>>> import re +>>> def stripchars(s, chars): + return re.sub('[%s]+' % re.escape(chars), '', s) + +>>> stripchars("She was a soul stripper. She took my heart!", "aei") +'Sh ws soul strppr. Sh took my hrt!' +>>> diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-1.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-1.rexx new file mode 100644 index 0000000000..2d95d6c5b6 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-1.rexx @@ -0,0 +1,22 @@ +/* Rexx */ + +Do + Say stripchars("She was a soul stripper. She took my heart!", "aei") + + Return +End +Exit + +stripchars: + Procedure +Do + Parse arg haystack, chs + + Do c_ = 1 to length(chs) + needle = substr(chs, c_, 1) + haystack = changestr(needle, haystack, '') + End c_ + + Return haystack +End +Exit diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx new file mode 100644 index 0000000000..69cfc3a877 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx @@ -0,0 +1,9 @@ +/*REXX program to remove a set of characters from a string (haystack). */ +say stripChars('She was a soul stripper. She took my heart!', "iea") +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────STRIPCGARS subroutine──────────────*/ +stripChars: procedure; parse arg haystack, remove + do j=1 for length(remove) + haystack=changestr(substr(remove,j,1), haystack, '') + end /*j*/ +return haystack diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx new file mode 100644 index 0000000000..f1e6eb5a74 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx @@ -0,0 +1,26 @@ +/*╔══════════════════════════════╗ CHANGESTR ╔═════════════════════════╗ +╔═╩══════════════════════════════╝ function ╚═════════════════════════╩═╗ +║ new string to be used──────────┐ ┌─────limit of # changes (times)║ +║ original string (haystack)────────┐ │ │ [default: ≈ one billian]║ +║ old string to be changed───┐ │ │ │ ┌───begin at this occurance #.║ +║ {O, H, and N can be null.} │ │ │ │ │ [default: 1st occurrance]║ +╚═╦════════════════════════════╗ │ │ │ │ │ ╔═══════════════════════╦═╝ + ╚════════════════════════════╝ ↓ ↓ ↓ ↓ ↓ ╚═══════════════════════╝*/ +changestr: procedure; parse arg o,h,n,t,b /* T and B are optional.*/ +$='' /*$: the returned string.*/ +t=word(t 999999999 , 1) /*maybe use the default? */ +b=word(b 1 , 1) /* " " " " */ +w=length(o) /*length of OLD string.*/ +if w==0 & t\=0 then return n || h /*changing a null char ? */ +#=0 /*# of changed occurances*/ + do j=1 until # >= t /*keep changing, T times.*/ + parse var h y (o) _ +(w) h /*parse the string ... */ + if _=='' then return $ || y /*no more left, return. */ + if j> "She was a soul stripper. She took my heart!".delete("aei") +=> "Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Strip-a-set-of-characters-from-a-string/Scala/strip-a-set-of-characters-from-a-string.scala b/Task/Strip-a-set-of-characters-from-a-string/Scala/strip-a-set-of-characters-from-a-string.scala new file mode 100644 index 0000000000..d6cd05b454 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Scala/strip-a-set-of-characters-from-a-string.scala @@ -0,0 +1,4 @@ +def stripChars(s:String, ch:String)= s filterNot (ch contains _) + +stripChars("She was a soul stripper. She took my heart!", "aei") +// => Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Sed/strip-a-set-of-characters-from-a-string.sed b/Task/Strip-a-set-of-characters-from-a-string/Sed/strip-a-set-of-characters-from-a-string.sed new file mode 100644 index 0000000000..6d6a82f9e3 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Sed/strip-a-set-of-characters-from-a-string.sed @@ -0,0 +1,6 @@ +#!/bin/bash + +strip_char() +{ + echo "$1" | sed "s/[$2]//g" +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Seed7/strip-a-set-of-characters-from-a-string.seed7 b/Task/Strip-a-set-of-characters-from-a-string/Seed7/strip-a-set-of-characters-from-a-string.seed7 new file mode 100644 index 0000000000..75c7577878 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Seed7/strip-a-set-of-characters-from-a-string.seed7 @@ -0,0 +1,18 @@ +$ include "seed7_05.s7i"; + +const func string: stripchars (in string: mainStri, in string: charList) is func + result + var string: strippedStri is ""; + local + var char: ch is ' '; + begin + strippedStri := mainStri; + for ch range charList do + strippedStri := replace(strippedStri, str(ch), ""); + end for; + end func; + +const proc: main is func + begin + writeln(stripchars("She was a soul stripper. She took my heart!", "aei")); + end func; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Smalltalk/strip-a-set-of-characters-from-a-string.st b/Task/Strip-a-set-of-characters-from-a-string/Smalltalk/strip-a-set-of-characters-from-a-string.st new file mode 100644 index 0000000000..878c982257 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Smalltalk/strip-a-set-of-characters-from-a-string.st @@ -0,0 +1,8 @@ +| stripChars | +stripChars := [ :string :chars | + string reject: [ :c | chars includes: c ] ]. +stripChars + value: 'She was a soul stripper. She took my heart!' + value: 'aei'. + +"'Sh ws soul strppr. Sh took my hrt!'" diff --git a/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-1.ml b/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-1.ml new file mode 100644 index 0000000000..39e10240a6 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-1.ml @@ -0,0 +1,9 @@ +fun stripchars (string, chars) = let + fun aux c = + if String.isSubstring (str c) chars then + "" + else + str c +in + String.translate aux string +end diff --git a/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-2.ml b/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-2.ml new file mode 100644 index 0000000000..7c4d5d0108 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Standard-ML/strip-a-set-of-characters-from-a-string-2.ml @@ -0,0 +1,2 @@ +fun stripchars (string, chars) = + String.concat (String.tokens (fn c => String.isSubstring (str c) chars) string) diff --git a/Task/Strip-a-set-of-characters-from-a-string/TUSCRIPT/strip-a-set-of-characters-from-a-string.tuscript b/Task/Strip-a-set-of-characters-from-a-string/TUSCRIPT/strip-a-set-of-characters-from-a-string.tuscript new file mode 100644 index 0000000000..c6f48389ee --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/TUSCRIPT/strip-a-set-of-characters-from-a-string.tuscript @@ -0,0 +1,5 @@ +$$ MODE TUSCRIPT,{} +string="She was a soul stripper. She took my heart!" +stringstrip=EXCHANGE (string,"_[aei]__") +print string +print stringstrip diff --git a/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr new file mode 100644 index 0000000000..628f60ec21 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/TXR/strip-a-set-of-characters-from-a-string.txr @@ -0,0 +1,14 @@ +@(next :args) +@arg1 +@arg2 +@(do (defun strip-chars (str set) + (for ((pieces ()) (str-suffix str)) + ((not (zerop (length str-suffix))) (cat-str (nreverse pieces) "")) + () + (let* ((len-piece (compl-span-str str-suffix set)) + (piece (sub-str str-suffix 0 len-piece)) + (suff0 (sub-str str-suffix len-piece nil)) + (len-non-piece (span-str suff0 set))) + (push piece pieces) + (set str-suffix (sub-str suff0 len-non-piece nil)))))) +@(bind result @(strip-chars arg1 arg2)) diff --git a/Task/Strip-a-set-of-characters-from-a-string/Tcl/strip-a-set-of-characters-from-a-string.tcl b/Task/Strip-a-set-of-characters-from-a-string/Tcl/strip-a-set-of-characters-from-a-string.tcl new file mode 100644 index 0000000000..df324bfe3f --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Tcl/strip-a-set-of-characters-from-a-string.tcl @@ -0,0 +1,7 @@ +proc stripchars {str chars} { + foreach c [split $chars ""] {set str [string map [list $c ""] $str]} + return $str +} + +set s "She was a soul stripper. She took my heart!" +puts [stripchars $s "aei"] diff --git a/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-1.sh b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-1.sh new file mode 100644 index 0000000000..83da251056 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-1.sh @@ -0,0 +1,3 @@ +strip_chars() { + echo "$1" | tr -d "$2" +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-2.sh b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-2.sh new file mode 100644 index 0000000000..cca8b8d647 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-2.sh @@ -0,0 +1,3 @@ +function strip_chars { + echo "${1//[$2]}" +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-3.sh b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-3.sh new file mode 100644 index 0000000000..5d14db26ae --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/UNIX-Shell/strip-a-set-of-characters-from-a-string-3.sh @@ -0,0 +1 @@ + strip_chars "She was a soul stripper. She took my heart!" aei diff --git a/Task/Strip-a-set-of-characters-from-a-string/Ursala/strip-a-set-of-characters-from-a-string.ursala b/Task/Strip-a-set-of-characters-from-a-string/Ursala/strip-a-set-of-characters-from-a-string.ursala new file mode 100644 index 0000000000..bb5a35a8fb --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Ursala/strip-a-set-of-characters-from-a-string.ursala @@ -0,0 +1,5 @@ +strip = ~&j + +#cast %s + +test = strip('she was a soul stripper. she took my heart','aei') diff --git a/Task/Strip-block-comments/0DESCRIPTION b/Task/Strip-block-comments/0DESCRIPTION new file mode 100644 index 0000000000..daa68f2de3 --- /dev/null +++ b/Task/Strip-block-comments/0DESCRIPTION @@ -0,0 +1,27 @@ +A block comment begins with a ''beginning delimiter'' and ends with a ''ending delimiter'', including the delimiters. These delimiters are often multi-character sequences. + +'''Task:''' Strip block comments from program text (of a programming language much like classic [[C]]). Your demos should at least handle simple, non-nested and multiline block comment delimiters. The beginning delimiter is the two-character sequence “/*” and the ending delimiter is “*/”. + +Sample text for stripping: +
+  /**
+   * Some comments
+   * longer comments here that we can parse.
+   *
+   * Rahoo
+   */
+   function subroutine() {
+    a = /* inline comment */ b + c ;
+   }
+   /*/ <-- tricky comments */
+
+   /**
+    * Another comment.
+    */
+    function something() {
+    }
+
+ +'''Extra credit:''' Ensure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them. (If your language supports them, [[Optional parameters|optional parameters]] may be useful for this.) + +C.f: [[Strip comments from a string]] diff --git a/Task/Strip-block-comments/1META.yaml b/Task/Strip-block-comments/1META.yaml new file mode 100644 index 0000000000..df2caea584 --- /dev/null +++ b/Task/Strip-block-comments/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Text processing diff --git a/Task/Strip-block-comments/Ada/strip-block-comments.ada b/Task/Strip-block-comments/Ada/strip-block-comments.ada new file mode 100644 index 0000000000..a99b5cd779 --- /dev/null +++ b/Task/Strip-block-comments/Ada/strip-block-comments.ada @@ -0,0 +1,93 @@ +with Ada.Strings.Fixed; +with Ada.Strings.Unbounded; +with Ada.Text_IO; +with Ada.Command_Line; + +procedure Strip is + use Ada.Strings.Unbounded; + procedure Print_Usage is + begin + Ada.Text_IO.Put_Line ("Usage:"); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (" strip [ []]"); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (" file: file to strip"); + Ada.Text_IO.Put_Line (" opening: string for opening comment"); + Ada.Text_IO.Put_Line (" closing: string for closing comment"); + Ada.Text_IO.New_Line; + end Print_Usage; + + Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*"); + Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/"); + Inside_Comment : Boolean := False; + + function Strip_Comments (From : String) return String is + use Ada.Strings.Fixed; + Opening_Index : Natural; + Closing_Index : Natural; + Start_Index : Natural := From'First; + begin + if Inside_Comment then + Start_Index := + Index (Source => From, Pattern => To_String (Closing_Pattern)); + if Start_Index < From'First then + return ""; + end if; + Inside_Comment := False; + Start_Index := Start_Index + Length (Closing_Pattern); + end if; + Opening_Index := + Index + (Source => From, + Pattern => To_String (Opening_Pattern), + From => Start_Index); + if Opening_Index < From'First then + return From (Start_Index .. From'Last); + else + Closing_Index := + Index + (Source => From, + Pattern => To_String (Closing_Pattern), + From => Opening_Index + Length (Opening_Pattern)); + if Closing_Index > 0 then + return From (Start_Index .. Opening_Index - 1) & + Strip_Comments + (From ( + Closing_Index + Length (Closing_Pattern) .. From'Last)); + else + Inside_Comment := True; + return From (Start_Index .. Opening_Index - 1); + end if; + end if; + end Strip_Comments; + + File : Ada.Text_IO.File_Type; +begin + if Ada.Command_Line.Argument_Count < 1 + or else Ada.Command_Line.Argument_Count > 3 + then + Print_Usage; + return; + end if; + if Ada.Command_Line.Argument_Count > 1 then + Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2)); + if Ada.Command_Line.Argument_Count > 2 then + Closing_Pattern := + To_Unbounded_String (Ada.Command_Line.Argument (3)); + else + Closing_Pattern := Opening_Pattern; + end if; + end if; + Ada.Text_IO.Open + (File => File, + Mode => Ada.Text_IO.In_File, + Name => Ada.Command_Line.Argument (1)); + while not Ada.Text_IO.End_Of_File (File => File) loop + declare + Line : constant String := Ada.Text_IO.Get_Line (File); + begin + Ada.Text_IO.Put_Line (Strip_Comments (Line)); + end; + end loop; + Ada.Text_IO.Close (File => File); +end Strip; diff --git a/Task/Strip-block-comments/BBC-BASIC/strip-block-comments.bbc b/Task/Strip-block-comments/BBC-BASIC/strip-block-comments.bbc new file mode 100644 index 0000000000..8122897f0e --- /dev/null +++ b/Task/Strip-block-comments/BBC-BASIC/strip-block-comments.bbc @@ -0,0 +1,38 @@ + infile$ = "C:\sample.c" + outfile$ = "C:\stripped.c" + + PROCstripblockcomments(infile$, outfile$, "/*", "*/") + END + + DEF PROCstripblockcomments(infile$, outfile$, start$, finish$) + LOCAL infile%, outfile%, comment%, test%, A$ + + infile% = OPENIN(infile$) + IF infile%=0 ERROR 100, "Could not open input file" + outfile% = OPENOUT(outfile$) + IF outfile%=0 ERROR 100, "Could not open output file" + + WHILE NOT EOF#infile% + A$ = GET$#infile% TO 10 + REPEAT + IF comment% THEN + test% = INSTR(A$, finish$) + IF test% THEN + A$ = MID$(A$, test% + LEN(finish$)) + comment% = FALSE + ENDIF + ELSE + test% = INSTR(A$, start$) + IF test% THEN + BPUT#outfile%, LEFT$(A$, test%-1); + A$ = MID$(A$, test% + LEN(start$)) + comment% = TRUE + ENDIF + ENDIF + UNTIL test%=0 + IF NOT comment% BPUT#outfile%, A$ + ENDWHILE + + CLOSE #infile% + CLOSE #outfile% + ENDPROC diff --git a/Task/Strip-block-comments/C++/strip-block-comments.cpp b/Task/Strip-block-comments/C++/strip-block-comments.cpp new file mode 100644 index 0000000000..7a98b3d2d6 --- /dev/null +++ b/Task/Strip-block-comments/C++/strip-block-comments.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +#include +#include + +int main( ) { + std::ifstream codeFile( "samplecode.txt" ) ; + if ( codeFile ) { + boost::regex commentre( "/\\*.*?\\*/" ) ;//comment start and end, and as few characters in between as possible + std::string my_erase( "" ) ; //erase them + std::string stripped ; + std::string code( (std::istreambuf_iterator( codeFile ) ) , + std::istreambuf_iterator( ) ) ; + codeFile.close( ) ; + stripped = boost::regex_replace( code , commentre , my_erase ) ; + std::cout << "Code unstripped:\n" << stripped << std::endl ; + return 0 ; + } + else { + std::cout << "Could not find code file!" << std::endl ; + return 1 ; + } +} diff --git a/Task/Strip-block-comments/C/strip-block-comments.c b/Task/Strip-block-comments/C/strip-block-comments.c new file mode 100644 index 0000000000..0181108332 --- /dev/null +++ b/Task/Strip-block-comments/C/strip-block-comments.c @@ -0,0 +1,53 @@ +#include +#include +#include + +const char *ca = "/*", *cb = "*/"; +int al = 2, bl = 2; + +char *loadfile(const char *fn) { + FILE *f = fopen(fn, "rb"); + int l; + char *s; + + if (f != NULL) { + fseek(f, 0, SEEK_END); + l = ftell(f); + s = malloc(l+1); + rewind(f); + if (s) + fread(s, 1, l, f); + fclose(f); + } + return s; +} + +void stripcomments(char *s) { + char *a, *b; + int len = strlen(s) + 1; + + while ((a = strstr(s, ca)) != NULL) { + b = strstr(a+al, cb); + if (b == NULL) + break; + b += bl; + memmove(a, b, len-(b-a)); + } +} + +int main(int argc, char **argv) { + const char *fn = "input.txt"; + char *s; + + if (argc >= 2) + fn = argv[1]; + s = loadfile(fn); + if (argc == 4) { + al = strlen(ca = argv[2]); + bl = strlen(cb = argv[3]); + } + stripcomments(s); + puts(s); + free(s); + return 0; +} diff --git a/Task/Strip-block-comments/Clojure/strip-block-comments.clj b/Task/Strip-block-comments/Clojure/strip-block-comments.clj new file mode 100644 index 0000000000..03f43b99e2 --- /dev/null +++ b/Task/Strip-block-comments/Clojure/strip-block-comments.clj @@ -0,0 +1,12 @@ +(defn comment-strip [txt & args] + (let [args (conj {:delim ["/*" "*/"]} (apply hash-map args)) ; This is the standard way of doing keyword/optional arguments in Clojure + [opener closer] (:delim args)] + (loop [out "", txt txt, delim-count 0] ; delim-count is needed to handle nested comments + (let [[hdtxt resttxt] (split-at (count opener) txt)] ; This splits "/* blah blah */" into hdtxt="/*" and restxt="blah blah */" + (printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count) + (cond + (empty? hdtxt) (str out (apply str txt)) + (= (apply str hdtxt) opener) (recur out resttxt (inc delim-count)) + (= (apply str hdtxt) closer) (recur out resttxt (dec delim-count)) + (= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count) + true (recur out (rest txt) delim-count)))))) diff --git a/Task/Strip-block-comments/D/strip-block-comments.d b/Task/Strip-block-comments/D/strip-block-comments.d new file mode 100644 index 0000000000..c97bd3cd93 --- /dev/null +++ b/Task/Strip-block-comments/D/strip-block-comments.d @@ -0,0 +1,89 @@ +import std.algorithm, std.regex; + +string[2] separateComments(in string txt, + in string cpat0, in string cpat1) { + int[2] plen; // to handle /*/ + int i, j; // cursors + bool inside; // is inside comment? + + // pre-compute regex here if desired + //auto r0 = regex(cpat0); + //auto r1 = regex(cpat1); + //enum rct = ctRegex!(r"\n|\r"); + + bool advCursor() { + auto mo = match(txt[i .. $], inside ? cpat1 : cpat0); + if (mo.empty) + return false; + plen[inside] = max(0, plen[inside], mo.front[0].length); + j = i + mo.pre.length; // got comment head + if (inside) + j += mo.front[0].length; // or comment tail + + // special adjust for \n\r + if (!match(mo.front[0], r"\n|\r").empty) + j--; + return true; + } + + string[2] result; + while (true) { + if (!advCursor()) + break; + result[inside] ~= txt[i .. j]; // save slice of result + + // handle /*/ pattern + if (inside && (j - i < plen[0] + plen[1])) { + i = j; + if (!advCursor()) + break; + result[inside] ~= txt[i .. j]; // save result again + } + + i = j; // advance cursor + inside = !inside; // toggle search type + } + + if (inside) + throw new Exception("Mismatched Comment"); + result[inside] ~= txt[i .. $]; // save rest(non-comment) + return result; +} + + +void main() { + import std.stdio; + + static void showResults(in string e, in string[2] pair) { + writeln("===Original text:\n", e); + writeln("\n\n===Text without comments:\n", pair[0]); + writeln("\n\n===The stripped comments:\n", pair[1]); + } + + // First example ------------------------------ + immutable ex1 = ` /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }`; + + showResults(ex1, separateComments(ex1, `/\*`, `\*/`)); + + // Second example ------------------------------ + writeln("\n"); + immutable ex2 = "apples, pears # and bananas +apples, pears; and bananas "; // test for line comment + + showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`)); +} diff --git a/Task/Strip-block-comments/Go/strip-block-comments.go b/Task/Strip-block-comments/Go/strip-block-comments.go new file mode 100644 index 0000000000..17af822d22 --- /dev/null +++ b/Task/Strip-block-comments/Go/strip-block-comments.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "strings" +) + +// idiomatic to name a function newX that allocates an object, initializes it, +// and returns it ready to use. the object in this case is a closure. +func newStripper(start, end string) func(string) string { + // default to c-style block comments + if start == "" || end == "" { + start, end = "/*", "*/" + } + // closes on variables start, end. + return func(source string) string { + for { + cs := strings.Index(source, start) + if cs < 0 { + break + } + ce := strings.Index(source[cs+2:], end) + if ce < 0 { + break + } + source = source[:cs] + source[cs+ce+4:] + } + return source + } +} + +func main() { + // idiomatic is that zero values indicate to use meaningful defaults + stripC := newStripper("", "") + + // strip function now defined and can be called any number of times + // without respecifying delimiters + fmt.Println(stripC(` /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }`)) +} diff --git a/Task/Strip-block-comments/Groovy/strip-block-comments.groovy b/Task/Strip-block-comments/Groovy/strip-block-comments.groovy new file mode 100644 index 0000000000..573874fdb1 --- /dev/null +++ b/Task/Strip-block-comments/Groovy/strip-block-comments.groovy @@ -0,0 +1,20 @@ +def code = """ + /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +""" + +println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)").replaceAll('')) diff --git a/Task/Strip-block-comments/Haskell/strip-block-comments.hs b/Task/Strip-block-comments/Haskell/strip-block-comments.hs new file mode 100644 index 0000000000..57e1052560 --- /dev/null +++ b/Task/Strip-block-comments/Haskell/strip-block-comments.hs @@ -0,0 +1,16 @@ +import Data.List + +stripComments :: String -> String -> String -> String +stripComments start end = notComment + where notComment :: String -> String + notComment "" = "" + notComment xs + | start `isPrefixOf` xs = inComment $ drop (length start) xs + | otherwise = head xs:(notComment $ tail xs) + inComment :: String -> String + inComment "" = "" + inComment xs + | end `isPrefixOf` xs = notComment $ drop (length end) xs + | otherwise = inComment $ tail xs + +main = interact (stripComments "/*" "*/") diff --git a/Task/Strip-block-comments/Icon/strip-block-comments-1.icon b/Task/Strip-block-comments/Icon/strip-block-comments-1.icon new file mode 100644 index 0000000000..12738eb582 --- /dev/null +++ b/Task/Strip-block-comments/Icon/strip-block-comments-1.icon @@ -0,0 +1,16 @@ +procedure main() + every (unstripped := "") ||:= !&input || "\n" # Load file as one string + write(stripBlockComment(unstripped,"/*","*/")) +end + +procedure stripBlockComment(s1,s2,s3) #: strip comments between s2-s3 from s1 + result := "" + s1 ? { + while result ||:= tab(find(s2)) do { + move(*s2) + tab(find(s3)|0) # or end of string + move(*s3) + } + return result || tab(0) + } +end diff --git a/Task/Strip-block-comments/Icon/strip-block-comments-2.icon b/Task/Strip-block-comments/Icon/strip-block-comments-2.icon new file mode 100644 index 0000000000..e4a8501656 --- /dev/null +++ b/Task/Strip-block-comments/Icon/strip-block-comments-2.icon @@ -0,0 +1,14 @@ +procedure main() + every writes(stripBlockComment(!&input,"/*","*/")) +end + +procedure stripBlockComment(s,s2,s3) + static inC # non-null when inside comment + (s||"\n") ? while not pos(0) do { + if /inC then + if inC := 1(tab(find(s2))\1, move(*s2)) then suspend inC + else return tab(0) + else if (tab(find(s3))\1,move(*s3)) then inC := &null + else fail + } +end diff --git a/Task/Strip-block-comments/J/strip-block-comments-1.j b/Task/Strip-block-comments/J/strip-block-comments-1.j new file mode 100644 index 0000000000..95188de0eb --- /dev/null +++ b/Task/Strip-block-comments/J/strip-block-comments-1.j @@ -0,0 +1,6 @@ +strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;: + 1 0 0 + 0 2 0 + 2 3 2 + 0 2 2 +) diff --git a/Task/Strip-block-comments/J/strip-block-comments-2.j b/Task/Strip-block-comments/J/strip-block-comments-2.j new file mode 100644 index 0000000000..cd4792c684 --- /dev/null +++ b/Task/Strip-block-comments/J/strip-block-comments-2.j @@ -0,0 +1,18 @@ +example=: 0 :0 + /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +) diff --git a/Task/Strip-block-comments/J/strip-block-comments-3.j b/Task/Strip-block-comments/J/strip-block-comments-3.j new file mode 100644 index 0000000000..0d6e091089 --- /dev/null +++ b/Task/Strip-block-comments/J/strip-block-comments-3.j @@ -0,0 +1,10 @@ + strip example + + function subroutine() { + a = b + c ; + } + + + + function something() { + } diff --git a/Task/Strip-block-comments/J/strip-block-comments-4.j b/Task/Strip-block-comments/J/strip-block-comments-4.j new file mode 100644 index 0000000000..d3d469e989 --- /dev/null +++ b/Task/Strip-block-comments/J/strip-block-comments-4.j @@ -0,0 +1,7 @@ +stripp=:3 :0 + ('/*';'*/') stripp y +: + 'open close'=. x + marks=. (+./(-i._1+#open,close)|."0 1 open E. y) - close E.&.|. y + y #~ -. (+._1&|.) (1 <. 0 >. +)/\.&.|. marks +) diff --git a/Task/Strip-block-comments/Java/strip-block-comments.java b/Task/Strip-block-comments/Java/strip-block-comments.java new file mode 100644 index 0000000000..0710989e9a --- /dev/null +++ b/Task/Strip-block-comments/Java/strip-block-comments.java @@ -0,0 +1,50 @@ +import java.io.*; + +public class StripBlockComments{ + public static String readFile(String filename) { + BufferedReader reader = new BufferedReader(new FileReader(filename)); + try { + StringBuilder fileContents = new StringBuilder(); + char[] buffer = new char[4096]; + while (reader.read(buffer, 0, 4096) > 0) { + fileContents.append(buffer); + } + return fileContents.toString(); + } finally { + reader.close(); + } + } + + public static String stripComments(String beginToken, String endToken, + String input) { + StringBuilder output = new StringBuilder(); + while (true) { + int begin = input.indexOf(beginToken); + int end = input.indexOf(endToken, begin+beginToken.length()); + if (begin == -1 || end == -1) { + output.append(input); + return output.toString(); + } + output.append(input.substring(0, begin)); + input = input.substring(end + endToken.length()); + } + } + + public static void main(String[] args) { + if (args.length < 3) { + System.out.println("Usage: BeginToken EndToken FileToProcess"); + System.exit(1); + } + + String begin = args[0]; + String end = args[1]; + String input = args[2]; + + try { + System.out.println(stripComments(begin, end, readFile(input))); + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} diff --git a/Task/Strip-block-comments/Liberty-BASIC/strip-block-comments.liberty b/Task/Strip-block-comments/Liberty-BASIC/strip-block-comments.liberty new file mode 100644 index 0000000000..3e1ba90e20 --- /dev/null +++ b/Task/Strip-block-comments/Liberty-BASIC/strip-block-comments.liberty @@ -0,0 +1,45 @@ +global CRLF$ +CRLF$ =chr$( 13) +chr$( 10) + +sample$ =" /**"+CRLF$+_ +" * Some comments"+CRLF$+_ +" * longer comments here that we can parse."+CRLF$+_ +" *"+CRLF$+_ +" * Rahoo "+CRLF$+_ +" */"+CRLF$+_ +" function subroutine() {"+CRLF$+_ +" a = /* inline comment */ b + c ;"+CRLF$+_ +" }"+CRLF$+_ +" /*/ <-- tricky comments */"+CRLF$+_ +""+CRLF$+_ +" /**"+CRLF$+_ +" * Another comment."+CRLF$+_ +" */"+CRLF$+_ +" function something() {"+CRLF$+_ +" }"+CRLF$ + +startDelim$ ="/*" +finishDelim$ ="*/" + +print "________________________________" +print sample$ +print "________________________________" +print blockStripped$( sample$, startDelim$, finishDelim$) +print "________________________________" + +end + +function blockStripped$( in$, s$, f$) + for i =1 to len( in$) -len( s$) + if mid$( in$, i, len( s$)) =s$ then + i =i +len( s$) + do + if mid$( in$, i, 2) =CRLF$ then blockStripped$ =blockStripped$ +CRLF$ + i =i +1 + loop until ( mid$( in$, i, len( f$)) =f$) or ( i =len( in$) -len( f$)) + i =i +len( f$) -1 + else + blockStripped$ =blockStripped$ +mid$( in$, i, 1) + end if + next i +end function diff --git a/Task/Strip-block-comments/Lua/strip-block-comments.lua b/Task/Strip-block-comments/Lua/strip-block-comments.lua new file mode 100644 index 0000000000..4151eb7ddd --- /dev/null +++ b/Task/Strip-block-comments/Lua/strip-block-comments.lua @@ -0,0 +1,8 @@ +filename = "Text1.txt" + +fp = io.open( filename, "r" ) +str = fp:read( "*all" ) +fp:close() + +stripped = string.gsub( str, "/%*.-%*/", "" ) +print( stripped ) diff --git a/Task/Strip-block-comments/MATLAB/strip-block-comments.m b/Task/Strip-block-comments/MATLAB/strip-block-comments.m new file mode 100644 index 0000000000..a891ccbb69 --- /dev/null +++ b/Task/Strip-block-comments/MATLAB/strip-block-comments.m @@ -0,0 +1,13 @@ +function str = stripblockcomment(str,startmarker,endmarker) + while(1) + ix1 = strfind(str, startmarker); + if isempty(ix1) return; end; + ix2 = strfind(str(ix1+length(startmarker):end),endmarker); + if isempty(ix2) + str = str(1:ix1(1)-1); + return; + else + str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)]; + end; + end; +end; diff --git a/Task/Strip-block-comments/Mathematica/strip-block-comments.math b/Task/Strip-block-comments/Mathematica/strip-block-comments.math new file mode 100644 index 0000000000..a2ee18a0bd --- /dev/null +++ b/Task/Strip-block-comments/Mathematica/strip-block-comments.math @@ -0,0 +1,11 @@ +StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""] + +-> + function subroutine() { + a = b + c ; + } + + + + function something() { + } diff --git a/Task/Strip-block-comments/PL-I/strip-block-comments.pli b/Task/Strip-block-comments/PL-I/strip-block-comments.pli new file mode 100644 index 0000000000..8d668e244d --- /dev/null +++ b/Task/Strip-block-comments/PL-I/strip-block-comments.pli @@ -0,0 +1,34 @@ +/* A program to remove comments from text. */ +strip: procedure options (main); /* 8/1/2011 */ + declare text character (80) varying; + declare (j, k) fixed binary; + + on endfile (sysin) stop; + + do forever; + get edit (text) (L); + do until (k = 0); + k = index(text, '/*'); + if k > 0 then /* we have a start of comment. */ + do; + /* Look for end of comment. */ + j = index(text, '*/', k+2); + if j > 0 then + do; + text = substr(text, 1, k-1) || + substr(text, j+2, length(text)-(j+2)+1); + end; + else + do; /* The comment continues onto the next line. */ + put skip list ( substr(text, 1, k-1) ); +more: get edit (text) (L); + j = index(text, '*/'); + if j = 0 then do; put skip; go to more; end; + text = substr(text, j+2, length(text) - (j+2) + 1); + end; + end; + end; + put skip list (text); + end; + +end strip; diff --git a/Task/Strip-block-comments/Perl-6/strip-block-comments.pl6 b/Task/Strip-block-comments/Perl-6/strip-block-comments.pl6 new file mode 100644 index 0000000000..a78d2da59d --- /dev/null +++ b/Task/Strip-block-comments/Perl-6/strip-block-comments.pl6 @@ -0,0 +1,20 @@ +sample().split(/ '/*' .+? '*/' /).print; + +sub sample { +' /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +'} diff --git a/Task/Strip-block-comments/Perl/strip-block-comments.pl b/Task/Strip-block-comments/Perl/strip-block-comments.pl new file mode 100644 index 0000000000..dd3d8ffe9b --- /dev/null +++ b/Task/Strip-block-comments/Perl/strip-block-comments.pl @@ -0,0 +1,13 @@ +#!/usr/bin/perl -w +use strict ; +use warnings ; + +open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ; +my $code = "" ; +{ + local $/ ; + $code = ; #slurp mode +} +close FH ; +$code =~ s,/\*.*?\*/,,sg ; +print $code . "\n" ; diff --git a/Task/Strip-block-comments/PicoLisp/strip-block-comments.l b/Task/Strip-block-comments/PicoLisp/strip-block-comments.l new file mode 100644 index 0000000000..299b42da48 --- /dev/null +++ b/Task/Strip-block-comments/PicoLisp/strip-block-comments.l @@ -0,0 +1,3 @@ +(in "sample.txt" + (while (echo "/*") + (out "/dev/null" (echo "*/")) ) ) diff --git a/Task/Strip-block-comments/PureBasic/strip-block-comments.purebasic b/Task/Strip-block-comments/PureBasic/strip-block-comments.purebasic new file mode 100644 index 0000000000..013ed3f44c --- /dev/null +++ b/Task/Strip-block-comments/PureBasic/strip-block-comments.purebasic @@ -0,0 +1,51 @@ +Procedure.s escapeChars(text.s) + Static specialChars.s = "[\^$.|?*+()" + Protected output.s, nextChar.s, i, countChar = Len(text) + For i = 1 To countChar + nextChar = Mid(text, i, 1) + If FindString(specialChars, nextChar, 1) + output + "\" + nextChar + Else + output + nextChar + EndIf + Next + ProcedureReturn output +EndProcedure + +Procedure.s stripBlocks(text.s, first.s, last.s) + Protected delimter_1.s = escapeChars(first), delimter_2.s = escapeChars(last) + Protected expNum = CreateRegularExpression(#PB_Any, delimter_1 + ".*?" + delimter_2, #PB_RegularExpression_DotAll) + Protected output.s = ReplaceRegularExpression(expNum, text, "") + FreeRegularExpression(expNum) + ProcedureReturn output +EndProcedure + +Define source.s +source.s = " /**" + #CRLF$ +source.s + " * Some comments" + #CRLF$ +source.s + " * longer comments here that we can parse." + #CRLF$ +source.s + " *" + #CRLF$ +source.s + " * Rahoo " + #CRLF$ +source.s + " */" + #CRLF$ +source.s + " function subroutine() {" + #CRLF$ +source.s + " a = /* inline comment */ b + c ;" + #CRLF$ +source.s + " }" + #CRLF$ +source.s + " /*/ <-- tricky comments */" + #CRLF$ +source.s + "" + #CRLF$ +source.s + " /**" + #CRLF$ +source.s + " * Another comment." + #CRLF$ +source.s + " */" + #CRLF$ +source.s + " function something() {" + #CRLF$ +source.s + " }" + #CRLF$ + +If OpenConsole() + PrintN("--- source ---") + PrintN(source) + PrintN("--- source with block comments between '/*' and '*/' removed ---") + PrintN(stripBlocks(source, "/*", "*/")) + PrintN("--- source with block comments between '*' and '*' removed ---") + PrintN(stripBlocks(source, "*", "*")) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Strip-block-comments/Python/strip-block-comments-1.py b/Task/Strip-block-comments/Python/strip-block-comments-1.py new file mode 100644 index 0000000000..71f0d08c9e --- /dev/null +++ b/Task/Strip-block-comments/Python/strip-block-comments-1.py @@ -0,0 +1,24 @@ +def _commentstripper(txt, delim): + 'Strips first nest of block comments' + + deliml, delimr = delim + out = '' + if deliml in txt: + indx = txt.index(deliml) + out += txt[:indx] + txt = txt[indx+len(deliml):] + txt = _commentstripper(txt, delim) + assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt + indx = txt.index(delimr) + out += txt[(indx+len(delimr)):] + else: + out = txt + return out + +def commentstripper(txt, delim=('/*', '*/')): + 'Strips nests of block comments' + + deliml, delimr = delim + while deliml in txt: + txt = _commentstripper(txt, delim) + return txt diff --git a/Task/Strip-block-comments/Python/strip-block-comments-2.py b/Task/Strip-block-comments/Python/strip-block-comments-2.py new file mode 100644 index 0000000000..a17fa38d40 --- /dev/null +++ b/Task/Strip-block-comments/Python/strip-block-comments-2.py @@ -0,0 +1,41 @@ +def test(): + print('\nNON-NESTED BLOCK COMMENT EXAMPLE:') + sample = ''' /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }''' + print(commentstripper(sample)) + + print('\nNESTED BLOCK COMMENT EXAMPLE:') + sample = ''' /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + *//* + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + */ + /** + * Another comment. + */ + function something() { + }''' + print(commentstripper(sample)) + +if __name__ == '__main__': + test() diff --git a/Task/Strip-block-comments/Ruby/strip-block-comments.rb b/Task/Strip-block-comments/Ruby/strip-block-comments.rb new file mode 100644 index 0000000000..bc2f57db52 --- /dev/null +++ b/Task/Strip-block-comments/Ruby/strip-block-comments.rb @@ -0,0 +1,32 @@ +def remove_comments!(str, comment_start='/*', comment_end='*/') + while start_idx = str.index(comment_start) + end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1 + str[start_idx .. end_idx] = "" + end + str +end + +def remove_comments(str, comment_start='/*', comment_end='*/') + remove_comments!(str.dup, comment_start, comment_end) +end + +example = < +apples, pears # and bananas +apples, pears ; and bananas + + +Cf. [[Strip block comments]] diff --git a/Task/Strip-comments-from-a-string/1META.yaml b/Task/Strip-comments-from-a-string/1META.yaml new file mode 100644 index 0000000000..3bdc51ea57 --- /dev/null +++ b/Task/Strip-comments-from-a-string/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Basic language learning diff --git a/Task/Strip-comments-from-a-string/ALGOL-68/strip-comments-from-a-string.alg b/Task/Strip-comments-from-a-string/ALGOL-68/strip-comments-from-a-string.alg new file mode 100644 index 0000000000..d861e42dac --- /dev/null +++ b/Task/Strip-comments-from-a-string/ALGOL-68/strip-comments-from-a-string.alg @@ -0,0 +1,26 @@ +#!/usr/local/bin/a68g --script # + +PROC trim comment = (STRING line, CHAR marker)STRING:( + INT index := UPB line+1; + char in string(marker, index, line); + FOR i FROM index-1 BY -1 TO LWB line + WHILE line[i]=" " DO index := i OD; + line[:index-1] +); + +CHAR q = """"; + +print(( + q, trim comment("apples, pears # and bananas", "#"), q, new line, + q, trim comment("apples, pears ; and bananas", ";"), q, new line, + q, trim comment("apples, pears and bananas ", ";"), q, new line, + q, trim comment(" ", ";"), q, new line, # blank string # + q, trim comment("", ";"), q, new line # empty string # +)) + +CO Alternatively Algol68g has available "grep" +;STRING re marker := " *#", line := "apples, pears # and bananas"; + INT index := UPB line; + grep in string(re marker, line, index, NIL); + print((q, line[:index-1], q, new line)) +END CO diff --git a/Task/Strip-comments-from-a-string/AWK/strip-comments-from-a-string.awk b/Task/Strip-comments-from-a-string/AWK/strip-comments-from-a-string.awk new file mode 100644 index 0000000000..72dec94c7b --- /dev/null +++ b/Task/Strip-comments-from-a-string/AWK/strip-comments-from-a-string.awk @@ -0,0 +1,5 @@ +#!/usr/local/bin/awk -f +{ + sub("[ \t]*[#;].*$","",$0); + print; +} diff --git a/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.ada b/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.ada new file mode 100644 index 0000000000..6452f6ca31 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.ada @@ -0,0 +1,20 @@ +with Ada.Text_IO; +procedure Program is + Comment_Characters : String := "#;"; +begin + loop + declare + Line : String := Ada.Text_IO.Get_Line; + begin + exit when Line'Length = 0; + Outer_Loop : for I in Line'Range loop + for J in Comment_Characters'Range loop + if Comment_Characters(J) = Line(I) then + Ada.Text_IO.Put_Line(Line(Line'First .. I - 1)); + exit Outer_Loop; + end if; + end loop; + end loop Outer_Loop; + end; + end loop; +end Program; diff --git a/Task/Strip-comments-from-a-string/AutoHotkey/strip-comments-from-a-string.ahk b/Task/Strip-comments-from-a-string/AutoHotkey/strip-comments-from-a-string.ahk new file mode 100644 index 0000000000..46eab0f751 --- /dev/null +++ b/Task/Strip-comments-from-a-string/AutoHotkey/strip-comments-from-a-string.ahk @@ -0,0 +1,19 @@ +Delims := "#;" +str := "apples, pears # and bananas" +str2:= "apples, pears, `; and bananas" ; needed to escape the ; since that is AHK's comment marker +msgbox % StripComments(Str,Delims) +msgbox % StripComments(Str2,Delims) +; The % forces expression mode. + + +StripComments(String1,Delims){ + Loop, parse, delims + { + If Instr(String1,A_LoopField) + EndPosition := InStr(String1,A_LoopField) - 1 + Else + EndPosition := StrLen(String1) + StringLeft, String1, String1, EndPosition + } + return String1 +} diff --git a/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.autoit b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.autoit new file mode 100644 index 0000000000..2329163995 --- /dev/null +++ b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.autoit @@ -0,0 +1,17 @@ +Dim $Line1 = "apples, pears # and bananas" +Dim $Line2 = "apples, pears ; and bananas" + +_StripAtMarker($Line1) +_StripAtMarker($Line2) + +Func _StripAtMarker($_Line, $sMarker='# ;') + Local $aMarker = StringSplit($sMarker, ' ') + Local $iPos + For $i = 1 To $aMarker[0] + $iPos = StringInStr($_Line, $aMarker[$i]) + If $iPos Then + ConsoleWrite($_Line & @CRLF) + ConsoleWrite( StringStripWS( StringLeft($_Line, $iPos -1), 2) & @CRLF) + EndIf + Next +EndFunc ;==>_StripAtMarker diff --git a/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.autoit b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.autoit new file mode 100644 index 0000000000..c7dfdf0f42 --- /dev/null +++ b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.autoit @@ -0,0 +1,56 @@ +Dim $aLines[4] = _ +[ _ +"$a = $b + $c ; Comment line 1", _ +"Dim $s1 = 'some text; tiled with semicolon', $s2 = 'another text; also tiled with semicolon' ; Comment line 2 - semicolon as part of assignment", _ +"_SomeFunctionCall('string parameter with ;', $anotherParam) ; Comment line 3 - semicolon as part parameter in an function call", _ +"Func _AnotherFunction($param1=';', $param2=';', $param3=';') ; Comment line 4 - semicolon as default value in parameter of a function headline" _ +] + +For $i = 0 To 3 + ConsoleWrite('+> Line ' & $i+1 & ' full:' & @CRLF & '+>' & $aLines[$i] & @CRLF) + ConsoleWrite('!> without comment:' & @CRLF & '!>' & _LineStripComment($aLines[$i]) & @CRLF & @CRLF) +Next + + +Func _LineStripComment($_Line) + ; == tile line by all included comment marker + Local $aPartsWithMarker = StringSplit($_Line, ';') + Local $sNoComment + + ; == if no comment marker: return full line + If $aPartsWithMarker[0] = 0 Then Return $_Line + + ; == check if string in part, if is'nt: following part(s) are comment + For $i = 1 To $aPartsWithMarker[0] + If Not StringRegExp($aPartsWithMarker[$i], "('|\x22)") Then + If $i = 1 Then + Return StringStripWS($aPartsWithMarker[$i], 2) + Else + Return StringStripWS($sNoComment & $aPartsWithMarker[$i], 2) + EndIf + Else + ; == check if next leftside string delimiter has uneven count + Local $iLen = StringLen($aPartsWithMarker[$i]) + Local $fDetectDelim = False, $sStringDelim, $iDelimCount, $sCurr + For $j = $iLen To 1 Step -1 + $sCurr = StringMid($aPartsWithMarker[$i], $j, 1) + If Not $fDetectDelim Then + If $sCurr = "'" Or $sCurr = '"' Then + $sStringDelim = $sCurr + $iDelimCount += 1 + $fDetectDelim = True + EndIf + Else + If $sCurr = $sStringDelim Then $iDelimCount += 1 + EndIf + Next + If Mod($iDelimCount, 2) Then + ; == uneven count: so it masks the comment marker + $sNoComment &= $aPartsWithMarker[$i] & ';' + Else + ; == even count: all following is comment + Return StringStripWS($sNoComment & $aPartsWithMarker[$i], 2) + EndIf + EndIf + Next +EndFunc ;==>_LineStripComment diff --git a/Task/Strip-comments-from-a-string/BBC-BASIC/strip-comments-from-a-string.bbc b/Task/Strip-comments-from-a-string/BBC-BASIC/strip-comments-from-a-string.bbc new file mode 100644 index 0000000000..136a9d922a --- /dev/null +++ b/Task/Strip-comments-from-a-string/BBC-BASIC/strip-comments-from-a-string.bbc @@ -0,0 +1,15 @@ + marker$ = "#;" + PRINT FNstripcomment("apples, pears # and bananas", marker$) + PRINT FNstripcomment("apples, pears ; and bananas", marker$) + PRINT FNstripcomment(" apples, pears ", marker$) + END + + DEF FNstripcomment(text$, delim$) + LOCAL I%, D% + FOR I% = 1 TO LEN(delim$) + D% = INSTR(text$, MID$(delim$, I%, 1)) + IF D% text$ = LEFT$(text$, D%-1) + NEXT I% + WHILE ASC(text$) = 32 text$ = MID$(text$,2) : ENDWHILE + WHILE LEFT$(text$) = " " text$ = RIGHT$(text$) : ENDWHILE + = text$ diff --git a/Task/Strip-comments-from-a-string/C++/strip-comments-from-a-string.cpp b/Task/Strip-comments-from-a-string/C++/strip-comments-from-a-string.cpp new file mode 100644 index 0000000000..2197369608 --- /dev/null +++ b/Task/Strip-comments-from-a-string/C++/strip-comments-from-a-string.cpp @@ -0,0 +1,23 @@ +#include +#include + +std::string strip_white(const std::string& input) +{ + size_t b = input.find_first_not_of(' '); + if (b == std::string::npos) b = 0; + return input.substr(b, input.find_last_not_of(' ') + 1 - b); +} + +std::string strip_comments(const std::string& input, const std::string& delimiters) +{ + return strip_white(input.substr(0, input.find_first_of(delimiters))); +} + +int main( ) { + std::string input; + std::string delimiters("#;"); + while ( getline(std::cin, input) && !input.empty() ) { + std::cout << strip_comments(input, delimiters) << std::endl ; + } + return 0; +} diff --git a/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c b/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c new file mode 100644 index 0000000000..025ae111ba --- /dev/null +++ b/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c @@ -0,0 +1,26 @@ +#include + +int main() +{ + char ch, str[100]; + int i; + + do{ + printf("\nEnter the string :"); + fgets(str,100,stdin); + for(i=0;str[i]!=00;i++) + { + if(str[i]=='#'||str[i]==';') + { + str[i]=00; + break; + } + } + printf("\nThe modified string is : %s",str); + printf("\nDo you want to repeat (y/n): "); + scanf("%c",&ch); + fflush(stdin); + }while(ch=='y'||ch=='Y'); + + return 0; +} diff --git a/Task/Strip-comments-from-a-string/Clojure/strip-comments-from-a-string.clj b/Task/Strip-comments-from-a-string/Clojure/strip-comments-from-a-string.clj new file mode 100644 index 0000000000..99be9d9b80 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Clojure/strip-comments-from-a-string.clj @@ -0,0 +1,2 @@ +> (apply str (take-while #(not (#{\# \;} %)) "apples # comment")) +"apples " diff --git a/Task/Strip-comments-from-a-string/D/strip-comments-from-a-string.d b/Task/Strip-comments-from-a-string/D/strip-comments-from-a-string.d new file mode 100644 index 0000000000..e027e6c8da --- /dev/null +++ b/Task/Strip-comments-from-a-string/D/strip-comments-from-a-string.d @@ -0,0 +1,13 @@ +import std.stdio, std.regex; + +string remove1LineComment(in string s, in string pat=";#") { + const re = "([^" ~ pat ~ "]*)([" ~ pat ~ `])[^\n\r]*([\n\r]|$)`; + return s.replace(regex(re, "gm"), "$1$3"); +} + +void main() { + const s = "apples, pears # and bananas +apples, pears ; and bananas "; + + writeln(s, "\n====>\n", s.remove1LineComment()); +} diff --git a/Task/Strip-comments-from-a-string/DWScript/strip-comments-from-a-string.dwscript b/Task/Strip-comments-from-a-string/DWScript/strip-comments-from-a-string.dwscript new file mode 100644 index 0000000000..74d7d8aab9 --- /dev/null +++ b/Task/Strip-comments-from-a-string/DWScript/strip-comments-from-a-string.dwscript @@ -0,0 +1,10 @@ +function StripComments(s : String) : String; +begin + var p := FindDelimiter('#;', s); + if p>0 then + Result := Trim(Copy(s, 1, p-1)) + else Result := Trim(s); +end; + +PrintLn(StripComments('apples, pears # and bananas')); +PrintLn(StripComments('apples, pears ; and bananas')); diff --git a/Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.delphi b/Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.delphi new file mode 100644 index 0000000000..e26484d9db --- /dev/null +++ b/Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.delphi @@ -0,0 +1,18 @@ +program StripComments; + +{$APPTYPE CONSOLE} + +uses + SysUtils; + +function DoStripComments(const InString: string; const CommentMarker: Char): string; +begin + Result := Trim(Copy(InString,1,Pos(CommentMarker,InString)-1)); +end; + +begin + Writeln('apples, pears # and bananas --> ' + DoStripComments('apples, pears # and bananas','#')); + Writeln(''); + Writeln('apples, pears ; and bananas --> ' + DoStripComments('apples, pears ; and bananas',';')); + Readln; +end. diff --git a/Task/Strip-comments-from-a-string/Fantom/strip-comments-from-a-string.fantom b/Task/Strip-comments-from-a-string/Fantom/strip-comments-from-a-string.fantom new file mode 100644 index 0000000000..a1670fd628 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Fantom/strip-comments-from-a-string.fantom @@ -0,0 +1,19 @@ +class Main +{ + static Str removeComment (Str str) + { + regex := Regex <|(;|#)|> + matcher := regex.matcher (str) + if (matcher.find) + return str[0..0) then + str2 = str(1:i-1) + else + str2 = str + end if + + end function strip_comments + +!**************************************************** + end module string_routines +!**************************************************** + +!**************************************************** + program main +!**************************************************** +! Example use of strip_comments function +!**************************************************** + use string_routines, only: strip_comments + implicit none + + write(*,*) strip_comments('apples, pears # and bananas', '#') + write(*,*) strip_comments('apples, pears ; and bananas', ';') + +!**************************************************** + end program main +!**************************************************** diff --git a/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go new file mode 100644 index 0000000000..9b2ab7c5d9 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "strings" +) + +const commentChars = "#;" + +func stripComment(source string) string { + if cut := strings.IndexAny(source, commentChars); cut >= 0 { + return source[:cut] + } + return source +} + +func main() { + for _, s := range []string{ + "apples, pears # and bananas", + "apples, pears ; and bananas", + "no bananas", + } { + fmt.Printf("source: %q\n", s) + fmt.Printf("stripped: %q\n", stripComment(s)) + } +} diff --git a/Task/Strip-comments-from-a-string/Haskell/strip-comments-from-a-string.hs b/Task/Strip-comments-from-a-string/Haskell/strip-comments-from-a-string.hs new file mode 100644 index 0000000000..0713e448a5 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Haskell/strip-comments-from-a-string.hs @@ -0,0 +1,4 @@ +ms = ";#" + +main = getContents >>= + mapM_ (putStrLn . takeWhile (`notElem` ms)) . lines diff --git a/Task/Strip-comments-from-a-string/Icon/strip-comments-from-a-string.icon b/Task/Strip-comments-from-a-string/Icon/strip-comments-from-a-string.icon new file mode 100644 index 0000000000..77a2e2da27 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Icon/strip-comments-from-a-string.icon @@ -0,0 +1,12 @@ +# strip_comments: +# return part of string up to first character in 'markers', +# or else the whole string if no comment marker is present +procedure strip_comments (str, markers) + return str ? tab(upto(markers) | 0) +end + +procedure main () + write (strip_comments ("apples, pears and bananas", cset ("#;"))) + write (strip_comments ("apples, pears # and bananas", cset ("#;"))) + write (strip_comments ("apples, pears ; and bananas", cset ("#;"))) +end diff --git a/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf b/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf new file mode 100644 index 0000000000..21a019bc1f --- /dev/null +++ b/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf @@ -0,0 +1,11 @@ +Home is a room. + +When play begins: + strip comments from "apples, pears # and bananas"; + strip comments from "apples, pears ; and bananas"; + end the story. + +To strip comments from (T - indexed text): + say "[T] -> "; + replace the regular expression "<#;>.*$" in T with ""; + say "[T][line break]". diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j new file mode 100644 index 0000000000..76f3434c34 --- /dev/null +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-1.j @@ -0,0 +1 @@ +strip=: #~ *./\@:-.@e.&';#' diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j new file mode 100644 index 0000000000..79e3998b28 --- /dev/null +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-2.j @@ -0,0 +1 @@ +strip=: {.~ <./@i.&';#' diff --git a/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j new file mode 100644 index 0000000000..37e72a92f4 --- /dev/null +++ b/Task/Strip-comments-from-a-string/J/strip-comments-from-a-string-3.j @@ -0,0 +1,4 @@ + strip 'apples, pears # and bananas' +apples, pears + strip 'apples, pears ; and bananas' +apples, pears diff --git a/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java b/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java new file mode 100644 index 0000000000..3c3ea6e8c7 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java @@ -0,0 +1,23 @@ +import java.io.*; + +public class StripLineComments{ + public static void main( String[] args ){ + if( args.length < 1 ){ + System.out.println("Usage: java StripLineComments StringToProcess"); + } + else{ + String inputFile = args[0]; + String input = ""; + try{ + BufferedReader reader = new BufferedReader( new FileReader( inputFile ) ); + String line = ""; + while((line = reader.readLine()) != null){ + System.out.println( line.split("[#;]")[0] ); + } + } + catch( Exception e ){ + e.printStackTrace(); + } + } + } +} diff --git a/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-1.js b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-1.js new file mode 100644 index 0000000000..87b1ff5d31 --- /dev/null +++ b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-1.js @@ -0,0 +1,11 @@ +function stripComments(s) { + var re1 = /^\s+|\s+$/g; // Strip leading and trailing spaces + var re2 = /\s*[#;].+$/g; // Strip everything after # or ; to the end of the line, including preceding spaces + return s.replace(re1,'').replace(re2,''); +} + + +var s1 = 'apples, pears # and bananas'; +var s2 = 'apples, pears ; and bananas'; + +alert(stripComments(s1) + '\n' + stripComments(s2)); diff --git a/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-2.js b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-2.js new file mode 100644 index 0000000000..7bf64c19cc --- /dev/null +++ b/Task/Strip-comments-from-a-string/JavaScript/strip-comments-from-a-string-2.js @@ -0,0 +1,7 @@ +var stripComments = (function () { + var re1 = /^\s+|\s+$/g; + var re2 = /\s*[#;].+$/g; + return function (s) { + return s.replace(re1,'').replace(re2,''); + }; +}()); diff --git a/Task/Strip-comments-from-a-string/Liberty-BASIC/strip-comments-from-a-string.liberty b/Task/Strip-comments-from-a-string/Liberty-BASIC/strip-comments-from-a-string.liberty new file mode 100644 index 0000000000..6ae2f1f595 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Liberty-BASIC/strip-comments-from-a-string.liberty @@ -0,0 +1,16 @@ +string1$ = "apples, pears # and bananas" +string2$ = "pears;, " + chr$(34) + "apples ; " + chr$(34) + " an;d bananas" +commentMarker$ = "; #" +Print parse$(string2$, commentMarker$) +End + +Function parse$(string$, commentMarker$) + For i = 1 To Len(string$) + charIn$ = Mid$(string$, i, 1) + If charIn$ = Chr$(34) Then + inQuotes = Not(inQuotes) + End If + If Instr(commentMarker$, charIn$) And (inQuotes = 0) Then Exit For + next i + parse$ = Left$(string$, (i - 1)) +End Function diff --git a/Task/Strip-comments-from-a-string/Lua/strip-comments-from-a-string.lua b/Task/Strip-comments-from-a-string/Lua/strip-comments-from-a-string.lua new file mode 100644 index 0000000000..a59360e8e3 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Lua/strip-comments-from-a-string.lua @@ -0,0 +1,7 @@ +comment_symbols = ";#" + +s1 = "apples, pears # and bananas" +s2 = "apples, pears ; and bananas" + +print ( string.match( s1, "[^"..comment_symbols.."]+" ) ) +print ( string.match( s2, "[^"..comment_symbols.."]+" ) ) diff --git a/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m b/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m new file mode 100644 index 0000000000..c1de1a971e --- /dev/null +++ b/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m @@ -0,0 +1,8 @@ +function line = stripcomment(line) + e = min([find(line=='#',1),find(line==';',1)]); + if ~isempty(e) + e = e-1; + while isspace(line(e)) e = e - 1; end; + line = line(1:e); + end; +end; diff --git a/Task/Strip-comments-from-a-string/Mathematica/strip-comments-from-a-string.math b/Task/Strip-comments-from-a-string/Mathematica/strip-comments-from-a-string.math new file mode 100644 index 0000000000..263a8f8bb0 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Mathematica/strip-comments-from-a-string.math @@ -0,0 +1,4 @@ +a = "apples, pears # and bananas + apples, pears ; and bananas"; +b = StringReplace[a, RegularExpression["[ ]+[#;].+[\n]"] -> "\n"]; +StringReplace[b, RegularExpression["[ ]+[#;].+$"] -> ""] // FullForm diff --git a/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ocaml b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ocaml new file mode 100644 index 0000000000..55c1afbb1e --- /dev/null +++ b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ocaml @@ -0,0 +1,20 @@ +let strip_comments str = + let len = String.length str in + let rec aux print i = + if i >= len then () else + match str.[i] with + | '#' | ';' -> + aux false (succ i) + | '\n' -> + print_char '\n'; + aux true (succ i) + | c -> + if print then print_char c; + aux print (succ i) + in + aux true 0 + +let () = + strip_comments "apples, pears # and bananas\n"; + strip_comments "apples, pears ; and bananas\n"; +;; diff --git a/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ocaml b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ocaml new file mode 100644 index 0000000000..c67494e1bd --- /dev/null +++ b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ocaml @@ -0,0 +1,6 @@ +let strip_comments = + let print = ref true in + String.iter (function + | ';' | '#' -> print := false + | '\n' -> print_char '\n'; print := true + | c -> if !print then print_char c) diff --git a/Task/Strip-comments-from-a-string/PL-I/strip-comments-from-a-string.pli b/Task/Strip-comments-from-a-string/PL-I/strip-comments-from-a-string.pli new file mode 100644 index 0000000000..01dece26fe --- /dev/null +++ b/Task/Strip-comments-from-a-string/PL-I/strip-comments-from-a-string.pli @@ -0,0 +1,3 @@ +k = search(text, '#;'); +if k = 0 then put skip list (text); + else put skip list (substr(text, 1, k-1)); diff --git a/Task/Strip-comments-from-a-string/Perl-6/strip-comments-from-a-string.pl6 b/Task/Strip-comments-from-a-string/Perl-6/strip-comments-from-a-string.pl6 new file mode 100644 index 0000000000..6e041ea90b --- /dev/null +++ b/Task/Strip-comments-from-a-string/Perl-6/strip-comments-from-a-string.pl6 @@ -0,0 +1 @@ +$*IN.slurp.subst(/ \h* <[ # ; ]> \N* /, '', :g).print diff --git a/Task/Strip-comments-from-a-string/Perl/strip-comments-from-a-string.pl b/Task/Strip-comments-from-a-string/Perl/strip-comments-from-a-string.pl new file mode 100644 index 0000000000..0ce759a96b --- /dev/null +++ b/Task/Strip-comments-from-a-string/Perl/strip-comments-from-a-string.pl @@ -0,0 +1,7 @@ +while (<>) + { + s/[#;].*$//s; # remove comment + s/^\s+//; # remove leading whitespace + s/\s+$//; # remove trailing whitespace + print + } diff --git a/Task/Strip-comments-from-a-string/PicoLisp/strip-comments-from-a-string.l b/Task/Strip-comments-from-a-string/PicoLisp/strip-comments-from-a-string.l new file mode 100644 index 0000000000..81a56cbfb7 --- /dev/null +++ b/Task/Strip-comments-from-a-string/PicoLisp/strip-comments-from-a-string.l @@ -0,0 +1,2 @@ +(for Str '("apples, pears # and bananas" "apples, pears ; and bananas") + (prinl (car (split (chop Str) "#" ";"))) ) diff --git a/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-1.pro b/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-1.pro new file mode 100644 index 0000000000..bc0548e036 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-1.pro @@ -0,0 +1,11 @@ +stripcomment(A,B) :- stripcomment(A,B,a). +stripcomment([A|AL],[A|BL],a) :- \+ A=0';, \+ A=0'# , \+ A=10, \+ A=13 , stripcomment(AL,BL,a). +stripcomment([A|AL], BL ,a) :- ( A=0';; A=0'#), \+ A=10, \+ A=13 , stripcomment(AL,BL,b). +stripcomment([A|AL], BL ,b) :- \+ A=10, \+ A=13 , stripcomment(AL,BL,b). +stripcomment([A|AL],[A|BL],_M):- ( A=10; A=13), stripcomment(AL,BL,a). +stripcomment([],[],_M). +start :- +In = "apples, pears ; and bananas +apples, pears # and bananas", + stripcomment(In,Out), + format("~s~n",[Out]). diff --git a/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-2.pro b/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-2.pro new file mode 100644 index 0000000000..3056953f94 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Prolog/strip-comments-from-a-string-2.pro @@ -0,0 +1 @@ +strip_1comment(A,D) :- ((S1=0'#;S1=0';),append(B,[S1|C],A)), \+ ((S2=0'#;S2=0';),append(_X,[S2|_Y],B)) -> B=D; A=D. diff --git a/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-1.purebasic b/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-1.purebasic new file mode 100644 index 0000000000..da56842080 --- /dev/null +++ b/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-1.purebasic @@ -0,0 +1,17 @@ +Procedure.s Strip_comments(Str$) + Protected result$=Str$, l, l1, l2 + l1 =FindString(Str$,"#",1) + l2 =FindString(Str$,";",1) + ; + ; See if any comment sign was found, prioritizing '#' + If l1 + l=l1 + ElseIf l2 + l=l2 + EndIf + l-1 + If l>0 + result$=Left(Str$,l) + EndIf + ProcedureReturn result$ +EndProcedure diff --git a/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-2.purebasic b/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-2.purebasic new file mode 100644 index 0000000000..666d5710db --- /dev/null +++ b/Task/Strip-comments-from-a-string/PureBasic/strip-comments-from-a-string-2.purebasic @@ -0,0 +1,5 @@ +#instring1 ="apples, pears # and bananas" +#instring2 ="apples, pears ; and bananas" + +PrintN(Strip_comments(#instring1)) +PrintN(Strip_comments(#instring2)) diff --git a/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-1.py b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-1.py new file mode 100644 index 0000000000..e0789fb567 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-1.py @@ -0,0 +1,7 @@ +>>> marker, line = '#', 'apples, pears # and bananas' +>>> line[:line.index(marker)].strip() +'apples, pears' +>>> +>>> marker, line = ';', ' apples, pears ; and bananas' +>>> line[:line.index(marker)].strip() +'apples, pears' diff --git a/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-2.py b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-2.py new file mode 100644 index 0000000000..353065d215 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-2.py @@ -0,0 +1,8 @@ +def remove_comments(line, sep): + for s in sep: + line = line.split(s)[0] + return line.strip() + +# test +print remove_comments('apples ; pears # and bananas', ';#') +print remove_comments('apples ; pears # and bananas', '!') diff --git a/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-1.r b/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-1.r new file mode 100644 index 0000000000..8593023bf1 --- /dev/null +++ b/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-1.r @@ -0,0 +1,5 @@ +strip_comments <- function(str) +{ + if(!require(stringr)) stop("you need to install the stringr package") + str_trim(str_split_fixed(str, "#|;", 2)[, 1]) +} diff --git a/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-2.r b/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-2.r new file mode 100644 index 0000000000..abb149536e --- /dev/null +++ b/Task/Strip-comments-from-a-string/R/strip-comments-from-a-string-2.r @@ -0,0 +1,7 @@ +x <-c( + "apples, pears # and bananas", # the requested hash test + "apples, pears ; and bananas", # the requested semicolon test + "apples, pears and bananas", # without a comment + " apples, pears # and bananas" # with preceding spaces +) +strip_comments(x) diff --git a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx new file mode 100644 index 0000000000..301db52943 --- /dev/null +++ b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx @@ -0,0 +1,41 @@ +/*REXX program strips a string delinated by a hash (#) or semicolon (;).*/ +old1=' apples, pears # and bananas' ; say ' old ───►'old1"◄───" +new1=stripCom1(old1) ; say '1st version new ───►'new1"◄───" +new2=stripCom2(old1) ; say '2nd version new ───►'new2"◄───" +new3=stripCom3(old1) ; say '3rd version new ───►'new3"◄───" +new4=stripCom3(old1) ; say '4th version new ───►'new4"◄───" + say copies('═',55) +old2=' apples, pears ; and bananas' ; say ' old ───►'old2"◄───" +new1=stripCom1(old2) ; say '1st version new ───►'new1"◄───" +new2=stripCom2(old2) ; say '2nd version new ───►'new2"◄───" +new3=stripCom3(old2) ; say '3rd version new ───►'new3"◄───" +new4=stripCom3(old2) ; say '4th version new ───►'new4"◄───" +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────STRIPCOM1 subroutine────────────────*/ +stripCom1: procedure; parse arg x /*get the argument (string). */ +x=translate(x,'#',";") /*translate semicolons to hash. */ +parse var x x '#' /*parse string, ending in hash. */ +return strip(x) /*return striped shortened string*/ +/*──────────────────────────────────STRIPCOM2 subroutine────────────────*/ +stripCom2: procedure; parse arg x /*get the argument (string). */ +d='#;' /*delimiter list to be used. */ +d1=left(d,1) /*get the 1st character in delim.*/ +x=translate(x,copies(d1,length(d)),d) /*trans all delims ──► 1st delim.*/ +parse var x x (d1) /*parse string, ending in hash. */ +return strip(x) /*return striped shortened string*/ +/*──────────────────────────────────STRIPCOM3 subroutine────────────────*/ +stripCom3: procedure; parse arg x /*get the argument (string). */ +d=';#' /*delimiter list to be used. */ + do j=1 for length(d) /*process each delimiter singly. */ + _=substr(d,j,1) /*use one delimiter at a time. */ + parse var x x (_) /*parse X string for each delim. */ + end /*j*/ +return strip(x) /*return striped shortened string*/ +/*──────────────────────────────────STRIPCOM4 subroutine────────────────*/ +stripCom4: procedure; parse arg x /*get the argument (string). */ +d=';#' /*delimiter list to be used. */ + do k=1 for length(d) /*process each delimiter singly. */ + p=pos(substr(d,k,1),x) /*see if a delimiter is in X. */ + if p\==0 then x=left(x,p-1) /*shorten the X string.*/ + end /*k*/ +return strip(x) /*return striped shortened string*/ diff --git a/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb b/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb new file mode 100644 index 0000000000..5f30d04365 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Ruby/strip-comments-from-a-string.rb @@ -0,0 +1,10 @@ +class String + def strip_comment( markers = ['#',';'] ) + re = Regexp.union( markers ) # construct a regular expression which will match any of the markers + self[0, self =~ re] # slice the string where the regular expression matches, and return it. + end +end + +puts 'apples, pears # and bananas'.strip_comment +str = 'apples, pears ; and bananas' +puts str.strip_comment diff --git a/Task/Strip-comments-from-a-string/Scala/strip-comments-from-a-string.scala b/Task/Strip-comments-from-a-string/Scala/strip-comments-from-a-string.scala new file mode 100644 index 0000000000..efd2430637 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Scala/strip-comments-from-a-string.scala @@ -0,0 +1,23 @@ +object StripComments { + def stripComments1(s:String, markers:String =";#")=s takeWhile (!markers.contains(_)) trim + + // using regex and pattern matching + def stripComments2(s:String, markers:String =";#")={ + val R=("(.*?)[" + markers + "].*").r + (s match { + case R(line) => line + case _ => s + }) trim + } + + def print(s:String)={ + println("'"+s+"' =>") + println(" '"+stripComments1(s)+"'") + println(" '"+stripComments2(s)+"'") + } + + def main(args: Array[String]): Unit = { + print("apples, pears # and bananas") + print("apples, pears ; and bananas") + } +} diff --git a/Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.ss b/Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.ss new file mode 100644 index 0000000000..5894d99b2a --- /dev/null +++ b/Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.ss @@ -0,0 +1,8 @@ +(use-modules (ice-9 regex)) + +(define (strip-comments s) + (regexp-substitute #f + (string-match "[ \t\r\n\v\f]*[#;].*" s) 'pre "" 'post)) + +(display (strip-comments "apples, pears # and bananas"))(newline) +(display (strip-comments "apples, pears ; and bananas"))(newline) diff --git a/Task/Strip-comments-from-a-string/Seed7/strip-comments-from-a-string.seed7 b/Task/Strip-comments-from-a-string/Seed7/strip-comments-from-a-string.seed7 new file mode 100644 index 0000000000..86d6a3333c --- /dev/null +++ b/Task/Strip-comments-from-a-string/Seed7/strip-comments-from-a-string.seed7 @@ -0,0 +1,31 @@ +$ include "seed7_05.s7i"; + +const func string: stripComment (in string: line) is func + result + var string: lineWithoutComment is ""; + local + var integer: lineEnd is 0; + var integer: pos is 0; + begin + lineEnd := length(line); + for pos range 1 to length(line) do + if line[pos] in {'#', ';'} then + lineEnd := pred(pos); + pos := length(line); + end if; + end for; + lineWithoutComment := line[.. lineEnd]; + end func; + +const proc: main is func + local + var string: stri is "apples, pears # and bananas\n\ + \apples, pears ; and bananas"; + var string: line is "" + begin + writeln(stri); + writeln("====>"); + for line range split(stri, '\n') do + writeln(stripComment(line)); + end for; + end func; diff --git a/Task/Strip-comments-from-a-string/TUSCRIPT/strip-comments-from-a-string.tuscript b/Task/Strip-comments-from-a-string/TUSCRIPT/strip-comments-from-a-string.tuscript new file mode 100644 index 0000000000..2f139a61b4 --- /dev/null +++ b/Task/Strip-comments-from-a-string/TUSCRIPT/strip-comments-from-a-string.tuscript @@ -0,0 +1,11 @@ +$$ MODE TUSCRIPT +strngcomment=* +DATA apples, pears # and bananas +DATA apples, pears ; and bananas + +BUILD S_TABLE comment_char="|#|;|" + +LOOP s=strngcomment +x=SPLIT (s,comment_char,string,comment) +PRINT string +ENDLOOP diff --git a/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-1.tcl b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-1.tcl new file mode 100644 index 0000000000..8d1efbe27a --- /dev/null +++ b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-1.tcl @@ -0,0 +1,6 @@ +proc stripLineComments {inputString {commentChars ";#"}} { + # Switch the RE engine into line-respecting mode instead of the default whole-string mode + regsub -all -line "\[$commentChars\].*$" $inputString "" commentStripped + # Now strip the whitespace + regsub -all -line {^[ \t\r]*(.*\S)?[ \t\r]*$} $commentStripped {\1} +} diff --git a/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-2.tcl b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-2.tcl new file mode 100644 index 0000000000..1eb912a2d6 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-2.tcl @@ -0,0 +1,5 @@ +# Multi-line string constant +set input "apples, pears # and bananas +apples, pears ; and bananas" +# Do the stripping +puts [stripLineComments $input] diff --git a/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-3.tcl b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-3.tcl new file mode 100644 index 0000000000..265df19643 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Tcl/strip-comments-from-a-string-3.tcl @@ -0,0 +1,8 @@ +proc stripLineComments {inputString {commentChars ";#"}} { + # Convert the character set into a transformation + foreach c [split $commentChars ""] {lappend map $c "\uFFFF"}; # *very* rare character! + # Apply transformation and then use a simpler constant RE to strip + regsub -all -line {\uFFFF.*$} [string map $map $inputString] "" commentStripped + # Now strip the whitespace + regsub -all -line {^[ \t\r]*(.*\S)?[ \t\r]*$} $commentStripped {\1} +} diff --git a/Task/Strip-comments-from-a-string/UNIX-Shell/strip-comments-from-a-string.sh b/Task/Strip-comments-from-a-string/UNIX-Shell/strip-comments-from-a-string.sh new file mode 100644 index 0000000000..f8a4123d46 --- /dev/null +++ b/Task/Strip-comments-from-a-string/UNIX-Shell/strip-comments-from-a-string.sh @@ -0,0 +1,7 @@ +bash$ a='apples, pears ; and bananas' +bash$ b='apples, pears # and bananas' +bash$ echo ${a%%;*} +apples, pears +bash$ echo ${b%%#*} +apples, pears +bash$ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/0DESCRIPTION b/Task/Strip-control-codes-and-extended-characters-from-a-string/0DESCRIPTION new file mode 100644 index 0000000000..fc55d0291e --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/0DESCRIPTION @@ -0,0 +1,8 @@ +The task is to strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results: + +* a string with control codes stripped (but extended characters not stripped) +* a string with control codes and extended characters stripped + +In ASCII, the control codes have decimal codes 0 through to 31 and 127 and greater than 126. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ascii table. + +On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.ada b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.ada new file mode 100644 index 0000000000..990b5b0f1a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.ada @@ -0,0 +1,35 @@ +with Ada.Text_IO; + +procedure Strip_ASCII is + + Full: String := 'a' & Character'Val(11) & 'b' & Character'Val(166) & + 'c' & Character'Val(127) & Character'Val(203) & + Character'Val(202) & "de"; + -- 5 ordinary characters ('a' .. 'e') + -- 2 control characters (11, 127); note that 11 is the "vertical tab" + -- 3 extended characters (166, 203, 202) + + function Filter(S: String; + From: Character := ' '; + To: Character := Character'Val(126); + Above: Character := Character'Val(127)) return String is + begin + if S'Length = 0 then + return ""; + elsif (S(S'First) >= From and then S(S'First) <= To) or else S(S'First) > Above then + return S(S'First) & Filter(S(S'First+1 .. S'Last), From, To, Above); + else + return Filter(S(S'First+1 .. S'Last), From, To, Above); + end if; + end Filter; + + procedure Put_Line(Text, S: String) is + begin + Ada.Text_IO.Put_Line(Text & " """ & S & """, Length:" & Integer'Image(S'Length)); + end Put_Line; + +begin + Put_Line("The full string :", Full); + Put_Line("No Control Chars:", Filter(Full)); -- default values for From, To, and Above + Put_Line("Neither_Extended:", Filter(Full, Above => Character'Last)); -- defaults for From and To +end Strip_ASCII; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/AutoHotkey/strip-control-codes-and-extended-characters-from-a-string.ahk b/Task/Strip-control-codes-and-extended-characters-from-a-string/AutoHotkey/strip-control-codes-and-extended-characters-from-a-string.ahk new file mode 100644 index 0000000000..4fe62e38bb --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/AutoHotkey/strip-control-codes-and-extended-characters-from-a-string.ahk @@ -0,0 +1,7 @@ +Stripped(x){ + Loop Parse, x + if Asc(A_LoopField) > 31 and Asc(A_LoopField) < 128 + r .= A_LoopField + return r +} +MsgBox % stripped("`ba" Chr(00) "b`n`rc`fd" Chr(0xc3)) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/BASIC/strip-control-codes-and-extended-characters-from-a-string.basic b/Task/Strip-control-codes-and-extended-characters-from-a-string/BASIC/strip-control-codes-and-extended-characters-from-a-string.basic new file mode 100644 index 0000000000..c9f27f49ff --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/BASIC/strip-control-codes-and-extended-characters-from-a-string.basic @@ -0,0 +1,38 @@ +DECLARE FUNCTION strip$ (what AS STRING) +DECLARE FUNCTION strip2$ (what AS STRING) + +DIM x AS STRING, y AS STRING, z AS STRING + +' tab c+cedilla eof +x = CHR$(9) + "Fran" + CHR$(135) + "ais" + CHR$(26) +y = strip(x) +z = strip2(x) + +PRINT "x:"; x +PRINT "y:"; y +PRINT "z:"; z + +FUNCTION strip$ (what AS STRING) + DIM outP AS STRING, L0 AS INTEGER, tmp AS STRING + FOR L0 = 1 TO LEN(what) + tmp = MID$(what, L0, 1) + SELECT CASE ASC(tmp) + CASE 32 TO 126 + outP = outP + tmp + END SELECT + NEXT + strip$ = outP +END FUNCTION + +FUNCTION strip2$ (what AS STRING) + DIM outP AS STRING, L1 AS INTEGER, tmp AS STRING + FOR L1 = 1 TO LEN(what) + tmp = MID$(what, L1, 1) + SELECT CASE ASC(tmp) + 'normal accented various greek, math, etc. + CASE 32 TO 126, 128 TO 168, 171 TO 175, 224 TO 253 + outP = outP + tmp + END SELECT + NEXT + strip2$ = outP +END FUNCTION diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/BBC-BASIC/strip-control-codes-and-extended-characters-from-a-string.bbc b/Task/Strip-control-codes-and-extended-characters-from-a-string/BBC-BASIC/strip-control-codes-and-extended-characters-from-a-string.bbc new file mode 100644 index 0000000000..5266aa4184 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/BBC-BASIC/strip-control-codes-and-extended-characters-from-a-string.bbc @@ -0,0 +1,27 @@ + test$ = CHR$(9) + "Fran" + CHR$(231) + "ais." + CHR$(127) + PRINT "Original ISO-8859-1 string: " test$ " (length " ; LEN(test$) ")" + test$ = FNstripcontrol(test$) + PRINT "Control characters stripped: " test$ " (length " ; LEN(test$) ")" + test$ = FNstripextended(test$) + PRINT "Control & extended stripped: " test$ " (length " ; LEN(test$) ")" + END + + DEF FNstripcontrol(A$) : REM CHR$(127) is a 'control' code + LOCAL I% + WHILE I%127 THEN + A$ = LEFT$(A$,I%-1) + MID$(A$,I%+1) + ENDIF + ENDWHILE + = A$ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/C++/strip-control-codes-and-extended-characters-from-a-string.cpp b/Task/Strip-control-codes-and-extended-characters-from-a-string/C++/strip-control-codes-and-extended-characters-from-a-string.cpp new file mode 100644 index 0000000000..cfb93ad538 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/C++/strip-control-codes-and-extended-characters-from-a-string.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace boost::lambda ; + +struct MyRandomizer { + char operator( )( ) { + return static_cast( rand( ) % 256 ) ; + } +} ; + +std::string deleteControls ( std::string startstring ) { + std::string noControls( " " ) ;//creating space for + //the standard algorithm remove_copy_if + std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noControls.begin( ) , + ll_static_cast( _1 ) < 32 && ll_static_cast( _1 ) == 127 ) ; + return noControls ; +} + +std::string deleteExtended( std::string startstring ) { + std::string noExtended ( " " ) ;//same as above + std::remove_copy_if( startstring.begin( ) , startstring.end( ) , noExtended.begin( ) , + ll_static_cast( _1 ) > 127 || ll_static_cast( _1 ) < 32 ) ; + return noExtended ; +} + +int main( ) { + std::string my_extended_string ; + for ( int i = 0 ; i < 40 ; i++ ) //we want the extended string to be 40 characters long + my_extended_string.append( " " ) ; + srand( time( 0 ) ) ; + std::generate_n( my_extended_string.begin( ) , 40 , MyRandomizer( ) ) ; + std::string no_controls( deleteControls( my_extended_string ) ) ; + std::string no_extended ( deleteExtended( my_extended_string ) ) ; + std::cout << "string with all characters: " << my_extended_string << std::endl ; + std::cout << "string without control characters: " << no_controls << std::endl ; + std::cout << "string without extended characters: " << no_extended << std::endl ; + return 0 ; +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-1.c b/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-1.c new file mode 100644 index 0000000000..8f2e186b8b --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-1.c @@ -0,0 +1,64 @@ +#include +#include + +#define IS_CTRL (1 << 0) +#define IS_EXT (1 << 1) +#define IS_ALPHA (1 << 2) +#define IS_DIGIT (1 << 3) /* not used, just give you an idea */ + +unsigned int char_tbl[256] = {0}; + +/* could use ctypes, but then they pretty much do the same thing */ +void init_table() +{ + int i; + + for (i = 0; i < 32; i++) char_tbl[i] |= IS_CTRL; + char_tbl[127] |= IS_CTRL; + + for (i = 'A'; i <= 'Z'; i++) { + char_tbl[i] |= IS_ALPHA; + char_tbl[i + 0x20] |= IS_ALPHA; /* lower case */ + } + + for (i = 128; i < 256; i++) char_tbl[i] |= IS_EXT; +} + +/* depends on what "stripped" means; we do it in place. + * "what" is a combination of the IS_* macros, meaning strip if + * a char IS_ any of them + */ +void strip(char * str, int what) +{ + unsigned char *ptr, *s = (void*)str; + ptr = s; + while (*s != '\0') { + if ((char_tbl[(int)*s] & what) == 0) + *(ptr++) = *s; + s++; + } + *ptr = '\0'; +} + +int main() +{ + char a[256]; + int i; + + init_table(); + + /* populate string with one of each char */ + for (i = 1; i < 255; i++) a[i - 1] = i; a[255] = '\0'; + strip(a, IS_CTRL); + printf("%s\n", a); + + for (i = 1; i < 255; i++) a[i - 1] = i; a[255] = '\0'; + strip(a, IS_CTRL | IS_EXT); + printf("%s\n", a); + + for (i = 1; i < 255; i++) a[i - 1] = i; a[255] = '\0'; + strip(a, IS_CTRL | IS_EXT | IS_ALPHA); + printf("%s\n", a); + + return 0; +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-2.c b/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-2.c new file mode 100644 index 0000000000..351b60da3c --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-2.c @@ -0,0 +1,3 @@ + !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ + !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/D/strip-control-codes-and-extended-characters-from-a-string.d b/Task/Strip-control-codes-and-extended-characters-from-a-string/D/strip-control-codes-and-extended-characters-from-a-string.d new file mode 100644 index 0000000000..1adcb64839 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/D/strip-control-codes-and-extended-characters-from-a-string.d @@ -0,0 +1,19 @@ +import std.traits; + +S stripChars(S)(S s, bool function(dchar) pure nothrow mustStrip) + pure nothrow if (isSomeString!S) { + S result; + foreach (c; s) { + if (!mustStrip(c)) + result ~= c; + } + return result; +} + +void main() { + import std.stdio, std.uni; + auto s = "\u0000\u000A abc\u00E9def\u007F"; + writeln(s.stripChars( &isControl )); + writeln(s.stripChars( c => isControl(c) || c == '\u007F' )); + writeln(s.stripChars( c => isControl(c) || c >= '\u007F' )); +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Forth/strip-control-codes-and-extended-characters-from-a-string.fth b/Task/Strip-control-codes-and-extended-characters-from-a-string/Forth/strip-control-codes-and-extended-characters-from-a-string.fth new file mode 100644 index 0000000000..c6368910b0 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Forth/strip-control-codes-and-extended-characters-from-a-string.fth @@ -0,0 +1,8 @@ +: strip ( buf len -- buf len' ) \ repacks buffer, so len' <= len + over + over swap over ( buf dst limit src ) + do + i c@ 32 127 within if + i c@ over c! char+ + then + loop + over - ; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Fortran/strip-control-codes-and-extended-characters-from-a-string.f b/Task/Strip-control-codes-and-extended-characters-from-a-string/Fortran/strip-control-codes-and-extended-characters-from-a-string.f new file mode 100644 index 0000000000..99e397afbc --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Fortran/strip-control-codes-and-extended-characters-from-a-string.f @@ -0,0 +1,54 @@ +module stripcharacters +implicit none + +contains + + pure logical function not_control(ch) + character, intent(in) :: ch + not_control = iachar(ch) >= 32 .and. iachar(ch) /= 127 + end function not_control + + pure logical function not_extended(ch) + character, intent(in) :: ch + not_extended = iachar(ch) >= 32 .and. iachar(ch) < 127 + end function not_extended + + pure function strip(string,accept) result(str) + character(len=*), intent(in) :: string + character(len=len(string)) :: str + interface + pure logical function accept(ch) + character, intent(in) :: ch + end function except + end interface + integer :: i,n + str = repeat(' ',len(string)) + n = 0 + do i=1,len(string) + if ( accept(string(i:i)) ) then + n = n+1 + str(n:n) = string(i:i) + end if + end do + end function strip + +end module stripcharacters + + +program test + use stripcharacters + + character(len=256) :: string, str + integer :: ascii(256), i + forall (i=0:255) ascii(i) = i + forall (i=1:len(string)) string(i:i) = achar(ascii(i)) + write (*,*) string + + write (*,*) 'Control characters deleted:' + str = strip(string,not_control) + write (*,*) str + + forall (i=1:len(string)) string(i:i) = achar(ascii(i)) + write (*,*) 'Extended characters deleted:' + write (*,*) strip(string,not_extended) +end program test diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go b/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go new file mode 100644 index 0000000000..3abfa3ca63 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go @@ -0,0 +1,69 @@ +package main + +import ( + "fmt" + "strings" +) + +// two byte-oriented functions identical except for operator comparing c to 127. +func stripCtlFromBytes(str string) string { + b := make([]byte, len(str)) + var bl int + for i := 0; i < len(str); i++ { + c := str[i] + if c >= 32 && c != 127 { + b[bl] = c + bl++ + } + } + return string(b[:bl]) +} + +func stripCtlAndExtFromBytes(str string) string { + b := make([]byte, len(str)) + var bl int + for i := 0; i < len(str); i++ { + c := str[i] + if c >= 32 && c < 127 { + b[bl] = c + bl++ + } + } + return string(b[:bl]) +} + +// two UTF-8 functions identical except for operator comparing c to 127 +func stripCtlFromUTF8(str string) string { + return strings.Map(func(r rune) rune { + if r >= 32 && r != 127 { + return r + } + return -1 + }, str) +} + +func stripCtlAndExtFromUTF8(str string) string { + return strings.Map(func(r rune) rune { + if r >= 32 && r < 127 { + return r + } + return -1 + }, str) +} + +const src = "déjà vu" + // precomposed unicode + "\n\000\037 \041\176\177\200\377\n" + // various boundary cases + "as⃝df̅" // unicode combining characters + +func main() { + fmt.Println("source text:") + fmt.Println(src, "\n") + fmt.Println("as bytes, stripped of control codes:") + fmt.Println(stripCtlFromBytes(src), "\n") + fmt.Println("as bytes, stripped of control codes and extended characters:") + fmt.Println(stripCtlAndExtFromBytes(src), "\n") + fmt.Println("as UTF-8, stripped of control codes:") + fmt.Println(stripCtlFromUTF8(src), "\n") + fmt.Println("as UTF-8, stripped of control codes and extended characters:") + fmt.Println(stripCtlAndExtFromUTF8(src)) +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs b/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs new file mode 100644 index 0000000000..b3940dd955 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Haskell/strip-control-codes-and-extended-characters-from-a-string.hs @@ -0,0 +1,3 @@ +import Data.Char + +strip = filter (\x -> ord x > 32 && ord x < 126) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-1.icon b/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-1.icon new file mode 100644 index 0000000000..a2aa4ecb0d --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-1.icon @@ -0,0 +1,4 @@ +procedure main(A) +write(image(deletec(&ascii,&ascii--(&ascii)[33:127]))) +end +link strings diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-2.icon b/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-2.icon new file mode 100644 index 0000000000..7980fe1ff9 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Icon/strip-control-codes-and-extended-characters-from-a-string-2.icon @@ -0,0 +1,7 @@ +procedure deletec(s, c) #: delete characters + result := "" + s ? { + while result ||:= tab(upto(c)) do tab(many(c)) + return result ||:= tab(0) + } +end diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-1.j b/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-1.j new file mode 100644 index 0000000000..ec0aab9811 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-1.j @@ -0,0 +1,2 @@ +stripControlCodes=: -.&(DEL,32{.a.) +stripControlExtCodes=: ([ -. -.)&(32}.127{.a.) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-2.j b/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-2.j new file mode 100644 index 0000000000..31e272431a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/J/strip-control-codes-and-extended-characters-from-a-string-2.j @@ -0,0 +1,15 @@ + mystring=: a. {~ ?~256 NB. ascii chars 0-255 in random order + #mystring NB. length of string +256 + #stripControlCodes mystring NB. length of string without control codes +223 + #stripControlExtCodes mystring NB. length of string without control codes or extended chars +95 + #myunicodestring=: u: ?~1000 NB. unicode characters 0-999 in random order +1000 + #stripControlCodes myunicodestring +967 + #stripControlExtCodes myunicodestring +95 + stripControlExtCodes myunicodestring +k}w:]U3xEh9"GZdr/#^B.Sn%\uFOo[(`t2-J6*IA=Vf&N;lQ8,${XLz5?D0~s)'Y7Kq|ip41ejPy diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Liberty-BASIC/strip-control-codes-and-extended-characters-from-a-string.liberty b/Task/Strip-control-codes-and-extended-characters-from-a-string/Liberty-BASIC/strip-control-codes-and-extended-characters-from-a-string.liberty new file mode 100644 index 0000000000..42412ba9fa --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Liberty-BASIC/strip-control-codes-and-extended-characters-from-a-string.liberty @@ -0,0 +1,37 @@ + all$ ="" + for i =0 to 255 + all$ =all$ +chr$( i) + next i + + print "Original string of bytes. ( chr$( 10) causes a CRLF.)" + print all$ + print + + lessControl$ =controlStripped$( all$) + print "With control codes stripped out." + print lessControl$ + print + + lessExtendedAndControl$ =extendedStripped$( lessControl$) + print "With extended codes stripped out too." + print lessExtendedAndControl$ + + end + + function controlStripped$( i$) + r$ ="" + for j =1 to len( i$) + ch$ =mid$( i$, j, 1) + if asc( ch$) >=32 then r$ =r$ +ch$ + next j + controlStripped$ =r$ + end function + + function extendedStripped$( i$) + r$ ="" + for j =1 to len( i$) + ch$ =mid$( i$, j, 1) + if asc( ch$) <=128 then r$ =r$ +ch$ + next j + extendedStripped$ =r$ + end function diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Lua/strip-control-codes-and-extended-characters-from-a-string.lua b/Task/Strip-control-codes-and-extended-characters-from-a-string/Lua/strip-control-codes-and-extended-characters-from-a-string.lua new file mode 100644 index 0000000000..13dc361c19 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Lua/strip-control-codes-and-extended-characters-from-a-string.lua @@ -0,0 +1,25 @@ +function Strip_Control_Codes( str ) + local s = "" + for i in str:gmatch( "%C+" ) do + s = s .. i + end + return s +end + +function Strip_Control_and_Extended_Codes( str ) + local s = "" + for i = 1, str:len() do + if str:byte(i) >= 32 and str:byte(i) <= 126 then + s = s .. str:sub(i,i) + end + end + return s +end + +q = "" +for i = 0, 255 do + q = q .. string.char(i) +end + +print( Strip_Control_Codes(q) ) +print( Strip_Control_and_Extended_Codes(q) ) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/MATLAB/strip-control-codes-and-extended-characters-from-a-string.m b/Task/Strip-control-codes-and-extended-characters-from-a-string/MATLAB/strip-control-codes-and-extended-characters-from-a-string.m new file mode 100644 index 0000000000..a4f93c8590 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/MATLAB/strip-control-codes-and-extended-characters-from-a-string.m @@ -0,0 +1,3 @@ + function str = stripped(str) + str = str(31 127 + +let strip f str = + let len = String.length str in + let res = String.create len in + let rec aux i j = + if i >= len then String.sub res 0 j else + if f str.[i] + then aux (succ i) j + else begin + res.[j] <- str.[i]; + aux (succ i) (succ j) + end + in + aux 0 0 + +let () = + let len = 32 in + let s = String.create len in + Random.self_init(); + for i = 0 to pred len do + s.[i] <- char_of_int (Random.int 256) + done; + print_endline (strip is_control_code s); + print_endline (strip (fun c -> (is_control_code c) || (is_extended_char c)) s); +;; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PL-I/strip-control-codes-and-extended-characters-from-a-string.pli b/Task/Strip-control-codes-and-extended-characters-from-a-string/PL-I/strip-control-codes-and-extended-characters-from-a-string.pli new file mode 100644 index 0000000000..b8b5c0ca18 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PL-I/strip-control-codes-and-extended-characters-from-a-string.pli @@ -0,0 +1,65 @@ +stripper: proc options (main); + declare s character (100) varying; + declare i fixed binary; + + s = 'the quick brown fox jumped'; + /* A loop to replace blanks with control characters */ + do i = 1 to length(s); + if substr(s, i, 1) = ' ' then + substr(s, i, 1) = '01'x; + end; + put skip list (s); + + call stripcc (s); + put skip list (s); + + s = 'now is the time for all good men'; + /* A loop to replace blanks with control characters */ + do i = 1 to length(s); + if substr(s, i, 1) = ' ' then + substr(s, i, 1) = 'A1'x; + end; + put skip list (s); + + call stripex (s); + put skip list (s); + +/* Strip control codes. */ +stripcc: procedure (s); + declare s character (*) varying; + declare w character (length(s)); + declare c character (1); + declare (i, j) fixed binary; + + j = 0; + do i = 1 to length (s); + c = substr(s, i, 1); + if unspec(c) >= '00100000'b | unspec(c) = '01111111'b then + do; + j = j + 1; + substr(w, j, 1) = c; + end; + end; + s = substr(w, 1, j); +end stripcc; + +/* Strips control codes and extended characters. */ +stripex: procedure (s); + declare s character (*) varying; + declare w character (length(s)); + declare c character (1); + declare (i, j) fixed binary; + + j = 0; + do i = 1 to length (s); + c = substr(s, i, 1); + if unspec(c) >= '00100000'b & unspec(c) < '01111111'b then + do; + j = j + 1; + substr(w, j, 1) = c; + end; + end; + s = substr(w, 1, j); +end stripex; + +end stripper; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Pascal/strip-control-codes-and-extended-characters-from-a-string.pascal b/Task/Strip-control-codes-and-extended-characters-from-a-string/Pascal/strip-control-codes-and-extended-characters-from-a-string.pascal new file mode 100644 index 0000000000..bc33a78fe8 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Pascal/strip-control-codes-and-extended-characters-from-a-string.pascal @@ -0,0 +1,26 @@ +program StripCharacters(output); + +function Strip (s: string; control, extended: boolean): string; + var + index: integer; + begin + Strip := ''; + for index:= 1 to length(s) do + if not ((control and (ord(s[index]) <= 32)) or (extended and (ord(s[index]) > 127))) then + Strip := Strip + s[index]; + end; + +var + test: string; + i: integer; + +begin + setlength(test, 40); + randomize; + for i := 1 to length(test) do + test[i] := char(1 + random(255)); + writeln ('Original: ', test); + writeln ('No CNTL: ', Strip(test, true, false)); + writeln ('No extnd: ', Strip(test, false, true)); + writeln ('ASCII: ', Strip(test, true, true)); +end. diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl-6/strip-control-codes-and-extended-characters-from-a-string.pl6 b/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl-6/strip-control-codes-and-extended-characters-from-a-string.pl6 new file mode 100644 index 0000000000..cdb9289fa2 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl-6/strip-control-codes-and-extended-characters-from-a-string.pl6 @@ -0,0 +1,5 @@ +my $str = (0..400).roll(80)».chr.join; + +say $str; +say $str.subst(/<[ ^@..^_ ]>/, '', :g); +say $str.subst(/<-[ \ ..~ ]>/, '', :g); diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl/strip-control-codes-and-extended-characters-from-a-string.pl b/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl/strip-control-codes-and-extended-characters-from-a-string.pl new file mode 100644 index 0000000000..113cb9f646 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Perl/strip-control-codes-and-extended-characters-from-a-string.pl @@ -0,0 +1,19 @@ +#!/usr/bin/perl -w +use strict ; + +my @letters ; +my @nocontrols ; +my @noextended ; +for ( 1..40 ) { + push @letters , int( rand( 256 ) ) ; +} +print "before sanitation : " ; +print join( '' , map { chr( $_ ) } @letters ) ; +print "\n" ; +@nocontrols = grep { $_ > 32 && $_ != 127 } @letters ; +print "Without controls: " ; +print join( '' , map { chr( $_ ) } @nocontrols ) ; +@noextended = grep { $_ < 127 } @nocontrols ; +print "\nWithout extended: " ; +print join( '' , map { chr( $_ ) } @noextended ) ; +print "\n" ; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PicoLisp/strip-control-codes-and-extended-characters-from-a-string.l b/Task/Strip-control-codes-and-extended-characters-from-a-string/PicoLisp/strip-control-codes-and-extended-characters-from-a-string.l new file mode 100644 index 0000000000..61b5380c96 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PicoLisp/strip-control-codes-and-extended-characters-from-a-string.l @@ -0,0 +1,12 @@ +(de stripCtrl (Str) + (pack + (filter + '((C) + (nor (= "^?" C) (> " " C "^A")) ) + (chop Str) ) ) ) + +(de stripCtrlExt (Str) + (pack + (filter + '((C) (> "^?" C "^_")) + (chop Str) ) ) ) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Pike/strip-control-codes-and-extended-characters-from-a-string.pike b/Task/Strip-control-codes-and-extended-characters-from-a-string/Pike/strip-control-codes-and-extended-characters-from-a-string.pike new file mode 100644 index 0000000000..c533225f9e --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Pike/strip-control-codes-and-extended-characters-from-a-string.pike @@ -0,0 +1,3 @@ +> string input = random_string(100); +> (string)((array)input-enumerate(32)-enumerate(255-126,1,127)); +Result: "p_xx08M]cK)Tmi|This string has control characters + - - - - - - + +in it +Strip control characters <@ SAYSALVAR>i +Assign infix <@ LETVARSALVAR>j|i <@ SAYVAR>j +Assign prepend <@ LETSALVARVAR>k|i <@ SAYVAR>k +Reflexive assign <@ ACTSALVAR>i <@ SAYVAR>i diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium b/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium new file mode 100644 index 0000000000..d2b71f8c11 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Protium/strip-control-codes-and-extended-characters-from-a-string-2.protium @@ -0,0 +1,5 @@ +Create variable with high and low ANSI: <@ SAYLETVARLIT>i|This string has both low ansi and high ansi characters - il doit d'être prévenu +Strip high ANSI <@ SAYSAHVAR>i +Assign infix <@ LETVARSAHVAR>j|i <@ SAYVAR>j +Assign prepend <@ LETSAHVARVAR>k|i <@ SAYVAR>k +Reflexive assign <@ ACTSAHVAR>i <@ SAYVAR>i diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PureBasic/strip-control-codes-and-extended-characters-from-a-string.purebasic b/Task/Strip-control-codes-and-extended-characters-from-a-string/PureBasic/strip-control-codes-and-extended-characters-from-a-string.purebasic new file mode 100644 index 0000000000..01b4bda765 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PureBasic/strip-control-codes-and-extended-characters-from-a-string.purebasic @@ -0,0 +1,38 @@ +Procedure.s stripControlCodes(source.s) + Protected i, *ptrChar.Character, length = Len(source), result.s + *ptrChar = @source + For i = 1 To length + If *ptrChar\c > 31 + result + Chr(*ptrChar\c) + EndIf + *ptrChar + SizeOf(Character) + Next + ProcedureReturn result +EndProcedure + +Procedure.s stripControlExtCodes(source.s) + Protected i, *ptrChar.Character, length = Len(source), result.s + *ptrChar = @source + For i = 1 To length + If *ptrChar\c > 31 And *ptrChar\c < 128 + result + Chr(*ptrChar\c) + EndIf + *ptrChar + SizeOf(Character) + Next + ProcedureReturn result +EndProcedure + +If OpenConsole() + ;create sample string + Define i, s.s + For i = 1 To 80 + s + Chr(Random(254) + 1) ;include character values from 1 to 255 + Next + + PrintN(stripControlCodes(s)) ;string without control codes + PrintN("---------") + PrintN(stripControlExtCodes(s)) ;string without control codes or extended chars + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py new file mode 100644 index 0000000000..3b2638eb0f --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py @@ -0,0 +1,4 @@ +def stripped(x): + return "".join([i for i in x if ord(i) in range(32, 127)]) + +print stripped("\ba\x00b\n\rc\fd\xc3") diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-2.py b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-2.py new file mode 100644 index 0000000000..acbe86c7c8 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-2.py @@ -0,0 +1 @@ +abcd diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx new file mode 100644 index 0000000000..b0c143410d --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-1.rexx @@ -0,0 +1,18 @@ +/*REXX program to strip all "control codes" from a string (ASCII|EBCDIC)*/ +xxx='string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄' + /*in EBCDIC, digit 1 is 'f1'x,*/ + /*in ASCII, digit 1 is '31'x.*/ +ebcdic= 1=='f1'x /*is this an EBCDIC computer?*/ + /*generate a string of chars from*/ + /*'00'x ──► [1 just before blank]*/ +ccChars = xrange(,d2c(c2d(' ') -1)) /*generate a range of characters.*/ +if \ebcdic then ccChars=ccChars'7f'x /*add the ASCII '7f'X char. */ +say 'hex ccChars =' c2x(ccChars) /*might as well do a show & tell.*/ +ccCharsX = ccChars'ff'x /*add a "stop" char for ccCharsX.*/ +/*══════════════════════════════════════════════════════════════════════*/ +_stop = substr(ccCharsX, verify(ccCharsX, xxx), 1) /*find a stop char.*/ +yyy = translate(space(translate(xxx, _stop, " "ccChars), 0), , _stop) +/*══════════════════════════════════════════════════════════════════════*/ +say 'old = >>>'xxx"<<<" /*add fence before&after old text*/ +say 'new = >>>'yyy"<<<" /* " " " " new text*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx new file mode 100644 index 0000000000..7763b47b29 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/REXX/strip-control-codes-and-extended-characters-from-a-string-2.rexx @@ -0,0 +1,22 @@ +/*REXX program to strip all "control codes" from a string (ASCII|EBCDIC)*/ +xxx='string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄' + /*in EBCDIC, digit 1 is 'f1'x,*/ + /*in ASCII, digit 1 is '31'x.*/ +ascii= '31'x==1 /*is this an ASCII computer? */ + /* (if you are ASCII-centric.) */ + /*generate a string of chars from*/ + /*'00'x --> [1 just before blank]*/ +ccChars=xrange(, d2c(c2d(' ') -1)) /*generate a range of characters.*/ +if ascii then ccChars = ccChars'7f'x /*add the ASCII '7f'X char. */ +say 'hex ccChars =' c2x(ccChars) /*might as well do a show & tell.*/ +/*══════════════════════════════════════════════════════════════════════*/ +yyy='' /*start with a clean slate. */ + do j=1 for length(xxx) /*build new str, 1 byte at a time*/ + _ = substr(xxx,j,1) /*get next char in the old string*/ + if pos(_,ccChars)\==0 then iterate /*skip this char, it's a no-no. */ + yyy = yyy || _ /*we found a good & decent fellow*/ + end +/*══════════════════════════════════════════════════════════════════════*/ +say 'old = >>>'xxx"<<<" /*add fence before&after old text*/ +say 'new = >>>'yyy"<<<" /* " " " " new text*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb new file mode 100644 index 0000000000..1b5d10b6e8 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb @@ -0,0 +1,24 @@ +class String + + def strip_control_characters() + self.chars.inject("") do |str, char| + unless char.ascii_only? and (char.ord < 32 or char.ord == 127) + str << char + end + str + end + end + + def strip_control_and_extended_characters() + self.chars.inject("") do |str, char| + if char.ascii_only? and char.ord.between?(32,126) + str << char + end + str + end + end +end + +p s = "\ba\x00b\n\rc\fd\xc3\x7ffoo" +p s.strip_control_characters +p s.strip_control_and_extended_characters diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Run-BASIC/strip-control-codes-and-extended-characters-from-a-string.run b/Task/Strip-control-codes-and-extended-characters-from-a-string/Run-BASIC/strip-control-codes-and-extended-characters-from-a-string.run new file mode 100644 index 0000000000..bb8171850a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Run-BASIC/strip-control-codes-and-extended-characters-from-a-string.run @@ -0,0 +1,21 @@ +s$ = chr$(31) + "abc" + chr$(13) + "def" + chr$(11) + "ghi" + chr$(10) +print strip$(s$) + +' ----------------------------------------- +' strip junk +' ----------------------------------------- +FUNCTION strip$(str$) +for i = 1 to len(str$) + a$ = MID$(str$,i,1) + a = ASC(a$) + if a > 31 then + if a < 123 then + if a$ <> "'" then + if a$ <> """" then + strip$ = strip$ + a$ + end if + end if + end if + end if +next i +END FUNCTION diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-1.scala b/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-1.scala new file mode 100644 index 0000000000..979954cefc --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-1.scala @@ -0,0 +1,12 @@ +val controlCode : (Char) => Boolean = (c:Char) => (c <= 32 || c == 127) +val extendedCode : (Char) => Boolean = (c:Char) => (c <= 32 || c > 127) + + +// ASCII test... +val teststring = scala.util.Random.shuffle( (1.toChar to 254.toChar).toList ).mkString + +println( "ctrl filtered out: \n\n" + + teststring.filterNot(controlCode) + "\n" ) + +println( "ctrl and extended filtered out: \n\n" + + teststring.filterNot(controlCode).filterNot(extendedCode) + "\n" ) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-2.scala b/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-2.scala new file mode 100644 index 0000000000..32e0785273 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Scala/strip-control-codes-and-extended-characters-from-a-string-2.scala @@ -0,0 +1,20 @@ +// +// A Unicode test string +// +val ulist = 0x8232.toChar :: 0xFFF9.toChar :: 0x200E.toChar :: (1.toChar to 2000.toChar).toList +val ustring = scala.util.Random.shuffle( ulist ).mkString + +// Remove control codes including private codes +val sNoCtrlCode = ustring.replaceAll("[\\p{C}]","") + +val htmlNoCtrlCode = for( i <- sNoCtrlCode.indices ) yield + "&#" + sNoCtrlCode(i).toInt + ";" + (if( (i+1) % 10 == 0 ) "\n" else "") +println( "ctrl filtered out:

\n\n" + htmlNoCtrlCode.mkString + "

\n" ) + + +// Keep 0x00-0x7f and remove control codes +val sNoExtCode = ustring.replaceAll("[^\\p{InBasicLatin}]","").replaceAll("[\\p{C}]","") + +val htmlNoExtCode = for( i <- sNoExtCode.indices ) yield + "&#" + sNoExtCode(i).toInt + ";" + (if( (i+1) % 10 == 0 ) "\n" else "") +println( "ctrl and extended filtered out:

\n\n" + htmlNoExtCode.mkString + "

\n" ) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 b/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 new file mode 100644 index 0000000000..71dd31c4d3 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Seed7/strip-control-codes-and-extended-characters-from-a-string.seed7 @@ -0,0 +1,51 @@ +$ include "seed7_05.s7i"; + include "utf8.s7i"; + +const func string: stripControl (in string: stri) is func + result + var string: stripped is ""; + local + var integer: old_pos is 1; + var integer: index is 0; + var char: ch is ' '; + begin + for ch key index range stri do + if ch < ' ' or ch = '\127\' then + stripped &:= stri[old_pos .. pred(index)]; + old_pos := succ(index); + end if; + end for; + stripped &:= stri[old_pos ..]; + end func; + +const func string: stripControlAndExtended (in string: stri) is func + result + var string: stripped is ""; + local + var integer: old_pos is 1; + var integer: index is 0; + var char: ch is ' '; + begin + for ch key index range stri do + if ch < ' ' or ch >= '\127\' then + stripped &:= stri[old_pos .. pred(index)]; + old_pos := succ(index); + end if; + end for; + stripped &:= stri[old_pos ..]; + end func; + +const string: src is "déjà vu\ # Unicode + \\n\0\\31\ \33\\126\\127\\128\\255\\n\ # Various boundary cases + \as⃝df̅"; # Unicode combining characters + +const proc: main is func + begin + OUT := STD_UTF8_OUT; + writeln("source text:"); + writeln(src); + writeln("Stripped of control codes:"); + writeln(stripControl(src)); + writeln("Stripped of control codes and extended characters:"); + writeln(stripControlAndExtended(src)); + end func; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-1.ti-83 b/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-1.ti-83 new file mode 100644 index 0000000000..0389241675 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-1.ti-83 @@ -0,0 +1 @@ +#$&@;_`abcdefghijklmnopqrstuvwxyz|~ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-2.ti-83 b/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-2.ti-83 new file mode 100644 index 0000000000..b87b72b72d --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/TI-83-BASIC/strip-control-codes-and-extended-characters-from-a-string-2.ti-83 @@ -0,0 +1,9 @@ +:" !#$%&'()*+,-./0123456789:;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"→Str0 +:Input ">",Str1 +:":"+Str1+":"→Str1 +:For(I,2,length(Str1)-2) +:If not(inString(Str0,sub(Str1,I,1))) +:sub(Str1,1,I-1)+sub(Str1,I+1,length(Str1)-(I+1))→Str1 +:End +:sub(Str1,2,length(Str1)-1)→Str1 +:Pause Str1 diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Tcl/strip-control-codes-and-extended-characters-from-a-string.tcl b/Task/Strip-control-codes-and-extended-characters-from-a-string/Tcl/strip-control-codes-and-extended-characters-from-a-string.tcl new file mode 100644 index 0000000000..67bad5ecb5 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Tcl/strip-control-codes-and-extended-characters-from-a-string.tcl @@ -0,0 +1,6 @@ +proc stripAsciiCC str { + regsub -all {[\u0000-\u001f\u007f]+} $str "" +} +proc stripCC str { + regsub -all {[^\u0020-\u007e]+} $str "" +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/XPL0/strip-control-codes-and-extended-characters-from-a-string.xpl0 b/Task/Strip-control-codes-and-extended-characters-from-a-string/XPL0/strip-control-codes-and-extended-characters-from-a-string.xpl0 new file mode 100644 index 0000000000..66a8323696 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/XPL0/strip-control-codes-and-extended-characters-from-a-string.xpl0 @@ -0,0 +1,29 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated string convention + +proc Strip(Str, Both); \Strip out control and optionally extended chars +char Str; int Both; +int I, J, C; +[I:= 0; +while Str(I) do + [C:= Str(I); + if Both then C:= extend(C); \if stripping extended chars too, extend sign + if C<$20 or C=$7F then + [J:= I; \eliminate char by shifting string down over it + repeat C:= Str(J+1); + Str(J):= C; + J:= J+1; + until C=0; + ] + else I:= I+1; + ]; +]; + +char String; +[String:= "Hello^M^J World àáâã"; +Text(0, String); CrLf(0); +Strip(String, false); +Text(0, String); CrLf(0); +Strip(String, true); +Text(0, String); CrLf(0); +] diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/0DESCRIPTION b/Task/Strip-whitespace-from-a-string-Top-and-tail/0DESCRIPTION new file mode 100644 index 0000000000..d7119b8a49 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/0DESCRIPTION @@ -0,0 +1,7 @@ +The task is to demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: + +* String with leading whitespace removed +* String with trailing whitespace removed +* String with both leading and trailing whitespace removed + +For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/1META.yaml b/Task/Strip-whitespace-from-a-string-Top-and-tail/1META.yaml new file mode 100644 index 0000000000..ae625822b7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/1META.yaml @@ -0,0 +1,2 @@ +--- +note: String manipulation diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk new file mode 100644 index 0000000000..22fdeeca3b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk @@ -0,0 +1,9 @@ +#!/usr/bin/awk -f +function trim(str) { + sub(/^[ \t]+/,"",str); # remove leading whitespaces + sub(/[ \t]+$/,"",str); # remove trailing whitespaces + return str; +} +{ + print trim($0); +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.ada b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.ada new file mode 100644 index 0000000000..81aa82446c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.ada @@ -0,0 +1,10 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings; use Ada.Strings; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +procedure StripDemo is + str : String := " Jabberwocky "; +begin + Put_Line ("'" & Trim (str, Left) & "'"); + Put_Line ("'" & Trim (str, Right) & "'"); + Put_Line ("'" & Trim (str, Both) & "'"); +end StripDemo; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AutoHotkey/strip-whitespace-from-a-string-top-and-tail.ahk b/Task/Strip-whitespace-from-a-string-Top-and-tail/AutoHotkey/strip-whitespace-from-a-string-top-and-tail.ahk new file mode 100644 index 0000000000..eba0dda214 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AutoHotkey/strip-whitespace-from-a-string-top-and-tail.ahk @@ -0,0 +1,2 @@ +string := " abc " +MsgBox % clipboard := "<" LTrim(string) ">`n<" RTrim(string) ">`n<" . Trim(string) ">" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/BASIC/strip-whitespace-from-a-string-top-and-tail.basic b/Task/Strip-whitespace-from-a-string-Top-and-tail/BASIC/strip-whitespace-from-a-string-top-and-tail.basic new file mode 100644 index 0000000000..2e27e7ca9d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/BASIC/strip-whitespace-from-a-string-top-and-tail.basic @@ -0,0 +1,3 @@ + mystring$=ltrim(mystring$) ' remove leading whitespace + mystring$=rtrim(mystring$) ' remove trailing whitespace + mystring$=ltrim(rtrim(mystring$)) ' remove both leading and trailing whitespace diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/BBC-BASIC/strip-whitespace-from-a-string-top-and-tail.bbc b/Task/Strip-whitespace-from-a-string-Top-and-tail/BBC-BASIC/strip-whitespace-from-a-string-top-and-tail.bbc new file mode 100644 index 0000000000..01c39dcc4a --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/BBC-BASIC/strip-whitespace-from-a-string-top-and-tail.bbc @@ -0,0 +1,9 @@ + REM Remove leading whitespace: + WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE + + REM Remove trailing whitespace: + WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE + + REM Remove both leading and trailing whitespace: + WHILE ASC(A$)<=32 A$ = MID$(A$,2) : ENDWHILE + WHILE ASC(RIGHT$(A$))<=32 A$ = LEFT$(A$) : ENDWHILE diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Bracmat/strip-whitespace-from-a-string-top-and-tail.bracmat b/Task/Strip-whitespace-from-a-string-Top-and-tail/Bracmat/strip-whitespace-from-a-string-top-and-tail.bracmat new file mode 100644 index 0000000000..38c11a6528 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Bracmat/strip-whitespace-from-a-string-top-and-tail.bracmat @@ -0,0 +1,34 @@ +( ( ltrim + = s + . @( !arg + : ? + ( ( %@ + : ~( " " + | \a + | \b + | \n + | \r + | \t + | \v + ) + ) + ? + : ?s + ) + ) + & !s + ) +& (rtrim=.rev$(ltrim$(rev$!arg))) +& (trim=.rev$(ltrim$(rev$(ltrim$!arg)))) +& (string=" \a Hear + the sound? +\v + +\r +") +& out$(str$("Input:[" !string "]")) +& out$(str$("ltrim:[" ltrim$!string "]")) +& out$(str$("rtrim:[" rtrim$!string "]")) +& out$(str$("trim :[" trim$!string "]")) +& +); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Burlesque/strip-whitespace-from-a-string-top-and-tail.blq b/Task/Strip-whitespace-from-a-string-Top-and-tail/Burlesque/strip-whitespace-from-a-string-top-and-tail.blq new file mode 100644 index 0000000000..2d3851478a --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Burlesque/strip-whitespace-from-a-string-top-and-tail.blq @@ -0,0 +1,6 @@ +blsq ) " this is a string "t[ +"this is a string " +blsq ) " this is a string "t] +" this is a string" +blsq ) " this is a string "tt +"this is a string" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp new file mode 100644 index 0000000000..ce5f4a1eaf --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp @@ -0,0 +1,15 @@ +#include +#include +#include + +int main( ) { + std::string testphrase( " There are unwanted blanks here! " ) ; + std::string lefttrimmed = boost::trim_left_copy( testphrase ) ; + std::string righttrimmed = boost::trim_right_copy( testphrase ) ; + std::cout << "The test phrase is :" << testphrase << "\n" ; + std::cout << "Trimmed on the left side :" << lefttrimmed << "\n" ; + std::cout << "Trimmed on the right side :" << righttrimmed << "\n" ; + boost::trim( testphrase ) ; + std::cout << "Trimmed on both sides :" << testphrase << "\n" ; + return 0 ; +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/C/strip-whitespace-from-a-string-top-and-tail.c b/Task/Strip-whitespace-from-a-string-Top-and-tail/C/strip-whitespace-from-a-string-top-and-tail.c new file mode 100644 index 0000000000..15938440ba --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/C/strip-whitespace-from-a-string-top-and-tail.c @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +char *rtrim(const char *s) +{ + while( isspace(*s) || !isprint(*s) ) ++s; + return strdup(s); +} + +char *ltrim(const char *s) +{ + char *r = strdup(s); + if (r != NULL) + { + char *fr = r + strlen(s) - 1; + while( (isspace(*fr) || !isprint(*fr) || *fr == 0) && fr >= r) --fr; + *++fr = 0; + } + return r; +} + +char *trim(const char *s) +{ + char *r = rtrim(s); + char *f = ltrim(r); + free(r); + return f; +} + +const char *a = " this is a string "; + +int main() +{ + char *b = rtrim(a); + char *c = ltrim(a); + char *d = trim(a); + + printf("'%s'\n'%s'\n'%s'\n", b, c, d); + + free(b); + free(c); + free(d); + return 0; +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/D/strip-whitespace-from-a-string-top-and-tail.d b/Task/Strip-whitespace-from-a-string-Top-and-tail/D/strip-whitespace-from-a-string-top-and-tail.d new file mode 100644 index 0000000000..830fe91ec3 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/D/strip-whitespace-from-a-string-top-and-tail.d @@ -0,0 +1,8 @@ +import std.stdio, std.string; + +void main() { + auto s = " \t \r \n String with spaces \t \r \n "; + assert(s.stripLeft() == "String with spaces \t \r \n "); + assert(s.stripRight() == " \t \r \n String with spaces"); + assert(s.strip() == "String with spaces"); +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/DWScript/strip-whitespace-from-a-string-top-and-tail.dwscript b/Task/Strip-whitespace-from-a-string-Top-and-tail/DWScript/strip-whitespace-from-a-string-top-and-tail.dwscript new file mode 100644 index 0000000000..3e9a7b9650 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/DWScript/strip-whitespace-from-a-string-top-and-tail.dwscript @@ -0,0 +1,6 @@ +const TEST_STRING = ' String with spaces '; + +PrintLn('"' + TEST_STRING + '"'); +PrintLn('"' + TrimLeft(TEST_STRING) + '"'); +PrintLn('"' + TrimRight(TEST_STRING) + '"'); +PrintLn('"' + Trim(TEST_STRING) + '"'); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.delphi b/Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.delphi new file mode 100644 index 0000000000..25e6e981f2 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.delphi @@ -0,0 +1,14 @@ +program StripWhitespace; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +const + TEST_STRING = ' String with spaces '; +begin + Writeln('"' + TEST_STRING + '"'); + Writeln('"' + TrimLeft(TEST_STRING) + '"'); + Writeln('"' + TrimRight(TEST_STRING) + '"'); + Writeln('"' + Trim(TEST_STRING) + '"'); +end. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.euphoria b/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.euphoria new file mode 100644 index 0000000000..e36885b051 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.euphoria @@ -0,0 +1,17 @@ +include std/console.e +include std/text.e + +sequence removables = " \t\n\r\x05\u0234\" " +sequence extraSeq = " \x05\r \" A B C \n \t\t \u0234 \r\r \x05 " + +extraSeq = trim(extraSeq,removables) --the work is done by the trim function + +--only output programming next : +printf(1, "String Trimmed is now: %s \r\n", {extraSeq} ) --print the resulting string to screen + +for i = 1 to length(extraSeq) do --loop over each character in the sequence. + printf(1, "String element %d", i) --to look at more detail, + printf(1, " : %d\r\n", extraSeq[i])--print integer values(ascii) of the string. +end for + +any_key() diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail.fth b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail.fth new file mode 100644 index 0000000000..0c76b5900c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Forth/strip-whitespace-from-a-string-top-and-tail.fth @@ -0,0 +1,8 @@ +: -leading ( addr len -- addr' len' ) + begin over c@ bl = while 1 /string repeat ; +\ -trailing is built in + +s" test " +2dup -leading cr type +2dup -trailing cr type + -leading -trailing cr type diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Go/strip-whitespace-from-a-string-top-and-tail.go b/Task/Strip-whitespace-from-a-string-Top-and-tail/Go/strip-whitespace-from-a-string-top-and-tail.go new file mode 100644 index 0000000000..afc9447f75 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Go/strip-whitespace-from-a-string-top-and-tail.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +var simple = ` + simple ` + +func main() { + show("original", simple) + show("leading ws removed", strings.TrimLeftFunc(simple, unicode.IsSpace)) + show("trailing ws removed", strings.TrimRightFunc(simple, unicode.IsSpace)) + // equivalent to strings.TrimFunc(simple, unicode.IsSpace) + show("both removed", strings.TrimSpace(simple)) +} + +func show(label, str string) { + fmt.Printf("%s: |%s| %v\n", label, str, []rune(str)) +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Groovy/strip-whitespace-from-a-string-top-and-tail.groovy b/Task/Strip-whitespace-from-a-string-Top-and-tail/Groovy/strip-whitespace-from-a-string-top-and-tail.groovy new file mode 100644 index 0000000000..99f1d15fcd --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Groovy/strip-whitespace-from-a-string-top-and-tail.groovy @@ -0,0 +1,22 @@ +//Grape setup to get library +@Grab('org.apache.commons:commons-lang3:3.0.1') +import static org.apache.commons.lang3.StringUtils.* + +def abc = '\r\n\t abc \r\n\t' + +def printTest = { + println ('|' + it + '|') +} + +println 'Unstripped\n------------' +printTest abc + +println '============\n\nStripped\n------------' +printTest strip(abc) + +println '============\n\nLeft Stripped\n------------' +printTest stripStart(abc, null) + +println '============\n\nRight Stripped\n------------' +printTest stripEnd(abc, null) +println '============' diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Haskell/strip-whitespace-from-a-string-top-and-tail.hs b/Task/Strip-whitespace-from-a-string-Top-and-tail/Haskell/strip-whitespace-from-a-string-top-and-tail.hs new file mode 100644 index 0000000000..7ee480a565 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Haskell/strip-whitespace-from-a-string-top-and-tail.hs @@ -0,0 +1,11 @@ +import Data.Char + +trimLeft :: String -> String +trimLeft = dropWhile isSpace + +trimRight :: String -> String +trimRight str | all isSpace str = "" +trimRight (c : cs) = c : trimRight cs + +trim :: String -> String +trim = trimLeft . trimRight diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Icon/strip-whitespace-from-a-string-top-and-tail.icon b/Task/Strip-whitespace-from-a-string-Top-and-tail/Icon/strip-whitespace-from-a-string-top-and-tail.icon new file mode 100644 index 0000000000..faa044eac7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Icon/strip-whitespace-from-a-string-top-and-tail.icon @@ -0,0 +1,8 @@ +procedure main() + unp := &cset[1+:32]++' \t'++&cset[127:0] # all 'unprintable' chars + s := " Hello, people of earth! " + write("Original: '",s,"'") + write("leading trim: '",reverse(trim(reverse(s),unp)),"'") + write("trailing trim: '",trim(s,unp),"'") + write("full trim: '",reverse(trim(reverse(trim(s,unp)),unp)),"'") +end diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-1.j b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-1.j new file mode 100644 index 0000000000..3ca24f8476 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-1.j @@ -0,0 +1,7 @@ + require 'strings' NB. the strings library is automatically loaded in versions from J7 on + quote dlb ' String with spaces ' NB. delete leading blanks +'String with spaces ' + quote dtb ' String with spaces ' NB. delete trailing blanks +' String with spaces' + quote dltb ' String with spaces ' NB. delete leading and trailing blanks +'String with spaces' diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-2.j b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-2.j new file mode 100644 index 0000000000..115ac918c0 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-2.j @@ -0,0 +1,2 @@ + quote deb ' String with spaces ' NB. delete extraneous blanks +'String with spaces' diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-3.j b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-3.j new file mode 100644 index 0000000000..01572cedfe --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/J/strip-whitespace-from-a-string-top-and-tail-3.j @@ -0,0 +1,5 @@ +whpsc=: ' ',TAB NB. define whitespace as desired +dlws=: }.~ (e.&whpsc i. 0:) NB. delete leading whitespace (spaces and tabs) +dtws=: #~ ([: +./\. -.@:e.&whpsc) NB. delete trailing whitespace +dltws=: #~ ([: (+./\ *. +./\.) -.@:e.&whpsc) NB. delete leading & trailing whitespace +dews=: #~ (+. (1: |. (> 0 && Character.isWhitespace(s.charAt(i))){ + i--; + } + return s.substring(0, i + 1); + } + + public static void main(String[] args){ + String s = " \t \r \n String with spaces \t \r \n "; + System.out.println(ltrim(s)); + System.out.println(rtrim(s)); + System.out.println(s.trim()); //trims both ends + } +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia b/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia new file mode 100644 index 0000000000..ee2f3c1eaf --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia @@ -0,0 +1,11 @@ +strip(string[, chars]) +Return string with any leading and trailing whitespace removed. If a string chars is provided, instead remove characters contained in that string. + +lstrip(string[, chars]) +Return string with any leading whitespace removed. If a string chars is provided, instead remove characters contained in that string. + +rstrip(string[, chars]) +Return string with any trailing whitespace removed. If a string chars is provided, instead remove characters contained in that string. + +chomp(string) +Remove a trailing newline from a string diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Liberty-BASIC/strip-whitespace-from-a-string-top-and-tail.liberty b/Task/Strip-whitespace-from-a-string-Top-and-tail/Liberty-BASIC/strip-whitespace-from-a-string-top-and-tail.liberty new file mode 100644 index 0000000000..c73402a20b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Liberty-BASIC/strip-whitespace-from-a-string-top-and-tail.liberty @@ -0,0 +1,26 @@ +a$=" This is a test " + +'LB TRIM$ removes characters with codes 0..31 as well as a space(code 32) +'So these versions of ltrim rtrim remove them too +'a$=" "+chr$(31)+"This is a test"+chr$(31)+" " + +print "Source line" +print ">";a$;"<" +print "Strip left" +print ">";ltrim$(a$);"<" +print "Strip right" +print ">";rtrim$(a$);"<" +print "Strip both" +print ">";trim$(a$);"<" + +end + +function ltrim$(a$) + c$=trim$(a$+".") + ltrim$ = mid$(c$, 1, len(c$)-1) +end function + +function rtrim$(a$) + c$=trim$("."+a$) + rtrim$ = mid$(c$, 2) +end function diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Lua/strip-whitespace-from-a-string-top-and-tail.lua b/Task/Strip-whitespace-from-a-string-Top-and-tail/Lua/strip-whitespace-from-a-string-top-and-tail.lua new file mode 100644 index 0000000000..ef1d3d8f19 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Lua/strip-whitespace-from-a-string-top-and-tail.lua @@ -0,0 +1,5 @@ +str = " \t \r \n String with spaces \t \r \n " + +print( string.format( "Leading whitespace removed: %s", str:match( "^%s*(.+)" ) ) ) +print( string.format( "Trailing whitespace removed: %s", str:match( "(.-)%s*$" ) ) ) +print( string.format( "Leading and trailing whitespace removed: %s", str:match( "^%s*(.-)%s*$" ) ) ) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/MATLAB/strip-whitespace-from-a-string-top-and-tail.m b/Task/Strip-whitespace-from-a-string-Top-and-tail/MATLAB/strip-whitespace-from-a-string-top-and-tail.m new file mode 100644 index 0000000000..847457cff3 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/MATLAB/strip-whitespace-from-a-string-top-and-tail.m @@ -0,0 +1,11 @@ +% remove trailing whitespaces + str = str(1:find(~isspace(str),1,'last')); +% remove leading whitespaces + str = str(find(~isspace(str),1):end); + +% removes leading and trailing whitespaces, vectorized version + f = ~isspace(str); + str = str(find(f,1,'first'):find(f,1,'last'); + +% a built-in function, removes leading and trailing whitespaces + str = strtrim(str); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Mathematica/strip-whitespace-from-a-string-top-and-tail.math b/Task/Strip-whitespace-from-a-string-Top-and-tail/Mathematica/strip-whitespace-from-a-string-top-and-tail.math new file mode 100644 index 0000000000..dfbad0b423 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Mathematica/strip-whitespace-from-a-string-top-and-tail.math @@ -0,0 +1 @@ +StringTrim[" \n\t string with spaces \n \t "] diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Mercury/strip-whitespace-from-a-string-top-and-tail.mercury b/Task/Strip-whitespace-from-a-string-Top-and-tail/Mercury/strip-whitespace-from-a-string-top-and-tail.mercury new file mode 100644 index 0000000000..e954c0db84 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Mercury/strip-whitespace-from-a-string-top-and-tail.mercury @@ -0,0 +1,14 @@ +:- module top_and_tail. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module list, string. + +main(!IO) :- + TestPhrase = "\t\r\n String with spaces \t\r\n ", + io.format("leading ws removed: %s\n", [s(lstrip(TestPhrase))], !IO), + io.format("trailing ws removed: %s\n", [s(rstrip(TestPhrase))], !IO), + io.format("both removed: %s\b", [s(strip(TestPhrase))], !IO). diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Nemerle/strip-whitespace-from-a-string-top-and-tail.nemerle b/Task/Strip-whitespace-from-a-string-Top-and-tail/Nemerle/strip-whitespace-from-a-string-top-and-tail.nemerle new file mode 100644 index 0000000000..f6f8b60a6d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Nemerle/strip-whitespace-from-a-string-top-and-tail.nemerle @@ -0,0 +1,4 @@ +def str = "\t\n\t A string with\nwhitespace\n\n\t "; +WriteLine(str.TrimStart()); +WriteLine(str.TrimEnd()); +WriteLine(str.Trim()); // both ends at once, of course, internal whitespace is preserved in all 3 diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/NetRexx/strip-whitespace-from-a-string-top-and-tail.netrexx b/Task/Strip-whitespace-from-a-string-Top-and-tail/NetRexx/strip-whitespace-from-a-string-top-and-tail.netrexx new file mode 100644 index 0000000000..8f64f4f5b7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/NetRexx/strip-whitespace-from-a-string-top-and-tail.netrexx @@ -0,0 +1,89 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method stripWhitespace(sstring, soption = 'BOTH') public static + wsChars = getWhitspaceCharacterString() + po1 = sstring.verify(wsChars) + if po1 = 0 then do + sstring = '' + end + else do + po2 = sstring.length - (sstring.reverse().verify(wsChars) - 1) + 1 + ss = sstring + parse ss sl =(po1) sm =(po2) st + if po1 <= 1 then sl = '' + soption = soption.upper() + select + when 'BOTH'.abbrev(soption, 1) then sstring = sm + when 'LEADING'.abbrev(soption, 1) then sstring = sm || st + when 'TRAILING'.abbrev(soption, 1) then sstring = sl || sm + otherwise sstring = sm + end + end + return sstring + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +/** + * Create an array containing a useful subset of unicode whitespace characters + * + * @return an array of unicode whitespace characters + * @see http://www.fileformat.info/info/unicode/category/index.htm + */ +method getWhitspaceCharacters() public static returns Rexx[] + wsChars = [ - + /* LINE SEPARATOR [Zi] */ '\u2028', /* PARAGRAPH SEPARATOR [Zp] */ '\u2029', - + /* SPACE [Zs] */ '\u0020', /* NO-BREAK SPACE [Zs] */ '\u00A0', - + /* OGHAM SPACE MARK [Zs] */ '\u1680', /* MONGOLIAN VOWEL SEPARATOR [Zs] */ '\u180E', - + /* EN QUAD [Zs] */ '\u2000', /* EM QUAD [Zs] */ '\u2001', - + /* EN SPACE [Zs] */ '\u2002', /* EM SPACE [Zs] */ '\u2003', - + /* THREE-PER-EM SPACE [Zs] */ '\u2004', /* FOUR-PER-EM SPACE [Zs] */ '\u2005', - + /* SIX-PER-EM SPACE [Zs] */ '\u2006', /* FIGURE SPACE [Zs] */ '\u2007', - + /* PUNCTUATION SPACE [Zs] */ '\u2008', /* THIN SPACE [Zs] */ '\u2009', - + /* HAIR SPACE [Zs] */ '\u200A', /* NARROW NO-BREAK SPACE [Zs] */ '\u202F', - + /* MEDIUM MATHEMATICAL SPACE [Zs] */ '\u3000', /* IDIOGRAPHIC SPACE [Zs] */ '\u205F', - + /* BACKSPACE [Cc] */ '\u0008', /* CHARACTER TABULATION, HT [Cc] */ '\u0009', - + /* LINE FEED (LF) [Cc] */ '\u000A', /* LINE TABULATION (VT) [Cc] */ '\u000B', - + /* FORM FEED (FF) [Cc] */ '\u000C', /* CARRIAGE RETURN (CR) [Cc] */ '\u000D', - + /* INFORMATION SEPARATOR FOUR [Cc] */ '\u001C', /* INFORMATION SEPARATOR THREE [Cc] */ '\u001D', - + /* INFORMATION SEPARATOR TWO [Cc] */ '\u001E', /* INFORMATION SEPARATOR ONE [Cc] */ '\u001F', - + /* NEXT LINE (NEL) [Cc] */ '\u0085', - + /* ZERO WIDTH SPACE [Cf] */ '\u200B', /* ZERO WIDTH NO-BREAK SPACE [Cf] */ '\uFEFF' - + ] + return wsChars + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method getWhitspaceCharacterString() public static returns Rexx + wsCharstring = '' + loop wsChar over getWhitspaceCharacters() + wsCharstring = wsCharstring || wsChar + end wsChar + return wsCharstring + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) public static + sstrings = [ - + ' \u0020 \u0009 \u000D\r \n \u2029\uFEFF1 String with white space. \t \r \n \u1680 ', - + ' \t 2 String with white space. \t ', - + '3 String with white space. \t', - + ' \t 4 String with white space.', - + '5 String with white space.', - + '\u0020\u0009\u2029\uFEFF\u1680\u2006', - + ' ', - + '' - + ] + loop sstringO over sstrings + sstringL = stripWhitespace(sstringO, 'l') + sstringT = stripWhitespace(sstringO, 't') + sstringB = stripWhitespace(sstringO) + say ' Original string ['sstringO']' + say ' strip leading ['sstringL']' + say ' strip trailing ['sstringT']' + say ' strip both ['sstringB']' + say + end sstringO + + return diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ocaml b/Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ocaml new file mode 100644 index 0000000000..7d325447ba --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ocaml @@ -0,0 +1,36 @@ +let left_pos s len = + let rec aux i = + if i >= len then None + else match s.[i] with + | ' ' | '\n' | '\t' | '\r' -> aux (succ i) + | _ -> Some i + in + aux 0 + +let right_pos s len = + let rec aux i = + if i < 0 then None + else match s.[i] with + | ' ' | '\n' | '\t' | '\r' -> aux (pred i) + | _ -> Some i + in + aux (pred len) + +let trim s = + let len = String.length s in + match left_pos s len, right_pos s len with + | Some i, Some j -> String.sub s i (j - i + 1) + | None, None -> "" + | _ -> assert false + +let ltrim s = + let len = String.length s in + match left_pos s len with + | Some i -> String.sub s i (len - i) + | None -> "" + +let rtrim s = + let len = String.length s in + match right_pos s len with + | Some i -> String.sub s 0 (i + 1) + | None -> "" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Oberon-2/strip-whitespace-from-a-string-top-and-tail.oberon-2 b/Task/Strip-whitespace-from-a-string-Top-and-tail/Oberon-2/strip-whitespace-from-a-string-top-and-tail.oberon-2 new file mode 100644 index 0000000000..dca9a180da --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Oberon-2/strip-whitespace-from-a-string-top-and-tail.oberon-2 @@ -0,0 +1,58 @@ +MODULE Trim; +IMPORT Out,Strings,SYSTEM; + +CONST + (* whitespaces *) + HT = 09X; VT = 0BX; FF = 0CX; GS = 1DX; US = 1FX; + LF = 0AX; CR = 0DX; FS = 1CX; RS = 1EX; SPC = 20X; + +PROCEDURE LTrim(VAR s: ARRAY OF CHAR); +VAR + j : INTEGER; +BEGIN + j := 0; + WHILE (s[j] = HT) OR (s[j] = LF) OR (s[j] = VT) OR (s[j] = CR) OR + (s[j] = FF) OR (s[j] = FS) OR (s[j] = FS) OR (s[j] = GS) OR + (s[j] = RS) OR (s[j] = US) OR (s[j] = SPC) DO INC(j) END; + SYSTEM.MOVE(SYSTEM.ADR(s[j]),SYSTEM.ADR(s[0]),LEN(s) - j); +END LTrim; + +PROCEDURE RTrim(VAR s: ARRAY OF CHAR); +VAR + j : INTEGER; +BEGIN + j := LEN(s) - 1; + WHILE (j >= 0) & (s[j] = 0X) DO DEC(j) END; + WHILE (j >= 0) & ((s[j] = HT) OR (s[j] = LF) OR (s[j] = VT) OR (s[j] = CR) OR + (s[j] = FF) OR (s[j] = FS) OR (s[j] = FS) OR (s[j] = GS) OR + (s[j] = RS) OR (s[j] = US) OR (s[j] = SPC)) DO + s[j] := 0X; + DEC(j) + END +END RTrim; + +PROCEDURE Trim(VAR s: ARRAY OF CHAR); +BEGIN + LTrim(s); + RTrim(s) +END Trim; + +VAR + s: ARRAY 100 OF CHAR; + +BEGIN + s := " A AAA"; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);LTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + s := "AAA A "; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);RTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + s := " A AA A "; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);Trim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + s := " "; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);Trim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + s := " "; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);RTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + s := " "; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);LTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);RTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; + Out.Char("[");Out.String(s);Out.String("]=");Out.Char(HT);LTrim(s);Out.Char("[");Out.String(s);Out.Char("]");Out.Ln; +END Trim. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m b/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m new file mode 100644 index 0000000000..32ca79949d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Objective-C/strip-whitespace-from-a-string-top-and-tail.m @@ -0,0 +1,53 @@ +#import + +@interface NSString (RCExt) +-(NSString *) ltrim; +-(NSString *) rtrim; +-(NSString *) trim; +@end + +@implementation NSString (RCExt) +-(NSString *) ltrim +{ + NSInteger i; + NSCharacterSet *cs = [NSCharacterSet whitespaceAndNewlineCharacterSet]; + for(i = 0; i < [self length]; i++) + { + if ( ![cs characterIsMember: [self characterAtIndex: i]] ) break; + } + return [self substringFromIndex: i]; +} + +-(NSString *) rtrim +{ + NSInteger i; + NSCharacterSet *cs = [NSCharacterSet whitespaceAndNewlineCharacterSet]; + for(i = [self length] -1; i >= 0; i--) + { + if ( ![cs characterIsMember: [self characterAtIndex: i]] ) break; + } + return [self substringToIndex: (i+1)]; +} + +-(NSString *) trim +{ + return [self + stringByTrimmingCharactersInSet: + [NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} +@end + +int main() +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSString *s = @" this is a string "; + + NSLog(@"'%@'", s); + NSLog(@"'%@'", [s ltrim]); + NSLog(@"'%@'", [s rtrim]); + NSLog(@"'%@'", [s trim]); + + + [pool release]; + return 0; +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/OpenEdge-Progress/strip-whitespace-from-a-string-top-and-tail.openedge b/Task/Strip-whitespace-from-a-string-Top-and-tail/OpenEdge-Progress/strip-whitespace-from-a-string-top-and-tail.openedge new file mode 100644 index 0000000000..b18ead5877 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/OpenEdge-Progress/strip-whitespace-from-a-string-top-and-tail.openedge @@ -0,0 +1,7 @@ +DEF VAR cc AS CHAR INIT " string with spaces ". + +MESSAGE + "|" + LEFT-TRIM( cc ) + "|" SKIP + "|" + RIGHT-TRIM( cc ) + "|" SKIP + "|" + TRIM( cc ) + "|" +VIEW-AS ALERT-BOX. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php b/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php new file mode 100644 index 0000000000..21ad3aeff1 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PHP/strip-whitespace-from-a-string-top-and-tail.php @@ -0,0 +1,3 @@ + + {\+code_type(X, graph), !}, + strip_action(T). + + +strip_action(X) --> X. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail.purebasic b/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail.purebasic new file mode 100644 index 0000000000..1c1ee137a7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail.purebasic @@ -0,0 +1,37 @@ +;define the whitespace as desired +#whitespace$ = " " + Chr($9) + Chr($A) + Chr($B) + Chr($C) + Chr($D) + Chr($1C) + Chr($1D) + Chr($1E) + Chr($1F) + +Procedure.s myLTrim(source.s) + Protected i, *ptrChar.Character, length = Len(source) + *ptrChar = @source + For i = 1 To length + If Not FindString(#whitespace$, Chr(*ptrChar\c)) + ProcedureReturn Right(source, length + 1 - i) + EndIf + *ptrChar + SizeOf(Character) + Next +EndProcedure + +Procedure.s myRTrim(source.s) + Protected i, *ptrChar.Character, length = Len(source) + *ptrChar = @source + (length - 1) * SizeOf(Character) + For i = length To 1 Step - 1 + If Not FindString(#whitespace$, Chr(*ptrChar\c)) + ProcedureReturn Left(source, i) + EndIf + *ptrChar - SizeOf(Character) + Next +EndProcedure + +Procedure.s myTrim(source.s) + ProcedureReturn myRTrim(myLTrim(source)) +EndProcedure + +If OpenConsole() + PrintN(#DQUOTE$ + myLTrim(" Top ") + #DQUOTE$) + PrintN(#DQUOTE$ + myRTrim(" Tail ") + #DQUOTE$) + PrintN(#DQUOTE$ + myTrim(" Both ") + #DQUOTE$) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Python/strip-whitespace-from-a-string-top-and-tail.py b/Task/Strip-whitespace-from-a-string-Top-and-tail/Python/strip-whitespace-from-a-string-top-and-tail.py new file mode 100644 index 0000000000..18e6e24476 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Python/strip-whitespace-from-a-string-top-and-tail.py @@ -0,0 +1,10 @@ +>>> s = ' \t \r \n String with spaces \t \r \n ' +>>> s +' \t \r \n String with spaces \t \r \n ' +>>> s.lstrip() +'String with spaces \t \r \n ' +>>> s.rstrip() +' \t \r \n String with spaces' +>>> s.strip() +'String with spaces' +>>> diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-1.rexx b/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-1.rexx new file mode 100644 index 0000000000..8115a5fe98 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-1.rexx @@ -0,0 +1,36 @@ +/*REXX program to show how to strip leading and/or trailing spaces. */ + +yyy=" this is a string that has leading and trailing blanks, fur shure. " + + /*white space also includes tabs (VT & HT),*/ + /*among other characters. */ + + /*all examples in each group are equivalent*/ + /*only the option's first char is examined.*/ + + /*───────────────────────just remove the leading white space. */ +noL=strip(yyy,'L') +noL=strip(yyy,"l") +noL=strip(yyy,'leading') +g="Listen, birds / those signs cost money / so roost a while / but don't get funny / Burma-shave" +noL=strip(yyy,g) /*a long way to go to fetch a pail of water.*/ + + /*───────────────────────just remove the trailing white space. */ +noT=strip(yyy,'T') +noT=strip(yyy,"t") +noT=strip(yyy,'trailing') +noT=strip(yyy,'trains ride the rails') +j="Toughest Whiskers / In the town / We hold 'em up / You mow 'em down / Burma-Shave" +noT=strip(yyy,j) + + /*───────────────────────remove leading and trailing white space. */ +noB=strip(yyy) +noB=strip(yyy,) +noB=strip(yyy,'B') +noB=strip(yyy,"b") +noB=strip(yyy,'both') +opt='Be a noble / Not a knave / Caesar uses / Burma-Shave' +noB=strip(yyy,opt) + + /*───────────────────────also remove all superfluous white space, */ +noX=space(yyy) /* including white space between words. */ diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-2.rexx b/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-2.rexx new file mode 100644 index 0000000000..ac068313fe --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/REXX/strip-whitespace-from-a-string-top-and-tail-2.rexx @@ -0,0 +1,25 @@ +/* REXX *************************************************************** +* 01.1.2012 Walter Pachl taking care of all non-printable chars +**********************************************************************/ +pc='abcdefghijklmnopqrstuvwxyz' +pc=pc||translate(pc)'äöüÄÖÜß1234567890!"§&/()=?*+''#;:_,.-<>^!' +x01='01'x +s=x01||' Hi '||x01||' there! '||x01 +say pc /* all printable characters */ +s=x01||' Hi '||x01||' there! '||x01 /* my source string */ +Say 's >'s'<' /* show it */ +p1=verify(s,pc,'M') /* find first printable char */ +sl=substr(s,p1) /* start with it */ +Say 'sl>'sl'<' +sr=reverse(s) +p2=verify(sr,pc,'M') /* find last printable char */ +sr=left(s,length(s)-p2+1) /* end with it */ +Say 'sr>'sr'<' +sb=substr(s,p1,length(s)-p1-p2+1) /* remove leading & trailing */ +Say 'sb>'space(sb)'!' /* whitespace */ +sa=translate(s,pc,pc!!xrange('00'x,'FF'x)) /* all nonprintable chars */ + /* are translated to blanks */ +sa=space(sa) /* eliminate them except 1 */ +Say 'sa>'sa'<'<' /* between words */ +s0=space(sa,0) /* remove all whitespace */ +Say 's0>'s0'<' diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Retro/strip-whitespace-from-a-string-top-and-tail.retro b/Task/Strip-whitespace-from-a-string-Top-and-tail/Retro/strip-whitespace-from-a-string-top-and-tail.retro new file mode 100644 index 0000000000..7562464d4d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Retro/strip-whitespace-from-a-string-top-and-tail.retro @@ -0,0 +1,3 @@ +" this is a test " ^strings'trimLeft +" this is a test " ^strings'trimRight +" this is a test " ^strings'trimLeft ^strings'trimRight diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb new file mode 100644 index 0000000000..bbe9078692 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ruby/strip-whitespace-from-a-string-top-and-tail.rb @@ -0,0 +1,2 @@ +s = " \t\v\r\n\ffoo \t\v\r\n\f" +p [s, s.lstrip, s.rstrip, s.strip] diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Run-BASIC/strip-whitespace-from-a-string-top-and-tail.run b/Task/Strip-whitespace-from-a-string-Top-and-tail/Run-BASIC/strip-whitespace-from-a-string-top-and-tail.run new file mode 100644 index 0000000000..d7a5353347 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Run-BASIC/strip-whitespace-from-a-string-top-and-tail.run @@ -0,0 +1,6 @@ +string$ = " abcdefg " + +print " Top:";trim$(string$+"|") ' top left trim +print "Bottom:";trim$("|"+string$) ' bottom right trim +print " Both:";trim$(string$) ' both left and right +end diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Sather/strip-whitespace-from-a-string-top-and-tail.sa b/Task/Strip-whitespace-from-a-string-Top-and-tail/Sather/strip-whitespace-from-a-string-top-and-tail.sa new file mode 100644 index 0000000000..1e8a79b310 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Sather/strip-whitespace-from-a-string-top-and-tail.sa @@ -0,0 +1,37 @@ +class MAIN is + ltrim(s :STR) :STR is + i ::= 0; + loop while!(i < s.size); + if " \t\f\v\n".contains(s[i]) then + i := i + 1; + else + break!; + end; + end; + return s.tail(s.size - i); + end; + + rtrim(s :STR) :STR is + i ::= s.size-1; + loop while!(i >= 0); + if " \t\f\v\n".contains(s[i]) then + i := i - 1; + else + break!; + end; + end; + return s.head(i+1); + end; + + trim(s :STR) :STR is + return ltrim(rtrim(s)); + end; + + + main is + p ::= " this is a string "; + #OUT + ltrim(p).pretty + "\n"; + #OUT + rtrim(p).pretty + "\n"; + #OUT + trim(p).pretty + "\n"; + end; +end; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala new file mode 100644 index 0000000000..d9c03e1dff --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Scala/strip-whitespace-from-a-string-top-and-tail.scala @@ -0,0 +1,13 @@ +def trimLeft(str:String)=str dropWhile (_.isWhitespace) +def trimRight(str:String)=str take (str.lastIndexWhere(!_.isWhitespace) + 1) +def trimRight2(str:String)=trimLeft(str reverse) reverse +def trim(str:String)=str trim + +def testTrim()={ + val str=" \u001F String with spaces \t \n \r " + println("original : |"+str+"|") + println("trimLeft : |"+trimLeft(str)+"|") + println("trimRight : |"+trimRight(str)+"|") + println("trimRight2: |"+trimRight2(str)+"|") + println("trim : |"+trim(str)+"|") +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail.seed7 b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail.seed7 new file mode 100644 index 0000000000..367dffeec5 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail.seed7 @@ -0,0 +1,10 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const string: testStri is " \t \r \n String with spaces \t \r \n "; + begin + writeln(ltrim(testStri)); + writeln(rtrim(testStri)); + writeln(trim(testStri)); + end func; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Smalltalk/strip-whitespace-from-a-string-top-and-tail.st b/Task/Strip-whitespace-from-a-string-Top-and-tail/Smalltalk/strip-whitespace-from-a-string-top-and-tail.st new file mode 100644 index 0000000000..f9c065245c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Smalltalk/strip-whitespace-from-a-string-top-and-tail.st @@ -0,0 +1,20 @@ +String extend +[ + ltrim [ + ^self replacingRegex: '^\s+' with: ''. + ] + rtrim [ + ^self replacingRegex: '\s+$' with: ''. + ] + trim [ + ^self ltrim rtrim. + ] +] + +|a| +a := ' this is a string '. + +('"%1"' % {a}) displayNl. +('"%1"' % {a ltrim}) displayNl. +('"%1"' % {a rtrim}) displayNl. +('"%1"' % {a trim}) displayNl. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TI-83-BASIC/strip-whitespace-from-a-string-top-and-tail.ti-83 b/Task/Strip-whitespace-from-a-string-Top-and-tail/TI-83-BASIC/strip-whitespace-from-a-string-top-and-tail.ti-83 new file mode 100644 index 0000000000..45281309ea --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TI-83-BASIC/strip-whitespace-from-a-string-top-and-tail.ti-83 @@ -0,0 +1,27 @@ +PROGRAM:WHITESPC +Input Str1 +0→M +Menu(" REMOVE ","TRAILIN WHTSPC",A,"LEADING WHTSPC",C,"BOTH",B) + +Lbl B +1→M + +Lbl A +While sub(Str1,length(Str1)-1),1)=" " +sub(Str1,1,length(Str1)-1)→Str1 +End + +If M=1 +Then +Goto C +Else +Goto F +End + +Lbl C +While sub(str1,1,1)=" " +sub(Str1,2,length(Str1)-1)→Str1 +End + +Lbl F +Disp "'"+Str1+"'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TUSCRIPT/strip-whitespace-from-a-string-top-and-tail.tuscript b/Task/Strip-whitespace-from-a-string-Top-and-tail/TUSCRIPT/strip-whitespace-from-a-string-top-and-tail.tuscript new file mode 100644 index 0000000000..165d6221e4 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TUSCRIPT/strip-whitespace-from-a-string-top-and-tail.tuscript @@ -0,0 +1,9 @@ +$$ MODE TUSCRIPT +str= " sentence w/whitespace before and after " +trimmedtop=EXTRACT (str,":<|<> :"|,0) +trimmedtail=EXTRACT (str,0,":<> >|:") +trimmedboth=SQUEEZE(str) +PRINT "string <|", str," >|" +PRINT "trimmed on top <|",trimmedtop,">|" +PRINT "trimmed on tail <|", trimmedtail,">|" +PRINT "trimmed on both <|", trimmedboth,">|" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail.txr b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail.txr new file mode 100644 index 0000000000..c5f43a293f --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/TXR/strip-whitespace-from-a-string-top-and-tail.txr @@ -0,0 +1,20 @@ +@(define trim_left (in out)) +@ (next :list in) +@/[ \t]*/@out +@(end) +@(define trim_right (in out)) +@ (local blanks middle) +@ (next :list in) +@ (cases) +@ {blanks /[ \t]*/}@middle@/[\t ]+/ +@ (bind out `@blanks@middle`) +@ (or) +@ out +@ (end) +@(end) +@line_of_input +@(output) +trim-left: [@{line_of_input :filter (:fun trim_left)}] +trim_right: [@{line_of_input :filter (:fun trim_right)}] +trim_both: [@{line_of_input :filter ((:fun trim_left) (:fun trim_right))}] +@(end) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Tcl/strip-whitespace-from-a-string-top-and-tail.tcl b/Task/Strip-whitespace-from-a-string-Top-and-tail/Tcl/strip-whitespace-from-a-string-top-and-tail.tcl new file mode 100644 index 0000000000..6c2a4d7617 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Tcl/strip-whitespace-from-a-string-top-and-tail.tcl @@ -0,0 +1,5 @@ +set str " hello world " +puts "original: >$str<" +puts "trimmed head: >[string trimleft $str]<" +puts "trimmed tail: >[string trimright $str]<" +puts "trimmed both: >[string trim $str]<" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ursala/strip-whitespace-from-a-string-top-and-tail.ursala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ursala/strip-whitespace-from-a-string-top-and-tail.ursala new file mode 100644 index 0000000000..ebc481182e --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ursala/strip-whitespace-from-a-string-top-and-tail.ursala @@ -0,0 +1,10 @@ +#import std + +white = ==` !| not @iNC %sI +trim_left = white-~r +trim_right = white~-l +trim_both = trim_left+ trim_right + +#cast %sgUL + +main = <.trim_left,trim_right,trim_both> ' string with spaces ' diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-1.vala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-1.vala new file mode 100644 index 0000000000..d45ccb9926 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-1.vala @@ -0,0 +1,2 @@ +string s = " word "; +string s_chug = s.chug(); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-2.vala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-2.vala new file mode 100644 index 0000000000..0793893fa7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-2.vala @@ -0,0 +1,2 @@ +string s = " word "; +string s_chomp = s.chomp(); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-3.vala b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-3.vala new file mode 100644 index 0000000000..ceb68795d8 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Vala/strip-whitespace-from-a-string-top-and-tail-3.vala @@ -0,0 +1,2 @@ +string s = " word "; +string s_strip = s.strip(); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/XPL0/strip-whitespace-from-a-string-top-and-tail.xpl0 b/Task/Strip-whitespace-from-a-string-Top-and-tail/XPL0/strip-whitespace-from-a-string-top-and-tail.xpl0 new file mode 100644 index 0000000000..5dc32d8faa --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/XPL0/strip-whitespace-from-a-string-top-and-tail.xpl0 @@ -0,0 +1,37 @@ +code ChOut=8, CrLf=9, Text=12; +string 0; \use zero-terminated string convention + +func StripLead(S0); \Strip leading whitespace (<=$20) from string +char S0; +char S1(80); \BEWARE: very temporary string space returned +int I, J, C, Stripped; +[I:= 0; J:= 0; Stripped:= false; +repeat C:= S0(I); I:= I+1; + if Stripped ! C>$20 ! C=0 then + [S1(J):= C; J:= J+1; Stripped:= true]; +until C=0; +return S1; +]; + +func StripTrail(S0); \Strip trailing whitespace (<=$20) from string +char S0; +char S1(80); \BEWARE: very temporary string space returned +int I, SI; +[I:= 0; +loop [if S0(I) <= $20 then + [SI:= I; + while S0(I) <= $20 do + [if S0(I) = 0 then [S1(SI):= 0; return S1]; + S1(I):= S0(I); I:= I+1; + ]; + ] + else [S1(I):= S0(I); I:= I+1]; + ]; +]; + +char String; +[String:= " Hello World "; +Text(0, StripLead(String)); ChOut(0, ^!); CrLf(0); +Text(0, StripTrail(String)); ChOut(0, ^!); CrLf(0); +Text(0, StripTrail(StripLead(String))); ChOut(0, ^!); CrLf(0); +] diff --git a/Task/Substring-Top-and-tail/0DESCRIPTION b/Task/Substring-Top-and-tail/0DESCRIPTION new file mode 100644 index 0000000000..0eee731225 --- /dev/null +++ b/Task/Substring-Top-and-tail/0DESCRIPTION @@ -0,0 +1,7 @@ +The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: + +* String with first character removed +* String with last character removed +* String with both the first and last characters removed + +If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. diff --git a/Task/Substring-Top-and-tail/1META.yaml b/Task/Substring-Top-and-tail/1META.yaml new file mode 100644 index 0000000000..12b5b405fb --- /dev/null +++ b/Task/Substring-Top-and-tail/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- String manipulation diff --git a/Task/Substring-Top-and-tail/ACL2/substring-top-and-tail.acl2 b/Task/Substring-Top-and-tail/ACL2/substring-top-and-tail.acl2 new file mode 100644 index 0000000000..1f58f7e2b2 --- /dev/null +++ b/Task/Substring-Top-and-tail/ACL2/substring-top-and-tail.acl2 @@ -0,0 +1,15 @@ +(defun str-rest (str) + (coerce (rest (coerce str 'list)) 'string)) + +(defun rdc (xs) + (if (endp (rest xs)) + nil + (cons (first xs) + (rdc (rest xs))))) + +(defun str-rdc (str) + (coerce (rdc (coerce str 'list)) 'string)) + +(str-rdc "string") +(str-rest "string") +(str-rest (str-rdc "string")) diff --git a/Task/Substring-Top-and-tail/ALGOL-68/substring-top-and-tail.alg b/Task/Substring-Top-and-tail/ALGOL-68/substring-top-and-tail.alg new file mode 100644 index 0000000000..3efb4ba8f9 --- /dev/null +++ b/Task/Substring-Top-and-tail/ALGOL-68/substring-top-and-tail.alg @@ -0,0 +1,14 @@ +#!/usr/local/bin/a68g --script # + +STRING str="upraisers"; +printf(($gl$, + str, # remove no characters # + str[LWB str+1: ], # remove the first character # + str[ :UPB str-1], # remove the last character # + str[LWB str+1:UPB str-1], # remove both the first and last character # + str[LWB str+2: ], # remove the first 2 characters # + str[ :UPB str-2], # remove the last 2 characters # + str[LWB str+1:UPB str-2], # remove 1 before and 2 after # + str[LWB str+2:UPB str-1], # remove 2 before and one after # + str[LWB str+2:UPB str-2] # remove both the first and last 2 characters # +)) diff --git a/Task/Substring-Top-and-tail/AWK/substring-top-and-tail.awk b/Task/Substring-Top-and-tail/AWK/substring-top-and-tail.awk new file mode 100644 index 0000000000..154d0ec8bd --- /dev/null +++ b/Task/Substring-Top-and-tail/AWK/substring-top-and-tail.awk @@ -0,0 +1,6 @@ +BEGIN { + mystring="knights" + print substr(mystring,2) # remove the first letter + print substr(mystring,1,length(mystring)-1) # remove the last character + print substr(mystring,2,length(mystring)-2) # remove both the first and last character +} diff --git a/Task/Substring-Top-and-tail/Ada/substring-top-and-tail.ada b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail.ada new file mode 100644 index 0000000000..875c71f5db --- /dev/null +++ b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail.ada @@ -0,0 +1,11 @@ +with Ada.Text_IO; + +procedure Remove_Characters is + S: String := "upraisers"; + use Ada.Text_IO; +begin + Put_Line("Full String: """ & S & """"); + Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """"); + Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """"); + Put_Line("Without_Both: """ & S(S'First+1 .. S'Last-1) & """"); +end Remove_Characters; diff --git a/Task/Substring-Top-and-tail/AutoHotkey/substring-top-and-tail.ahk b/Task/Substring-Top-and-tail/AutoHotkey/substring-top-and-tail.ahk new file mode 100644 index 0000000000..1d3f782c80 --- /dev/null +++ b/Task/Substring-Top-and-tail/AutoHotkey/substring-top-and-tail.ahk @@ -0,0 +1,4 @@ +myString := "knights" +MsgBox % SubStr(MyString, 2) +MsgBox % SubStr(MyString, 1, StrLen(MyString)-1) +MsgBox % SubStr(MyString, 2, StrLen(MyString)-2) diff --git a/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail.basic b/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail.basic new file mode 100644 index 0000000000..e665e37b01 --- /dev/null +++ b/Task/Substring-Top-and-tail/BASIC/substring-top-and-tail.basic @@ -0,0 +1,8 @@ +10 PRINT FN F$("KNIGHTS"): REM STRIP THE FIRST LETTER +20 PRINT FN L$("SOCKS"): REM STRIP THE LAST LETTER +30 PRINT FN B$("BROOMS"): REM STRIP BOTH THE FIRST AND LAST LETTER +100 END + +9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1) +9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1) +9020 DEF FN B$(A$)=FN L$(FN F$(A$)) diff --git a/Task/Substring-Top-and-tail/BBC-BASIC/substring-top-and-tail.bbc b/Task/Substring-Top-and-tail/BBC-BASIC/substring-top-and-tail.bbc new file mode 100644 index 0000000000..dd7c6fb6ad --- /dev/null +++ b/Task/Substring-Top-and-tail/BBC-BASIC/substring-top-and-tail.bbc @@ -0,0 +1,4 @@ + s$ = "Rosetta Code" + PRINT MID$(s$, 2) + PRINT LEFT$(s$) + PRINT LEFT$(MID$(s$, 2)) diff --git a/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-1.bracmat b/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-1.bracmat new file mode 100644 index 0000000000..805a633fda --- /dev/null +++ b/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-1.bracmat @@ -0,0 +1,20 @@ +(substringUTF-8= + @( Δημοτική + : (%?a&utf$!a) ?"String with first character removed" + ) +& @( Δημοτική + : ?"String with last character removed" (?z&utf$!z) + ) +& @( Δημοτική + : (%?a&utf$!a) + ?"String with both the first and last characters removed" + (?z&utf$!z) + ) +& out + $ ("String with first character removed:" !"String with first character removed") +& out + $ ("String with last character removed:" !"String with last character removed") +& out + $ ( "String with both the first and last characters removed:" + !"String with both the first and last characters removed" + )); diff --git a/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-2.bracmat b/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-2.bracmat new file mode 100644 index 0000000000..e27e761c8a --- /dev/null +++ b/Task/Substring-Top-and-tail/Bracmat/substring-top-and-tail-2.bracmat @@ -0,0 +1,14 @@ +(substring-8-bit= + @("8-bit string":%@ ?"String with first character removed") +& @("8-bit string":?"String with last character removed" @) +& @( "8-bit string" + : %@ ?"String with both the first and last characters removed" @ + ) +& out + $ ("String with first character removed:" !"String with first character removed") +& out + $ ("String with last character removed:" !"String with last character removed") +& out + $ ( "String with both the first and last characters removed:" + !"String with both the first and last characters removed" + )); diff --git a/Task/Substring-Top-and-tail/C++/substring-top-and-tail.cpp b/Task/Substring-Top-and-tail/C++/substring-top-and-tail.cpp new file mode 100644 index 0000000000..389bfcb00f --- /dev/null +++ b/Task/Substring-Top-and-tail/C++/substring-top-and-tail.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main( ) { + std::string word( "Premier League" ) ; + std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; + std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; + std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; + return 0 ; +} diff --git a/Task/Substring-Top-and-tail/C-sharp/substring-top-and-tail.cs b/Task/Substring-Top-and-tail/C-sharp/substring-top-and-tail.cs new file mode 100644 index 0000000000..e0b894e3fa --- /dev/null +++ b/Task/Substring-Top-and-tail/C-sharp/substring-top-and-tail.cs @@ -0,0 +1,12 @@ +using System; + +class Program +{ + static void Main(string[] args) + { + string testString = "test"; + Console.WriteLine(testString.Substring(1)); + Console.WriteLine(testString.Substring(0, testString.Length - 1)); + Console.WriteLine(testString.Substring(1, testString.Length - 2)); + } +} diff --git a/Task/Substring-Top-and-tail/C/substring-top-and-tail.c b/Task/Substring-Top-and-tail/C/substring-top-and-tail.c new file mode 100644 index 0000000000..7ba2df5938 --- /dev/null +++ b/Task/Substring-Top-and-tail/C/substring-top-and-tail.c @@ -0,0 +1,25 @@ +#include +#include +#include + +int main( int argc, char ** argv ){ + const char * str_a = "knight"; + const char * str_b = "socks"; + const char * str_c = "brooms"; + + char * new_a = malloc( strlen( str_a ) - 1 ); + char * new_b = malloc( strlen( str_b ) - 1 ); + char * new_c = malloc( strlen( str_c ) - 2 ); + + strcpy( new_a, str_a + 1 ); + strncpy( new_b, str_b, strlen( str_b ) - 1 ); + strncpy( new_c, str_c + 1, strlen( str_c ) - 2 ); + + printf( "%s\n%s\n%s\n", new_a, new_b, new_c ); + + free( new_a ); + free( new_b ); + free( new_c ); + + return 0; +} diff --git a/Task/Substring-Top-and-tail/D/substring-top-and-tail.d b/Task/Substring-Top-and-tail/D/substring-top-and-tail.d new file mode 100644 index 0000000000..02db31ef10 --- /dev/null +++ b/Task/Substring-Top-and-tail/D/substring-top-and-tail.d @@ -0,0 +1,12 @@ +import std.stdio; + +void main() { + // strip first character + writeln("knight"[1 .. $]); + + // strip last character + writeln("socks"[0 .. $ - 1]); + + // strip both first and last characters + writeln("brooms"[1 .. $ - 1]); +} diff --git a/Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.delphi b/Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.delphi new file mode 100644 index 0000000000..1735eabe48 --- /dev/null +++ b/Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.delphi @@ -0,0 +1,14 @@ +program TopAndTail; + +{$APPTYPE CONSOLE} + +const + TEST_STRING = '1234567890'; +begin + Writeln(TEST_STRING); // full string + Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING))); // first character removed + Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1)); // last character removed + Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING) - 2)); // first and last characters removed + + Readln; +end. diff --git a/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.euphoria b/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.euphoria new file mode 100644 index 0000000000..b7935693d5 --- /dev/null +++ b/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.euphoria @@ -0,0 +1,15 @@ +function strip_first(sequence s) + return s[2..$] +end function + +function strip_last(sequence s) + return s[1..$-1] +end function + +function strip_both(sequence s) + return s[2..$-1] +end function + +puts(1, strip_first("knight")) -- strip first character +puts(1, strip_last("write")) -- strip last character +puts(1, strip_both("brooms")) -- strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Forth/substring-top-and-tail.fth b/Task/Substring-Top-and-tail/Forth/substring-top-and-tail.fth new file mode 100644 index 0000000000..2340bf490e --- /dev/null +++ b/Task/Substring-Top-and-tail/Forth/substring-top-and-tail.fth @@ -0,0 +1,8 @@ +: hello ( -- c-addr u ) + s" Hello" ; + +hello 1 /string type \ => ello + +hello 1- type \ => hell + +hello 1 /string 1- type \ => ell diff --git a/Task/Substring-Top-and-tail/Fortran/substring-top-and-tail.f b/Task/Substring-Top-and-tail/Fortran/substring-top-and-tail.f new file mode 100644 index 0000000000..a1bb1a1513 --- /dev/null +++ b/Task/Substring-Top-and-tail/Fortran/substring-top-and-tail.f @@ -0,0 +1,11 @@ +program substring + + character(len=5) :: string + string = "Hello" + + write (*,*) string + write (*,*) string(2:) + write (*,*) string( :len(string)-1) + write (*,*) string(2:len(string)-1) + +end program substring diff --git a/Task/Substring-Top-and-tail/GW-BASIC/substring-top-and-tail.gw-basic b/Task/Substring-Top-and-tail/GW-BASIC/substring-top-and-tail.gw-basic new file mode 100644 index 0000000000..09932524a4 --- /dev/null +++ b/Task/Substring-Top-and-tail/GW-BASIC/substring-top-and-tail.gw-basic @@ -0,0 +1,4 @@ +10 A$="knight":B$="socks":C$="brooms" +20 PRINT MID$(A$,2) +30 PRINT LEFT$(B$,LEN(B$)-1) +40 PRINT MID$(C$,2,LEN(C$)-2) diff --git a/Task/Substring-Top-and-tail/Go/substring-top-and-tail.go b/Task/Substring-Top-and-tail/Go/substring-top-and-tail.go new file mode 100644 index 0000000000..374040f6db --- /dev/null +++ b/Task/Substring-Top-and-tail/Go/substring-top-and-tail.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "unicode/utf8" +) + +func main() { + // ASCII contents: Interpreting "characters" as bytes. + s := "ASCII" + fmt.Println("String: ", s) + fmt.Println("First byte removed: ", s[1:]) + fmt.Println("Last byte removed: ", s[:len(s)-1]) + fmt.Println("First and last removed:", s[1:len(s)-1]) + // UTF-8 contents: "Characters" as runes (unicode code points) + u := "Δημοτική" + fmt.Println("String: ", u) + _, sizeFirst := utf8.DecodeRuneInString(u) + fmt.Println("First rune removed: ", u[sizeFirst:]) + _, sizeLast := utf8.DecodeLastRuneInString(u) + fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) + fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) +} diff --git a/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-1.groovy b/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-1.groovy new file mode 100644 index 0000000000..6c03e7aac3 --- /dev/null +++ b/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-1.groovy @@ -0,0 +1,2 @@ +def top = { it.size() > 1 ? it[0..-2] : '' } +def tail = { it.size() > 1 ? it[1..-1] : '' } diff --git a/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-2.groovy b/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-2.groovy new file mode 100644 index 0000000000..f2420742a4 --- /dev/null +++ b/Task/Substring-Top-and-tail/Groovy/substring-top-and-tail-2.groovy @@ -0,0 +1,7 @@ +def testVal = 'upraisers' +println """ +original: ${testVal} +top: ${top(testVal)} +tail: ${tail(testVal)} +top&tail: ${tail(top(testVal))} +""" diff --git a/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail.hs b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail.hs new file mode 100644 index 0000000000..ab68a7be0c --- /dev/null +++ b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail.hs @@ -0,0 +1,18 @@ +-- We define the functions to return an empty string if the argument is too +-- short for the particular operation. + +remFirst, remLast, remBoth :: String -> String + +remFirst "" = "" +remFirst cs = tail cs + +remLast "" = "" +remLast cs = init cs + +remBoth (c:cs) = remLast cs +remBoth _ = "" + +main :: IO () +main = do + let s = "Some string." + mapM_ (\f -> putStrLn . f $ s) [remFirst, remLast, remBoth] diff --git a/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-1.icon b/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-1.icon new file mode 100644 index 0000000000..1464eb81a6 --- /dev/null +++ b/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-1.icon @@ -0,0 +1,5 @@ +procedure main() +write(s := "knight"," --> ", s[2:0]) # drop 1st char +write(s := "sock"," --> ", s[1:-1]) # drop last +write(s := "brooms"," --> ", s[2:-1]) # drop both +end diff --git a/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-2.icon b/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-2.icon new file mode 100644 index 0000000000..e20feb6ef1 --- /dev/null +++ b/Task/Substring-Top-and-tail/Icon/substring-top-and-tail-2.icon @@ -0,0 +1 @@ +write(s := "knight"," --> ", s[1] := "", s) # drop 1st char diff --git a/Task/Substring-Top-and-tail/J/substring-top-and-tail.j b/Task/Substring-Top-and-tail/J/substring-top-and-tail.j new file mode 100644 index 0000000000..1fe3511749 --- /dev/null +++ b/Task/Substring-Top-and-tail/J/substring-top-and-tail.j @@ -0,0 +1,6 @@ + }. 'knight' NB. drop first item +night + }: 'socks' NB. drop last item +sock + }: }. 'brooms' NB. drop first and last items +room diff --git a/Task/Substring-Top-and-tail/Java/substring-top-and-tail.java b/Task/Substring-Top-and-tail/Java/substring-top-and-tail.java new file mode 100644 index 0000000000..084dd71b25 --- /dev/null +++ b/Task/Substring-Top-and-tail/Java/substring-top-and-tail.java @@ -0,0 +1,14 @@ +public class RM_chars { + public static void main( String[] args ){ + System.out.println( "knight".substring( 1 ) ); + System.out.println( "socks".substring( 0, 4 ) ); + System.out.println( "brooms".substring( 1, 5 ) ); + // first, do this by selecting a specific substring + // to exclude the first and last characters + + System.out.println( "knight".replaceAll( "^.", "" ) ); + System.out.println( "socks".replaceAll( ".$", "" ) ); + System.out.println( "brooms".replaceAll( "^.|.$", "" ) ); + // then do this using a regular expressions + } +} diff --git a/Task/Substring-Top-and-tail/JavaScript/substring-top-and-tail.js b/Task/Substring-Top-and-tail/JavaScript/substring-top-and-tail.js new file mode 100644 index 0000000000..6cdd47e9fd --- /dev/null +++ b/Task/Substring-Top-and-tail/JavaScript/substring-top-and-tail.js @@ -0,0 +1,3 @@ +alert("knight".slice(1)); // strip first character +alert("socks".slice(0, -1)); // strip last character +alert("brooms".slice(1, -1)); // strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia b/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia new file mode 100644 index 0000000000..4d686d2928 --- /dev/null +++ b/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia @@ -0,0 +1,8 @@ +julia> "My String"[2:end] #without first character +"y String" + +julia> "My String"[1:end-1] #without last character +"My Strin" + +julia> chop("My String") #alternate remove last character +"My Strin" diff --git a/Task/Substring-Top-and-tail/Liberty-BASIC/substring-top-and-tail.liberty b/Task/Substring-Top-and-tail/Liberty-BASIC/substring-top-and-tail.liberty new file mode 100644 index 0000000000..ae0fab2222 --- /dev/null +++ b/Task/Substring-Top-and-tail/Liberty-BASIC/substring-top-and-tail.liberty @@ -0,0 +1,4 @@ +string$ = "Rosetta Code" +Print Mid$(string$, 2) +Print Left$(string$, (Len(string$) - 1)) +Print Mid$(string$, 2, (Len(string$) - 2)) diff --git a/Task/Substring-Top-and-tail/Locomotive-Basic/substring-top-and-tail.locomotive b/Task/Substring-Top-and-tail/Locomotive-Basic/substring-top-and-tail.locomotive new file mode 100644 index 0000000000..f04c6871b4 --- /dev/null +++ b/Task/Substring-Top-and-tail/Locomotive-Basic/substring-top-and-tail.locomotive @@ -0,0 +1,4 @@ +10 a$="knight":b$="socks":c$="brooms" +20 PRINT MID$(a$,2) +30 PRINT LEFT$(b$,LEN(b$)-1) +40 PRINT MID$(c$,2,LEN(c$)-2) diff --git a/Task/Substring-Top-and-tail/Lua/substring-top-and-tail.lua b/Task/Substring-Top-and-tail/Lua/substring-top-and-tail.lua new file mode 100644 index 0000000000..a217669589 --- /dev/null +++ b/Task/Substring-Top-and-tail/Lua/substring-top-and-tail.lua @@ -0,0 +1,3 @@ +print (string.sub("knights",2)) -- remove the first character +print (string.sub("knights",1,-2)) -- remove the last character +print (string.sub("knights",2,-2)) -- remove the first and last characters diff --git a/Task/Substring-Top-and-tail/MATLAB/substring-top-and-tail.m b/Task/Substring-Top-and-tail/MATLAB/substring-top-and-tail.m new file mode 100644 index 0000000000..8170630ad4 --- /dev/null +++ b/Task/Substring-Top-and-tail/MATLAB/substring-top-and-tail.m @@ -0,0 +1,6 @@ + % String with first character removed + str(2:end) + % String with last character removed + str(1:end-1) + % String with both the first and last characters removed + str(2:end-1) diff --git a/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-1.maple b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-1.maple new file mode 100644 index 0000000000..6a17c63403 --- /dev/null +++ b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-1.maple @@ -0,0 +1,9 @@ +> s := "some string": +> s[2..-1]; + "ome string" + +> s[1..-2]; + "some strin" + +> s[2..-2]; + "ome strin" diff --git a/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-2.maple b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-2.maple new file mode 100644 index 0000000000..5386979ee1 --- /dev/null +++ b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-2.maple @@ -0,0 +1,8 @@ +> substring( s, 2 .. -1 ); + "ome string" + +> substring( s, 1 .. -2 ); + "some strin" + +> substring( s, 2 .. -2 ); + "ome strin" diff --git a/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-3.maple b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-3.maple new file mode 100644 index 0000000000..560eef87ed --- /dev/null +++ b/Task/Substring-Top-and-tail/Maple/substring-top-and-tail-3.maple @@ -0,0 +1,10 @@ +> use StringTools in +> SubString( s, 2 .. -1 ); +> SubString( s, 1 .. -1 ); +> SubString( s, 2 .. -2 ) +> end use; + "ome string" + + "some string" + + "ome strin" diff --git a/Task/Substring-Top-and-tail/Mathematica/substring-top-and-tail.math b/Task/Substring-Top-and-tail/Mathematica/substring-top-and-tail.math new file mode 100644 index 0000000000..8569c8e511 --- /dev/null +++ b/Task/Substring-Top-and-tail/Mathematica/substring-top-and-tail.math @@ -0,0 +1,3 @@ +StringDrop["input string",1] +StringDrop["input string",-1] +StringTake["input string",{2,-2}] diff --git a/Task/Substring-Top-and-tail/Nemerle/substring-top-and-tail.nemerle b/Task/Substring-Top-and-tail/Nemerle/substring-top-and-tail.nemerle new file mode 100644 index 0000000000..72586f75a1 --- /dev/null +++ b/Task/Substring-Top-and-tail/Nemerle/substring-top-and-tail.nemerle @@ -0,0 +1,15 @@ +using System; +using System.Console; + +module RemoveChars +{ + Main() : void + { + def str = "*A string*"; + def end = str.Remove(str.Length - 1); // from pos to end + def beg = str.Remove(0, 1); // start pos, # of chars to remove + def both = str.Trim(array['*']); // with Trim() you need to know what char's you're removing + + WriteLine($"$str -> $beg -> $end -> $both"); + } +} diff --git a/Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ocaml b/Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ocaml new file mode 100644 index 0000000000..b3482cebde --- /dev/null +++ b/Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ocaml @@ -0,0 +1,18 @@ +let strip_first_char str = + if str = "" then "" else + String.sub str 1 ((String.length str) - 1) + +let strip_last_char str = + if str = "" then "" else + String.sub str 0 ((String.length str) - 1) + +let strip_both_chars str = + match String.length str with + | 0 | 1 | 2 -> "" + | len -> String.sub str 1 (len - 2) + +let () = + print_endline (strip_first_char "knight"); + print_endline (strip_last_char "socks"); + print_endline (strip_both_chars "brooms"); +;; diff --git a/Task/Substring-Top-and-tail/Objeck/substring-top-and-tail.objeck b/Task/Substring-Top-and-tail/Objeck/substring-top-and-tail.objeck new file mode 100644 index 0000000000..0748471e9e --- /dev/null +++ b/Task/Substring-Top-and-tail/Objeck/substring-top-and-tail.objeck @@ -0,0 +1,10 @@ +bundle Default { + class TopTail { + function : Main(args : System.String[]) ~ Nil { + string := "test"; + string->SubString(1, string->Size() - 1)->PrintLine(); + string->SubString(string->Size() - 1)->PrintLine(); + string->SubString(1, string->Size() - 2)->PrintLine(); + } + } +} diff --git a/Task/Substring-Top-and-tail/PARI-GP/substring-top-and-tail.pari b/Task/Substring-Top-and-tail/PARI-GP/substring-top-and-tail.pari new file mode 100644 index 0000000000..3fbccb0128 --- /dev/null +++ b/Task/Substring-Top-and-tail/PARI-GP/substring-top-and-tail.pari @@ -0,0 +1,3 @@ +df(s)=concat(vecextract(Vec(s),1<<#s-2)); +dl(s)=concat(vecextract(Vec(s),1<<(#s-1)-1)); +db(s)=concat(vecextract(Vec(s),1<<(#s-1)-2)); diff --git a/Task/Substring-Top-and-tail/PHP/substring-top-and-tail.php b/Task/Substring-Top-and-tail/PHP/substring-top-and-tail.php new file mode 100644 index 0000000000..fad4ad187f --- /dev/null +++ b/Task/Substring-Top-and-tail/PHP/substring-top-and-tail.php @@ -0,0 +1,5 @@ + diff --git a/Task/Substring-Top-and-tail/PL-I/substring-top-and-tail.pli b/Task/Substring-Top-and-tail/PL-I/substring-top-and-tail.pli new file mode 100644 index 0000000000..61ca489ac4 --- /dev/null +++ b/Task/Substring-Top-and-tail/PL-I/substring-top-and-tail.pli @@ -0,0 +1,7 @@ +declare s character (100) varying; +s = 'now is the time to come to the aid of the party'; +if length(s) <= 2 then stop; +put skip list ('First character removed=' || substr(s,2) ); +put skip list ('Last character removed=' || substr(s, 1, length(s)-1) ); +put skip list ('One character from each end removed=' || + substr(s, 2, length(s)-2) ); diff --git a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 new file mode 100644 index 0000000000..4f2c696ad4 --- /dev/null +++ b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-1.pl6 @@ -0,0 +1,8 @@ +say substr('knight', 1); # strip first character - sub +say 'knight'.substr(1); # strip first character - method + +say substr('socks', 0, -1); # strip last character - sub +say 'socks'.substr( 0, -1); # strip last character - method + +say substr('brooms', 1, -1); # strip both first and last characters - sub +say 'brooms'.substr(1, -1); # strip both first and last characters - method diff --git a/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 new file mode 100644 index 0000000000..73c1892179 --- /dev/null +++ b/Task/Substring-Top-and-tail/Perl-6/substring-top-and-tail-2.pl6 @@ -0,0 +1,5 @@ +my $string = 'ouch'; +say $string.chop; # ouc - does not modify original $string +say $string; # ouch +say $string.p5chop; # h - returns the character chopped off and modifies $string +say $string; # ouc diff --git a/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-1.pl b/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-1.pl new file mode 100644 index 0000000000..6938857839 --- /dev/null +++ b/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-1.pl @@ -0,0 +1,3 @@ +print substr("knight",1), "\n"; # strip first character +print substr("socks", 0, -1), "\n"; # strip last character +print substr("brooms", 1, -1), "\n"; # strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-2.pl b/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-2.pl new file mode 100644 index 0000000000..945f16d4cd --- /dev/null +++ b/Task/Substring-Top-and-tail/Perl/substring-top-and-tail-2.pl @@ -0,0 +1,4 @@ +$string = 'ouch'; +$bits = chop($string); # The last letter is returned by the chop function +print $bits; # h +print $string; # ouc # See we really did chop the last letter off diff --git a/Task/Substring-Top-and-tail/PicoLisp/substring-top-and-tail.l b/Task/Substring-Top-and-tail/PicoLisp/substring-top-and-tail.l new file mode 100644 index 0000000000..f18a4d1aba --- /dev/null +++ b/Task/Substring-Top-and-tail/PicoLisp/substring-top-and-tail.l @@ -0,0 +1,8 @@ +: (pack (cdr (chop "knight"))) # Remove first character +-> "night" + +: (pack (head -1 (chop "socks"))) # Remove last character +-> "sock" + +: (pack (cddr (rot (chop "brooms")))) # Remove first and last characters +-> "room" diff --git a/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro b/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro new file mode 100644 index 0000000000..30c0204c53 --- /dev/null +++ b/Task/Substring-Top-and-tail/Prolog/substring-top-and-tail.pro @@ -0,0 +1,13 @@ +remove_first_last_chars :- + L = "Rosetta", + L = [_|L1], + remove_last(L, L2), + remove_last(L1, L3), + writef('Original string : %s\n', [L]), + writef('Without first char : %s\n', [L1]), + writef('Without last char : %s\n', [L2]), + writef('Without first/last chars : %s\n', [L3]). + +remove_last(L, LR) :- + reverse(L, [_ | L1]), + reverse(L1, LR). diff --git a/Task/Substring-Top-and-tail/PureBasic/substring-top-and-tail.purebasic b/Task/Substring-Top-and-tail/PureBasic/substring-top-and-tail.purebasic new file mode 100644 index 0000000000..1a42f36c33 --- /dev/null +++ b/Task/Substring-Top-and-tail/PureBasic/substring-top-and-tail.purebasic @@ -0,0 +1,8 @@ +If OpenConsole() + PrintN(Right("knight", Len("knight") - 1)) ;strip the first letter + PrintN(Left("socks", Len("socks")- 1)) ;strip the last letter + PrintN(Mid("brooms", 2, Len("brooms") - 2)) ;strip both the first and last letter + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Substring-Top-and-tail/Python/substring-top-and-tail.py b/Task/Substring-Top-and-tail/Python/substring-top-and-tail.py new file mode 100644 index 0000000000..bc28f6b428 --- /dev/null +++ b/Task/Substring-Top-and-tail/Python/substring-top-and-tail.py @@ -0,0 +1,3 @@ +print "knight"[1:] # strip first character +print "socks"[:-1] # strip last character +print "brooms"[1:-1] # strip both first and last characters diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx new file mode 100644 index 0000000000..dcb6700b2c --- /dev/null +++ b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx @@ -0,0 +1,20 @@ +/*REXX program to show removal of 1st/last/1st&last chars from a string.*/ + +z = 'abcdefghijk' + +say ' the original string =' z +say 'string first character removed =' substr(z,2) +say 'string last character removed =' left(z,length(z)-1) +say 'string first & last character removed =' substr(z,2,length(z)-2) +exit + /* ┌───────────────────────────────────────────────┐ + │ however, the original string may be null, │ + │ or of insufficient length which may cause the │ + │ BIFs to fail (because of negative length). │ + └───────────────────────────────────────────────┘ */ + +say ' the original string =' z +say 'string first character removed =' substr(z,2) +say 'string last character removed =' left(z,max(0,length(z)-1)) +say 'string first & last character removed =' substr(z,2,max(0,length(z)-2)) + /*stick a fork in it,we're done.*/ diff --git a/Task/Substring-Top-and-tail/Racket/substring-top-and-tail.rkt b/Task/Substring-Top-and-tail/Racket/substring-top-and-tail.rkt new file mode 100644 index 0000000000..2ad2983a8e --- /dev/null +++ b/Task/Substring-Top-and-tail/Racket/substring-top-and-tail.rkt @@ -0,0 +1,7 @@ +#lang racket + +(define str "ストリング") + +(substring str 1) +(substring str 0 (sub1 (string-length str))) +(substring str 1 (sub1 (string-length str))) diff --git a/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb b/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb new file mode 100644 index 0000000000..0435d87dcd --- /dev/null +++ b/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb @@ -0,0 +1,4 @@ +puts "knight"[1..-1] # strip first character +puts "socks"[0..-2] # strip last character +puts "socks".chop # alternate way to strip last character +puts "brooms"[1..-2] # strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Run-BASIC/substring-top-and-tail.run b/Task/Substring-Top-and-tail/Run-BASIC/substring-top-and-tail.run new file mode 100644 index 0000000000..d336c01d70 --- /dev/null +++ b/Task/Substring-Top-and-tail/Run-BASIC/substring-top-and-tail.run @@ -0,0 +1,4 @@ +s$ = "Run BASIC" +print mid$(s$,2) 'strip first +print left$(s$,len(s$) -1) 'strip last +print mid$(s$,2,len(s$) -2) 'strip first and last diff --git a/Task/Substring-Top-and-tail/SNOBOL4/substring-top-and-tail.sno b/Task/Substring-Top-and-tail/SNOBOL4/substring-top-and-tail.sno new file mode 100644 index 0000000000..f7e38f586e --- /dev/null +++ b/Task/Substring-Top-and-tail/SNOBOL4/substring-top-and-tail.sno @@ -0,0 +1,3 @@ + "knight" len(1) rem . output ;* strip first character + "socks" rtab(1) . output ;* strip last character + "brooms" len(1) rtab(1) . output ;* strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala b/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala new file mode 100644 index 0000000000..6fe9e89947 --- /dev/null +++ b/Task/Substring-Top-and-tail/Scala/substring-top-and-tail.scala @@ -0,0 +1,3 @@ +println("knight" tail) // strip first character +println("socks" dropRight 1) // strip last character +println("brooms".tail dropRight 1) // strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Seed7/substring-top-and-tail.seed7 b/Task/Substring-Top-and-tail/Seed7/substring-top-and-tail.seed7 new file mode 100644 index 0000000000..726dd8ed98 --- /dev/null +++ b/Task/Substring-Top-and-tail/Seed7/substring-top-and-tail.seed7 @@ -0,0 +1,11 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const string: stri is "upraisers"; + begin + writeln("Full string: " <& stri); + writeln("Without first: " <& stri[2 ..]); + writeln("Without last: " <& stri[.. pred(length(stri))]); + writeln("Without both: " <& stri[2 .. pred(length(stri))]); + end func; diff --git a/Task/Substring-Top-and-tail/TUSCRIPT/substring-top-and-tail.tuscript b/Task/Substring-Top-and-tail/TUSCRIPT/substring-top-and-tail.tuscript new file mode 100644 index 0000000000..217ecfd33a --- /dev/null +++ b/Task/Substring-Top-and-tail/TUSCRIPT/substring-top-and-tail.tuscript @@ -0,0 +1,9 @@ +$$ MODE TUSCRIPT +str="upraisers" +str1=EXTRACT (str,2,0) +str2=EXTRACT (str,0,-1) +str3=EXTRACT (str,2,-1) +PRINT str +PRINT str1 +PRINT str2 +PRINT str3 diff --git a/Task/Substring-Top-and-tail/Tcl/substring-top-and-tail.tcl b/Task/Substring-Top-and-tail/Tcl/substring-top-and-tail.tcl new file mode 100644 index 0000000000..1677f4d83d --- /dev/null +++ b/Task/Substring-Top-and-tail/Tcl/substring-top-and-tail.tcl @@ -0,0 +1,3 @@ +puts [string range "knight" 1 end]; # strip first character +puts [string range "write" 0 end-1]; # strip last character +puts [string range "brooms" 1 end-1]; # strip both first and last characters diff --git a/Task/Substring-Top-and-tail/UNIX-Shell/substring-top-and-tail.sh b/Task/Substring-Top-and-tail/UNIX-Shell/substring-top-and-tail.sh new file mode 100644 index 0000000000..9a469ec2f8 --- /dev/null +++ b/Task/Substring-Top-and-tail/UNIX-Shell/substring-top-and-tail.sh @@ -0,0 +1,5 @@ +#!/bin/zsh +str='abcdefg' +echo ${str#?} # Remove first char +echo ${str%?} # Remove last char +echo ${${str#?}%?} # Remove first & last chars diff --git a/Task/Substring-Top-and-tail/Vala/substring-top-and-tail.vala b/Task/Substring-Top-and-tail/Vala/substring-top-and-tail.vala new file mode 100644 index 0000000000..b2d2d5a898 --- /dev/null +++ b/Task/Substring-Top-and-tail/Vala/substring-top-and-tail.vala @@ -0,0 +1,8 @@ +// declare test string +string s = "Hello, world!"; +// remove first letter +string s_first = s[1:s.length]; +//remove last letter +string s_last = s[0:s.length - 1]; +// remove first and last letters +string s_first_last = s[1:s.length - 1]; diff --git a/Task/Substring-Top-and-tail/XPL0/substring-top-and-tail.xpl0 b/Task/Substring-Top-and-tail/XPL0/substring-top-and-tail.xpl0 new file mode 100644 index 0000000000..a527458f40 --- /dev/null +++ b/Task/Substring-Top-and-tail/XPL0/substring-top-and-tail.xpl0 @@ -0,0 +1,12 @@ +include c:\cxpl\stdlib; +char S, P; +[S:= "Smiles"; +Text(0, S+1); \first character removed +CrLf(0); +P:= S + StrLen(S) - 2; \point to last character in string +P(0):= P(0) ! $80; \set the MSb on the last character +Text(0, S); \last character removed +CrLf(0); +Text(0, S+1); \first and last characters removed +CrLf(0); +] diff --git a/Task/Substring-Top-and-tail/ZX-Spectrum-Basic/substring-top-and-tail.zx b/Task/Substring-Top-and-tail/ZX-Spectrum-Basic/substring-top-and-tail.zx new file mode 100644 index 0000000000..d51cae28ab --- /dev/null +++ b/Task/Substring-Top-and-tail/ZX-Spectrum-Basic/substring-top-and-tail.zx @@ -0,0 +1,8 @@ +10 PRINT FN f$("knight"): REM strip the first letter +20 PRINT FN l$("socks"): REM strip the last letter +30 PRINT FN b$("brooms"): REM strip both the first and last letter +100 STOP + +9000 DEF FN f$(a$)=a$(2 TO LEN(a$)) +9010 DEF FN l$(a$)=a$(1 TO LEN(a$)-(1 AND (LEN(a$)>=1))) +9020 DEF FN b$(a$)=FN l$(FN f$(a$)) diff --git a/Task/Substring/0DESCRIPTION b/Task/Substring/0DESCRIPTION new file mode 100644 index 0000000000..5eed4dc616 --- /dev/null +++ b/Task/Substring/0DESCRIPTION @@ -0,0 +1,9 @@ +{{basic data operation}}In this task display a substring: + +* starting from n characters in and of m length; +* starting from n characters in, up to the end of the string; +* whole string minus last character; +* starting from a known character within the string and of m length; +* starting from a known substring within the string and of m length. + +If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. diff --git a/Task/Substring/1META.yaml b/Task/Substring/1META.yaml new file mode 100644 index 0000000000..3bdc51ea57 --- /dev/null +++ b/Task/Substring/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- String manipulation +note: Basic language learning diff --git a/Task/Substring/ALGOL-68/substring.alg b/Task/Substring/ALGOL-68/substring.alg new file mode 100644 index 0000000000..2627ac7eaa --- /dev/null +++ b/Task/Substring/ALGOL-68/substring.alg @@ -0,0 +1,16 @@ +main: ( + STRING s = "abcdefgh"; + INT n = 2, m = 3; + CHAR char = "d"; + STRING chars = "cd"; + + printf(($gl$, s[n:n+m-1])); + printf(($gl$, s[n:])); + printf(($gl$, s[:UPB s-1])); + + INT pos; + char in string("d", pos, s); + printf(($gl$, s[pos:pos+m-1])); + string in string("de", pos, s); + printf(($gl$, s[pos:pos+m-1])) +) diff --git a/Task/Substring/AWK/substring.awk b/Task/Substring/AWK/substring.awk new file mode 100644 index 0000000000..7d8455c51d --- /dev/null +++ b/Task/Substring/AWK/substring.awk @@ -0,0 +1,11 @@ +BEGIN { + str = "abcdefghijklmnopqrstuvwxyz" + n = 12 + m = 5 + + print substr(str, n, m) + print substr(str, n) + print substr(str, 1, length(str) - 1) + print substr(str, index(str, "q"), m) + print substr(str, index(str, "pq"), m) +} diff --git a/Task/Substring/Ada/substring-1.ada b/Task/Substring/Ada/substring-1.ada new file mode 100644 index 0000000000..b6f5e4cdef --- /dev/null +++ b/Task/Substring/Ada/substring-1.ada @@ -0,0 +1 @@ +type String is array (Positive range <>) of Character; diff --git a/Task/Substring/Ada/substring-2.ada b/Task/Substring/Ada/substring-2.ada new file mode 100644 index 0000000000..bd99168aed --- /dev/null +++ b/Task/Substring/Ada/substring-2.ada @@ -0,0 +1 @@ +A (..) diff --git a/Task/Substring/Ada/substring-3.ada b/Task/Substring/Ada/substring-3.ada new file mode 100644 index 0000000000..00232f593f --- /dev/null +++ b/Task/Substring/Ada/substring-3.ada @@ -0,0 +1,14 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; + +procedure Test_Slices is + Str : constant String := "abcdefgh"; + N : constant := 2; + M : constant := 3; +begin + Put_Line (Str (Str'First + N - 1..Str'First + N + M - 2)); + Put_Line (Str (Str'First + N - 1..Str'Last)); + Put_Line (Str (Str'First..Str'Last - 1)); + Put_Line (Head (Tail (Str, Str'Last - Index (Str, "d", 1)), M)); + Put_Line (Head (Tail (Str, Str'Last - Index (Str, "de", 1) - 1), M)); +end Test_Slices; diff --git a/Task/Substring/Aikido/substring.aikido b/Task/Substring/Aikido/substring.aikido new file mode 100644 index 0000000000..558c23ed36 --- /dev/null +++ b/Task/Substring/Aikido/substring.aikido @@ -0,0 +1,12 @@ +const str = "abcdefg" +var n = 2 +var m = 3 + +println (str[n:n+m-1]) // pos 2 length 3 +println (str[n:]) // pos 2 to end +println (str >> 1) // remove last character +var p = find (str, 'c') +println (str[p:p+m-1]) // from pos of p length 3 + +var s = find (str, "bc") +println (str[s, s+m-1]) // pos of bc length 3 diff --git a/Task/Substring/AutoHotkey/substring.ahk b/Task/Substring/AutoHotkey/substring.ahk new file mode 100644 index 0000000000..ebafbf22fa --- /dev/null +++ b/Task/Substring/AutoHotkey/substring.ahk @@ -0,0 +1,34 @@ +String := "abcdefghijklmnopqrstuvwxyz" +; also: String = abcdefghijklmnopqrstuvwxyz +n := 12 +m := 5 + +; starting from n characters in and of m length; +subString := SubStr(String, n, m) +; alternative: StringMid, subString, String, n, m +MsgBox % subString + +; starting from n characters in, up to the end of the string; +subString := SubStr(String, n) +; alternative: StringMid, subString, String, n +MsgBox % subString + +; whole string minus last character; +StringTrimRight, subString, String, 1 +; alternatives: subString := SubStr(String, 1, StrLen(String) - 1) +; StringMid, subString, String, 1, StrLen(String) - 1 +MsgBox % subString + +; starting from a known character within the string and of m length; +findChar := "q" +subString := SubStr(String, InStr(String, findChar), m) +; alternatives: RegExMatch(String, findChar . ".{" . m - 1 . "}", subString) +; StringMid, subString, String, InStr(String, findChar), m +MsgBox % subString + +; starting from a known character within the string and of m length; +findString := "pq" +subString := SubStr(String, InStr(String, findString), m) +; alternatives: RegExMatch(String, findString . ".{" . m - StrLen(findString) . "}", subString) +; StringMid, subString, String, InStr(String, findString), m +MsgBox % subString diff --git a/Task/Substring/BASIC/substring-1.basic b/Task/Substring/BASIC/substring-1.basic new file mode 100644 index 0000000000..ba97b4b6b9 --- /dev/null +++ b/Task/Substring/BASIC/substring-1.basic @@ -0,0 +1,24 @@ +DIM baseString AS STRING, subString AS STRING, findString AS STRING +DIM m AS INTEGER, n AS INTEGER + +baseString = "abcdefghijklmnopqrstuvwxyz" +n = 12 +m = 5 + +' starting from n characters in and of m length; +subString = MID$(baseString, n, m) +PRINT subString + +' starting from n characters in, up to the end of the string; +subString = MID$(baseString, n) +PRINT subString + +' whole string minus last character; +subString = LEFT$(baseString, LEN(baseString) - 1) +PRINT subString + +' starting from a known character within the string and of m length; +' starting from a known substring within the string and of m length. +findString = "pq" +subString = MID$(baseString, INSTR(baseString, findString), m) +PRINT subString diff --git a/Task/Substring/BASIC/substring-2.basic b/Task/Substring/BASIC/substring-2.basic new file mode 100644 index 0000000000..27521e04fe --- /dev/null +++ b/Task/Substring/BASIC/substring-2.basic @@ -0,0 +1,13 @@ +10 LET A$="abcdefghijklmnopqrstuvwxyz" +15 LET n=10: LET m=7 +20 PRINT A$(n TO n+m-1) +30 PRINT A$(n TO ) +40 PRINT A$( TO LEN (A$)-1) +50 FOR i=1 TO LEN (A$) +60 IF A$(i)="g" THEN PRINT A$(i TO i+m-1): LET i=LEN (A$): GO TO 70 +70 NEXT i +80 LET B$="ijk" +90 FOR i=1 TO LEN (A$)-LEN (B$)+1 +100 IF A$(i TO i+LEN (B$)-1)=B$ THEN PRINT A$(i TO i+m-1): LET i=LEN (A$)-LEN (B$)+1: GO TO 110 +110 NEXT i +120 STOP diff --git a/Task/Substring/BBC-BASIC/substring.bbc b/Task/Substring/BBC-BASIC/substring.bbc new file mode 100644 index 0000000000..fe6367ff76 --- /dev/null +++ b/Task/Substring/BBC-BASIC/substring.bbc @@ -0,0 +1,25 @@ + basestring$ = "The five boxing wizards jump quickly" + n% = 10 + m% = 5 + + REM starting from n characters in and of m length: + substring$ = MID$(basestring$, n%, m%) + PRINT substring$ + + REM starting from n characters in, up to the end of the string: + substring$ = MID$(basestring$, n%) + PRINT substring$ + + REM whole string minus last character: + substring$ = LEFT$(basestring$) + PRINT substring$ + + REM starting from a known character within the string and of m length: + char$ = "w" + substring$ = MID$(basestring$, INSTR(basestring$, char$), m%) + PRINT substring$ + + REM starting from a known substring within the string and of m length: + find$ = "iz" + substring$ = MID$(basestring$, INSTR(basestring$, find$), m%) + PRINT substring$ diff --git a/Task/Substring/Bracmat/substring.bracmat b/Task/Substring/Bracmat/substring.bracmat new file mode 100644 index 0000000000..b47ad16f32 --- /dev/null +++ b/Task/Substring/Bracmat/substring.bracmat @@ -0,0 +1,27 @@ +( (basestring = "The five boxing wizards jump quickly") +& (n = 10) +& (m = 5) + + { starting from n characters in and of m length: } +& @(!basestring:? [(!n+-1) ?substring [(!n+!m+-1) ?) +& out$!substring + + { starting from n characters in, up to the end of the string: } +& @(!basestring:? [(!n+-1) ?substring) +& out$!substring + + { whole string minus last character: } +& @(!basestring:?substring [-2 ?) +& out$!substring + + { starting from a known character within the string and of m length: } +& (char = "w") +& @(!basestring:? ([?p !char ?: ?substring [(!p+!m) ?)) +& out$!substring + + { starting from a known substring within the string and of m length: } +& (find = "iz") +& @(!basestring:? ([?p !find ?: ?substring [(!p+!m) ?)) +& out$!substring +& +) diff --git a/Task/Substring/C++/substring.cpp b/Task/Substring/C++/substring.cpp new file mode 100644 index 0000000000..0352f17497 --- /dev/null +++ b/Task/Substring/C++/substring.cpp @@ -0,0 +1,18 @@ +#include +#include + +int main() +{ + std::string s = "0123456789"; + + int const n = 3; + int const m = 4; + char const c = '2'; + std::string const sub = "456"; + + std::cout << s.substr(n, m)<< "\n"; + std::cout << s.substr(n) << "\n"; + std::cout << s.substr(0, s.size()-1) << "\n"; + std::cout << s.substr(s.find(c), m) << "\n"; + std::cout << s.substr(s.find(sub), m) << "\n"; +} diff --git a/Task/Substring/C/substring.c b/Task/Substring/C/substring.c new file mode 100644 index 0000000000..7fbd7a9ae1 --- /dev/null +++ b/Task/Substring/C/substring.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include + +char *substring(const char *s, size_t n, ptrdiff_t m) +{ + char *result; + /* check for null s */ + if (NULL == s) + return NULL; + /* negative m to mean 'up to the mth char from right' */ + if (m < 0) + m = strlen(s) + m - n + 1; + + /* n < 0 or m < 0 is invalid */ + if (n < 0 || m < 0) + return NULL; + + /* make sure string does not end before n + * and advance the "s" pointer to beginning of substring */ + for ( ; n > 0; s++, n--) + if (*s == '\0') + /* string ends before n: invalid */ + return NULL; + + result = malloc(m+1); + if (NULL == result) + /* memory allocation failed */ + return NULL; + result[0]=0; + strncat(result, s, m); /* strncat() will automatically add null terminator + * if string ends early or after reading m characters */ + return result; +} + +char *str_wholeless1(const char *s) +{ + return substring(s, 0, strlen(s) - 1); +} + +char *str_fromch(const char *s, int ch, ptrdiff_t m) +{ + return substring(s, strchr(s, ch) - s, m); +} + +char *str_fromstr(const char *s, char *in, ptrdiff_t m) +{ + return substring(s, strstr(s, in) - s , m); +} + + +#define TEST(A) do { \ + char *r = (A); \ + if (NULL == r) \ + puts("--error--"); \ + else { \ + puts(r); \ + free(r); \ + } \ + } while(0) + +int main() +{ + const char *s = "hello world shortest program"; + + TEST( substring(s, 12, 5) ); // get "short" + TEST( substring(s, 6, -1) ); // get "world shortest program" + TEST( str_wholeless1(s) ); // "... progra" + TEST( str_fromch(s, 'w', 5) ); // "world" + TEST( str_fromstr(s, "ro", 3) ); // "rog" + + return 0; +} diff --git a/Task/Substring/Clojure/substring.clj b/Task/Substring/Clojure/substring.clj new file mode 100644 index 0000000000..c530384a84 --- /dev/null +++ b/Task/Substring/Clojure/substring.clj @@ -0,0 +1,22 @@ +(def string "alphabet") +(def n 2) +(def m 4) +(def len (count string)) + +;starting from n characters in and of m length; +(println + (subs string n (+ n m))) ;phab +;starting from n characters in, up to the end of the string; +(println + (subs string n)) ;phabet +;whole string minus last character; +(println + (subs string 0 (dec len))) ;alphabe +;starting from a known character within the string and of m length; +(let [pos (.indexOf string (int \l))] + (println + (subs string pos (+ pos m)))) ;lpha +;starting from a known substring within the string and of m length. +(let [pos (.indexOf string "ph")] + (println + (subs string pos (+ pos m)))) ;phab diff --git a/Task/Substring/Common-Lisp/substring.lisp b/Task/Substring/Common-Lisp/substring.lisp new file mode 100644 index 0000000000..87180ce8e7 --- /dev/null +++ b/Task/Substring/Common-Lisp/substring.lisp @@ -0,0 +1,12 @@ +(let ((string "0123456789") + (n 2) + (m 3) + (start #\5) + (substring "34")) + (list (subseq string n (+ n m)) + (subseq string n) + (subseq string 0 (1- (length string))) + (let ((pos (position start string))) + (subseq string pos (+ pos m))) + (let ((pos (search substring string))) + (subseq string pos (+ pos m))))) diff --git a/Task/Substring/D/substring.d b/Task/Substring/D/substring.d new file mode 100644 index 0000000000..c12ac2eda4 --- /dev/null +++ b/Task/Substring/D/substring.d @@ -0,0 +1,18 @@ +import std.stdio, std.string; + +void main() { + const s = "the quick brown fox jumps over the lazy dog"; + enum n = 5, m = 3; + + writeln(s[n .. n + m]); + + writeln(s[n .. $]); + + writeln(s[0 .. $ - 1]); + + const i = s.indexOf("q"); + writeln(s[i .. i + m]); + + const j = s.indexOf("qu"); + writeln(s[j .. j + m]); +} diff --git a/Task/Substring/Delphi/substring.delphi b/Task/Substring/Delphi/substring.delphi new file mode 100644 index 0000000000..c7c16a699f --- /dev/null +++ b/Task/Substring/Delphi/substring.delphi @@ -0,0 +1,19 @@ +program ShowSubstring; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +const + s = '0123456789'; + n = 3; + m = 4; + c = '2'; + sub = '456'; +begin + Writeln(Copy(s, n, m)); // starting from n characters in and of m length; + Writeln(Copy(s, n, Length(s))); // starting from n characters in, up to the end of the string; + Writeln(Copy(s, 1, Length(s) - 1)); // whole string minus last character; + Writeln(Copy(s, Pos(c, s), m)); // starting from a known character within the string and of m length; + Writeln(Copy(s, Pos(sub, s), m)); // starting from a known substring within the string and of m length. +end. diff --git a/Task/Substring/E/substring.e b/Task/Substring/E/substring.e new file mode 100644 index 0000000000..54bbeea1de --- /dev/null +++ b/Task/Substring/E/substring.e @@ -0,0 +1,8 @@ +def string := "aardvarks" +def n := 4 +def m := 4 +println(string(n, n + m)) +println(string(n)) +println(string(0, string.size() - 1)) +println({string(def i := string.indexOf1('d'), i + m)}) +println({string(def i := string.startOf("ard"), i + m)}) diff --git a/Task/Substring/Euphoria/substring.euphoria b/Task/Substring/Euphoria/substring.euphoria new file mode 100644 index 0000000000..2e4c9b5252 --- /dev/null +++ b/Task/Substring/Euphoria/substring.euphoria @@ -0,0 +1,39 @@ +sequence baseString, subString, findString +integer findChar +integer m, n + +baseString = "abcdefghijklmnopqrstuvwxyz" + +-- starting from n characters in and of m length; +n = 12 +m = 5 +subString = baseString[n..n+m-1] +puts(1, subString ) +puts(1,'\n') + +-- starting from n characters in, up to the end of the string; +n = 12 +subString = baseString[n..$] +puts(1, subString ) +puts(1,'\n') + +-- whole string minus last character; +subString = baseString[1..$-1] +puts(1, subString ) +puts(1,'\n') + +-- starting from a known character within the string and of m length; +findChar = 'o' +m = 5 +n = find(findChar,baseString) +subString = baseString[n..n+m-1] +puts(1, subString ) +puts(1,'\n') + +-- starting from a known substring within the string and of m length. +findString = "pq" +m = 5 +n = match(findString,baseString) +subString = baseString[n..n+m-1] +puts(1, subString ) +puts(1,'\n') diff --git a/Task/Substring/Factor/substring.factor b/Task/Substring/Factor/substring.factor new file mode 100644 index 0000000000..498966742a --- /dev/null +++ b/Task/Substring/Factor/substring.factor @@ -0,0 +1,20 @@ +USING: math sequences kernel ; + +! starting from n characters in and of m length +: subseq* ( from length seq -- newseq ) [ over + ] dip subseq ; + +! starting from n characters in, up to the end of the string +: dummy ( seq n -- tailseq ) tail ; + +! whole string minus last character +: dummy1 ( seq -- headseq ) but-last ; + +USING: fry sequences kernel ; +! helper word +: subseq-from-* ( subseq len seq quot -- seq ) [ nip ] prepose 2keep subseq* ; inline + +! starting from a known character within the string and of m length; +: subseq-from-char ( char len seq -- seq ) [ index ] subseq-from-* ; + +! starting from a known substring within the string and of m length. +: subseq-from-seq ( subseq len seq -- seq ) [ start ] subseq-from-* ; diff --git a/Task/Substring/Forth/substring.fth b/Task/Substring/Forth/substring.fth new file mode 100644 index 0000000000..62682ef7b6 --- /dev/null +++ b/Task/Substring/Forth/substring.fth @@ -0,0 +1,9 @@ +2 constant Pos +3 constant Len +: Str ( -- c-addr u ) s" abcdefgh" ; + +Str Pos /string drop Len type \ cde +Str Pos /string type \ cdefgh +Str 1- type \ abcdefg +Str char d scan drop Len type \ def +Str s" de" search 2drop Len type \ def diff --git a/Task/Substring/Fortran/substring.f b/Task/Substring/Fortran/substring.f new file mode 100644 index 0000000000..a8c5f8837a --- /dev/null +++ b/Task/Substring/Fortran/substring.f @@ -0,0 +1,24 @@ +program test_substring + + character (*), parameter :: string = 'The quick brown fox jumps over the lazy dog.' + character (*), parameter :: substring = 'brown' + character , parameter :: c = 'q' + integer , parameter :: n = 5 + integer , parameter :: m = 15 + integer :: i + +! Display the substring starting from n characters in and of length m. + write (*, '(a)') string (n : n + m - 1) +! Display the substring starting from n characters in, up to the end of the string. + write (*, '(a)') string (n :) +! Display the whole string minus the last character. + i = len (string) - 1 + write (*, '(a)') string (: i) +! Display the substring starting from a known character and of length m. + i = index (string, c) + write (*, '(a)') string (i : i + m - 1) +! Display the substring starting from a known substring and of length m. + i = index (string, substring) + write (*, '(a)') string (i : i + m - 1) + +end program test_substring diff --git a/Task/Substring/GAP/substring.gap b/Task/Substring/GAP/substring.gap new file mode 100644 index 0000000000..e6b872ff02 --- /dev/null +++ b/Task/Substring/GAP/substring.gap @@ -0,0 +1,4 @@ +LETTERS; +# "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +LETTERS{[5 .. 10]}; +# "EFGHIJ" diff --git a/Task/Substring/Go/substring.go b/Task/Substring/Go/substring.go new file mode 100644 index 0000000000..44d4b36023 --- /dev/null +++ b/Task/Substring/Go/substring.go @@ -0,0 +1,14 @@ +package main +import "fmt" +import "strings" + +func main() { + s := "ABCDEFGH" + n, m := 2, 3 + + fmt.Println(s[n:n+m]) // "CDE" + fmt.Println(s[n:]) // "CDEFGH" + fmt.Println(s[0:len(s)-1]) // "ABCDEFG" + fmt.Println(s[strings.Index(s, "D"):strings.Index(s, "D")+m]) // "DEF" + fmt.Println(s[strings.Index(s, "DE"):strings.Index(s, "DE")+m]) // "DEF" +} diff --git a/Task/Substring/Groovy/substring.groovy b/Task/Substring/Groovy/substring.groovy new file mode 100644 index 0000000000..72793d1013 --- /dev/null +++ b/Task/Substring/Groovy/substring.groovy @@ -0,0 +1,10 @@ +def str = 'abcdefgh' +def n = 2 +def m = 3 +println str[n..n+m-1] +println str[n..-1] +println str[0..-2] +def index1 = str.indexOf('d') +println str[index1..index1+m-1] +def index2 = str.indexOf('de') +println str[index2..index2+m-1] diff --git a/Task/Substring/Haskell/substring.hs b/Task/Substring/Haskell/substring.hs new file mode 100644 index 0000000000..6571cb90c9 --- /dev/null +++ b/Task/Substring/Haskell/substring.hs @@ -0,0 +1,3 @@ +t45 n c s | null sub = [] + | otherwise = take n. head $ sub + where sub = filter(isPrefixOf c) $ tails s diff --git a/Task/Substring/HicEst/substring.hicest b/Task/Substring/HicEst/substring.hicest new file mode 100644 index 0000000000..baaceb7989 --- /dev/null +++ b/Task/Substring/HicEst/substring.hicest @@ -0,0 +1,12 @@ +CHARACTER :: string = 'ABCDEFGHIJK', known = 'B', substring = 'CDE' +REAL, PARAMETER :: n = 5, m = 8 + +WRITE(Messagebox) string(n : n + m - 1), "| substring starting from n, length m" +WRITE(Messagebox) string(n :), "| substring starting from n, to end of string" +WRITE(Messagebox) string(1: LEN(string)-1), "| whole string minus last character" + +pos_known = INDEX(string, known) +WRITE(Messagebox) string(pos_known : pos_known+m-1), "| substring starting from pos_known, length m" + +pos_substring = INDEX(string, substring) +WRITE(Messagebox) string(pos_substring : pos_substring+m-1), "| substring starting from pos_substring, length m" diff --git a/Task/Substring/Icon/substring.icon b/Task/Substring/Icon/substring.icon new file mode 100644 index 0000000000..b6979db25b --- /dev/null +++ b/Task/Substring/Icon/substring.icon @@ -0,0 +1,14 @@ +procedure main(arglist) +write("Usage: substring ") +s := \arglist[1] | "aardvarks" +n := \arglist[2] | 5 +m := \arglist[3] | 4 +c := \arglist[4] | "d" +ss := \arglist[5] | "ard" + +write( s[n+:m] ) +write( s[n:0] ) +write( s[1:-1] ) +write( s[find(c,s)+:m] ) +write( s[find(ss,s)+:m] ) +end diff --git a/Task/Substring/J/substring-1.j b/Task/Substring/J/substring-1.j new file mode 100644 index 0000000000..16c18c6fa6 --- /dev/null +++ b/Task/Substring/J/substring-1.j @@ -0,0 +1,12 @@ + 5{.3}.'Marshmallow' +shmal + 3}.'Marshmallow' +shmallow + }.'Marshmallow' +arshmallow + }:'Marshmallow' +Marshmallo + 5{.(}.~ i.&'m')'Marshmallow' +mallo + 5{.(}.~ I.@E.~&'sh')'Marshmallow' +shmal diff --git a/Task/Substring/J/substring-2.j b/Task/Substring/J/substring-2.j new file mode 100644 index 0000000000..89206a6f82 --- /dev/null +++ b/Task/Substring/J/substring-2.j @@ -0,0 +1,2 @@ + 'Marshmallow'{~(+i.)/3 5 +shmal diff --git a/Task/Substring/J/substring-3.j b/Task/Substring/J/substring-3.j new file mode 100644 index 0000000000..62e97afcf9 --- /dev/null +++ b/Task/Substring/J/substring-3.j @@ -0,0 +1,7 @@ + require 'strings' + 'sh' dropto 'Marshmallow' +shmallow + 5{. 'sh' dropto 'Marshmallow' +shmal + 'sh' takeafter 'Marshmallow' +mallow diff --git a/Task/Substring/J/substring-4.j b/Task/Substring/J/substring-4.j new file mode 100644 index 0000000000..64a58d57c6 --- /dev/null +++ b/Task/Substring/J/substring-4.j @@ -0,0 +1,4 @@ + 3}. 2 3 5 7 11 13 17 19 +7 11 13 17 19 + 7 11 dropafter 2 3 5 7 11 13 17 19 +2 3 5 7 11 diff --git a/Task/Substring/Java/substring.java b/Task/Substring/Java/substring.java new file mode 100644 index 0000000000..594eb2adaa --- /dev/null +++ b/Task/Substring/Java/substring.java @@ -0,0 +1,10 @@ +String x = "testing123"; +System.out.println(x.substring(n, n + m)); +System.out.println(x.substring(n)); +System.out.println(x.substring(0, x.length() - 1)); +int index1 = x.indexOf('i'); +System.out.println(x.substring(index1, index1 + m)); +int index2 = x.indexOf("ing"); +System.out.println(x.substring(index2, index2 + m)); +//indexOf methods also have an optional "from index" argument which will +//make indexOf ignore characters before that index diff --git a/Task/Substring/JavaScript/substring.js b/Task/Substring/JavaScript/substring.js new file mode 100644 index 0000000000..d55087411b --- /dev/null +++ b/Task/Substring/JavaScript/substring.js @@ -0,0 +1,20 @@ +var str = "abcdefgh"; + +var n = 2; +var m = 3; + +// * starting from n characters in and of m length; +str.substr(n, m); // => "cde" + +// * starting from n characters in, up to the end of the string; +str.substr(n); // => "cdefgh" +str.substring(n); // => "cdefgh" + +// * whole string minus last character; +str.substring(0, str.length - 1); // => "abcdefg" + +// * starting from a known character within the string and of m length; +str.substr(str.indexOf('b'), m); // => "bcd" + +// * starting from a known substring within the string and of m length. +str.substr(str.indexOf('bc'), m); // => "bcd" diff --git a/Task/Substring/Julia/substring.julia b/Task/Substring/Julia/substring.julia new file mode 100644 index 0000000000..009aaad2e9 --- /dev/null +++ b/Task/Substring/Julia/substring.julia @@ -0,0 +1,23 @@ +julia> s = "abcdefg" +"abcdefg" + +julia> n = 3 +3 + +julia> s[n:end] +"cdefg" + +julia> m=2 +2 + +julia> s[n:n+m] +"cde" + +julia> s[1:end-1] +"abcdef" + +julia> s[search(s,'c')] +'c' + +julia> s[search(s,'c'):search(s,'c')+m] +"cde" diff --git a/Task/Substring/Lang5/substring.lang5 b/Task/Substring/Lang5/substring.lang5 new file mode 100644 index 0000000000..4a3eb2607c --- /dev/null +++ b/Task/Substring/Lang5/substring.lang5 @@ -0,0 +1,20 @@ +: cr "\n". ; [] '__A set : dip swap __A swap 1 compress append '__A set execute __A + -1 extract nip ; : nip swap drop ; : tuck swap over ; : -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; +: 2dip swap 'dip dip ; : 2drop drop drop ; : |a,b> over - iota + ; : bi* 'dip dip execute ; : bi@ dup bi* ; +: comb "" split ; : concat "" join ; : empty? length 0= ; : tail over lensize |a,b> subscript ; +: lensize length nip ; : while do 'dup dip 'execute 2dip rot if dup 2dip else break then loop 2drop ; + +: comb -rot over + |a,b> subscript concat ; +: str-tail tail concat ; +: str-index + : 2streq 2dup over lensize iota subscript eq '* reduce ; + swap 'comb bi@ length -rot 0 -rot + "2dup 'lensize bi@ <=" + "2streq if 0 reshape else '1+ 2dip 0 extract drop then" + while empty? if 2drop tuck == if drop -1 then else 4 ndrop -1 then ; + +'abcdefgh 'str set 2 'n set 3 'm set +n m str +str comb n str-tail +str "d" str-index m str +str "de" str-index m str diff --git a/Task/Substring/Liberty-BASIC/substring.liberty b/Task/Substring/Liberty-BASIC/substring.liberty new file mode 100644 index 0000000000..65021d02a4 --- /dev/null +++ b/Task/Substring/Liberty-BASIC/substring.liberty @@ -0,0 +1,22 @@ +'These tasks can be completed with various combinations of Liberty Basic's +'built in Mid$()/ Instr()/ Left$()/ Right$()/ and Len() functions, but these +'examples only use the Mid$()/ Instr()/ and Len() functions. + +baseString$ = "Thequickbrownfoxjumpsoverthelazydog." +n = 12 +m = 5 + +'starting from n characters in and of m length +Print Mid$(baseString$, n, m) + +'starting from n characters in, up to the end of the string +Print Mid$(baseString$, n) + +'whole string minus last character +Print Mid$(baseString$, 1, (Len(baseString$) - 1)) + +'starting from a known character within the string and of m length +Print Mid$(baseString$, Instr(baseString$, "f", 1), m) + +'starting from a known substring within the string and of m length +Print Mid$(baseString$, Instr(baseString$, "jump", 1), m) diff --git a/Task/Substring/Logo/substring.logo b/Task/Substring/Logo/substring.logo new file mode 100644 index 0000000000..73d1319a75 --- /dev/null +++ b/Task/Substring/Logo/substring.logo @@ -0,0 +1,38 @@ +to items :n :thing + if :n >= count :thing [output :thing] + output items :n butlast :thing +end + +to butitems :n :thing + if or :n <= 0 empty? :thing [output :thing] + output butitems :n-1 butfirst :thing +end + +to middle :n :m :thing + output items :m-(:n-1) butitems :n-1 :thing +end + +to lastitems :n :thing + if :n >= count :thing [output :thing] + output lastitems :n butfirst :thing +end + +to starts.with :sub :thing + if empty? :sub [output "true] + if empty? :thing [output "false] + if not equal? first :sub first :thing [output "false] + output starts.with butfirst :sub butfirst :thing +end + +to members :sub :thing + output cascade [starts.with :sub ?] [bf ?] :thing +end + +; note: Logo indices start at one +make "s "abcdefgh +print items 3 butitems 2 :s ; cde +print middle 3 5 :s ; cde +print butitems 2 :s ; cdefgh +print butlast :s ; abcdefg +print items 3 member "d :s ; def +print items 3 members "de :s ; def diff --git a/Task/Substring/Lua/substring.lua b/Task/Substring/Lua/substring.lua new file mode 100644 index 0000000000..50c0d13413 --- /dev/null +++ b/Task/Substring/Lua/substring.lua @@ -0,0 +1,24 @@ +str = "abcdefghijklmnopqrstuvwxyz" +n, m = 5, 15 + +print( string.sub( str, n, m ) ) -- efghijklmno +print( string.sub( str, n, -1 ) ) -- efghijklmnopqrstuvwxyz +print( string.sub( str, 1, -2 ) ) -- abcdefghijklmnopqrstuvwxy + +pos = string.find( str, "i" ) +if pos ~= nil then print( string.sub( str, pos, pos+m ) ) end -- ijklmnopqrstuvwx + +pos = string.find( str, "ijk" ) +if pos ~= nil then print( string.sub( str, pos, pos+m ) ) end-- ijklmnopqrstuvwx + +-- Alternative (more modern) notation + +print ( str:sub(n,m) ) -- efghijklmno +print ( str:sub(n) ) -- efghijklmnopqrstuvwxyz +print ( str:sub(1,-2) ) -- abcdefghijklmnopqrstuvwxy + +pos = str:find "i" +if pos then print (str:sub(pos,pos+m)) end -- ijklmnopqrstuvwx + +pos = str:find "ijk" +if pos then print (str:sub(pos,pos+m)) end d-- ijklmnopqrstuvwx diff --git a/Task/Substring/MATLAB/substring.m b/Task/Substring/MATLAB/substring.m new file mode 100644 index 0000000000..5cbf64e289 --- /dev/null +++ b/Task/Substring/MATLAB/substring.m @@ -0,0 +1,11 @@ + % starting from n characters in and of m length; + s(n+(1:m)) + s(n+1:n+m) + % starting from n characters in, up to the end of the string; + s(n+1:end) + % whole string minus last character; + s(1:end-1) + % starting from a known character within the string and of m length; + s(find(s==c,1)+[0:m-1]) + % starting from a known substring within the string and of m length. + s(strfind(s,pattern)+[0:m-1]) diff --git a/Task/Substring/MUMPS/substring.mumps b/Task/Substring/MUMPS/substring.mumps new file mode 100644 index 0000000000..f29f50270d --- /dev/null +++ b/Task/Substring/MUMPS/substring.mumps @@ -0,0 +1,23 @@ +SUBSTR(S,N,M,C,K) + ;show substring operations + ;S is the string + ;N is a position within the string (that is, n cde ) newline + +( starting from n characters in, up to the end of the string ) +s n len substring . ( => cdefgh ) newline + +( whole string minus last character ) +s 0 len 1 - substring . ( => abcdefg ) newline + +( starting from a known character within the string and of m length ) +s s 'b str-find dup m + substring . ( => bcd ) newline + +( starting from a known substring within the string and of m length ) +s s 'bc str-find dup m + substring . ( => bcd ) newline diff --git a/Task/Substring/OCaml/substring.ocaml b/Task/Substring/OCaml/substring.ocaml new file mode 100644 index 0000000000..94157383d8 --- /dev/null +++ b/Task/Substring/OCaml/substring.ocaml @@ -0,0 +1,23 @@ +# let s = "ABCDEFGH" ;; +val s : string = "ABCDEFGH" + +# let n, m = 2, 3 ;; +val n : int = 2 +val m : int = 3 + +# String.sub s n m ;; +- : string = "CDE" + +# String.sub s n (String.length s - n) ;; +- : string = "CDEFGH" + +# String.sub s 0 (String.length s - 1) ;; +- : string = "ABCDEFG" + +# String.sub s (String.index s 'D') m ;; +- : string = "DEF" + +# #load "str.cma";; +# let n = Str.search_forward (Str.regexp_string "DE") s 0 in + String.sub s n m ;; +- : string = "DEF" diff --git a/Task/Substring/Objeck/substring.objeck b/Task/Substring/Objeck/substring.objeck new file mode 100644 index 0000000000..9cedd95833 --- /dev/null +++ b/Task/Substring/Objeck/substring.objeck @@ -0,0 +1,18 @@ +bundle Default { + class SubString { + function : Main(args : String[]) ~ Nil { + s := "0123456789"; + + n := 3; + m := 4; + c := '2'; + sub := "456"; + + s->SubString(n, m)->PrintLine(); + s->SubString(n)->PrintLine(); + s->SubString(0, s->Size())->PrintLine(); + s->SubString(s->Find(c), m)->PrintLine(); + s->SubString(s->Find(sub), m)->PrintLine(); + } + } +} diff --git a/Task/Substring/Oz/substring.oz b/Task/Substring/Oz/substring.oz new file mode 100644 index 0000000000..84fb8db8a6 --- /dev/null +++ b/Task/Substring/Oz/substring.oz @@ -0,0 +1,21 @@ +declare + fun {DropUntil Xs Prefix} + case Xs of nil then nil + [] _|Xr then + if {List.isPrefix Prefix Xs} then Xs + else {DropUntil Xr Prefix} + end + end + end + + Digits = "1234567890" +in + {ForAll + [{List.take {List.drop Digits 2} 3} = "345" + {List.drop Digits 2} = "34567890" + {List.take Digits {Length Digits}-1} = "123456789" + {List.take {DropUntil Digits "4"} 3} = "456" + {List.take {DropUntil Digits "56"} 3} = "567" + {List.take {DropUntil Digits "31"} 3} = "" + ] + System.showInfo} diff --git a/Task/Substring/PHP/substring.php b/Task/Substring/PHP/substring.php new file mode 100644 index 0000000000..f66131d657 --- /dev/null +++ b/Task/Substring/PHP/substring.php @@ -0,0 +1,10 @@ + diff --git a/Task/Substring/PL-I/substring.pli b/Task/Substring/PL-I/substring.pli new file mode 100644 index 0000000000..0dd2e5b650 --- /dev/null +++ b/Task/Substring/PL-I/substring.pli @@ -0,0 +1,7 @@ +s='abcdefghijk'; +n=4; m=3; +u=substr(s,n,m); +u=substr(s,n); +u=substr(s,1,length(s)-1); +u=substr(s,index(s,'def',m); +u=substr(s,index(s,'g',m); diff --git a/Task/Substring/Perl-6/substring.pl6 b/Task/Substring/Perl-6/substring.pl6 new file mode 100644 index 0000000000..b4e45be750 --- /dev/null +++ b/Task/Substring/Perl-6/substring.pl6 @@ -0,0 +1,8 @@ +my $str = 'abcdefgh'; +my $n = 2; +my $m = 3; +say $str.substr($n, $m); +say $str.substr($n); +say $str.substr(0, *-1); +say $str.substr($str.index('d'), $m); +say $str.substr($str.index('de'), $m); diff --git a/Task/Substring/Perl/substring.pl b/Task/Substring/Perl/substring.pl new file mode 100644 index 0000000000..711cacd5ae --- /dev/null +++ b/Task/Substring/Perl/substring.pl @@ -0,0 +1,8 @@ +my $str = 'abcdefgh'; +my $n = 2; +my $m = 3; +print substr($str, $n, $m), "\n"; +print substr($str, $n), "\n"; +print substr($str, 0, -1), "\n"; +print substr($str, index($str, 'd'), $m), "\n"; +print substr($str, index($str, 'de'), $m), "\n"; diff --git a/Task/Substring/PicoLisp/substring.l b/Task/Substring/PicoLisp/substring.l new file mode 100644 index 0000000000..6d3e9c45f9 --- /dev/null +++ b/Task/Substring/PicoLisp/substring.l @@ -0,0 +1,8 @@ +(let Str (chop "This is a string") + (prinl (head 4 (nth Str 6))) # From 6 of 4 length + (prinl (nth Str 6)) # From 6 up to the end + (prinl (head -1 Str)) # Minus last character + (prinl (head 8 (member "s" Str))) # From character "s" of length 8 + (prinl # From "isa" of length 8 + (head 8 + (seek '((S) (pre? "is a" S)) Str) ) ) ) diff --git a/Task/Substring/PowerShell/substring.psh b/Task/Substring/PowerShell/substring.psh new file mode 100644 index 0000000000..e849279fd1 --- /dev/null +++ b/Task/Substring/PowerShell/substring.psh @@ -0,0 +1,23 @@ +# test string +$s = "abcdefgh" +# test parameters +$n, $m, $c, $s2 = 2, 3, [char]'d', $s2 = 'cd' + +# starting from n characters in and of m length +# n = 2, m = 3 +$s.Substring($n-1, $m) # returns 'bcd' + +# starting from n characters in, up to the end of the string +# n = 2 +$s.Substring($n-1) # returns 'bcdefgh' + +# whole string minus last character +$s.Substring(0, $s.Length - 1) # returns 'abcdefg' + +# starting from a known character within the string and of m length +# c = 'd', m =3 +$s.Substring($s.IndexOf($c), $m) # returns 'def' + +# starting from a known substring within the string and of m length +# s2 = 'cd', m = 3 +$s.Substring($s.IndexOf($s2), $m) # returns 'cde' diff --git a/Task/Substring/PureBasic/substring.purebasic b/Task/Substring/PureBasic/substring.purebasic new file mode 100644 index 0000000000..e0f3ddaf88 --- /dev/null +++ b/Task/Substring/PureBasic/substring.purebasic @@ -0,0 +1,27 @@ +If OpenConsole() + + Define baseString.s, m, n + + baseString = "Thequickbrownfoxjumpsoverthelazydog." + n = 12 + m = 5 + + ;Display the substring starting from n characters in and of m length. + PrintN(Mid(baseString, n, m)) + + ;Display the substring starting from n characters in, up to the end of the string. + PrintN(Mid(baseString, n)) ;or PrintN(Right(baseString, Len(baseString) - n)) + + ;Display the substring whole string minus last character + PrintN(Left(baseString, Len(baseString) - 1)) + + ;Display the substring starting from a known character within the string and of m length. + PrintN(Mid(baseString, FindString(baseString, "b", 1), m)) + + ;Display the substring starting from a known substring within the string and of m length. + PrintN(Mid(baseString, FindString(baseString, "ju", 1), m)) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Substring/Python/substring.py b/Task/Substring/Python/substring.py new file mode 100644 index 0000000000..cf255ee216 --- /dev/null +++ b/Task/Substring/Python/substring.py @@ -0,0 +1,20 @@ +>>> s = 'abcdefgh' +>>> n, m, char, chars = 2, 3, 'd', 'cd' +>>> # starting from n=2 characters in and m=3 in length; +>>> s[n-1:n+m-1] +'bcd' +>>> # starting from n characters in, up to the end of the string; +>>> s[n-1:] +'bcdefgh' +>>> # whole string minus last character; +>>> s[:-1] +'abcdefg' +>>> # starting from a known character char="d" within the string and of m length; +>>> indx = s.index(char) +>>> s[indx:indx+m] +'def' +>>> # starting from a known substring chars="cd" within the string and of m length. +>>> indx = s.index(chars) +>>> s[indx:indx+m] +'cde' +>>> diff --git a/Task/Substring/R/substring.r b/Task/Substring/R/substring.r new file mode 100644 index 0000000000..fead825305 --- /dev/null +++ b/Task/Substring/R/substring.r @@ -0,0 +1,9 @@ +s <- "abcdefgh" +n <- 2; m <- 2; char <- 'd'; chars <- 'cd' +substring(s, n, n + m) +substring(s, n) +substring(s, 1, nchar(s)-1) +indx <- which(strsplit(s, '')[[1]]%in%strsplit(char, '')[[1]]) +substring(s, indx, indx + m) +indx <- which(strsplit(s, '')[[1]]%in%strsplit(chars, '')[[1]])[1] +substring(s, indx, indx + m) diff --git a/Task/Substring/REBOL/substring.rebol b/Task/Substring/REBOL/substring.rebol new file mode 100644 index 0000000000..0b1c629277 --- /dev/null +++ b/Task/Substring/REBOL/substring.rebol @@ -0,0 +1,43 @@ +REBOL [ + Title: "Retrieve Substring" + Author: oofoe + Date: 2009-12-06 + URL: http://rosettacode.org/wiki/Retrieve_a_substring +] + +s: "abcdefgh" n: 2 m: 3 char: #"d" chars: "cd" + +; Note that REBOL uses base-1 indexing. Strings are series values, +; just like blocks or lists so I can use the same words to manipulate +; them. All these examples use the 'copy' function against the 's' +; string with a particular offset as needed. + +; For the fragment "copy/part skip s n - 1 m", read from right to +; left. First you have 'm', which we ignore for now. Then evaluate +; 'n - 1' (makes 1), to adjust the offset. Then 'skip' jumps from the +; start of the string by that offset. 'copy' starts copying from the +; new start position and the '/part' refinement limits the copy by 'm' +; characters. + +print ["Starting from n, length m:" + copy/part skip s n - 1 m] + +; It may be helpful to see the expression with optional parenthesis: + +print ["Starting from n, length m (parens):" + (copy/part (skip s (n - 1)) m)] + +; This example is much simpler, so hopefully it's easier to see how +; the string start is position for the copy: + +print ["Starting from n to end of string:" + copy skip s n - 1] + +print ["Whole string minus last character:" + copy/part s (length? s) - 1] + +print ["Starting from known character, length m:" + copy/part find s char m] + +print ["Starting from substring, length m:" + copy/part find s chars m] diff --git a/Task/Substring/REXX/substring.rexx b/Task/Substring/REXX/substring.rexx new file mode 100644 index 0000000000..f6563d491b --- /dev/null +++ b/Task/Substring/REXX/substring.rexx @@ -0,0 +1,20 @@ +/*REXX program demonstrates various ways to extract substrings from a string of characters. */ +s='abcdefghijk'; n=4; m=3 /*define come REXX constants (string, index, length of string).*/ +say 'original string:' s /* [↑] M can be zero (which indicates a null string). */ + +u=substr(s,n,m) /*starting from N characters in and of M length. */ +say u + +u=substr(s,n) /*starting from N characters in, up to the end-of-string. */ +say u + +u=substr(s,1,length(s)-1) /*OK: the whole string except the last character. */ +u=substr(s,1,max(0,length(s)-1)) /*better: this version handles the case of a null string. */ +say u + +u=substr(s,pos('def',s),m) /*starting from a known char within the string & of M length.*/ +say u + +u=substr(s,pos('g',s),m) /*starting from a known substr within the string & of M length.*/ +say u + /*stick a fork in it sir, we're all done and Bob's your uncle. */ diff --git a/Task/Substring/Ruby/substring.rb b/Task/Substring/Ruby/substring.rb new file mode 100644 index 0000000000..5b9b1b06d9 --- /dev/null +++ b/Task/Substring/Ruby/substring.rb @@ -0,0 +1,9 @@ +str = 'abcdefgh' +n = 2 +m = 3 +puts str[n, m] +puts str[n..-1] +puts str[0..-2] +puts str[str.index('d'), m] +puts str[str.index('de'), m] +puts str[/a.*d/] diff --git a/Task/Substring/Run-BASIC/substring.run b/Task/Substring/Run-BASIC/substring.run new file mode 100644 index 0000000000..f3b4974444 --- /dev/null +++ b/Task/Substring/Run-BASIC/substring.run @@ -0,0 +1,8 @@ +n = 2 +m = 3 +s$ = "abcd" +a$ = mid$(a$,n,m) ' starting from n characters in and of m length +a$ = mid$(a$,n) ' starting from n characters in, up to the end of the string +a$ = Print mid$(a$,1,(len(a$)-1)) ' whole string minus last character +a$ = mid$(a$,instr(a$,s$,1),m) ' starting from a known character within the string and of m length +a$ = mid$(a$,instr(a$,s$,1), m) ' starting from a known substring within the string and of m length. diff --git a/Task/Substring/SAS/substring.sas b/Task/Substring/SAS/substring.sas new file mode 100644 index 0000000000..dec1934d99 --- /dev/null +++ b/Task/Substring/SAS/substring.sas @@ -0,0 +1,6 @@ +data _null_; + a="abracadabra"; + b=substr(a,2,3); /* first number is position, starting at 1, + second number is length */ + put _all_; +run; diff --git a/Task/Substring/SNOBOL4/substring.sno b/Task/Substring/SNOBOL4/substring.sno new file mode 100644 index 0000000000..03c5ba2028 --- /dev/null +++ b/Task/Substring/SNOBOL4/substring.sno @@ -0,0 +1,16 @@ + string = "abcdefghijklmnopqrstuvwxyz" + n = 12 + m = 5 + known_char = "q" + known_str = "pq" +* starting from n characters in and of m length; + string len(n - 1) len(m) . output +* starting from n characters in, up to the end of the string; + string len(n - 1) rem . output +* whole string minus last character; + string rtab(1) . output +* starting from a known character within the string and of m length; + string break(known_char) len(m) . output +* starting from a known substring <= m within the string and of m length. + string (known_str len(m - size(known_str))) . output +end diff --git a/Task/Substring/Sather/substring.sa b/Task/Substring/Sather/substring.sa new file mode 100644 index 0000000000..31e64b67b6 --- /dev/null +++ b/Task/Substring/Sather/substring.sa @@ -0,0 +1,10 @@ +class MAIN is + main is + s ::= "hello world shortest program"; + #OUT + s.substring(12, 5) + "\n"; + #OUT + s.substring(6) + "\n"; + #OUT + s.head( s.size - 1) + "\n"; + #OUT + s.substring(s.search('w'), 5) + "\n"; + #OUT + s.substring(s.search("ro"), 3) + "\n"; + end; +end; diff --git a/Task/Substring/Scala/substring.scala b/Task/Substring/Scala/substring.scala new file mode 100644 index 0000000000..73fb1b10f2 --- /dev/null +++ b/Task/Substring/Scala/substring.scala @@ -0,0 +1,9 @@ +val str = "The good life is one inspired by love and guided by knowledge." +val n = 21 +val m = 16 + +println(str.slice(n, n+m)) +println(str.slice(n, str.length)) +println(str.slice(0, str.length-1)) +println(str.slice(str.indexOf('l'), str.indexOf('l')+m)) +println(str.slice(str.indexOf("good"), str.indexOf("good")+m)) diff --git a/Task/Substring/Scheme/substring.ss b/Task/Substring/Scheme/substring.ss new file mode 100644 index 0000000000..f068b23131 --- /dev/null +++ b/Task/Substring/Scheme/substring.ss @@ -0,0 +1,18 @@ +(define s "Hello, world!") +(define n 5) +(define m (+ n 6)) + +(display (substring s n m)) +(newline) + +(display (substring s n)) +(newline) + +(display (substring s 0 (- (string-length s) 1))) +(newline) + +(display (substring s (string-index s #\o) m)) +(newline) + +(display (substring s (string-contains s "lo") m)) +(newline) diff --git a/Task/Substring/Sed/substring.sed b/Task/Substring/Sed/substring.sed new file mode 100644 index 0000000000..5f54e8a351 --- /dev/null +++ b/Task/Substring/Sed/substring.sed @@ -0,0 +1,11 @@ +# 2 chars starting from 3rd +$ echo string | sed -r 's/.{3}(.{2}).*/\1/' +in +# remove first 3 chars +echo string | sed -r 's/^.{3}//' +# delete last char +$ echo string | sed -r 's/.$//' +strin +# `r' with two following chars +$ echo string | sed -r 's/.*(r.{2}).*/\1/' +rin diff --git a/Task/Substring/Seed7/substring.seed7 b/Task/Substring/Seed7/substring.seed7 new file mode 100644 index 0000000000..5ae21d86b0 --- /dev/null +++ b/Task/Substring/Seed7/substring.seed7 @@ -0,0 +1,14 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const string: stri is "abcdefgh"; + const integer: N is 2; + const integer: M is 3; + begin + writeln(stri[N len M]); + writeln(stri[N ..]); + writeln(stri[.. pred(length(stri))]); + writeln(stri[pos(stri, 'c') len M]); + writeln(stri[pos(stri, "de") len M]); + end func; diff --git a/Task/Substring/Slate/substring.slate b/Task/Substring/Slate/substring.slate new file mode 100644 index 0000000000..5e1ce62c18 --- /dev/null +++ b/Task/Substring/Slate/substring.slate @@ -0,0 +1,8 @@ +#s := 'hello world shortest program'. +#n := 13. +#m := 4. +inform: (s copyFrom: n to: n + m). +inform: (s copyFrom: n). +inform: s allButLast. +inform: (s copyFrom: (s indexOf: $w) to: (s indexOf: $w) + m). +inform: (s copyFrom: (s indexOfSubSeq: 'ro') to: (s indexOfSubSeq: 'ro') + m). diff --git a/Task/Substring/Smalltalk/substring-1.st b/Task/Substring/Smalltalk/substring-1.st new file mode 100644 index 0000000000..5749447da5 --- /dev/null +++ b/Task/Substring/Smalltalk/substring-1.st @@ -0,0 +1,14 @@ +|s| +s := 'hello world shortest program'. + +(s copyFrom: 13 to: (13+4)) displayNl. +"4 is the length (5) - 1, since we need the index of the + last char we want, which is included" + +(s copyFrom: 7) displayNl. +(s allButLast) displayNl. + +(s copyFrom: ((s indexOfRegex: 'w') first) + to: ( ((s indexOfRegex: 'w') first) + 4) ) displayNl. +(s copyFrom: ((s indexOfRegex: 'ro') first) + to: ( ((s indexOfRegex: 'ro') first) + 2) ) displayNl. diff --git a/Task/Substring/Smalltalk/substring-2.st b/Task/Substring/Smalltalk/substring-2.st new file mode 100644 index 0000000000..5f5a55a2a9 --- /dev/null +++ b/Task/Substring/Smalltalk/substring-2.st @@ -0,0 +1,16 @@ +String extend [ + copyFrom: index length: nChar [ + ^ self copyFrom: index to: ( index + nChar - 1 ) + ] + copyFromRegex: regEx length: nChar [ + |i| + i := self indexOfRegex: regEx. + ^ self copyFrom: (i first) length: nChar + ] +]. + +"and show it simpler..." + +(s copyFrom: 13 length: 5) displayNl. +(s copyFromRegex: 'w' length: 5) displayNl. +(s copyFromRegex: 'ro' length: 3) displayNl. diff --git a/Task/Substring/TUSCRIPT/substring.tuscript b/Task/Substring/TUSCRIPT/substring.tuscript new file mode 100644 index 0000000000..383a585733 --- /dev/null +++ b/Task/Substring/TUSCRIPT/substring.tuscript @@ -0,0 +1,13 @@ +$$ MODE TUSCRIPT +string="abcdefgh", n=4,m=n+2 +substring=EXTRACT (string,#n,#m) + PRINT substring +substring=Extract (string,#n,0) + PRINT substring +substring=EXTRACT (string,0,-1) + PRINT substring +n=SEARCH (string,":d:"),m=n+2 +substring=EXTRACT (string,#n,#m) + PRINT substring +substring=EXTRACT (string,":{substring}:"|,0) + PRINT substring diff --git a/Task/Substring/Tcl/substring-1.tcl b/Task/Substring/Tcl/substring-1.tcl new file mode 100644 index 0000000000..2a41f13c01 --- /dev/null +++ b/Task/Substring/Tcl/substring-1.tcl @@ -0,0 +1,16 @@ +set str "abcdefgh" +set n 2 +set m 3 + +puts [string range $str $n [expr {$n+$m-1}]] +puts [string range $str $n end] +puts [string range $str 0 end-1] +# Because Tcl does substrings with a pair of indices, it is easier to express +# the last two parts of the task as a chained pair of [string range] operations. +# A maximally efficient solution would calculate the indices in full first. +puts [string range [string range $str [string first "d" $str] end] [expr {$m-1}]] +puts [string range [string range $str [string first "de" $str] end] [expr {$m-1}]] + +# From Tcl 8.5 onwards, these can be contracted somewhat. +puts [string range [string range $str [string first "d" $str] end] $m-1] +puts [string range [string range $str [string first "de" $str] end] $m-1] diff --git a/Task/Substring/Tcl/substring-2.tcl b/Task/Substring/Tcl/substring-2.tcl new file mode 100644 index 0000000000..60c35bebfb --- /dev/null +++ b/Task/Substring/Tcl/substring-2.tcl @@ -0,0 +1,19 @@ +# Define the substring operation, efficiently +proc ::substring {string start length} { + string range $string $start [expr {$start + $length - 1}] +} +# Plumb it into the language +set ops [namespace ensemble configure string -map] +dict set ops substr ::substring +namespace ensemble configure string -map $ops + +# Now show off by repeating the challenge! +set str "abcdefgh" +set n 2 +set m 3 + +puts [string substr $str $n $m] +puts [string range $str $n end] +puts [string range $str 0 end-1] +puts [string substr $str [string first "d" $str] $m] +puts [string substr $str [string first "de" $str] $m] diff --git a/Task/Substring/UNIX-Shell/substring-1.sh b/Task/Substring/UNIX-Shell/substring-1.sh new file mode 100644 index 0000000000..e4d7db11cd --- /dev/null +++ b/Task/Substring/UNIX-Shell/substring-1.sh @@ -0,0 +1,9 @@ +str="abc qrdef qrghi" +n=6 +m=3 + +expr "x$str" : "x.\{$n\}\(.\{1,$m\}\)" +expr "x$str" : "x.\{$n\}\(.*\)" +printf '%s\n' "${str%?}" +expr "r${str#*r}" : "\(.\{1,$m\}\)" +expr "qr${str#*qr}" : "\(.\{1,$m\}\)" diff --git a/Task/Substring/UNIX-Shell/substring-2.sh b/Task/Substring/UNIX-Shell/substring-2.sh new file mode 100644 index 0000000000..b54d704a12 --- /dev/null +++ b/Task/Substring/UNIX-Shell/substring-2.sh @@ -0,0 +1,17 @@ +str="abc qrdef qrghi" +n=6 +m=3 + +expr "x$str" : "x.\{$n\}\(.\{1,$m\}\)" +expr "x$str" : "x.\{$n\}\(.*\)" +expr "x$str" : "x\(.*\)." + +index() { + i=0 s=$1 + until test "x$s" = x || expr "x$s" : "x$2" >/dev/null; do + i=`expr $i + 1` s=`expr "x$s" : "x.\(.*\)"` + done + echo $i +} +expr "x$str" : "x.\{`index "$str" r`\}\(.\{1,$m\}\)" +expr "x$str" : "x.\{`index "$str" qr`\}\(.\{1,$m\}\)" diff --git a/Task/Substring/UNIX-Shell/substring-3.sh b/Task/Substring/UNIX-Shell/substring-3.sh new file mode 100644 index 0000000000..c715e65c13 --- /dev/null +++ b/Task/Substring/UNIX-Shell/substring-3.sh @@ -0,0 +1,8 @@ +#!/bin/zsh +string='abcdefghijk' +echo ${string:2:3} # Display 3 chars starting 2 chars in ie: 'cde' +echo ${string:2} # Starting 2 chars in, display to end of string +echo ${string:0:${#string}-1} # Whole string minus last character +echo ${string%?} # Shorter variant of the above +echo ${${string/*c/c}:0:3} # Display 3 chars starting with 'c' +echo ${${string/*cde/cde}:0:3} # Display 3 chars starting with 'cde' diff --git a/Task/Substring/UNIX-Shell/substring-4.sh b/Task/Substring/UNIX-Shell/substring-4.sh new file mode 100644 index 0000000000..82829648f8 --- /dev/null +++ b/Task/Substring/UNIX-Shell/substring-4.sh @@ -0,0 +1,10 @@ +#!/bin/sh +str=abcdefghijklmnopqrstuvwxyz +n=12 +m=5 + +printf %s "$str" | cut -c $n-`expr $n + $m - 1` +printf %s "$str" | cut -c $n- +printf '%s\n' "${str%?}" +printf q%s "${str#*q}" | cut -c 1-$m +printf pq%s "${str#*pq}" | cut -c 1-$m diff --git a/Task/Substring/Vala/substring.vala b/Task/Substring/Vala/substring.vala new file mode 100644 index 0000000000..2cee194f57 --- /dev/null +++ b/Task/Substring/Vala/substring.vala @@ -0,0 +1,15 @@ +string s = "Hello, world!"; +int n = 1; +int m = 3; +// start at n and go m letters +string s_n_to_m = s[n:n+m]; +// start at n and go to end +string s_n_to_end = s[n:s.length]; +// start at beginning and show all but last +string s_notlast = s[0:s.length - 1]; +// start from known letter and then go m letters +int index_of_l = s.index_of("l"); +string s_froml_for_m = s[index_of_l:index_of_l + m]; +// start from known substring then go m letters +int index_of_lo = s.index_of("lo"); +string s_fromlo_for_m = s[index_of_lo:index_of_lo + m]; diff --git a/Task/Substring/Yorick/substring.yorick b/Task/Substring/Yorick/substring.yorick new file mode 100644 index 0000000000..2c4444a475 --- /dev/null +++ b/Task/Substring/Yorick/substring.yorick @@ -0,0 +1,16 @@ +str = "abcdefgh"; +n = 2; +m = 3; + +// starting from n character in and of m length +write, strpart(str, n:n+m-1); +// starting from n character in, up to the end of the string +write, strpart(str, n:); +// whole string minus last character +write, strpart(str, :-1); +// starting from a known character within the string and of m length +match = strfind("d", str); +write, strpart(str, [match(1), match(1)+m]); +// starting from a known substring within the string and of m length +match = strfind("cd", str); +write, strpart(str, [match(1), match(1)+m]); diff --git a/Task/Subtractive-generator/0DESCRIPTION b/Task/Subtractive-generator/0DESCRIPTION new file mode 100644 index 0000000000..1077491747 --- /dev/null +++ b/Task/Subtractive-generator/0DESCRIPTION @@ -0,0 +1,33 @@ +A ''subtractive generator'' calculates a sequence of [[random number generator|random numbers]], where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is + +* r_n = r_{(n - i)} - r_{(n - j)} \pmod m + +for some fixed values of i, j and m, all positive integers. Supposing that i > j, then the state of this generator is the list of the previous numbers from r_{n - i} to r_{n - 1}. Many states generate uniform random integers from 0 to m - 1, but some states are bad. A state, filled with zeros, generates only zeros. If m is even, then a state, filled with even numbers, generates only even numbers. More generally, if f is a factor of m, then a state, filled with multiples of f, generates only multiples of f. + +All subtractive generators have some weaknesses. The formula correlates r_n, r_{(n - i)} and r_{(n - j)}; these three numbers are not independent, as true random numbers would be. Anyone who observes i consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of ''Freeciv'' ([http://svn.gna.org/viewcvs/freeciv/trunk/utility/rand.c?view=markup utility/rand.c]) and ''xpat2'' (src/testit2.c) knew another problem: the low bits are less random than the high bits. + +The subtractive generator has a better reputation than the [[linear congruential generator]], perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of r_{(n - i)} - r_{(n - j)} is always between -m and m, so a program only needs to add m to negative numbers. + +The choice of i and j affects the period of the generator. A popular choice is i = 55 and j = 24, so the formula is + +* r_n = r_{(n - 55)} - r_{(n - 24)} \pmod m + +The subtractive generator from ''xpat2'' uses + +* r_n = r_{(n - 55)} - r_{(n - 24)} \pmod{10^9} + +The implementation is by J. Bentley and comes from program_tools/universal.c of [ftp://dimacs.rutgers.edu/pub/netflow/ the DIMACS (netflow) archive] at Rutgers University. It credits Knuth, [[wp:The Art of Computer Programming|''TAOCP'']], Volume 2, Section 3.2.2 (Algorithm A). + +Bentley uses this clever algorithm to seed the generator. + +# Start with a single seed in range 0 to 10^9 - 1. +# Set s_0 = seed and s_1 = 1. The inclusion of s_1 = 1 avoids some bad states (like all zeros, or all multiples of 10). +# Compute s_2, s_3, ..., s_{54} using the subtractive formula s_n = s_{(n - 2)} - s_{(n - 1)} \pmod{10^9}. +# Reorder these 55 values so r_0 = s_{34}, r_1 = s_{13}, r_2 = s_{47}, ..., r_n = s_{(34 * (n + 1) \pmod{55})}. +#* This is the same order as s_0 = r_{54}, s_1 = r_{33}, s_2 = r_{12}, ..., s_n = r_{((34 * n) - 1 \pmod{55})}. +#* This rearrangement exploits how 34 and 55 are relatively prime. +# Compute the next 165 values r_{55} to r_{219}. Store the last 55 values. + +This generator yields the sequence r_{220}, r_{221}, r_{222} and so on. For example, if the seed is 292929, then the sequence begins with r_{220} = 467478574, r_{221} = 512932792, r_{222} = 539453717. By starting at r_{220}, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next r_n. Any array or list would work; a [[ring buffer]] is ideal but not necessary. + +Implement a subtractive generator that replicates the sequences from ''xpat2''. diff --git a/Task/Subtractive-generator/1META.yaml b/Task/Subtractive-generator/1META.yaml new file mode 100644 index 0000000000..2ba437190b --- /dev/null +++ b/Task/Subtractive-generator/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Randomness diff --git a/Task/Subtractive-generator/Ada/subtractive-generator-1.ada b/Task/Subtractive-generator/Ada/subtractive-generator-1.ada new file mode 100644 index 0000000000..9e05313b9c --- /dev/null +++ b/Task/Subtractive-generator/Ada/subtractive-generator-1.ada @@ -0,0 +1,11 @@ +package Subtractive_Generator is + type State is private; + procedure Initialize (Generator : in out State; Seed : Natural); + procedure Next (Generator : in out State; N : out Natural); +private + type Number_Array is array (Natural range <>) of Natural; + type State is record + R : Number_Array (0 .. 54); + Last : Natural; + end record; +end Subtractive_Generator; diff --git a/Task/Subtractive-generator/Ada/subtractive-generator-2.ada b/Task/Subtractive-generator/Ada/subtractive-generator-2.ada new file mode 100644 index 0000000000..ab2374c80a --- /dev/null +++ b/Task/Subtractive-generator/Ada/subtractive-generator-2.ada @@ -0,0 +1,33 @@ +package body Subtractive_Generator is + + procedure Initialize (Generator : in out State; Seed : Natural) is + S : Number_Array (0 .. 1); + I : Natural := 0; + J : Natural := 1; + begin + S (0) := Seed; + S (1) := 1; + Generator.R (54) := S (0); + Generator.R (33) := S (1); + for N in 2 .. Generator.R'Last loop + S (I) := (S (I) - S (J)) mod 10 ** 9; + Generator.R ((34 * N - 1) mod 55) := S (I); + I := (I + 1) mod 2; + J := (J + 1) mod 2; + end loop; + Generator.Last := 54; + for I in 1 .. 165 loop + Subtractive_Generator.Next (Generator => Generator, N => J); + end loop; + end Initialize; + + procedure Next (Generator : in out State; N : out Natural) is + begin + Generator.Last := (Generator.Last + 1) mod 55; + Generator.R (Generator.Last) := + (Generator.R (Generator.Last) + - Generator.R ((Generator.Last - 24) mod 55)) mod 10 ** 9; + N := Generator.R (Generator.Last); + end Next; + +end Subtractive_Generator; diff --git a/Task/Subtractive-generator/Ada/subtractive-generator-3.ada b/Task/Subtractive-generator/Ada/subtractive-generator-3.ada new file mode 100644 index 0000000000..1208de6f0f --- /dev/null +++ b/Task/Subtractive-generator/Ada/subtractive-generator-3.ada @@ -0,0 +1,14 @@ +with Ada.Text_IO; +with Subtractive_Generator; + +procedure Main is + Random : Subtractive_Generator.State; + N : Natural; +begin + Subtractive_Generator.Initialize (Generator => Random, + Seed => 292929); + for I in 220 .. 222 loop + Subtractive_Generator.Next (Generator => Random, N => N); + Ada.Text_IO.Put_Line (Integer'Image (I) & ":" & Integer'Image (N)); + end loop; +end Main; diff --git a/Task/Subtractive-generator/BBC-BASIC/subtractive-generator.bbc b/Task/Subtractive-generator/BBC-BASIC/subtractive-generator.bbc new file mode 100644 index 0000000000..c6fab457e0 --- /dev/null +++ b/Task/Subtractive-generator/BBC-BASIC/subtractive-generator.bbc @@ -0,0 +1,26 @@ + dummy% = FNsubrand(292929) + FOR i% = 1 TO 10 + PRINT FNsubrand(0) + NEXT + END + + DEF FNsubrand(s%) + PRIVATE r%(), p% : DIM r%(54) + IF s% = 0 THEN + p% = (p% + 1) MOD 55 + r%(p%) = r%(p%) - r%((p% + 31) MOD 55) + IF r%(p%) < 0 r%(p%) += 10^9 + = r%(p%) + ENDIF + LOCAL i% + r%(54) = s% : r%(33) = 1 + p% = 12 + FOR i% = 2 TO 54 + r%(p%) = r%((p%+42) MOD 55) - r%((p%+21) MOD 55) + IF r%(p%) < 0 r%(p%) += 10^9 + p% = (p% + 34) MOD 55 + NEXT + FOR i% = 55 TO 219 + IF FNsubrand(0) + NEXT + = 0 diff --git a/Task/Subtractive-generator/Bracmat/subtractive-generator.bracmat b/Task/Subtractive-generator/Bracmat/subtractive-generator.bracmat new file mode 100644 index 0000000000..2abcb3afda --- /dev/null +++ b/Task/Subtractive-generator/Bracmat/subtractive-generator.bracmat @@ -0,0 +1,52 @@ +1000000000:?MOD; +tbl$(state,55); +0:?si:?sj; + +(subrand-seed= + i,j,p2 +. 1:?p2 + & mod$(!arg,!MOD):?(0$?state) + & 1:?i + & 21:?j + & whl + ' ( !i:<55 + & (!j:~<55&!j+-55:?j|) + & !p2:?(!j$?state) + & ( !arg+-1*!p2:?p2:<0 + & !p2+!MOD:?p2 + | + ) + & !(!j$state):?arg + & !i+1:?i + & !j+21:?j + ) + & 0:?s1:?i + & 24:?sj + & whl + ' ( !i:<165 + & subrand$ + & !i+1:?i + )); + +(subrand= + x +. (!si:!sj&subrand-seed$0|) + & (!si:>0&!si+-1|54):?si + & (!sj:>0&!sj+-1|54):?sj + & ( !(!si$state)+-1*!(!sj$state):?x:<0 + & !x+!MOD:?x + | + ) + & !x:?(!si$?state)); + +(Main= + i +. subrand-seed$292929 + & 0:?i + & whl + ' ( !i:<10 + & out$(subrand$) + & !i+1:?i + )); + +Main$; diff --git a/Task/Subtractive-generator/C++/subtractive-generator.cpp b/Task/Subtractive-generator/C++/subtractive-generator.cpp new file mode 100644 index 0000000000..8e8150a66e --- /dev/null +++ b/Task/Subtractive-generator/C++/subtractive-generator.cpp @@ -0,0 +1,63 @@ +// written for clarity not efficiency. + +#include +using std::cout; +using std::endl; + +#include +#include + +class Subtractive_generator { +private: + static const int param_i = 55; + static const int param_j = 24; + static const int initial_load = 219; + static const int mod = 1e9; + boost::circular_buffer r; +public: + Subtractive_generator(int seed); + int next(); + int operator()(){return next();} +}; + +Subtractive_generator::Subtractive_generator(int seed) +:r(param_i) +{ + boost::array s; + s[0] = seed; + s[1] = 1; + for(int n = 2; n < param_i; ++n){ + int t = s[n-2]-s[n-1]; + if (t < 0 ) t+= mod; + s[n] = t; + } + + for(int n = 0; n < param_i; ++n){ + int i = (34 * (n+1)) % param_i; + r.push_back(s[i]); + } + for(int n = param_i; n <= initial_load; ++n) next(); +} + +int Subtractive_generator::next() +{ + int t = r[0]-r[31]; + if (t < 0) t += mod; + r.push_back(t); + return r[param_i-1]; +} + +int main() +{ + Subtractive_generator rg(292929); + + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + cout << "result = " << rg() << endl; + + return 0; +} diff --git a/Task/Subtractive-generator/C/subtractive-generator.c b/Task/Subtractive-generator/C/subtractive-generator.c new file mode 100644 index 0000000000..a5f3caccd1 --- /dev/null +++ b/Task/Subtractive-generator/C/subtractive-generator.c @@ -0,0 +1,43 @@ +#include + +#define MOD 1000000000 +int state[55], si = 0, sj = 0; + +int subrand(); + +void subrand_seed(int p1) +{ + int i, j, p2 = 1; + + state[0] = p1 % MOD; + for (i = 1, j = 21; i < 55; i++, j += 21) { + if (j >= 55) j -= 55; + state[j] = p2; + if ((p2 = p1 - p2) < 0) p2 += MOD; + p1 = state[j]; + } + si = 0; + sj = 24; + for (i = 0; i < 165; i++) subrand(); +} + +int subrand() +{ + int x; + if (si == sj) subrand_seed(0); + + if (!si--) si = 54; + if (!sj--) sj = 54; + if ((x = state[si] - state[sj]) < 0) x += MOD; + + return state[si] = x; +} + +int main() +{ + subrand_seed(292929); + int i; + for (i = 0; i < 10; i++) printf("%d\n", subrand()); + + return 0; +} diff --git a/Task/Subtractive-generator/Common-Lisp/subtractive-generator.lisp b/Task/Subtractive-generator/Common-Lisp/subtractive-generator.lisp new file mode 100644 index 0000000000..0513adaab9 --- /dev/null +++ b/Task/Subtractive-generator/Common-Lisp/subtractive-generator.lisp @@ -0,0 +1,23 @@ +(defun sub-rand (state) + (let ((x (last state)) (y (last state 25))) + ;; I take "circular buffer" very seriously (until some guru + ;; points out it's utterly wrong thing to do) + (setf (cdr x) state) + (lambda () (setf x (cdr x) + y (cdr y) + (car x) (mod (- (car x) (car y)) (expt 10 9)))))) + +;; returns an RNG with Bentley seeding +(defun bentley-clever (seed) + (let ((s (list 1 seed)) f) + (dotimes (i 53) + (push (mod (- (cadr s) (car s)) (expt 10 9)) s)) + (setf f (sub-rand + (loop for i from 1 to 55 collect + (elt s (- 54 (mod (* 34 i) 55)))))) + (dotimes (x 165) (funcall f)) + f)) + +;; test it (output same as everyone else's) +(let ((f (bentley-clever 292929))) + (dotimes (x 10) (format t "~a~%" (funcall f)))) diff --git a/Task/Subtractive-generator/D/subtractive-generator.d b/Task/Subtractive-generator/D/subtractive-generator.d new file mode 100644 index 0000000000..c543e5e7b8 --- /dev/null +++ b/Task/Subtractive-generator/D/subtractive-generator.d @@ -0,0 +1,52 @@ +import std.stdio; + +struct Subtractive { + enum MOD = 1_000_000_000; + private int[55] state; + private int si, sj; + + this(in int p1) pure nothrow { + subrandSeed(p1); + } + + void subrandSeed(int p1) pure nothrow { + int p2 = 1; + + state[0] = p1 % MOD; + for (int i = 1, j = 21; i < 55; i++, j += 21) { + if (j >= 55) + j -= 55; + state[j] = p2; + if ((p2 = p1 - p2) < 0) + p2 += MOD; + p1 = state[j]; + } + + si = 0; + sj = 24; + foreach (i; 0 .. 165) + subrand(); + } + + int subrand() pure nothrow { + if (si == sj) + subrandSeed(0); + + if (!si--) + si = 54; + if (!sj--) + sj = 54; + + int x = state[si] - state[sj]; + if (x < 0) + x += MOD; + + return state[si] = x; + } +} + +void main() { + auto gen = Subtractive(292_929); + foreach (i; 0 .. 10) + writeln(gen.subrand()); +} diff --git a/Task/Subtractive-generator/Go/subtractive-generator.go b/Task/Subtractive-generator/Go/subtractive-generator.go new file mode 100644 index 0000000000..fe87cbc1c7 --- /dev/null +++ b/Task/Subtractive-generator/Go/subtractive-generator.go @@ -0,0 +1,100 @@ +package main + +import ( + "fmt" + "os" +) + +// A fairly close port of the Bentley code, but parameterized to better +// conform to the algorithm description in the task, which didn't assume +// constants for i, j, m, and seed. also parameterized here are k, +// the reordering factor, and s, the number of intial numbers to discard, +// as these are dependant on i. +func newSG(i, j, k, s, m, seed int) func() int { + // check parameters for range and mutual consistency + assert(i > 0, "i must be > 0") + assert(j > 0, "j must be > 0") + assert(i > j, "i must be > j") + assert(k > 0, "k must be > 0") + p, q := i, k + if p < q { + p, q = q, p + } + for q > 0 { + p, q = q, p%q + } + assert(p == 1, "k, i must be relatively prime") + assert(s >= i, "s must be >= i") + assert(m > 0, "m must be > 0") + assert(seed >= 0, "seed must be >= 0") + // variables for closure f + arr := make([]int, i) + a := 0 + b := j + // f is Bently RNG lprand + f := func() int { + if a == 0 { + a = i + } + a-- + if b == 0 { + b = i + } + b-- + t := arr[a] - arr[b] + if t < 0 { + t += m + } + arr[a] = t + return t + } + // Bentley seed algorithm sprand + last := seed + arr[0] = last + next := 1 + for i0 := 1; i0 < i; i0++ { + ii := k * i0 % i + arr[ii] = next + next = last - next + if next < 0 { + next += m + } + last = arr[ii] + } + for i0 := i; i0 < s; i0++ { + f() + } + // return the fully initialized RNG + return f +} + +func assert(p bool, m string) { + if !p { + fmt.Println(m) + os.Exit(1) + } +} + +func main() { + // 1st test case included in program_tools/universal.c. + // (2nd test case fails. A single digit is missing, indicating a typo.) + ptTest(0, 1, []int{921674862, 250065336, 377506581}) + + // reproduce 3 values given in task description + skip := 220 + sg := newSG(55, 24, 21, skip, 1e9, 292929) + for n := skip; n <= 222; n++ { + fmt.Printf("r(%d) = %d\n", n, sg()) + } +} + +func ptTest(nd, s int, rs []int) { + sg := newSG(55, 24, 21, 220+nd, 1e9, s) + for _, r := range rs { + a := sg() + if r != a { + fmt.Println("Fail") + os.Exit(1) + } + } +} diff --git a/Task/Subtractive-generator/Haskell/subtractive-generator.hs b/Task/Subtractive-generator/Haskell/subtractive-generator.hs new file mode 100644 index 0000000000..713d4e4a68 --- /dev/null +++ b/Task/Subtractive-generator/Haskell/subtractive-generator.hs @@ -0,0 +1,8 @@ +subtractgen seed = drop 220 out where + out = mmod $ r ++ zipWith (-) out (drop 31 out) where + r = take 55 $ shuffle $ cycle $ take 55 s + shuffle x = head xx:shuffle xx where xx = drop 34 x + s = mmod $ seed:1:zipWith (-) s (tail s) + mmod = map (`mod` 10^9) + +main = mapM_ print $ take 10 $ subtractgen 292929 diff --git a/Task/Subtractive-generator/Icon/subtractive-generator.icon b/Task/Subtractive-generator/Icon/subtractive-generator.icon new file mode 100644 index 0000000000..9f93960feb --- /dev/null +++ b/Task/Subtractive-generator/Icon/subtractive-generator.icon @@ -0,0 +1,26 @@ +procedure main() + every 1 to 10 do + write(rand_sub(292929)) +end + +procedure rand_sub(x) +static ring,m + if /ring then { + m := 10^9 + every (seed | ring) := list(55) + seed[1] := \x | ?(m-1) + seed[2] := 1 + every seed[n := 3 to 55] := (seed[n-2]-seed[n-1])%m + every ring[(n := 0 to 54) + 1] := seed[1 + (34 * (n + 1)%55)] + every n := *ring to 219 do { + ring[1] -:= ring[-24] + ring[1] %= m + put(ring,get(ring)) + } + } + ring[1] -:= ring[-24] + ring[1] %:= m + if ring[1] < 0 then ring[1] +:= m + put(ring,get(ring)) + return ring[-1] +end diff --git a/Task/Subtractive-generator/J/subtractive-generator-1.j b/Task/Subtractive-generator/J/subtractive-generator-1.j new file mode 100644 index 0000000000..d60052cf67 --- /dev/null +++ b/Task/Subtractive-generator/J/subtractive-generator-1.j @@ -0,0 +1,17 @@ +came_from_locale_sg_=: coname'' +cocurrent'sg' NB. install the state of rng sg into locale sg + +SEED=: 292929 +'I J M first_Bentley_number B2'=: 55 24 1e9 34 165 +SG=: 1 : 'M&|@:-/@:(m&{)' +r=: (I|(first_Bentley_number*>:i.I)) { (, _2 _1 SG)^:(I-2) 1,~SEED + +sg=: 3 : 0 +t=. (, (-I,J)SG)^:y r +r=: y }. t +t {.~ -y +) +discard=. sg B2 + +cocurrent came_from_locale NB. return to previous locale +sg=: sg_sg_ NB. make a local name for sg in locale sg diff --git a/Task/Subtractive-generator/J/subtractive-generator-2.j b/Task/Subtractive-generator/J/subtractive-generator-2.j new file mode 100644 index 0000000000..6fda0d3e89 --- /dev/null +++ b/Task/Subtractive-generator/J/subtractive-generator-2.j @@ -0,0 +1,6 @@ +$ jconsole + load'sg.ijs' + sg 2 +467478574 512932792 + sg 4 +539453717 20349702 615542081 378707948 diff --git a/Task/Subtractive-generator/Mathematica/subtractive-generator.math b/Task/Subtractive-generator/Mathematica/subtractive-generator.math new file mode 100644 index 0000000000..f54a44d163 --- /dev/null +++ b/Task/Subtractive-generator/Mathematica/subtractive-generator.math @@ -0,0 +1,9 @@ +initialize[n_] := + Module[{buffer}, + buffer = + Join[Nest[Flatten@{#, Mod[Subtract @@ #[[-2 ;;]], 10^9]} &, {n, 1}, + 53][[1 + Mod[34 Range@54, 55]]], {n}]; + Nest[nextValue, buffer, 165]] + + nextValue[buffer_] := + Flatten@{Rest@buffer, Mod[Subtract @@ buffer[[{1, 32}]], 10^9]} diff --git a/Task/Subtractive-generator/OCaml/subtractive-generator.ocaml b/Task/Subtractive-generator/OCaml/subtractive-generator.ocaml new file mode 100644 index 0000000000..8ff3427d51 --- /dev/null +++ b/Task/Subtractive-generator/OCaml/subtractive-generator.ocaml @@ -0,0 +1,34 @@ +let _mod = 1_000_000_000 +let state = Array.create 55 0 +let si = ref 0 +let sj = ref 0 + +let rec subrand_seed _p1 = + let p1 = ref _p1 in + let p2 = ref 1 in + state.(0) <- !p1 mod _mod; + let j = ref 21 in + for i = 1 to pred 55 do + if !j >= 55 then j := !j - 55; + state.(!j) <- !p2; + p2 := !p1 - !p2; + if !p2 < 0 then p2 := !p2 + _mod; + p1 := state.(!j); + j := !j + 21; + done; + si := 0; + sj := 24; + for i = 0 to pred 165 do ignore (subrand()) done + +and subrand() = + if !si = !sj then subrand_seed 0; + decr si; if !si < 0 then si := 54; + decr sj; if !sj < 0 then sj := 54; + let x = state.(!si) - state.(!sj) in + let x = if x < 0 then x + _mod else x in + state.(!si) <- x; + (x) + +let () = + subrand_seed 292929; + for i = 1 to 10 do Printf.printf "%d\n" (subrand()) done diff --git a/Task/Subtractive-generator/PARI-GP/subtractive-generator.pari b/Task/Subtractive-generator/PARI-GP/subtractive-generator.pari new file mode 100644 index 0000000000..83c6622b5b --- /dev/null +++ b/Task/Subtractive-generator/PARI-GP/subtractive-generator.pari @@ -0,0 +1,2 @@ +sgv=vector(55,i,random(10^9));sgi=1; +sg()=sgv[sgi=sgi%55+1]=(sgv[sgi]-sgv[(sgi+30)%55+1])%10^9 diff --git a/Task/Subtractive-generator/PL-I/subtractive-generator.pli b/Task/Subtractive-generator/PL-I/subtractive-generator.pli new file mode 100644 index 0000000000..cac7ea2674 --- /dev/null +++ b/Task/Subtractive-generator/PL-I/subtractive-generator.pli @@ -0,0 +1,31 @@ +subtractive_generator: procedure options (main); + + declare (r, s) (0:54) fixed binary (31); + declare (i, n, seed) fixed binary (31); + + /* Bentley's initialization */ + seed = 292929; + s(0) = seed; s(1) = 1; + + /* Compute s2,s3,...,s54 using the subtractive formula sn = s(n-2) - s(n-1)(mod 10**9). */ + do n = 2 to hbound(s,1); + s(n) = mod ( s(n-2) - s(n-1), 1000000000); + end; + + /* Rearrange initial values. */ + do n = 0 to hbound(r,1); + r(n) = s( mod(34*(n+1), 55)); + end; + + do n = 55 to 219; + i = mod (n, 55); + r(i) = mod ( r(mod(n-55, 55)) - r(mod(n-24, 55)), 1000000000); + end; + + do n = 220 to 235; + i = mod(n, 55); + r(i) = mod ( r(mod(n-55, 55)) - r(mod(n-24, 55)), 1000000000); + put skip list (r(i)); + end; + +end subtractive_generator; diff --git a/Task/Subtractive-generator/Perl-6/subtractive-generator.pl6 b/Task/Subtractive-generator/Perl-6/subtractive-generator.pl6 new file mode 100644 index 0000000000..aa837aa3b5 --- /dev/null +++ b/Task/Subtractive-generator/Perl-6/subtractive-generator.pl6 @@ -0,0 +1,17 @@ +sub bentley_clever($seed) { + constant $mod = 1_000_000_000; + my @seeds = ($seed % $mod, 1, (* - *) % $mod ... *)[^55]; + my @state = @seeds[ 34, (* + 34 ) % 55 ... 0 ]; + + sub subrand() { + push @state, (my $x = (@state.shift - @state[*-24]) % $mod); + $x; + } + + subrand for 55 .. 219; + + &subrand ... *; +} + +my @sr := bentley_clever(292929); +.say for @sr[^10]; diff --git a/Task/Subtractive-generator/Perl/subtractive-generator.pl b/Task/Subtractive-generator/Perl/subtractive-generator.pl new file mode 100644 index 0000000000..35eea991c6 --- /dev/null +++ b/Task/Subtractive-generator/Perl/subtractive-generator.pl @@ -0,0 +1,26 @@ +use 5.10.0; +use strict; + +{ # bracket state data into a lexical scope + my @state; + my $mod = 1_000_000_000; + + sub bentley_clever { + my @s = ( shift() % $mod, 1); + push @s, ($s[-2] - $s[-1]) % $mod while @s < 55; + @state = map($s[(34 + 34 * $_) % 55], 0 .. 54); + subrand() for (55 .. 219); + } + + sub subrand() + { + bentley_clever(0) unless @state; # just incase + + my $x = (shift(@state) - $state[-24]) % $mod; + push @state, $x; + $x; + } +} + +bentley_clever(292929); +say subrand() for (1 .. 10); diff --git a/Task/Subtractive-generator/PicoLisp/subtractive-generator-1.l b/Task/Subtractive-generator/PicoLisp/subtractive-generator-1.l new file mode 100644 index 0000000000..dfcd92f31c --- /dev/null +++ b/Task/Subtractive-generator/PicoLisp/subtractive-generator-1.l @@ -0,0 +1,18 @@ +(setq + *Bentley (apply circ (need 55)) + *Bentley2 (nth *Bentley 32) ) + +(de subRandSeed (S) + (let (N 1 P (nth *Bentley 55)) + (set P S) + (do 54 + (set (setq P (nth P 35)) N) + (when (lt0 (setq N (- S N))) + (inc 'N 1000000000) ) + (setq S (car P)) ) ) + (do 165 (subRand)) ) + +(de subRand () + (when (lt0 (dec *Bentley (pop '*Bentley2))) + (inc *Bentley 1000000000) ) + (pop '*Bentley) ) diff --git a/Task/Subtractive-generator/PicoLisp/subtractive-generator-2.l b/Task/Subtractive-generator/PicoLisp/subtractive-generator-2.l new file mode 100644 index 0000000000..abc4b3b4ee --- /dev/null +++ b/Task/Subtractive-generator/PicoLisp/subtractive-generator-2.l @@ -0,0 +1,2 @@ +(subRandSeed 292929) +(do 7 (println (subRand))) diff --git a/Task/Subtractive-generator/Python/subtractive-generator.py b/Task/Subtractive-generator/Python/subtractive-generator.py new file mode 100644 index 0000000000..18af2a1622 --- /dev/null +++ b/Task/Subtractive-generator/Python/subtractive-generator.py @@ -0,0 +1,42 @@ +import collections +s= collections.deque(maxlen=55) +# Start with a single seed in range 0 to 10**9 - 1. +seed = 292929 + +# Set s0 = seed and s1 = 1. +# The inclusion of s1 = 1 avoids some bad states +# (like all zeros, or all multiples of 10). +s.append(seed) +s.append(1) + +# Compute s2,s3,...,s54 using the subtractive formula +# sn = s(n - 2) - s(n - 1)(mod 10**9). +for n in xrange(2, 55): + s.append((s[n-2] - s[n-1]) % 10**9) + +# Reorder these 55 values so r0 = s34, r1 = s13, r2 = s47, ..., +# rn = s(34 * (n + 1)(mod 55)). + +r = collections.deque(maxlen=55) +for n in xrange(55): + i = (34 * (n+1)) % 55 + r.append(s[i]) +# This is the same order as s0 = r54, s1 = r33, s2 = r12, ..., +# sn = r((34 * n) - 1(mod 55)). +# This rearrangement exploits how 34 and 55 are relatively prime. +# Compute the next 165 values r55 to r219. Store the last 55 values. + + +def getnextr(): + """get next random number""" + r.append((r[0]-r[31])%10**9) + return r[54] + +# rn = r(n - 55) - r(n - 24)(mod 10**9) for n >= 55 +for n in xrange(219 - 54): + getnextr() + +# now fully initilised +# print first five numbers +for i in xrange(5): + print "result = ", getnextr() diff --git a/Task/Subtractive-generator/REXX/subtractive-generator.rexx b/Task/Subtractive-generator/REXX/subtractive-generator.rexx new file mode 100644 index 0000000000..01105e5289 --- /dev/null +++ b/Task/Subtractive-generator/REXX/subtractive-generator.rexx @@ -0,0 +1,23 @@ +/*REXX pgm uses a subtractive generator, creates a seq of random numbers*/ +numeric digits 20; billion = 10**9; s.0 = 292929; s.1 = 1 +cI = 55; cJ = 24; cP = 34 + do i=2 to cI-1 + s.i=mod(s(i-2)-s(i-1),billion) + end /*i*/ + do j=0 to cI-1 + r.j = s(mod(cP*(j+1),cI)) + end /*j*/ + +m=219; do k=cI to m; x=k//cI + r.x = mod(r(mod(k-cI,cI)) - r(mod(k-cJ,cI)),billion) + end /*m*/ + +t=235; do n=m+1 to t; y=n//cI + r.y = mod(r(mod(n-cI,cI)) - r(mod(n-cJ,cI)),billion) + say right(r.y,40) + end /*n*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +r: parse arg _; return r._ +s: parse arg _; return s._ +mod: procedure; arg a,b; return ((a // b) + b) // b diff --git a/Task/Subtractive-generator/Ruby/subtractive-generator.rb b/Task/Subtractive-generator/Ruby/subtractive-generator.rb new file mode 100644 index 0000000000..3aa7d263c1 --- /dev/null +++ b/Task/Subtractive-generator/Ruby/subtractive-generator.rb @@ -0,0 +1,37 @@ +# SubRandom is a subtractive random number generator which generates +# the same sequences as Bentley's generator, as used in xpat2. +class SubRandom + # The original seed of this generator. + attr_reader :seed + + # Creates a SubRandom generator with the given _seed_. + # The _seed_ must be an integer from 0 to 999_999_999. + def initialize(seed = Kernel.rand(1_000_000_000)) + (0..999_999_999).include? seed or + raise ArgumentError, "seed not in 0..999_999_999" + + # @state = 55 elements. + ary = [seed, 1] + 53.times { ary << ary[-2] - ary[-1] } + @state = [] + 34.step(1870, 34) {|i| @state << ary[i % 55] } + + 220.times { rand } # Discard first 220 elements of sequence. + + @seed = seed # Save original seed. + end + + # Duplicates internal state so SubRandom#dup never shares state. + def initialize_copy(orig) + @state = @state.dup + end + + # Returns the next random integer, from 0 to 999_999_999. + def rand + @state << (@state[-55] - @state[-24]) % 1_000_000_000 + @state.shift + end +end + +rng = SubRandom.new(292929) +p (1..3).map { rng.rand } diff --git a/Task/Subtractive-generator/Tcl/subtractive-generator.tcl b/Task/Subtractive-generator/Tcl/subtractive-generator.tcl new file mode 100644 index 0000000000..310ef24f95 --- /dev/null +++ b/Task/Subtractive-generator/Tcl/subtractive-generator.tcl @@ -0,0 +1,35 @@ +package require Tcl 8.5 +namespace eval subrand { + variable mod 1000000000 state [lrepeat 55 0] si 0 sj 0 + + proc seed p1 { + global subrand::mod subrand::state subrand::si subrand::sj + set p2 1 + lset state 0 [expr {$p1 % $mod}] + for {set i 1; set j 21} {$i < 55} {incr i; incr j 21} { + if {$j >= 55} {incr j -55} + lset state $j $p2 + if {[set p2 [expr {$p1 - $p2}]] < 0} {incr p2 $mod} + set p1 [lindex $state $j] + } + set si 0 + set sj 24 + for {set i 0} {$i < 165} {incr i} { gen } + } + + proc gen {} { + global subrand::mod subrand::state subrand::si subrand::sj + if {$si == $sj} {seed 0} + if {[incr si -1] < 0} {set si 54} + if {[incr sj -1] < 0} {set sj 54} + set x [expr {[lindex $state $si] - [lindex $state $sj]}] + if {$x < 0} {incr x $mod} + lset state $si $x + return $x + } +} + +subrand::seed 292929 +for {set i 0} {$i < 10} {incr i} { + puts [subrand::gen] +} diff --git a/Task/Sudoku/0DESCRIPTION b/Task/Sudoku/0DESCRIPTION new file mode 100644 index 0000000000..4bf99beaa5 --- /dev/null +++ b/Task/Sudoku/0DESCRIPTION @@ -0,0 +1 @@ +Solve a partially filled-in normal 9x9 [[wp:Sudoku|Sudoku]] grid and display the result in a human-readable format. [[wp:Algorithmics_of_sudoku|Algorithmics of Sudoku]] may help implement this. diff --git a/Task/Sudoku/1META.yaml b/Task/Sudoku/1META.yaml new file mode 100644 index 0000000000..a2413d963b --- /dev/null +++ b/Task/Sudoku/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Games diff --git a/Task/Sudoku/ALGOL-68/sudoku.alg b/Task/Sudoku/ALGOL-68/sudoku.alg new file mode 100644 index 0000000000..9f526dfbf9 --- /dev/null +++ b/Task/Sudoku/ALGOL-68/sudoku.alg @@ -0,0 +1,95 @@ +MODE AVAIL = [9]BOOL; +MODE BOX = [3, 3]CHAR; + +FORMAT row fmt = $"|"3(" "3(g" ")"|")l$; +FORMAT line = $"+"3(7"-","+")l$; +FORMAT puzzle fmt = $f(line)3(3(f(row fmt))f(line))$; + +AVAIL gen full = (TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE); + +OP REPR = (AVAIL avail)STRING: ( + STRING out := ""; + FOR i FROM LWB avail TO UPB avail DO + IF avail[i] THEN out +:= REPR(ABS "0" + i) FI + OD; + out +); + +CHAR empty = "_"; + +OP -:= = (REF AVAIL set, CHAR index)VOID: ( + set[ABS index - ABS "0"]:=FALSE +); + +# these two functions assume that the number has not already been found # +PROC avail slice = (REF[]CHAR slice, REF AVAIL available)REF AVAIL:( + FOR ele FROM LWB slice TO UPB slice DO + IF slice[ele] /= empty THEN available-:=slice[ele] FI + OD; + available +); + +PROC avail box = (INT x, y, REF AVAIL available)REF AVAIL:( + # x designates row, y designates column # + # get a base index for the boxes # + INT bx := x - (x-1) MOD 3; + INT by := y - (y-1) MOD 3; + REF BOX box = puzzle[bx:bx+2, by:by+2]; + FOR i FROM LWB box TO UPB box DO + FOR j FROM 2 LWB box TO 2 UPB box DO + IF box[i, j] /= empty THEN available-:=box[i, j] FI + OD + OD; + available +); + +[9, 9]CHAR puzzle; +PROC solve = ([,]CHAR in puzzle)VOID:( + puzzle := in puzzle; + TO UPB puzzle UP 2 DO + BOOL done := TRUE; + FOR i FROM LWB puzzle TO UPB puzzle DO + FOR j FROM 2 LWB puzzle TO 2 UPB puzzle DO + CHAR ele := puzzle[i, j]; + IF ele = empty THEN + # poke at the elements that are "_" # + AVAIL remaining := avail box(i, j, + avail slice(puzzle[i, ], + avail slice(puzzle[, j], + LOC AVAIL := gen full))); + STRING s = REPR remaining; + IF UPB s = 1 THEN puzzle[i, j] := s[LWB s] + ELSE done := FALSE + FI + FI + OD + OD; + IF done THEN break FI + OD; +break: + # write out completed puzzle # + printf(($gl$, "Completed puzzle:")); + printf((puzzle fmt, puzzle)) +); +main:( + solve(("394__267_", + "___3__4__", + "5__69__2_", + "_45___9__", + "6_______7", + "__7___58_", + "_1__67__8", + "__9__8___", + "_264__735")) +CO # note: This codes/algorithm does not [yet] solve: # + solve(("9__2__5__", + "_4__6__3_", + "__3_____6", + "___9__2__", + "____5__8_", + "__7__4__3", + "7_____1__", + "_5__2__4_", + "__1__6__9")) +END CO +) diff --git a/Task/Sudoku/AutoHotkey/sudoku.ahk b/Task/Sudoku/AutoHotkey/sudoku.ahk new file mode 100644 index 0000000000..fd27379203 --- /dev/null +++ b/Task/Sudoku/AutoHotkey/sudoku.ahk @@ -0,0 +1,144 @@ +#SingleInstance, Force +SetBatchLines, -1 +SetTitleMatchMode, 3 + + Loop 9 { + r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) + Loop 9 { + c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) + Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext + } + } + Gui, Add, Button, vButton gSolve w175 x10 Center, Solve + Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve + Gui, Show,, Sudoku Solver +Return + +Solve: + Gui, Submit, NoHide + Loop 9 + { + r := A_Index + Loop 9 + If (%r%_%A_Index% = "") + puzzle .= "@" + Else + puzzle .= %r%_%A_Index% + } + s := A_TickCount + answer := Sudoku(puzzle) + iterations := ErrorLevel + e := A_TickCount + seconds := (e-s)/1000 + StringSplit, a, answer, | + Loop 9 + { + r := A_Index + Loop 9 + { + b := (r*9)+A_Index-9 + GuiControl,, %r%_%A_Index%, % a%b% + GuiControl, +ReadOnly, %r%_%A_Index% + } + } + if answer + GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% + else + GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% + GuiControl,, Button, Again! + GuiControl, +gAgain, Button +return + +GuiClose: + ExitApp + +Again: + Reload + +#IfWinActive, Sudoku Solver +~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" +~Up:: + GuiControlGet, f, focus + StringTrimLeft, f, f, 4 + f := ((f >= 1 && f <= 9) ? f+72 : f-9) + GuiControl, Focus, Edit%f% +return +~Down:: + GuiControlGet, f, focus + StringTrimLeft, f, f, 4 + f := ((f >= 73 && f <= 81) ? f-72 : f + 9) + GuiControl, Focus, Edit%f% +return +~Left:: + GuiControlGet, f, focus + StringTrimLeft, f, f, 4 + f := Mod(f + 79, 81) + 1 + GuiControl, Focus, Edit%f% +return +Next: +~Right:: + GuiControlGet, f, focus + StringTrimLeft, f, f, 4 + f := Mod(f, 81) + 1 + GuiControl, Focus, Edit%f% +return +#IfWinActive + +; Functions Start here + +Sudoku( p ) { ;ErrorLevel contains the number of iterations + p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 ;format puzzle as single line string + return Sudoku_Display(Sudoku_Solve(p)) +} + +Sudoku_Solve( p, d = 0 ) { ;d is 0-based +; http://www.autohotkey.com/forum/topic46679.html +; p: 81 character puzzle string +; (concat all 9 rows of 9 chars each) +; givens represented as chars 1-9 +; fill-ins as any non-null, non 1-9 char +; d: used internally. omit on initial call +; +; returns: 81 char string with non-givens replaced with valid solution +; + If (d >= 81), ErrorLevel++ + return p ;this is 82nd iteration, so it has successfully finished iteration 81 + If InStr( "123456789", SubStr(p, d+1, 1) ) ;this depth is a given, skip through + return Sudoku_Solve(p, d+1) + m := Sudoku_Constraints(p,d) ;a string of this level's constraints. + ; (these will not change for all 9 loops) + Loop 9 + { + If InStr(m, A_Index) + Continue + NumPut(Asc(A_Index), p, d, "Char") + If r := Sudoku_Solve(p, d+1) + return r + } + return 0 +} + +Sudoku_Constraints( ByRef p, d ) { +; returns a string of the constraints for a particular position + c := Mod(d,9) + , r := (d - c) // 9 + , b := r//3*27 + c//3*3 + 1 + ;convert to 1-based + , c++ + return "" + ; row: + . SubStr(p, r * 9 + 1, 9) + ; column: + . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) + . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) + . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) + ;box + . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) +} + +Sudoku_Display( p ) { + If StrLen(p) = 81 + loop 81 + r .= SubStr(p, A_Index, 1) . "|" + return r +} diff --git a/Task/Sudoku/BBC-BASIC/sudoku.bbc b/Task/Sudoku/BBC-BASIC/sudoku.bbc new file mode 100644 index 0000000000..9b13eda644 --- /dev/null +++ b/Task/Sudoku/BBC-BASIC/sudoku.bbc @@ -0,0 +1,105 @@ + VDU 23,22,453;453;8,20,16,128 + *FONT Arial,28 + + DIM Board%(8,8) + Board%() = %111111111 + + FOR L% = 0 TO 9:P% = L%*100 + LINE 2,P%+2,902,P%+2 + IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4 + LINE P%+2,2,P%+2,902 + IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902 + NEXT + + DATA " 4 5 6 " + DATA " 6 1 8 9" + DATA "3 7 " + DATA " 8 5 " + DATA " 4 3 " + DATA " 6 7 " + DATA " 2 6" + DATA "1 5 4 3 " + DATA " 2 7 1 " + + FOR R% = 8 TO 0 STEP -1 + READ A$ + FOR C% = 0 TO 8 + A% = ASCMID$(A$,C%+1) AND 15 + IF A% Board%(R%,C%) = 1 << (A%-1) + NEXT + NEXT R% + + GCOL 4 + PROCshow + WAIT 200 + dummy% = FNsolve(Board%(), TRUE) + GCOL 2 + PROCshow + REPEAT WAIT 1 : UNTIL FALSE + END + + DEF PROCshow + LOCAL C%,P%,R% + FOR C% = 0 TO 8 + FOR R% = 0 TO 8 + P% = Board%(R%,C%) + IF (P% AND (P%-1)) = 0 THEN + IF P% P% = LOGP%/LOG2+1.5 + MOVE C%*100+30,R%*100+90 + VDU 5,P%+48,4 + ENDIF + NEXT + NEXT + ENDPROC + + DEF FNsolve(P%(),F%) + LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%() + DIM Q%(8,8) + REPEAT + Q%() = P%() + FOR R% = 0 TO 8 + FOR C% = 0 TO 8 + D% = P%(R%,C%) + IF (D% AND (D%-1))=0 THEN + M% = NOT D% + FOR X% = 0 TO 8 + IF X%<>C% P%(R%,X%) AND= M% + IF X%<>R% P%(X%,C%) AND= M% + NEXT + FOR X% = C%DIV3*3 TO C%DIV3*3+2 + FOR Y% = R%DIV3*3 TO R%DIV3*3+2 + IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M% + NEXT + NEXT + ENDIF + NEXT + NEXT + Q%() -= P%() + UNTIL SUMQ%()=0 + M% = 10 + FOR R% = 0 TO 8 + FOR C% = 0 TO 8 + D% = P%(R%,C%) + IF D%=0 M% = 0 + IF D% AND (D%-1) THEN + N% = 0 + REPEAT N% += D% AND 1 + D% DIV= 2 + UNTIL D% = 0 + IF N%" x y !x !y) + & get' + ) + | (!x !y.!trc) !todo:?todo + ) + | % % + | &!DOING:(?.!trc) + ) + ) + | !tr + ) + ) + & !arg:(?tree.?todo) + & ( loop + = !todo: + | !todo + : ((?certainValue.%?d %?c %?b %?a):?DOING) ?todo + & update$(!a ? !c ?.!certainValue.!tree.) + : ?tree + & update$(!a !b <>!c ?.!certainValue.!tree.) + : ?tree + & update$(<>!a ? !c !d.!certainValue.!tree.) + : ?tree + & !loop + ) + & !loop + & ( ~( !tree + : ? + (?.? (?.? (?.? (?.% %) ?) ?) ?) + ? + ) + | 9:?minlen + & :?minp + & ( len + = + . !arg:% %?arg&1+len$!arg + | 1 + ) + & ( !tree + : ? + ( ?a + . ? + ( ?b + . ? + ( ?c + . ? + ( ?d + . % %:?p + & len$!p: +using namespace std; + +class SudokuSolver { +private: + int grid[81]; + +public: + + SudokuSolver(string s) { + for (unsigned int i = 0; i < s.length(); i++) { + grid[i] = (int) (s[i] - '0'); + } + } + + void solve() { + try { + placeNumber(0); + cout << "Unsolvable!" << endl; + } catch (char* ex) { + cout << ex << endl; + cout << this->toString() << endl; + } + } + + void placeNumber(int pos) { + if (pos == 81) { + throw (char*) "Finished!"; + } + if (grid[pos] > 0) { + placeNumber(pos + 1); + return; + } + for (int n = 1; n <= 9; n++) { + if (checkValidity(n, pos % 9, pos / 9)) { + grid[pos] = n; + placeNumber(pos + 1); + grid[pos] = 0; + } + } + } + + bool checkValidity(int val, int x, int y) { + for (int i = 0; i < 9; i++) { + if (grid[y * 9 + i] == val || grid[i * 9 + x] == val) + return false; + } + int startX = (x / 3) * 3; + int startY = (y / 3) * 3; + for (int i = startY; i < startY + 3; i++) { + for (int j = startX; j < startX + 3; j++) { + if (grid[i * 9 + j] == val) + return false; + } + } + return true; + } + + string toString() { + string sb; + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + char c[2]; + c[0] = grid[i * 9 + j] + '0'; + c[1] = '\0'; + sb.append(c); + sb.append(" "); + if (j == 2 || j == 5) + sb.append("| "); + } + sb.append("\n"); + if (i == 2 || i == 5) + sb.append("------+-------+------\n"); + } + return sb; + } + +}; + +int main() { + SudokuSolver ss( + (string) "850002400" + + (string) "720000009" + + (string) "004000000" + + (string) "000107002" + + (string) "305000900" + + (string) "040000000" + + (string) "000080070" + + (string) "017000000" + + (string) "000036040" + ); + ss.solve(); +} diff --git a/Task/Sudoku/C/sudoku.c b/Task/Sudoku/C/sudoku.c new file mode 100644 index 0000000000..663753cb28 --- /dev/null +++ b/Task/Sudoku/C/sudoku.c @@ -0,0 +1,67 @@ +#include + +void show(int *x) +{ + int i, j; + for (i = 0; i < 9; i++) { + if (!(i % 3)) putchar('\n'); + for (j = 0; j < 9; j++) + printf(j % 3 ? "%2d" : "%3d", *x++); + putchar('\n'); + } +} + +int trycell(int *x, int pos) +{ + int row = pos / 9; + int col = pos % 9; + int i, j, used = 0; + + if (pos == 81) return 1; + if (x[pos]) return trycell(x, pos + 1); + + for (i = 0; i < 9; i++) + used |= 1 << (x[i * 9 + col] - 1); + + for (j = 0; j < 9; j++) + used |= 1 << (x[row * 9 + j] - 1); + + row = row / 3 * 3; + col = col / 3 * 3; + for (i = row; i < row + 3; i++) + for (j = col; j < col + 3; j++) + used |= 1 << (x[i * 9 + j] - 1); + + for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1) + if (!(used & 1) && trycell(x, pos + 1)) return 1; + + x[pos] = 0; + return 0; +} + +void solve(const char *s) +{ + int i, x[81]; + for (i = 0; i < 81; i++) + x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0; + + if (trycell(x, 0)) + show(x); + else + puts("no solution"); +} + +int main(void) +{ + solve( "5x..7...." + "6..195..." + ".98....6." + "8...6...3" + "4..8.3..1" + "7...2...6" + ".6....28." + "...419..5" + "....8..79" ); + + return 0; +} diff --git a/Task/Sudoku/Clojure/sudoku-1.clj b/Task/Sudoku/Clojure/sudoku-1.clj new file mode 100644 index 0000000000..492cdebe8a --- /dev/null +++ b/Task/Sudoku/Clojure/sudoku-1.clj @@ -0,0 +1,41 @@ +(ns sudoku + (:use [clojure.contrib.math :only (sqrt)])) + +(defn print-grid [grid] + (doseq [y (range (count grid))] + (doseq [x (range (count grid))] + (print (retrieve grid x y) " ")) + (println)) + (println)) + +(defn retrieve [grid x y] + (get (get grid y) x)) + +(defn store [grid x y n] + (assoc grid y (assoc (get grid y) x n))) + +(defn coordinates [grid x y] + (let [n (sqrt (count grid)) + zx (* n (quot x n)) + zy (* n (quot y n))] + (for [x (range zx (+ zx n)) y (range zy (+ zy n))] + [x y]))) + +(defn compatible? [grid x y n] + (or + (= n (retrieve grid x y)) + (and + (zero? (retrieve grid x y)) + (every? #(and (not= n (retrieve grid % y)) (not= n (retrieve grid x %))) (range (count grid))) + (every? #(not= n (retrieve grid (first %) (second %))) (coordinates grid x y))))) + +(defn solve [grid x y] + (let [m (count grid)] + (if (= y m) + (print-grid grid) + (doseq [n (range 1 (inc m))] + (when (compatible? grid x y n) + (let [new-grid (store grid x y n)] + (if (= x (dec m)) + (solve new-grid 0 (inc y)) + (solve new-grid (inc x) y)))))))) diff --git a/Task/Sudoku/Clojure/sudoku-2.clj b/Task/Sudoku/Clojure/sudoku-2.clj new file mode 100644 index 0000000000..8f26b9a99e --- /dev/null +++ b/Task/Sudoku/Clojure/sudoku-2.clj @@ -0,0 +1,21 @@ +sudoku> (solve [[3 9 4 0 0 2 6 7 0] + [0 0 0 3 0 0 4 0 0] + [5 0 0 6 9 0 0 2 0] + [0 4 5 0 0 0 9 0 0] + [6 0 0 0 0 0 0 0 7] + [0 0 7 0 0 0 5 8 0] + [0 1 0 0 6 7 0 0 8] + [0 0 9 0 0 8 0 0 0] + [0 2 6 4 0 0 7 3 5]] + 0 0) +3 9 4 8 5 2 6 7 1 +2 6 8 3 7 1 4 5 9 +5 7 1 6 9 4 8 2 3 +1 4 5 7 8 3 9 6 2 +6 8 2 9 4 5 3 1 7 +9 3 7 1 2 6 5 8 4 +4 1 3 5 6 7 2 9 8 +7 5 9 2 3 8 1 4 6 +8 2 6 4 1 9 7 3 5 + +nil diff --git a/Task/Sudoku/Common-Lisp/sudoku.lisp b/Task/Sudoku/Common-Lisp/sudoku.lisp new file mode 100644 index 0000000000..0fc38668b1 --- /dev/null +++ b/Task/Sudoku/Common-Lisp/sudoku.lisp @@ -0,0 +1,40 @@ +(defun row-neighbors (row column grid &aux (neighbors '())) + (dotimes (i 9 neighbors) + (let ((x (aref grid row i))) + (unless (or (eq '_ x) (= i column)) + (push x neighbors))))) + +(defun column-neighbors (row column grid &aux (neighbors '())) + (dotimes (i 9 neighbors) + (let ((x (aref grid i column))) + (unless (or (eq x '_) (= i row)) + (push x neighbors))))) + +(defun square-neighbors (row column grid &aux (neighbors '())) + (let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3)) + (cmin (* 3 (floor column 3))) (cmax (+ cmin 3))) + (do ((r rmin (1+ r))) ((= r rmax) neighbors) + (do ((c cmin (1+ c))) ((= c cmax)) + (let ((x (aref grid r c))) + (unless (or (eq x '_) (= r row) (= c column)) + (push x neighbors))))))) + +(defun choices (row column grid) + (nset-difference + (list 1 2 3 4 5 6 7 8 9) + (nconc (row-neighbors row column grid) + (column-neighbors row column grid) + (square-neighbors row column grid)))) + +(defun solve (grid &optional (row 0) (column 0)) + (cond + ((= row 9) + grid) + ((= column 9) + (solve grid (1+ row) 0)) + ((not (eq '_ (aref grid row column))) + (solve grid row (1+ column))) + (t (dolist (choice (choices row column grid) (setf (aref grid row column) '_)) + (setf (aref grid row column) choice) + (when (eq grid (solve grid row (1+ column))) + (return grid)))))) diff --git a/Task/Sudoku/Curry/sudoku.curry b/Task/Sudoku/Curry/sudoku.curry new file mode 100644 index 0000000000..9eb4033feb --- /dev/null +++ b/Task/Sudoku/Curry/sudoku.curry @@ -0,0 +1,63 @@ +----------------------------------------------------------------------------- +--- Solving Su Doku puzzles in Curry with FD constraints +--- +--- @author Michael Hanus +--- @version December 2005 +----------------------------------------------------------------------------- + +import CLPFD +import List + +-- Solving a Su Doku puzzle represented as a matrix of numbers (possibly free +-- variables): +sudoku :: [[Int]] -> Success +sudoku m = + domain (concat m) 1 9 & -- define domain of all digits + foldr1 (&) (map allDifferent m) & -- all rows contain different digits + foldr1 (&) (map allDifferent (transpose m)) & -- all columns have different digits + foldr1 (&) (map allDifferent (squaresOfNine m)) & -- all 3x3 squares are different + labeling [FirstFailConstrained] (concat m) + +-- translate a matrix into a list of small 3x3 squares +squaresOfNine :: [[a]] -> [[a]] +squaresOfNine [] = [] +squaresOfNine (l1:l2:l3:ls) = group3Rows [l1,l2,l3] ++ squaresOfNine ls + +group3Rows l123 = if null (head l123) then [] else + concatMap (take 3) l123 : group3Rows (map (drop 3) l123) + +-- read a Su Doku specification written as a list of strings containing digits +-- and spaces +readSudoku :: [String] -> [[Int]] +readSudoku s = map (map transDigit) s + where + transDigit c = if c==' ' then x else ord c - ord '0' + where x free + +-- show a solved Su Doku matrix +showSudoku :: [[Int]] -> String +showSudoku = unlines . map (concatMap (\i->[chr (i + ord '0'),' '])) + +-- the main function, e.g., evaluate (main s1): +main s | sudoku m = putStrLn (showSudoku m) + where m = readSudoku s + +s1 = ["9 2 5 ", + " 4 6 3 ", + " 3 6", + " 9 2 ", + " 5 8 ", + " 7 4 3", + "7 1 ", + " 5 2 4 ", + " 1 6 9"] + +s2 = ["819 5 ", + " 2 75 ", + " 371 4 6 ", + "4 59 1 ", + "7 3 8 2", + " 3 62 7", + " 5 7 921 ", + " 64 9 ", + " 2 438"] diff --git a/Task/Sudoku/D/sudoku.d b/Task/Sudoku/D/sudoku.d new file mode 100644 index 0000000000..50361a5f4a --- /dev/null +++ b/Task/Sudoku/D/sudoku.d @@ -0,0 +1,156 @@ +import std.stdio, std.range, std.string, std.algorithm, std.array, + std.typetuple, std.ascii, std.typecons; + +template Range(size_t stop) { // For loop unrolling. + static if (stop == 0) + alias TypeTuple!() Range; + else + alias TypeTuple!(Range!(stop - 1), stop - 1) Range; +} + + +enum size_t sudokuUnitSide = 3; +enum size_t sudokuSide = sudokuUnitSide ^^ 2; // Sudoku grid side. + + +struct Digit { + immutable char d; + + this(in char d_) pure nothrow + in { assert(d_ >= '0' && d_ <= '9'); } + body { this.d = d_; } + + this(in int d_) pure nothrow + in { assert(d_ >= '0' && d_ <= '9'); } + body { this.d = cast(char)d_; } // Required cast. + + alias d this; +} + +alias SudokuTable = Digit[sudokuSide ^^ 2]; + + +Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem) +/*pure nothrow*/ { + alias Tgrid = uint; + Tgrid[SudokuTable.length] grid = void; + problem[].map!(c => c - '0')().copy(grid[]); // Not pure. + + // DMD doesn't inline this function. Performance loss. + Tgrid access(in size_t x, in size_t y) nothrow { + return grid[y * sudokuSide + x]; + } + + // DMD doesn't inline this function. If you want to retain + // the same performance as the C++ entry and you use the DMD + // compiler then this function must be manually inlined. + bool checkValidity(in Tgrid val, in size_t x, in size_t y) nothrow { + /*static*/ foreach (immutable i; Range!sudokuSide) + if (access(i, y) == val || access(x, i) == val) + return false; + + immutable startX = (x / sudokuUnitSide) * sudokuUnitSide; + immutable startY = (y / sudokuUnitSide) * sudokuUnitSide; + + /*static*/ foreach (immutable i; Range!sudokuUnitSide) + /*static*/ foreach (immutable j; Range!sudokuUnitSide) + if (access(startX + j, startY + i) == val) + return false; + + return true; + } + + bool canPlaceNumbers(in size_t pos=0) nothrow { + if (pos == SudokuTable.length) + return true; + if (grid[pos] > 0) + return canPlaceNumbers(pos + 1); + + foreach (immutable n; 1 .. sudokuSide + 1) + if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) { + grid[pos] = n; + if (canPlaceNumbers(pos + 1)) + return true; + grid[pos] = 0; + } + + return false; + } + + if (canPlaceNumbers()) { + //return typeof(return)(grid[] + // .map!(c => Digit(c + '0'))() + // .array()); + Digit[] aux; + foreach (c; grid) + aux ~= Digit(c + '0'); + immutable SudokuTable result = aux; + return typeof(return)(result); + } else + return typeof(return)(); +} + + +string representSudoku(in ref SudokuTable sudo) +pure nothrow out(result) { + // assert(result.countchars("1-9") == sudo.countchars("^0")); + uint nPosDigits; + foreach (c; sudo) + if (c >= '1' && c <= '9') + nPosDigits++; + assert(result.countchars("1-9") == nPosDigits); +} body { + static assert(sudo.length == 81, + "representSudoku works only with a 9x9 Sudoku."); + string result; + + foreach (immutable i; 0 .. sudokuSide) { + foreach (immutable j; 0 .. sudokuSide) { + // immutable digit = sudo[i * sudokuSide + j]; + immutable char digit = sudo[i * sudokuSide + j]; + result ~= (digit == '0') ? '.' : digit; + result ~= ' '; + if (j == 2 || j == 5) + result ~= "| "; + } + result ~= "\n"; + if (i == 2 || i == 5) + result ~= "------+-------+------\n"; + } + + //return result.replace("0", "."); // Not pure, not nothrow. + return result; +} + + +U[] validator(U, T)(in T[] items) pure nothrow { + typeof(return) result; + foreach (immutable item; items) + result ~= U(item); + return result; +} + +template ValidateCells(string s) { + enum ValidateCells = validator!Digit(s); +} + + +void main() { + immutable SudokuTable problem = ValidateCells!(" + 850002400 + 720000009 + 004000000 + 000107002 + 305000900 + 040000000 + 000080070 + 017000000 + 000036040".removechars(std.ascii.whitespace)); + problem.representSudoku().writeln(); + + immutable solution = sudokuSolver(problem); + if (solution.isNull) + writeln("Unsolvable!"); + else + solution.get().representSudoku().writeln(); +} diff --git a/Task/Sudoku/Delphi/sudoku-1.delphi b/Task/Sudoku/Delphi/sudoku-1.delphi new file mode 100644 index 0000000000..e5bb268c76 --- /dev/null +++ b/Task/Sudoku/Delphi/sudoku-1.delphi @@ -0,0 +1,122 @@ +type + TIntArray = array of Integer; + + { TSudokuSolver } + + TSudokuSolver = class + private + FGrid: TIntArray; + + function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean; + function ToString: string; reintroduce; + procedure PlaceNumber(pos: Integer); + public + constructor Create(s: string); + + procedure Solve; + end; + +implementation + +uses + Dialogs; + +{ TSudokuSolver } + +function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer + ): Boolean; +var + i: Integer; + j: Integer; + StartX: Integer; + StartY: Integer; +begin + for i := 0 to 8 do + begin + if (FGrid[y * 9 + i] = val) or + (FGrid[i * 9 + x] = val) then + begin + Result := False; + Exit; + end; + end; + StartX := (x div 3) * 3; + StartY := (y div 3) * 3; + for i := StartY to Pred(StartY + 3) do + begin + for j := StartX to Pred(StartX + 3) do + begin + if FGrid[i * 9 + j] = val then + begin + Result := False; + Exit; + end; + end; + end; + Result := True; +end; + +function TSudokuSolver.ToString: string; +var + sb: string; + i: Integer; + j: Integer; + c: char; +begin + sb := ''; + for i := 0 to 8 do + begin + for j := 0 to 8 do + begin + c := (IntToStr(FGrid[i * 9 + j]) + '0')[1]; + sb := sb + c + ' '; + if (j = 2) or (j = 5) then sb := sb + '| '; + end; + sb := sb + #13#10; + if (i = 2) or (i = 5) then + sb := sb + '-----+-----+-----' + #13#10; + end; + Result := sb; +end; + +procedure TSudokuSolver.PlaceNumber(pos: Integer); +var + n: Integer; +begin + if Pos = 81 then + raise Exception.Create('Finished!'); + if FGrid[pos] > 0 then + begin + PlaceNumber(Succ(pos)); + Exit; + end; + for n := 1 to 9 do + begin + if CheckValidity(n, pos mod 9, pos div 9) then + begin + FGrid[pos] := n; + PlaceNumber(Succ(pos)); + FGrid[pos] := 0; + end; + end; +end; + +constructor TSudokuSolver.Create(s: string); +var + lcv: Cardinal; +begin + SetLength(FGrid, 81); + for lcv := 0 to Pred(Length(s)) do + FGrid[lcv] := StrToInt(s[Succ(lcv)]); +end; + +procedure TSudokuSolver.Solve; +begin + try + PlaceNumber(0); + ShowMessage('Unsolvable'); + except + ShowMessage((ExceptObject as Exception).Message); + ShowMessage(ToString); + end; +end; diff --git a/Task/Sudoku/Delphi/sudoku-2.delphi b/Task/Sudoku/Delphi/sudoku-2.delphi new file mode 100644 index 0000000000..039433688d --- /dev/null +++ b/Task/Sudoku/Delphi/sudoku-2.delphi @@ -0,0 +1,18 @@ +var + SudokuSolver: TSudokuSolver; +begin + SudokuSolver := TSudokuSolver.Create('850002400' + + '720000009' + + '004000000' + + '000107002' + + '305000900' + + '040000000' + + '000080070' + + '017000000' + + '000036040'); + try + SudokuSolver.Solve; + finally + FreeAndNil(SudokuSolver); + end; +end; diff --git a/Task/Sudoku/Forth/sudoku.fth b/Task/Sudoku/Forth/sudoku.fth new file mode 100644 index 0000000000..bdf830bc2b --- /dev/null +++ b/Task/Sudoku/Forth/sudoku.fth @@ -0,0 +1,364 @@ +include lib/interprt.4th +include lib/istype.4th +include lib/argopen.4th + +\ --------------------- +\ Variables +\ --------------------- + +81 string sudokugrid +9 array sudoku_row +9 array sudoku_col +9 array sudoku_box + +\ ------------- +\ 4tH interface +\ ------------- + +: >grid ( n2 a1 n1 -- n3) + rot dup >r 9 chars * sudokugrid + dup >r swap + 0 do ( a1 a2) + over i chars + c@ dup is-digit ( a1 a2 c f) + if [char] 0 - over c! char+ else drop then + loop ( a1 a2) + nip r> - 9 / r> + ( n3) +; + +0 +s" 090004007" >grid +s" 000007900" >grid +s" 800000000" >grid +s" 405800000" >grid +s" 300000002" >grid +s" 000009706" >grid +s" 000000004" >grid +s" 003500000" >grid +s" 200600080" >grid +drop + +\ --------------------- +\ Logic +\ --------------------- +\ Basically : +\ Grid is parsed. All numbers are put into sets, which are +\ implemented as bitmaps (sudoku_row, sudoku_col, sudoku_box) +\ which represent sets of numbers in each row, column, box. +\ only one specific instance of a number can exist in a +\ particular set. + +\ SOLVER is recursively called +\ SOLVER looks for the next best guess using FINDNEXTSPACE +\ tries this trail down... if fails, backtracks... and tries +\ again. + + +\ Grid Related + +: xy 9 * + ; \ x y -- offset ; +: getrow 9 / ; +: getcol 9 mod ; +: getbox dup getrow 3 / 3 * swap getcol 3 / + ; + +\ Puts and gets numbers from/to grid only +: setnumber sudokugrid + c! ; \ n position -- +: getnumber sudokugrid + c@ ; + +: cleargrid sudokugrid 81 bounds do 0 i c! loop ; + +\ -------------- +\ Set related: sets are sudoku_row, sudoku_col, sudoku_box + +\ ie x y -- ; adds x into bitmap y +: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ; +: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ; +: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ; + +\ ie x y -- ; remove number x from bitmap y +: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ; +: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ; +: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ; + +\ clears all bitsmaps to 0 +: clearbitmaps 9 0 do i cells + 0 over sudoku_row + ! + 0 over sudoku_col + ! + 0 swap sudoku_box + ! + loop ; + +\ Adds number to grid and sets +: addnumber \ number position -- + 2dup setnumber + 2dup getrow addbits_row + 2dup getcol addbits_col + getbox addbits_box +; + +\ Remove number from grid, and sets +: removenumber \ position -- + dup getnumber swap + 2dup getrow removebits_row + 2dup getcol removebits_col + 2dup getbox removebits_box + nip 0 swap setnumber +; + +\ gets bitmap at position, ie +\ position -- bitmap + +: getrow_bits getrow cells sudoku_row + @ ; +: getcol_bits getcol cells sudoku_col + @ ; +: getbox_bits getbox cells sudoku_box + @ ; + +\ position -- composite bitmap (or'ed) +: getbits + dup getrow_bits + over getcol_bits + rot getbox_bits or or +; + +\ algorithm from c.l.f circa 1995 ? Will Baden +: countbits ( number -- bits ) + [HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND + + DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND + + DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND + + [DECIMAL] 255 MOD +; + +\ Try tests a number in a said position of grid +\ Returns true if it's possible, else false. +: try \ number position -- true/false + getbits 1 rot lshift and 0= +; + +\ -------------- +: parsegrid \ Parses Grid to fill sets.. Run before solver. + sudokugrid \ to ensure all numbers are parsed into sets/bitmaps + 81 0 do + dup i + c@ + dup if + dup i try if + i addnumber + else + unloop drop drop FALSE exit + then + else + drop + then + loop + drop + TRUE +; + +\ Morespaces? manually checks for spaces ... +\ Obviously this can be optimised to a count var, done initially +\ Any additions/subtractions made to the grid could decrement +\ a 'spaces' variable. + +: morespaces? + 0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ; + +: findnextmove \ -- n ; n = index next item, if -1 finished. + + -1 10 \ index prev_possibilities -- + \ err... yeah... local variables, kind of... + + 81 0 do + i sudokugrid + c@ 0= IF + i getbits countbits 9 swap - + + \ get bitmap and see how many possibilities + \ stack diagram: + \ index prev_possibilities new_possiblities -- + + 2dup > if + \ if new_possibilities < prev_possibilities... + nip nip i swap + \ new_index new_possibilies -- + + else \ else prev_possibilities < new possibilities, so: + + drop \ new_index new_possibilies -- + + then + THEN + loop + drop +; + +\ findnextmove returns index of best next guess OR returns -1 +\ if no more guesses. You then have to check to see if there are +\ spaces left on the board unoccupied. If this is the case, you +\ need to back up the recursion and try again. + +: solver + findnextmove + dup 0< if + morespaces? if + drop false exit + else + drop true exit + then + then + + 10 1 do + i over try if + i over addnumber + recurse if + drop unloop TRUE EXIT + else + dup removenumber + then + then + loop + + drop FALSE +; + +\ SOLVER + +: startsolving + clearbitmaps \ reparse bitmaps and reparse grid + parsegrid \ just in case.. + solver + AND +; + +\ --------------------- +\ Display Grid +\ --------------------- + +\ Prints grid nicely + +: .sudokugrid + CR CR + sudokugrid + 81 0 do + dup i + c@ . + i 1+ + dup 3 mod 0= if + dup 9 mod 0= if + CR + dup 27 mod 0= if + dup 81 < if ." ------+-------+------" CR then + then + else + ." | " + then + then + drop + loop + drop + CR +; + +\ --------------------- +\ Higher Level Words +\ --------------------- + +: checkifoccupied ( offset -- t/f) + sudokugrid + c@ +; + +: add ( n x y --) + xy 2dup + dup checkifoccupied if + dup removenumber + then + try if + addnumber + .sudokugrid + else + CR ." Not a valid move. " CR + 2drop + then +; + +: rm + xy removenumber + .sudokugrid +; + +: clearit + cleargrid + clearbitmaps + .sudokugrid +; + +: solveit + CR + startsolving + if + ." Solution found!" CR .sudokugrid + else + ." No solution found!" CR CR + then +; + +: showit .sudokugrid ; + +\ Print help menu +: help + CR + ." Type clearit ; to clear grid " CR + ." 1-9 x y add ; to add 1-9 to grid at x y (0 based) " CR + ." x y rm ; to remove number at x y " CR + ." showit ; redisplay grid " CR + ." solveit ; to solve " CR + ." help ; for help " CR + CR +; + +\ --------------------- +\ Execution starts here +\ --------------------- + +: godoit + clearbitmaps + parsegrid if + CR ." Grid valid!" + else + CR ." Warning: grid invalid!" + then + .sudokugrid + help +; + +\ ------------- +\ 4tH interface +\ ------------- + +: read-sudoku + input 1 arg-open 0 + begin dup 9 < while refill while 0 parse >grid repeat + drop close +; + +: bye quit ; + +create wordlist \ dictionary + ," clearit" ' clearit , + ," add" ' add , + ," rm" ' rm , + ," showit" ' showit , + ," solveit" ' solveit , + ," quit" ' bye , + ," exit" ' bye , + ," bye" ' bye , + ," q" ' bye , + ," help" ' help , + NULL , + +wordlist to dictionary +:noname ." Unknown command '" type ." '" cr ; is NotFound + \ sudoku interpreter +: sudoku + argn 1 > if read-sudoku then + godoit + begin + ." OK" cr + refill drop ['] interpret + catch if ." Error" cr then + again +; + +sudoku diff --git a/Task/Sudoku/Fortran/sudoku.f b/Task/Sudoku/Fortran/sudoku.f new file mode 100644 index 0000000000..1fdf1663ab --- /dev/null +++ b/Task/Sudoku/Fortran/sudoku.f @@ -0,0 +1,98 @@ +program sudoku + + implicit none + integer, dimension (9, 9) :: grid + integer, dimension (9, 9) :: grid_solved + grid = reshape ((/ & + & 0, 0, 3, 0, 2, 0, 6, 0, 0, & + & 9, 0, 0, 3, 0, 5, 0, 0, 1, & + & 0, 0, 1, 8, 0, 6, 4, 0, 0, & + & 0, 0, 8, 1, 0, 2, 9, 0, 0, & + & 7, 0, 0, 0, 0, 0, 0, 0, 8, & + & 0, 0, 6, 7, 0, 8, 2, 0, 0, & + & 0, 0, 2, 6, 0, 9, 5, 0, 0, & + & 8, 0, 0, 2, 0, 3, 0, 0, 9, & + & 0, 0, 5, 0, 1, 0, 3, 0, 0/), & + & shape = (/9, 9/), & + & order = (/2, 1/)) + call pretty_print (grid) + call solve (1, 1) + write (*, *) + call pretty_print (grid_solved) + +contains + + recursive subroutine solve (i, j) + implicit none + integer, intent (in) :: i + integer, intent (in) :: j + integer :: n + integer :: n_tmp + if (i > 9) then + grid_solved = grid + else + do n = 1, 9 + if (is_safe (i, j, n)) then + n_tmp = grid (i, j) + grid (i, j) = n + if (j == 9) then + call solve (i + 1, 1) + else + call solve (i, j + 1) + end if + grid (i, j) = n_tmp + end if + end do + end if + end subroutine solve + + function is_safe (i, j, n) result (res) + implicit none + integer, intent (in) :: i + integer, intent (in) :: j + integer, intent (in) :: n + logical :: res + integer :: i_min + integer :: j_min + if (grid (i, j) == n) then + res = .true. + return + end if + if (grid (i, j) /= 0) then + res = .false. + return + end if + if (any (grid (i, :) == n)) then + res = .false. + return + end if + if (any (grid (:, j) == n)) then + res = .false. + return + end if + i_min = 1 + 3 * ((i - 1) / 3) + j_min = 1 + 3 * ((j - 1) / 3) + if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then + res = .false. + return + end if + res = .true. + end function is_safe + + subroutine pretty_print (grid) + implicit none + integer, dimension (9, 9), intent (in) :: grid + integer :: i + integer :: j + character (*), parameter :: bar = '+-----+-----+-----+' + character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")' + write (*, '(a)') bar + do j = 0, 6, 3 + do i = j + 1, j + 3 + write (*, fmt) grid (i, :) + end do + write (*, '(a)') bar + end do + end subroutine pretty_print + +end program sudoku diff --git a/Task/Sudoku/Go/sudoku.go b/Task/Sudoku/Go/sudoku.go new file mode 100644 index 0000000000..93b04cb008 --- /dev/null +++ b/Task/Sudoku/Go/sudoku.go @@ -0,0 +1,202 @@ +package main + +import "fmt" + +// sudoku puzzle representation is an 81 character string +var puzzle = "" + + "394 267 " + + " 3 4 " + + "5 69 2 " + + " 45 9 " + + "6 7" + + " 7 58 " + + " 1 67 8" + + " 9 8 " + + " 264 735" + +func main() { + printGrid("puzzle:", puzzle) + if s := solve(puzzle); s == "" { + fmt.Println("no solution") + } else { + printGrid("solved:", s) + } +} + +// print grid (with title) from 81 character string +func printGrid(title, s string) { + fmt.Println(title) + for r, i := 0, 0; r < 9; r, i = r+1, i+9 { + fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2], + s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8]) + if r == 2 || r == 5 { + fmt.Println("------+-------+------") + } + } +} + +// solve puzzle in 81 character string format. +// if solved, result is 81 character string. +// if not solved, result is the empty string. +func solve(u string) string { + // construct an dlx object with 324 constraint columns. + // other than the number 324, this is not specific to sudoku. + d := newDlxObject(324) + // now add constraints that define sudoku rules. + for r, i := 0, 0; r < 9; r++ { + for c := 0; c < 9; c, i = c+1, i+1 { + b := r/3*3 + c/3 + n := int(u[i] - '1') + if n >= 0 && n < 9 { + d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, + 243 + b*9 + n}) + } else { + for n = 0; n < 9; n++ { + d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n, + 243 + b*9 + n}) + } + } + } + } + // run dlx. not sudoku specific. + d.search() + // extract the sudoku-specific 81 character result from the dlx solution. + return d.text() +} + +// Knuth's data object +type x struct { + c *y + u, d, l, r *x + // except x0 is not Knuth's. it's pointer to first constraint in row, + // so that the sudoku string can be constructed from the dlx solution. + x0 *x +} + +// Knuth's column object +type y struct { + x + s int // size + n int // name +} + +// an object to hold the matrix and solution +type dlx struct { + ch []y // all column headers + h *y // ch[0], the root node + o []*x // solution +} + +// constructor creates the column headers but no rows. +func newDlxObject(nCols int) *dlx { + ch := make([]y, nCols+1) + h := &ch[0] + d := &dlx{ch, h, nil} + h.c = h + h.l = &ch[nCols].x + ch[nCols].r = &h.x + nh := ch[1:] + for i := range ch[1:] { + hi := &nh[i] + ix := &hi.x + hi.n = i + hi.c = hi + hi.u = ix + hi.d = ix + hi.l = &h.x + h.r = ix + h = hi + } + return d +} + +// rows define constraints +func (d *dlx) addRow(nr []int) { + if len(nr) == 0 { + return + } + r := make([]x, len(nr)) + x0 := &r[0] + for x, j := range nr { + ch := &d.ch[j+1] + ch.s++ + np := &r[x] + np.c = ch + np.u = ch.u + np.d = &ch.x + np.l = &r[(x+len(r)-1)%len(r)] + np.r = &r[(x+1)%len(r)] + np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np + np.x0 = x0 + } +} + +// extracts 81 character sudoku string +func (d *dlx) text() string { + b := make([]byte, len(d.o)) + for _, r := range d.o { + x0 := r.x0 + b[x0.c.n] = byte(x0.r.c.n%9) + '1' + } + return string(b) +} + +// the dlx algorithm +func (d *dlx) search() bool { + h := d.h + j := h.r.c + if j == h { + return true + } + c := j + for minS := j.s; ; { + j = j.r.c + if j == h { + break + } + if j.s < minS { + c, minS = j, j.s + } + } + + cover(c) + k := len(d.o) + d.o = append(d.o, nil) + for r := c.d; r != &c.x; r = r.d { + d.o[k] = r + for j := r.r; j != r; j = j.r { + cover(j.c) + } + if d.search() { + return true + } + r = d.o[k] + c = r.c + for j := r.l; j != r; j = j.l { + uncover(j.c) + } + } + d.o = d.o[:len(d.o)-1] + uncover(c) + return false +} + +func cover(c *y) { + c.r.l, c.l.r = c.l, c.r + for i := c.d; i != &c.x; i = i.d { + for j := i.r; j != i; j = j.r { + j.d.u, j.u.d = j.u, j.d + j.c.s-- + } + } +} + +func uncover(c *y) { + for i := c.u; i != &c.x; i = i.u { + for j := i.l; j != i; j = j.l { + j.c.s++ + j.d.u, j.u.d = j, j + } + } + c.r.l, c.l.r = &c.x, &c.x +} diff --git a/Task/Sudoku/Groovy/sudoku-1.groovy b/Task/Sudoku/Groovy/sudoku-1.groovy new file mode 100644 index 0000000000..f7a4229f93 --- /dev/null +++ b/Task/Sudoku/Groovy/sudoku-1.groovy @@ -0,0 +1,68 @@ +final CELL_VALUES = ('1'..'9') + +class GridException extends Exception { + GridException(String message) { super(message) } +} + +def string2grid = { string -> + assert string.size() == 81 + (0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } } +} + +def gridRow = { grid, slot -> grid[slot.i] as Set } + +def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set } + +def gridBox = { grid, slot -> + def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3] + (0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set +} + +def slotList = { grid -> + def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \ + .collect {j -> [i: i, j: j] } }.flatten() +} + +def assignCandidates = { grid, slots = slotList(grid) -> + slots.each { slot -> + def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set + slot.candidates = CELL_VALUES - unavailable + } + slots.sort { - it.candidates.size() } + if (slots && ! slots[-1].candidates) { + throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1]) + } + slots +} + +def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) } + +def solve +solve = { grid -> + def slots = assignCandidates(grid) + if (! slots) { return grid } + while (slots[-1].candidates.size() == 1) { + def slot = slots.pop() + grid[slot.i][slot.j] = slot.candidates[0] + if (! slots) { return grid } + slots = assignCandidates(grid, slots) + } + if (! slots) { return grid } + def slot = slots.pop() + slot.candidates.each { + if (! isSolved(grid)) { + try { + def sGrid = grid.collect { row -> row.collect { cell -> cell } } + sGrid[slot.i][slot.j] = it + grid = solve(sGrid) + } catch (GridException ge) { + grid[slot.i][slot.j] = '.' + } + } + } + if (!isSolved(grid)) { + slots = assignCandidates(grid) + throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots) + } + grid +} diff --git a/Task/Sudoku/Groovy/sudoku-2.groovy b/Task/Sudoku/Groovy/sudoku-2.groovy new file mode 100644 index 0000000000..ed25949184 --- /dev/null +++ b/Task/Sudoku/Groovy/sudoku-2.groovy @@ -0,0 +1,64 @@ +def sudokus = [ + //Used in Curry solution: ~ 0.1 seconds + '819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438', + + //Used in Perl and PicoLisp solutions: ~ 0.1 seconds + '53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.', + + //Used in Fortran solution: ~ 0.1 seconds + '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..', + + //Used in many other solutions, notably Ada: ~ 0.1 seconds + '394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735', + + //Used in C# solution: ~ 0.2 seconds + '97.3...6..6.75.........8.5.......67.....3.....539..2..7...25.....2.1...8.4...73..', + + //Used in Oz solution: ~ 0.2 seconds + '4......6.5...8.9..3....1....2.7....1.9.....4.8....3.5....2....7..6.5...8.1......6', + + //Used in many other solutions, notably C++: ~ 0.3 seconds + '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.', + + //Used in VBA solution: ~ 0.3 seconds + '..1..5.7.92.6.......8...6...9..2.4.1.........3.4.8..9...7...3.......7.69.1.8..7..', + + //Used in Forth solution: ~ 0.8 seconds + '.9...4..7.....79..8........4.58.....3.......2.....97.6........4..35.....2..6...8.', + + //3rd "exceptionally difficult" example in Wikipedia: ~ 2.3 seconds + '12.3....435....1....4........54..2..6...7.........8.9...31..5.......9.7.....6...8', + + //Used in Curry solution: ~ 2.4 seconds + '9..2..5...4..6..3...3.....6...9..2......5..8...7..4..37.....1...5..2..4...1..6..9', + + //"AL Escargot", so-called "hardest sudoku" (HA!): ~ 3.0 seconds + '1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..', + + //1st "exceptionally difficult" example in Wikipedia: ~ 6.5 seconds + '12.4..3..3...1..5...6...1..7...9.....4.6.3.....3..2...5...8.7....7.....5.......98', + + //Used in Bracmat and Scala solutions: ~ 6.7 seconds + '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9', + + //2nd "exceptionally difficult" example in Wikipedia: ~ 8.8 seconds + '.......39.....1..5..3.5.8....8.9...6.7...2...1..4.......9.8..5..2....6..4..7.....', + + //Used in MATLAB solution: ~15 seconds + '....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6', + + //4th "exceptionally difficult" example in Wikipedia: ~29 seconds + '..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5..'] + +sudokus.each { sudoku -> + def grid = string2grid(sudoku) + println '\nPUZZLE' + grid.each { println it } + + println '\nSOLUTION' + def start = System.currentTimeMillis() + def solution = solve(grid) + def elapsed = (System.currentTimeMillis() - start)/1000 + solution.each { println it } + println "\nELAPSED: ${elapsed} seconds" +} diff --git a/Task/Sudoku/Java/sudoku.java b/Task/Sudoku/Java/sudoku.java new file mode 100644 index 0000000000..70f69ff73e --- /dev/null +++ b/Task/Sudoku/Java/sudoku.java @@ -0,0 +1,88 @@ +public class Sudoku +{ + private int mBoard[][]; + private int mBoardSize; + private int mBoxSize; + private boolean mRowSubset[][]; + private boolean mColSubset[][]; + private boolean mBoxSubset[][]; + + public Sudoku(int board[][]) { + mBoard = board; + mBoardSize = mBoard.length; + mBoxSize = (int)Math.sqrt(mBoardSize); + } + + public void initSubsets() { + mRowSubset = new boolean[mBoardSize][mBoardSize]; + mColSubset = new boolean[mBoardSize][mBoardSize]; + mBoxSubset = new boolean[mBoardSize][mBoardSize]; + for(int i = 0; i < mBoard.length; i++) { + for(int j = 0; j < mBoard.length; j++) { + int value = mBoard[i][j]; + if(value != 0) + setSubsetValue(i, j, value, true); + } + } + } + + private void setSubsetValue(int i, int j, int value, boolean present) { + mRowSubset[i][value - 1] = present; + mColSubset[j][value - 1] = present; + mBoxSubset[computeBoxNo(i, j)][value - 1] = present; + } + + public boolean solve() { + return solve(0, 0); + } + + public boolean solve(int i, int j) { + if(i == mBoardSize) { + i = 0; + if(++j == mBoardSize) + return true; + } + if(mBoard[i][j] != 0) + return solve(i + 1, j); + for(int value = 1; value <= mBoardSize; value++) + if(isValid(i, j, value)) { + mBoard[i][j] = value; + setSubsetValue(i, j, value, true); + if(solve(i + 1, j)) + return true; + setSubsetValue(i, j, value, false); + } + + mBoard[i][j] = 0; + return false; + } + + private boolean isValid(int i, int j, int val) { + val--; + boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]; + return !isPresent; + } + + private int computeBoxNo(int i, int j) { + int boxRow = i / mBoxSize; + int boxCol = j / mBoxSize; + return boxRow * mBoxSize + boxCol; + } + + public void print() { + for(int i = 0; i < mBoardSize; i++) { + if(i % mBoxSize == 0) + System.out.println(" -----------------------"); + for(int j = 0; j < mBoardSize; j++) { + if(j % mBoxSize == 0) + System.out.print("| "); + System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : " "); + System.out.print(' '); + } + + System.out.println("|"); + } + + System.out.println(" -----------------------"); + } +} diff --git a/Task/Sudoku/MATLAB/sudoku-1.m b/Task/Sudoku/MATLAB/sudoku-1.m new file mode 100644 index 0000000000..b62608f216 --- /dev/null +++ b/Task/Sudoku/MATLAB/sudoku-1.m @@ -0,0 +1,353 @@ +function solution = sudokuSolver(sudokuGrid) + + %Define what each of the sub-boxes of the sudoku grid are by defining + %the start and end coordinates of each sub-box. The indecies represent + %the column and row of a grid coordinate on the actual sudoku grid. + %The contents of each cell with the same grid coordinates contain the + %information to determine which sub-box that grid coordinate is + %contained in on the sudoku grid. The array in position 1, i.e. + %subBoxes{row,column}(1), represents the row indecies of the subbox. + %The array in position 2, i.e. subBoxes{row,column}(2),represents the + %column indecies of the subbox. + + subBoxes(1:9,1:9) = {{(1:3),(1:3)}}; + subBoxes(4:6,:)= {{(4:6),(1:3)}}; + subBoxes(7:9,:)= {{(7:9),(1:3)}}; + + for column = (4:6) + for row = (1:9) + subBoxes{row,column}(2)= {4:6}; + end + end + for column = (7:9) + for row = (1:9) + subBoxes{row,column}(2)= {7:9}; + end + end + + %Generate a cell of arrays which contain the possible values of the + %sudoku grid for each cell in the grid. The possible values a specific + %grid coordinate can take share the same indices as the sudoku grid + %coordinate they represent. + %For example sudokuGrid(m,n) can be possibly filled in by the + %values stored in the array at possibleValues(m,n). + possibleValues(1:9,1:9) = { (1:9) }; + + %Filter the possibleValues so that no entry exists for coordinates that + %have already been filled in. This will replace any array with an empty + %array in the possibleValues cell matrix at the coordinates of a grid + %already filled in the sudoku grid. + possibleValues( ~isnan(sudokuGrid) )={[]}; + + %Iterate through each grid coordinate and filter out the possible + %values for that grid point that aren't alowed by the rules given the + %current values that are filled in. Or, if there is only one possible + %value for the current coordinate, fill it in. + + solution = sudokuGrid; %so the original sudoku input isn't modified + memory = 0; %contains the previous iterations possibleValues + dontStop = true; %stops the while loop when nothing else can be reasoned about the sudoku + + while( dontStop ) + +%% Process of elimination deduction method + + while( ~isequal(possibleValues,memory) ) %Stops using the process of elimination deduction method when this deduction rule stops working + + memory = possibleValues; %Copies the current possibleValues into memory, for the above conditional on the next iteration. + + %Iterate through everything + for row = (1:9) + for column = (1:9) + + if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value. + + %Look at column to see what values have already + %been filled in and thus the current grid + %coordinate can't be + removableValues = solution( ~isnan(solution(:,column)),column ); + + %If there are any values that have been assigned to + %other cells in the same column, filter those out + %of the current cell's possiblValues + if ~isempty(removableValues) + for m = ( 1:numel(removableValues) ) + possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[]; + end + end + + %If the current grid coordinate can only atain one + %possible value, assign it that value + if numel( possibleValues{row,column} ) == 1 + solution(row,column) = possibleValues{row,column}; + possibleValues(row,column)={[]}; + end + end %end if + + if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value. + + %Look at row to see what values have already + %been filled in and thus the current grid + %coordinate can't be + removableValues = solution( row,~isnan(solution(row,:)) ); + + %If there are any values that have been assigned to + %other cells in the same row, filter those out + %of the current cell's possiblValues + if ~isempty(removableValues) + for m = ( 1:numel(removableValues) ) + possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[]; + end + end + + %If the current grid coordinate can only atain one + %possible value, assign it that value + if numel( possibleValues{row,column} ) == 1 + solution(row,column) = possibleValues{row,column}; + possibleValues(row,column)={[]}; + end + end %end if + + if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value. + + %Look at sub-box to see if any possible values can be + %filtered out. First pull the boundaries of the sub-box + %containing the current array coordinate + currentBoxBoundaries=subBoxes{row,column}; + + %Then pull the sub-boxes values out of the solution + box = solution(currentBoxBoundaries{:}); + + %Look at sub-box to see what values have already + %been filled in and thus the current grid + %coordinate can't be + removableValues = box( ~isnan(box) ); + + %If there are any values that have been assigned to + %other cells in the same sub-box, filter those out + %of the current cell's possiblValues + if ~isempty(removableValues) + for m = ( 1:numel(removableValues) ) + possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[]; + end + end + + %If the current grid coordinate can only atain one + %possible value, assign it that value + if numel( possibleValues{row,column} ) == 1 + solution(row,column) = possibleValues{row,column}; + possibleValues(row,column)={[]}; + end + end %end if + + end %end for column + end %end for row + end %stop process of elimination + +%% Check that there are no contradictions in the solved grid coordinates. + + %Check that each row at most contains one of each of the integers + %from 1 to 9 + if ~isempty( find( histc( solution,(1:9),1 )>1 ) ) + solution = false; + return + end + + %Check that each column at most contains one of each of the integers + %from 1 to 9 + if ~isempty( find( histc( solution,(1:9),2 )>1 ) ) + solution = false; + return + end + + %Check that each sub-box at most contains one of each of the integers + %from 1 to 9 + subBoxBins = zeros(9,9); + counter = 0; + for row = [2 5 8] + for column = [2 5 8] + counter = counter +1; + + %because the sub-boxes are extracted as square matricies, + %we need to reshape them into row vectors so all of the + %boxes can be input into histc simultaneously + subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 ); + end + end + if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) ) + solution = false; + return + end + + %Check to make sure there are no grid coordinates that are not + %filled in and have no possible values. + + [rowStack,columnStack] = find(isnan(solution)); %extracts the indicies of the unsolved grid coordinates + if (numel(rowStack) > 0) + + for counter = (1:numel(rowStack)) + if isempty(possibleValues{rowStack(counter),columnStack(counter)}) + solution = false; + return + end + end + + %if there are no more grid coordinates to be filed in then the + %sudoku is solved and we can return the solution without further + %computation + elseif (numel(rowStack) == 0) + return + end + +%% Use the unique relative compliment of sets deduction method + + %Because no more information can be determined by the process of + %ellimination we have to try a new method of reasoning. Now we will + %look at the possible values a cell can take. If there is a value that + %that grid coordinate can take but no other coordinates in the same row, + %column or sub-box can take that value then we assign that coordinate + %that value. + + keepGoing = true; %signals to keep applying rules to the current grid-coordinate because it hasn't been solved using previous rules + dontStop = false; %if this method doesn't figure anything out, this will terminate the top level while loop + + [rowStack,columnStack] = find(isnan(solution)); %This will also take care of the case where the sudoku is solved + counter = 0; %makes sure the loop terminates when there are no more cells to consider + + while( keepGoing && (counter < numel(rowStack)) ) %stop this method of reasoning when the value of one of the cells has been determined and return to the process of elimination method + + counter = counter + 1; + + row = rowStack(counter); + column = columnStack(counter); + + gridPossibles = [possibleValues{row,column}]; + + coords = (1:9); + coords(column) = []; + rowPossibles = [possibleValues{row,coords}]; %extract possible values for everything in the same row except the current grid coordinate + + totalMatches = zeros( numel(gridPossibles),1 ); %preallocate for speed + + %count how many times a possible value for the current cell + %appears as a possible value for the cells in the same row + for n = ( 1:numel(gridPossibles) ) + totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) ); + end + + %remove any possible values for the current cell that have + %matches in other cells + gridPossibles = gridPossibles(totalMatches==0); + + %if there is only one possible value that the current cell can + %take that aren't shared by other cells, assign that value to + %the current cell. + if numel(gridPossibles) == 1 + + solution(row,column) = gridPossibles; + possibleValues(row,column)={[]}; + keepGoing = false; %stop this method of deduction and return to the process of elimination + dontStop = true; %keep the top level loop going + + end + + if(keepGoing) %do the same as above but for the current cell's column + + gridPossibles = [possibleValues{row,column}]; + + coords = (1:9); + coords(row) = []; + columnPossibles = [possibleValues{coords,column}]; + + totalMatches = zeros( numel(gridPossibles),1 ); + for n = ( 1:numel(gridPossibles) ) + totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) ); + end + + gridPossibles = gridPossibles(totalMatches==0); + + if numel(gridPossibles) == 1 + + solution(row,column) = gridPossibles; + possibleValues(row,column)={[]}; + keepGoing = false; + dontStop = true; + + end + end + + if(keepGoing) %do the same as above but for the current cell's sub-box + + gridPossibles = [possibleValues{row,column}]; + + currentBoxBoundaries = subBoxes{row,column}; + subBoxPossibles = []; + for m = currentBoxBoundaries{1} + for n = currentBoxBoundaries{2} + if ~((m == row) && (n == column)) + subBoxPossibles = [subBoxPossibles possibleValues{m,n}]; + end + end + end + + totalMatches = zeros( numel(gridPossibles),1 ); + for n = ( 1:numel(gridPossibles) ) + totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) ); + end + + gridPossibles = gridPossibles(totalMatches==0); + + if numel(gridPossibles) == 1 + + solution(row,column) = gridPossibles; + possibleValues(row,column)={[]}; + keepGoing = false; + dontStop = true; + + end + end %end + + end %end set comliment rule while loop + end %end top-level while loop + +%% Depth-first search of the solution tree + + %There is no more reasoning that can solve the puzzle so now it is time + %for a depth-first search of the possible answers, basically + %guess-and-check. This is implimented recursively. + + [rowStack,columnStack] = find(isnan(solution)); %Get all of the unsolved cells + + if (numel(rowStack) > 0) %If all of the above stuff terminates then there will be at least one grid coordinate not filled in + + %Treat the rowStack and columnStack like stacks, and pop the top + %value off the stack to act as the current node whose + %possibleValues to search through, then assign the possible values + %of that grid coordinate to a variable that holds that values to + %search through + searchTreeNodes = possibleValues{rowStack(1),columnStack(1)}; + + keepSearching = true; %used to continue the search + counter = 0; %counts the amount of possible values searched for the current node + tempSolution = solution; %used so that the solution is not overriden until a solution hase been found + + while( keepSearching && (counter < numel(searchTreeNodes)) ) %stop recursing if we run out of possible values for the current node + + counter = counter + 1; + tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter); %assign a possible value to the current node in the tree + tempSolution = sudokuSolver(tempSolution); %recursively call the solver with the current guess value for the current grid coordinate + + if ~islogical(tempSolution) %if tempSolution is not a boolean but a valid sudoku stop recursing and set solution to tempSolution + keepSearching = false; + solution = tempSolution; + elseif counter == numel(searchTreeNodes) %if we have run out of guesses for the current node, stop recursing and return a value of "false" for the solution + solution = false; + else %reset tempSolution to the current state of the board and try the next guess for the possible value of the current cell + tempSolution = solution; + end + + end %end recursion + end %end if + +%% End of program +end %end sudokuSolver diff --git a/Task/Sudoku/MATLAB/sudoku-2.m b/Task/Sudoku/MATLAB/sudoku-2.m new file mode 100644 index 0000000000..3f89999c30 --- /dev/null +++ b/Task/Sudoku/MATLAB/sudoku-2.m @@ -0,0 +1,9 @@ +sudoku = [NaN NaN NaN NaN 8 3 9 NaN NaN + 1 NaN NaN NaN NaN NaN NaN 3 NaN + NaN NaN 4 NaN NaN NaN NaN 7 NaN + NaN 4 2 NaN 3 NaN NaN NaN NaN + 6 NaN NaN NaN NaN NaN NaN NaN 4 + NaN NaN NaN NaN 7 NaN NaN 1 NaN + NaN 2 NaN NaN NaN NaN NaN NaN NaN + NaN 8 NaN NaN NaN 9 2 NaN NaN + NaN NaN NaN 2 5 NaN NaN NaN 6] diff --git a/Task/Sudoku/MATLAB/sudoku-3.m b/Task/Sudoku/MATLAB/sudoku-3.m new file mode 100644 index 0000000000..0e4c0eb8a6 --- /dev/null +++ b/Task/Sudoku/MATLAB/sudoku-3.m @@ -0,0 +1,11 @@ +solution = + + 7 6 5 4 8 3 9 2 1 + 1 9 8 7 2 6 4 3 5 + 2 3 4 9 1 5 6 7 8 + 8 4 2 5 3 1 7 6 9 + 6 1 7 8 9 2 3 5 4 + 3 5 9 6 7 4 8 1 2 + 9 2 6 1 4 7 5 8 3 + 5 8 1 3 6 9 2 4 7 + 4 7 3 2 5 8 1 9 6 diff --git a/Task/Sudoku/Mathematica/sudoku-1.math b/Task/Sudoku/Mathematica/sudoku-1.math new file mode 100644 index 0000000000..9ea1a4d429 --- /dev/null +++ b/Task/Sudoku/Mathematica/sudoku-1.math @@ -0,0 +1,13 @@ +solve[array_] := + NestWhile[ + Join @@ Function[newarray, + Function[{i, j}, + Table[ReplacePart[newarray, + Position[newarray, 0, {2}, 1][[1]] -> n], {n, + Select[Range@9, + FreeQ[newarray[[i]], #] && FreeQ[newarray[[All, j]], #] && + FreeQ[Partition[ + newarray, {3, 3}][[Sequence @@ + Quotient[{i, j}, 3, -2]]], #] &]}]] @@ + Position[newarray, 0, {2}, 1][[1]]] /@ # &, {array}, ! + FreeQ[#, 0] &] diff --git a/Task/Sudoku/Mathematica/sudoku-2.math b/Task/Sudoku/Mathematica/sudoku-2.math new file mode 100644 index 0000000000..78afbff115 --- /dev/null +++ b/Task/Sudoku/Mathematica/sudoku-2.math @@ -0,0 +1,9 @@ +solve[{{9, 7, 0, 3, 0, 0, 0, 6, 0}, + {0, 6, 0, 7, 5, 0, 0, 0, 0}, + {0, 0, 0, 0, 0, 8, 0, 5, 0}, + {0, 0, 0, 0, 0, 0, 6, 7, 0}, + {0, 0, 0, 0, 3, 0, 0, 0, 0}, + {0, 5, 3, 9, 0, 0, 2, 0, 0}, + {7, 0, 0, 0, 2, 5, 0, 0, 0}, + {0, 0, 2, 0, 1, 0, 0, 0, 8}, + {0, 4, 0, 0, 0, 7, 3, 0, 0}}] diff --git a/Task/Sudoku/OCaml/sudoku.ocaml b/Task/Sudoku/OCaml/sudoku.ocaml new file mode 100644 index 0000000000..77dbea8530 --- /dev/null +++ b/Task/Sudoku/OCaml/sudoku.ocaml @@ -0,0 +1,70 @@ +(* Ocamlgraph demo program: solving the Sudoku puzzle using graph coloring + Copyright 2004-2007 Sylvain Conchon, Jean-Christophe Filliatre, Julien Signoles + + This software is free software; you can redistribute it and/or modify + it under the terms of the GNU Library General Public License version 2, + with the special exception on linking described in file LICENSE. + + This software is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *) + +open Format +open Graph + +(* We use undirected graphs with nodes containing a pair of integers + (the cell coordinates in 0..8 x 0..8). + The integer marks of the nodes will store the colors. *) +module G = Imperative.Graph.Abstract(struct type t = int * int end) + +(* The Sudoku grid = a graph with 9x9 nodes *) +let g = G.create () + +(* We create the 9x9 nodes, add them to the graph and keep them in a matrix + for later access *) +let nodes = + let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in + Array.init 9 (fun i -> Array.init 9 (new_node i)) + +let node i j = nodes.(i).(j) (* shortcut for easier access *) + +(* We add the edges: + two nodes are connected whenever they can't have the same value, + i.e. they belong to the same line, the same column or the same 3x3 group *) +let () = + for i = 0 to 8 do for j = 0 to 8 do + for k = 0 to 8 do + if k <> i then G.add_edge g (node i j) (node k j); + if k <> j then G.add_edge g (node i j) (node i k); + done; + let gi = 3 * (i / 3) and gj = 3 * (j / 3) in + for di = 0 to 2 do for dj = 0 to 2 do + let i' = gi + di and j' = gj + dj in + if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') + done done + done done + +(* Displaying the current state of the graph *) +let display () = + for i = 0 to 8 do + for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; + printf "\n"; + done; + printf "@?" + +(* We read the initial constraints from standard input and we display g *) +let () = + for i = 0 to 8 do + let s = read_line () in + for j = 0 to 8 do match s.[j] with + | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') + | _ -> () + done + done; + display (); + printf "---------@." + +(* We solve the Sudoku by 9-coloring the graph g and we display the solution *) +module C = Coloring.Mark(G) + +let () = C.coloring g 9; display () diff --git a/Task/Sudoku/Oz/sudoku.oz b/Task/Sudoku/Oz/sudoku.oz new file mode 100644 index 0000000000..67d7bd4723 --- /dev/null +++ b/Task/Sudoku/Oz/sudoku.oz @@ -0,0 +1,84 @@ +declare + %% a puzzle is a function that returns an initial board configuration + fun {Puzzle1} + %% a board is a list of 9 rows + [[4 _ _ _ _ _ _ 6 _] + [5 _ _ _ 8 _ 9 _ _] + [3 _ _ _ _ 1 _ _ _] + + [_ 2 _ 7 _ _ _ _ 1] + [_ 9 _ _ _ _ _ 4 _] + [8 _ _ _ _ 3 _ 5 _] + + [_ _ _ 2 _ _ _ _ 7] + [_ _ 6 _ 5 _ _ _ 8] + [_ 1 _ _ _ _ _ _ 6]] + end + + %% Returns a list of solutions for the given puzzle. + fun {Solve Puzzle} + {SearchAll {GetScript Puzzle}} + end + + %% Creates a solver script for a puzzle. + fun {GetScript Puzzle} + proc {$ Board} + %% Every row is a list of nine finite domain vars + %% with the domain 1..9. + Board = {MapRange fun {$ _} {FD.list 9 1#9} end} + %% Post initial configuration. + Board = {Puzzle} + + %% The core constraints: + {ForAll {Rows Board} FD.distinct} + {ForAll {Columns Board} FD.distinct} + {ForAll {Boxes Board} FD.distinct} + + %% Search if necessary. + {FD.distribute ff {Flatten Board}} + end + end + + %% Returns the board as a list of rows. + fun {Rows Board} + Board %% This is already the representation we have chosen. + end + + %% Returns the board as a list of columns. + fun {Columns Board} + {MapRange fun {$ I} {Column Board I} end} + end + + %% Returns the board as a list of boxes (sub-grids). + fun {Boxes Board} + {MapRange fun {$ I} {Box Board I} end} + end + + %% Helper function: map the range 1..9 to something. + fun {MapRange F} + {Map [1 2 3 4 5 6 7 8 9] F} + end + + %% Returns a column of the board as a list of fields. + fun {Column Board Index} + {Map Board + fun {$ Row} + {Nth Row Index} + end + } + end + + %% Returns a box of the board as a list of fields. + fun {Box Board Index} + Index0 = Index-1 + Fields = {Flatten Board} + Start = (Index0 div 3) * 27 + (Index0 mod 3)*3 + in + {Flatten + for I in 0..2 collect:C do + {C {List.take {List.drop Fields Start+I*9} 3}} + end + } + end +in + {Inspect {Solve Puzzle1}.1} diff --git a/Task/Sudoku/Perl-6/sudoku.pl6 b/Task/Sudoku/Perl-6/sudoku.pl6 new file mode 100644 index 0000000000..6699b3a9dc --- /dev/null +++ b/Task/Sudoku/Perl-6/sudoku.pl6 @@ -0,0 +1,42 @@ +use v6; +my @A = < + 5 3 0 0 2 4 7 0 0 + 0 0 2 0 0 0 8 0 0 + 1 0 0 7 0 3 9 0 2 + + 0 0 8 0 7 2 0 4 9 + 0 2 0 9 8 0 0 7 0 + 7 9 0 0 0 0 0 8 0 + + 0 0 0 0 3 0 5 0 6 + 9 6 0 0 1 0 3 0 0 + 0 5 0 6 9 0 0 1 0 +>; + +my &I = * div 9; # line number +my &J = * % 9; # column number +my &K = { ($_ div 27) * 3 + $_ % 9 div 3 }; # bloc number + +sub solve { + for ^@A -> $i { + next if @A[$i]; + my @taken-values = @A[ + grep { + I($_) == I($i) || J($_) == J($i) || K($_) == K($i) + }, ^@A + ]; + for grep none(@taken-values), 1..9 { + @A[$i] = $_; + solve; + } + return @A[$i] = 0; + } + my $i = 1; + for ^@A { + print "@A[$_] "; + print " " if $i %% 3; + print "\n" if $i %% 9; + print "\n" if $i++ %% 27; + } +} +solve; diff --git a/Task/Sudoku/Perl/sudoku.pl b/Task/Sudoku/Perl/sudoku.pl new file mode 100644 index 0000000000..590314b686 --- /dev/null +++ b/Task/Sudoku/Perl/sudoku.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl +use integer; +use strict; + +my @A = qw( + 5 3 0 0 2 4 7 0 0 + 0 0 2 0 0 0 8 0 0 + 1 0 0 7 0 3 9 0 2 + + 0 0 8 0 7 2 0 4 9 + 0 2 0 9 8 0 0 7 0 + 7 9 0 0 0 0 0 8 0 + + 0 0 0 0 3 0 5 0 6 + 9 6 0 0 1 0 3 0 0 + 0 5 0 6 9 0 0 1 0 +); + +sub solve { + my $i; + foreach $i ( 0 .. 80 ) { + next if $A[$i]; + my %t = map { + $_ / 9 == $i / 9 || + $_ % 9 == $i % 9 || + $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 + ? $A[$_] : 0, + 1; + } 0 .. 80; + solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; + return $A[$i] = 0; + } + $i = 0; + foreach (@A) { + print "-----+-----+-----\n" if !($i%27) && $i; + print !($i%9) ? '': $i%3 ? ' ' : '|', $_; + print "\n" unless ++$i%9; + } +} +solve(); diff --git a/Task/Sudoku/PicoLisp/sudoku-1.l b/Task/Sudoku/PicoLisp/sudoku-1.l new file mode 100644 index 0000000000..b502d243dd --- /dev/null +++ b/Task/Sudoku/PicoLisp/sudoku-1.l @@ -0,0 +1,82 @@ +(load "lib/simul.l") + +### Fields/Board ### +# val lst + +(setq + *Board (grid 9 9) + *Fields (apply append *Board) ) + +# Init values to zero (empty) +(for L *Board + (for This L + (=: val 0) ) ) + +# Build lookup lists +(for (X . L) *Board + (for (Y . This) L + (=: lst + (make + (let A (* 3 (/ (dec X) 3)) + (do 3 + (inc 'A) + (let B (* 3 (/ (dec Y) 3)) + (do 3 + (inc 'B) + (unless (and (= A X) (= B Y)) + (link + (prop (get *Board A B) 'val) ) ) ) ) ) ) + (for Dir '(`west `east `south `north) + (for (This (Dir This) This (Dir This)) + (unless (memq (:: val) (made)) + (link (:: val)) ) ) ) ) ) ) ) + +# Cut connections (for display only) +(for (X . L) *Board + (for (Y . This) L + (when (member X (3 6)) + (con (car (val This))) ) + (when (member Y (4 7)) + (set (cdr (val This))) ) ) ) + +# Display board +(de display () + (disp *Board 0 + '((This) + (if (=0 (: val)) + " " + (pack " " (: val) " ") ) ) ) ) + +# Initialize board +(de main (Lst) + (for (Y . L) Lst + (for (X . N) L + (put *Board X (- 10 Y) 'val N) ) ) + (display) ) + +# Find solution +(de go () + (unless + (recur (*Fields) + (with (car *Fields) + (if (=0 (: val)) + (loop + (NIL + (or + (assoc (inc (:: val)) (: lst)) + (recurse (cdr *Fields)) ) ) + (T (= 9 (: val)) (=: val 0)) ) + (recurse (cdr *Fields)) ) ) ) + (display) ) ) + +(main + (quote + (5 3 0 0 7 0 0 0 0) + (6 0 0 1 9 5 0 0 0) + (0 9 8 0 0 0 0 6 0) + (8 0 0 0 6 0 0 0 3) + (4 0 0 8 0 3 0 0 1) + (7 0 0 0 2 0 0 0 6) + (0 6 0 0 0 0 2 8 0) + (0 0 0 4 1 9 0 0 5) + (0 0 0 0 8 0 0 7 9) ) ) diff --git a/Task/Sudoku/PicoLisp/sudoku-2.l b/Task/Sudoku/PicoLisp/sudoku-2.l new file mode 100644 index 0000000000..3770a5c2e0 --- /dev/null +++ b/Task/Sudoku/PicoLisp/sudoku-2.l @@ -0,0 +1 @@ +(go) diff --git a/Task/Sudoku/Prolog/sudoku.pro b/Task/Sudoku/Prolog/sudoku.pro new file mode 100644 index 0000000000..e1fe09c75c --- /dev/null +++ b/Task/Sudoku/Prolog/sudoku.pro @@ -0,0 +1,26 @@ +:- use_module(library(clpfd)). + +sudoku(Rows) :- + length(Rows, 9), maplist(length_(9), Rows), + append(Rows, Vs), Vs ins 1..9, + maplist(all_distinct, Rows), + transpose(Rows, Columns), maplist(all_distinct, Columns), + Rows = [A,B,C,D,E,F,G,H,I], + blocks(A, B, C), blocks(D, E, F), blocks(G, H, I). + +length_(L, Ls) :- length(Ls, L). + +blocks([], [], []). +blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :- + all_distinct([A,B,C,D,E,F,G,H,I]), + blocks(Bs1, Bs2, Bs3). + +problem(1, [[_,_,_,_,_,_,_,_,_], + [_,_,_,_,_,3,_,8,5], + [_,_,1,_,2,_,_,_,_], + [_,_,_,5,_,7,_,_,_], + [_,_,4,_,_,_,1,_,_], + [_,9,_,_,_,_,_,_,_], + [5,_,_,_,_,_,_,7,3], + [_,_,2,_,1,_,_,_,_], + [_,_,_,_,4,_,_,_,9]]). diff --git a/Task/Sudoku/PureBasic/sudoku.purebasic b/Task/Sudoku/PureBasic/sudoku.purebasic new file mode 100644 index 0000000000..74afc512e1 --- /dev/null +++ b/Task/Sudoku/PureBasic/sudoku.purebasic @@ -0,0 +1,111 @@ +DataSection + puzzle: + Data.s "394002670" + Data.s "000300400" + Data.s "500690020" + Data.s "045000900" + Data.s "600000007" + Data.s "007000580" + Data.s "010067008" + Data.s "009008000" + Data.s "026400735" +EndDataSection + +#IsPossible = 0 +#IsNotPossible = 1 +#Unknown = 0 +Global Dim sudoku(8, 8) +;-declarations +Declare readSudoku() +Declare displaySudoku() +Declare.s buildpossible(x, y, Array possible.b(1)) +Declare solvePuzzle(x = 0, y = 0) + +;-procedures +Procedure readSudoku() + Protected a$, row, column + + Restore puzzle + For row = 0 To 8 + Read.s a$ + For column = 0 To 8 + sudoku(column, row) = Val(Mid(a$, column + 1, 1)) + Next + Next +EndProcedure + +Procedure displaySudoku() + Protected row, column + Static border.s = "+-----+-----+-----+" + For row = 0 To 8 + If row % 3 = 0: PrintN(border): EndIf + For column = 0 To 8 + If column % 3 = 0: Print("|"): Else: Print(" "): EndIf + If sudoku(column, row): Print(Str(sudoku(column, row))): Else: Print("."): EndIf + Next + PrintN("|") + Next + PrintN(border) +EndProcedure + +Procedure.s buildpossible(x, y, Array possible.b(1)) + Protected index, column, row, boxColumn = (x / 3) * 3, boxRow = (y / 3) * 3 + Dim possible.b(9) + + For index = 0 To 8 + possible(sudoku(index, y)) = #IsNotPossible ;record possibles in column + possible(sudoku(x, index)) = #IsNotPossible ;record possibles in row + Next + + ;record possibles in box + For row = boxRow To boxRow + 2 + For column = boxColumn To boxColumn + 2 + possible(sudoku(column, row)) = #IsNotPossible + Next + Next +EndProcedure + +Procedure solvePuzzle(x = 0, y = 0) + Protected row, column, spot, digit + Dim possible.b(9) + + For row = y To 8 + For column = x To 8 + If sudoku(column, row) = #Unknown + buildpossible(column, row, possible()) + + For digit = 1 To 9 + If possible(digit) = #IsPossible + sudoku(column, row) = digit + spot = row * 9 + column + 1 + If solvePuzzle(spot % 9, spot / 9) + Break 3 + EndIf + EndIf + Next + + If digit = 10 + sudoku(column, row) = #Unknown + ProcedureReturn #False + EndIf + EndIf + Next + x = 0 ;reset column start point + Next + ProcedureReturn #True +EndProcedure + +If OpenConsole() + readSudoku() + displaySudoku() + If solvePuzzle() + PrintN("Solved.") + displaySudoku() + Else + PrintN("Unable to solve puzzle") ;due to bad starting data + EndIf + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Sudoku/Python/sudoku.py b/Task/Sudoku/Python/sudoku.py new file mode 100644 index 0000000000..09a97693ea --- /dev/null +++ b/Task/Sudoku/Python/sudoku.py @@ -0,0 +1,83 @@ +def initiate(): + box.append([0, 1, 2, 9, 10, 11, 18, 19, 20]) + box.append([3, 4, 5, 12, 13, 14, 21, 22, 23]) + box.append([6, 7, 8, 15, 16, 17, 24, 25, 26]) + box.append([27, 28, 29, 36, 37, 38, 45, 46, 47]) + box.append([30, 31, 32, 39, 40, 41, 48, 49, 50]) + box.append([33, 34, 35, 42, 43, 44, 51, 52, 53]) + box.append([54, 55, 56, 63, 64, 65, 72, 73, 74]) + box.append([57, 58, 59, 66, 67, 68, 75, 76, 77]) + box.append([60, 61, 62, 69, 70, 71, 78, 79, 80]) + for i in range(0, 81, 9): + row.append(range(i, i+9)) + for i in range(9): + column.append(range(i, 80+i, 9)) + +def valid(n, pos): + current_row = pos/9 + current_col = pos%9 + current_box = (current_row/3)*3 + (current_col/3) + for i in row[current_row]: + if (grid[i] == n): + return False + for i in column[current_col]: + if (grid[i] == n): + return False + for i in box[current_box]: + if (grid[i] == n): + return False + return True + +def solve(): + i = 0 + proceed = 1 + while(i < 81): + if given[i]: + if proceed: + i += 1 + else: + i -= 1 + else: + n = grid[i] + prev = grid[i] + while(n < 9): + if (n < 9): + n += 1 + if valid(n, i): + grid[i] = n + proceed = 1 + break + if (grid[i] == prev): + grid[i] = 0 + proceed = 0 + if proceed: + i += 1 + else: + i -=1 + +def inputs(): + nextt = 'T' + number = 0 + pos = 0 + while(not(nextt == 'N' or nextt == 'n')): + print "Enter the position:", + pos = int(raw_input()) + given[pos - 1] = True + print "Enter the numerical:", + number = int(raw_input()) + grid[pos - 1] = number + print "Do you want to enter another given?(Y, for yes: N, for no)" + nextt = raw_input() + + +grid = [0]*81 +given = [False]*81 +box = [] +row = [] +column = [] +initiate() +inputs() +solve() +for i in range(9): + print grid[i*9:i*9+9] +raw_input() diff --git a/Task/Sudoku/Rascal/sudoku.rascal b/Task/Sudoku/Rascal/sudoku.rascal new file mode 100644 index 0000000000..7e4b2db217 --- /dev/null +++ b/Task/Sudoku/Rascal/sudoku.rascal @@ -0,0 +1,84 @@ +import Prelude; +import vis::Figure; +import vis::Render; + +public rel[int,int,int] sudoku(rel[int x, int y, int v] sudoku){ + annotated= annotateGrid(sudoku); + solved = {<0,0,0,0,{0}>}; + + while(!isEmpty(solved)){ + for (n <- [0 ..8]){ + column = domainR(annotated, {n}); + annotated -= column; + annotated += reduceOptions(column); + + row = { | <- annotated, y==n}; + annotated -= row; + annotated += reduceOptions(row); + + grid1 = { | <- annotated, g==n}; + annotated -= grid1; + annotated += reduceOptions(grid1); + } + + solved = { | <- annotated, size(p)==1}; + annotated -= solved; + annotated += { | <- solved}; + } + + result = { | <- annotated}; + return result; +} + + +//adds gridnumber and default set of options +public rel[int,int,int,int,set[int]] annotateGrid(rel[int x, int y, int v] sudoku){ + result = {}; + for ( <- sudoku){ + g = 0; + if (x<3 && y<3) g = 0; + if (25 && y<3) g = 2; + + if (x<3 && 25 && 25) g=6; + if (25) g=7; + if (x>5 && y>5) g=8; + + result += ; + } + return result; +} + +//reduces set of options +public rel[int,int,int,int,set[int]] reduceOptions(rel[int x, int y, int v, int g, set[int] p] subSudoku){ + solved = { | <- subSudoku, v!=0}; + numbers = {*[1 .. 9]} - {v | <- solved}; + remaining = { | <- subSudoku-solved}; + result = remaining + solved; + return result; +} + +//a function to visualize the result +public void displaySudoku(rel[int x, int y, int v] sudoku){ + points = [box(text(""), align(0.111111*(x+1),0.111111*(y+1)),shrink(0.1)) | <- sudoku]; + print(points); + render(overlay([*points], aspectRatio(1.0))); +} + +//a sudoku +public rel[int, int, int] sudokuA = +{ +<0,0,3>, <1,0,9>, <2,0,4>, <3,0,0>, <4,0,0>, <5,0,2>, <6,0,6>, <7,0,7>, <8,0,0>, +<0,1,0>, <1,1,0>, <2,1,0>, <3,1,3>, <4,1,0>, <5,1,0>, <6,1,4>, <7,1,0>, <8,1,0>, +<0,2,5>, <1,2,0>, <2,2,0>, <3,2,6>, <4,2,9>, <5,2,0>, <6,2,0>, <7,2,2>, <8,2,0>, +<0,3,0>, <1,3,4>, <2,3,5>, <3,3,0>, <4,3,0>, <5,3,0>, <6,3,9>, <7,3,0>, <8,3,0>, +<0,4,6>, <1,4,0>, <2,4,0>, <3,4,0>, <4,4,0>, <5,4,0>, <6,4,0>, <7,4,0>, <8,4,7>, +<0,5,0>, <1,5,0>, <2,5,7>, <3,5,0>, <4,5,0>, <5,5,0>, <6,5,5>, <7,5,8>, <8,5,0>, +<0,6,0>, <1,6,1>, <2,6,0>, <3,6,0>, <4,6,6>, <5,6,7>, <6,6,0>, <7,6,0>, <8,6,8>, +<0,7,0>, <1,7,0>, <2,7,9>, <3,7,0>, <4,7,0>, <5,7,8>, <6,7,0>, <7,7,0>, <8,7,0>, +<0,8,0>, <1,8,2>, <2,8,6>, <3,8,4>, <4,8,0>, <5,8,0>, <6,8,7>, <7,8,3>, <8,8,5> +}; diff --git a/Task/Sudoku/Ruby/sudoku.rb b/Task/Sudoku/Ruby/sudoku.rb new file mode 100644 index 0000000000..1f148019fc --- /dev/null +++ b/Task/Sudoku/Ruby/sudoku.rb @@ -0,0 +1,111 @@ +def read_matrix(fh) + matrix = [] + + (0..8).each { |i| + l = fh.readline + matrix[i] = [] + (0..8).each { |j| + matrix[i][j] = l[j..j].to_i + } + } + matrix +end + +def permissible(matrix, i, j) + ok = [true] * 9 + # Same as another in the column isn't permissible... + (0..8).each { |i2| + next if matrix[i2][j] == 0 + ok[matrix[i2][j] - 1] = false + } + # Same as another in the row isn't permissible... + (0..8).each { |j2| + next if matrix[i][j2] == 0 + ok[matrix[i][j2] - 1] = false + } + # Same as another in the 3x3 block isn't permissible... + igroup = (i / 3) * 3 + jgroup = (j / 3) * 3 + (igroup..(igroup + 2)).each { |i2| + (jgroup..(jgroup + 2)).each { |j2| + next if matrix[i2][j2] == 0 + ok[matrix[i2][j2] - 1] = false + } + } + # Convert to the array format... + (1..9).select { |i2| ok[i2-1] } +end + +def deep_copy_sudoku(matrix) + matrix.collect { |row| row.dup } +end + +def solve_sudoku(matrix) + loop do + options = [] + (0..8).each { |i| + (0..8).each { |j| + next if matrix[i][j] != 0 + p = permissible(matrix, i, j) + # If nothing is permissible, there is no solution at this level. + return nil if p.length == 0 + options.push({:i => i, :j => j, :permissible => p}) + } + } + # If the matrix is complete, we have a solution... + return matrix if options.length == 0 + + omin = options.min_by { |x| x[:permissible].length } + + # If there is an option with only one solution, set it and re-check permissibility + if omin[:permissible].length == 1 + matrix[omin[:i]][omin[:j]] = omin[:permissible][0] + next + end + + # We have two or more choices. We need to search both... + omin[:permissible].each { |v| + mtmp = deep_copy_sudoku(matrix) + mtmp[omin[:i]][omin[:j]] = v + ret = solve_sudoku(mtmp) + return ret if ret + } + + # We did an exhaustive search on this branch and nothing worked out. + return nil + end +end + +def print_matrix(matrix) + if not matrix + puts "Impossible" + return + end + + border = "+-----+-----+-----+" + (0..8).each { |i| + puts border if i%3 == 0 + (0..8).each { |j| + print(j%3 == 0 ? "|" : " ") + print(matrix[i][j] == 0 ? "." : matrix[i][j]) + } + print "|\n" + } + puts border +end + +matrix = read_matrix(DATA) +print_matrix(matrix) +puts +print_matrix(solve_sudoku(matrix)) + +__END__ +394__267_ +___3__4__ +5__69__2_ +_45___9__ +6_______7 +__7___58_ +_1__67__8 +__9__8___ +_264__735 diff --git a/Task/Sudoku/Scala/sudoku-1.scala b/Task/Sudoku/Scala/sudoku-1.scala new file mode 100644 index 0000000000..95a458bd74 --- /dev/null +++ b/Task/Sudoku/Scala/sudoku-1.scala @@ -0,0 +1,132 @@ +object SudokuSolver extends App { + + class Solver { + + var solution = new Array[Int](81) //listOfFields toArray + + val fp2m: Int => Tuple2[Int,Int] = pos => Pair(pos/9+1,pos%9+1) //get row, col from array position + val setAll = (1 to 9) toSet //all possibilities + + val arrayGroups = new Array[List[List[Int]]](81) + val sv: Int => Int = (row: Int) => (row-1)*9 //start value group row + val ev: Int => Int = (row: Int) => sv(row)+8 //end value group row + val fgc: (Int,Int) => Int = (i,col) => i*9+col-1 //get group col + val fgs: Int => (Int,Int) = p => Pair(p, p/(27)*3+p%9/3) //get group square box + for (pos <- 0 to 80) { + val (row,col) = fp2m(pos) + val gRow = (sv(row) to ev(row)).toList + val gCol = ((0 to 8) toList) map (fgc(_,col)) + val gSquare = (0 to 80 toList) map fgs filter (_._2==(fgs(pos))._2) map (_._1) + arrayGroups(pos) = List(gRow,gCol,gSquare) + } + val listGroups = arrayGroups toList + + val fpv4s: (Int) => List[Int] = pos => { //get possible values for solving + val setRow = (listGroups(pos)(0) map (solution(_))).toSet + val setCol = listGroups(pos)(1).map(solution(_)).toSet + val setSquare = listGroups(pos)(2).map(solution(_)).toSet + val setG = setRow++setCol++setSquare--Set(0) + val setPossible = setAll--setG + setPossible.toList.sortWith(_<_) + } + + + //solve the riddle: Nil ==> solution does not exist + def solve(listOfFields: List[Int]): List[Int] = { + solution = listOfFields toArray + + def checkSol(uncheckedSol: List[Int]): List[Int] = { + if (uncheckedSol == Nil) return Nil + solution = uncheckedSol toArray + val check = (0 to 80).map(fpv4s(_)).filter(_.size>0) + if (check == Nil) return uncheckedSol + return Nil + } + + val f1: Int => Pair[Int,Int] = p => Pair(p,listOfFields(p)) + val numFields = (0 to 80 toList) map f1 filter (_._2==0) + val iter = numFields map ((_: (Int,Int))._1) + var p_iter = 0 + + val first: () => Int = () => { + val ret = numFields match { + case Nil => -1 + case _ => numFields(0)._1 + } + ret + } + + val last: () => Int = () => { + val ret = numFields match { + case Nil => -1 + case _ => numFields(numFields.size-1)._1 + } + ret + } + + val hasPrev: () => Boolean = () => p_iter > 0 + val prev: () => Int = () => {p_iter -= 1; iter(p_iter)} + val hasNext: () => Boolean = () => p_iter < iter.size-1 + val next: () => Int = () => {p_iter += 1; iter(p_iter)} + val fixed: Int => Boolean = pos => listOfFields(pos) != 0 + val possiArray = new Array[List[Int]](numFields.size) + val firstUF = first() //first unfixed + if (firstUF < 0) return checkSol(solution.toList) //that is it! + var pif = iter(p_iter) //pos in fields + val lastUF = last() //last unfixed + val (row,col) = fp2m(pif) + possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_) + + while(pif <= lastUF) { + val (row,col) = fp2m(pif) + if (possiArray(p_iter) == null) possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_) + val possis = possiArray(p_iter) + if (possis.isEmpty) { + if (hasPrev()) { + possiArray(p_iter) = null + solution(pif) = 0 + pif = prev() + } else { + return Nil + } + } else { + solution(pif) = possis(0) + possiArray(p_iter) = (possis.toSet - possis(0)).toList.sortWith(_<_) + if (hasNext()) { + pif = next() + } else { + return checkSol(solution.toList) + } + } + } + checkSol(solution.toList) + } + } + + val f2Str: List[Int] => String = fields => { + val sepLine = "+---+---+---+" + val sepPoints = Set(2,5,8) + val fs: (Int, Int) => String = (i, v) => v.toString.replace("0"," ")+(if (sepPoints.contains(i%9)) "|" else "") + sepLine+"\n"+(0 to fields.size-1).map(i => (if (i%9==0) "|" else "")+fs(i,fields(i))+(if (i%9==8) if (sepPoints.contains(i/9)) "\n"+sepLine+"\n" else "\n" else "")).foldRight("")(_+_) + } + + val solver = new Solver() + + val riddle = List(3,9,4,0,0,2,6,7,0, + 0,0,0,3,0,0,4,0,0, + 5,0,0,6,9,0,0,2,0, + 0,4,5,0,0,0,9,0,0, + 6,0,0,0,0,0,0,0,7, + 0,0,7,0,0,0,5,8,0, + 0,1,0,0,6,7,0,0,8, + 0,0,9,0,0,8,0,0,0, + 0,2,6,4,0,0,7,3,5) + + println("riddle:") + println(f2Str(riddle)) + var solution = solver.solve(riddle) + + println("solution:") + println(solution match {case Nil => "no solution!!!" case _ => f2Str(solution)}) + +} diff --git a/Task/Sudoku/Scala/sudoku-2.scala b/Task/Sudoku/Scala/sudoku-2.scala new file mode 100644 index 0000000000..b950dad886 --- /dev/null +++ b/Task/Sudoku/Scala/sudoku-2.scala @@ -0,0 +1,118 @@ +object SudokuSolver extends App { + + object Solver { + var solution = new Array[Int](81) + + val fap: (Int, Int) => Int = (row, col) => (row)*9+col //function array position + + def solve(listOfFields: List[Int]): List[Int] = { + solution = listOfFields toArray + + val mRowSubset = new Array[Boolean](81) + val mColSubset = new Array[Boolean](81) + val mBoxSubset = new Array[Boolean](81) + + def initSubsets: Unit = { + for (row <- 0 to 8) { + for (col <- 0 to 8) { + val value = solution(fap(row, col)) + if (value != 0) + setSubsetValue(row, col, value, true) + } + } + } + + def setSubsetValue(r: Int, c: Int, value: Int, present: Boolean): Unit = { + mRowSubset(fap(r, value - 1)) = present + mColSubset(fap(c, value - 1)) = present + mBoxSubset(fap(computeBoxNo(r, c), value - 1)) = present + } + + def computeBoxNo(r: Int, c: Int): Int = { + val boxRow = r / 3 + val boxCol = c / 3 + return boxRow * 3 + boxCol + } + + def isValid(r: Int, c: Int, value: Int): Boolean = { + val vVal = value - 1 + val isPresent = mRowSubset(fap(r, vVal)) || mColSubset(fap(c, vVal)) || mBoxSubset(fap(computeBoxNo(r, c), vVal)) + return !isPresent + } + + def solve(row: Int, col: Int): Boolean = { + var r = row + var c = col + + if (r == 9) { + r = 0 + c += 1 + if (c == 9) + return true + } + + if(solution(fap(r,c)) != 0) + return solve(r+1,c) + for(value <- 1 to 9) + if(isValid(r, c, value)) { + solution(fap(r,c)) = value + setSubsetValue(r, c, value, true) + if(solve(r+1,c)) + return true + setSubsetValue(r, c, value, false) + } + solution(fap(r,c)) = 0 + return false + } + + def checkSol: Boolean = { + initSubsets + if ((mRowSubset.exists(_==false)) || (mColSubset.exists(_==false)) || (mBoxSubset.exists(_==false))) return false + true + } + + initSubsets + val ret = solve(0,0) + if (ret) + if (checkSol) return solution.toList else Nil + else + return Nil + } + } + + val f2Str: List[Int] => String = fields => { + val f2Stri: List[Int] => String = fields => { + val sepLine = "+---+---+---+" + val sepPoints = Set(2,5,8) + val fs: (Int, Int) => String = (i, v) => v.toString.replace("0"," ")+(if (sepPoints.contains(i%9)) "|" else "") + val s = sepLine+"\n"+(0 to fields.size-1).map(i => (if (i%9==0) "|" else "")+fs(i,fields(i))+(if (i%9==8) if (sepPoints.contains(i/9)) "\n"+sepLine+"\n" else "\n" else "")).foldRight("")(_+_) + s + } + val s = fields match {case Nil => "no solution!!!" case _ => f2Stri(fields)} + s + } + + val elapsedtime: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000} + + var sol = List[Int]() + + val sudokus = List( + ("riddle used in Ada section:", + "394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735"), + ("riddle used in Bracmat section:", + "..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9"), + ("riddle from Groovy section: 4th exceptionally difficult example in Wikipedia: ~80 seconds", + "..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5.."), + ("riddle used in Ada section with incorrect modifactions - it should fail:", + "3943.267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735"), + ("riddle constructed with mess - it should fail too:", + "123456789456789123789123456.45..89..6.......72.7...58.31..67..8..9..8....264..735")) + + for (sudoku <- sudokus) { + val desc = sudoku._1 + val riddle = sudoku._2.replace(".","0").toList.map(_.toString.toInt) + println(desc+"\n"+f2Str(riddle)+"\n" + +"elapsed time: "+elapsedtime(sol = Solver.solve(riddle))+" sec"+"\n"+"solution:"+"\n"+f2Str(sol) + +("\n"*2)) + } +} diff --git a/Task/Sudoku/Tcl/sudoku-1.tcl b/Task/Sudoku/Tcl/sudoku-1.tcl new file mode 100644 index 0000000000..b8e38e4ab7 --- /dev/null +++ b/Task/Sudoku/Tcl/sudoku-1.tcl @@ -0,0 +1,249 @@ +package require Tcl 8.6 +oo::class create Sudoku { + variable idata + + method clear {} { + for {set y 0} {$y < 9} {incr y} { + for {set x 0} {$x < 9} {incr x} { + my set $x $y {} + } + } + } + method load {data} { + set error "data must be a 9-element list, each element also being a\ + list of 9 numbers from 1 to 9 or blank or an @ symbol." + if {[llength $data] != 9} { + error $error + } + for {set y 0} {$y<9} {incr y} { + set row [lindex $data $y] + if {[llength $row] != 9} { + error $error + } + for {set x 0} {$x<9} {incr x} { + set d [lindex $row $x] + if {![regexp {^[@1-9]?$} $d]} { + error $d-$error + } + if {$d eq "@"} {set d ""} + my set $x $y $d + } + } + } + method dump {} { + set rows {} + for {set y 0} {$y < 9} {incr y} { + lappend rows [my getRow 0 $y] + } + return $rows + } + + method Log msg { + # Chance to print message + } + + method set {x y value} { + if {[catch {set value [format %d $value]}]} {set value 0} + if {$value<1 || $value>9} { + set idata(sq$x$y) {} + } else { + set idata(sq$x$y) $value + } + } + method get {x y} { + if {![info exists idata(sq$x$y)]} { + return {} + } + return $idata(sq$x$y) + } + + method getRow {x y} { + set row {} + for {set x 0} {$x<9} {incr x} { + lappend row [my get $x $y] + } + return $row + } + method getCol {x y} { + set col {} + for {set y 0} {$y<9} {incr y} { + lappend col [my get $x $y] + } + return $col + } + method getRegion {x y} { + set xR [expr {($x/3)*3}] + set yR [expr {($y/3)*3}] + set regn {} + for {set x $xR} {$x < $xR+3} {incr x} { + for {set y $yR} {$y < $yR+3} {incr y} { + lappend regn [my get $x $y] + } + } + return $regn + } +} + +# SudokuSolver inherits from Sudoku, and adds the ability to filter +# possibilities for a square by looking at all the squares in the row, column, +# and region that the square is a part of. The method 'solve' contains a list +# of rule-objects to use, and iterates over each square on the board, applying +# each rule sequentially until the square is allocated. + +oo::class create SudokuSolver { + superclass Sudoku + method validchoices {x y} { + if {[my get $x $y] ne {}} { + return [my get $x $y] + } + + set row [my getRow $x $y] + set col [my getCol $x $y] + set regn [my getRegion $x $y] + set eliminate [list {*}$row {*}$col {*}$regn] + set eliminate [lsearch -all -inline -not $eliminate {}] + set eliminate [lsort -unique $eliminate] + + set choices {} + for {set c 1} {$c < 10} {incr c} { + if {$c ni $eliminate} { + lappend choices $c + } + } + if {[llength $choices]==0} { + error "No choices left for square $x,$y" + } + return $choices + } + method completion {} { + return [expr { + 81-[llength [lsearch -all -inline [join [my dump]] {}]] + }] + } + method solve {} { + foreach ruleClass [info class subclass Rule] { + lappend rules [$ruleClass new] + } + + while {1} { + set begin [my completion] + for {set y 0} {$y < 9} {incr y} { + for {set x 0} {$x < 9} {incr x} { + if {[my get $x $y] eq ""} { + foreach rule $rules { + set c [$rule solve [self] $x $y] + if {$c} { + my set $x $y $c + my Log "[info object class $rule] solved [self] at $x,$y for $c" + break + } + } + } + } + } + set end [my completion] + if {$end==81} { + my Log "Finished solving!" + break + } elseif {$begin==$end} { + my Log "A round finished without solving any squares, giving up." + break + } + } + foreach rule $rules { + $rule destroy + } + } +} + +# Rule is the template for the rules used in Solver. The other rule-objects +# apply their logic to the values passed in and return either '0' or a number +# to allocate to the requested square. +oo::class create Rule { + method solve {hSudoku x y} { + if {![info object isa typeof $hSudoku SudokuSolver]} { + error "hSudoku must be an instance of class SudokuSolver." + } + + tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] + } +} + +# Get all the allocated numbers for each square in the the row, column, and +# region containing $x,$y. If there is only one unallocated number among all +# three groups, it must be allocated at $x,$y +oo::class create RuleOnlyChoice { + superclass Rule + method Solve {hSudoku x y choices} { + if {[llength $choices]==1} { + return $choices + } else { + return 0 + } + } +} + +# Test each column to determine if $choice is an invalid choice for all other +# columns in row $X. If it is, it must only go in square $x,$y. +oo::class create RuleColumnChoice { + superclass Rule + method Solve {hSudoku x y choices} { + foreach choice $choices { + set failed 0 + for {set x2 0} {$x2<9} {incr x2} { + if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { + set failed 1 + break + } + } + if {!$failed} {return $choice} + } + return 0 + } +} + +# Test each row to determine if $choice is an invalid choice for all other +# rows in column $y. If it is, it must only go in square $x,$y. +oo::class create RuleRowChoice { + superclass Rule + method Solve {hSudoku x y choices} { + foreach choice $choices { + set failed 0 + for {set y2 0} {$y2<9} {incr y2} { + if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { + set failed 1 + break + } + } + if {!$failed} {return $choice} + } + return 0 + } +} + +# Test each square in the region occupied by $x,$y to determine if $choice is +# an invalid choice for all other squares in that region. If it is, it must +# only go in square $x,$y. +oo::class create RuleRegionChoice { + superclass Rule + method Solve {hSudoku x y choices} { + foreach choice $choices { + set failed 0 + set regnX [expr {($x/3)*3}] + set regnY [expr {($y/3)*3}] + for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { + for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { + if { + ($x2!=$x || $y2!=$y) + && $choice in [$hSudoku validchoices $x2 $y2] + } then { + set failed 1 + break + } + } + } + if {!$failed} {return $choice} + } + return 0 + } +} diff --git a/Task/Sudoku/Tcl/sudoku-2.tcl b/Task/Sudoku/Tcl/sudoku-2.tcl new file mode 100644 index 0000000000..141df796e3 --- /dev/null +++ b/Task/Sudoku/Tcl/sudoku-2.tcl @@ -0,0 +1,24 @@ +SudokuSolver create sudoku +sudoku load { + {3 9 4 @ @ 2 6 7 @} + {@ @ @ 3 @ @ 4 @ @} + {5 @ @ 6 9 @ @ 2 @} + + {@ 4 5 @ @ @ 9 @ @} + {6 @ @ @ @ @ @ @ 7} + {@ @ 7 @ @ @ 5 8 @} + + {@ 1 @ @ 6 7 @ @ 8} + {@ @ 9 @ @ 8 @ @ @} + {@ 2 6 4 @ @ 7 3 5} +} +sudoku solve +# Simple pretty-printer for completed sudokus +puts +-----+-----+-----+ +foreach line [sudoku dump] postline {0 0 1 0 0 1 0 0 1} { + puts |[lrange $line 0 2]|[lrange $line 3 5]|[lrange $line 6 8]| + if {$postline} { + puts +-----+-----+-----+ + } +} +sudoku destroy diff --git a/Task/Sudoku/Tcl/sudoku-3.tcl b/Task/Sudoku/Tcl/sudoku-3.tcl new file mode 100644 index 0000000000..0c2636f315 --- /dev/null +++ b/Task/Sudoku/Tcl/sudoku-3.tcl @@ -0,0 +1 @@ +oo::objdefine sudoku method Log msg {puts $msg} diff --git a/Task/Sudoku/Ursala/sudoku-1.ursala b/Task/Sudoku/Ursala/sudoku-1.ursala new file mode 100644 index 0000000000..6d0732f1bd --- /dev/null +++ b/Task/Sudoku/Ursala/sudoku-1.ursala @@ -0,0 +1,13 @@ +#import std +#import nat + +sudoku = + +@FL mat0+ block3+ mat` *+ block3*+ block9+ -+ + ~&rSL+ (psort (nleq+)* <~&blrl,~&blrr>)+ ~&arg^& -+ + ~&al?\~&ar ~&aa^&~&afahPRPfafatPJPRY+ ~&farlthlriNCSPDPDrlCS2DlrTS2J, + ^|J/~& ~&rt!=+ ^= ~&s+ ~&H( + -+.|=&lrr;,|=&lrl;,|=≪+-, + ~&rgg&& ~&irtPFXlrjrXPS; ~&lrK2tkZ2g&& ~&llrSL2rDrlPrrPljXSPTSL)+-, + //~&p ^|DlrDSLlrlPXrrPDSL(~&,num*+ rep2 block3)*= num block27 ~&iiK0 iota9, + * `0?=\~&iNC ! ~&t digits+- diff --git a/Task/Sudoku/Ursala/sudoku-2.ursala b/Task/Sudoku/Ursala/sudoku-2.ursala new file mode 100644 index 0000000000..b722432cdd --- /dev/null +++ b/Task/Sudoku/Ursala/sudoku-2.ursala @@ -0,0 +1,16 @@ +#show+ + +example = + +sudoku + +-[ +394002670 +000300400 +500690020 +045000900 +600000007 +007000580 +010067008 +009008000 +026400735]- diff --git a/Task/Sudoku/VBA/sudoku.vba b/Task/Sudoku/VBA/sudoku.vba new file mode 100644 index 0000000000..5c33ff39b1 --- /dev/null +++ b/Task/Sudoku/VBA/sudoku.vba @@ -0,0 +1,102 @@ +Dim grid(9, 9) +Dim gridSolved(9, 9) + +Public Sub Solve(i, j) + If i > 9 Then + 'exit with gridSolved = Grid + For r = 1 To 9 + For c = 1 To 9 + gridSolved(r, c) = grid(r, c) + Next c + Next r + Exit Sub + End If + For n = 1 To 9 + If isSafe(i, j, n) Then + nTmp = grid(i, j) + grid(i, j) = n + If j = 9 Then + Solve i + 1, 1 + Else + Solve i, j + 1 + End If + grid(i, j) = nTmp + End If + Next n +End Sub + +Public Function isSafe(i, j, n) As Boolean +Dim iMin As Integer +Dim jMin As Integer + +If grid(i, j) <> 0 Then + isSafe = (grid(i, j) = n) + Exit Function +End If + +'grid(i,j) is an empty cell. Check if n is OK +'first check the row i +For c = 1 To 9 + If grid(i, c) = n Then + isSafe = False + Exit Function + End If +Next c + +'now check the column j +For r = 1 To 9 + If grid(r, j) = n Then + isSafe = False + Exit Function + End If +Next r + +'finally, check the 3x3 subsquare containing grid(i,j) +iMin = 1 + 3 * Int((i - 1) / 3) +jMin = 1 + 3 * Int((j - 1) / 3) +For r = iMin To iMin + 2 + For c = jMin To jMin + 2 + If grid(r, c) = n Then + isSafe = False + Exit Function + End If + Next c +Next r + +'all tests were OK +isSafe = True +End Function + +Public Sub Sudoku() + 'main routine + 'to use, fill in the grid and + 'type "Sudoku" in the Immediate panel of the Visual Basic for Applications window + + Dim s(9) As String + + 'initialise grid using 9 strings,one per row + s(1) = "001005070" + s(2) = "920600000" + s(3) = "008000600" + s(4) = "090020401" + s(5) = "000000000" + s(6) = "304080090" + s(7) = "007000300" + s(8) = "000007069" + s(9) = "010800700" + For i = 1 To 9 + For j = 1 To 9 + grid(i, j) = Int(Val(Mid$(s(i), j, 1))) + Next j + Next i + 'solve it! + Solve 1, 1 + 'print solution + Debug.Print "Solution:" + For i = 1 To 9 + For j = 1 To 9 + Debug.Print Format$(gridSolved(i, j)); " "; + Next j + Debug.Print + Next i +End Sub diff --git a/Task/Sudoku/XPL0/sudoku.xpl0 b/Task/Sudoku/XPL0/sudoku.xpl0 new file mode 100644 index 0000000000..670fa9555b --- /dev/null +++ b/Task/Sudoku/XPL0/sudoku.xpl0 @@ -0,0 +1,71 @@ +code ChOut=8, CrLf=9, IntOut=11, Text=12; + +proc Show(X); +char X; +int I, J; +[for I:= 0 to 8 do + [if rem(I/3) = 0 then CrLf(0); + for J:= 0 to 8 do + [if rem(J/3) = 0 then ChOut(0, ^ ); + ChOut(0, ^ ); IntOut(0, X(0)); + X:= X+1; + ]; + CrLf(0); + ]; +]; + +func TryCell(X, Pos); +char X; +int Pos; +int Row, Col, I, J, Used; +[Row:= Pos/9; +Col:= rem(0); +Used:= 0; + +if Pos = 81 then return true; +if X(Pos) then return TryCell(X, Pos+1); + +for I:= 0 to 8 do Used:= Used ! 1 << (X(I*9+Col)-1); +for J:= 0 to 8 do Used:= Used ! 1 << (X(Row*9+J)-1); + +Row:= Row/3*3; +Col:= Col/3*3; +for I:= Row to Row+2 do + for J:= Col to Col+2 do + Used:= Used ! 1 << (X(I*9+J)-1); + +for I:= 1 to 9 do + [X(Pos):= I; + if (Used&1)=0 & TryCell(X, Pos+1) then return true; + Used:= Used>>1; + ]; +X(Pos):= 0; +return false; +]; + +proc Solve(S); +char S; +int I, J, C; +char X(81); +[J:= 0; +for I:= 0 to 80 do + [repeat C:= S(J); + J:= J+1; + until C>=^1 & C<=^9 ! C=^.; + X(I):= if C=^. then 0 else C-^0; + ]; + +if TryCell(X, 0) then Show(X) +else Text(0, "No solution"); +]; + +[Solve("394 ..2 67. + ... 3.. 4.. + 5.. 69. .2. + .45 ... 9.. + 6.. ... ..7 + ..7 ... 58. + .1. .67 ..8 + ..9 ..8 ... + .26 4.. 735 "); +] diff --git a/Task/Sum-and-product-of-an-array/0DESCRIPTION b/Task/Sum-and-product-of-an-array/0DESCRIPTION new file mode 100644 index 0000000000..f033e6b69e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/0DESCRIPTION @@ -0,0 +1 @@ +Compute the sum and product of an array of integers. diff --git a/Task/Sum-and-product-of-an-array/1META.yaml b/Task/Sum-and-product-of-an-array/1META.yaml new file mode 100644 index 0000000000..5a01ada41b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Iteration +note: Arithmetic operations diff --git a/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d b/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d new file mode 100644 index 0000000000..03b36813b0 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d @@ -0,0 +1,11 @@ +ARRAY INTEGER($list;0) +For ($i;1;5) + APPEND TO ARRAY($list;$i) +End for + +$sum:=0 +$product:=1 +For ($i;1;Size of array($list)) + $sum:=$var+$list{$i} + $product:=$product*$list{$i} +End for diff --git a/Task/Sum-and-product-of-an-array/ACL2/sum-and-product-of-an-array.acl2 b/Task/Sum-and-product-of-an-array/ACL2/sum-and-product-of-an-array.acl2 new file mode 100644 index 0000000000..89426d081a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ACL2/sum-and-product-of-an-array.acl2 @@ -0,0 +1,11 @@ +(defun sum (xs) + (if (endp xs) + 0 + (+ (first xs) + (sum (rest xs))))) + +(defun prod (xs) + (if (endp xs) + 1 + (* (first xs) + (prod (rest xs))))) diff --git a/Task/Sum-and-product-of-an-array/ALGOL-68/sum-and-product-of-an-array.alg b/Task/Sum-and-product-of-an-array/ALGOL-68/sum-and-product-of-an-array.alg new file mode 100644 index 0000000000..4d593758d9 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ALGOL-68/sum-and-product-of-an-array.alg @@ -0,0 +1,21 @@ +main:( + INT default upb := 3; + MODE INTARRAY = [default upb]INT; + + INTARRAY array = (1,2,3,4,5,6,7,8,9,10); + INT sum := 0; + FOR i FROM LWB array TO UPB array DO + sum +:= array[i] + OD; + + # Define the product function # + PROC int product = (INTARRAY item)INT: + ( + INT prod :=1; + FOR i FROM LWB item TO UPB item DO + prod *:= item[i] + OD; + prod + ) # int product # ; + printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array))) +) diff --git a/Task/Sum-and-product-of-an-array/APL/sum-and-product-of-an-array.apl b/Task/Sum-and-product-of-an-array/APL/sum-and-product-of-an-array.apl new file mode 100644 index 0000000000..cba51f1f4a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/APL/sum-and-product-of-an-array.apl @@ -0,0 +1,10 @@ + sum ← +/ + prod ← ×/ + + list ← 1 2 3 4 5 + + sum list +15 + + prod list +120 diff --git a/Task/Sum-and-product-of-an-array/AWK/sum-and-product-of-an-array.awk b/Task/Sum-and-product-of-an-array/AWK/sum-and-product-of-an-array.awk new file mode 100644 index 0000000000..f29a383fff --- /dev/null +++ b/Task/Sum-and-product-of-an-array/AWK/sum-and-product-of-an-array.awk @@ -0,0 +1,7 @@ +$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}' +1 2 3 4 5 6 7 8 9 10 +55 + +$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' +1 2 3 4 5 6 7 8 9 10 +3628800 diff --git a/Task/Sum-and-product-of-an-array/ActionScript/sum-and-product-of-an-array.as b/Task/Sum-and-product-of-an-array/ActionScript/sum-and-product-of-an-array.as new file mode 100644 index 0000000000..f959453fa6 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ActionScript/sum-and-product-of-an-array.as @@ -0,0 +1,22 @@ +package { + import flash.display.Sprite; + + public class SumAndProduct extends Sprite + { + public function SumAndProduct() + { + var arr:Array = [1, 2, 3, 4, 5]; + var sum:int = 0; + var prod:int = 1; + + for (var i:int = 0; i < arr.length; i++) + { + sum += arr[i]; + prod *= arr[i]; + } + + trace("Sum: " + sum); // 15 + trace("Product: " + prod); // 120 + } + } +} diff --git a/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-1.ada b/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-1.ada new file mode 100644 index 0000000000..916791c7bc --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-1.ada @@ -0,0 +1,7 @@ +type Int_Array is array(Integer range <>) of Integer; + +array : Int_Array := (1,2,3,4,5,6,7,8,9,10); +Sum : Integer := 0; +for I in array'range loop + Sum := Sum + array(I); +end loop; diff --git a/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-2.ada b/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-2.ada new file mode 100644 index 0000000000..560c183fbd --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-2.ada @@ -0,0 +1,8 @@ +function Product(Item : Int_Array) return Integer is + Prod : Integer := 1; +begin + for I in Item'range loop + Prod := Prod * Item(I); + end loop; + return Prod; +end Product; diff --git a/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array.applescript b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array.applescript new file mode 100644 index 0000000000..95a7391542 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/AppleScript/sum-and-product-of-an-array.applescript @@ -0,0 +1,7 @@ +set array to {1, 2, 3, 4, 5} +set sum to 0 +set product to 1 +repeat with i in array + set sum to sum + i + set product to product * i +end repeat diff --git a/Task/Sum-and-product-of-an-array/AutoHotkey/sum-and-product-of-an-array.ahk b/Task/Sum-and-product-of-an-array/AutoHotkey/sum-and-product-of-an-array.ahk new file mode 100644 index 0000000000..e79c907181 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/AutoHotkey/sum-and-product-of-an-array.ahk @@ -0,0 +1,8 @@ +numbers = 1,2,3,4,5 +product := 1 +loop, parse, numbers, `, +{ +sum += A_LoopField +product *= A_LoopField +} +msgbox, sum = %sum%`nproduct = %product% diff --git a/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array.basic b/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array.basic new file mode 100644 index 0000000000..eb20baeaf6 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/BASIC/sum-and-product-of-an-array.basic @@ -0,0 +1,8 @@ +dim array(5) as integer = { 1, 2, 3, 4, 5 } + +dim sum as integer = 0 +dim prod as integer = 1 +for index as integer = lbound(array) to ubound(array) + sum += array(index) + prod *= array(index) +next diff --git a/Task/Sum-and-product-of-an-array/BBC-BASIC/sum-and-product-of-an-array.bbc b/Task/Sum-and-product-of-an-array/BBC-BASIC/sum-and-product-of-an-array.bbc new file mode 100644 index 0000000000..956f96f4c5 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/BBC-BASIC/sum-and-product-of-an-array.bbc @@ -0,0 +1,10 @@ + DIM array%(5) + array%() = 1, 2, 3, 4, 5, 6 + + PRINT "Sum of array elements = " ; SUM(array%()) + + product% = 1 + FOR I% = 0 TO DIM(array%(),1) + product% *= array%(I%) + NEXT + PRINT "Product of array elements = " ; product% diff --git a/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-1.pb b/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-1.pb new file mode 100644 index 0000000000..0ebce84476 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-1.pb @@ -0,0 +1,13 @@ +main: { [2 3 5 7 11 13] sp } + +sum! : { <- 0 -> { + } eachar } +product!: { <- 1 -> { * } eachar } + +sp!: + { dup + sum %d cr << + product %d cr << } + +Result: +41 +30030 diff --git a/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-2.pb b/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-2.pb new file mode 100644 index 0000000000..48ea21371f --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Babel/sum-and-product-of-an-array-2.pb @@ -0,0 +1,19 @@ +main: + { [2 3 5 7 11 13] + ar2ls dup cp + <- sum_stack -> + prod_stack + %d cr << + %d cr << } + +sum_stack: + { { give + { + } + { depth 1 > } + do_while } nest } + +prod_stack: + { { give + { * } + { depth 1 > } + do_while } nest } diff --git a/Task/Sum-and-product-of-an-array/Befunge/sum-and-product-of-an-array.bf b/Task/Sum-and-product-of-an-array/Befunge/sum-and-product-of-an-array.bf new file mode 100644 index 0000000000..0d400a98c3 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Befunge/sum-and-product-of-an-array.bf @@ -0,0 +1,3 @@ +0 &>: #v_ $. @ + >1- \ & + \v + ^ < diff --git a/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-1.cpp b/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-1.cpp new file mode 100644 index 0000000000..b103808e41 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-1.cpp @@ -0,0 +1,9 @@ +#include +#include + +int arg[] = { 1, 2, 3, 4, 5 }; +int sum = std::accumulate(arg, arg+5, 0, std::plus()); +// or just +// std::accumulate(arg, arg + 5, 0); +// since plus() is the default functor for accumulate +int prod = std::accumulate(arg, arg+5, 1, std::multiplies()); diff --git a/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-2.cpp b/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-2.cpp new file mode 100644 index 0000000000..b3ecd0bdfd --- /dev/null +++ b/Task/Sum-and-product-of-an-array/C++/sum-and-product-of-an-array-2.cpp @@ -0,0 +1,28 @@ +// this would be more elegant using STL collections +template T sum (const T *array, const unsigned n) +{ + T accum = 0; + for (unsigned i=0; i T prod (const T *array, const unsigned n) +{ + T accum = 1; + for (unsigned i=0; i +using std::cout; +using std::endl; + +int main () +{ + int aint[] = {1, 2, 3}; + cout << sum(aint,3) << " " << prod(aint, 3) << endl; + float aflo[] = {1.1, 2.02, 3.003, 4.0004}; + cout << sum(aflo,4) << " " << prod(aflo,4) << endl; + return 0; +} diff --git a/Task/Sum-and-product-of-an-array/C/sum-and-product-of-an-array.c b/Task/Sum-and-product-of-an-array/C/sum-and-product-of-an-array.c new file mode 100644 index 0000000000..a5e54d3e3e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/C/sum-and-product-of-an-array.c @@ -0,0 +1,11 @@ +/* using pointer arithmetic (because we can, I guess) */ +int arg[] = { 1,2,3,4,5 }; +int arg_length = sizeof(arg)/sizeof(arg[0]); +int *end = arg+arg_length; +int sum = 0, prod = 1; +int *p; + +for (p = arg; p!=end; ++p) { + sum += *p; + prod *= *p; +} diff --git a/Task/Sum-and-product-of-an-array/Chef/sum-and-product-of-an-array.chef b/Task/Sum-and-product-of-an-array/Chef/sum-and-product-of-an-array.chef new file mode 100644 index 0000000000..f98e6376eb --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Chef/sum-and-product-of-an-array.chef @@ -0,0 +1,23 @@ +Sum and Product of Numbers as a Piece of Cake. + +This recipe sums N given numbers. + +Ingredients. +1 N +0 sum +1 product +1 number + +Method. +Put sum into 1st mixing bowl. +Put product into 2nd mixing bowl. +Take N from refrigerator. +Chop N. +Take number from refrigerator. +Add number into 1st mixing bowl. +Combine number into 2nd mixing bowl. +Chop N until choped. +Pour contents of 2nd mixing bowl into the baking dish. +Pour contents of 1st mixing bowl into the baking dish. + +Serves 1. diff --git a/Task/Sum-and-product-of-an-array/Clean/sum-and-product-of-an-array.clean b/Task/Sum-and-product-of-an-array/Clean/sum-and-product-of-an-array.clean new file mode 100644 index 0000000000..26d6f78553 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Clean/sum-and-product-of-an-array.clean @@ -0,0 +1,3 @@ +array = {1, 2, 3, 4, 5} +Sum = sum [x \\ x <-: array] +Prod = foldl (*) 1 [x \\ x <-: array] diff --git a/Task/Sum-and-product-of-an-array/Clojure/sum-and-product-of-an-array.clj b/Task/Sum-and-product-of-an-array/Clojure/sum-and-product-of-an-array.clj new file mode 100644 index 0000000000..63995b031b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Clojure/sum-and-product-of-an-array.clj @@ -0,0 +1,3 @@ +(defn sum [vals] (reduce + vals)) + +(defn product [vals] (reduce * vals)) diff --git a/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-1.cfm b/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-1.cfm new file mode 100644 index 0000000000..901f4b61ca --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-1.cfm @@ -0,0 +1,2 @@ + +#ArraySum(Variables.myArray)# diff --git a/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-2.cfm b/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-2.cfm new file mode 100644 index 0000000000..97f2d288c4 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ColdFusion/sum-and-product-of-an-array-2.cfm @@ -0,0 +1,6 @@ + + + + + +#Variables.Product# 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 new file mode 100644 index 0000000000..1f697ca583 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array.lisp @@ -0,0 +1,3 @@ +(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/D/sum-and-product-of-an-array-1.d b/Task/Sum-and-product-of-an-array/D/sum-and-product-of-an-array-1.d new file mode 100644 index 0000000000..40c0cb651a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/D/sum-and-product-of-an-array-1.d @@ -0,0 +1,16 @@ +import std.stdio; + +void main() { + immutable array = [1, 2, 3, 4, 5]; + + int sum = 0; + int prod = 1; + + foreach (x; array) { + sum += x; + prod *= x; + } + + writeln("Sum: ", sum); + writeln("Product: ", prod); +} diff --git a/Task/Sum-and-product-of-an-array/D/sum-and-product-of-an-array-2.d b/Task/Sum-and-product-of-an-array/D/sum-and-product-of-an-array-2.d new file mode 100644 index 0000000000..be82b3c56c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/D/sum-and-product-of-an-array-2.d @@ -0,0 +1,11 @@ +import std.stdio, std.algorithm, std.typecons; + +void main() { + immutable array = [1, 2, 3, 4, 5]; + + // Results are stored in a 2-tuple + immutable r = reduce!(q{a + b}, q{a * b})(tuple(0, 1), array); + + writeln("Sum: ", r[0]); + writeln("Product: ", r[1]); +} diff --git a/Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.delphi b/Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.delphi new file mode 100644 index 0000000000..a50466bc7c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.delphi @@ -0,0 +1,21 @@ +program SumAndProductOfArray; + +{$APPTYPE CONSOLE} + +var + i: integer; + lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5); + lSum: integer = 0; + lProduct: integer = 1; +begin + for i := 1 to length(lIntArray) do + begin + Inc(lSum, lIntArray[i]); + lProduct := lProduct * lIntArray[i] + end; + + Write('Sum: '); + Writeln(lSum); + Write('Product: '); + Writeln(lProduct); +end. diff --git a/Task/Sum-and-product-of-an-array/E/sum-and-product-of-an-array.e b/Task/Sum-and-product-of-an-array/E/sum-and-product-of-an-array.e new file mode 100644 index 0000000000..02e5180797 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/E/sum-and-product-of-an-array.e @@ -0,0 +1,3 @@ +pragma.enable("accumulator") +accum 0 for x in [1,2,3,4,5] { _ + x } +accum 1 for x in [1,2,3,4,5] { _ * x } 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 new file mode 100644 index 0000000000..cee29a0b1f --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array.l @@ -0,0 +1,3 @@ +(setq array [1 2 3 4 5]) +(eval (concatenate 'list '(+) array)) +(eval (concatenate 'list '(*) array)) diff --git a/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-1.erl b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-1.erl new file mode 100644 index 0000000000..dc8ab1789d --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-1.erl @@ -0,0 +1,6 @@ +% create the list: +L = lists:seq(1, 10). + +% and compute its sum: +S = lists:sum(L). +P = lists:foldl(fun (X, P) -> X * P end, 1, L). diff --git a/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-2.erl b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-2.erl new file mode 100644 index 0000000000..1c8d6e3c28 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-2.erl @@ -0,0 +1 @@ +{Prod,Sum} = lists:foldl(fun (X, {P,S}) -> {P*X,S+X} end, {1,0}, lists:seq(1,10)). diff --git a/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-3.erl b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-3.erl new file mode 100644 index 0000000000..89d76aaea9 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Erlang/sum-and-product-of-an-array-3.erl @@ -0,0 +1,16 @@ +-module(list_sum). +-export([sum_rec/1, sum_tail/1]). + +% recursive definition: +sum_rec([]) -> + 0; +sum_rec([Head|Tail]) -> + Head + sum_rec(Tail). + +% tail-recursive definition: +sum_tail(L) -> + sum_tail(L, 0). +sum_tail([], Acc) -> + Acc; +sum_tail([Head|Tail], Acc) -> + sum_tail(Tail, Head + Acc). diff --git a/Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.euphoria b/Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.euphoria new file mode 100644 index 0000000000..ab5972cb81 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.euphoria @@ -0,0 +1,14 @@ +sequence array +integer sum,prod + +array = { 1, 2, 3, 4, 5 } + +sum = 0 +prod = 1 +for i = 1 to length(array) do + sum += array[i] + prod *= array[i] +end for + +printf(1,"sum is %d\n",sum) +printf(1,"prod is %d\n",prod) diff --git a/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-1.factor b/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-1.factor new file mode 100644 index 0000000000..ef252f4316 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-1.factor @@ -0,0 +1,4 @@ +1 5 1 [ sum . ] [ product . ] bi + 15 120 +{ 1 2 3 4 } [ sum ] [ product ] bi + 10 24 diff --git a/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-2.factor b/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-2.factor new file mode 100644 index 0000000000..2ae9d79241 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Factor/sum-and-product-of-an-array-2.factor @@ -0,0 +1,2 @@ +: sum ( seq -- n ) 0 [ + ] reduce ; +: product ( seq -- n ) 1 [ * ] reduce ; diff --git a/Task/Sum-and-product-of-an-array/Fantom/sum-and-product-of-an-array.fantom b/Task/Sum-and-product-of-an-array/Fantom/sum-and-product-of-an-array.fantom new file mode 100644 index 0000000000..1547a689c9 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Fantom/sum-and-product-of-an-array.fantom @@ -0,0 +1,32 @@ +class Main +{ + public static Void main () + { + Int[] array := (1..20).toList + + // you can use a loop + Int sum := 0 + array.each |Int n| { sum += n } + echo ("Sum of array is : $sum") + + Int product := 1 + array.each |Int n| { product *= n } + echo ("Product of array is : $product") + + // or use 'reduce' + // 'reduce' takes a function, + // the first argument is the accumulated value + // and the second is the next item in the list + sum = array.reduce(0) |Obj r, Int v -> Obj| + { + return (Int)r + v + } + echo ("Sum of array : $sum") + + product = array.reduce(1) |Obj r, Int v -> Obj| + { + return (Int)r * v + } + echo ("Product of array : $product") + } +} diff --git a/Task/Sum-and-product-of-an-array/Forth/sum-and-product-of-an-array.fth b/Task/Sum-and-product-of-an-array/Forth/sum-and-product-of-an-array.fth new file mode 100644 index 0000000000..c3d58f07c2 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Forth/sum-and-product-of-an-array.fth @@ -0,0 +1,8 @@ +: third ( a b c -- a b c a ) 2 pick ; +: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n ) + cells bounds do i @ third execute cell +loop nip ; + +create a 1 , 2 , 3 , 4 , 5 , + +' + 0 a 5 reduce . \ 15 +' * 1 a 5 reduce . \ 120 diff --git a/Task/Sum-and-product-of-an-array/Fortran/sum-and-product-of-an-array.f b/Task/Sum-and-product-of-an-array/Fortran/sum-and-product-of-an-array.f new file mode 100644 index 0000000000..6c26e33848 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Fortran/sum-and-product-of-an-array.f @@ -0,0 +1,5 @@ +integer, dimension(10) :: a = (/ (i, i=1, 10) /) +integer :: sresult, presult + +sresult = sum(a); +presult = product(a); diff --git a/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap b/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap new file mode 100644 index 0000000000..fe8df7db92 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/GAP/sum-and-product-of-an-array.gap @@ -0,0 +1,7 @@ +v := [1 .. 8]; + +Sum(v); +# 36 + +Product(v); +# 40320 diff --git a/Task/Sum-and-product-of-an-array/GW-BASIC/sum-and-product-of-an-array.gw-basic b/Task/Sum-and-product-of-an-array/GW-BASIC/sum-and-product-of-an-array.gw-basic new file mode 100644 index 0000000000..50f92842ac --- /dev/null +++ b/Task/Sum-and-product-of-an-array/GW-BASIC/sum-and-product-of-an-array.gw-basic @@ -0,0 +1,13 @@ +10 REM Create an array with some test data in it +20 DIM A(5) +30 FOR I = 1 TO 5: READ A(I): NEXT I +40 DATA 1, 2, 3, 4, 5 +50 REM Find the sum of elements in the array +60 S = 0 +65 P = 1 +70 FOR I = 1 TO 5 +72 S = SUM + A(I) +75 P = P * A(I) +77 NEXT I +80 PRINT "The sum is "; S; +90 PRINT " and the product is "; P diff --git a/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array.go b/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array.go new file mode 100644 index 0000000000..b3dc32f20b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func main() { + sum, prod := 0, 1 + for _, x := range []int{1,2,5} { + sum += x + prod *= x + } + fmt.Println(sum, prod) +} diff --git a/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-1.groovy b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-1.groovy new file mode 100644 index 0000000000..ff519bad54 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-1.groovy @@ -0,0 +1 @@ +[1,2,3,4,5].sum() diff --git a/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-2.groovy b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-2.groovy new file mode 100644 index 0000000000..e0268440ab --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-2.groovy @@ -0,0 +1,2 @@ +[1,2,3,4,5].inject(0) { sum, val -> sum + val } +[1,2,3,4,5].inject(1) { prod, val -> prod * val } diff --git a/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-3.groovy b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-3.groovy new file mode 100644 index 0000000000..f9db3b1442 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Groovy/sum-and-product-of-an-array-3.groovy @@ -0,0 +1,2 @@ +println ([1,2,3,4,5].inject([sum: 0, product: 1]) { result, value -> + [sum: result.sum + value, product: result.product * value]}) diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs new file mode 100644 index 0000000000..711a9a2c9c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-1.hs @@ -0,0 +1,7 @@ +values = [1..10] + +s = sum values -- the easy way +p = product values + +s' = foldl (+) 0 values -- the hard way +p' = foldl (*) 1 values diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs new file mode 100644 index 0000000000..b170853913 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs @@ -0,0 +1,6 @@ +import Data.Array + +values = listArray (1,10) [1..10] + +s = sum . elems $ values +p = product . elems $ values diff --git a/Task/Sum-and-product-of-an-array/HicEst/sum-and-product-of-an-array.hicest b/Task/Sum-and-product-of-an-array/HicEst/sum-and-product-of-an-array.hicest new file mode 100644 index 0000000000..e315614174 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/HicEst/sum-and-product-of-an-array.hicest @@ -0,0 +1,10 @@ +array = $ ! 1, 2, ..., LEN(array) + +sum = SUM(array) + +product = 1 ! no built-in product function in HicEst +DO i = 1, LEN(array) + product = product * array(i) +ENDDO + +WRITE(ClipBoard, Name) n, sum, product ! n=100; sum=5050; product=9.33262154E157; diff --git a/Task/Sum-and-product-of-an-array/IDL/sum-and-product-of-an-array.idl b/Task/Sum-and-product-of-an-array/IDL/sum-and-product-of-an-array.idl new file mode 100644 index 0000000000..c6834c53df --- /dev/null +++ b/Task/Sum-and-product-of-an-array/IDL/sum-and-product-of-an-array.idl @@ -0,0 +1,3 @@ +array = [3,6,8] +print,total(array) +print,product(array) diff --git a/Task/Sum-and-product-of-an-array/Icon/sum-and-product-of-an-array.icon b/Task/Sum-and-product-of-an-array/Icon/sum-and-product-of-an-array.icon new file mode 100644 index 0000000000..c50a2ed14d --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Icon/sum-and-product-of-an-array.icon @@ -0,0 +1,5 @@ +procedure main(arglist) +every ( sum := 0 ) +:= !arglist +every ( prod := 1 ) *:= !arglist +write("sum := ", sum,", prod := ",prod) +end diff --git a/Task/Sum-and-product-of-an-array/Inform-7/sum-and-product-of-an-array.inf b/Task/Sum-and-product-of-an-array/Inform-7/sum-and-product-of-an-array.inf new file mode 100644 index 0000000000..405dcbdfee --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Inform-7/sum-and-product-of-an-array.inf @@ -0,0 +1,12 @@ +Sum And Product is a room. + +To decide which number is the sum of (N - number) and (M - number) (this is summing): + decide on N + M. + +To decide which number is the product of (N - number) and (M - number) (this is production): + decide on N * M. + +When play begins: + let L be {1, 2, 3, 4, 5}; + say "List: [L in brace notation], sum = [summing reduction of L], product = [production reduction of L]."; + end the story. diff --git a/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-1.j b/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-1.j new file mode 100644 index 0000000000..218a317ccf --- /dev/null +++ b/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-1.j @@ -0,0 +1,2 @@ +sum =: +/ +product =: */ diff --git a/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-2.j b/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-2.j new file mode 100644 index 0000000000..173315fc32 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/J/sum-and-product-of-an-array-2.j @@ -0,0 +1,22 @@ + sum 1 3 5 7 9 11 13 +49 + product 1 3 5 7 9 11 13 +135135 + + a=: 3 10 ?@$ 100 NB. random array + a +90 47 58 29 22 32 55 5 55 73 +58 50 40 5 69 46 34 40 46 84 +29 8 75 97 24 40 21 82 77 9 + + NB. on a table, each row is an item to be summed: + sum a +177 105 173 131 115 118 110 127 178 166 + product a +151380 18800 174000 14065 36432 58880 39270 16400 194810 55188 + + NB. but we can tell J to sum everything within each row, instead: + sum"1 a +466 472 462 + product"1 a +5.53041e15 9.67411e15 1.93356e15 diff --git a/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array.java b/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array.java new file mode 100644 index 0000000000..0f0cfe9351 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array.java @@ -0,0 +1,14 @@ +public class SumProd +{ + public static void main(final String[] args) + { + int sum = 0; + int prod = 1; + int[] arg = {1,2,3,4,5}; + for (int i : arg) + { + sum += i; + prod *= i; + } + } +} diff --git a/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-1.js b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-1.js new file mode 100644 index 0000000000..7ae8a0b39c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-1.js @@ -0,0 +1,9 @@ +var array = [1, 2, 3, 4, 5], + sum = 0, + prod = 1, + i; +for (i = 0; i < array.length; i += 1) { + sum += array[i]; + prod *= array[i]; +} +alert(sum + ' ' + prod); diff --git a/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-2.js b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-2.js new file mode 100644 index 0000000000..515f111371 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/JavaScript/sum-and-product-of-an-array-2.js @@ -0,0 +1,8 @@ +var array = [1, 2, 3, 4, 5], + sum = array.reduce(function (a, b) { + return a + b; + }, 0), + prod = array.reduce(function (a, b) { + return a * b; + }, 1); +alert(sum + ' ' + prod); diff --git a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia new file mode 100644 index 0000000000..37d817e8c5 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia @@ -0,0 +1,5 @@ +julia> sum(1:5) +15 + +julia> prod(1:5) +120 diff --git a/Task/Sum-and-product-of-an-array/Lang5/sum-and-product-of-an-array.lang5 b/Task/Sum-and-product-of-an-array/Lang5/sum-and-product-of-an-array.lang5 new file mode 100644 index 0000000000..3d18bc72a0 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Lang5/sum-and-product-of-an-array.lang5 @@ -0,0 +1,4 @@ +4 iota 1 + dup + +'+ reduce +'* reduce diff --git a/Task/Sum-and-product-of-an-array/Liberty-BASIC/sum-and-product-of-an-array.liberty b/Task/Sum-and-product-of-an-array/Liberty-BASIC/sum-and-product-of-an-array.liberty new file mode 100644 index 0000000000..2319352f23 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Liberty-BASIC/sum-and-product-of-an-array.liberty @@ -0,0 +1,15 @@ +Dim array(19) + +For i = 0 To 19 + array(i) = Int(Rnd(1) * 20) +Next i + +'product must first equal one or you will get 0 as the product +product = 1 +For i = 0 To 19 + sum = (sum + array(i)) + product = (product * array(i)) +next i + +Print "Sum is " + str$(sum) +Print "Product is " + str$(product) diff --git a/Task/Sum-and-product-of-an-array/Logo/sum-and-product-of-an-array.logo b/Task/Sum-and-product-of-an-array/Logo/sum-and-product-of-an-array.logo new file mode 100644 index 0000000000..2ea55ea4e6 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Logo/sum-and-product-of-an-array.logo @@ -0,0 +1,2 @@ +print apply "sum arraytolist {1 2 3 4 5} +print apply "product arraytolist {1 2 3 4 5} diff --git a/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array.lua b/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array.lua new file mode 100644 index 0000000000..ac11a1c243 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array.lua @@ -0,0 +1,7 @@ +function sumf(a, ...) return a and a + sumf(...) or 0 end +function sumt(t) return sumf(unpack(t)) end +function prodf(a, ...) return a and a * prodf(...) or 1 end +function prodt(t) return prodf(unpack(t)) end + +print(sumt{1, 2, 3, 4, 5}) +print(prodt{1, 2, 3, 4, 5}) diff --git a/Task/Sum-and-product-of-an-array/Lucid/sum-and-product-of-an-array.lucid b/Task/Sum-and-product-of-an-array/Lucid/sum-and-product-of-an-array.lucid new file mode 100644 index 0000000000..e71cf7fd67 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Lucid/sum-and-product-of-an-array.lucid @@ -0,0 +1,6 @@ +[%sum,product%] + where + x = 1 fby x + 1; + sum = 0 fby sum + x; + product = 1 fby product * x + end diff --git a/Task/Sum-and-product-of-an-array/MATLAB/sum-and-product-of-an-array.m b/Task/Sum-and-product-of-an-array/MATLAB/sum-and-product-of-an-array.m new file mode 100644 index 0000000000..091e54b174 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/MATLAB/sum-and-product-of-an-array.m @@ -0,0 +1,35 @@ +>> array = [1 2 3;4 5 6;7 8 9] + +array = + + 1 2 3 + 4 5 6 + 7 8 9 + +>> sum(array,1) + +ans = + + 12 15 18 + +>> sum(array,2) + +ans = + + 6 + 15 + 24 + +>> prod(array,1) + +ans = + + 28 80 162 + +>> prod(array,2) + +ans = + + 6 + 120 + 504 diff --git a/Task/Sum-and-product-of-an-array/MAXScript/sum-and-product-of-an-array.maxscript b/Task/Sum-and-product-of-an-array/MAXScript/sum-and-product-of-an-array.maxscript new file mode 100644 index 0000000000..4d65dd390a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/MAXScript/sum-and-product-of-an-array.maxscript @@ -0,0 +1,5 @@ +arr = #(1, 2, 3, 4, 5) +sum = 0 +for i in arr do sum += i +product = 1 +for i in arr do product *= i diff --git a/Task/Sum-and-product-of-an-array/MUMPS/sum-and-product-of-an-array.mumps b/Task/Sum-and-product-of-an-array/MUMPS/sum-and-product-of-an-array.mumps new file mode 100644 index 0000000000..e7b7cd6bc7 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/MUMPS/sum-and-product-of-an-array.mumps @@ -0,0 +1,12 @@ +SUMPROD(A) + ;Compute the sum and product of the numbers in the array A + NEW SUM,PROD,POS + ;SUM is the running sum, + ;PROD is the running product, + ;POS is the position within the array A + SET SUM=0,PROD=1,POS="" + FOR SET POS=$ORDER(A(POS)) Q:POS="" SET SUM=SUM+A(POS),PROD=PROD*A(POS) + WRITE !,"The sum of the array is "_SUM + WRITE !,"The product of the array is "_PROD + KILL SUM,PROD,POS + QUIT diff --git a/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-1.math b/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-1.math new file mode 100644 index 0000000000..1f63bdd469 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-1.math @@ -0,0 +1,8 @@ +a = {1, 2, 3, 4, 5} +Plus @@ a +Apply[Plus, a] +Total[a] +Total@a +a // Total +Sum[a[[i]], {i, 1, Length[a]}] +Sum[i, {i, a}] diff --git a/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-2.math b/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-2.math new file mode 100644 index 0000000000..f8d778c0bf --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Mathematica/sum-and-product-of-an-array-2.math @@ -0,0 +1,5 @@ +a = {1, 2, 3, 4, 5} +Times @@ a +Apply[Times, a] +Product[a[[i]], {i, 1, Length[a]}] +Product[i, {i, a}] diff --git a/Task/Sum-and-product-of-an-array/Maxima/sum-and-product-of-an-array.maxima b/Task/Sum-and-product-of-an-array/Maxima/sum-and-product-of-an-array.maxima new file mode 100644 index 0000000000..6823fbc90d --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Maxima/sum-and-product-of-an-array.maxima @@ -0,0 +1,5 @@ +lreduce("+", [1, 2, 3, 4, 5, 6, 7, 8]); +36 + +lreduce("*", [1, 2, 3, 4, 5, 6, 7, 8]); +40320 diff --git a/Task/Sum-and-product-of-an-array/Modula-3/sum-and-product-of-an-array.mod3 b/Task/Sum-and-product-of-an-array/Modula-3/sum-and-product-of-an-array.mod3 new file mode 100644 index 0000000000..5259d5ff14 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Modula-3/sum-and-product-of-an-array.mod3 @@ -0,0 +1,17 @@ +MODULE Sumprod EXPORTS Main; + +FROM IO IMPORT Put; +FROM Fmt IMPORT Int; + +VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5}; +VAR sum: INTEGER := 0; +VAR prod: INTEGER := 1; + +BEGIN + FOR i := FIRST(a) TO LAST(a) DO + INC(sum, a[i]); + prod := prod * a[i]; + END; + Put("Sum of array: " & Int(sum) & "\n"); + Put("Product of array: " & Int(prod) & "\n"); +END Sumprod. diff --git a/Task/Sum-and-product-of-an-array/Nemerle/sum-and-product-of-an-array.nemerle b/Task/Sum-and-product-of-an-array/Nemerle/sum-and-product-of-an-array.nemerle new file mode 100644 index 0000000000..7f65c52e01 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Nemerle/sum-and-product-of-an-array.nemerle @@ -0,0 +1,30 @@ +using System; +using System.Console; +using System.Collections.Generic; +using Nemerle.Collections; + +module SumProd +{ + Sum[T] (nums : T) : int + where T : IEnumerable[int] + { + nums.FoldLeft(0, _+_) + } + + Product[T] (nums : T) : int + where T : IEnumerable[int] + { + nums.FoldLeft(1, _*_) + } + + Main() : void + { + def arr = array[1, 2, 3, 4, 5]; + def lis = [1, 2, 3, 4, 5]; + + def suml = Sum(lis); + def proda = Product(arr); + + WriteLine("Sum is: {0}\tProduct is: {1}", suml, proda); + } +} diff --git a/Task/Sum-and-product-of-an-array/NetRexx/sum-and-product-of-an-array.netrexx b/Task/Sum-and-product-of-an-array/NetRexx/sum-and-product-of-an-array.netrexx new file mode 100644 index 0000000000..ff79d52fee --- /dev/null +++ b/Task/Sum-and-product-of-an-array/NetRexx/sum-and-product-of-an-array.netrexx @@ -0,0 +1,24 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +harry = [long 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +sum = long 0 +product = long 1 +entries = Rexx '' + +loop n_ = int 0 to harry.length - 1 + nxt = harry[n_] + entries = entries nxt + sum = sum + nxt + product = product * nxt + end n_ + +entries = entries.strip + +say 'Sum and product of' entries.changestr(' ', ',')':' +say ' Sum:' sum +say ' Product:' product + +return diff --git a/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-1.nial b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-1.nial new file mode 100644 index 0000000000..3255077720 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-1.nial @@ -0,0 +1,4 @@ ++ 1 2 3 += 6 +* 1 2 3 += 6 diff --git a/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-2.nial b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-2.nial new file mode 100644 index 0000000000..5e1d2dd393 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-2.nial @@ -0,0 +1 @@ ++ [1,2,3] diff --git a/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-3.nial b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-3.nial new file mode 100644 index 0000000000..d667e4f5aa --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Nial/sum-and-product-of-an-array-3.nial @@ -0,0 +1,4 @@ +(* 1 2 3) += 6 +* (1 2 3) += 6 diff --git a/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ocaml b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ocaml new file mode 100644 index 0000000000..1753bd0e89 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ocaml @@ -0,0 +1,8 @@ +(* ints *) +let a = [| 1; 2; 3; 4; 5 |];; +Array.fold_left (+) 0 a;; +Array.fold_left ( * ) 1 a;; +(* floats *) +let a = [| 1.0; 2.0; 3.0; 4.0; 5.0 |];; +Array.fold_left (+.) 0.0 a;; +Array.fold_left ( *.) 1.0 a;; diff --git a/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ocaml b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ocaml new file mode 100644 index 0000000000..8677b6f1ca --- /dev/null +++ b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ocaml @@ -0,0 +1,8 @@ +(* ints *) +let x = [1; 2; 3; 4; 5];; +List.fold_left (+) 0 x;; +List.fold_left ( * ) 1 x;; +(* floats *) +let x = [1.0; 2.0; 3.0; 4.0; 5.0];; +List.fold_left (+.) 0.0 x;; +List.fold_left ( *.) 1.0 x;; diff --git a/Task/Sum-and-product-of-an-array/Objeck/sum-and-product-of-an-array.objeck b/Task/Sum-and-product-of-an-array/Objeck/sum-and-product-of-an-array.objeck new file mode 100644 index 0000000000..745996fd6b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Objeck/sum-and-product-of-an-array.objeck @@ -0,0 +1,7 @@ +sum := 0; +prod := 1; +arg := [1, 2, 3, 4, 5]; +each(i : arg) { + sum += arg[i]; + prod *= arg[i]; +}; diff --git a/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-1.m b/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-1.m new file mode 100644 index 0000000000..e2d5fcd287 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-1.m @@ -0,0 +1,13 @@ +- (float) sum:(NSMutableArray *)array +{ + int i, sum, value; + sum = 0; + value = 0; + + for (i = 0; i < [array count]; i++) { + value = [[array objectAtIndex: i] intValue]; + sum += value; + } + + return suml; +} diff --git a/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-2.m b/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-2.m new file mode 100644 index 0000000000..7556a5d677 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Objective-C/sum-and-product-of-an-array-2.m @@ -0,0 +1,13 @@ +- (float) prod:(NSMutableArray *)array +{ + int i, prod, value; + prod = 0; + value = 0; + + for (i = 0; i < [array count]; i++) { + value = [[array objectAtIndex: i] intValue]; + prod *= value; + } + + return suml; +} diff --git a/Task/Sum-and-product-of-an-array/Octave/sum-and-product-of-an-array.octave b/Task/Sum-and-product-of-an-array/Octave/sum-and-product-of-an-array.octave new file mode 100644 index 0000000000..633534a0c5 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Octave/sum-and-product-of-an-array.octave @@ -0,0 +1,4 @@ +a = [ 1, 2, 3, 4, 5, 6 ]; +b = [ 10, 20, 30, 40, 50, 60 ]; +vsum = a + b; +vprod = a .* b; diff --git a/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-1.oz b/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-1.oz new file mode 100644 index 0000000000..9e1cf3d3bc --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-1.oz @@ -0,0 +1,7 @@ +declare + Xs = [1 2 3 4 5] + Sum = {FoldL Xs Number.'+' 0} + Product = {FoldL Xs Number.'*' 1} +in + {Show Sum} + {Show Product} diff --git a/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-2.oz b/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-2.oz new file mode 100644 index 0000000000..4e7499db4f --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Oz/sum-and-product-of-an-array-2.oz @@ -0,0 +1,12 @@ +declare + Arr = {Array.new 1 3 0} + Sum = {NewCell 0} +in + Arr.1 := 1 + Arr.2 := 2 + Arr.3 := 3 + + for I in {Array.low Arr}..{Array.high Arr} do + Sum := @Sum + Arr.I + end + {Show @Sum} diff --git a/Task/Sum-and-product-of-an-array/PARI-GP/sum-and-product-of-an-array.pari b/Task/Sum-and-product-of-an-array/PARI-GP/sum-and-product-of-an-array.pari new file mode 100644 index 0000000000..cab3a612fd --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PARI-GP/sum-and-product-of-an-array.pari @@ -0,0 +1,6 @@ +vecsum(v)={ + sum(i=1,#v,v[i]) +}; +vecprod(v)={ + prod(i=1,#v,v[i]) +}; diff --git a/Task/Sum-and-product-of-an-array/PHP/sum-and-product-of-an-array.php b/Task/Sum-and-product-of-an-array/PHP/sum-and-product-of-an-array.php new file mode 100644 index 0000000000..bdb0362f3e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PHP/sum-and-product-of-an-array.php @@ -0,0 +1,3 @@ +$array = array(1,2,3,4,5,6,7,8,9); +echo array_sum($array); +echo array_product($array); diff --git a/Task/Sum-and-product-of-an-array/PL-I/sum-and-product-of-an-array.pli b/Task/Sum-and-product-of-an-array/PL-I/sum-and-product-of-an-array.pli new file mode 100644 index 0000000000..9a91beec27 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PL-I/sum-and-product-of-an-array.pli @@ -0,0 +1,5 @@ +declare A(10) fixed binary static initial + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +put skip list (sum(A)); +put skip list (prod(A)); diff --git a/Task/Sum-and-product-of-an-array/Perl-6/sum-and-product-of-an-array.pl6 b/Task/Sum-and-product-of-an-array/Perl-6/sum-and-product-of-an-array.pl6 new file mode 100644 index 0000000000..793046bfcc --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Perl-6/sum-and-product-of-an-array.pl6 @@ -0,0 +1,3 @@ +my @ary = 1, 5, 10, 100; +say 'Sum: ', [+] @ary; +say 'Product: ', [*] @ary; diff --git a/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-1.pl b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-1.pl new file mode 100644 index 0000000000..e5bf6d58d0 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-1.pl @@ -0,0 +1,5 @@ +my @list = ( 1, 2, 3 ); + +my ( $sum, $prod ) = ( 0, 1 ); +$sum += $_ foreach @list; +$prod *= $_ foreach @list; diff --git a/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl new file mode 100644 index 0000000000..030d1ba1bc --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl @@ -0,0 +1,6 @@ +use List::Util qw( sum reduce ); +my @list = ( 1, 2, 3 ); + +my $sum1 = sum 0, @list; # 0 identity to allow empty list +my $sum2 = reduce { $a + $b } 0, @list; +my $product = reduce { $a * $b } 1, @list; diff --git a/Task/Sum-and-product-of-an-array/PicoLisp/sum-and-product-of-an-array.l b/Task/Sum-and-product-of-an-array/PicoLisp/sum-and-product-of-an-array.l new file mode 100644 index 0000000000..40e048f693 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PicoLisp/sum-and-product-of-an-array.l @@ -0,0 +1,4 @@ +(let Data (1 2 3 4 5) + (cons + (apply + Data) + (apply * Data) ) ) diff --git a/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-1.pop11 b/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-1.pop11 new file mode 100644 index 0000000000..ee7ba2282e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-1.pop11 @@ -0,0 +1,5 @@ +lvars i, sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; +for i from 1 to length(ar) do + ar(i) + sum -> sum; + ar(i) * prod -> prod; +endfor; diff --git a/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-2.pop11 b/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-2.pop11 new file mode 100644 index 0000000000..2bff9f71bb --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Pop11/sum-and-product-of-an-array-2.pop11 @@ -0,0 +1,3 @@ +lvars sum = 0, prod = 1, ar = {1 2 3 4 5 6 7 8 9}; +appdata(ar, procedure(x); x + sum -> sum; endprocedure); +appdata(ar, procedure(x); x * prod -> prod; endprocedure); diff --git a/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-1.ps b/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-1.ps new file mode 100644 index 0000000000..c75066cb6b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-1.ps @@ -0,0 +1,20 @@ +/sumandproduct +{ +/x exch def +/sum 0 def +/prod 0 def +/i 0 def +x length 0 eq +{ +} +{ +/prod prod 1 add def +x length{ +/sum sum x i get add def +/prod prod x i get mul def +/i i 1 add def +}repeat +}ifelse +sum == +prod == +}def diff --git a/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-2.ps b/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-2.ps new file mode 100644 index 0000000000..ff38967fb4 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PostScript/sum-and-product-of-an-array-2.ps @@ -0,0 +1,4 @@ +% sum +[1 1 1 1 1] 0 {add} fold +% product +[1 1 1 1 1] 1 {mul} fold diff --git a/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-1.psh b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-1.psh new file mode 100644 index 0000000000..acf7f29747 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-1.psh @@ -0,0 +1,3 @@ +function Get-Sum ($a) { + return ($a | Measure-Object -Sum).Sum +} diff --git a/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-2.psh b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-2.psh new file mode 100644 index 0000000000..30df2dbc63 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-2.psh @@ -0,0 +1,11 @@ +function Get-Product ($a) { + if ($a.Length -eq 0) { + return 0 + } else { + $p = 1 + foreach ($x in $a) { + $p *= $x + } + return $p + } +} diff --git a/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-3.psh b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-3.psh new file mode 100644 index 0000000000..9edd3bdeab --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-3.psh @@ -0,0 +1,7 @@ +function Get-Product ($a) { + if ($a.Length -eq 0) { + return 0 + } + $s = $a -join '*' + return (Invoke-Expression $s) +} diff --git a/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-4.psh b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-4.psh new file mode 100644 index 0000000000..4f4ebf8c35 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-4.psh @@ -0,0 +1,16 @@ +function Get-SumAndProduct ($a) { + $sum = 0 + if ($a.Length -eq 0) { + $prod = 0 + } else { + $prod = 1 + foreach ($x in $a) { + $sum += $x + $prod *= $x + } + } + $ret = New-Object PSObject + $ret | Add-Member NoteProperty Sum $sum + $ret | Add-Member NoteProperty Product $prod + return $ret +} diff --git a/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-1.pro b/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-1.pro new file mode 100644 index 0000000000..91a496eb46 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-1.pro @@ -0,0 +1,4 @@ +sum([],0). +sum([H|T],X) :- sum(T,Y), X is H + Y. +product([],1). +product([H|T],X) :- product(T,Y), X is H * X. diff --git a/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-2.pro b/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-2.pro new file mode 100644 index 0000000000..8f3d9d6964 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Prolog/sum-and-product-of-an-array-2.pro @@ -0,0 +1,22 @@ +add(A,B,R):- + R is A + B. + +mul(A,B,R):- + R is A * B. + +% define fold now. +fold([], Act, Init, Init). + +fold(Lst, Act, Init, Res):- + head(Lst,Hd), + tail(Lst,Tl), + apply(Act,[Init, Hd, Ra]), + fold(Tl, Act, Ra, Res). + +sumproduct(Lst, Sum, Prod):- + fold(Lst,mul,1, Prod), + fold(Lst,add,0, Sum). + +?- sumproduct([1,2,3,4],Sum,Prod). +Sum = 10, +Prod = 24 . diff --git a/Task/Sum-and-product-of-an-array/PureBasic/sum-and-product-of-an-array.purebasic b/Task/Sum-and-product-of-an-array/PureBasic/sum-and-product-of-an-array.purebasic new file mode 100644 index 0000000000..28774dcd51 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/PureBasic/sum-and-product-of-an-array.purebasic @@ -0,0 +1,14 @@ +Dim MyArray(9) +Define a, sum=0, prod=1 + +For a = 0 To ArraySize(MyArray()) ; Create a list of some random numbers + MyArray(a) = 1 + Random(9) ; Insert a number [1...10] in current element +Next + +For a = 0 To ArraySize(MyArray()) ; Calculate Sum and Product of this Array + sum + MyArray(a) + prod * MyArray(a) +Next + +Debug "The sum is " + Str(sum) ; Present the results +Debug "Product is " + Str(prod) diff --git a/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-1.py b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-1.py new file mode 100644 index 0000000000..e6fbcffeca --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-1.py @@ -0,0 +1,6 @@ +numbers = [1, 2, 3] +total = sum(numbers) + +product = 1 +for i in numbers: + product *= i diff --git a/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-2.py b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-2.py new file mode 100644 index 0000000000..6da0470518 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-2.py @@ -0,0 +1,5 @@ +from operator import mul, add +sum = reduce(add, numbers) # note: this version doesn't work with empty lists +sum = reduce(add, numbers, 0) +product = reduce(mul, numbers) # note: this version doesn't work with empty lists +product = reduce(mul, numbers, 1) diff --git a/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-3.py b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-3.py new file mode 100644 index 0000000000..6d31e1f99e --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-3.py @@ -0,0 +1,4 @@ +from numpy import r_ +numbers = r_[1:4] +total = numbers.sum() +product = numbers.prod() diff --git a/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-4.py b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-4.py new file mode 100644 index 0000000000..6d73204a27 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Python/sum-and-product-of-an-array-4.py @@ -0,0 +1,2 @@ +import math +total = math.fsum(floats) diff --git a/Task/Sum-and-product-of-an-array/R/sum-and-product-of-an-array.r b/Task/Sum-and-product-of-an-array/R/sum-and-product-of-an-array.r new file mode 100644 index 0000000000..9e57843866 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/R/sum-and-product-of-an-array.r @@ -0,0 +1,2 @@ +total <- sum(1:5) +product <- prod(1:5) diff --git a/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol b/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol new file mode 100644 index 0000000000..39d2a3fa2a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol @@ -0,0 +1,37 @@ +REBOL [ + Title: "Sum and Product" + Date: 2010-01-04 + Author: oofoe + URL: http://rosettacode.org/wiki/Sum_and_product_of_array +] + +; Simple: + +sum: func [a [block!] /local x] [x: 0 forall a [x: x + a/1] x] + +product: func [a [block!] /local x] [x: 1 forall a [x: x * a/1] x] + +; Way too fancy: + +redux: func [ + "Applies an operation across an array to produce a reduced value." + a [block!] "Array to operate on." + op [word!] "Operation to perform." + /init x "Initial value (default 0)." +][if not init [x: 0] forall a [x: do compose [x (op) (a/1)]] x] + +rsum: func [a [block!]][redux a '+] + +rproduct: func [a [block!]][redux/init a '* 1] + +; Tests: + +assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] + +print "Simple dedicated functions:" +assert [55 = sum [1 2 3 4 5 6 7 8 9 10]] +assert [3628800 = product [1 2 3 4 5 6 7 8 9 10]] + +print [crlf "Fancy reducing function:"] +assert [55 = rsum [1 2 3 4 5 6 7 8 9 10]] +assert [3628800 = rproduct [1 2 3 4 5 6 7 8 9 10]] diff --git a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx new file mode 100644 index 0000000000..3c17cb2424 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx @@ -0,0 +1,18 @@ +/*REXX program to add and separately multiply elements of an array. */ +numeric digits 30 /*allow 30-digit numbers (default is 9)*/ + +m=20 /*one method of indicating array size. */ + do j=1 for m /*build an array of twenty elements. */ + y.j=j /*set 1st to 1, 3rd to 3, 9th to 9 ... */ + end /*j*/ +sum=0 /*initialize SUM to zero. */ +prod=1 /*initialize PROD to unity. */ + do k=1 for m + sum =sum +y.k /*add the element to the running total.*/ + prod=prod*y.k /*multiple the element to running prod.*/ + end /*k*/ + +say ' sum of' m "elements for the Y array is: " sum +say 'product of' m "elements for the Y array is: " prod + + /*stick a fork in it, we're done. */ diff --git a/Task/Sum-and-product-of-an-array/Racket/sum-and-product-of-an-array.rkt b/Task/Sum-and-product-of-an-array/Racket/sum-and-product-of-an-array.rkt new file mode 100644 index 0000000000..b8087a7b8c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Racket/sum-and-product-of-an-array.rkt @@ -0,0 +1,4 @@ +#lang racket + +(for/sum ([x #(3 1 4 1 5 9)]) x) +(for/product ([x #(3 1 4 1 5 9)]) x) diff --git a/Task/Sum-and-product-of-an-array/Raven/sum-and-product-of-an-array.raven b/Task/Sum-and-product-of-an-array/Raven/sum-and-product-of-an-array.raven new file mode 100644 index 0000000000..34b0843c69 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Raven/sum-and-product-of-an-array.raven @@ -0,0 +1,2 @@ +0 [ 1 2 3 ] each + +1 [ 1 2 3 ] each * diff --git a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb new file mode 100644 index 0000000000..bb4912d55c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb @@ -0,0 +1,5 @@ +arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a +sum = arr.inject(0) { |sum, item| sum + item } +# => 15 +product = arr.inject(1) { |prod, element| prod * element } +# => 120 diff --git a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb new file mode 100644 index 0000000000..38a3db68e5 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb @@ -0,0 +1,5 @@ +arr = [1,2,3,4,5] +sum = arr.inject(0, :+) +# => 15 +product = arr.inject(1, :*) +# => 120 diff --git a/Task/Sum-and-product-of-an-array/Run-BASIC/sum-and-product-of-an-array.run b/Task/Sum-and-product-of-an-array/Run-BASIC/sum-and-product-of-an-array.run new file mode 100644 index 0000000000..6881ef689c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Run-BASIC/sum-and-product-of-an-array.run @@ -0,0 +1,13 @@ +dim array(100) +for i = 1 To 100 + array(i) = rnd(0) * 100 +next i + +product = 1 +for i = 0 To 19 + sum = (sum + array(i)) + product = (product * array(i)) +next i + +Print " Sum is ";sum +Print "Product is ";product diff --git a/Task/Sum-and-product-of-an-array/SAS/sum-and-product-of-an-array.sas b/Task/Sum-and-product-of-an-array/SAS/sum-and-product-of-an-array.sas new file mode 100644 index 0000000000..e3511f00b6 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/SAS/sum-and-product-of-an-array.sas @@ -0,0 +1,8 @@ +data _null_; + array a{*} a1-a100; + do i=1 to 100; + a{i}=i*i; + end; + b=sum(of a{*}); + put b c; +run; diff --git a/Task/Sum-and-product-of-an-array/SETL/sum-and-product-of-an-array.setl b/Task/Sum-and-product-of-an-array/SETL/sum-and-product-of-an-array.setl new file mode 100644 index 0000000000..7a21f0abad --- /dev/null +++ b/Task/Sum-and-product-of-an-array/SETL/sum-and-product-of-an-array.setl @@ -0,0 +1,2 @@ +numbers := [1 2 3 4 5 6 7 8 9]; +print(+/ numbers, */ numbers); diff --git a/Task/Sum-and-product-of-an-array/SNOBOL4/sum-and-product-of-an-array.sno b/Task/Sum-and-product-of-an-array/SNOBOL4/sum-and-product-of-an-array.sno new file mode 100644 index 0000000000..3287fa343d --- /dev/null +++ b/Task/Sum-and-product-of-an-array/SNOBOL4/sum-and-product-of-an-array.sno @@ -0,0 +1,13 @@ + t = table() +* read the integer from the std. input +init_tab t = trim(input) :s(init_tab) + product = 1 + sum = 0 + +* counting backwards to 1 +loop i = t< x = ?gt(x,1) x - 1> :f(out) + sum = sum + i + product = product * i :(loop) +out output = "Sum: " sum + output = "Prod: " product +end diff --git a/Task/Sum-and-product-of-an-array/Sather/sum-and-product-of-an-array.sa b/Task/Sum-and-product-of-an-array/Sather/sum-and-product-of-an-array.sa new file mode 100644 index 0000000000..061ea24e82 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Sather/sum-and-product-of-an-array.sa @@ -0,0 +1,10 @@ +class MAIN is + main is + a :ARRAY{INT} := |10, 5, 5, 20, 60, 100|; + sum, prod :INT; + loop sum := sum + a.elt!; end; + prod := 1; + loop prod := prod * a.elt!; end; + #OUT + sum + " " + prod + "\n"; + end; +end; diff --git a/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-1.scala b/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-1.scala new file mode 100644 index 0000000000..df32374c44 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-1.scala @@ -0,0 +1,3 @@ +val seq = Seq(1, 2, 3, 4, 5) +val sum = seq.foldLeft(0)(_ + _) +val product = seq.foldLeft(1)(_ * _) diff --git a/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-2.scala b/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-2.scala new file mode 100644 index 0000000000..6036c304ba --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Scala/sum-and-product-of-an-array-2.scala @@ -0,0 +1,2 @@ +val sum = seq.sum +val product = seq.product diff --git a/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.ss b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.ss new file mode 100644 index 0000000000..40bec3f9f7 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.ss @@ -0,0 +1,2 @@ +(apply + '(1 2 3 4 5)) +(apply * '(1 2 3 4 5)) diff --git a/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.ss b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.ss new file mode 100644 index 0000000000..ef1bcefe74 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.ss @@ -0,0 +1,7 @@ +(define (reduce f i l) + (if (null? l) + i + (reduce f (f i (car l)) (cdr l)))) + +(reduce + 0 '(1 2 3 4 5)) ;; 0 is unit for + +(reduce * 1 '(1 2 3 4 5)) ;; 1 is unit for * diff --git a/Task/Sum-and-product-of-an-array/Seed7/sum-and-product-of-an-array.seed7 b/Task/Sum-and-product-of-an-array/Seed7/sum-and-product-of-an-array.seed7 new file mode 100644 index 0000000000..5a073c0b33 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Seed7/sum-and-product-of-an-array.seed7 @@ -0,0 +1,21 @@ +const func integer: sumArray (in array integer: valueArray) is func + result + var integer: sum is 0; + local + var integer: value is 0; + begin + for value range valueArray do + sum +:= value; + end for; + end func; + +const func integer: prodArray (in array integer: valueArray) is func + result + var integer: prod is 1; + local + var integer: value is 0; + begin + for value range valueArray do + prod *:= value; + end for; + end func; diff --git a/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-1.slate b/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-1.slate new file mode 100644 index 0000000000..91e409690f --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-1.slate @@ -0,0 +1,2 @@ +#(1 2 3 4 5) reduce: [:sum :number | sum + number] +#(1 2 3 4 5) reduce: [:product :number | product * number] diff --git a/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-2.slate b/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-2.slate new file mode 100644 index 0000000000..3cf7891b84 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Slate/sum-and-product-of-an-array-2.slate @@ -0,0 +1,2 @@ +#(1 2 3 4 5) reduce: #+ `er +#(1 2 3 4 5) reduce: #* `er diff --git a/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-1.st b/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-1.st new file mode 100644 index 0000000000..b92b5b3568 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-1.st @@ -0,0 +1,2 @@ +#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number] +#(1 2 3 4 5) inject: 1 into: [:product :number | product * number] diff --git a/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-2.st b/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-2.st new file mode 100644 index 0000000000..f4295d6eeb --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Smalltalk/sum-and-product-of-an-array-2.st @@ -0,0 +1,2 @@ +#(1 2 3 4 5) fold: [:sum :number | sum + number] +#(1 2 3 4 5) fold: [:product :number | product * number] diff --git a/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-1.ml b/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-1.ml new file mode 100644 index 0000000000..d7774e1889 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-1.ml @@ -0,0 +1,8 @@ +(* ints *) +val a = Array.fromList [1, 2, 3, 4, 5]; +Array.foldl op+ 0 a; +Array.foldl op* 1 a; +(* reals *) +val a = Array.fromList [1.0, 2.0, 3.0, 4.0, 5.0]; +Array.foldl op+ 0.0 a; +Array.foldl op* 1.0 a; diff --git a/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-2.ml b/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-2.ml new file mode 100644 index 0000000000..a6ecf2e37a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Standard-ML/sum-and-product-of-an-array-2.ml @@ -0,0 +1,8 @@ +(* ints *) +val x = [1, 2, 3, 4, 5]; +foldl op+ 0 x; +foldl op* 1 x; +(* reals *) +val x = [1.0, 2.0, 3.0, 4.0, 5.0]; +foldl op+ 0.0 x; +foldl op* 1.0 x; diff --git a/Task/Sum-and-product-of-an-array/TUSCRIPT/sum-and-product-of-an-array.tuscript b/Task/Sum-and-product-of-an-array/TUSCRIPT/sum-and-product-of-an-array.tuscript new file mode 100644 index 0000000000..0e6ed92af7 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/TUSCRIPT/sum-and-product-of-an-array.tuscript @@ -0,0 +1,10 @@ +$$ MODE TUSCRIPT +list="1'2'3'4'5" +sum=SUM(list) +PRINT " sum: ",sum + +product=1 +LOOP l=list +product=product*l +ENDLOOP +PRINT "product: ",product diff --git a/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-1.tcl b/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-1.tcl new file mode 100644 index 0000000000..0d2d04b00a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-1.tcl @@ -0,0 +1,3 @@ +set arr [list 3 6 8] +set sum [expr [join $arr +]] +set prod [expr [join $arr *]] diff --git a/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-2.tcl b/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-2.tcl new file mode 100644 index 0000000000..e81cd6f08b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Tcl/sum-and-product-of-an-array-2.tcl @@ -0,0 +1,3 @@ +set arr [list 3 6 8] +set sum [tcl::mathop::+ {*}$arr] +set prod [tcl::mathop::* {*}$arr] diff --git a/Task/Sum-and-product-of-an-array/Toka/sum-and-product-of-an-array.toka b/Task/Sum-and-product-of-an-array/Toka/sum-and-product-of-an-array.toka new file mode 100644 index 0000000000..5ada649b44 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Toka/sum-and-product-of-an-array.toka @@ -0,0 +1,12 @@ +4 cells is-array foo + +212 1 foo array.put +51 2 foo array.put +12 3 foo array.put +91 4 foo array.put + +[ ( array size -- sum ) + >r 0 r> 0 [ over i swap array.get + ] countedLoop nip ] is sum-array + + ( product ) +reset 1 4 0 [ i foo array.get * ] countedLoop . diff --git a/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-1.trith b/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-1.trith new file mode 100644 index 0000000000..111d4b637d --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-1.trith @@ -0,0 +1 @@ +[1 2 3 4 5] 0 [+] foldl diff --git a/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-2.trith b/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-2.trith new file mode 100644 index 0000000000..8b383d9b1c --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Trith/sum-and-product-of-an-array-2.trith @@ -0,0 +1 @@ +[1 2 3 4 5] 1 [*] foldl diff --git a/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-1.sh b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-1.sh new file mode 100644 index 0000000000..a2cb70be49 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-1.sh @@ -0,0 +1,7 @@ +sum=0 +prod=1 +list="1 2 3" +for n in $list +do sum="$(($sum + $n))"; prod="$(($prod * $n))" +done +echo $sum $prod diff --git a/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-2.sh b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-2.sh new file mode 100644 index 0000000000..18fe5b70cb --- /dev/null +++ b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-2.sh @@ -0,0 +1,6 @@ +sum=0 +prod=1 +for n +do sum="$(($sum + $n))"; prod="$(($prod * $n))" +done +echo $sum $prod diff --git a/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-3.sh b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-3.sh new file mode 100644 index 0000000000..b8ecbcf682 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-3.sh @@ -0,0 +1,6 @@ +sum=0 +prod=1 +while read n +do sum="$(($sum + $n))"; prod="$(($prod * $n))" +done +echo $sum $prod diff --git a/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-4.sh b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-4.sh new file mode 100644 index 0000000000..97664b4bbe --- /dev/null +++ b/Task/Sum-and-product-of-an-array/UNIX-Shell/sum-and-product-of-an-array-4.sh @@ -0,0 +1,6 @@ +LIST='20 20 2'; +SUM=0; PROD=1; +for i in $LIST; do + SUM=$[$SUM + $i]; PROD=$[$PROD * $i]; +done; +echo $SUM $PROD diff --git a/Task/Sum-and-product-of-an-array/UnixPipes/sum-and-product-of-an-array.unixpipes b/Task/Sum-and-product-of-an-array/UnixPipes/sum-and-product-of-an-array.unixpipes new file mode 100644 index 0000000000..2e7dc27e5b --- /dev/null +++ b/Task/Sum-and-product-of-an-array/UnixPipes/sum-and-product-of-an-array.unixpipes @@ -0,0 +1,15 @@ +prod() { + (read B; res=$1; test -n "$B" && expr $res \* $B || echo $res) +} + +sum() { + (read B; res=$1; test -n "$B" && expr $res + $B || echo $res) +} + +fold() { + (func=$1; while read a ; do fold $func | $func $a ; done) +} + + +(echo 3; echo 1; echo 4;echo 1;echo 5;echo 9) | + tee >(fold sum) >(fold prod) > /dev/null diff --git a/Task/Sum-and-product-of-an-array/Ursala/sum-and-product-of-an-array.ursala b/Task/Sum-and-product-of-an-array/Ursala/sum-and-product-of-an-array.ursala new file mode 100644 index 0000000000..e1c3b96ff5 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ursala/sum-and-product-of-an-array.ursala @@ -0,0 +1,4 @@ +#import nat +#cast %nW + +sp = ^(sum:-0,product:-1) <62,43,46,40,29,55,51,82,59,92,48,73,93,35,42,25> diff --git a/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-1.v b/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-1.v new file mode 100644 index 0000000000..4648b9fc04 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-1.v @@ -0,0 +1 @@ +[sp dup 0 [+] fold 'product=' put puts 1 [*] fold 'sum=' put puts]. diff --git a/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-2.v b/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-2.v new file mode 100644 index 0000000000..fb0f9c4f03 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/V/sum-and-product-of-an-array-2.v @@ -0,0 +1,4 @@ +[1 2 3 4 5] sp += +product=15 +sum=120 diff --git a/Task/Sum-and-product-of-an-array/Vala/sum-and-product-of-an-array.vala b/Task/Sum-and-product-of-an-array/Vala/sum-and-product-of-an-array.vala new file mode 100644 index 0000000000..e054575785 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Vala/sum-and-product-of-an-array.vala @@ -0,0 +1,10 @@ +public static void main(){ + int sum = 0, product = 1; + + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + foreach (int number in array){ + sum += number; + product *= number; + } +} diff --git a/Task/Sum-and-product-of-an-array/XPL0/sum-and-product-of-an-array.xpl0 b/Task/Sum-and-product-of-an-array/XPL0/sum-and-product-of-an-array.xpl0 new file mode 100644 index 0000000000..7034a5636a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/XPL0/sum-and-product-of-an-array.xpl0 @@ -0,0 +1,12 @@ +code CrLf=9, IntOut=11; + +func SumProd(A, L); +int A, L; +int S, P, I; +[S:= 0; P:= 1; +for I:= 0 to L-1 do [S:= S+A(I); P:= P*A(I)]; +IntOut(0, S); CrLf(0); +IntOut(0, P); CrLf(0); +]; \SumSq + +SumProd([1,2,3,4,5,6,7,8,9,10], 10) diff --git a/Task/Sum-and-product-of-an-array/XSLT/sum-and-product-of-an-array.xslt b/Task/Sum-and-product-of-an-array/XSLT/sum-and-product-of-an-array.xslt new file mode 100644 index 0000000000..84f1619c09 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/XSLT/sum-and-product-of-an-array.xslt @@ -0,0 +1,36 @@ + + + + + + + + + + +Sum: + + +Product: + + + + + + + + + + + + + + +Sum (built-in): + + + + + + + diff --git a/Task/Sum-digits-of-an-integer/0DESCRIPTION b/Task/Sum-digits-of-an-integer/0DESCRIPTION new file mode 100644 index 0000000000..1d46ddcb2b --- /dev/null +++ b/Task/Sum-digits-of-an-integer/0DESCRIPTION @@ -0,0 +1,5 @@ +This task is to take a Natural Number in a given Base and return the sum of its digits: +:110 sums to 1; +:123410 sums to 10; +:fe16 sums to 29; +:f0e16 sums to 29. diff --git a/Task/Sum-digits-of-an-integer/AWK/sum-digits-of-an-integer.awk b/Task/Sum-digits-of-an-integer/AWK/sum-digits-of-an-integer.awk new file mode 100644 index 0000000000..3b2bb2dcb6 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/AWK/sum-digits-of-an-integer.awk @@ -0,0 +1,23 @@ +#!/usr/bin/awk -f + +BEGIN { + print sumDigits("1") + print sumDigits("12") + print sumDigits("fe") + print sumDigits("f0e") +} + +function sumDigits(num, nDigs, digits, sum, d, dig, val, sum) { + nDigs = split(num, digits, "") + sum = 0 + for (d = 1; d <= nDigs; d++) { + dig = digits[d] + val = digToDec(dig) + sum += val + } + return sum +} + +function digToDec(dig) { + return index("0123456789abcdef", tolower(dig)) - 1 +} diff --git a/Task/Sum-digits-of-an-integer/Ada/sum-digits-of-an-integer.ada b/Task/Sum-digits-of-an-integer/Ada/sum-digits-of-an-integer.ada new file mode 100644 index 0000000000..cc7c3a7b05 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Ada/sum-digits-of-an-integer.ada @@ -0,0 +1,28 @@ +with Ada.Integer_Text_IO; + +procedure Sum_Digits is + -- sums the digits of an integer (in whatever base) + -- outputs the sum (in base 10) + + function Sum_Of_Digits(N: Natural; Base: Natural := 10) return Natural is + Sum: Natural := 0; + Val: Natural := N; + begin + while Val > 0 loop + Sum := Sum + (Val mod Base); + Val := Val / Base; + end loop; + return Sum; + end Sum_Of_Digits; + + use Ada.Integer_Text_IO; + +begin -- main procedure Sum_Digits + Put(Sum_OF_Digits(1)); -- 1 + Put(Sum_OF_Digits(12345)); -- 15 + Put(Sum_OF_Digits(123045)); -- 15 + Put(Sum_OF_Digits(123045, 50)); -- 104 + Put(Sum_OF_Digits(16#fe#, 10)); -- 11 + Put(Sum_OF_Digits(16#fe#, 16)); -- 29 + Put(Sum_OF_Digits(16#f0e#, 16)); -- 29 +end Sum_Digits; diff --git a/Task/Sum-digits-of-an-integer/BBC-BASIC/sum-digits-of-an-integer.bbc b/Task/Sum-digits-of-an-integer/BBC-BASIC/sum-digits-of-an-integer.bbc new file mode 100644 index 0000000000..b524a4aa0c --- /dev/null +++ b/Task/Sum-digits-of-an-integer/BBC-BASIC/sum-digits-of-an-integer.bbc @@ -0,0 +1,16 @@ + *FLOAT64 + PRINT "Digit sum of 1 (base 10) is "; FNdigitsum(1, 10) + PRINT "Digit sum of 12345 (base 10) is "; FNdigitsum(12345, 10) + PRINT "Digit sum of 9876543210 (base 10) is "; FNdigitsum(9876543210, 10) + PRINT "Digit sum of FE (base 16) is "; ~FNdigitsum(&FE, 16) " (base 16)" + PRINT "Digit sum of F0E (base 16) is "; ~FNdigitsum(&F0E, 16) " (base 16)" + END + + DEF FNdigitsum(n, b) + LOCAL q, s + WHILE n <> 0 + q = INT(n / b) + s += n - q * b + n = q + ENDWHILE + = s diff --git a/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer.cpp b/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer.cpp new file mode 100644 index 0000000000..b4963f0e1f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/C++/sum-digits-of-an-integer.cpp @@ -0,0 +1,22 @@ +#include +#include +int SumDigits(const unsigned long long int digits, const int BASE = 10) { + int sum = 0; + unsigned long long int x = digits; + for (int i = log(digits)/log(BASE); i>0; i--){ + const double z = std::pow(BASE,i); + const unsigned long long int t = x/z; + sum += t; + x -= t*z; + } + return x+sum; +} + +int main() { + std::cout << SumDigits(1) << ' ' + << SumDigits(12345) << ' ' + << SumDigits(123045) << ' ' + << SumDigits(0xfe, 16) << ' ' + << SumDigits(0xf0e, 16) << std::endl; + return 0; +} diff --git a/Task/Sum-digits-of-an-integer/C/sum-digits-of-an-integer.c b/Task/Sum-digits-of-an-integer/C/sum-digits-of-an-integer.c new file mode 100644 index 0000000000..807649b297 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/C/sum-digits-of-an-integer.c @@ -0,0 +1,18 @@ +#include + +int SumDigits(unsigned long long n, const int base) { + int sum = 0; + for (; n; n /= base) + sum += n % base; + return sum; +} + +int main() { + printf("%d %d %d %d %d\n", + SumDigits(1, 10), + SumDigits(12345, 10), + SumDigits(123045, 10), + SumDigits(0xfe, 16), + SumDigits(0xf0e, 16) ); + return 0; +} diff --git a/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-1.lisp b/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-1.lisp new file mode 100644 index 0000000000..cb87995265 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-1.lisp @@ -0,0 +1,4 @@ +(defun sum-digits (number base) + (loop for n = number then q + for (q r) = (multiple-value-list (truncate n base)) + sum r until (zerop q))) diff --git a/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-2.lisp b/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-2.lisp new file mode 100644 index 0000000000..4b84b05421 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Common-Lisp/sum-digits-of-an-integer-2.lisp @@ -0,0 +1,2 @@ +(loop for (number base) in '((1 10) (1234 10) (#xfe 16) (#xf0e 16)) + do (format t "(~a)_~a = ~a~%" number base (sum-digits number base))) diff --git a/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d new file mode 100644 index 0000000000..4c2715be73 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d @@ -0,0 +1,21 @@ +uint sumDigits(T)(T n, in uint base=10) /*pure nothrow*/ +in { + assert(base > 1); +} body { + typeof(return) total = 0; + //while (n) { + while (n != 0) { + total += n % base; + n /= base; + } + return total; +} + +void main() { + import std.stdio, std.bigint; + writeln(sumDigits(1)); + writeln(sumDigits(1_234)); + writeln(sumDigits(0xfe, 16)); + writeln(sumDigits(0xf0e, 16)); + writeln(sumDigits(BigInt(1_234))); +} diff --git a/Task/Sum-digits-of-an-integer/Erlang/sum-digits-of-an-integer.erl b/Task/Sum-digits-of-an-integer/Erlang/sum-digits-of-an-integer.erl new file mode 100644 index 0000000000..2561c9209c --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Erlang/sum-digits-of-an-integer.erl @@ -0,0 +1,15 @@ +-module(sum_digits). +-export([sum_digits/2, sum_digits/1]). + +sum_digits(N) -> + sum_digits(N,10). + +sum_digits(N,B) -> + sum_digits(N,B,0). + +sum_digits(0,_,Acc) -> + Acc; +sum_digits(N,B,Acc) when N < B -> + Acc+N; +sum_digits(N,B,Acc) -> + sum_digits(N div B, B, Acc + (N rem B)). diff --git a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go new file mode 100644 index 0000000000..58aa050361 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go @@ -0,0 +1,26 @@ +package digit + +import ( + "errors" + "strconv" +) + +func Sum(n string, base int) (int64, error) { + if base < 2 || base > 36 { + return 0, errors.New("base must be from 2 to 36") + } + i, err := strconv.ParseInt(n, base, 64) + if err != nil { + return 0, err + } + if i < 0 { + return 0, errors.New("number must be non-negative") + } + b64 := int64(base) + var sum int64 + for i > 0 { + sum += i % b64 + i /= b64 + } + return sum, nil +} diff --git a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go new file mode 100644 index 0000000000..770c380b58 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go @@ -0,0 +1,32 @@ +package digit_test + +import ( + "testing" + + "digit" +) + +type testCase struct { + n string + base int + dSum int64 +} + +var testData = []testCase{ + {"1", 10, 1}, + {"1234", 10, 10}, + {"fe", 16, 29}, + {"f0e", 16, 29}, +} + +func testSum(t *testing.T) { + for _, tc := range testData { + ds, err := digit.Sum(tc.n, tc.base) + if err != nil { + t.Fatal("test case", tc, err) + } + if ds != tc.dSum { + t.Fatal("test case", tc, "got", ds, "expected", tc.dSum) + } + } +} diff --git a/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-1.groovy b/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-1.groovy new file mode 100644 index 0000000000..e8c00ae913 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-1.groovy @@ -0,0 +1,3 @@ +def digitsum = { number, radix = 10 -> + Integer.toString(number, radix).collect { Integer.parseInt(it, radix) }.sum() +} diff --git a/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-2.groovy b/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-2.groovy new file mode 100644 index 0000000000..18f172cb5b --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Groovy/sum-digits-of-an-integer-2.groovy @@ -0,0 +1,9 @@ +[[30, 2], [30, 10], [1, 10], [12345, 10], [123405, 10], [0xfe, 16], [0xf0e, 16]].each { + println """ + Decimal value: ${it[0]} + Radix: ${it[1]} + Radix value: ${Integer.toString(it[0], it[1])} + Decimal Digit Sum: ${digitsum(it[0], it[1])} + Radix Digit Sum: ${Integer.toString(digitsum(it[0], it[1]), it[1])} + """ +} diff --git a/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs new file mode 100644 index 0000000000..79ce63457f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Haskell/sum-digits-of-an-integer.hs @@ -0,0 +1,6 @@ +digsum base = f 0 where + f a 0 = a + f a n = f (a+r) q where + (q,r) = n `divMod` base + +main = print $ digsum 16 255 -- "FF": 15 + 15 = 30 diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-1.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-1.j new file mode 100644 index 0000000000..7bc30b9e78 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-1.j @@ -0,0 +1 @@ +digsum=: 10&$: : (+/@(#.inv)) diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-2.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-2.j new file mode 100644 index 0000000000..2da745e6fe --- /dev/null +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-2.j @@ -0,0 +1,6 @@ + digsum 1234 +10 + 10 digsum 254 +11 + 16 digsum 254 +29 diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-3.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-3.j new file mode 100644 index 0000000000..18275046e8 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-3.j @@ -0,0 +1,8 @@ + 10 #. 1 2 3 4 +1234 + 10 #.inv 1234 +1 2 3 4 + 10 +/ 1 2 3 4 +10 + 10 +/@(#.inv) 1234 +10 diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-4.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-4.j new file mode 100644 index 0000000000..7b8a55b6f9 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-4.j @@ -0,0 +1,8 @@ + digsum 1 +1 + digsum 1234 +10 + 16 digsum 16bfe +29 + 16 digsum 16bf0e +29 diff --git a/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j new file mode 100644 index 0000000000..d776ea4db6 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/J/sum-digits-of-an-integer-5.j @@ -0,0 +1,8 @@ + 200+54 +254 + 254 +254 + 2.54e2 +254 + 16bfe +254 diff --git a/Task/Sum-digits-of-an-integer/Java/sum-digits-of-an-integer.java b/Task/Sum-digits-of-an-integer/Java/sum-digits-of-an-integer.java new file mode 100644 index 0000000000..8e4d353c00 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Java/sum-digits-of-an-integer.java @@ -0,0 +1,32 @@ +import java.math.BigInteger; +public class SumDigits { + public static int sumDigits(long num) { + return sumDigits(num, 10); + } + public static int sumDigits(long num, int base) { + String s = Long.toString(num, base); + int result = 0; + for (int i = 0; i < s.length(); i++) + result += Character.digit(s.charAt(i), base); + return result; + } + public static int sumDigits(BigInteger num) { + return sumDigits(num, 10); + } + public static int sumDigits(BigInteger num, int base) { + String s = num.toString(base); + int result = 0; + for (int i = 0; i < s.length(); i++) + result += Character.digit(s.charAt(i), base); + return result; + } + + public static void main(String[] args) { + System.out.println(sumDigits(1)); + System.out.println(sumDigits(12345)); + System.out.println(sumDigits(123045)); + System.out.println(sumDigits(0xfe, 16)); + System.out.println(sumDigits(0xf0e, 16)); + System.out.println(sumDigits(new BigInteger("12345678901234567890"))); + } +} diff --git a/Task/Sum-digits-of-an-integer/Mathematica/sum-digits-of-an-integer.math b/Task/Sum-digits-of-an-integer/Mathematica/sum-digits-of-an-integer.math new file mode 100644 index 0000000000..49be800f0a --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Mathematica/sum-digits-of-an-integer.math @@ -0,0 +1,2 @@ +Total[IntegerDigits[1234]] +Total[IntegerDigits[16^^FE, 16]] diff --git a/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-1.netrexx b/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-1.netrexx new file mode 100644 index 0000000000..c874472297 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-1.netrexx @@ -0,0 +1,66 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +parse arg input +inputs = ['1234', '01234', '0xfe', '0xf0e', '0', '00', '0,2' '1', '070', '77, 8' '0xf0e, 10', '070, 16', '0xf0e, 36', '000999ABCXYZ, 36', 'ff, 16', 'f, 10', 'z, 37'] -- test data +if input.length() > 0 then inputs = [input] -- replace test data with user input +loop i_ = 0 to inputs.length - 1 + in = inputs[i_] + parse in val . ',' base . + dSum = sumDigits(val, base) + say 'Sum of digits for integer "'val'" for a given base of "'base'":' dSum'\-' + -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9 + loop while dSum.length() > 1 & dSum.datatype('n') + dSum = sumDigits(dSum, 10) + say ',' dSum'\-' + end + say + end i_ + +-- Sum digits of an integer +method sumDigits(val = Rexx, base = Rexx '') public static returns Rexx + + rVal = 0 + parse normalizeValue(val, base) val base . + loop label digs for val.length() + -- loop to extract digits from input and sum them + parse val dv +1 val + do + rVal = rVal + Integer.valueOf(dv.toString(), base).intValue() + catch ex = NumberFormatException + rVal = 'NumberFormatException:' ex.getMessage() + leave digs + end + end digs + return rVal + +-- Clean up the input, normalize the data and determine which base to use +method normalizeValue(inV = Rexx, base = Rexx '') private static returns Rexx + inV = inV.strip('l') + base = base.strip() + parse inV xpref +2 . - + =0 opref +1 . - + =0 . '0x' xval . ',' . - + =0 . '0' oval . ',' . - + =0 dval . + + select + when xpref = '0x' & base.length() = 0 then do + -- value starts with '0x' and no base supplied. Assign hex as base + inval = xval + base = 16 + end + when opref = '0' & base.length() = 0 then do + -- value starts with '0' and no base supplied. Assign octal as base + inval = oval + base = 8 + end + otherwise do + inval = dval + end + end + if base.length() = 0 then base = 10 -- base not set. Assign decimal as base + if inval.length() <= 0 then inval = 0 -- boundary condition. Invalid input or a single zero + rVal = inval base + + return rVal diff --git a/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-2.netrexx b/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-2.netrexx new file mode 100644 index 0000000000..91f6071360 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/NetRexx/sum-digits-of-an-integer-2.netrexx @@ -0,0 +1,37 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +inputs = [[int 1234, 10], [octal('01234'), 8], [0xfe, 16], [0xf0e,16], [8b0, 2], [16b10101100, 2], [octal('077'), 8]] -- test data +loop i_ = 0 to inputs.length - 1 + in = inputs[i_, 0] + ib = inputs[i_, 1] + dSum = sumDigits(in, ib) + say 'Sum of digits for integer "'Integer.toString(in, ib)'" for a given base of "'ib'":' dSum'\-' + -- Carry the exercise to it's logical conclusion and sum the results to give a single digit in range 0-9 + loop while dSum.length() > 1 & dSum.datatype('n') + dSum = sumDigits(dSum, 10) + say ',' dSum'\-' + end + say + end i_ + +-- Sum digits of an integer +method sumDigits(val = int, base = int 10) public static returns Rexx + rVal = Rexx 0 + sVal = Rexx(Integer.toString(val, base)) + loop label digs for sVal.length() + -- loop to extract digits from input and sum them + parse sVal dv +1 sVal + do + rVal = rVal + Integer.valueOf(dv.toString(), base).intValue() + catch ex = NumberFormatException + rVal = 'NumberFormatException:' ex.getMessage() + leave digs + end + end digs + return rVal + +-- if there's a way to insert octal constants into an int in NetRexx I don't remember it +method octal(oVal = String) private constant returns int signals NumberFormatException + iVal = Integer.valueOf(oVal, 8).intValue() + return iVal diff --git a/Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ocaml b/Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ocaml new file mode 100644 index 0000000000..5958a1f84e --- /dev/null +++ b/Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ocaml @@ -0,0 +1,14 @@ +let sum_digits ~digits ~base = + let rec aux sum x = + if x <= 0 then sum else + aux (sum + x mod base) (x / base) + in + aux 0 digits + +let () = + Printf.printf "%d %d %d %d %d\n" + (sum_digits 1 10) + (sum_digits 12345 10) + (sum_digits 123045 10) + (sum_digits 0xfe 16) + (sum_digits 0xf0e 16) diff --git a/Task/Sum-digits-of-an-integer/Oberon-2/sum-digits-of-an-integer.oberon-2 b/Task/Sum-digits-of-an-integer/Oberon-2/sum-digits-of-an-integer.oberon-2 new file mode 100644 index 0000000000..9826e2218a --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Oberon-2/sum-digits-of-an-integer.oberon-2 @@ -0,0 +1,19 @@ +MODULE SumDigits; +IMPORT Out; +PROCEDURE Sum(n: LONGINT;base: INTEGER): LONGINT; +VAR + sum: LONGINT; +BEGIN + sum := 0; + WHILE (n > 0) DO + INC(sum,(n MOD base)); + n := n DIV base + END; + RETURN sum +END Sum; +BEGIN + Out.String("1 : ");Out.LongInt(Sum(1,10),10);Out.Ln; + Out.String("1234 : ");Out.LongInt(Sum(1234,10),10);Out.Ln; + Out.String("0FEH : ");Out.LongInt(Sum(0FEH,16),10);Out.Ln; + Out.String("OF0EH : ");Out.LongInt(Sum(0F0EH,16),10);Out.Ln +END SumDigits. diff --git a/Task/Sum-digits-of-an-integer/PARI-GP/sum-digits-of-an-integer.pari b/Task/Sum-digits-of-an-integer/PARI-GP/sum-digits-of-an-integer.pari new file mode 100644 index 0000000000..79851e3242 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PARI-GP/sum-digits-of-an-integer.pari @@ -0,0 +1 @@ +dsum(n,base)=my(s); while(n, s += n%base; n \= base); s diff --git a/Task/Sum-digits-of-an-integer/PHP/sum-digits-of-an-integer.php b/Task/Sum-digits-of-an-integer/PHP/sum-digits-of-an-integer.php new file mode 100644 index 0000000000..d4e2b277bd --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PHP/sum-digits-of-an-integer.php @@ -0,0 +1,13 @@ + diff --git a/Task/Sum-digits-of-an-integer/PL-I/sum-digits-of-an-integer.pli b/Task/Sum-digits-of-an-integer/PL-I/sum-digits-of-an-integer.pli new file mode 100644 index 0000000000..6113ebcd36 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PL-I/sum-digits-of-an-integer.pli @@ -0,0 +1,15 @@ +sum_digits: procedure options (main); /* 4/9/2012 */ + declare ch character (1); + declare (k, sd) fixed; + + on endfile (sysin) begin; put skip data (sd); stop; end; + sd = 0; + do forever; + get edit (ch) (a(1)); put edit (ch) (a); + k = index('abcdef', ch); + if k > 0 then /* we have a base above 10 */ + sd = sd + 9 + k; + else + sd = sd + ch; + end; +end sum_digits; diff --git a/Task/Sum-digits-of-an-integer/Perl-6/sum-digits-of-an-integer.pl6 b/Task/Sum-digits-of-an-integer/Perl-6/sum-digits-of-an-integer.pl6 new file mode 100644 index 0000000000..bb9d82204b --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Perl-6/sum-digits-of-an-integer.pl6 @@ -0,0 +1,3 @@ +say Σ $_ for <1 1234 1020304 fe f0e DEADBEEF>; + +sub Σ { [+] $^n.comb.map: { :36($_) } } diff --git a/Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer.pl b/Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer.pl new file mode 100644 index 0000000000..70712fc58d --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer.pl @@ -0,0 +1,23 @@ +#!/usr/bin/perl +use strict ; +use warnings ; + +#whatever the number base, a number stands for itself, and the letters start +#at number 10 ! + +sub sumdigits { + my $number = shift ; + my $hashref = shift ; + my $sum = 0 ; + map { if ( /\d/ ) { $sum += $_ } else { $sum += ${$hashref}{ $_ } } } + split( // , $number ) ; + return $sum ; +} + +my %lettervals ; +my $base = 10 ; +for my $letter ( 'a'..'z' ) { + $lettervals{ $letter } = $base++ ; +} +map { print "$_ sums to " . sumdigits( $_ , \%lettervals) . " !\n" } + ( 1 , 1234 , 'fe' , 'f0e' ) ; diff --git a/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-1.l b/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-1.l new file mode 100644 index 0000000000..7cf9cf2f42 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-1.l @@ -0,0 +1,4 @@ +(de sumDigits (N Base) + (or + (=0 N) + (+ (% N Base) (sumDigits (/ N Base) Base)) ) ) diff --git a/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-2.l b/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-2.l new file mode 100644 index 0000000000..c9f4945906 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PicoLisp/sum-digits-of-an-integer-2.l @@ -0,0 +1,11 @@ +: (sumDigits 1 10) +-> 1 + +: (sumDigits 1234 10) +-> 10 + +: (sumDigits (hex "fe") 16) +-> 29 + +: (sumDigits (hex "f0e") 16) +-> 29 diff --git a/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer.py b/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer.py new file mode 100644 index 0000000000..8144ba49aa --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer.py @@ -0,0 +1,32 @@ +def toBaseX(num, base): + output = [] + index = 0 + while num: + num, rem = divmod(num, base) + output.append(str(rem)) + return output + +def sumDigits( *args ): + if len(args) == 1: + number = str(args[0]) + else: + num = args[0] + base = args[1] + if base < 2: + print "Base must be between 2 and 36" + exit(1) + if num < base or num == base: + number = str(num) + else: + number = toBaseX(num,base) + + sumVal = 0 + for x in number: + sumVal += int(x) + return sumVal + +print sumDigits(1) +print sumDigits(12345) +print sumDigits(123045) +print sumDigits(0xfe, 16) +print sumDigits(0xf0e, 16) diff --git a/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-1.rexx b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-1.rexx new file mode 100644 index 0000000000..17d3b922b7 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-1.rexx @@ -0,0 +1,23 @@ +/* REXX ************************************************************** +* 04.12.2012 Walter Pachl +**********************************************************************/ +digits='0123456789ABCDEF' +Do i=1 To length(digits) + d=substr(digits,i,1) + value.d=i-1 + End +Call test '1' +Call test '1234' +Call test 'FE' +Call test 'F0E' +Exit +test: + Parse Arg number + res=right(number,4) + dsum=0 + Do While number<>'' + Parse Var number d +1 number + dsum=dsum+value.d + End + Say res '->' right(dsum,2) + Return diff --git a/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx new file mode 100644 index 0000000000..a169637fdd --- /dev/null +++ b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-2.rexx @@ -0,0 +1,12 @@ +/*REXX pgm sums the digits of natural numbers in any base up to base 36.*/ +parse arg nums; if nums='' then nums='1 1234 fe f0e +F0E -666.00' + do j=1 for words(nums); _=word(nums,j) + say right(sumDigs(_),9) ' is the sum of the digits for the number + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SUMDIGS subroutine──────────────────*/ +sumDigs: procedure; arg x; @='123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +s=0; do i=1 for length(x) + s=s+index(@,substr(x,i,1)) + end /*i*/ +return s diff --git a/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer.rb b/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer.rb new file mode 100644 index 0000000000..c59c162b57 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Ruby/sum-digits-of-an-integer.rb @@ -0,0 +1,14 @@ +>> def sumDigits(num, base = 10) +>> num.to_s(base).split(//).inject(0) {|z, x| z + x.to_i(base)} +>> end +=> nil +>> sumDigits(1) +=> 1 +>> sumDigits(12345) +=> 15 +>> sumDigits(123045) +=> 15 +>> sumDigits(0xfe, 16) +=> 29 +>> sumDigits(0xf0e, 16) +=> 29 diff --git a/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run b/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run new file mode 100644 index 0000000000..72f7135215 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Run-BASIC/sum-digits-of-an-integer.run @@ -0,0 +1,10 @@ +input "Gimme a number:";n + +print "Sum of digits :";n;" is ";sum(n) +end +function sum(n) +n$ = str$(n) +for i = 1 to len(n$) + sum = sum + val(mid$(n$,i,1)) +next i +end function diff --git a/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-1.scala b/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-1.scala new file mode 100644 index 0000000000..f39032f769 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-1.scala @@ -0,0 +1,2 @@ +def sumDigits(x:BigInt, base:Int=10):BigInt=sumDigits(x.toString(base), base) +def sumDigits(x:String, base:Int):BigInt = x map(_.asDigit) sum diff --git a/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-2.scala b/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-2.scala new file mode 100644 index 0000000000..c525a8463c --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Scala/sum-digits-of-an-integer-2.scala @@ -0,0 +1,19 @@ +sumDigits(0) // => 0 +sumDigits(0, 2) // => 0 +sumDigits(0, 16) // => 0 +sumDigits("00", 2) // => 0 +sumDigits("00", 10) // => 0 +sumDigits("00", 16) // => 0 +sumDigits(1234) // => 10 +sumDigits(0xfe) // => 11 +sumDigits(0xfe, 16) // => 29 +sumDigits(0xf0e, 16) // => 29 +sumDigits(077) // => 9 +sumDigits(077, 8) // => 14 +sumDigits("077", 8) // => 14 +sumDigits("077", 10) // => 14 +sumDigits("077", 16) // => 14 +sumDigits("0xf0e", 36) // => 62 +sumDigits("000999ABCXYZ", 36) // => 162 +sumDigits(BigInt("12345678901234567890")) // => 90 +sumDigits("12345678901234567890", 10) // => 90 diff --git a/Task/Sum-digits-of-an-integer/Seed7/sum-digits-of-an-integer.seed7 b/Task/Sum-digits-of-an-integer/Seed7/sum-digits-of-an-integer.seed7 new file mode 100644 index 0000000000..f500878bce --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Seed7/sum-digits-of-an-integer.seed7 @@ -0,0 +1,22 @@ +$ include "seed7_05.s7i"; + +const func integer: sumDigits (in var integer: num, in integer: base) is func + result + var integer: sum is 0; + begin + while num > 0 do + sum +:= num rem base; + num := num div base; + end while; + end func; + +const proc: main is func + begin + writeln(sumDigits(1, 10)); + writeln(sumDigits(12345, 10)); + writeln(sumDigits(123045, 10)); + writeln(sumDigits(123045, 50)); + writeln(sumDigits(16#fe, 10)); + writeln(sumDigits(16#fe, 16)); + writeln(sumDigits(16#f0e, 16)); + end func; diff --git a/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-1.tcl b/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-1.tcl new file mode 100644 index 0000000000..a3a28dc07f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-1.tcl @@ -0,0 +1,15 @@ +proc sumDigits {num {base 10}} { + set total 0 + foreach d [split $num ""] { + if {[string is alpha $d]} { + set d [expr {[scan [string tolower $d] %c] - 87}] + } elseif {![string is digit $d]} { + error "bad digit: $d" + } + if {$d >= $base} { + error "bad digit: $d" + } + incr total $d + } + return $total +} diff --git a/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-2.tcl b/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-2.tcl new file mode 100644 index 0000000000..7cc7502341 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Tcl/sum-digits-of-an-integer-2.tcl @@ -0,0 +1,6 @@ +puts [sumDigits 1] +puts [sumDigits 12345] +puts [sumDigits 123045] +puts [sumDigits fe 16] +puts [sumDigits f0e 16] +puts [sumDigits 000999ABCXYZ 36] diff --git a/Task/Sum-digits-of-an-integer/XPL0/sum-digits-of-an-integer.xpl0 b/Task/Sum-digits-of-an-integer/XPL0/sum-digits-of-an-integer.xpl0 new file mode 100644 index 0000000000..40a56e6694 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/XPL0/sum-digits-of-an-integer.xpl0 @@ -0,0 +1,18 @@ +code ChOut=8, CrLf=9, IntOut=11; + +func SumDigits(N, Base); +int N, Base, Sum; +[Sum:= 0; +repeat N:= N/Base; + Sum:= Sum + rem(0); +until N=0; +return Sum; +]; + +[IntOut(0, SumDigits(1, 10)); ChOut(0, ^ ); + IntOut(0, SumDigits(12345, 10)); ChOut(0, ^ ); + IntOut(0, SumDigits(123045, 10)); ChOut(0, ^ ); + IntOut(0, SumDigits($FE, 10)); ChOut(0, ^ ); + IntOut(0, SumDigits($FE, 16)); ChOut(0, ^ ); + IntOut(0, SumDigits($F0E, 16)); CrLf(0); +] diff --git a/Task/Sum-of-a-series/0DESCRIPTION b/Task/Sum-of-a-series/0DESCRIPTION new file mode 100644 index 0000000000..c888e53f4d --- /dev/null +++ b/Task/Sum-of-a-series/0DESCRIPTION @@ -0,0 +1,13 @@ +Compute the ''n''-th term of a [[wp:Series (mathematics)|series]], i.e. the sum of the ''n'' first terms of the corresponding [[wp:sequence|sequence]]. Informally, it is also called the ''sum of the series'', thus the title of this task. + +For this task, use: + +S_n = \sum_{k=1}^n \frac{1}{k^2} + +and compute S_{1000}. + +This approximates the [[wp:Riemann zeta function|zeta function]] for s=2, whose exact value + +\zeta(2) = {\pi^2\over 6} + +is the solution of the [[wp:Basel problem|Basel problem]]. diff --git a/Task/Sum-of-a-series/1META.yaml b/Task/Sum-of-a-series/1META.yaml new file mode 100644 index 0000000000..8644b2ad9b --- /dev/null +++ b/Task/Sum-of-a-series/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Arithmetic operations diff --git a/Task/Sum-of-a-series/ACL2/sum-of-a-series.acl2 b/Task/Sum-of-a-series/ACL2/sum-of-a-series.acl2 new file mode 100644 index 0000000000..6a66173a29 --- /dev/null +++ b/Task/Sum-of-a-series/ACL2/sum-of-a-series.acl2 @@ -0,0 +1,5 @@ +(defun sum-x^-2 (max-x) + (if (zp max-x) + 0 + (+ (/ (* max-x max-x)) + (sum-x^-2 (1- max-x))))) diff --git a/Task/Sum-of-a-series/ALGOL-68/sum-of-a-series.alg b/Task/Sum-of-a-series/ALGOL-68/sum-of-a-series.alg new file mode 100644 index 0000000000..7c9c86d2c9 --- /dev/null +++ b/Task/Sum-of-a-series/ALGOL-68/sum-of-a-series.alg @@ -0,0 +1,15 @@ +MODE RANGE = STRUCT(INT lwb, upb); + +PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:( + LONG REAL sum := LENG 0.0; + FOR i FROM lwb OF range TO upb OF range DO + sum := sum + f(i) + OD; + sum +); + +test:( + RANGE range = (1,100); + PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2; + print(("Sum of f(x) from", lwb OF range, " to ",upb OF range," is ", SHORTEN sum(f,range),".", new line)) +) diff --git a/Task/Sum-of-a-series/AWK/sum-of-a-series.awk b/Task/Sum-of-a-series/AWK/sum-of-a-series.awk new file mode 100644 index 0000000000..5fc52ad2e0 --- /dev/null +++ b/Task/Sum-of-a-series/AWK/sum-of-a-series.awk @@ -0,0 +1,2 @@ +$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}' +1.64393 diff --git a/Task/Sum-of-a-series/ActionScript/sum-of-a-series.as b/Task/Sum-of-a-series/ActionScript/sum-of-a-series.as new file mode 100644 index 0000000000..940852ef3b --- /dev/null +++ b/Task/Sum-of-a-series/ActionScript/sum-of-a-series.as @@ -0,0 +1,8 @@ +function partialSum(n:uint):Number +{ + var sum:Number = 0; + for(var i:uint = 1; i <= n; i++) + sum += 1/(i*i); + return sum; +} +trace(partialSum(1000)); diff --git a/Task/Sum-of-a-series/Ada/sum-of-a-series.ada b/Task/Sum-of-a-series/Ada/sum-of-a-series.ada new file mode 100644 index 0000000000..82edb2fb56 --- /dev/null +++ b/Task/Sum-of-a-series/Ada/sum-of-a-series.ada @@ -0,0 +1,20 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Sum_Series is + function F(X : Long_Float) return Long_Float is + begin + return 1.0 / X**2; + end F; + package Lf_Io is new Ada.Text_Io.Float_Io(Long_Float); + use Lf_Io; + Sum : Long_Float := 0.0; + subtype Param_Range is Integer range 1..1000; +begin + for I in Param_Range loop + Sum := Sum + F(Long_Float(I)); + end loop; + Put("Sum of F(x) from" & Integer'Image(Param_Range'First) & + " to" & Integer'Image(Param_Range'Last) & " is "); + Put(Item => Sum, Aft => 10, Exp => 0); + New_Line; +end Sum_Series; diff --git a/Task/Sum-of-a-series/AutoHotkey/sum-of-a-series.ahk b/Task/Sum-of-a-series/AutoHotkey/sum-of-a-series.ahk new file mode 100644 index 0000000000..42be9847ec --- /dev/null +++ b/Task/Sum-of-a-series/AutoHotkey/sum-of-a-series.ahk @@ -0,0 +1,4 @@ +SetFormat, FloatFast, 0.15 +While A_Index <= 1000 + sum += 1/A_Index**2 +MsgBox,% sum ;1.643934566681554 diff --git a/Task/Sum-of-a-series/BASIC/sum-of-a-series.basic b/Task/Sum-of-a-series/BASIC/sum-of-a-series.basic new file mode 100644 index 0000000000..8135be28c9 --- /dev/null +++ b/Task/Sum-of-a-series/BASIC/sum-of-a-series.basic @@ -0,0 +1,12 @@ +function s(x%) + s = 1 / x ^ 2 +end function + +function sum(low%, high%) + ret = 0 + for i = low to high + ret = ret + s(i) + next i + sum = ret +end function +print sum(1, 1000) diff --git a/Task/Sum-of-a-series/BBC-BASIC/sum-of-a-series.bbc b/Task/Sum-of-a-series/BBC-BASIC/sum-of-a-series.bbc new file mode 100644 index 0000000000..08e7c93fa5 --- /dev/null +++ b/Task/Sum-of-a-series/BBC-BASIC/sum-of-a-series.bbc @@ -0,0 +1,4 @@ + FOR i% = 1 TO 1000 + sum += 1/i%^2 + NEXT + PRINT sum diff --git a/Task/Sum-of-a-series/Brat/sum-of-a-series.brat b/Task/Sum-of-a-series/Brat/sum-of-a-series.brat new file mode 100644 index 0000000000..e89edb8d9a --- /dev/null +++ b/Task/Sum-of-a-series/Brat/sum-of-a-series.brat @@ -0,0 +1 @@ +p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816 diff --git a/Task/Sum-of-a-series/C++/sum-of-a-series.cpp b/Task/Sum-of-a-series/C++/sum-of-a-series.cpp new file mode 100644 index 0000000000..ac0beed0c1 --- /dev/null +++ b/Task/Sum-of-a-series/C++/sum-of-a-series.cpp @@ -0,0 +1,23 @@ +#include + +double f(double x); + +int main() +{ + unsigned int start = 1; + unsigned int end = 1000; + double sum = 0; + + for( unsigned int x = start; x <= end; ++x ) + { + sum += f(x); + } + std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl; + return 0; +} + + +double f(double x) +{ + return ( 1.0 / ( x * x ) ); +} diff --git a/Task/Sum-of-a-series/C/sum-of-a-series.c b/Task/Sum-of-a-series/C/sum-of-a-series.c new file mode 100644 index 0000000000..388389958c --- /dev/null +++ b/Task/Sum-of-a-series/C/sum-of-a-series.c @@ -0,0 +1,19 @@ +#include + +double Invsqr(double n) +{ + return 1 / (n*n); +} + +int main (int argc, char *argv[]) +{ + int i, start = 1, end = 1000; + double sum = 0.0; + + for( i = start; i <= end; i++) + sum += Invsqr((double)i); + + printf("%16.14f\n", sum); + + return 0; +} diff --git a/Task/Sum-of-a-series/CLIPS/sum-of-a-series.clips b/Task/Sum-of-a-series/CLIPS/sum-of-a-series.clips new file mode 100644 index 0000000000..5e73c91433 --- /dev/null +++ b/Task/Sum-of-a-series/CLIPS/sum-of-a-series.clips @@ -0,0 +1,9 @@ +(deffunction S (?x) (/ 1 (* ?x ?x))) +(deffunction partial-sum-S + (?start ?stop) + (bind ?sum 0) + (loop-for-count (?i ?start ?stop) do + (bind ?sum (+ ?sum (S ?i))) + ) + (return ?sum) +) diff --git a/Task/Sum-of-a-series/Clojure/sum-of-a-series.clj b/Task/Sum-of-a-series/Clojure/sum-of-a-series.clj new file mode 100644 index 0000000000..0b4647d1b1 --- /dev/null +++ b/Task/Sum-of-a-series/Clojure/sum-of-a-series.clj @@ -0,0 +1 @@ +(reduce + (map #(/ 1.0 % %) (range 1 1001))) diff --git a/Task/Sum-of-a-series/CoffeeScript/sum-of-a-series.coffeescript b/Task/Sum-of-a-series/CoffeeScript/sum-of-a-series.coffeescript new file mode 100644 index 0000000000..d07251f638 --- /dev/null +++ b/Task/Sum-of-a-series/CoffeeScript/sum-of-a-series.coffeescript @@ -0,0 +1 @@ +console.log [1..1000].reduce((acc, x) -> acc + (1.0 / (x*x))) diff --git a/Task/Sum-of-a-series/Common-Lisp/sum-of-a-series.lisp b/Task/Sum-of-a-series/Common-Lisp/sum-of-a-series.lisp new file mode 100644 index 0000000000..951fbdaf71 --- /dev/null +++ b/Task/Sum-of-a-series/Common-Lisp/sum-of-a-series.lisp @@ -0,0 +1 @@ +(loop for x from 1 to 1000 summing (expt x -2)) diff --git a/Task/Sum-of-a-series/D/sum-of-a-series-1.d b/Task/Sum-of-a-series/D/sum-of-a-series-1.d new file mode 100644 index 0000000000..3adf4247ba --- /dev/null +++ b/Task/Sum-of-a-series/D/sum-of-a-series-1.d @@ -0,0 +1,12 @@ +import std.stdio, std.traits; + +ReturnType!TF series(TF)(TF func, int end, int start=1) pure nothrow { + typeof(return) sum = 0; + foreach (i; start .. end + 1) + sum += func(i); + return sum; +} + +void main() { + writeln("Sum: ", series((int n) => 1.0L / (n ^^ 2), 1_000)); +} diff --git a/Task/Sum-of-a-series/D/sum-of-a-series-2.d b/Task/Sum-of-a-series/D/sum-of-a-series-2.d new file mode 100644 index 0000000000..ce4cdea080 --- /dev/null +++ b/Task/Sum-of-a-series/D/sum-of-a-series-2.d @@ -0,0 +1,9 @@ +import std.stdio, std.algorithm, std.range; + +auto series(alias F)(in int end, in int start=1) /*pure*/ { + return iota(start, end + 1).map!F().reduce!q{a + b}(); +} + +void main() { + writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000)); +} diff --git a/Task/Sum-of-a-series/DWScript/sum-of-a-series.dwscript b/Task/Sum-of-a-series/DWScript/sum-of-a-series.dwscript new file mode 100644 index 0000000000..12b02b9971 --- /dev/null +++ b/Task/Sum-of-a-series/DWScript/sum-of-a-series.dwscript @@ -0,0 +1,5 @@ +var s : Float; +for var i := 1 to 1000 do + s += 1 / Sqr(i); + +PrintLn(s); diff --git a/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi b/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi new file mode 100644 index 0000000000..cef8620898 --- /dev/null +++ b/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi @@ -0,0 +1,46 @@ +unit Form_SumOfASeries_Unit; + +interface + +uses + Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, + Dialogs, StdCtrls; + +type + TFormSumOfASeries = class(TForm) + M_Log: TMemo; + B_Calc: TButton; + procedure B_CalcClick(Sender: TObject); + private + { Private-Deklarationen } + public + { Public-Deklarationen } + end; + +var + FormSumOfASeries: TFormSumOfASeries; + +implementation + +{$R *.dfm} + +function Sum_Of_A_Series(_from,_to:int64):extended; +begin + result:=0; + while _from<=_to do + begin + result:=result+1.0/(_from*_from); + inc(_from); + end; +end; + +procedure TFormSumOfASeries.B_CalcClick(Sender: TObject); +begin + try + M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1,trunc(sqrt($7FFFFFFFFFFFFFFF-1))))); + except + M_Log.Lines.Add('Error'); + end; +end; + +end. diff --git a/Task/Sum-of-a-series/E/sum-of-a-series.e b/Task/Sum-of-a-series/E/sum-of-a-series.e new file mode 100644 index 0000000000..07dde81781 --- /dev/null +++ b/Task/Sum-of-a-series/E/sum-of-a-series.e @@ -0,0 +1,2 @@ +pragma.enable("accumulator") +accum 0 for x in 1..1000 { _ + 1 / x ** 2 } diff --git a/Task/Sum-of-a-series/Erlang/sum-of-a-series.erl b/Task/Sum-of-a-series/Erlang/sum-of-a-series.erl new file mode 100644 index 0000000000..9216416fee --- /dev/null +++ b/Task/Sum-of-a-series/Erlang/sum-of-a-series.erl @@ -0,0 +1 @@ +lists:sum([1/math:pow(X,2) || X <- lists:seq(1,1000)]). diff --git a/Task/Sum-of-a-series/Euphoria/sum-of-a-series.euphoria b/Task/Sum-of-a-series/Euphoria/sum-of-a-series.euphoria new file mode 100644 index 0000000000..449c89a744 --- /dev/null +++ b/Task/Sum-of-a-series/Euphoria/sum-of-a-series.euphoria @@ -0,0 +1,13 @@ +function s( atom x ) + return 1 / power( x, 2 ) +end function + +function sum( atom low, atom high ) + atom ret = 0.0 + for i = low to high do + ret = ret + s( i ) + end for + return ret +end function + +printf( 1, "%.15f\n", sum( 1, 1000 ) ) diff --git a/Task/Sum-of-a-series/Factor/sum-of-a-series.factor b/Task/Sum-of-a-series/Factor/sum-of-a-series.factor new file mode 100644 index 0000000000..ae32a881dd --- /dev/null +++ b/Task/Sum-of-a-series/Factor/sum-of-a-series.factor @@ -0,0 +1 @@ +1000 [1,b] [ >float sq recip ] map-sum diff --git a/Task/Sum-of-a-series/Fantom/sum-of-a-series.fantom b/Task/Sum-of-a-series/Fantom/sum-of-a-series.fantom new file mode 100644 index 0000000000..309378f9d9 --- /dev/null +++ b/Task/Sum-of-a-series/Fantom/sum-of-a-series.fantom @@ -0,0 +1,2 @@ +fansh> (1..1000).toList.reduce(0.0f) |Obj a, Int v -> Obj| { (Float)a + (1.0f/(v*v)) } +1.6439345666815615 diff --git a/Task/Sum-of-a-series/Forth/sum-of-a-series.fth b/Task/Sum-of-a-series/Forth/sum-of-a-series.fth new file mode 100644 index 0000000000..bc6cee1ed9 --- /dev/null +++ b/Task/Sum-of-a-series/Forth/sum-of-a-series.fth @@ -0,0 +1,9 @@ +: sum ( fn start count -- fsum ) + 0e + bounds do + i s>d d>f dup execute f+ + loop drop ; + +:noname ( x -- 1/x^2 ) fdup f* 1/f ; ( xt ) +1 1000 sum f. \ 1.64393456668156 +pi pi f* 6e f/ f. \ 1.64493406684823 diff --git a/Task/Sum-of-a-series/Fortran/sum-of-a-series.f b/Task/Sum-of-a-series/Fortran/sum-of-a-series.f new file mode 100644 index 0000000000..5ce510dcad --- /dev/null +++ b/Task/Sum-of-a-series/Fortran/sum-of-a-series.f @@ -0,0 +1,4 @@ +real, dimension(1000) :: a = (/ (1.0/(i*i), i=1, 1000) /) +real :: result + +result = sum(a); diff --git a/Task/Sum-of-a-series/GAP/sum-of-a-series.gap b/Task/Sum-of-a-series/GAP/sum-of-a-series.gap new file mode 100644 index 0000000000..00a70a71b6 --- /dev/null +++ b/Task/Sum-of-a-series/GAP/sum-of-a-series.gap @@ -0,0 +1,32 @@ +# We will compute the sum exactly + +# Computing an approximation of a rationnal (giving a string) +# Value is truncated toward zero +Approx := function(x, d) + local neg, a, b, n, m, s; + if x < 0 then + x := -x; + neg := true; + else + neg := false; + fi; + a := NumeratorRat(x); + b := DenominatorRat(x); + n := QuoInt(a, b); + a := RemInt(a, b); + m := 10^d; + s := ""; + if neg then + Append(s, "-"); + fi; + Append(s, String(n)); + n := Size(s) + 1; + Append(s, String(m + QuoInt(a*m, b))); + s[n] := '.'; + return s; +end; + +a := Sum([1 .. 1000], n -> 1/n^2);; +Approx(a, 10); +"1.6439345666" +# and pi^2/6 is 1.6449340668, truncated to ten digits diff --git a/Task/Sum-of-a-series/Go/sum-of-a-series.go b/Task/Sum-of-a-series/Go/sum-of-a-series.go new file mode 100644 index 0000000000..a3a8a37b42 --- /dev/null +++ b/Task/Sum-of-a-series/Go/sum-of-a-series.go @@ -0,0 +1,12 @@ +package main + +import ("fmt"; "math") + +func main() { + fmt.Println("known: ", math.Pi*math.Pi/6) + sum := 0. + for i := 1e3; i > 0; i-- { + sum += 1 / (i * i) + } + fmt.Println("computed:", sum) +} diff --git a/Task/Sum-of-a-series/Groovy/sum-of-a-series.groovy b/Task/Sum-of-a-series/Groovy/sum-of-a-series.groovy new file mode 100644 index 0000000000..873b6329cb --- /dev/null +++ b/Task/Sum-of-a-series/Groovy/sum-of-a-series.groovy @@ -0,0 +1 @@ +println ((1000..1).collect { x -> 1/(x*x) }.sum()) diff --git a/Task/Sum-of-a-series/Haskell/sum-of-a-series-1.hs b/Task/Sum-of-a-series/Haskell/sum-of-a-series-1.hs new file mode 100644 index 0000000000..90331ef773 --- /dev/null +++ b/Task/Sum-of-a-series/Haskell/sum-of-a-series-1.hs @@ -0,0 +1 @@ +sum [1 / x ^ 2 | x <- [1..1000]] diff --git a/Task/Sum-of-a-series/Haskell/sum-of-a-series-2.hs b/Task/Sum-of-a-series/Haskell/sum-of-a-series-2.hs new file mode 100644 index 0000000000..a279d8d51a --- /dev/null +++ b/Task/Sum-of-a-series/Haskell/sum-of-a-series-2.hs @@ -0,0 +1 @@ +sum $ map (\x -> 1 / x ^ 2) [1..1000] diff --git a/Task/Sum-of-a-series/Haskell/sum-of-a-series-3.hs b/Task/Sum-of-a-series/Haskell/sum-of-a-series-3.hs new file mode 100644 index 0000000000..a8939cb0fd --- /dev/null +++ b/Task/Sum-of-a-series/Haskell/sum-of-a-series-3.hs @@ -0,0 +1 @@ +(sum . map (1/) . map (^2)) [1..1000] diff --git a/Task/Sum-of-a-series/HicEst/sum-of-a-series-1.hicest b/Task/Sum-of-a-series/HicEst/sum-of-a-series-1.hicest new file mode 100644 index 0000000000..70610803e9 --- /dev/null +++ b/Task/Sum-of-a-series/HicEst/sum-of-a-series-1.hicest @@ -0,0 +1,3 @@ +REAL :: a(1000) + a = 1 / $^2 + WRITE(ClipBoard, Format='F17.15') SUM(a) diff --git a/Task/Sum-of-a-series/HicEst/sum-of-a-series-2.hicest b/Task/Sum-of-a-series/HicEst/sum-of-a-series-2.hicest new file mode 100644 index 0000000000..f61ceaa387 --- /dev/null +++ b/Task/Sum-of-a-series/HicEst/sum-of-a-series-2.hicest @@ -0,0 +1 @@ +1.643934566681561 diff --git a/Task/Sum-of-a-series/IDL/sum-of-a-series.idl b/Task/Sum-of-a-series/IDL/sum-of-a-series.idl new file mode 100644 index 0000000000..2019d11278 --- /dev/null +++ b/Task/Sum-of-a-series/IDL/sum-of-a-series.idl @@ -0,0 +1 @@ +print,total( 1/(1+findgen(1000))^2) diff --git a/Task/Sum-of-a-series/Icon/sum-of-a-series-1.icon b/Task/Sum-of-a-series/Icon/sum-of-a-series-1.icon new file mode 100644 index 0000000000..b3ba6fb514 --- /dev/null +++ b/Task/Sum-of-a-series/Icon/sum-of-a-series-1.icon @@ -0,0 +1,6 @@ +procedure main() + local i, sum + sum := 0 & i := 0 + every sum +:= 1.0/((| i +:= 1 ) ^ 2) \1000 + write(sum) +end diff --git a/Task/Sum-of-a-series/Icon/sum-of-a-series-2.icon b/Task/Sum-of-a-series/Icon/sum-of-a-series-2.icon new file mode 100644 index 0000000000..e660e4b228 --- /dev/null +++ b/Task/Sum-of-a-series/Icon/sum-of-a-series-2.icon @@ -0,0 +1,4 @@ +procedure main() + every (sum := 0) +:= 1.0/((1 to 1000)^2) + write(sum) +end diff --git a/Task/Sum-of-a-series/Icon/sum-of-a-series-3.icon b/Task/Sum-of-a-series/Icon/sum-of-a-series-3.icon new file mode 100644 index 0000000000..c9e4c3a6cb --- /dev/null +++ b/Task/Sum-of-a-series/Icon/sum-of-a-series-3.icon @@ -0,0 +1,3 @@ + x := y := 0 # := is right associative so, y is assigned 0, then x + 1 < x < 99 # comparison operators are left associative so, 1 < x returns x (if it is greater than 1), then x < 99 returns 99 if the comparison succeeds + (sum := 0) # returns a reference to sum which can in turn be used with augmented assignment +:= diff --git a/Task/Sum-of-a-series/J/sum-of-a-series.j b/Task/Sum-of-a-series/J/sum-of-a-series.j new file mode 100644 index 0000000000..84b2e63aef --- /dev/null +++ b/Task/Sum-of-a-series/J/sum-of-a-series.j @@ -0,0 +1,9 @@ + NB. sum of reciprocals of squares of first thousand positive integers + +/ % *: >: i. 1000 +1.64393 + + (*:o.1)%6 NB. pi squared over six, for comparison +1.64493 + + 1r6p2 NB. As a constant (J has a rich constant notation) +1.64493 diff --git a/Task/Sum-of-a-series/Java/sum-of-a-series.java b/Task/Sum-of-a-series/Java/sum-of-a-series.java new file mode 100644 index 0000000000..d0c8bfeaf9 --- /dev/null +++ b/Task/Sum-of-a-series/Java/sum-of-a-series.java @@ -0,0 +1,15 @@ +public class Sum{ + public static double f(double x){ + return 1/(x*x); + } + + public static void main(String[] args){ + double start = 1; + double end = 1000; + double sum = 0; + + for(double x = start;x <= end;x++) sum += f(x); + + System.out.println("Sum of f(x) from " + start + " to " + end +" is " + sum); + } +} diff --git a/Task/Sum-of-a-series/JavaScript/sum-of-a-series.js b/Task/Sum-of-a-series/JavaScript/sum-of-a-series.js new file mode 100644 index 0000000000..8dfd86c427 --- /dev/null +++ b/Task/Sum-of-a-series/JavaScript/sum-of-a-series.js @@ -0,0 +1,7 @@ +function sum(a,b,fn) { + var s = 0; + for ( ; a <= b; a++) s += fn(a); + return s; +} + + sum(1,1000, function(x) { return 1/(x*x) } ) // 1.64393456668156 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 new file mode 100644 index 0000000000..d1c2d880d7 --- /dev/null +++ b/Task/Sum-of-a-series/Julia/sum-of-a-series.julia @@ -0,0 +1,5 @@ +julia> f(x) = sum(1/[1:x].^2) +# method added to generic function f + +julia> f(1000) +1.6439345666815615 diff --git a/Task/Sum-of-a-series/K/sum-of-a-series.k b/Task/Sum-of-a-series/K/sum-of-a-series.k new file mode 100644 index 0000000000..7f39922b58 --- /dev/null +++ b/Task/Sum-of-a-series/K/sum-of-a-series.k @@ -0,0 +1,3 @@ + ssr: +/1%_sqr + ssr 1+!1000 +1.643935 diff --git a/Task/Sum-of-a-series/Lang5/sum-of-a-series.lang5 b/Task/Sum-of-a-series/Lang5/sum-of-a-series.lang5 new file mode 100644 index 0000000000..e4e6a6df21 --- /dev/null +++ b/Task/Sum-of-a-series/Lang5/sum-of-a-series.lang5 @@ -0,0 +1 @@ +1000 iota 1 + 1 swap / 2 ** '+ reduce . diff --git a/Task/Sum-of-a-series/Liberty-BASIC/sum-of-a-series.liberty b/Task/Sum-of-a-series/Liberty-BASIC/sum-of-a-series.liberty new file mode 100644 index 0000000000..d33ba73844 --- /dev/null +++ b/Task/Sum-of-a-series/Liberty-BASIC/sum-of-a-series.liberty @@ -0,0 +1,7 @@ +for i =1 to 1000 + sum =sum +1 /( i^2) +next i + +print sum + +end diff --git a/Task/Sum-of-a-series/Logo/sum-of-a-series.logo b/Task/Sum-of-a-series/Logo/sum-of-a-series.logo new file mode 100644 index 0000000000..31a757cd27 --- /dev/null +++ b/Task/Sum-of-a-series/Logo/sum-of-a-series.logo @@ -0,0 +1,11 @@ +to series :fn :a :b + localmake "sigma 0 + for [i :a :b] [make "sigma :sigma + invoke :fn :i] + output :sigma +end +to zeta.2 :x + output 1 / (:x * :x) +end +print series "zeta.2 1 1000 +make "pi (radarctan 0 1) * 2 +print :pi * :pi / 6 diff --git a/Task/Sum-of-a-series/Lua/sum-of-a-series.lua b/Task/Sum-of-a-series/Lua/sum-of-a-series.lua new file mode 100644 index 0000000000..dede56cb86 --- /dev/null +++ b/Task/Sum-of-a-series/Lua/sum-of-a-series.lua @@ -0,0 +1,3 @@ +sum = 0 +for i = 1, 1000 do sum = sum + 1/i^2 end +print(sum) diff --git a/Task/Sum-of-a-series/Lucid/sum-of-a-series.lucid b/Task/Sum-of-a-series/Lucid/sum-of-a-series.lucid new file mode 100644 index 0000000000..ed34efe3b7 --- /dev/null +++ b/Task/Sum-of-a-series/Lucid/sum-of-a-series.lucid @@ -0,0 +1,5 @@ +series = ssum asa n >= 1000 + where + num = 1 fby num + 1; + ssum = ssum + 1/(num * num) + end; diff --git a/Task/Sum-of-a-series/MATLAB/sum-of-a-series.m b/Task/Sum-of-a-series/MATLAB/sum-of-a-series.m new file mode 100644 index 0000000000..ddbd963d01 --- /dev/null +++ b/Task/Sum-of-a-series/MATLAB/sum-of-a-series.m @@ -0,0 +1 @@ + sum([1:1000].^(-2)) diff --git a/Task/Sum-of-a-series/MAXScript/sum-of-a-series.maxscript b/Task/Sum-of-a-series/MAXScript/sum-of-a-series.maxscript new file mode 100644 index 0000000000..343fbf4024 --- /dev/null +++ b/Task/Sum-of-a-series/MAXScript/sum-of-a-series.maxscript @@ -0,0 +1,6 @@ +total = 0 +for i in 1 to 1000 do +( + total += 1.0 / pow i 2 +) +print total diff --git a/Task/Sum-of-a-series/MMIX/sum-of-a-series.mmix b/Task/Sum-of-a-series/MMIX/sum-of-a-series.mmix new file mode 100644 index 0000000000..271181074a --- /dev/null +++ b/Task/Sum-of-a-series/MMIX/sum-of-a-series.mmix @@ -0,0 +1,106 @@ +x IS $1 % flt calculations +y IS $2 % id +z IS $3 % z = sum series +t IS $4 % temp var + + LOC Data_Segment + GREG @ +BUF OCTA 0,0,0 % print buffer + + LOC #1000 + GREG @ + +// print floating point number in scientific format: 0.xxx...ey.. +// most of this routine is adopted from: +// http://www.pspu.ru/personal/eremin/emmi/rom_subs/printreal.html +// float number in z + GREG @ +NaN BYTE "NaN..",0 +NewLn BYTE #a,0 +1H LDA x,NaN + TRAP 0,Fputs,StdOut + GO $127,$127,0 + +prtFlt FUN x,z,z % test if z == NaN + BNZ x,1B + CMP $73,z,0 % if necessary remember it is neg + BNN $73,4F +Sign BYTE '-' + LDA $255,Sign + TRAP 0,Fputs,StdOut + ANDNH z,#8000 % make number pos +// normalizing float number +4H SETH $74,#4024 % initialize mulfactor = 10.0 + SETH $73,#0023 + INCMH $73,#86f2 + INCML $73,#6fc1 % + FLOT $73,$73 % $73 = float 10^16 + SET $75,16 % set # decimals to 16 +8H FCMP $72,z,$73 % while z >= 10^16 do + BN $72,9F % + FDIV z,z,$74 % z = z / 10.0 + ADD $75,$75,1 % incr exponent + JMP 8B % wend +9H FDIV $73,$73,$74 % 10^16 / 10.0 +5H FCMP $72,z,$73 % while z < 10^15 do + BNN $72,6F + FMUL z,z,$74 % z = z * 10.0 + SUB $75,$75,1 % exp = exp - 1 + JMP 5B +NulPnt BYTE '0','.',#00 +6H LDA $255,NulPnt % print '0.' to StdOut + TRAP 0,Fputs,StdOut + FIX z,0,z % convert float z to integer +// print mantissa +0H GREG #3030303030303030 + STO 0B,BUF + STO 0B,BUF+8 % store print mask in buffer + LDA $255,BUF+16 % points after LSD + % repeat +2H SUB $255,$255,1 % move pointer down + DIV z,z,10 % (q,r) = divmod z 10 + GET t,rR % get remainder + INCL t,'0' % convert to ascii digit + STBU t,$255,0 % store digit in buffer + BNZ z,2B % until q == 0 + TRAP 0,Fputs,StdOut % print mantissa +Exp BYTE 'e',#00 + LDA $255,Exp % print 'exponent' indicator + TRAP 0,Fputs,StdOut +// print exponent +0H GREG #3030300000000000 + STO 0B,BUF + LDA $255,BUF+2 % store print mask in buffer + CMP $73,$75,0 % if exp neg then place - in buffer + BNN $73,2F +ExpSign BYTE '-' + LDA $255,ExpSign + TRAP 0,Fputs,StdOut + NEG $75,$75 % make exp positive +2H LDA $255,BUF+3 % points after LSD + % repeat +3H SUB $255,$255,1 % move pointer down + DIV $75,$75,10 % (q,r) = divmod exp 10 + GET t,rR + INCL t,'0' + STBU t,$255,0 % store exp. digit in buffer + BNZ $75,3B % until q == 0 + TRAP 0,Fputs,StdOut % print exponent + LDA $255,NewLn + TRAP 0,Fputs,StdOut % do a NL + GO $127,$127,0 % return + +i IS $5 ;iu IS $6 +Main SET iu,1000 + SETH y,#3ff0 y = 1.0 + SETH z,#0000 z = 0.0 + SET i,1 for (i=1;i<=1000; i++ ) { +1H FLOT x,i x = int i + FMUL x,x,x x = x^2 + FDIV x,y,x x = 1 / x + FADD z,z,x s = s + x + ADD i,i,1 + CMP t,i,iu + PBNP t,1B } z = sum + GO $127,prtFlt print sum --> StdOut + TRAP 0,Halt,0 diff --git a/Task/Sum-of-a-series/MUMPS/sum-of-a-series.mumps b/Task/Sum-of-a-series/MUMPS/sum-of-a-series.mumps new file mode 100644 index 0000000000..91de420a4b --- /dev/null +++ b/Task/Sum-of-a-series/MUMPS/sum-of-a-series.mumps @@ -0,0 +1,5 @@ +SOAS(N) + NEW SUM,I SET SUM=0 + FOR I=1:1:N DO + .SET SUM=SUM+(1/((I*I))) + QUIT SUM diff --git a/Task/Sum-of-a-series/Mathematica/sum-of-a-series-1.math b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-1.math new file mode 100644 index 0000000000..a3166bc8b0 --- /dev/null +++ b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-1.math @@ -0,0 +1 @@ +Sum[1/x^2, {x, 1, 1000}] diff --git a/Task/Sum-of-a-series/Mathematica/sum-of-a-series-2.math b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-2.math new file mode 100644 index 0000000000..dd8282b3c3 --- /dev/null +++ b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-2.math @@ -0,0 +1 @@ +N[Sum[1/x^2, {x, 1, 1000}]] diff --git a/Task/Sum-of-a-series/Mathematica/sum-of-a-series-3.math b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-3.math new file mode 100644 index 0000000000..ef6df6ff6e --- /dev/null +++ b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-3.math @@ -0,0 +1 @@ +NSum[1/x^2, {x, 1, 1000}] diff --git a/Task/Sum-of-a-series/Mathematica/sum-of-a-series-4.math b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-4.math new file mode 100644 index 0000000000..ba15049940 --- /dev/null +++ b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-4.math @@ -0,0 +1 @@ +Sum[1./x^2, {x, 1, 1000}] diff --git a/Task/Sum-of-a-series/Mathematica/sum-of-a-series-5.math b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-5.math new file mode 100644 index 0000000000..62dc9b60d8 --- /dev/null +++ b/Task/Sum-of-a-series/Mathematica/sum-of-a-series-5.math @@ -0,0 +1,4 @@ +Total[Table[1/x^2, {x, 1, 1000}]] +Total[Table[1./x^2, {x, 1, 1000}]] +Plus@@Table[1/x^2, {x, 1, 1000}] +Plus@@Table[1./x^2, {x, 1, 1000}] diff --git a/Task/Sum-of-a-series/Maxima/sum-of-a-series.maxima b/Task/Sum-of-a-series/Maxima/sum-of-a-series.maxima new file mode 100644 index 0000000000..e161e12169 --- /dev/null +++ b/Task/Sum-of-a-series/Maxima/sum-of-a-series.maxima @@ -0,0 +1,7 @@ +(%i45) sum(1/x^2, x, 1, 1000); + 835459384831496894781878542648[806 digits]396236858699094240207812766449 +(%o45) ------------------------------------------------------------------------ + 508207201043258126178352922730[806 digits]886537101453118476390400000000 + +(%i46) sum(1/x^2, x, 1, 1000),numer; +(%o46) 1.643934566681561 diff --git a/Task/Sum-of-a-series/Modula-3/sum-of-a-series.mod3 b/Task/Sum-of-a-series/Modula-3/sum-of-a-series.mod3 new file mode 100644 index 0000000000..31ec3b2394 --- /dev/null +++ b/Task/Sum-of-a-series/Modula-3/sum-of-a-series.mod3 @@ -0,0 +1,19 @@ +MODULE Sum EXPORTS Main; + +IMPORT IO, Fmt, Math; + +VAR sum: LONGREAL := 0.0D0; + +PROCEDURE F(x: LONGREAL): LONGREAL = + BEGIN + RETURN 1.0D0 / Math.pow(x, 2.0D0); + END F; + +BEGIN + FOR i := 1 TO 1000 DO + sum := sum + F(FLOAT(i, LONGREAL)); + END; + IO.Put("Sum of F(x) from 1 to 1000 is "); + IO.Put(Fmt.LongReal(sum)); + IO.Put("\n"); +END Sum. diff --git a/Task/Sum-of-a-series/Nial/sum-of-a-series.nial b/Task/Sum-of-a-series/Nial/sum-of-a-series.nial new file mode 100644 index 0000000000..a5418ad0f5 --- /dev/null +++ b/Task/Sum-of-a-series/Nial/sum-of-a-series.nial @@ -0,0 +1,2 @@ +|sum (1 / power (count 1000) 2) +=1.64393 diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ocaml new file mode 100644 index 0000000000..0aa43ad648 --- /dev/null +++ b/Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ocaml @@ -0,0 +1,6 @@ +let sum a b fn = + let result = ref 0. in + for i = a to b do + result := !result +. fn i + done; + !result diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ocaml new file mode 100644 index 0000000000..12efaf202e --- /dev/null +++ b/Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ocaml @@ -0,0 +1,7 @@ +let sum a b fn = + let rec aux i r = + if i > b then r + else aux (succ i) (r +. fn i) + in + aux a 0. +;; diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ocaml new file mode 100644 index 0000000000..073ed70b6c --- /dev/null +++ b/Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ocaml @@ -0,0 +1,2 @@ +let rec sum n = if n < 1 then 0.0 else sum (n-1) +. 1.0 /. float (n*n) +in sum 1000 diff --git a/Task/Sum-of-a-series/Objeck/sum-of-a-series.objeck b/Task/Sum-of-a-series/Objeck/sum-of-a-series.objeck new file mode 100644 index 0000000000..b80e1127dc --- /dev/null +++ b/Task/Sum-of-a-series/Objeck/sum-of-a-series.objeck @@ -0,0 +1,24 @@ +bundle Default { + class SumSeries { + function : Main(args : String[]) ~ Nil { + DoSumSeries(); + } + + function : native : DoSumSeries() ~ Nil { + start := 1; + end := 1000; + + sum := 0.0; + + for(x : Float := start; x <= end; x += 1;) { + sum += f(x); + }; + + IO.Console->GetInstance()->Print("Sum of f(x) from ")->Print(start)->Print(" to ")->Print(end)->Print(" is ")->PrintLine(sum); + } + + function : native : f(x : Float) ~ Float { + return 1.0 / (x * x); + } + } +} diff --git a/Task/Sum-of-a-series/Octave/sum-of-a-series.octave b/Task/Sum-of-a-series/Octave/sum-of-a-series.octave new file mode 100644 index 0000000000..ac393d6bff --- /dev/null +++ b/Task/Sum-of-a-series/Octave/sum-of-a-series.octave @@ -0,0 +1 @@ +sum(1 ./ [1:1000] .^ 2) diff --git a/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-1.openedge b/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-1.openedge new file mode 100644 index 0000000000..a041119cc2 --- /dev/null +++ b/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-1.openedge @@ -0,0 +1,8 @@ +def var dcResult as decimal no-undo. +def var n as int no-undo. + +do n = 1 to 1000 : + dcResult = dcResult + 1 / (n * n) . +end. + +display dcResult . diff --git a/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-2.openedge b/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-2.openedge new file mode 100644 index 0000000000..187d7e5599 --- /dev/null +++ b/Task/Sum-of-a-series/OpenEdge-Progress/sum-of-a-series-2.openedge @@ -0,0 +1,7 @@ +def var n as int no-undo. + +repeat n = 1 to 1000 : + accumulate 1 / (n * n) (total). +end. + +display ( accum total 1 / (n * n) ) . diff --git a/Task/Sum-of-a-series/Oz/sum-of-a-series-1.oz b/Task/Sum-of-a-series/Oz/sum-of-a-series-1.oz new file mode 100644 index 0000000000..81cd5a0d19 --- /dev/null +++ b/Task/Sum-of-a-series/Oz/sum-of-a-series-1.oz @@ -0,0 +1,11 @@ +declare + fun {SumSeries S N} + {FoldL {Map {List.number 1 N 1} S} + Number.'+' 0.} + end + + fun {S X} + 1. / {Int.toFloat X*X} + end +in + {Show {SumSeries S 1000}} diff --git a/Task/Sum-of-a-series/Oz/sum-of-a-series-2.oz b/Task/Sum-of-a-series/Oz/sum-of-a-series-2.oz new file mode 100644 index 0000000000..0617f5064f --- /dev/null +++ b/Task/Sum-of-a-series/Oz/sum-of-a-series-2.oz @@ -0,0 +1,8 @@ + fun {SumSeries S N} + R = {NewCell 0.} + in + for I in 1..N do + R := @R + {S I} + end + @R + end diff --git a/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-1.pari b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-1.pari new file mode 100644 index 0000000000..1d8e95213c --- /dev/null +++ b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-1.pari @@ -0,0 +1 @@ +sum(n=1,1000,1/n^2) diff --git a/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-2.pari b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-2.pari new file mode 100644 index 0000000000..583f182b0a --- /dev/null +++ b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-2.pari @@ -0,0 +1 @@ +sum(n=1,1000,1./n^2) diff --git a/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-3.pari b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-3.pari new file mode 100644 index 0000000000..cd2fb1b66c --- /dev/null +++ b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-3.pari @@ -0,0 +1 @@ +zeta(2)-intnum(x=1000.5,[1],1/x^2) diff --git a/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-4.pari b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-4.pari new file mode 100644 index 0000000000..3ce0827673 --- /dev/null +++ b/Task/Sum-of-a-series/PARI-GP/sum-of-a-series-4.pari @@ -0,0 +1 @@ +zeta(2)-1/1000.5 diff --git a/Task/Sum-of-a-series/PHP/sum-of-a-series.php b/Task/Sum-of-a-series/PHP/sum-of-a-series.php new file mode 100644 index 0000000000..c2eab4d8d7 --- /dev/null +++ b/Task/Sum-of-a-series/PHP/sum-of-a-series.php @@ -0,0 +1,21 @@ + + */ + +/** + * @param int $n + * @param int $k + * @return float|int + */ +function sum_of_a_series($n,$k) +{ + $sum_of_a_series = 0; + for($i=$k;$i<=$n;$i++) + { + $sum_of_a_series += (1/($i*$i)); + } + return $sum_of_a_series; +} + +echo sum_of_a_series(1000,1); diff --git a/Task/Sum-of-a-series/PL-I/sum-of-a-series.pli b/Task/Sum-of-a-series/PL-I/sum-of-a-series.pli new file mode 100644 index 0000000000..b5ac732768 --- /dev/null +++ b/Task/Sum-of-a-series/PL-I/sum-of-a-series.pli @@ -0,0 +1,8 @@ +/* sum the first 1000 terms of the series 1/n**2. */ +s = 0; + +do i = 1000 to 1 by -1; + s = s + 1/float(i**2); +end; + +put skip list (s); diff --git a/Task/Sum-of-a-series/Pascal/sum-of-a-series.pascal b/Task/Sum-of-a-series/Pascal/sum-of-a-series.pascal new file mode 100644 index 0000000000..8cf410556e --- /dev/null +++ b/Task/Sum-of-a-series/Pascal/sum-of-a-series.pascal @@ -0,0 +1,18 @@ +Program SumSeries; + +var + S: double; + i: integer; + +function f(number: integer): double; +begin + f := 1/(number*number); +end; + +begin + S := 0; + for i := 1 to 1000 do + S := S + f(i); + writeln('The sum of 1/x^2 from 1 to 1000 is: ', S:10:8); + writeln('Whereas pi^2/6 is: ', pi*pi/6:10:8); +end. diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-1.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-1.pl6 new file mode 100644 index 0000000000..df4039c0bf --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-1.pl6 @@ -0,0 +1 @@ +[+] map &f, 1 .. $n diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-2.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-2.pl6 new file mode 100644 index 0000000000..a9004c9ef8 --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-2.pl6 @@ -0,0 +1 @@ +say [+] map { 1 / $^n**2 }, 1 .. 1000; diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-3.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-3.pl6 new file mode 100644 index 0000000000..5f5ad0f359 --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-3.pl6 @@ -0,0 +1 @@ +say [+] 1 «/« (1..1000) »**» 2; diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-4.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-4.pl6 new file mode 100644 index 0000000000..c12a543962 --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-4.pl6 @@ -0,0 +1 @@ +say [+] 1 X/ (1..1000 X** 2); diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 new file mode 100644 index 0000000000..97d6d0204a --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-5.pl6 @@ -0,0 +1,2 @@ +constant @x = [\+] 0, { 1 / ++(state $n) ** 2 } ... *; +say @x[1000]; # prints 1.64393456668156 diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 new file mode 100644 index 0000000000..238a7b8dce --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-6.pl6 @@ -0,0 +1,2 @@ +constant ζish = [\+] map -> \𝑖 { 1 / 𝑖**2 }, 1..*; +say ζish[1000]; diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 new file mode 100644 index 0000000000..291b0c27f9 --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 @@ -0,0 +1,2 @@ +sub ζ($s) { [\+] map -> \n { 1 / n**$s }, 1..* } +say ζ(2)[1000]; diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 new file mode 100644 index 0000000000..8ecf94d87f --- /dev/null +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-8.pl6 @@ -0,0 +1 @@ +say [+] (1 / $_**2 for 1..1000); diff --git a/Task/Sum-of-a-series/Perl/sum-of-a-series-1.pl b/Task/Sum-of-a-series/Perl/sum-of-a-series-1.pl new file mode 100644 index 0000000000..f5956640ab --- /dev/null +++ b/Task/Sum-of-a-series/Perl/sum-of-a-series-1.pl @@ -0,0 +1,3 @@ +my $sum = 0; +$sum += 1 / $_ ** 2 foreach 1..1000; +print "$sum\n"; diff --git a/Task/Sum-of-a-series/Perl/sum-of-a-series-2.pl b/Task/Sum-of-a-series/Perl/sum-of-a-series-2.pl new file mode 100644 index 0000000000..f109176b0f --- /dev/null +++ b/Task/Sum-of-a-series/Perl/sum-of-a-series-2.pl @@ -0,0 +1,3 @@ +use List::Util qw(reduce); +$sum = reduce { $a + 1 / $b ** 2 } 0, 1..1000; +print "$sum\n"; diff --git a/Task/Sum-of-a-series/Perl/sum-of-a-series-3.pl b/Task/Sum-of-a-series/Perl/sum-of-a-series-3.pl new file mode 100644 index 0000000000..cef6b2663d --- /dev/null +++ b/Task/Sum-of-a-series/Perl/sum-of-a-series-3.pl @@ -0,0 +1,3 @@ +my $S = do { my ($sum, $k); sub { $sum += 1/++$k**2 } }; +my @S = map &$S, 1 .. 1000; +print $S[-1]; diff --git a/Task/Sum-of-a-series/PicoLisp/sum-of-a-series.l b/Task/Sum-of-a-series/PicoLisp/sum-of-a-series.l new file mode 100644 index 0000000000..f6e2904f00 --- /dev/null +++ b/Task/Sum-of-a-series/PicoLisp/sum-of-a-series.l @@ -0,0 +1,6 @@ +(scl 9) # Calculate with 9 digits precision + +(let S 0 + (for I 1000 + (inc 'S (*/ 1.0 (* I I))) ) + (prinl (round S 6)) ) # Round result to 6 digits diff --git a/Task/Sum-of-a-series/Pike/sum-of-a-series.pike b/Task/Sum-of-a-series/Pike/sum-of-a-series.pike new file mode 100644 index 0000000000..12816e4298 --- /dev/null +++ b/Task/Sum-of-a-series/Pike/sum-of-a-series.pike @@ -0,0 +1,3 @@ +array(int) x = enumerate(1000,1,1); +`+(@(1.0/pow(x[*],2)[*])); +Result: 1.64393 diff --git a/Task/Sum-of-a-series/Pop11/sum-of-a-series.pop11 b/Task/Sum-of-a-series/Pop11/sum-of-a-series.pop11 new file mode 100644 index 0000000000..5d0c339cf8 --- /dev/null +++ b/Task/Sum-of-a-series/Pop11/sum-of-a-series.pop11 @@ -0,0 +1,6 @@ +lvars s = 0, j; +for j from 1 to 1000 do + s + 1.0/(j*j) -> s; +endfor; + +s => diff --git a/Task/Sum-of-a-series/PostScript/sum-of-a-series-1.ps b/Task/Sum-of-a-series/PostScript/sum-of-a-series-1.ps new file mode 100644 index 0000000000..22f0e23bda --- /dev/null +++ b/Task/Sum-of-a-series/PostScript/sum-of-a-series-1.ps @@ -0,0 +1,12 @@ +/aproxriemann{ +/x exch def +/i 1 def +/sum 0 def +x{ +/sum sum i -2 exp add def +/i i 1 add def +}repeat +sum == +}def + +1000 aproxriemann diff --git a/Task/Sum-of-a-series/PostScript/sum-of-a-series-2.ps b/Task/Sum-of-a-series/PostScript/sum-of-a-series-2.ps new file mode 100644 index 0000000000..197caa2204 --- /dev/null +++ b/Task/Sum-of-a-series/PostScript/sum-of-a-series-2.ps @@ -0,0 +1 @@ +1.64393485 diff --git a/Task/Sum-of-a-series/PostScript/sum-of-a-series-3.ps b/Task/Sum-of-a-series/PostScript/sum-of-a-series-3.ps new file mode 100644 index 0000000000..e885b23bba --- /dev/null +++ b/Task/Sum-of-a-series/PostScript/sum-of-a-series-3.ps @@ -0,0 +1,5 @@ +% using map +[1 1000] 1 range {dup * 1 exch div} map 0 {+} fold + +% just using fold +[1 1000] 1 range 0 {dup * 1 exch div +} fold diff --git a/Task/Sum-of-a-series/PowerShell/sum-of-a-series.psh b/Task/Sum-of-a-series/PowerShell/sum-of-a-series.psh new file mode 100644 index 0000000000..9cef2a33d8 --- /dev/null +++ b/Task/Sum-of-a-series/PowerShell/sum-of-a-series.psh @@ -0,0 +1,4 @@ +$x = 1..1000 ` + | ForEach-Object { 1 / ($_ * $_) } ` + | Measure-Object -Sum +Write-Host Sum = $x.Sum diff --git a/Task/Sum-of-a-series/Prolog/sum-of-a-series.pro b/Task/Sum-of-a-series/Prolog/sum-of-a-series.pro new file mode 100644 index 0000000000..1afbecdbdf --- /dev/null +++ b/Task/Sum-of-a-series/Prolog/sum-of-a-series.pro @@ -0,0 +1,3 @@ +sum(S) :- + findall(L, (between(1,1000,N),L is 1/N^2), Ls), + sumlist(Ls, S). diff --git a/Task/Sum-of-a-series/PureBasic/sum-of-a-series.purebasic b/Task/Sum-of-a-series/PureBasic/sum-of-a-series.purebasic new file mode 100644 index 0000000000..e95d3d6e28 --- /dev/null +++ b/Task/Sum-of-a-series/PureBasic/sum-of-a-series.purebasic @@ -0,0 +1,7 @@ +Define i, sum.d + +For i=1 To 1000 + sum+1.0/(i*i) +Next i + +Debug sum diff --git a/Task/Sum-of-a-series/Python/sum-of-a-series.py b/Task/Sum-of-a-series/Python/sum-of-a-series.py new file mode 100644 index 0000000000..6f322f21c1 --- /dev/null +++ b/Task/Sum-of-a-series/Python/sum-of-a-series.py @@ -0,0 +1 @@ +print ( sum(1.0 / (x * x) for x in range(1, 1001)) ) diff --git a/Task/Sum-of-a-series/R/sum-of-a-series.r b/Task/Sum-of-a-series/R/sum-of-a-series.r new file mode 100644 index 0000000000..c2610de5e8 --- /dev/null +++ b/Task/Sum-of-a-series/R/sum-of-a-series.r @@ -0,0 +1 @@ +print( sum( 1/seq(1000)^2 ) ) diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx new file mode 100644 index 0000000000..732c3cef0e --- /dev/null +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx @@ -0,0 +1,13 @@ +/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ +parse arg N D . /*maybe get num of terms, digits.*/ +if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ +if D=='' then D=60 /* " " " " " */ +numeric digits D /*use D digits (9 is the default)*/ +w = length(N) /*use max width for nice output.*/ +sum = 0 /*initialize the sum to zero. */ + do j=1 for N /*compute for N terms. */ + sum = sum + 1 / j**2 /*add another term to the sum. */ + end /*j*/ + +say 'The sum of' right(N,w) "terms is:" sum + /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx new file mode 100644 index 0000000000..f92a7e2355 --- /dev/null +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx @@ -0,0 +1,15 @@ +/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ +parse arg N D . /*maybe get num of terms, digits.*/ +if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ +if D=='' then D=60 /* " " " " " */ +numeric digits D /*use D digits (9 is default).*/ +w = length(N) /*use max width for nice output.*/ +sum=0 /*initialize the sum to zero. */ + do j=1 for N /*compute for N terms. */ + sum = sum + 1 / j**2 /*add another term to the sum. */ + if left(j,1)\==1 then iterate /*does J start with a one ? */ + if right(j,1)\==0 then iterate /* " " end " " zero ? */ + if substr(j,2)\= 0 then iterate /* " " " " all zeroes ? */ + say 'The sum of' right(j,w) "terms is:" sum /*display it.*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx new file mode 100644 index 0000000000..080c1f205f --- /dev/null +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx @@ -0,0 +1,23 @@ +/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ +parse arg N D . /*optional num of terms, digits.*/ +if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ +if D=='' then D=60 /* " " " " " */ +@sig = 'The significant sum of' /*literal used in SAY statement.*/ +numeric digits D /*use D digits (9 is default).*/ +w = length(N) /*use max width for nice output.*/ +sum = 0 /*initialize the SUM to zero. */ +old = 1 /*the SUM to compared to the NEW.*/ +p = 0 /*significant precision so far. */ + do j=1 for N /*compute for n terms. */ + sum = sum + 1 / j**2 /*add another term to the sum. */ + c = compare(sum,old) /*see how we're doing with prec. */ + if c>p then do /*Got another significant digit? */ + say @sig right(j,w) "terms is:" left(sum,c) + p = c /*the new significant precision. */ + end + old = sum /*use "old" sum for next compare.*/ + end /*j*/ +say +say 'The sum of' right(N,w) "terms is:" /*display sum's preamble.*/ +say sum /*display the sum on its own line*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-a-series/RLaB/sum-of-a-series.rlab b/Task/Sum-of-a-series/RLaB/sum-of-a-series.rlab new file mode 100644 index 0000000000..142daf43fe --- /dev/null +++ b/Task/Sum-of-a-series/RLaB/sum-of-a-series.rlab @@ -0,0 +1,2 @@ +>> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6 +-0.000999500167 diff --git a/Task/Sum-of-a-series/Racket/sum-of-a-series.rkt b/Task/Sum-of-a-series/Racket/sum-of-a-series.rkt new file mode 100644 index 0000000000..1793a9809c --- /dev/null +++ b/Task/Sum-of-a-series/Racket/sum-of-a-series.rkt @@ -0,0 +1,6 @@ +#lang typed/racket + +(: S : Natural -> Real) +(define (S n) + (for/sum: : Real ([k : Natural (in-range 1 (+ n 1))]) + (/ 1.0 (* k k)))) diff --git a/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb b/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb new file mode 100644 index 0000000000..ece9cda47c --- /dev/null +++ b/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb @@ -0,0 +1 @@ +puts (1..1000).inject(0) {|sum, x| sum + 1.0 / x ** 2} diff --git a/Task/Sum-of-a-series/Run-BASIC/sum-of-a-series.run b/Task/Sum-of-a-series/Run-BASIC/sum-of-a-series.run new file mode 100644 index 0000000000..deb618dfe3 --- /dev/null +++ b/Task/Sum-of-a-series/Run-BASIC/sum-of-a-series.run @@ -0,0 +1,4 @@ +for i =1 to 1000 + sum = sum + 1 /( i^2) +next i +print sum diff --git a/Task/Sum-of-a-series/SAS/sum-of-a-series.sas b/Task/Sum-of-a-series/SAS/sum-of-a-series.sas new file mode 100644 index 0000000000..83034b7c56 --- /dev/null +++ b/Task/Sum-of-a-series/SAS/sum-of-a-series.sas @@ -0,0 +1,8 @@ +data _null_; +s=0; +do n=1 to 1000; + s+1/n**2; /* s+x is synonym of s=s+x */ +end; +e=s-constant('pi')**2/6; +put s e; +run; diff --git a/Task/Sum-of-a-series/SQL/sum-of-a-series.sql b/Task/Sum-of-a-series/SQL/sum-of-a-series.sql new file mode 100644 index 0000000000..d3d14d0087 --- /dev/null +++ b/Task/Sum-of-a-series/SQL/sum-of-a-series.sql @@ -0,0 +1,17 @@ +create table sequence ( + n real +) + +insert into sequence values (0) +insert into sequence values (1) +insert into sequence select 2+n from sequence +insert into sequence select 4+n from sequence +insert into sequence select 8+n from sequence +insert into sequence select 16+n from sequence +insert into sequence select 32+n from sequence +insert into sequence select 64+n from sequence +insert into sequence select 128+n from sequence +insert into sequence select 256+n from sequence +insert into sequence select 512+n from sequence + +select sum(1/n) from sequence where n>=1 and n<=1000 diff --git a/Task/Sum-of-a-series/Scala/sum-of-a-series.scala b/Task/Sum-of-a-series/Scala/sum-of-a-series.scala new file mode 100644 index 0000000000..66be57878f --- /dev/null +++ b/Task/Sum-of-a-series/Scala/sum-of-a-series.scala @@ -0,0 +1,2 @@ +scala> 1 to 1000 map (x => 1.0 / (x * x)) sum +res30: Double = 1.6439345666815615 diff --git a/Task/Sum-of-a-series/Scheme/sum-of-a-series-1.ss b/Task/Sum-of-a-series/Scheme/sum-of-a-series-1.ss new file mode 100644 index 0000000000..a81e8b8017 --- /dev/null +++ b/Task/Sum-of-a-series/Scheme/sum-of-a-series-1.ss @@ -0,0 +1,7 @@ +(define (sum a b fn) + (do ((i a (+ i 1)) + (result 0 (+ result (fn i)))) + ((> i b) result))) + +(sum 1 1000 (lambda (x) (/ 1 (* x x)))) ; fraction +(exact->inexact (sum 1 1000 (lambda (x) (/ 1 (* x x))))) ; decimal diff --git a/Task/Sum-of-a-series/Scheme/sum-of-a-series-2.ss b/Task/Sum-of-a-series/Scheme/sum-of-a-series-2.ss new file mode 100644 index 0000000000..d4a24f1e26 --- /dev/null +++ b/Task/Sum-of-a-series/Scheme/sum-of-a-series-2.ss @@ -0,0 +1,9 @@ +(define (invsq f to) + (let loop ((f f) (s 0)) + (if (> f to) + s + (loop (+ 1 f) (+ s (/ 1 f f)))))) + +;; whether you get a rational or a float depends on implementation +(invsq 1 1000) ; 835459384831...766449/50820...90400000000 +(exact->inexact (invsq 1 1000)) ; 1.64393456668156 diff --git a/Task/Sum-of-a-series/Seed7/sum-of-a-series.seed7 b/Task/Sum-of-a-series/Seed7/sum-of-a-series.seed7 new file mode 100644 index 0000000000..acf1e3e52b --- /dev/null +++ b/Task/Sum-of-a-series/Seed7/sum-of-a-series.seed7 @@ -0,0 +1,16 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const func float: invsqr (in float: n) is + return 1.0 / n**2; + +const proc: main is func + local + var integer: i is 0; + var float: sum is 0.0; + begin + for i range 1 to 1000 do + sum +:= invsqr(flt(i)); + end for; + writeln(sum digits 6 lpad 8); + end func; diff --git a/Task/Sum-of-a-series/Slate/sum-of-a-series.slate b/Task/Sum-of-a-series/Slate/sum-of-a-series.slate new file mode 100644 index 0000000000..3dbe7f7d04 --- /dev/null +++ b/Task/Sum-of-a-series/Slate/sum-of-a-series.slate @@ -0,0 +1 @@ +((1 to: 1000) reduce: [|:x :y | x + (y squared reciprocal as: Float)]). diff --git a/Task/Sum-of-a-series/Smalltalk/sum-of-a-series.st b/Task/Sum-of-a-series/Smalltalk/sum-of-a-series.st new file mode 100644 index 0000000000..e1aff0a219 --- /dev/null +++ b/Task/Sum-of-a-series/Smalltalk/sum-of-a-series.st @@ -0,0 +1,2 @@ +( (1 to: 1000) fold: [:sum :aNumber | + sum + (aNumber squared reciprocal) ] ) asFloat displayNl. diff --git a/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml b/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml new file mode 100644 index 0000000000..7ecf618b52 --- /dev/null +++ b/Task/Sum-of-a-series/Standard-ML/sum-of-a-series.ml @@ -0,0 +1,2 @@ +(* 1.64393456668 *) +List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0))) diff --git a/Task/Sum-of-a-series/TI-89-BASIC/sum-of-a-series.ti-89 b/Task/Sum-of-a-series/TI-89-BASIC/sum-of-a-series.ti-89 new file mode 100644 index 0000000000..8c0d63e12d --- /dev/null +++ b/Task/Sum-of-a-series/TI-89-BASIC/sum-of-a-series.ti-89 @@ -0,0 +1 @@ +∑(1/x^2,x,1,1000) diff --git a/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl b/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl new file mode 100644 index 0000000000..161690084c --- /dev/null +++ b/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl @@ -0,0 +1,12 @@ +package require Tcl 8.5 + +proc partial_sum {func - start - stop} { + for {set x $start; set sum 0} {$x <= $stop} {incr x} { + set sum [expr {$sum + [apply $func $x]}] + } + return $sum +} + +set S {x {expr {1.0 / $x**2}}} + +partial_sum $S from 1 to 1000 ;# => 1.6439345666815615 diff --git a/Task/Sum-of-a-series/Tcl/sum-of-a-series-2.tcl b/Task/Sum-of-a-series/Tcl/sum-of-a-series-2.tcl new file mode 100644 index 0000000000..2adcec0136 --- /dev/null +++ b/Task/Sum-of-a-series/Tcl/sum-of-a-series-2.tcl @@ -0,0 +1,8 @@ +package require Tcl 8.5 +package require struct::list + +proc sum_of {lambda nums} { + struct::list fold [struct::list map $nums [list apply $lambda]] 0 ::tcl::mathop::+ +} + +sum_of $S [range 1 1001] ;# ==> 1.6439345666815615 diff --git a/Task/Sum-of-a-series/Tcl/sum-of-a-series-3.tcl b/Task/Sum-of-a-series/Tcl/sum-of-a-series-3.tcl new file mode 100644 index 0000000000..1647f2f542 --- /dev/null +++ b/Task/Sum-of-a-series/Tcl/sum-of-a-series-3.tcl @@ -0,0 +1,16 @@ +# a range command akin to Python's +proc range args { + foreach {start stop step} [switch -exact -- [llength $args] { + 1 {concat 0 $args 1} + 2 {concat $args 1} + 3 {concat $args } + default {error {wrong # of args: should be "range ?start? stop ?step?"}} + }] break + if {$step == 0} {error "cannot create a range when step == 0"} + set range [list] + while {$step > 0 ? $start < $stop : $stop < $start} { + lappend range $start + incr start $step + } + return $range +} diff --git a/Task/Sum-of-a-series/UnixPipes/sum-of-a-series.unixpipes b/Task/Sum-of-a-series/UnixPipes/sum-of-a-series.unixpipes new file mode 100644 index 0000000000..3a4a9c9fae --- /dev/null +++ b/Task/Sum-of-a-series/UnixPipes/sum-of-a-series.unixpipes @@ -0,0 +1,18 @@ +term() { + b=$1;res=$2 + echo "scale=5;1/($res*$res)+$b" | bc +} + +sum() { + (read B; res=$1; + test -n "$B" && (term $B $res) || (term 0 $res)) +} + +fold() { + func=$1 + (while read a ; do + fold $func | $func $a + done) +} + +(echo 3; echo 1; echo 4) | fold sum diff --git a/Task/Sum-of-a-series/Ursala/sum-of-a-series.ursala b/Task/Sum-of-a-series/Ursala/sum-of-a-series.ursala new file mode 100644 index 0000000000..b829826cc5 --- /dev/null +++ b/Task/Sum-of-a-series/Ursala/sum-of-a-series.ursala @@ -0,0 +1,6 @@ +#import flo +#import nat + +#cast %e + +total = plus:-0 div/*1. sqr* float*t iota 1001 diff --git a/Task/Sum-of-a-series/Vala/sum-of-a-series.vala b/Task/Sum-of-a-series/Vala/sum-of-a-series.vala new file mode 100644 index 0000000000..94b1dee277 --- /dev/null +++ b/Task/Sum-of-a-series/Vala/sum-of-a-series.vala @@ -0,0 +1,9 @@ +public static void main(){ + int i, start = 1, end = 1000; + double sum = 0.0; + + for(i = start; i<= end; i++) + sum += (1 / (double)(i * i)); + + stdout.printf("%s\n", sum.to_string()); +} diff --git a/Task/Sum-of-a-series/XPL0/sum-of-a-series.xpl0 b/Task/Sum-of-a-series/XPL0/sum-of-a-series.xpl0 new file mode 100644 index 0000000000..7a49f4fe9a --- /dev/null +++ b/Task/Sum-of-a-series/XPL0/sum-of-a-series.xpl0 @@ -0,0 +1,6 @@ +code CrLf=9; code real RlOut=48; +int X; real S; +[S:= 0.0; +for X:= 1 to 1000 do S:= S + 1.0/float(X*X); +RlOut(0, S); CrLf(0); +] diff --git a/Task/Sum-of-a-series/Yorick/sum-of-a-series.yorick b/Task/Sum-of-a-series/Yorick/sum-of-a-series.yorick new file mode 100644 index 0000000000..6a4f427728 --- /dev/null +++ b/Task/Sum-of-a-series/Yorick/sum-of-a-series.yorick @@ -0,0 +1 @@ +(1./indgen(1:1000)^2)(sum) diff --git a/Task/Sum-of-squares/0DESCRIPTION b/Task/Sum-of-squares/0DESCRIPTION new file mode 100644 index 0000000000..81ec00542f --- /dev/null +++ b/Task/Sum-of-squares/0DESCRIPTION @@ -0,0 +1,3 @@ +Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of 0). + +See also [[Mean]]. diff --git a/Task/Sum-of-squares/1META.yaml b/Task/Sum-of-squares/1META.yaml new file mode 100644 index 0000000000..8644b2ad9b --- /dev/null +++ b/Task/Sum-of-squares/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Arithmetic operations diff --git a/Task/Sum-of-squares/ACL2/sum-of-squares.acl2 b/Task/Sum-of-squares/ACL2/sum-of-squares.acl2 new file mode 100644 index 0000000000..858e7466da --- /dev/null +++ b/Task/Sum-of-squares/ACL2/sum-of-squares.acl2 @@ -0,0 +1,5 @@ +(defun sum-of-squares (xs) + (if (endp xs) + 0 + (+ (* (first xs) (first xs)) + (sum-of-squares (rest xs))))) diff --git a/Task/Sum-of-squares/ALGOL-68/sum-of-squares-1.alg b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-1.alg new file mode 100644 index 0000000000..8d859961f1 --- /dev/null +++ b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-1.alg @@ -0,0 +1,10 @@ +PROC sum of squares = ([]REAL argv)REAL:( + REAL sum := 0; + FOR i FROM LWB argv TO UPB argv DO + sum +:= argv[i]**2 + OD; + sum +); +test:( + printf(($g(0)l$,sum of squares([]REAL(3, 1, 4, 1, 5, 9)))); +) diff --git a/Task/Sum-of-squares/ALGOL-68/sum-of-squares-2.alg b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-2.alg new file mode 100644 index 0000000000..f6391f6c19 --- /dev/null +++ b/Task/Sum-of-squares/ALGOL-68/sum-of-squares-2.alg @@ -0,0 +1,16 @@ +[]REAL data = (3, 1, 4, 1, 5, 9); + +PROC map = ( PROC(REAL)REAL func, []REAL argv)REAL: + ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out); + +test:( + REAL sum := 0; + printf(($xg(0)l$, map ( ((REAL argv)REAL: sum +:= argv ** 2), data) )); + + PRIO MAP = 5; # the same priority as the operators <, =<, >=, & > maybe... # + OP MAP = ( PROC(REAL)REAL func, []REAL argv)REAL: + ( REAL out:=0; FOR i FROM LWB argv TO UPB argv DO out:=func(argv[i]) OD; out); + + sum := 0; + printf(($g(0)l$, ((REAL argv)REAL: sum +:= argv ** 2) MAP data )) +) diff --git a/Task/Sum-of-squares/AWK/sum-of-squares.awk b/Task/Sum-of-squares/AWK/sum-of-squares.awk new file mode 100644 index 0000000000..0d681ab276 --- /dev/null +++ b/Task/Sum-of-squares/AWK/sum-of-squares.awk @@ -0,0 +1,5 @@ +$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}' +3 1 4 1 5 9 +133 + +0 diff --git a/Task/Sum-of-squares/ActionScript/sum-of-squares.as b/Task/Sum-of-squares/ActionScript/sum-of-squares.as new file mode 100644 index 0000000000..2c7be74fcb --- /dev/null +++ b/Task/Sum-of-squares/ActionScript/sum-of-squares.as @@ -0,0 +1,7 @@ +function sumOfSquares(vector:Vector.):Number +{ + var sum:Number = 0; + for(var i:uint = 0; i < vector.length; i++) + sum += vector[i]*vector[i]; + return sum; +} diff --git a/Task/Sum-of-squares/Ada/sum-of-squares.ada b/Task/Sum-of-squares/Ada/sum-of-squares.ada new file mode 100644 index 0000000000..d1ef88394d --- /dev/null +++ b/Task/Sum-of-squares/Ada/sum-of-squares.ada @@ -0,0 +1,18 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Sum_Of_Squares is + type Float_Array is array (Integer range <>) of Float; + + function Sum_Of_Squares (X : Float_Array) return Float is + Sum : Float := 0.0; + begin + for I in X'Range loop + Sum := Sum + X (I) ** 2; + end loop; + return Sum; + end Sum_Of_Squares; + +begin + Put_Line (Float'Image (Sum_Of_Squares ((1..0 => 1.0)))); -- Empty array + Put_Line (Float'Image (Sum_Of_Squares ((3.0, 1.0, 4.0, 1.0, 5.0, 9.0)))); +end Test_Sum_Of_Squares; diff --git a/Task/Sum-of-squares/Alore/sum-of-squares.alore b/Task/Sum-of-squares/Alore/sum-of-squares.alore new file mode 100644 index 0000000000..04220a05c9 --- /dev/null +++ b/Task/Sum-of-squares/Alore/sum-of-squares.alore @@ -0,0 +1,10 @@ +def sum_squares(a) + var sum = 0 + for i in a + sum = sum + i**2 + end + return sum +end + +WriteLn(sum_squares([3,1,4,1,5,9])) +end diff --git a/Task/Sum-of-squares/AutoHotkey/sum-of-squares.ahk b/Task/Sum-of-squares/AutoHotkey/sum-of-squares.ahk new file mode 100644 index 0000000000..c44f006b2f --- /dev/null +++ b/Task/Sum-of-squares/AutoHotkey/sum-of-squares.ahk @@ -0,0 +1,4 @@ +list = 3 1 4 1 5 9 +Loop, Parse, list, %A_Space% + sum += A_LoopField**2 +MsgBox,% sum diff --git a/Task/Sum-of-squares/BASIC/sum-of-squares.basic b/Task/Sum-of-squares/BASIC/sum-of-squares.basic new file mode 100644 index 0000000000..286e71c84e --- /dev/null +++ b/Task/Sum-of-squares/BASIC/sum-of-squares.basic @@ -0,0 +1,5 @@ +sum = 0 +FOR I = LBOUND(a) TO UBOUND(a) + sum = sum + a(I) ^ 2 +NEXT I +PRINT "The sum of squares is: " + sum diff --git a/Task/Sum-of-squares/BBC-BASIC/sum-of-squares.bbc b/Task/Sum-of-squares/BBC-BASIC/sum-of-squares.bbc new file mode 100644 index 0000000000..c61fa66d0e --- /dev/null +++ b/Task/Sum-of-squares/BBC-BASIC/sum-of-squares.bbc @@ -0,0 +1,4 @@ + DIM vector(5) + vector() = 1, 2, 3, 4, 5, 6 + + PRINT "Sum of squares = " ; MOD(vector()) ^ 2 diff --git a/Task/Sum-of-squares/Brat/sum-of-squares.brat b/Task/Sum-of-squares/Brat/sum-of-squares.brat new file mode 100644 index 0000000000..fce0478070 --- /dev/null +++ b/Task/Sum-of-squares/Brat/sum-of-squares.brat @@ -0,0 +1 @@ +p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385 diff --git a/Task/Sum-of-squares/C++/sum-of-squares-1.cpp b/Task/Sum-of-squares/C++/sum-of-squares-1.cpp new file mode 100644 index 0000000000..8e0d4cbfdc --- /dev/null +++ b/Task/Sum-of-squares/C++/sum-of-squares-1.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +double add_square(double prev_sum, double new_val) +{ + return prev_sum + new_val*new_val; +} + +double vec_add_squares(std::vector& v) +{ + return std::accumulate(v.begin(), v.end(), 0.0, add_square); +} + +int main() +{ + // first, show that for empty vectors we indeed get 0 + std::vector v; // empty + std::cout << vec_add_squares(v) << std::endl; + + // now, use some values + double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 }; + v.assign(data, data+7); + std::cout << vec_add_squares(v) << std::endl; + return 0; +} diff --git a/Task/Sum-of-squares/C++/sum-of-squares-2.cpp b/Task/Sum-of-squares/C++/sum-of-squares-2.cpp new file mode 100644 index 0000000000..a8009ab264 --- /dev/null +++ b/Task/Sum-of-squares/C++/sum-of-squares-2.cpp @@ -0,0 +1,10 @@ +#include +#include +#include "boost/lambda/lambda.hpp" + +double vec_add_squares(std::vector& v) +{ + using namespace boost::lambda; + + return std::accumulate(v.begin(), v.end(), 0.0, _1 + _2 * _2); +} diff --git a/Task/Sum-of-squares/C/sum-of-squares.c b/Task/Sum-of-squares/C/sum-of-squares.c new file mode 100644 index 0000000000..d94385b6a2 --- /dev/null +++ b/Task/Sum-of-squares/C/sum-of-squares.c @@ -0,0 +1,19 @@ +#include + +double squaredsum(double *l, int e) +{ + int i; double sum = 0.0; + for(i = 0 ; i < e ; i++) sum += l[i]*l[i]; + return sum; +} + +int main() +{ + double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0}; + + printf("%lf\n", squaredsum(list, 6)); + printf("%lf\n", squaredsum(list, 0)); + /* the same without using a real list as if it were 0-element long */ + printf("%lf\n", squaredsum(NULL, 0)); + return 0; +} diff --git a/Task/Sum-of-squares/Chef/sum-of-squares.chef b/Task/Sum-of-squares/Chef/sum-of-squares.chef new file mode 100644 index 0000000000..0c52aa1fa7 --- /dev/null +++ b/Task/Sum-of-squares/Chef/sum-of-squares.chef @@ -0,0 +1,21 @@ +Sum of squares. + +First input is length of vector, then rest of input is vector. + +Ingredients. +1 g eggs +0 g bacon + +Method. +Put bacon into the 1st mixing bowl. +Take eggs from refrigerator. +Square the eggs. +Take bacon from refrigerator. +Put bacon into 2nd mixing bowl. +Combine bacon into 2nd mixing bowl. +Fold bacon into 2nd mixing bowl. +Add the bacon into the 1st mixing bowl. +Ask the eggs until squared. +Pour contents of the 1st mixing bowl into the 1st baking dish. + +Serves 1. diff --git a/Task/Sum-of-squares/Clojure/sum-of-squares.clj b/Task/Sum-of-squares/Clojure/sum-of-squares.clj new file mode 100644 index 0000000000..d07b95ee14 --- /dev/null +++ b/Task/Sum-of-squares/Clojure/sum-of-squares.clj @@ -0,0 +1,2 @@ +(defn sum-of-squares [v] + (reduce #(+ %1 (* %2 %2)) 0 v)) diff --git a/Task/Sum-of-squares/Common-Lisp/sum-of-squares.lisp b/Task/Sum-of-squares/Common-Lisp/sum-of-squares.lisp new file mode 100644 index 0000000000..366e3f9d86 --- /dev/null +++ b/Task/Sum-of-squares/Common-Lisp/sum-of-squares.lisp @@ -0,0 +1,2 @@ +(defun sum-of-squares (vector) + (loop for x across vector sum (expt x 2))) diff --git a/Task/Sum-of-squares/D/sum-of-squares-1.d b/Task/Sum-of-squares/D/sum-of-squares-1.d new file mode 100644 index 0000000000..9acd560df2 --- /dev/null +++ b/Task/Sum-of-squares/D/sum-of-squares-1.d @@ -0,0 +1,13 @@ +import std.stdio: writeln; + +T sumSquares(T)(T[] a) { + T sum = 0; + foreach (e; a) + sum += e ^^ 2; + return sum; +} + +void main() { + auto items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0]; + writeln(sumSquares(items)); +} diff --git a/Task/Sum-of-squares/D/sum-of-squares-2.d b/Task/Sum-of-squares/D/sum-of-squares-2.d new file mode 100644 index 0000000000..d1648d34c0 --- /dev/null +++ b/Task/Sum-of-squares/D/sum-of-squares-2.d @@ -0,0 +1,11 @@ +import std.stdio, std.algorithm, std.traits, std.range; + +auto sumSquares(Range)(Range data) { + return reduce!q{a + b ^^ 2}(cast(ForeachType!Range)0, data); +} + +void main() { + auto items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0]; + writeln(sumSquares(items)); + writeln(sumSquares(iota(10))); +} diff --git a/Task/Sum-of-squares/Dart/sum-of-squares.dart b/Task/Sum-of-squares/Dart/sum-of-squares.dart new file mode 100644 index 0000000000..cb9b160d5b --- /dev/null +++ b/Task/Sum-of-squares/Dart/sum-of-squares.dart @@ -0,0 +1,11 @@ +sumOfSquares(list) { + var sum=0; + list.forEach((var n) { sum+=(n*n); }); + return sum; +} + +main() { + print(sumOfSquares([])); + print(sumOfSquares([1,2,3])); + print(sumOfSquares([10])); +} diff --git a/Task/Sum-of-squares/Delphi/sum-of-squares.delphi b/Task/Sum-of-squares/Delphi/sum-of-squares.delphi new file mode 100644 index 0000000000..d5868d853a --- /dev/null +++ b/Task/Sum-of-squares/Delphi/sum-of-squares.delphi @@ -0,0 +1,21 @@ +program SumOfSq; + +{$APPTYPE CONSOLE} + +uses Math; + +type + TDblArray = array of Double; + +var + A: TDblArray; + +begin + Writeln(SumOfSquares([]):6:2); // 0.00 + Writeln(SumOfSquares([1, 2, 3, 4]):6:2); // 30.00 + A:= nil; + Writeln(SumOfSquares(A):6:2); // 0.00 + A:= TDblArray.Create(1, 2, 3, 4); + Writeln(SumOfSquares(A):6:2); // 30.00 + Readln; +end. diff --git a/Task/Sum-of-squares/E/sum-of-squares.e b/Task/Sum-of-squares/E/sum-of-squares.e new file mode 100644 index 0000000000..79f5ca4770 --- /dev/null +++ b/Task/Sum-of-squares/E/sum-of-squares.e @@ -0,0 +1,7 @@ +def sumOfSquares(numbers) { + var sum := 0 + for x in numbers { + sum += x**2 + } + return sum +} diff --git a/Task/Sum-of-squares/Eiffel/sum-of-squares.e b/Task/Sum-of-squares/Eiffel/sum-of-squares.e new file mode 100644 index 0000000000..261100c3ee --- /dev/null +++ b/Task/Sum-of-squares/Eiffel/sum-of-squares.e @@ -0,0 +1,17 @@ +class SUMSQUARES +creation make +feature + make is + local + numbers: ARRAY[DOUBLE]; + sum : DOUBLE; + i : INTEGER; + do + numbers := <<1, 2, 3, 4, 5>>; + from i := numbers.lower until i > numbers.upper loop + sum := sum + numbers.item(i).pow(2); + i := i + 1; + end + io.put_string(sum.to_string_format(2) + "%N"); + end +end diff --git a/Task/Sum-of-squares/Erlang/sum-of-squares.erl b/Task/Sum-of-squares/Erlang/sum-of-squares.erl new file mode 100644 index 0000000000..30f70e2582 --- /dev/null +++ b/Task/Sum-of-squares/Erlang/sum-of-squares.erl @@ -0,0 +1 @@ +lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]). diff --git a/Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria b/Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria new file mode 100644 index 0000000000..14127228b3 --- /dev/null +++ b/Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria @@ -0,0 +1,8 @@ +function SumOfSquares(sequence v) + atom sum + sum = 0 + for i = 1 to length(v) do + sum += v[i]*v[i] + end for + return sum +end function diff --git a/Task/Sum-of-squares/FALSE/sum-of-squares.false b/Task/Sum-of-squares/FALSE/sum-of-squares.false new file mode 100644 index 0000000000..8ed11f05fc --- /dev/null +++ b/Task/Sum-of-squares/FALSE/sum-of-squares.false @@ -0,0 +1 @@ +0 3 1 4 1 5 9$*\ [$0=~][$*+\]#%. diff --git a/Task/Sum-of-squares/Factor/sum-of-squares.factor b/Task/Sum-of-squares/Factor/sum-of-squares.factor new file mode 100644 index 0000000000..4eeb56419d --- /dev/null +++ b/Task/Sum-of-squares/Factor/sum-of-squares.factor @@ -0,0 +1,5 @@ +USE: math sequences ; + +: sum-of-squares ( seq -- n ) [ sq ] map-sum ; + +{ 1.0 2.0 4.0 8.0 16.0 } sum-of-squares diff --git a/Task/Sum-of-squares/Fantom/sum-of-squares.fantom b/Task/Sum-of-squares/Fantom/sum-of-squares.fantom new file mode 100644 index 0000000000..1c858301bf --- /dev/null +++ b/Task/Sum-of-squares/Fantom/sum-of-squares.fantom @@ -0,0 +1,17 @@ +class SumSquares +{ + static Int sumSquares (Int[] numbers) + { + Int sum := 0 + numbers.each |n| { sum += n * n } + return sum + } + + public static Void main () + { + Int[] n := [,] + echo ("Sum of squares of $n = ${sumSquares(n)}") + n = [1,2,3,4,5] + echo ("Sum of squares of $n = ${sumSquares(n)}") + } +} diff --git a/Task/Sum-of-squares/Fish/sum-of-squares.fish b/Task/Sum-of-squares/Fish/sum-of-squares.fish new file mode 100644 index 0000000000..68247d1c95 --- /dev/null +++ b/Task/Sum-of-squares/Fish/sum-of-squares.fish @@ -0,0 +1,4 @@ +v +\0& +>l?!v:*&+& + >&n; diff --git a/Task/Sum-of-squares/Forth/sum-of-squares.fth b/Task/Sum-of-squares/Forth/sum-of-squares.fth new file mode 100644 index 0000000000..c772b73822 --- /dev/null +++ b/Task/Sum-of-squares/Forth/sum-of-squares.fth @@ -0,0 +1,9 @@ +: fsum**2 ( addr n -- f ) + 0e + dup 0= if 2drop exit then + floats bounds do + i f@ fdup f* f+ + 1 floats +loop ; + +create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, +test 6 fsum**2 f. \ 133. diff --git a/Task/Sum-of-squares/Fortran/sum-of-squares.f b/Task/Sum-of-squares/Fortran/sum-of-squares.f new file mode 100644 index 0000000000..a80d9d0b2f --- /dev/null +++ b/Task/Sum-of-squares/Fortran/sum-of-squares.f @@ -0,0 +1,9 @@ +real, dimension(1000) :: a = (/ (i, i=1, 1000) /) +real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array +real :: result, zresult + +result = sum(a*a) ! Multiply array by itself to get squares + +result = sum(a**2) ! Use exponentiation operator to get squares + +zresult = sum(p*p) ! P is zero-length; P*P is valid zero-length array expression; SUM(P*P) == 0.0 as expected diff --git a/Task/Sum-of-squares/GAP/sum-of-squares.gap b/Task/Sum-of-squares/GAP/sum-of-squares.gap new file mode 100644 index 0000000000..df2c779630 --- /dev/null +++ b/Task/Sum-of-squares/GAP/sum-of-squares.gap @@ -0,0 +1,9 @@ +# Just multiplying a vector by itself yields the sum of squares (it's an inner product) +# It's necessary to check for the empty vector though +SumSq := function(v) + if Size(v) = 0 then + return 0; + else + return v*v; + fi; +end; diff --git a/Task/Sum-of-squares/Go/sum-of-squares.go b/Task/Sum-of-squares/Go/sum-of-squares.go new file mode 100644 index 0000000000..2d79bcff0c --- /dev/null +++ b/Task/Sum-of-squares/Go/sum-of-squares.go @@ -0,0 +1,11 @@ +package main + +import "fmt" + +func main() { + var sum float32 + for _, x := range []float32{1,2,.5} { + sum += x*x + } + fmt.Println(sum) +} diff --git a/Task/Sum-of-squares/Golfscript/sum-of-squares.golfscript b/Task/Sum-of-squares/Golfscript/sum-of-squares.golfscript new file mode 100644 index 0000000000..be89893108 --- /dev/null +++ b/Task/Sum-of-squares/Golfscript/sum-of-squares.golfscript @@ -0,0 +1,3 @@ +{0\{.*+}%}:sqsum; +# usage example +[1 2 3]sqsum puts diff --git a/Task/Sum-of-squares/Groovy/sum-of-squares.groovy b/Task/Sum-of-squares/Groovy/sum-of-squares.groovy new file mode 100644 index 0000000000..b8a7861369 --- /dev/null +++ b/Task/Sum-of-squares/Groovy/sum-of-squares.groovy @@ -0,0 +1,10 @@ +def array = 1..3 + +// square via multiplication +def sumSq = array.collect { it * it }.sum() +println sumSq + +// square via exponentiation +sumSq = array.collect { it ** 2 }.sum() + +println sumSq diff --git a/Task/Sum-of-squares/Haskell/sum-of-squares.hs b/Task/Sum-of-squares/Haskell/sum-of-squares.hs new file mode 100644 index 0000000000..70fe8aedad --- /dev/null +++ b/Task/Sum-of-squares/Haskell/sum-of-squares.hs @@ -0,0 +1,4 @@ +sumOfSquares = sum . map (^ 2) + +> sumOfSquares [3,1,4,1,5,9] +133 diff --git a/Task/Sum-of-squares/IDL/sum-of-squares.idl b/Task/Sum-of-squares/IDL/sum-of-squares.idl new file mode 100644 index 0000000000..35dca8fdae --- /dev/null +++ b/Task/Sum-of-squares/IDL/sum-of-squares.idl @@ -0,0 +1 @@ +print,total(array^2) diff --git a/Task/Sum-of-squares/Icon/sum-of-squares.icon b/Task/Sum-of-squares/Icon/sum-of-squares.icon new file mode 100644 index 0000000000..be71632081 --- /dev/null +++ b/Task/Sum-of-squares/Icon/sum-of-squares.icon @@ -0,0 +1,14 @@ +procedure main() + local lst + lst := [] + #Construct a simple list and pass it to getsum + every put(lst,seq()\2) + write(getsum(lst)) +end + +procedure getsum(lst) + local total + total := 0 + every total +:= !lst ^ 2 + return total +end diff --git a/Task/Sum-of-squares/Inform-7/sum-of-squares.inf b/Task/Sum-of-squares/Inform-7/sum-of-squares.inf new file mode 100644 index 0000000000..5f29660f55 --- /dev/null +++ b/Task/Sum-of-squares/Inform-7/sum-of-squares.inf @@ -0,0 +1,16 @@ +Sum Of Squares is a room. + +To decide which number is the sum of (N - number) and (M - number) (this is summing): + decide on N + M. + +To decide which number is (N - number) squared (this is squaring): + decide on N * N. + +To decide which number is the sum of squares of (L - list of numbers): + decide on the summing reduction of squaring applied to L. + +When play begins: + say the sum of squares of {}; + say line break; + say the sum of squares of {1, 2, 3}; + end the story. diff --git a/Task/Sum-of-squares/Io/sum-of-squares.io b/Task/Sum-of-squares/Io/sum-of-squares.io new file mode 100644 index 0000000000..720016ef52 --- /dev/null +++ b/Task/Sum-of-squares/Io/sum-of-squares.io @@ -0,0 +1 @@ +list(3,1,4,1,5,9) map(squared) sum diff --git a/Task/Sum-of-squares/J/sum-of-squares-1.j b/Task/Sum-of-squares/J/sum-of-squares-1.j new file mode 100644 index 0000000000..0b466700cc --- /dev/null +++ b/Task/Sum-of-squares/J/sum-of-squares-1.j @@ -0,0 +1 @@ +ss=: +/ @: *: diff --git a/Task/Sum-of-squares/J/sum-of-squares-2.j b/Task/Sum-of-squares/J/sum-of-squares-2.j new file mode 100644 index 0000000000..5ffec5b1b0 --- /dev/null +++ b/Task/Sum-of-squares/J/sum-of-squares-2.j @@ -0,0 +1,7 @@ + ss 3 1 4 1 5 9 +133 + ss $0 NB. $0 is a zero-length vector +0 + x=: 20 4 ?@$ 0 NB. a 20-by-4 table of random (0,1) numbers + ss x +9.09516 5.19512 5.84173 6.6916 diff --git a/Task/Sum-of-squares/J/sum-of-squares-3.j b/Task/Sum-of-squares/J/sum-of-squares-3.j new file mode 100644 index 0000000000..988ede376e --- /dev/null +++ b/Task/Sum-of-squares/J/sum-of-squares-3.j @@ -0,0 +1,11 @@ +ss1=: 3 : 0 + z=. 0 + for_i. i.#y do. z=. z+*:i{y end. +) + + ss1 3 1 4 1 5 9 +133 + ss1 $0 +0 + ss1 x +9.09516 5.19512 5.84173 6.6916 diff --git a/Task/Sum-of-squares/Java/sum-of-squares.java b/Task/Sum-of-squares/Java/sum-of-squares.java new file mode 100644 index 0000000000..88789318c5 --- /dev/null +++ b/Task/Sum-of-squares/Java/sum-of-squares.java @@ -0,0 +1,11 @@ +public class SumSquares +{ + public static void main(final String[] args) + { + double sum = 0; + int[] nums = {1,2,3,4,5}; + for (int i : sum) + sum += i * i; + System.out.println("The sum of the squares is: " + sum); + } +} diff --git a/Task/Sum-of-squares/JavaScript/sum-of-squares-1.js b/Task/Sum-of-squares/JavaScript/sum-of-squares-1.js new file mode 100644 index 0000000000..c6b299c719 --- /dev/null +++ b/Task/Sum-of-squares/JavaScript/sum-of-squares-1.js @@ -0,0 +1,11 @@ +function sumsq(array) { + var sum = 0; + var i, iLen; + + for (i = 0, iLen = array.length; i < iLen; i++) { + sum += array[i] * array[i]; + } + return sum; +} + +alert(sumsq([1,2,3,4,5])); // 55 diff --git a/Task/Sum-of-squares/JavaScript/sum-of-squares-2.js b/Task/Sum-of-squares/JavaScript/sum-of-squares-2.js new file mode 100644 index 0000000000..45d021af9d --- /dev/null +++ b/Task/Sum-of-squares/JavaScript/sum-of-squares-2.js @@ -0,0 +1,10 @@ +function sumsq(array) { + var sum = 0, + i = array.length; + + while (i--) sum += Math.pow(array[i], 2); + + return sum; +} + +alert(sumsq([1,2,3,4,5])); // 55 diff --git a/Task/Sum-of-squares/JavaScript/sum-of-squares-3.js b/Task/Sum-of-squares/JavaScript/sum-of-squares-3.js new file mode 100644 index 0000000000..4915fe3ed9 --- /dev/null +++ b/Task/Sum-of-squares/JavaScript/sum-of-squares-3.js @@ -0,0 +1 @@ +Functional.reduce("x+y*y", 0, [1,2,3,4,5]) diff --git a/Task/Sum-of-squares/JavaScript/sum-of-squares-4.js b/Task/Sum-of-squares/JavaScript/sum-of-squares-4.js new file mode 100644 index 0000000000..1bf542232d --- /dev/null +++ b/Task/Sum-of-squares/JavaScript/sum-of-squares-4.js @@ -0,0 +1 @@ +[3,1,4,1,5,9].map(function (n) { return Math.pow(n,2); }).reduce(function (sum,n) { return sum+n; }); diff --git a/Task/Sum-of-squares/Julia/sum-of-squares.julia b/Task/Sum-of-squares/Julia/sum-of-squares.julia new file mode 100644 index 0000000000..b70d255040 --- /dev/null +++ b/Task/Sum-of-squares/Julia/sum-of-squares.julia @@ -0,0 +1,8 @@ +julia> sum([1,2,3,4,5].^2) +55 + +julia> sum([x^2 for x in [1,2,3,4,5]]) +55 + +julia> sum([x^2 for x in []]) +0 diff --git a/Task/Sum-of-squares/K/sum-of-squares.k b/Task/Sum-of-squares/K/sum-of-squares.k new file mode 100644 index 0000000000..7f48207fba --- /dev/null +++ b/Task/Sum-of-squares/K/sum-of-squares.k @@ -0,0 +1,5 @@ + ss: {+/x*x} + ss 1 2 3 4 5 +55 + ss@!0 +0 diff --git a/Task/Sum-of-squares/Lang5/sum-of-squares.lang5 b/Task/Sum-of-squares/Lang5/sum-of-squares.lang5 new file mode 100644 index 0000000000..33cd30afbd --- /dev/null +++ b/Task/Sum-of-squares/Lang5/sum-of-squares.lang5 @@ -0,0 +1 @@ +[1 2 3 4 5] 2 ** '+ reduce . diff --git a/Task/Sum-of-squares/Liberty-BASIC/sum-of-squares.liberty b/Task/Sum-of-squares/Liberty-BASIC/sum-of-squares.liberty new file mode 100644 index 0000000000..c36bdd5c7a --- /dev/null +++ b/Task/Sum-of-squares/Liberty-BASIC/sum-of-squares.liberty @@ -0,0 +1,27 @@ +' [RC] Sum of Squares + + SourceList$ ="3 1 4 1 5 9" + 'SourceList$ ="" + + ' If saved as an array we'd have to have a flag for last data. + ' LB has the very useful word$() to read from delimited strings. + ' The default delimiter is a space character, " ". + + SumOfSquares =0 + n =0 + data$ ="666" ' temporary dummy to enter the loop. + + while data$ <>"" ' we loop until no data left. + data$ =word$( SourceList$, n +1) ' first data, as a string + NewVal =val( data$) ' convert string to number + SumOfSquares =SumOfSquares +NewVal^2 ' add to existing sum of squares + n =n +1 ' increment number of data items found + wend + + n =n -1 + + print "Supplied data was "; SourceList$ + print "This contained "; n; " numbers." + print "Sum of squares is "; SumOfSquares + + end diff --git a/Task/Sum-of-squares/Logo/sum-of-squares.logo b/Task/Sum-of-squares/Logo/sum-of-squares.logo new file mode 100644 index 0000000000..69f85e167c --- /dev/null +++ b/Task/Sum-of-squares/Logo/sum-of-squares.logo @@ -0,0 +1 @@ +print apply "sum map [? * ?] [1 2 3 4 5] ; 55 diff --git a/Task/Sum-of-squares/Logtalk/sum-of-squares.logtalk b/Task/Sum-of-squares/Logtalk/sum-of-squares.logtalk new file mode 100644 index 0000000000..d0b2ca3f77 --- /dev/null +++ b/Task/Sum-of-squares/Logtalk/sum-of-squares.logtalk @@ -0,0 +1,7 @@ +sum(List, Sum) :- + sum(List, 0, Sum). + +sum([], Sum, Sum). +sum([X| Xs], Acc, Sum) :- + Acc2 is Acc + X, + sum(Xs, Acc2, Sum). diff --git a/Task/Sum-of-squares/Lua/sum-of-squares.lua b/Task/Sum-of-squares/Lua/sum-of-squares.lua new file mode 100644 index 0000000000..03f3a40074 --- /dev/null +++ b/Task/Sum-of-squares/Lua/sum-of-squares.lua @@ -0,0 +1,4 @@ +function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end +function squaresumt(t) return squaresum(unpack(t)) end + +print(squaresumt{3, 5, 4, 1, 7}) diff --git a/Task/Sum-of-squares/MATLAB/sum-of-squares.m b/Task/Sum-of-squares/MATLAB/sum-of-squares.m new file mode 100644 index 0000000000..efe6dbf383 --- /dev/null +++ b/Task/Sum-of-squares/MATLAB/sum-of-squares.m @@ -0,0 +1,2 @@ +function [squaredSum] = sumofsquares(inputVector) + squaredSum = sum( inputVector.^2 ); diff --git a/Task/Sum-of-squares/MOO/sum-of-squares.moo b/Task/Sum-of-squares/MOO/sum-of-squares.moo new file mode 100644 index 0000000000..99fe2cc427 --- /dev/null +++ b/Task/Sum-of-squares/MOO/sum-of-squares.moo @@ -0,0 +1,15 @@ +@verb #100:sum_squares this none this rd +@program #100:sum_squares +sum = 0; +list = args[1]; +for i in (list) + sum = sum + (i^2); +endfor +player:tell(toliteral(list), " => ", sum); +. + +Output: +;#100:sum_squares({3,1,4,1,5,9}) +{3, 1, 4, 1, 5, 9} => 133 +;#100:sum_squares({}) +{} => 0 diff --git a/Task/Sum-of-squares/MUMPS/sum-of-squares.mumps b/Task/Sum-of-squares/MUMPS/sum-of-squares.mumps new file mode 100644 index 0000000000..39478d86df --- /dev/null +++ b/Task/Sum-of-squares/MUMPS/sum-of-squares.mumps @@ -0,0 +1,6 @@ +SUMSQUARE(X) + ;X is assumed to be a list of numbers separated by "^" + NEW RESULT,I + SET RESULT=0,I=1 + FOR QUIT:(I>$LENGTH(X,"^")) SET RESULT=($PIECE(X,"^",I)*$PIECE(X,"^",I))+RESULT,I=I+1 + QUIT RESULT diff --git a/Task/Sum-of-squares/Mathematica/sum-of-squares-1.math b/Task/Sum-of-squares/Mathematica/sum-of-squares-1.math new file mode 100644 index 0000000000..7e23048469 --- /dev/null +++ b/Task/Sum-of-squares/Mathematica/sum-of-squares-1.math @@ -0,0 +1,2 @@ +SumOfSquares[x_]:=Total[x^2] +SumOfSquares[{1,2,3,4,5}] diff --git a/Task/Sum-of-squares/Mathematica/sum-of-squares-2.math b/Task/Sum-of-squares/Mathematica/sum-of-squares-2.math new file mode 100644 index 0000000000..bd3ea7754f --- /dev/null +++ b/Task/Sum-of-squares/Mathematica/sum-of-squares-2.math @@ -0,0 +1,2 @@ +SumOfSquares[x_]:=x.x +SumOfSquares[{1,2,3,4,5}] diff --git a/Task/Sum-of-squares/Mathematica/sum-of-squares-3.math b/Task/Sum-of-squares/Mathematica/sum-of-squares-3.math new file mode 100644 index 0000000000..e3ca395d0a --- /dev/null +++ b/Task/Sum-of-squares/Mathematica/sum-of-squares-3.math @@ -0,0 +1 @@ +{1,2,3,4,5} // Total[#^2] & diff --git a/Task/Sum-of-squares/Mathematica/sum-of-squares-4.math b/Task/Sum-of-squares/Mathematica/sum-of-squares-4.math new file mode 100644 index 0000000000..b089b979d8 --- /dev/null +++ b/Task/Sum-of-squares/Mathematica/sum-of-squares-4.math @@ -0,0 +1 @@ +{1, 2, 3, 4, 5} // #^2 & // Total diff --git a/Task/Sum-of-squares/Mathematica/sum-of-squares-5.math b/Task/Sum-of-squares/Mathematica/sum-of-squares-5.math new file mode 100644 index 0000000000..0ef65b4b6d --- /dev/null +++ b/Task/Sum-of-squares/Mathematica/sum-of-squares-5.math @@ -0,0 +1 @@ +{1, 2, 3, 4, 5} // #.#& diff --git a/Task/Sum-of-squares/Maxima/sum-of-squares.maxima b/Task/Sum-of-squares/Maxima/sum-of-squares.maxima new file mode 100644 index 0000000000..d385b527a7 --- /dev/null +++ b/Task/Sum-of-squares/Maxima/sum-of-squares.maxima @@ -0,0 +1,2 @@ +nums : [3,1,4,1,5,9]; +sum(nums[i]^2,i,1,length(nums)); diff --git a/Task/Sum-of-squares/Mercury/sum-of-squares.mercury b/Task/Sum-of-squares/Mercury/sum-of-squares.mercury new file mode 100644 index 0000000000..de6c05e480 --- /dev/null +++ b/Task/Sum-of-squares/Mercury/sum-of-squares.mercury @@ -0,0 +1,16 @@ +:- module sum_of_squares. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module int, list. + +main(!IO) :- + io.write_int(sum_of_squares([3, 1, 4, 1, 5, 9]), !IO), + io.nl(!IO). + +:- func sum_of_squares(list(int)) = int. + +sum_of_squares(Ns) = list.foldl((func(N, Acc) = Acc + N * N), Ns, 0). diff --git a/Task/Sum-of-squares/Modula-3/sum-of-squares.mod3 b/Task/Sum-of-squares/Modula-3/sum-of-squares.mod3 new file mode 100644 index 0000000000..abfcbdaea5 --- /dev/null +++ b/Task/Sum-of-squares/Modula-3/sum-of-squares.mod3 @@ -0,0 +1,19 @@ +MODULE SumSquares EXPORTS Main; + +IMPORT IO, Fmt; + +TYPE RealArray = ARRAY OF REAL; + +PROCEDURE SumOfSquares(x: RealArray): REAL = + VAR sum := 0.0; + BEGIN + FOR i := FIRST(x) TO LAST(x) DO + sum := sum + x[i] * x[i]; + END; + RETURN sum; + END SumOfSquares; + +BEGIN + IO.Put(Fmt.Real(SumOfSquares(RealArray{3.0, 1.0, 4.0, 1.0, 5.0, 9.0}))); + IO.Put("\n"); +END SumSquares. diff --git a/Task/Sum-of-squares/Nemerle/sum-of-squares.nemerle b/Task/Sum-of-squares/Nemerle/sum-of-squares.nemerle new file mode 100644 index 0000000000..60b20923bb --- /dev/null +++ b/Task/Sum-of-squares/Nemerle/sum-of-squares.nemerle @@ -0,0 +1,5 @@ +SS(x : list[double]) : double +{ + |[] => 0.0 + |_ => x.Map(fun (x) {x*x}).FoldLeft(0.0, _+_) +} diff --git a/Task/Sum-of-squares/NewLISP/sum-of-squares.newlisp b/Task/Sum-of-squares/NewLISP/sum-of-squares.newlisp new file mode 100644 index 0000000000..09edd2efc5 --- /dev/null +++ b/Task/Sum-of-squares/NewLISP/sum-of-squares.newlisp @@ -0,0 +1,4 @@ +(apply + (map (fn(x) (* x x)) '(3 1 4 1 5 9))) +-> 133 +(apply + (map (fn(x) (* x x)) '())) +-> 0 diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml new file mode 100644 index 0000000000..dc787f62da --- /dev/null +++ b/Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml @@ -0,0 +1 @@ +List.fold_left (fun sum a -> sum + a * a) 0 ints diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml new file mode 100644 index 0000000000..cb73d020db --- /dev/null +++ b/Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml @@ -0,0 +1 @@ +List.fold_left (fun sum a -> sum +. a *. a) 0. floats diff --git a/Task/Sum-of-squares/Objeck/sum-of-squares.objeck b/Task/Sum-of-squares/Objeck/sum-of-squares.objeck new file mode 100644 index 0000000000..32370ec849 --- /dev/null +++ b/Task/Sum-of-squares/Objeck/sum-of-squares.objeck @@ -0,0 +1,16 @@ +bundle Default { + class Sum { + function : native : SquaredSum(values : Float[]) ~ Float { + sum := 0.0; + for(i := 0 ; i < values->Size() ; i += 1;) { + sum += (values[i] * values[i]); + }; + + return sum; + } + + function : Main(args : String[]) ~ Nil { + SquaredSum([3.0, 1.0, 4.0, 1.0, 5.0, 9.0])->PrintLine(); + } + } +} diff --git a/Task/Sum-of-squares/Octave/sum-of-squares.octave b/Task/Sum-of-squares/Octave/sum-of-squares.octave new file mode 100644 index 0000000000..5c39b9220f --- /dev/null +++ b/Task/Sum-of-squares/Octave/sum-of-squares.octave @@ -0,0 +1,2 @@ +a = [1:10]; +sumsq = sum(a .^ 2); diff --git a/Task/Sum-of-squares/Order/sum-of-squares.order b/Task/Sum-of-squares/Order/sum-of-squares.order new file mode 100644 index 0000000000..4c679298ee --- /dev/null +++ b/Task/Sum-of-squares/Order/sum-of-squares.order @@ -0,0 +1,6 @@ +#include + +ORDER_PP(8to_lit( + 8seq_fold(8plus, 0, + 8seq_map(8fn(8X, 8times(8X, 8X)), 8seq(3, 1, 4, 1, 5, 9))) +)) diff --git a/Task/Sum-of-squares/Oz/sum-of-squares.oz b/Task/Sum-of-squares/Oz/sum-of-squares.oz new file mode 100644 index 0000000000..73689e71be --- /dev/null +++ b/Task/Sum-of-squares/Oz/sum-of-squares.oz @@ -0,0 +1,8 @@ +declare + fun {SumOfSquares Xs} + for X in Xs sum:S do + {S X*X} + end + end +in + {Show {SumOfSquares [3 1 4 1 5 9]}} diff --git a/Task/Sum-of-squares/PARI-GP/sum-of-squares.pari b/Task/Sum-of-squares/PARI-GP/sum-of-squares.pari new file mode 100644 index 0000000000..fc741d3cd4 --- /dev/null +++ b/Task/Sum-of-squares/PARI-GP/sum-of-squares.pari @@ -0,0 +1,3 @@ +ss(v)={ + sum(i=1,#v,v[i]^2) +}; diff --git a/Task/Sum-of-squares/PHP/sum-of-squares-1.php b/Task/Sum-of-squares/PHP/sum-of-squares-1.php new file mode 100644 index 0000000000..92f17e68f1 --- /dev/null +++ b/Task/Sum-of-squares/PHP/sum-of-squares-1.php @@ -0,0 +1,5 @@ +function sum_squares(array $args) { + return array_reduce( + $args, create_function('$x, $y', 'return $x+$y*$y;'), 0 + ); +} diff --git a/Task/Sum-of-squares/PHP/sum-of-squares-2.php b/Task/Sum-of-squares/PHP/sum-of-squares-2.php new file mode 100644 index 0000000000..48420a71ea --- /dev/null +++ b/Task/Sum-of-squares/PHP/sum-of-squares-2.php @@ -0,0 +1,5 @@ +function sum_squares(array $args) { + return array_reduce($args, function($x, $y) { + return $x+$y*$y; + }, 0); +} diff --git a/Task/Sum-of-squares/PL-I/sum-of-squares.pli b/Task/Sum-of-squares/PL-I/sum-of-squares.pli new file mode 100644 index 0000000000..a55852539f --- /dev/null +++ b/Task/Sum-of-squares/PL-I/sum-of-squares.pli @@ -0,0 +1,3 @@ +declare A(10) float initial (10, 9, 8, 7, 6, 5, 4, 3, 2, 1); + +put (sum(A**2)); diff --git a/Task/Sum-of-squares/Pascal/sum-of-squares.pascal b/Task/Sum-of-squares/Pascal/sum-of-squares.pascal new file mode 100644 index 0000000000..3ba88cc152 --- /dev/null +++ b/Task/Sum-of-squares/Pascal/sum-of-squares.pascal @@ -0,0 +1,19 @@ +Program Example45; + +{ Program to demonstrate the SumOfSquares function. } + +Uses math; + +Var + I : 1..100; + ExArray : Array[1..100] of Float; + +begin + Randomize; + for I:=low(ExArray) to high(ExArray) do + ExArray[i]:=(Random-Random)*100; + Writeln('Max : ',MaxValue(ExArray):8:4); + Writeln('Min : ',MinValue(ExArray):8:4); + Writeln('Sum squares : ',SumOfSquares(ExArray):8:4); + Writeln('Sum squares (b) : ',SumOfSquares(@ExArray[1],100):8:4); +end. diff --git a/Task/Sum-of-squares/Perl-6/sum-of-squares-1.pl6 b/Task/Sum-of-squares/Perl-6/sum-of-squares-1.pl6 new file mode 100644 index 0000000000..d86b3fe9cb --- /dev/null +++ b/Task/Sum-of-squares/Perl-6/sum-of-squares-1.pl6 @@ -0,0 +1 @@ +say [+] map * ** 2, 3, 1, 4, 1, 5, 9; diff --git a/Task/Sum-of-squares/Perl-6/sum-of-squares-2.pl6 b/Task/Sum-of-squares/Perl-6/sum-of-squares-2.pl6 new file mode 100644 index 0000000000..570dcb27f1 --- /dev/null +++ b/Task/Sum-of-squares/Perl-6/sum-of-squares-2.pl6 @@ -0,0 +1 @@ +say [+] 3,1,4,1,5,9 X** 2 diff --git a/Task/Sum-of-squares/Perl/sum-of-squares-1.pl b/Task/Sum-of-squares/Perl/sum-of-squares-1.pl new file mode 100644 index 0000000000..1254a3f1ab --- /dev/null +++ b/Task/Sum-of-squares/Perl/sum-of-squares-1.pl @@ -0,0 +1,7 @@ +sub sum_of_squares { + my $sum = 0; + $sum += $_**2 foreach @_; + return $sum; +} + +print sum_of_squares(3, 1, 4, 1, 5, 9), "\n"; diff --git a/Task/Sum-of-squares/Perl/sum-of-squares-2.pl b/Task/Sum-of-squares/Perl/sum-of-squares-2.pl new file mode 100644 index 0000000000..67e09a07ad --- /dev/null +++ b/Task/Sum-of-squares/Perl/sum-of-squares-2.pl @@ -0,0 +1,6 @@ +use List::Util qw(reduce); +sub sum_of_squares { + reduce { $a + $b **2 } 0, @_; +} + +print sum_of_squares(3, 1, 4, 1, 5, 9), "\n"; diff --git a/Task/Sum-of-squares/PicoLisp/sum-of-squares.l b/Task/Sum-of-squares/PicoLisp/sum-of-squares.l new file mode 100644 index 0000000000..27236f2693 --- /dev/null +++ b/Task/Sum-of-squares/PicoLisp/sum-of-squares.l @@ -0,0 +1,4 @@ +: (sum '((N) (* N N)) (3 1 4 1 5 9)) +-> 133 +: (sum '((N) (* N N)) ()) +-> 0 diff --git a/Task/Sum-of-squares/Pop11/sum-of-squares.pop11 b/Task/Sum-of-squares/Pop11/sum-of-squares.pop11 new file mode 100644 index 0000000000..c6909375a1 --- /dev/null +++ b/Task/Sum-of-squares/Pop11/sum-of-squares.pop11 @@ -0,0 +1,9 @@ +define sum_squares(v); + lvars s = 0, j; + for j from 1 to length(v) do + s + v(j)*v(j) -> s; + endfor; + s; +enddefine; + +sum_squares({1 2 3 4 5}) => diff --git a/Task/Sum-of-squares/PostScript/sum-of-squares-1.ps b/Task/Sum-of-squares/PostScript/sum-of-squares-1.ps new file mode 100644 index 0000000000..18d59acc13 --- /dev/null +++ b/Task/Sum-of-squares/PostScript/sum-of-squares-1.ps @@ -0,0 +1,14 @@ +/sqrsum{ +/x exch def +/sum 0 def +/i 0 def +x length 0 eq +{} +{ +x length{ +/sum sum x i get 2 exp add def +/i i 1 add def +}repeat +}ifelse +sum == +}def diff --git a/Task/Sum-of-squares/PostScript/sum-of-squares-2.ps b/Task/Sum-of-squares/PostScript/sum-of-squares-2.ps new file mode 100644 index 0000000000..972c755880 --- /dev/null +++ b/Task/Sum-of-squares/PostScript/sum-of-squares-2.ps @@ -0,0 +1 @@ +[3 1 4 1 5 9] 0 {dup * +} fold diff --git a/Task/Sum-of-squares/PowerShell/sum-of-squares.psh b/Task/Sum-of-squares/PowerShell/sum-of-squares.psh new file mode 100644 index 0000000000..c7cffb9a69 --- /dev/null +++ b/Task/Sum-of-squares/PowerShell/sum-of-squares.psh @@ -0,0 +1,10 @@ +function Get-SquareSum ($a) { + if ($a.Length -eq 0) { + return 0 + } else { + $x = $a ` + | ForEach-Object { $_ * $_ } ` + | Measure-Object -Sum + return $x.Sum + } +} diff --git a/Task/Sum-of-squares/PureBasic/sum-of-squares.purebasic b/Task/Sum-of-squares/PureBasic/sum-of-squares.purebasic new file mode 100644 index 0000000000..62532bfc09 --- /dev/null +++ b/Task/Sum-of-squares/PureBasic/sum-of-squares.purebasic @@ -0,0 +1,6 @@ +Procedure SumOfSquares(List base()) + ForEach base() + Sum + base()*base() + Next + ProcedureReturn Sum +EndProcedure diff --git a/Task/Sum-of-squares/Python/sum-of-squares.py b/Task/Sum-of-squares/Python/sum-of-squares.py new file mode 100644 index 0000000000..42c554d25c --- /dev/null +++ b/Task/Sum-of-squares/Python/sum-of-squares.py @@ -0,0 +1 @@ +sum(x*x for x in [1, 2, 3, 4, 5]) diff --git a/Task/Sum-of-squares/R/sum-of-squares.r b/Task/Sum-of-squares/R/sum-of-squares.r new file mode 100644 index 0000000000..4e01400253 --- /dev/null +++ b/Task/Sum-of-squares/R/sum-of-squares.r @@ -0,0 +1,2 @@ +arr <- c(1,2,3,4,5) +result <- sum(arr^2) diff --git a/Task/Sum-of-squares/REXX/sum-of-squares.rexx b/Task/Sum-of-squares/REXX/sum-of-squares.rexx new file mode 100644 index 0000000000..a270a2ec1a --- /dev/null +++ b/Task/Sum-of-squares/REXX/sum-of-squares.rexx @@ -0,0 +1,11 @@ +/*REXX program to sum the squares of a vector of fifteen numbers. */ +numeric digits 50 /*allow 50-digit # (default is 9)*/ +v=-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with some #s. */ +sum=0 /*initialize SUM to zero. */ + /*if vector is empty, sum = zero.*/ + do k=1 while word(v,k)\=='' /*sum squares whilest they're #s.*/ + sum=sum + word(v,k)**2 /*add squared element to the sum.*/ + end /*k*/ + +say 'The sum of ' k-1 " elements for the V vector is: " sum + /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-squares/Racket/sum-of-squares.rkt b/Task/Sum-of-squares/Racket/sum-of-squares.rkt new file mode 100644 index 0000000000..6add3e0386 --- /dev/null +++ b/Task/Sum-of-squares/Racket/sum-of-squares.rkt @@ -0,0 +1,2 @@ +#lang racket +(for/sum ([x #(3 1 4 1 5 9)]) (* x x)) diff --git a/Task/Sum-of-squares/Ruby/sum-of-squares-1.rb b/Task/Sum-of-squares/Ruby/sum-of-squares-1.rb new file mode 100644 index 0000000000..69d7c2ee8a --- /dev/null +++ b/Task/Sum-of-squares/Ruby/sum-of-squares-1.rb @@ -0,0 +1 @@ +[3,1,4,1,5,9].inject(0) { |sum,x| sum += x**2 } diff --git a/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb new file mode 100644 index 0000000000..3b4e8f15ca --- /dev/null +++ b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb @@ -0,0 +1 @@ +[3,1,4,1,5,9].map { |x| x**2 }.reduce(:+) diff --git a/Task/Sum-of-squares/Run-BASIC/sum-of-squares.run b/Task/Sum-of-squares/Run-BASIC/sum-of-squares.run new file mode 100644 index 0000000000..2da59a0f09 --- /dev/null +++ b/Task/Sum-of-squares/Run-BASIC/sum-of-squares.run @@ -0,0 +1,9 @@ +list$ = "1,2,3,4,5" +print sumOfSquares(list$) + +FUNCTION sumOfSquares(sos$) + while word$(sos$,i+1,",") <> "" + i = i + 1 + sumOfSquares = sumOfSquares + val(word$(sos$,i,","))^2 + wend +END FUNCTION diff --git a/Task/Sum-of-squares/SNOBOL4/sum-of-squares.sno b/Task/Sum-of-squares/SNOBOL4/sum-of-squares.sno new file mode 100644 index 0000000000..12d8e9d0c3 --- /dev/null +++ b/Task/Sum-of-squares/SNOBOL4/sum-of-squares.sno @@ -0,0 +1,9 @@ + define('ssq(a)i') :(ssq_end) +ssq i = i + 1; ssq = ssq + (a * a) :s(sumsq)f(return) +ssq_end + +* # Fill array, test and display + str = '1 2 3 5 7 11 13 17 19 23'; a = array(10) +loop i = i + 1; str len(p) span('0123456789') . a @p :s(loop) + output = str ' -> ' sumsq(a) +end diff --git a/Task/Sum-of-squares/SQL/sum-of-squares.sql b/Task/Sum-of-squares/SQL/sum-of-squares.sql new file mode 100644 index 0000000000..171b6d89c7 --- /dev/null +++ b/Task/Sum-of-squares/SQL/sum-of-squares.sql @@ -0,0 +1 @@ +select sum(x*x) from vector diff --git a/Task/Sum-of-squares/Sather/sum-of-squares.sa b/Task/Sum-of-squares/Sather/sum-of-squares.sa new file mode 100644 index 0000000000..0e6152f80b --- /dev/null +++ b/Task/Sum-of-squares/Sather/sum-of-squares.sa @@ -0,0 +1,16 @@ +class MAIN is + + sqsum(s, e:FLT):FLT is + return s + e*e; + end; + + sum_of_squares(v :ARRAY{FLT}):FLT is + return (#ARRAY{FLT}(|0.0|).append(v)).reduce(bind(sqsum(_,_))); + end; + + main is + v :ARRAY{FLT} := |3.0, 1.0, 4.0, 1.0, 5.0, 9.0|; + #OUT + sum_of_squares(v) + "\n"; + end; + +end; diff --git a/Task/Sum-of-squares/Scala/sum-of-squares.scala b/Task/Sum-of-squares/Scala/sum-of-squares.scala new file mode 100644 index 0000000000..0af92cd01a --- /dev/null +++ b/Task/Sum-of-squares/Scala/sum-of-squares.scala @@ -0,0 +1 @@ +def sum_of_squares(xs: Seq[Double]) = xs.foldLeft(0) {(a,x) => a + x*x} diff --git a/Task/Sum-of-squares/Scheme/sum-of-squares.ss b/Task/Sum-of-squares/Scheme/sum-of-squares.ss new file mode 100644 index 0000000000..0e33eb70d3 --- /dev/null +++ b/Task/Sum-of-squares/Scheme/sum-of-squares.ss @@ -0,0 +1,2 @@ +(define (sum-of-squares l) + (apply + (map * l l))) diff --git a/Task/Sum-of-squares/Seed7/sum-of-squares.seed7 b/Task/Sum-of-squares/Seed7/sum-of-squares.seed7 new file mode 100644 index 0000000000..8266cfca19 --- /dev/null +++ b/Task/Sum-of-squares/Seed7/sum-of-squares.seed7 @@ -0,0 +1,22 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const array float: list1 is [] (3.0, 1.0, 4.0, 1.0, 5.0, 9.0); +const array float: list2 is 0 times 0.0; + +const func float: squaredSum (in array float: floatList) is func + result + var float: sum is 0.0; + local + var float: number is 0.0; + begin + for number range floatList do + sum +:= number ** 2; + end for; + end func; + +const proc: main is func + begin + writeln(squaredSum(list1)); + writeln(squaredSum(list2)); + end func; diff --git a/Task/Sum-of-squares/Slate/sum-of-squares.slate b/Task/Sum-of-squares/Slate/sum-of-squares.slate new file mode 100644 index 0000000000..66a4cbb983 --- /dev/null +++ b/Task/Sum-of-squares/Slate/sum-of-squares.slate @@ -0,0 +1,2 @@ +{1. 2. 3} reduce: [|:x :y| y squared + x]. +{} reduce: [|:x :y| y squared + x] ifEmpty: [0]. diff --git a/Task/Sum-of-squares/Smalltalk/sum-of-squares.st b/Task/Sum-of-squares/Smalltalk/sum-of-squares.st new file mode 100644 index 0000000000..1988f8d460 --- /dev/null +++ b/Task/Sum-of-squares/Smalltalk/sum-of-squares.st @@ -0,0 +1 @@ +#(3 1 4 1 5 9) inject: 0 into: [:sum :aNumber | sum + aNumber squared] diff --git a/Task/Sum-of-squares/Standard-ML/sum-of-squares-1.ml b/Task/Sum-of-squares/Standard-ML/sum-of-squares-1.ml new file mode 100644 index 0000000000..24584be9c2 --- /dev/null +++ b/Task/Sum-of-squares/Standard-ML/sum-of-squares-1.ml @@ -0,0 +1 @@ +foldl (fn (a, sum) => sum + a * a) 0 ints diff --git a/Task/Sum-of-squares/Standard-ML/sum-of-squares-2.ml b/Task/Sum-of-squares/Standard-ML/sum-of-squares-2.ml new file mode 100644 index 0000000000..691a301756 --- /dev/null +++ b/Task/Sum-of-squares/Standard-ML/sum-of-squares-2.ml @@ -0,0 +1 @@ +foldl (fn (a, sum) => sum + a * a) 0.0 reals diff --git a/Task/Sum-of-squares/TUSCRIPT/sum-of-squares.tuscript b/Task/Sum-of-squares/TUSCRIPT/sum-of-squares.tuscript new file mode 100644 index 0000000000..872e753366 --- /dev/null +++ b/Task/Sum-of-squares/TUSCRIPT/sum-of-squares.tuscript @@ -0,0 +1,6 @@ +$$ MODE TUSCRIPT +array="3'1'4'1'5'9",sum=0 +LOOP a=array +sum=sum+(a*a) +ENDLOOP +PRINT sum diff --git a/Task/Sum-of-squares/Tcl/sum-of-squares-1.tcl b/Task/Sum-of-squares/Tcl/sum-of-squares-1.tcl new file mode 100644 index 0000000000..8830b0b4b4 --- /dev/null +++ b/Task/Sum-of-squares/Tcl/sum-of-squares-1.tcl @@ -0,0 +1,9 @@ +proc sumOfSquares {nums} { + set sum 0 + foreach num $nums { + set sum [expr {$sum + $num**2}] + } + return $sum +} +sumOfSquares {1 2 3 4 5} ;# ==> 55 +sumOfSquares {} ;# ==> 0 diff --git a/Task/Sum-of-squares/Tcl/sum-of-squares-2.tcl b/Task/Sum-of-squares/Tcl/sum-of-squares-2.tcl new file mode 100644 index 0000000000..0e612f4479 --- /dev/null +++ b/Task/Sum-of-squares/Tcl/sum-of-squares-2.tcl @@ -0,0 +1,9 @@ +package require struct::list + +proc square x {expr {$x * $x}} +proc + {a b} {expr {$a + $b}} +proc sumOfSquares {nums} { + struct::list fold [struct::list map $nums square] 0 + +} +sumOfSquares {1 2 3 4 5} ;# ==> 55 +sumOfSquares {} ;# ==> 0 diff --git a/Task/Sum-of-squares/Tcl/sum-of-squares-3.tcl b/Task/Sum-of-squares/Tcl/sum-of-squares-3.tcl new file mode 100644 index 0000000000..4badc0cfcc --- /dev/null +++ b/Task/Sum-of-squares/Tcl/sum-of-squares-3.tcl @@ -0,0 +1,9 @@ +package require Tcl 8.5 +package require struct::list +namespace path ::tcl::mathop + +proc sum_of {lambda nums} { + struct::list fold [struct::list map $nums [list apply $lambda]] 0 + +} + +sum_of {x {* $x $x}} {1 2 3 4 5} ;# ==> 55 diff --git a/Task/Sum-of-squares/Trith/sum-of-squares.trith b/Task/Sum-of-squares/Trith/sum-of-squares.trith new file mode 100644 index 0000000000..e7b93ef1b6 --- /dev/null +++ b/Task/Sum-of-squares/Trith/sum-of-squares.trith @@ -0,0 +1 @@ +[3 1 4 1 5 9] 0 [dup * +] foldl diff --git a/Task/Sum-of-squares/UnixPipes/sum-of-squares.unixpipes b/Task/Sum-of-squares/UnixPipes/sum-of-squares.unixpipes new file mode 100644 index 0000000000..1eee1f0de9 --- /dev/null +++ b/Task/Sum-of-squares/UnixPipes/sum-of-squares.unixpipes @@ -0,0 +1,12 @@ +folder() { + (read B; res=$( expr $1 \* $1 ) ; test -n "$B" && expr $res + $B || echo $res) +} + +fold() { + (while read a ; do + fold | folder $a + done) +} + + +(echo 3; echo 1; echo 4;echo 1;echo 5; echo 9) | fold diff --git a/Task/Sum-of-squares/Ursala/sum-of-squares.ursala b/Task/Sum-of-squares/Ursala/sum-of-squares.ursala new file mode 100644 index 0000000000..285d4d22ad --- /dev/null +++ b/Task/Sum-of-squares/Ursala/sum-of-squares.ursala @@ -0,0 +1,7 @@ +#import nat + +ssq = sum:-0+ product*iip + +#cast %n + +main = ssq <21,12,77,0,94,23,96,93,72,72,79,24,8,50,9,93> diff --git a/Task/Sum-of-squares/V/sum-of-squares.v b/Task/Sum-of-squares/V/sum-of-squares.v new file mode 100644 index 0000000000..8bfdaf152e --- /dev/null +++ b/Task/Sum-of-squares/V/sum-of-squares.v @@ -0,0 +1,5 @@ +[sumsq [dup *] map 0 [+] fold]. + +[] sumsq +=0 +[1 2 3] sumsq diff --git a/Task/Sum-of-squares/Visual-Basic-.NET/sum-of-squares.visual b/Task/Sum-of-squares/Visual-Basic-.NET/sum-of-squares.visual new file mode 100644 index 0000000000..511af0c61c --- /dev/null +++ b/Task/Sum-of-squares/Visual-Basic-.NET/sum-of-squares.visual @@ -0,0 +1,35 @@ + Private Shared Function sumsq(ByVal i As ICollection(Of Integer)) As Integer + If i Is Nothing OrElse i.Count = 0 Then + Return 0 + End If + Return i.[Select](Function(x) x * x).Sum() + End Function + + Private Shared Sub Main() + Dim a As Integer() = New Integer() {1, 2, 3, 4, 5} + ' 55 + Console.WriteLine(sumsq(a)) + + For K As Integer = 0 To 16 + Console.WriteLine("SumOfSquares({0}) = {1}", K, SumOfSquares(K)) + Next + End Sub + Function SumOfSquares(ByVal Max As Integer) + Dim Square As Integer = 0 + Dim Add As Integer = 1 + Dim Sum As Integer = 0 + For J As Integer = 0 To Max - 1 + Square += Add + Add += 2 + Sum += Square + Next + Return Sum + End Function + + Function SumOfSquaresByMult(ByVal Max As Integer) + Dim Sum As Integer = 0 + For J As Integer = 1 To Max + Sum += J * J + Next + Return Sum + End Function diff --git a/Task/Sum-of-squares/XPL0/sum-of-squares.xpl0 b/Task/Sum-of-squares/XPL0/sum-of-squares.xpl0 new file mode 100644 index 0000000000..8a4269c301 --- /dev/null +++ b/Task/Sum-of-squares/XPL0/sum-of-squares.xpl0 @@ -0,0 +1,13 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +func SumSq(V, L); +int V, L; +int S, I; +[S:= 0; +for I:= 0 to L-1 do S:= S+sq(V(I)); +return S; +]; \SumSq + +[IntOut(0, SumSq([1,2,3,4,5,6,7,8,9,10], 10)); CrLf(0); + IntOut(0, SumSq([0], 0)); CrLf(0); \zero-length vector "[]" doesn't compile +] diff --git a/Task/Sutherland-Hodgman-polygon-clipping/0DESCRIPTION b/Task/Sutherland-Hodgman-polygon-clipping/0DESCRIPTION new file mode 100644 index 0000000000..1db06522bd --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/0DESCRIPTION @@ -0,0 +1,10 @@ +The [[wp:Sutherland-Hodgman clipping algorithm|Sutherland-Hodgman clipping algorithm]] finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed. + +For this task, take the closed polygon defined by the points: +: [(50, 150), (200, 50), (350, 150), (350, 300), (250, 300), (200, 250), (150, 350), (100, 250), (100, 200)] +and clip it by the rectangle defined by the points: +: [(100, 100), (300, 100), (300, 300), (100, 300)] + +Print the sequence of points that define the resulting clipped polygon. + +'''Extra credit:''' Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon. (When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/1META.yaml b/Task/Sutherland-Hodgman-polygon-clipping/1META.yaml new file mode 100644 index 0000000000..e997ed0748 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Graphics algorithms diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Ada/sutherland-hodgman-polygon-clipping.ada b/Task/Sutherland-Hodgman-polygon-clipping/Ada/sutherland-hodgman-polygon-clipping.ada new file mode 100644 index 0000000000..1a697b0b03 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Ada/sutherland-hodgman-polygon-clipping.ada @@ -0,0 +1,113 @@ +with Ada.Containers.Doubly_Linked_Lists; +with Ada.Text_IO; + +procedure Main is + package FIO is new Ada.Text_IO.Float_IO (Float); + + type Point is record + X, Y : Float; + end record; + + function "-" (Left, Right : Point) return Point is + begin + return (Left.X - Right.X, Left.Y - Right.Y); + end "-"; + + type Edge is array (1 .. 2) of Point; + + package Point_Lists is new Ada.Containers.Doubly_Linked_Lists + (Element_Type => Point); + use type Point_Lists.List; + subtype Polygon is Point_Lists.List; + + function Inside (P : Point; E : Edge) return Boolean is + begin + return (E (2).X - E (1).X) * (P.Y - E (1).Y) > + (E (2).Y - E (1).Y) * (P.X - E (1).X); + end Inside; + + function Intersecton (P1, P2 : Point; E : Edge) return Point is + DE : Point := E (1) - E (2); + DP : Point := P1 - P2; + N1 : Float := E (1).X * E (2).Y - E (1).Y * E (2).X; + N2 : Float := P1.X * P2.Y - P1.Y * P2.X; + N3 : Float := 1.0 / (DE.X * DP.Y - DE.Y * DP.X); + begin + return ((N1 * DP.X - N2 * DE.X) * N3, (N1 * DP.Y - N2 * DE.Y) * N3); + end Intersecton; + + function Clip (P, C : Polygon) return Polygon is + use Point_Lists; + A, B, S, E : Cursor; + Inputlist : List; + Outputlist : List := P; + AB : Edge; + begin + A := C.First; + B := C.Last; + while A /= No_Element loop + AB := (Element (B), Element (A)); + Inputlist := Outputlist; + Outputlist.Clear; + S := Inputlist.Last; + E := Inputlist.First; + while E /= No_Element loop + if Inside (Element (E), AB) then + if not Inside (Element (S), AB) then + Outputlist.Append + (Intersecton (Element (S), Element (E), AB)); + end if; + Outputlist.Append (Element (E)); + elsif Inside (Element (S), AB) then + Outputlist.Append + (Intersecton (Element (S), Element (E), AB)); + end if; + S := E; + E := Next (E); + end loop; + B := A; + A := Next (A); + end loop; + return Outputlist; + end Clip; + + procedure Print (P : Polygon) is + use Point_Lists; + C : Cursor := P.First; + begin + Ada.Text_IO.Put_Line ("{"); + while C /= No_Element loop + Ada.Text_IO.Put (" ("); + FIO.Put (Element (C).X, Exp => 0); + Ada.Text_IO.Put (','); + FIO.Put (Element (C).Y, Exp => 0); + Ada.Text_IO.Put (')'); + C := Next (C); + if C /= No_Element then + Ada.Text_IO.Put (','); + end if; + Ada.Text_IO.New_Line; + end loop; + Ada.Text_IO.Put_Line ("}"); + end Print; + + Source : Polygon; + Clipper : Polygon; + Result : Polygon; +begin + Source.Append ((50.0, 150.0)); + Source.Append ((200.0, 50.0)); + Source.Append ((350.0, 150.0)); + Source.Append ((350.0, 300.0)); + Source.Append ((250.0, 300.0)); + Source.Append ((200.0, 250.0)); + Source.Append ((150.0, 350.0)); + Source.Append ((100.0, 250.0)); + Source.Append ((100.0, 200.0)); + Clipper.Append ((100.0, 100.0)); + Clipper.Append ((300.0, 100.0)); + Clipper.Append ((300.0, 300.0)); + Clipper.Append ((100.0, 300.0)); + Result := Clip (Source, Clipper); + Print (Result); +end Main; diff --git a/Task/Sutherland-Hodgman-polygon-clipping/BBC-BASIC/sutherland-hodgman-polygon-clipping.bbc b/Task/Sutherland-Hodgman-polygon-clipping/BBC-BASIC/sutherland-hodgman-polygon-clipping.bbc new file mode 100644 index 0000000000..2bfa95a3ed --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/BBC-BASIC/sutherland-hodgman-polygon-clipping.bbc @@ -0,0 +1,77 @@ + VDU 23,22,200;200;8,16,16,128 + VDU 23,23,2;0;0;0; + + DIM SubjPoly{(8) x, y} + DIM ClipPoly{(3) x, y} + FOR v% = 0 TO 8 : READ SubjPoly{(v%)}.x, SubjPoly{(v%)}.y : NEXT + DATA 50,150,200,50,350,150,350,300,250,300,200,250,150,350,100,250,100,200 + FOR v% = 0 TO 3 : READ ClipPoly{(v%)}.x, ClipPoly{(v%)}.y : NEXT + DATA 100,100, 300,100, 300,300, 100,300 + + GCOL 4 : PROCplotpoly(SubjPoly{()}, 9) + GCOL 1 : PROCplotpoly(ClipPoly{()}, 4) + nvert% = FNsutherland_hodgman(SubjPoly{()}, ClipPoly{()}, Clipped{()}) + GCOL 2 : PROCplotpoly(Clipped{()}, nvert%) + END + + DEF FNsutherland_hodgman(subj{()}, clip{()}, RETURN out{()}) + LOCAL i%, j%, n%, o%, p1{}, p2{}, s{}, e{}, p{}, inp{()} + DIM p1{x,y}, p2{x,y}, s{x,y}, e{x,y}, p{x,y} + n% = DIM(subj{()},1) + DIM(clip{()},1) + DIM inp{(n%) x, y}, out{(n%) x,y} + FOR o% = 0 TO DIM(subj{()},1) : out{(o%)} = subj{(o%)} : NEXT + p1{} = clip{(DIM(clip{()},1))} + FOR i% = 0 TO DIM(clip{()},1) + p2{} = clip{(i%)} + FOR n% = 0 TO o% - 1 : inp{(n%)} = out{(n%)} : NEXT : o% = 0 + IF n% >= 2 THEN + s{} = inp{(n% - 1)} + FOR j% = 0 TO n% - 1 + e{} = inp{(j%)} + IF FNside(e{}, p1{}, p2{}) THEN + IF NOT FNside(s{}, p1{}, p2{}) THEN + PROCintersection(p1{}, p2{}, s{}, e{}, p{}) + out{(o%)} = p{} + o% += 1 + ENDIF + out{(o%)} = e{} + o% += 1 + ELSE + IF FNside(s{}, p1{}, p2{}) THEN + PROCintersection(p1{}, p2{}, s{}, e{}, p{}) + out{(o%)} = p{} + o% += 1 + ENDIF + ENDIF + s{} = e{} + NEXT + ENDIF + p1{} = p2{} + NEXT i% + = o% + + REM Which side of the line p1-p2 is the point p? + DEF FNside(p{}, p1{}, p2{}) + = (p2.x - p1.x) * (p.y - p1.y) > (p2.y - p1.y) * (p.x - p1.x) + + REM Find the intersection of two lines p1-p2 and p3-p4 + DEF PROCintersection(p1{}, p2{}, p3{}, p4{}, p{}) + LOCAL a{}, b{}, k, l, m : DIM a{x,y}, b{x,y} + a.x = p1.x - p2.x : a.y = p1.y - p2.y + b.x = p3.x - p4.x : b.y = p3.y - p4.y + k = p1.x * p2.y - p1.y * p2.x + l = p3.x * p4.y - p3.y * p4.x + m = 1 / (a.x * b.y - a.y * b.x) + p.x = m * (k * b.x - l * a.x) + p.y = m * (k * b.y - l * a.y) + ENDPROC + + REM plot a polygon + DEF PROCplotpoly(poly{()}, n%) + LOCAL i% + MOVE poly{(0)}.x, poly{(0)}.y + FOR i% = 1 TO n%-1 + DRAW poly{(i%)}.x, poly{(i%)}.y + NEXT + DRAW poly{(0)}.x, poly{(0)}.y + ENDPROC diff --git a/Task/Sutherland-Hodgman-polygon-clipping/C/sutherland-hodgman-polygon-clipping.c b/Task/Sutherland-Hodgman-polygon-clipping/C/sutherland-hodgman-polygon-clipping.c new file mode 100644 index 0000000000..05fcb0dd66 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/C/sutherland-hodgman-polygon-clipping.c @@ -0,0 +1,180 @@ +#include +#include +#include + +typedef struct { double x, y; } vec_t, *vec; + +inline double dot(vec a, vec b) +{ + return a->x * b->x + a->y * b->y; +} + +inline double cross(vec a, vec b) +{ + return a->x * b->y - a->y * b->x; +} + +inline vec vsub(vec a, vec b, vec res) +{ + res->x = a->x - b->x; + res->y = a->y - b->y; + return res; +} + +/* tells if vec c lies on the left side of directed edge a->b + * 1 if left, -1 if right, 0 if colinear + */ +int left_of(vec a, vec b, vec c) +{ + vec_t tmp1, tmp2; + double x; + vsub(b, a, &tmp1); + vsub(c, b, &tmp2); + x = cross(&tmp1, &tmp2); + return x < 0 ? -1 : x > 0; +} + +int line_sect(vec x0, vec x1, vec y0, vec y1, vec res) +{ + vec_t dx, dy, d; + vsub(x1, x0, &dx); + vsub(y1, y0, &dy); + vsub(x0, y0, &d); + /* x0 + a dx = y0 + b dy -> + x0 X dx = y0 X dx + b dy X dx -> + b = (x0 - y0) X dx / (dy X dx) */ + double dyx = cross(&dy, &dx); + if (!dyx) return 0; + dyx = cross(&d, &dx) / dyx; + if (dyx <= 0 || dyx >= 1) return 0; + + res->x = y0->x + dyx * dy.x; + res->y = y0->y + dyx * dy.y; + return 1; +} + +/* === polygon stuff === */ +typedef struct { int len, alloc; vec v; } poly_t, *poly; + +poly poly_new() +{ + poly p = malloc(sizeof(poly_t)); + p->len = p->alloc = 0; + p->v = 0; + return p; +} + +void poly_free(poly p) +{ + if (p->alloc) { + free(p->v); + free(p); + } +} + +void poly_append(poly p, vec v) +{ + if (p->len >= p->alloc) { + p->alloc *= 2; + if (!p->alloc) p->alloc = 4; + p->v = realloc(p->v, sizeof(vec_t) * p->alloc); + } + p->v[p->len++] = *v; +} + +/* this works only if all of the following are true: + * 1. poly has no colinear edges; + * 2. poly has no duplicate vertices; + * 3. poly has at least three vertices; + * 4. poly is convex (implying 3). +*/ +int poly_winding(poly p) +{ + return left_of(p->v, p->v + 1, p->v + 2); +} + +void poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res) +{ + int i, side0, side1; + vec_t tmp; + vec v0 = sub->v + sub->len - 1, v1; + res->len = 0; + + side0 = left_of(x0, x1, v0); + if (side0 != -left) poly_append(res, v0); + + for (i = 0; i < sub->len; i++) { + v1 = sub->v + i; + side1 = left_of(x0, x1, v1); + if (side0 + side1 == 0 && side0) + /* last point and current straddle the edge */ + if (line_sect(x0, x1, v0, v1, &tmp)) + poly_append(res, &tmp); + if (i == sub->len - 1) break; + if (side1 != -left) poly_append(res, v1); + v0 = v1; + side0 = side1; + } +} + +poly poly_clip(poly sub, poly clip) +{ + int i; + poly p1 = poly_new(), p2 = poly_new(), tmp; + + int dir = poly_winding(clip); + poly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2); + for (i = 0; i < clip->len - 1; i++) { + tmp = p2; p2 = p1; p1 = tmp; + poly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2); + } + + poly_free(p1); + return p2; +} + +int main() +{ + int i; + vec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}}; + //vec_t c[] = {{100,300}, {300,300}, {300,100}, {100,100}}; + vec_t s[] = { {50,150}, {200,50}, {350,150}, + {350,300},{250,300},{200,250}, + {150,350},{100,250},{100,200}}; +#define clen (sizeof(c)/sizeof(vec_t)) +#define slen (sizeof(s)/sizeof(vec_t)) + poly_t clipper = {clen, 0, c}; + poly_t subject = {slen, 0, s}; + + poly res = poly_clip(&subject, &clipper); + + for (i = 0; i < res->len; i++) + printf("%g %g\n", res->v[i].x, res->v[i].y); + + /* long and arduous EPS printout */ + FILE * eps = fopen("test.eps", "w"); + fprintf(eps, "%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n" + "/l {lineto} def /m{moveto} def /s{setrgbcolor} def" + "/c {closepath} def /gs {fill grestore stroke} def\n"); + fprintf(eps, "0 setlinewidth %g %g m ", c[0].x, c[0].y); + for (i = 1; i < clen; i++) + fprintf(eps, "%g %g l ", c[i].x, c[i].y); + fprintf(eps, "c .5 0 0 s gsave 1 .7 .7 s gs\n"); + + fprintf(eps, "%g %g m ", s[0].x, s[0].y); + for (i = 1; i < slen; i++) + fprintf(eps, "%g %g l ", s[i].x, s[i].y); + fprintf(eps, "c 0 .2 .5 s gsave .4 .7 1 s gs\n"); + + fprintf(eps, "2 setlinewidth [10 8] 0 setdash %g %g m ", + res->v[0].x, res->v[0].y); + for (i = 1; i < res->len; i++) + fprintf(eps, "%g %g l ", res->v[i].x, res->v[i].y); + fprintf(eps, "c .5 0 .5 s gsave .7 .3 .8 s gs\n"); + + fprintf(eps, "%%%%EOF"); + fclose(eps); + printf("test.eps written\n"); + + return 0; +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d new file mode 100644 index 0000000000..706f508c05 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/D/sutherland-hodgman-polygon-clipping.d @@ -0,0 +1,119 @@ +import std.stdio, std.array, std.range, std.typecons; + +struct Vec2 { // To be replaced with Phobos code. + double x, y; + + Vec2 opBinary(string op="-")(in Vec2 other) const pure nothrow { + return Vec2(this.x - other.x, this.y - other.y); + } + + typeof(x) cross(in Vec2 other) const pure nothrow { + return this.x * other.y - this.y * other.x; + } +} + +immutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon) +/*pure nothrow*/ in { + assert(subjectPolygon.length > 1); + assert(clipPolygon.length > 1); + // Probably clipPolygon needs to be convex and probably + // its vertices need to be listed in a direction. +} out(result) { + assert(result.length > 1); +} body { + alias Tuple!(Vec2,"p", Vec2,"q") Edge; + + static bool isInside(in Vec2 p, in Edge cle) pure nothrow { + return (cle.q.x - cle.p.x) * (p.y - cle.p.y) > + (cle.q.y - cle.p.y) * (p.x - cle.p.x); + } + + static Vec2 intersection(in Edge se, in Edge cle) pure nothrow { + immutable dc = cle.p - cle.q; + immutable dp = se.p - se.q; + immutable n1 = cle.p.cross(cle.q); + immutable n2 = se.p.cross(se.q); + immutable n3 = 1.0 / dc.cross(dp); + return Vec2((n1 * dp.x - n2 * dc.x) * n3, + (n1 * dp.y - n2 * dc.y) * n3); + } + + // How much slower is this compared to lower-level code? + static edges(in Vec2[] poly) /*pure nothrow*/ { + return poly[$ - 1 .. $].chain(poly).zip(poly); + } + + // Not nothrow. Appender? + immutable(Vec2)[] result = subjectPolygon.idup; + + foreach (immutable Edge clipEdge; edges(clipPolygon)) { + immutable inputList = result; + result.clear(); + foreach (immutable Edge inEdge; edges(inputList)) { + if (isInside(inEdge.q, clipEdge)) { + if (!isInside(inEdge.p, clipEdge)) + result ~= intersection(inEdge, clipEdge); + result ~= inEdge.q; + } else if (isInside(inEdge.p, clipEdge)) + result ~= intersection(inEdge, clipEdge); + } + } + + return result; +} + +// Code adapted from the C version. +void saveEPSImage(in string fileName, in Vec2[] subjPoly, + in Vec2[] clipPoly, in Vec2[] clipped) +in { + assert(!fileName.empty); + assert(subjPoly.length > 1); + assert(clipPoly.length > 1); + assert(clipped.length > 1); +} body { + auto eps = File(fileName, "w"); + + // The image bounding box is hard-coded, not computed. + eps.writeln( +"%%!PS-Adobe-3.0 +%%%%BoundingBox: 40 40 360 360 +/l {lineto} def +/m {moveto} def +/s {setrgbcolor} def +/c {closepath} def +/gs {fill grestore stroke} def +"); + + eps.writef("0 setlinewidth %g %g m ", clipPoly[0].tupleof); + foreach (immutable cl; clipPoly[1 .. $]) + eps.writef("%g %g l ", cl.tupleof); + eps.writefln("c 0.5 0 0 s gsave 1 0.7 0.7 s gs"); + + eps.writef("%g %g m ", subjPoly[0].tupleof); + foreach (immutable s; subjPoly[1 .. $]) + eps.writef("%g %g l ", s.tupleof); + eps.writefln("c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs"); + + eps.writef("2 setlinewidth [10 8] 0 setdash %g %g m ", + clipped[0].tupleof); + foreach (immutable c; clipped[1 .. $]) + eps.writef("%g %g l ", c.tupleof); + eps.writefln("c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs"); + + eps.writefln("%%%%EOF"); + eps.close(); + writeln(fileName, " written."); +} + +void main() { + alias V = Vec2; + immutable subjectPolygon = [V(50, 150), V(200, 50), V(350, 150), + V(350, 300), V(250, 300), V(200, 250), + V(150, 350), V(100, 250), V(100, 200)]; + immutable clippingPolygon = [V(100, 100), V(300, 100), + V(300, 300), V(100, 300)]; + immutable clipped = subjectPolygon.clip(clippingPolygon); + writefln("%(%s\n%)", clipped); + saveEPSImage("sutherland_hodgman_clipping_out.eps", + subjectPolygon, clippingPolygon, clipped); +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Go/sutherland-hodgman-polygon-clipping.go b/Task/Sutherland-Hodgman-polygon-clipping/Go/sutherland-hodgman-polygon-clipping.go new file mode 100644 index 0000000000..db401a6340 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Go/sutherland-hodgman-polygon-clipping.go @@ -0,0 +1,49 @@ +package main + +import "fmt" + +type point struct { + x, y float32 +} + +var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, + {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} + +var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} + +func main() { + var cp1, cp2, s, e point + inside := func(p point) bool { + return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) + } + intersection := func() (p point) { + dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y + dpx, dpy := s.x-e.x, s.y-e.y + n1 := cp1.x*cp2.y - cp1.y*cp2.x + n2 := s.x*e.y - s.y*e.x + n3 := 1 / (dcx*dpy - dcy*dpx) + p.x = (n1*dpx - n2*dcx) * n3 + p.y = (n1*dpy - n2*dcy) * n3 + return + } + outputList := subjectPolygon + cp1 = clipPolygon[len(clipPolygon)-1] + for _, cp2 = range clipPolygon { // WP clipEdge is cp1,cp2 here + inputList := outputList + outputList = nil + s = inputList[len(inputList)-1] + for _, e = range inputList { + if inside(e) { + if !inside(s) { + outputList = append(outputList, intersection()) + } + outputList = append(outputList, e) + } else if inside(s) { + outputList = append(outputList, intersection()) + } + s = e + } + cp1 = cp2 + } + fmt.Println(outputList) +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-1.hs b/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-1.hs new file mode 100644 index 0000000000..58f88f26af --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-1.hs @@ -0,0 +1,51 @@ +module SuthHodgClip (clipTo) where + +import Data.List + +type Pt a = (a, a) +type Ln a = (Pt a, Pt a) +type Poly a = [Pt a] + +-- Return a polygon from a list of points. +polyFrom ps = last ps : ps + +-- Return a list of lines from a list of points. +linesFrom pps@(_:ps) = zip pps ps + +-- Return true if the point (x,y) is on or to the left of the oriented line +-- defined by (px,py) and (qx,qy). +(.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool +(x,y) .| ((px,py),(qx,qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px) + +-- Return the intersection of two lines. +(><) :: Fractional a => Ln a -> Ln a -> Pt a +((x1,y1),(x2,y2)) >< ((x3,y3),(x4,y4)) = + let (r,s) = (x1*y2-y1*x2, x3*y4-y3*x4) + (t,u,v,w) = (x1-x2, y3-y4, y1-y2, x3-x4) + d = t*u-v*w + in ((r*w-t*s)/d, (r*u-v*s)/d) + +-- Intersect the line segment (p0,p1) with the clipping line's left halfspace, +-- returning the point closest to p1. In the special case where p0 lies outside +-- the halfspace and p1 lies inside we return both the intersection point and +-- p1. This ensures we will have the necessary segment along the clipping line. +(-|) :: (Fractional a, Ord a) => Ln a -> Ln a -> [Pt a] +ln@(p0, p1) -| clipLn = + case (p0 .| clipLn, p1 .| clipLn) of + (False, False) -> [] + (False, True) -> [isect, p1] + (True, False) -> [isect] + (True, True) -> [p1] + where isect = ln >< clipLn + +-- Intersect the polygon with the clipping line's left halfspace. +(<|) :: (Fractional a, Ord a) => Poly a -> Ln a -> Poly a +poly <| clipLn = polyFrom $ concatMap (-| clipLn) (linesFrom poly) + +-- Intersect a target polygon with a clipping polygon. The latter is assumed to +-- be convex. +clipTo :: (Fractional a, Ord a) => [Pt a] -> [Pt a] -> [Pt a] +targPts `clipTo` clipPts = + let targPoly = polyFrom targPts + clipLines = linesFrom (polyFrom clipPts) + in foldl' (<|) targPoly clipLines diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-2.hs b/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-2.hs new file mode 100644 index 0000000000..fd6e9cd7be --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Haskell/sutherland-hodgman-polygon-clipping-2.hs @@ -0,0 +1,31 @@ +import Graphics.HGL +import SuthHodgClip + +targPts = [( 50,150), (200, 50), (350,150), (350,300), (250,300), + (200,250), (150,350), (100,250), (100,200)] :: [(Float,Float)] +clipPts = [(100,100), (300,100), (300,300), (100,300)] :: [(Float,Float)] + +toInts = map (\(a,b) -> (round a, round b)) +complete xs = last xs : xs + +drawSolid w c = drawInWindow w . withRGB c . polygon +drawLines w p = drawInWindow w . withPen p . polyline . toInts . complete + +blue = RGB 0x99 0x99 0xff +green = RGB 0x99 0xff 0x99 +pink = RGB 0xff 0x99 0x99 +white = RGB 0xff 0xff 0xff + +main = do + let resPts = targPts `clipTo` clipPts + sz = 400 + win = [(0,0), (sz,0), (sz,sz), (0,sz)] + runWindow "Sutherland-Hodgman Polygon Clipping" (sz,sz) $ \w -> do + print $ toInts resPts + penB <- createPen Solid 3 blue + penP <- createPen Solid 5 pink + drawSolid w white win + drawLines w penB targPts + drawLines w penP clipPts + drawSolid w green $ toInts resPts + getKey w diff --git a/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-1.j b/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-1.j new file mode 100644 index 0000000000..7be5b543c5 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-1.j @@ -0,0 +1,25 @@ +NB. assumes counterclockwise orientation. +NB. determine whether point y is inside edge x. +isinside=:0< [:-/ .* {.@[ -~"1 {:@[,:] + +NB. (p0,:p1) intersection (p2,:p3) +intersection=:|:@[ (+/ .* (,-.)) [:{. ,.&(-~/) %.~ -&{: + +SutherlandHodgman=:4 :0 NB. clip S-H subject + clip=.2 ]\ (,{.) x + subject=.y + for_edge. clip do. + S=.{:input=.subject + subject=.0 2$0 + for_E. input do. + if. edge isinside E do. + if. -.edge isinside S do. + subject=.subject,edge intersection S,:E end. + subject=.subject,E + elseif. edge isinside S do. + subject=.subject,edge intersection S,:E end. + S=.E + end. + end. + subject +) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-2.j b/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-2.j new file mode 100644 index 0000000000..ba0646e612 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/J/sutherland-hodgman-polygon-clipping-2.j @@ -0,0 +1,13 @@ + subject=: 50 150,200 50,350 150,350 300,250 300,200 250,150 350,100 250,:100 200 + clip=: 100 100,300 100,300 300,:100 300 + clip SutherlandHodgman subject +100 116.667 +125 100 +275 100 +300 116.667 +300 300 +250 300 +200 250 +175 300 +125 300 +100 250 diff --git a/Task/Sutherland-Hodgman-polygon-clipping/JavaScript/sutherland-hodgman-polygon-clipping.js b/Task/Sutherland-Hodgman-polygon-clipping/JavaScript/sutherland-hodgman-polygon-clipping.js new file mode 100644 index 0000000000..f06f9238ad --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/JavaScript/sutherland-hodgman-polygon-clipping.js @@ -0,0 +1,69 @@ + + + + + + + diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-1.lua b/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-1.lua new file mode 100644 index 0000000000..ef1a9d1737 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-1.lua @@ -0,0 +1,62 @@ +subjectPolygon = { + {50, 150}, {200, 50}, {350, 150}, {350, 300}, + {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200} +} + +clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}} + +function inside(p, cp1, cp2) + return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) +end + +function intersection(cp1, cp2, s, e) + local dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y + local dpx, dpy = s.x-e.x, s.y-e.y + local n1 = cp1.x*cp2.y - cp1.y*cp2.x + local n2 = s.x*e.y - s.y*e.x + local n3 = 1 / (dcx*dpy - dcy*dpx) + local x = (n1*dpx - n2*dcx) * n3 + local y = (n1*dpy - n2*dcy) * n3 + return {x=x, y=y} +end + +function clip(subjectPolygon, clipPolygon) + local outputList = subjectPolygon + local cp1 = clipPolygon[#clipPolygon] + for _, cp2 in ipairs(clipPolygon) do -- WP clipEdge is cp1,cp2 here + local inputList = outputList + outputList = {} + local s = inputList[#inputList] + for _, e in ipairs(inputList) do + if inside(e, cp1, cp2) then + if not inside(s, cp1, cp2) then + outputList[#outputList+1] = intersection(cp1, cp2, s, e) + end + outputList[#outputList+1] = e + elseif inside(s, cp1, cp2) then + outputList[#outputList+1] = intersection(cp1, cp2, s, e) + end + s = e + end + cp1 = cp2 + end + return outputList +end + +function main() + local function mkpoints(t) + for i, p in ipairs(t) do + p.x, p.y = p[1], p[2] + end + end + mkpoints(subjectPolygon) + mkpoints(clipPolygon) + + local outputList = clip(subjectPolygon, clipPolygon) + + for _, p in ipairs(outputList) do + print(('{%f, %f},'):format(p.x, p.y)) + end +end + +main() diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-2.lua b/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-2.lua new file mode 100644 index 0000000000..1221907fed --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Lua/sutherland-hodgman-polygon-clipping-2.lua @@ -0,0 +1,10 @@ +{100.000000, 116.666667}, +{125.000000, 100.000000}, +{275.000000, 100.000000}, +{300.000000, 116.666667}, +{300.000000, 300.000000}, +{250.000000, 300.000000}, +{200.000000, 250.000000}, +{175.000000, 300.000000}, +{125.000000, 300.000000}, +{100.000000, 250.000000}, diff --git a/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-1.m b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-1.m new file mode 100644 index 0000000000..806024dfc8 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-1.m @@ -0,0 +1,85 @@ +%The inputs are a table of x-y pairs for the verticies of the subject +%polygon and boundary polygon. (x values in column 1 and y values in column +%2) The output is a table of x-y pairs for the clipped version of the +%subject polygon. + +function clippedPolygon = sutherlandHodgman(subjectPolygon,clipPolygon) + +%% Helper Functions + + %computerIntersection() assumes the two lines intersect + function intersection = computeIntersection(line1,line2) + + %this is an implementation of + %http://en.wikipedia.org/wiki/Line-line_intersection + + intersection = zeros(1,2); + + detL1 = det(line1); + detL2 = det(line2); + + detL1x = det([line1(:,1),[1;1]]); + detL1y = det([line1(:,2),[1;1]]); + + detL2x = det([line2(:,1),[1;1]]); + detL2y = det([line2(:,2),[1;1]]); + + denominator = det([detL1x detL1y;detL2x detL2y]); + + intersection(1) = det([detL1 detL1x;detL2 detL2x]) / denominator; + intersection(2) = det([detL1 detL1y;detL2 detL2y]) / denominator; + + end %computeIntersection + + %inside() assumes the boundary is oriented counter-clockwise + function in = inside(point,boundary) + + pointPositionVector = [diff([point;boundary(1,:)]) 0]; + boundaryVector = [diff(boundary) 0]; + crossVector = cross(pointPositionVector,boundaryVector); + + if ( crossVector(3) <= 0 ) + in = true; + else + in = false; + end + + end %inside + +%% Sutherland-Hodgman Algorithm + + clippedPolygon = subjectPolygon; + numVerticies = size(clipPolygon,1); + clipVertexPrevious = clipPolygon(end,:); + + for clipVertex = (1:numVerticies) + + clipBoundary = [clipPolygon(clipVertex,:) ; clipVertexPrevious]; + + inputList = clippedPolygon; + + clippedPolygon = []; + previousVertex = inputList(end,:); + + for subjectVertex = (1:size(inputList,1)) + + if ( inside(inputList(subjectVertex,:),clipBoundary) ) + + if( not(inside(previousVertex,clipBoundary)) ) + subjectLineSegment = [previousVertex;inputList(subjectVertex,:)]; + clippedPolygon(end+1,1:2) = computeIntersection(clipBoundary,subjectLineSegment); + end + + clippedPolygon(end+1,1:2) = inputList(subjectVertex,:); + + elseif( inside(previousVertex,clipBoundary) ) + subjectLineSegment = [previousVertex;inputList(subjectVertex,:)]; + clippedPolygon(end+1,1:2) = computeIntersection(clipBoundary,subjectLineSegment); + end + + previousVertex = inputList(subjectVertex,:); + clipVertexPrevious = clipPolygon(clipVertex,:); + + end %for subject verticies + end %for boundary verticies +end %sutherlandHodgman diff --git a/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m new file mode 100644 index 0000000000..39bf3fe3f3 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/MATLAB/sutherland-hodgman-polygon-clipping-2.m @@ -0,0 +1,8 @@ +>> subject = [[50;200;350;350;250;200;150;100;100],[150;50;150;300;300;250;350;250;200]]; +>> clipPolygon = [[100;300;300;100],[100;100;300;300]]; +>> clippedSubject = sutherlandHodgman(subject,clipPolygon); +>> plot([subject(:,1);subject(1,1)],[subject(:,2);subject(1,2)],'blue') +>> hold on +>> plot([clipPolygon(:,1);clipPolygon(1,1)],[clipPolygon(:,2);clipPolygon(1,2)],'r') +>> patch(clippedSubject(:,1),clippedSubject(:,2),0); +>> axis square diff --git a/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ocaml b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ocaml new file mode 100644 index 0000000000..0831c157a5 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ocaml @@ -0,0 +1,51 @@ +let is_inside (x,y) ((ax,ay), (bx,by)) = + (bx -. ax) *. (y -. ay) > (by -. ay) *. (x -. ax) + +let intersection (sx,sy) (ex,ey) ((ax,ay), (bx,by)) = + let dc_x, dc_y = (ax -. bx, ay -. by) in + let dp_x, dp_y = (sx -. ex, sy -. ey) in + let n1 = ax *. by -. ay *. bx in + let n2 = sx *. ey -. sy *. ex in + let n3 = 1.0 /. (dc_x *. dp_y -. dc_y *. dp_x) in + ((n1 *. dp_x -. n2 *. dc_x) *. n3, + (n1 *. dp_y -. n2 *. dc_y) *. n3) + +let last lst = List.hd (List.rev lst) + +let polygon_iter_edges poly f init = + if poly = [] then init else + let p0 = List.hd poly in + let rec aux acc = function + | p1 :: p2 :: tl -> aux (f (p1, p2) acc) (p2 :: tl) + | p :: [] -> f (p, p0) acc + | [] -> acc + in + aux init poly + +let poly_clip subject_polygon clip_polygon = + polygon_iter_edges clip_polygon (fun clip_edge input_list -> + fst ( + List.fold_left (fun (out, s) e -> + + match (is_inside e clip_edge), (is_inside s clip_edge) with + | true, false -> (e :: (intersection s e clip_edge) :: out), e + | true, true -> (e :: out), e + | false, true -> ((intersection s e clip_edge) :: out), e + | false, false -> (out, e) + + ) ([], last input_list) input_list) + + ) subject_polygon + +let () = + let subject_polygon = + [ ( 50.0, 150.0); (200.0, 50.0); (350.0, 150.0); + (350.0, 300.0); (250.0, 300.0); (200.0, 250.0); + (150.0, 350.0); (100.0, 250.0); (100.0, 200.0); ] in + + let clip_polygon = + [ (100.0, 100.0); (300.0, 100.0); (300.0, 300.0); (100.0, 300.0) ] in + + List.iter (fun (x,y) -> + Printf.printf " (%g, %g)\n" x y; + ) (poly_clip subject_polygon clip_polygon) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ocaml b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ocaml new file mode 100644 index 0000000000..cfd5cb52b2 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ocaml @@ -0,0 +1,28 @@ +let subject_polygon = + [ ( 50.0, 150.0); (200.0, 50.0); (350.0, 150.0); + (350.0, 300.0); (250.0, 300.0); (200.0, 250.0); + (150.0, 350.0); (100.0, 250.0); (100.0, 200.0); ] + +let clip_polygon = + [ (100.0, 100.0); (300.0, 100.0); (300.0, 300.0); (100.0, 300.0) ] + +let () = + Graphics.open_graph " 400x400"; + let to_grid poly = + let round x = int_of_float (floor (x +. 0.5)) in + Array.map + (fun (x, y) -> (round x, round y)) + (Array.of_list poly) + in + let draw_poly fill stroke poly = + let p = to_grid poly in + Graphics.set_color fill; + Graphics.fill_poly p; + Graphics.set_color stroke; + Graphics.draw_poly p; + in + draw_poly Graphics.red Graphics.blue subject_polygon; + draw_poly Graphics.cyan Graphics.blue clip_polygon; + draw_poly Graphics.magenta Graphics.blue (poly_clip subject_polygon clip_polygon); + let _ = Graphics.wait_next_event [Graphics.Button_down; Graphics.Key_pressed] in + Graphics.close_graph () diff --git a/Task/Sutherland-Hodgman-polygon-clipping/PureBasic/sutherland-hodgman-polygon-clipping.purebasic b/Task/Sutherland-Hodgman-polygon-clipping/PureBasic/sutherland-hodgman-polygon-clipping.purebasic new file mode 100644 index 0000000000..6fbc27d506 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/PureBasic/sutherland-hodgman-polygon-clipping.purebasic @@ -0,0 +1,84 @@ +Structure point_f + x.f + y.f +EndStructure + +Procedure isInside(*p.point_f, *cp1.point_f, *cp2.point_f) + If (*cp2\x - *cp1\x) * (*p\y - *cp1\y) > (*cp2\y - *cp1\y) * (*p\x - *cp1\x) + ProcedureReturn 1 + EndIf +EndProcedure + +Procedure intersection(*cp1.point_f, *cp2.point_f, *s.point_f, *e.point_f, *newPoint.point_f) + Protected.point_f dc, dp + Protected.f n1, n2, n3 + dc\x = *cp1\x - *cp2\x: dc\y = *cp1\y - *cp2\y + dp\x = *s\x - *e\x: dp\y = *s\y - *e\y + n1 = *cp1\x * *cp2\y - *cp1\y * *cp2\x + n2 = *s\x * *e\y - *s\y * *e\x + n3 = 1 / (dc\x * dp\y - dc\y * dp\x) + *newPoint\x = (n1 * dp\x - n2 * dc\x) * n3: *newPoint\y = (n1 * dp\y - n2 * dc\y) * n3 +EndProcedure + +Procedure clip(List vPolygon.point_f(), List vClippedBy.point_f(), List vClippedPolygon.point_f()) + Protected.point_f cp1, cp2, s, e, newPoint + CopyList(vPolygon(), vClippedPolygon()) + If LastElement(vClippedBy()) + cp1 = vClippedBy() + + NewList vPreClipped.point_f() + ForEach vClippedBy() + cp2 = vClippedBy() + CopyList(vClippedPolygon(), vPreClipped()) + ClearList(vClippedPolygon()) + If LastElement(vPreClipped()) + s = vPreClipped() + ForEach vPreClipped() + e = vPreClipped() + If isInside(e, cp1, cp2) + If Not isInside(s, cp1, cp2) + intersection(cp1, cp2, s, e, newPoint) + AddElement(vClippedPolygon()): vClippedPolygon() = newPoint + EndIf + AddElement(vClippedPolygon()): vClippedPolygon() = e + ElseIf isInside(s, cp1, cp2) + intersection(cp1, cp2, s, e, newPoint) + AddElement(vClippedPolygon()): vClippedPolygon() = newPoint + EndIf + s = e + Next + EndIf + cp1 = cp2 + Next + EndIf +EndProcedure + +DataSection + Data.f 50,150, 200,50, 350,150, 350,300, 250,300, 200,250, 150,350, 100,250, 100,200 ;subjectPolygon's vertices (x,y) + Data.f 100,100, 300,100, 300,300, 100,300 ;clipPolygon's vertices (x,y) +EndDataSection + +NewList subjectPolygon.point_f() +For i = 1 To 9 + AddElement(subjectPolygon()) + Read.f subjectPolygon()\x + Read.f subjectPolygon()\y +Next + +NewList clipPolygon.point_f() +For i = 1 To 4 + AddElement(clipPolygon()) + Read.f clipPolygon()\x + Read.f clipPolygon()\y +Next + +NewList newPolygon.point_f() +clip(subjectPolygon(), clipPolygon(), newPolygon()) +If OpenConsole() + ForEach newPolygon() + PrintN("(" + StrF(newPolygon()\x, 2) + ", " + StrF(newPolygon()\y, 2) + ")") + Next + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Python/sutherland-hodgman-polygon-clipping.py b/Task/Sutherland-Hodgman-polygon-clipping/Python/sutherland-hodgman-polygon-clipping.py new file mode 100644 index 0000000000..11a6270a8a --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Python/sutherland-hodgman-polygon-clipping.py @@ -0,0 +1,32 @@ +def clip(subjectPolygon, clipPolygon): + def inside(p): + return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]) + + def computeIntersection(): + dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ] + dp = [ s[0] - e[0], s[1] - e[1] ] + n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0] + n2 = s[0] * e[1] - s[1] * e[0] + n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]) + return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3] + + outputList = subjectPolygon + cp1 = clipPolygon[-1] + + for clipVertex in clipPolygon: + cp2 = clipVertex + inputList = outputList + outputList = [] + s = inputList[-1] + + for subjectVertex in inputList: + e = subjectVertex + if inside(e): + if not inside(s): + outputList.append(computeIntersection()) + outputList.append(e) + elif inside(s): + outputList.append(computeIntersection()) + s = e + cp1 = cp2 + return(outputList) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb b/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb new file mode 100644 index 0000000000..b22457c63a --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Ruby/sutherland-hodgman-polygon-clipping.rb @@ -0,0 +1,49 @@ +Point = Struct.new(:x,:y) + +def sutherland_hodgman subjectPolygon, clipPolygon + # These inner functions reduce the argument passing to + # _inside_ and _intersection_. + cp1, cp2, e, s = nil + inside = proc do |p| + next (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) + end + intersection = proc do + dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y + dpx, dpy = s.x-e.x, s.y-e.y + n1 = cp1.x*cp2.y - cp1.y*cp2.x + n2 = s.x*e.y - s.y*e.x + n3 = 1.0 / (dcx*dpy - dcy*dpx) + next Point.new((n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3) + end + + outputList = subjectPolygon + cp1 = clipPolygon.last + clipPolygon.each do |point| + cp2 = point + inputList = outputList + outputList = [] + s = inputList.last + inputList.each do |point| + e = point + if inside[e] + outputList << intersection[] if !inside[s] + outputList << e + elsif inside[s] + outputList << intersection[] + end + s = e + end + cp1 = cp2 + end + outputList +end + +$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], + [250, 300], [200, 250], [150, 350], [100, 250], + [100, 200]].collect{|pnt| Point.new(*pnt)} + +$clipPolygon = [[100, 100], [300, 100], [300, 300], + [100, 300]].collect{|pnt| Point.new(*pnt)} + +puts sutherland_hodgman($subjectPolygon, $clipPolygon).collect{|pnt| + "(#{pnt.x},#{pnt.y})"}.join(", ") diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-1.tcl b/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-1.tcl new file mode 100644 index 0000000000..7a7e2042e9 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-1.tcl @@ -0,0 +1,121 @@ +# Find intersection of an arbitrary polygon with a convex one. +package require Tcl 8.6 + +# Does the path (x0,y0)->(x1,y1)->(x2,y2) turn clockwise +# or counterclockwise? +proc cw {x0 y0 x1 y1 x2 y2} { + set dx1 [expr {$x1 - $x0}]; set dy1 [expr {$y1 - $y0}] + set dx2 [expr {$x2 - $x0}]; set dy2 [expr {$y2 - $y0}] + # (0,0,$dx1*$dy2 - $dx2*$dy1) is the crossproduct of + # ($x1-$x0,$y1-$y0,0) and ($x2-$x0,$y2-$y0,0). + # Its z-component is positive if the turn + # is clockwise, negative if the turn is counterclockwise. + set pr1 [expr {$dx1 * $dy2}] + set pr2 [expr {$dx2 * $dy1}] + if {$pr1 > $pr2} { + # Clockwise + return 1 + } elseif {$pr1 < $pr2} { + # Counter-clockwise + return -1 + } elseif {$dx1*$dx2 < 0 || $dy1*$dy2 < 0} { + # point 0 is the middle point + return 0 + } elseif {($dx1*$dx1 + $dy1*$dy1) < ($dx2*$dx2 + $dy2+$dy2)} { + # point 1 is the middle point + return 0 + } else { + # point 2 lies on the segment joining points 0 and 1 + return 1 + } +} + +# Calculate the point of intersection of two lines +# containing the line segments (x1,y1)-(x2,y2) and (x3,y3)-(x4,y4) +proc intersect {x1 y1 x2 y2 x3 y3 x4 y4} { + set d [expr {($y4 - $y3) * ($x2 - $x1) - ($x4 - $x3) * ($y2 - $y1)}] + set na [expr {($x4 - $x3) * ($y1 - $y3) - ($y4 - $y3) * ($x1 - $x3)}] + if {$d == 0} { + return {} + } + set r [list \ + [expr {$x1 + $na * ($x2 - $x1) / $d}] \ + [expr {$y1 + $na * ($y2 - $y1) / $d}]] + return $r +} + +# Coroutine that yields the elements of a list in pairs +proc pairs {list} { + yield [info coroutine] + foreach {x y} $list { + yield [list $x $y] + } + return {} +} + +# Coroutine to clip one segment of a polygon against a line. +proc clipsegment {inside0 cx0 cy0 cx1 cy1 sx0 sy0 sx1 sy1} { + set inside1 [expr {[cw $cx0 $cy0 $cx1 $cy1 $sx1 $sy1] > 0}] + if {$inside1} { + if {!$inside0} { + set int [intersect $cx0 $cy0 $cx1 $cy1 \ + $sx0 $sy0 $sx1 $sy1] + if {[llength $int] >= 0} { + yield $int + } + } + yield [list $sx1 $sy1] + } else { + if {$inside0} { + set int [intersect $cx0 $cy0 $cx1 $cy1 \ + $sx0 $sy0 $sx1 $sy1] + if {[llength $int] >= 0} { + yield $int + } + } + } + return $inside1 +} + +# Coroutine to perform one step of Sutherland-Hodgman polygon clipping +proc clipstep {source cx0 cy0 cx1 cy1} { + yield [info coroutine] + set pt0 [{*}$source] + if {[llength $pt0] == 0} { + return + } + lassign $pt0 sx0 sy0 + set inside0 [expr {[cw $cx0 $cy0 $cx1 $cy1 $sx0 $sy0] > 0}] + set finished 0 + while {!$finished} { + set thispt [{*}$source] + if {[llength $thispt] == 0} { + set thispt $pt0 + set finished 1 + } + lassign $thispt sx1 sy1 + set inside0 [clipsegment $inside0 \ + $cx0 $cy0 $cx1 $cy1 $sx0 $sy0 $sx1 $sy1] + set sx0 $sx1 + set sy0 $sy1 + } + return {} +} + +# Perform Sutherland-Hodgman polygon clipping +proc clippoly {cpoly spoly} { + variable clipindx + set source [coroutine clipper[incr clipindx] pairs $spoly] + set cx0 [lindex $cpoly end-1] + set cy0 [lindex $cpoly end] + foreach {cx1 cy1} $cpoly { + set source [coroutine clipper[incr clipindx] \ + clipstep $source $cx0 $cy0 $cx1 $cy1] + set cx0 $cx1; set cy0 $cy1 + } + set result {} + while {[llength [set pt [{*}$source]]] > 0} { + lappend result {*}$pt + } + return $result +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-2.tcl b/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-2.tcl new file mode 100644 index 0000000000..183bb41b11 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Tcl/sutherland-hodgman-polygon-clipping-2.tcl @@ -0,0 +1,13 @@ +package require Tk + +grid [canvas .c -width 400 -height 400 -background \#ffffff] +proc demonstrate {cpoly spoly} { + set rpoly [clippoly $cpoly $spoly] + puts $rpoly + .c create polygon $cpoly -outline \#ff9999 -fill {} -width 5 + .c create polygon $spoly -outline \#9999ff -fill {} -width 3 + .c create polygon $rpoly -fill \#99ff99 -outline black -width 1 +} + +demonstrate {100 100 300 100 300 300 100 300} \ + {50 150 200 50 350 150 350 300 250 300 200 250 150 350 100 250 100 200} diff --git a/Task/Symmetric-difference/0DESCRIPTION b/Task/Symmetric-difference/0DESCRIPTION new file mode 100644 index 0000000000..a8ba5d384f --- /dev/null +++ b/Task/Symmetric-difference/0DESCRIPTION @@ -0,0 +1,27 @@ +Given two [[set]]s ''A'' and ''B'', where ''A'' contains: + +* John +* Bob +* Mary +* Serena + +and ''B'' contains: + +* Jim +* Mary +* John +* Bob + +compute + +:(A \setminus B) \cup (B \setminus A). + +That is, enumerate the items that are in ''A'' or ''B'' but not both. This set is called the [[wp:Symmetric difference|symmetric difference]] of ''A'' and ''B''. + +In other words: (A \cup B) \setminus (A \cap B) (the set of items that are in at least one of ''A'' or ''B'' minus the set of items that are in both ''A'' and ''B''). + +Optionally, give the individual differences (A \setminus B and B \setminus A) as well. + +;Notes +# If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order. +# In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their ''union''); and A ∩ B gives the set of items that are in both A and B (their ''intersection''). diff --git a/Task/Symmetric-difference/1META.yaml b/Task/Symmetric-difference/1META.yaml new file mode 100644 index 0000000000..9e130e8a7b --- /dev/null +++ b/Task/Symmetric-difference/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Discrete math diff --git a/Task/Symmetric-difference/Ada/symmetric-difference.ada b/Task/Symmetric-difference/Ada/symmetric-difference.ada new file mode 100644 index 0000000000..3793bacc3d --- /dev/null +++ b/Task/Symmetric-difference/Ada/symmetric-difference.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_XOR is + type Person is (John, Bob, Mary, Serena, Jim); + type Group is array (Person) of Boolean; + procedure Put (Set : Group) is + First : Boolean := True; + begin + for I in Set'Range loop + if Set (I) then + if First then + First := False; + else + Put (','); + end if; + Put (Person'Image (I)); + end if; + end loop; + end Put; + + A : Group := (John | Bob | Mary | Serena => True, others => False); + B : Group := (Jim | Mary | John | Bob => True, others => False); +begin + Put ("A xor B = "); Put (A xor B); New_Line; + Put ("A - B = "); Put (A and not B); New_Line; + Put ("B - A = "); Put (B and not A); New_Line; +end Test_XOR; diff --git a/Task/Symmetric-difference/AutoHotkey/symmetric-difference.ahk b/Task/Symmetric-difference/AutoHotkey/symmetric-difference.ahk new file mode 100644 index 0000000000..e7a74a4a52 --- /dev/null +++ b/Task/Symmetric-difference/AutoHotkey/symmetric-difference.ahk @@ -0,0 +1,23 @@ +setA = John, Bob, Mary, Serena +setB = Jim, Mary, John, Bob +MsgBox,, Singles, % SymmetricDifference(setA, setB) + +setA = John, Serena, Bob, Mary, Serena +setB = Jim, Mary, John, Jim, Bob +MsgBox,, Duplicates, % SymmetricDifference(setA, setB) + +;--------------------------------------------------------------------------- +SymmetricDifference(A, B) { ; returns the symmetric difference of A and B +;--------------------------------------------------------------------------- + StringSplit, A_, A, `,, %A_Space% + Loop, %A_0% + If Not InStr(B, A_%A_Index%) + And Not InStr(Result, A_%A_Index%) + Result .= A_%A_Index% ", " + StringSplit, B_, B, `,, %A_Space% + Loop, %B_0% + If Not InStr(A, B_%A_Index%) + And Not InStr(Result, B_%A_Index%) + Result .= B_%A_Index% ", " + Return, SubStr(Result, 1, -2) +} diff --git a/Task/Symmetric-difference/BBC-BASIC/symmetric-difference.bbc b/Task/Symmetric-difference/BBC-BASIC/symmetric-difference.bbc new file mode 100644 index 0000000000..a34e0b14f6 --- /dev/null +++ b/Task/Symmetric-difference/BBC-BASIC/symmetric-difference.bbc @@ -0,0 +1,23 @@ + DIM list$(4) + list$() = "Bob", "Jim", "John", "Mary", "Serena" + + setA% = %11101 + PRINT "Set A: " FNlistset(list$(), setA%) + setB% = %01111 + PRINT "Set B: " FNlistset(list$(), setB%) + + REM Compute symmetric difference: + setC% = setA% EOR setB% + PRINT '"Symmetric difference: " FNlistset(list$(), setC%) + + REM Optional: + PRINT "Set A \ Set B: " FNlistset(list$(), setA% AND NOT setB%) + PRINT "Set B \ Set A: " FNlistset(list$(), setB% AND NOT setA%) + END + + DEF FNlistset(list$(), set%) + LOCAL i%, o$ + FOR i% = 0 TO 31 + IF set% AND 1 << i% o$ += list$(i%) + ", " + NEXT + = LEFT$(LEFT$(o$)) diff --git a/Task/Symmetric-difference/Bracmat/symmetric-difference-1.bracmat b/Task/Symmetric-difference/Bracmat/symmetric-difference-1.bracmat new file mode 100644 index 0000000000..8c6d484a31 --- /dev/null +++ b/Task/Symmetric-difference/Bracmat/symmetric-difference-1.bracmat @@ -0,0 +1,16 @@ +(SymmetricDifference= + A B x symdiff +. !arg:(?A.?B) + & :?symdiff + & ( !A !B + : ? + ( %@?x + & ( !A:? !x ?&!B:? !x ? + | !symdiff:? !x ? + | !symdiff !x:?symdiff + ) + & ~ + ) + ? + | !symdiff + )); diff --git a/Task/Symmetric-difference/Bracmat/symmetric-difference-2.bracmat b/Task/Symmetric-difference/Bracmat/symmetric-difference-2.bracmat new file mode 100644 index 0000000000..d23efac318 --- /dev/null +++ b/Task/Symmetric-difference/Bracmat/symmetric-difference-2.bracmat @@ -0,0 +1 @@ +SymmetricDifference$(john serena bob mary serena.jim mary john jim bob) diff --git a/Task/Symmetric-difference/Bracmat/symmetric-difference-3.bracmat b/Task/Symmetric-difference/Bracmat/symmetric-difference-3.bracmat new file mode 100644 index 0000000000..a37a690fdb --- /dev/null +++ b/Task/Symmetric-difference/Bracmat/symmetric-difference-3.bracmat @@ -0,0 +1 @@ +serena jim diff --git a/Task/Symmetric-difference/C++/symmetric-difference.cpp b/Task/Symmetric-difference/C++/symmetric-difference.cpp new file mode 100644 index 0000000000..a568f2dc0b --- /dev/null +++ b/Task/Symmetric-difference/C++/symmetric-difference.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +#include +#include + +using namespace std; + +int main( ) { + string setA[] = { "John", "Bob" , "Mary", "Serena" }; + string setB[] = { "Jim" , "Mary", "John", "Bob" }; + set + firstSet( setA , setA + 4 ), + secondSet( setB , setB + 4 ), + symdiff; + + set_symmetric_difference( firstSet.begin(), firstSet.end(), + secondSet.begin(), secondSet.end(), + inserter( symdiff, symdiff.end() ) ); + + copy( symdiff.begin(), symdiff.end(), ostream_iterator( cout , " " ) ); + cout << endl; + return 0; +} diff --git a/Task/Symmetric-difference/C/symmetric-difference-1.c b/Task/Symmetric-difference/C/symmetric-difference-1.c new file mode 100644 index 0000000000..d8fe9736d2 --- /dev/null +++ b/Task/Symmetric-difference/C/symmetric-difference-1.c @@ -0,0 +1,52 @@ +#include +#include + +const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" }; +const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" }; + +#define LEN(x) sizeof(x)/sizeof(x[0]) + +/* null duplicate items */ +void uniq(const char *x[], int len) +{ + int i, j; + for (i = 0; i < len; i++) + for (j = i + 1; j < len; j++) + if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0; +} + +int in_set(const char *const x[], int len, const char *match) +{ + int i; + for (i = 0; i < len; i++) + if (x[i] && !strcmp(x[i], match)) + return 1; + return 0; +} + +/* x - y */ +void show_diff(const char *const x[], int lenx, const char *const y[], int leny) +{ + int i; + for (i = 0; i < lenx; i++) + if (x[i] && !in_set(y, leny, x[i])) + printf(" %s\n", x[i]); +} + +/* X ^ Y */ +void show_sym_diff(const char *const x[], int lenx, const char *const y[], int leny) +{ + show_diff(x, lenx, y, leny); + show_diff(y, leny, x, lenx); +} + +int main() +{ + uniq(A, LEN(A)); + uniq(B, LEN(B)); + printf("A \\ B:\n"); show_diff(A, LEN(A), B, LEN(B)); + printf("\nB \\ A:\n"); show_diff(B, LEN(B), A, LEN(A)); + printf("\nA ^ B:\n"); show_sym_diff(A, LEN(A), B, LEN(B)); + + return 0; +} diff --git a/Task/Symmetric-difference/C/symmetric-difference-2.c b/Task/Symmetric-difference/C/symmetric-difference-2.c new file mode 100644 index 0000000000..41012a2627 --- /dev/null +++ b/Task/Symmetric-difference/C/symmetric-difference-2.c @@ -0,0 +1,135 @@ +#include +#include +#include +#include + +const char *mary="Mary"; +const char *bob="Bob"; +const char *jim="Jim"; +const char *john="John"; +const char *serena="Serena"; + +const char *setA[] = {john,bob,mary,serena}; +const char *setB[] = {jim,mary,john,bob}; + +#define XSET(j) j, (sizeof(j)/sizeof(*j)) +#define TALLOC(n,typ) malloc(n*sizeof(typ)) + +typedef enum { + esdDIFFERENCE, + esdSYMMETRIC } EsdFunction; +/** * * * * * * * * * * * * * * * * * * * * + * return value is difference or symmetric difference set + * its size is returned in sym_size + * f determinse whether it is a symmetric difference, or normal difference + * * * * * * * * * * * * * * * * * * * * **/ +const char ** symmdiff( int *sym_size, EsdFunction f, const char *setA[], int setAsize, const char *setB[], int setBsize) +{ + int union_size; + int max_union_size; + int diff_size; + const char **union_set; + const char **diff_set; + int *union_xor; + int ix, ixu; + + max_union_size = setAsize + setBsize; + union_set = TALLOC(max_union_size, const char *); + union_xor = TALLOC(max_union_size, int); + + /* I'm assuming here that setA has no duplicates, + * i.e. is a set in mathematical sense */ + for (ix=0; ix0; i--) { + e = list[i]; + for (j = i-1; j>=0; j--) { + if (strcmp(list[j], e) == 0) { + return 0; + } + } + } + return 1; +} + +void printSet (const char *set[], int ssize) +{ + int ix; + printf(" = {"); + for (ix=0;ix !canFind(other.items,a))(items))); + } + + Set opAdd(in Set other) const /*pure nothrow*/ { + return Set(this.items ~ (other - this).items); + } +} + +Set!T symmetricDifference(T)(in Set!T left, in Set!T right) { + return (left - right) + (right - left); +} + +void main() { + immutable A = Set!string(["John", "Bob", "Mary", "Serena"]); + immutable B = Set!string(["Jim", "Mary", "John", "Bob"]); + + writeln(" A\\B: ", (A - B).items); + writeln(" B\\A: ", (B - A).items); + writeln("A symdiff B: ", symmetricDifference(A, B).items); +} diff --git a/Task/Symmetric-difference/E/symmetric-difference.e b/Task/Symmetric-difference/E/symmetric-difference.e new file mode 100644 index 0000000000..c69ee7b3ff --- /dev/null +++ b/Task/Symmetric-difference/E/symmetric-difference.e @@ -0,0 +1,5 @@ +? def symmDiff(a, b) { return (a &! b) | (b &! a) } +# value: + +? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet()) +# value: ["Jim", "Serena"].asSet() diff --git a/Task/Symmetric-difference/Eiffel/symmetric-difference.e b/Task/Symmetric-difference/Eiffel/symmetric-difference.e new file mode 100644 index 0000000000..9af5a78112 --- /dev/null +++ b/Task/Symmetric-difference/Eiffel/symmetric-difference.e @@ -0,0 +1,45 @@ +note + description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}." + URI: "http://rosettacode.org/wiki/Symmetric_difference" + +class + SYMETRIC_DIFFERENCE_EXAMPLE + +create + make + +feature {NONE} -- Initialization + + make + local + a,a1,b,b1: ARRAYED_SET [STRING] + do + create a.make (4) + create b.make (4) + a.compare_objects + b.compare_objects + a.put ("John") + a.put ("Bob") + a.put ("Mary") + a.put ("Serena") + + create a1.make (4) + a1.copy (a) + + b.put ("Jim") + b.put ("Mary") + b.put ("John") + b.put ("Bob") + + create b1.make (4) + b1.copy (b) + + a1.subtract (b1) + b.subtract (a) + a1.merge (b) + across a1 as c loop + print (" " + c.item) + end + end + +end diff --git a/Task/Symmetric-difference/Factor/symmetric-difference.factor b/Task/Symmetric-difference/Factor/symmetric-difference.factor new file mode 100644 index 0000000000..768d2a5837 --- /dev/null +++ b/Task/Symmetric-difference/Factor/symmetric-difference.factor @@ -0,0 +1,4 @@ +: symmetric-diff ( a b -- c ) + [ diff ] [ swap diff ] 2bi append ; + +{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff . diff --git a/Task/Symmetric-difference/Forth/symmetric-difference.fth b/Task/Symmetric-difference/Forth/symmetric-difference.fth new file mode 100644 index 0000000000..f05d94bf05 --- /dev/null +++ b/Task/Symmetric-difference/Forth/symmetric-difference.fth @@ -0,0 +1,23 @@ +: elm ( n -- ; one cell per set ) + [ cell 8 * 1- ] literal umin CREATE 1 swap lshift , +DOES> ( -- 2^n ) @ ; + +: universe ( u "name" -- ) + dup 0 DO I elm latest swap LOOP + CREATE dup , 0 DO , LOOP + DOES> ( n a -- ) dup @ tuck cells + + swap 0 + DO ( n a' ) + over I rshift 1 AND + IF dup @ name>string space type THEN + 1 cells - + LOOP 2drop ; + +5 universe john bob mary serena jim persons +john bob mary serena or or or +jim mary john bob or or or + +2dup xor persons +2dup -1 xor and cr persons +swap -1 xor and cr persons +cr bye diff --git a/Task/Symmetric-difference/Fortran/symmetric-difference.f b/Task/Symmetric-difference/Fortran/symmetric-difference.f new file mode 100644 index 0000000000..3dda22cd19 --- /dev/null +++ b/Task/Symmetric-difference/Fortran/symmetric-difference.f @@ -0,0 +1,22 @@ +program Symmetric_difference +implicit none + + character(6) :: a(4) = (/ "John ", "Bob ", "Mary ", "Serena" /) + character(6) :: b(4) = (/ "Jim ", "Mary ", "John ", "Bob " /) + integer :: i, j + +outer1: do i = 1, size(a) + do j = 1, i-1 + if(a(i) == a(j)) cycle outer1 ! Do not check duplicate items + end do + if(.not. any(b == a(i))) write(*,*) a(i) + end do outer1 + +outer2: do i = 1, size(b) + do j = 1, i-1 + if(b(i) == b(j)) cycle outer2 ! Do not check duplicate items + end do + if(.not. any(a == b(i))) write(*,*) b(i) + end do outer2 + +end program diff --git a/Task/Symmetric-difference/GAP/symmetric-difference.gap b/Task/Symmetric-difference/GAP/symmetric-difference.gap new file mode 100644 index 0000000000..ad073d72a8 --- /dev/null +++ b/Task/Symmetric-difference/GAP/symmetric-difference.gap @@ -0,0 +1,8 @@ +SymmetricDifference := function(a, b) + return Union(Difference(a, b), Difference(b, a)); +end; + +a := ["John", "Serena", "Bob", "Mary", "Serena"]; +b := ["Jim", "Mary", "John", "Jim", "Bob"]; +SymmetricDifference(a,b); +[ "Jim", "Serena" ] diff --git a/Task/Symmetric-difference/Go/symmetric-difference-1.go b/Task/Symmetric-difference/Go/symmetric-difference-1.go new file mode 100644 index 0000000000..103d7b2679 --- /dev/null +++ b/Task/Symmetric-difference/Go/symmetric-difference-1.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +var a = map[string]bool{"John": true, "Bob": true, "Mary": true, "Serena": true} +var b = map[string]bool{"Jim": true, "Mary": true, "John": true, "Bob": true} + +func main() { + sd := make(map[string]bool) + for e := range a { + if !b[e] { + sd[e] = true + } + } + for e := range b { + if !a[e] { + sd[e] = true + } + } + fmt.Println(sd) +} diff --git a/Task/Symmetric-difference/Go/symmetric-difference-2.go b/Task/Symmetric-difference/Go/symmetric-difference-2.go new file mode 100644 index 0000000000..01454f8007 --- /dev/null +++ b/Task/Symmetric-difference/Go/symmetric-difference-2.go @@ -0,0 +1,6 @@ +func main() { + for e := range b { + delete(a, e) + } + fmt.Println(a) +} diff --git a/Task/Symmetric-difference/Groovy/symmetric-difference-1.groovy b/Task/Symmetric-difference/Groovy/symmetric-difference-1.groovy new file mode 100644 index 0000000000..96bc6f3856 --- /dev/null +++ b/Task/Symmetric-difference/Groovy/symmetric-difference-1.groovy @@ -0,0 +1,5 @@ +def symDiff = { Set s1, Set s2 -> + assert s1 != null + assert s2 != null + (s1 + s2) - (s1.intersect(s2)) +} diff --git a/Task/Symmetric-difference/Groovy/symmetric-difference-2.groovy b/Task/Symmetric-difference/Groovy/symmetric-difference-2.groovy new file mode 100644 index 0000000000..371b6e6c21 --- /dev/null +++ b/Task/Symmetric-difference/Groovy/symmetric-difference-2.groovy @@ -0,0 +1,93 @@ +Set a = ['John', 'Serena', 'Bob', 'Mary', 'Serena'] +Set b = ['Jim', 'Mary', 'John', 'Jim', 'Bob'] + +assert a.size() == 4 +assert a == (['Bob', 'John', 'Mary', 'Serena'] as Set) +assert b.size() == 4 +assert b == (['Bob', 'Jim', 'John', 'Mary'] as Set) + +def aa = symDiff(a, a) +def ab = symDiff(a, b) +def ba = symDiff(b, a) +def bb = symDiff(b, b) + +assert aa.empty +assert bb.empty +assert ab == ba +assert ab == (['Jim', 'Serena'] as Set) +assert ab == (['Serena', 'Jim'] as Set) + +println """ +a: ${a} +b: ${b} + +Symmetric Differences +===================== +a <> a: ${aa} +a <> b: ${ab} +b <> a: ${ba} +b <> b: ${bb} + + +""" + +Set apostles = ['Matthew', 'Mark', 'Luke', 'John', 'Peter', 'Paul', 'Silas'] +Set beatles = ['John', 'Paul', 'George', 'Ringo', 'Peter', 'Stuart'] +Set csny = ['Crosby', 'Stills', 'Nash', 'Young'] +Set ppm = ['Peter', 'Paul', 'Mary'] + +def AA = symDiff(apostles, apostles) +def AB = symDiff(apostles, beatles) +def AC = symDiff(apostles, csny) +def AP = symDiff(apostles, ppm) + +def BA = symDiff(beatles, apostles) +def BB = symDiff(beatles, beatles) +def BC = symDiff(beatles, csny) +def BP = symDiff(beatles, ppm) + +def CA = symDiff(csny, apostles) +def CB = symDiff(csny, beatles) +def CC = symDiff(csny, csny) +def CP = symDiff(csny, ppm) + +def PA = symDiff(ppm, apostles) +def PB = symDiff(ppm, beatles) +def PC = symDiff(ppm, csny) +def PP = symDiff(ppm, ppm) + +assert AB == BA +assert AC == CA +assert AP == PA +assert BC == CB +assert BP == PB +assert CP == PC + +println """ +apostles: ${apostles} + beatles: ${beatles} + csny: ${csny} + ppm: ${ppm} + +Symmetric Differences +===================== +apostles <> apostles: ${AA} +apostles <> beatles: ${AB} +apostles <> csny: ${AC} +apostles <> ppm: ${AP} + +beatles <> apostles: ${BA} +beatles <> beatles: ${BB} +beatles <> csny: ${BC} +beatles <> ppm: ${BP} + +csny <> apostles: ${CA} +csny <> beatles: ${CB} +csny <> csny: ${CC} +csny <> ppm: ${CP} + +ppm <> apostles: ${PA} +ppm <> beatles: ${PB} +ppm <> csny: ${PC} +ppm <> ppm: ${PP} +""" diff --git a/Task/Symmetric-difference/Haskell/symmetric-difference-1.hs b/Task/Symmetric-difference/Haskell/symmetric-difference-1.hs new file mode 100644 index 0000000000..bf8427ceb2 --- /dev/null +++ b/Task/Symmetric-difference/Haskell/symmetric-difference-1.hs @@ -0,0 +1,8 @@ +import Data.Set + +a = fromList ["John", "Bob", "Mary", "Serena"] +b = fromList ["Jim", "Mary", "John", "Bob"] + +(-|-) :: Ord a => Set a -> Set a -> Set a +(-|-) x y = (x \\ y) `union` (y \\ x) + -- Equivalently: (x `union` y) \\ (x `intersect` y) diff --git a/Task/Symmetric-difference/Haskell/symmetric-difference-2.hs b/Task/Symmetric-difference/Haskell/symmetric-difference-2.hs new file mode 100644 index 0000000000..c4bdc75433 --- /dev/null +++ b/Task/Symmetric-difference/Haskell/symmetric-difference-2.hs @@ -0,0 +1,2 @@ +*Main> a -|- b +fromList ["Jim","Serena"] diff --git a/Task/Symmetric-difference/Haskell/symmetric-difference-3.hs b/Task/Symmetric-difference/Haskell/symmetric-difference-3.hs new file mode 100644 index 0000000000..b15d4bea91 --- /dev/null +++ b/Task/Symmetric-difference/Haskell/symmetric-difference-3.hs @@ -0,0 +1,5 @@ +*Main> a \\ b +fromList ["Serena"] + +*Main> b \\ a +fromList ["Jim"] diff --git a/Task/Symmetric-difference/HicEst/symmetric-difference.hicest b/Task/Symmetric-difference/HicEst/symmetric-difference.hicest new file mode 100644 index 0000000000..985b4d5623 --- /dev/null +++ b/Task/Symmetric-difference/HicEst/symmetric-difference.hicest @@ -0,0 +1,19 @@ +CALL SymmDiff("John,Serena,Bob,Mary,Serena,", "Jim,Mary,John,Jim,Bob,") +CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,") + +SUBROUTINE SymmDiff(set1, set2) + CHARACTER set1, set2, answer*50 + answer = " " + CALL setA_setB( set1, set2, answer ) + CALL setA_setB( set2, set1, answer ) + WRITE(Messagebox,Name) answer ! answer = "Serena,Jim," in both cases +END + +SUBROUTINE setA_setB( set1, set2, differences ) + CHARACTER set1, set2, differences, a*100 + a = set1 + EDIT(Text=a, $inLeXicon=set2) ! eg a <= $John,Serena,$Bob,$Mary,Serena, + EDIT(Text=a, Right="$", Mark1, Right=",", Mark2, Delete, DO) ! Serena,Serena, + EDIT(Text=a, Option=1, SortDelDbls=a) ! Option=1: keep case; Serena, + differences = TRIM( differences ) // a +END diff --git a/Task/Symmetric-difference/Icon/symmetric-difference.icon b/Task/Symmetric-difference/Icon/symmetric-difference.icon new file mode 100644 index 0000000000..dd4f9d3855 --- /dev/null +++ b/Task/Symmetric-difference/Icon/symmetric-difference.icon @@ -0,0 +1,19 @@ +procedure main() + +a := set(["John", "Serena", "Bob", "Mary", "Serena"]) +b := set(["Jim", "Mary", "John", "Jim", "Bob"]) + +showset("a",a) +showset("b",b) +showset("(a\\b) \xef (b\\a)",(a -- b) ++ (b -- a)) +showset("(a\\b)",a -- b) +showset("(b\\a)",b -- a) +end + + +procedure showset(n,x) +writes(n," = { ") +every writes(!x," ") +write("}") +return +end diff --git a/Task/Symmetric-difference/J/symmetric-difference-1.j b/Task/Symmetric-difference/J/symmetric-difference-1.j new file mode 100644 index 0000000000..e51653be82 --- /dev/null +++ b/Task/Symmetric-difference/J/symmetric-difference-1.j @@ -0,0 +1,11 @@ + A=: ~.;:'John Serena Bob Mary Serena' + B=: ~. ;:'Jim Mary John Jim Bob' + + (A-.B) , (B-.A) NB. Symmetric Difference +┌──────┬───┐ +│Serena│Jim│ +└──────┴───┘ + A (-. , -.~) B NB. Tacit equivalent +┌──────┬───┐ +│Serena│Jim│ +└──────┴───┘ diff --git a/Task/Symmetric-difference/J/symmetric-difference-2.j b/Task/Symmetric-difference/J/symmetric-difference-2.j new file mode 100644 index 0000000000..a7aa096d2c --- /dev/null +++ b/Task/Symmetric-difference/J/symmetric-difference-2.j @@ -0,0 +1,12 @@ + A -. B NB. items in A but not in B +┌──────┐ +│Serena│ +└──────┘ + A -.~ B NB. items in B but not in A +┌───┐ +│Jim│ +└───┘ + A NB. A is a sequence without duplicates +┌────┬──────┬───┬────┐ +│John│Serena│Bob│Mary│ +└────┴──────┴───┴────┘ diff --git a/Task/Symmetric-difference/J/symmetric-difference-3.j b/Task/Symmetric-difference/J/symmetric-difference-3.j new file mode 100644 index 0000000000..8e82c0d1ed --- /dev/null +++ b/Task/Symmetric-difference/J/symmetric-difference-3.j @@ -0,0 +1,4 @@ + A (, -. [ -. -.) B +┌──────┬───┐ +│Serena│Jim│ +└──────┴───┘ diff --git a/Task/Symmetric-difference/Java/symmetric-difference.java b/Task/Symmetric-difference/Java/symmetric-difference.java new file mode 100644 index 0000000000..88ae516b0d --- /dev/null +++ b/Task/Symmetric-difference/Java/symmetric-difference.java @@ -0,0 +1,44 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class SymmetricDifference { + public static void main(String[] args) { + Set setA = new HashSet(Arrays.asList("John", "Serena", "Bob", "Mary", "Serena")); + Set setB = new HashSet(Arrays.asList("Jim", "Mary", "John", "Jim", "Bob")); + + // Present our initial data set + System.out.println("In set A: " + setA); + System.out.println("In set B: " + setB); + + // Option 1: union of differences + // Get our individual differences. + Set notInSetA = new HashSet(setB); + notInSetA.removeAll(setA); + Set notInSetB = new HashSet(setA); + notInSetB.removeAll(setB); + + // The symmetric difference is the concatenation of the two individual differences + Set symmetricDifference = new HashSet(notInSetA); + symmetricDifference.addAll(notInSetB); + + // Option 2: union minus intersection + // Combine both sets + Set union = new HashSet(setA); + union.addAll(setB); + + // Get the intersection + Set intersection = new HashSet(setA); + intersection.retainAll(setB); + + // The symmetric difference is the union of the 2 sets minus the intersection + Set symmetricDifference2 = new HashSet(union); + symmetricDifference2.removeAll(intersection); + + // Present our results + System.out.println("Not in set A: " + notInSetA); + System.out.println("Not in set B: " + notInSetB); + System.out.println("Symmetric Difference: " + symmetricDifference); + System.out.println("Symmetric Difference 2: " + symmetricDifference2); + } +} diff --git a/Task/Symmetric-difference/JavaScript/symmetric-difference.js b/Task/Symmetric-difference/JavaScript/symmetric-difference.js new file mode 100644 index 0000000000..ac8d84f835 --- /dev/null +++ b/Task/Symmetric-difference/JavaScript/symmetric-difference.js @@ -0,0 +1,16 @@ +// in A but not in B +function relative_complement(A, B) { + return A.filter(function(elem) {return B.indexOf(elem) == -1}); +} + +// in A or in B but not in both +function symmetric_difference(A,B) { + return relative_complement(A,B).concat(relative_complement(B,A)); +} + +var a = ["John", "Serena", "Bob", "Mary", "Serena"].unique(); +var b = ["Jim", "Mary", "John", "Jim", "Bob"].unique(); + +print(a); +print(b); +print(symmetric_difference(a,b)); diff --git a/Task/Symmetric-difference/K/symmetric-difference.k b/Task/Symmetric-difference/K/symmetric-difference.k new file mode 100644 index 0000000000..99b0c66a27 --- /dev/null +++ b/Task/Symmetric-difference/K/symmetric-difference.k @@ -0,0 +1,10 @@ + A: ?("John";"Bob";"Mary";"Serena") + B: ?("Jim";"Mary";"John";"Bob") + + A _dvl B / in A but not in B +"Serena" + B _dvl A / in B but not in A +"Jim" + (A _dvl B;B _dvl A) / Symmetric difference +("Serena" + "Jim") diff --git a/Task/Symmetric-difference/Logo/symmetric-difference.logo b/Task/Symmetric-difference/Logo/symmetric-difference.logo new file mode 100644 index 0000000000..3b59170c5e --- /dev/null +++ b/Task/Symmetric-difference/Logo/symmetric-difference.logo @@ -0,0 +1,11 @@ +to diff :a :b [:acc []] + if empty? :a [output sentence :acc :b] + ifelse member? first :a :b ~ + [output (diff butfirst :a remove first :a :b :acc)] ~ + [output (diff butfirst :a :b lput first :a :acc)] +end + +make "a [John Bob Mary Serena] +make "b [Jim Mary John Bob] + +show diff :a :b ; [Serena Jim] diff --git a/Task/Symmetric-difference/Lua/symmetric-difference.lua b/Task/Symmetric-difference/Lua/symmetric-difference.lua new file mode 100644 index 0000000000..ba8d2224bb --- /dev/null +++ b/Task/Symmetric-difference/Lua/symmetric-difference.lua @@ -0,0 +1,19 @@ +A = { ["John"] = true, ["Bob"] = true, ["Mary"] = true, ["Serena"] = true } +B = { ["Jim"] = true, ["Mary"] = true, ["John"] = true, ["Bob"] = true } + +A_B = {} +for a in pairs(A) do + if not B[a] then A_B[a] = true end +end + +B_A = {} +for b in pairs(B) do + if not A[b] then B_A[b] = true end +end + +for a_b in pairs(A_B) do + print( a_b ) +end +for b_a in pairs(B_A) do + print( b_a ) +end diff --git a/Task/Symmetric-difference/MATLAB/symmetric-difference-1.m b/Task/Symmetric-difference/MATLAB/symmetric-difference-1.m new file mode 100644 index 0000000000..885d9997c3 --- /dev/null +++ b/Task/Symmetric-difference/MATLAB/symmetric-difference-1.m @@ -0,0 +1,5 @@ +>> [setdiff([1 2 3],[2 3 4]) setdiff([2 3 4],[1 2 3])] + +ans = + + 1 4 diff --git a/Task/Symmetric-difference/MATLAB/symmetric-difference-2.m b/Task/Symmetric-difference/MATLAB/symmetric-difference-2.m new file mode 100644 index 0000000000..c6b9f5ae40 --- /dev/null +++ b/Task/Symmetric-difference/MATLAB/symmetric-difference-2.m @@ -0,0 +1,91 @@ +function resultantSet = symmetricDifference(set1,set2) + + assert( ~xor(iscell(set1),iscell(set2)), 'Both sets must be of the same type, either cells or matricies, but not a combination of the two' ); +%% Helper function definitions + + %Define what set equality means for cell arrays + function trueFalse = equality(set1,set2) + if xor(iscell(set1),iscell(set2)) %set1 or set2 is a set and the other isn't + trueFalse = false; + return + elseif ~(iscell(set1) || iscell(set2)) %set1 and set2 are not sets + if ischar(set1) && ischar(set2) %set1 and set2 are chars or strings + trueFalse = strcmp(set1,set2); + elseif xor(ischar(set1),ischar(set2)) %set1 or set2 is a string but the other isn't + trueFalse = false; + else %set1 and set2 are not strings + if numel(set1) == numel(set2) %Since they must be matricies if the are of equal cardinality then they can be compaired + trueFalse = all((set1 == set2)); + else %If they aren't of equal cardinality then they can't be equal + trueFalse = false; + end + end + return + else %set1 and set2 are both sets + + for x = (1:numel(set1)) + trueFalse = false; + for y = (1:numel(set2)) + + %Compair the current element of set1 with every element + %in set2 + trueFalse = equality(set1{x},set2{y}); + + %If the element of set1 is equal to the current element + %of set2 remove that element from set2 and break out of + %this inner loop + if trueFalse + set2(y) = []; + break + end + end + + %If the loop completes without breaking then the current + %element of set1 is not contained in set2 therefore the two + %sets are not equal and we can return an equality of false + if (~trueFalse) + return + end + end + + %If, after checking every element in both sets, there are still + %elements in set2 then the two sets are not equivalent + if ~isempty(set2) + trueFalse = false; + end + %If the executation makes it here without the previous if + %statement evaluating to true, then this function will return + %true. + end + end %equality + + %Define the relative compliment for cell arrays + function set1 = relativeComplement(set1,set2) + + for k = (1:numel(set2)) + + if numel(set1) == 0 + return + end + + j = 1; + while j <= numel(set1) + if equality(set1{j},set2{k}) + set1(j) = []; + j = j-1; + end + j = j+1; + end + end + end %relativeComplement + +%% The Symmetric Difference Algorithm + if iscell(set1) && iscell(set2) + resultantSet = [relativeComplement(set1,set2) relativeComplement(set2,set1)]; + else + resultantSet = [setdiff(set1,set2) setdiff(set2,set1)]; + end + + resultantSet = unique(resultantSet); %Make sure there are not duplicates + +end %symmetricDifference diff --git a/Task/Symmetric-difference/MATLAB/symmetric-difference-3.m b/Task/Symmetric-difference/MATLAB/symmetric-difference-3.m new file mode 100644 index 0000000000..af7ff22b3d --- /dev/null +++ b/Task/Symmetric-difference/MATLAB/symmetric-difference-3.m @@ -0,0 +1,23 @@ +>> A = {'John','Bob','Mary','Serena'} + +A = + + 'John' 'Bob' 'Mary' 'Serena' + +>> B = {'Jim','Mary','John','Bob'} + +B = + + 'Jim' 'Mary' 'John' 'Bob' + +>> symmetricDifference(A,B) + +ans = + + 'Serena' 'Jim' %Correct + +>> symmetricDifference([1 2 3],[2 3 4]) + +ans = + + 1 4 %Correct diff --git a/Task/Symmetric-difference/Mathematica/symmetric-difference-1.math b/Task/Symmetric-difference/Mathematica/symmetric-difference-1.math new file mode 100644 index 0000000000..36044a82aa --- /dev/null +++ b/Task/Symmetric-difference/Mathematica/symmetric-difference-1.math @@ -0,0 +1 @@ +SymmetricDifference[x_List,y_List] := Join[Complement[x,Intersection[x,y]],Complement[y,Intersection[x,y]]] diff --git a/Task/Symmetric-difference/Mathematica/symmetric-difference-2.math b/Task/Symmetric-difference/Mathematica/symmetric-difference-2.math new file mode 100644 index 0000000000..bdfe2025d0 --- /dev/null +++ b/Task/Symmetric-difference/Mathematica/symmetric-difference-2.math @@ -0,0 +1 @@ +CachedSymmetricDifference[x_List,y_List] := Module[{intersect=Intersection[x,y]},Join[Complement[x,intersect],Complement[y,intersect]]] diff --git a/Task/Symmetric-difference/Maxima/symmetric-difference.maxima b/Task/Symmetric-difference/Maxima/symmetric-difference.maxima new file mode 100644 index 0000000000..f2ffa0c328 --- /dev/null +++ b/Task/Symmetric-difference/Maxima/symmetric-difference.maxima @@ -0,0 +1,4 @@ +/* builtin */ +symmdifference({"John", "Bob", "Mary", "Serena"}, + {"Jim", "Mary", "John", "Bob"}); +{"Jim", "Serena"} diff --git a/Task/Symmetric-difference/Mercury/symmetric-difference.mercury b/Task/Symmetric-difference/Mercury/symmetric-difference.mercury new file mode 100644 index 0000000000..af775edba3 --- /dev/null +++ b/Task/Symmetric-difference/Mercury/symmetric-difference.mercury @@ -0,0 +1,21 @@ +:- module symdiff. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module list, set, string. + +main(!IO) :- + A = set(["John", "Bob", "Mary", "Serena"]), + B = set(["Jim", "Mary", "John", "Bob"]), + print_set("A\\B", DiffAB @ (A `difference` B), !IO), + print_set("B\\A", DiffBA @ (B `difference` A), !IO), + print_set("A symdiff B", DiffAB `union` DiffBA, !IO). + +:- pred print_set(string::in, set(T)::in, io::di, io::uo) is det. + +print_set(Desc, Set, !IO) :- + to_sorted_list(Set, Elems), + io.format("%11s: %s\n", [s(Desc), s(string(Elems))], !IO). diff --git a/Task/Symmetric-difference/OCaml/symmetric-difference-1.ocaml b/Task/Symmetric-difference/OCaml/symmetric-difference-1.ocaml new file mode 100644 index 0000000000..0aee6c86fa --- /dev/null +++ b/Task/Symmetric-difference/OCaml/symmetric-difference-1.ocaml @@ -0,0 +1,8 @@ +let unique lst = + let f lst x = if List.mem x lst then lst else x::lst in + List.rev (List.fold_left f [] lst) + +let ( -| ) a b = + unique (List.filter (fun v -> not (List.mem v b)) a) + +let ( -|- ) a b = (b -| a) @ (a -| b) diff --git a/Task/Symmetric-difference/OCaml/symmetric-difference-2.ocaml b/Task/Symmetric-difference/OCaml/symmetric-difference-2.ocaml new file mode 100644 index 0000000000..8e6dfdebc9 --- /dev/null +++ b/Task/Symmetric-difference/OCaml/symmetric-difference-2.ocaml @@ -0,0 +1,14 @@ +# let a = [ "John"; "Bob"; "Mary"; "Serena" ] + and b = [ "Jim"; "Mary"; "John"; "Bob" ] + ;; +val a : string list = ["John"; "Bob"; "Mary"; "Serena"] +val b : string list = ["Jim"; "Mary"; "John"; "Bob"] + +# a -|- b ;; +- : string list = ["Jim"; "Serena"] + +# a -| b ;; +- : string list = ["Serena"] + +# b -| a ;; +- : string list = ["Jim"] diff --git a/Task/Symmetric-difference/Objective-C/symmetric-difference.m b/Task/Symmetric-difference/Objective-C/symmetric-difference.m new file mode 100644 index 0000000000..5ee917fbe0 --- /dev/null +++ b/Task/Symmetric-difference/Objective-C/symmetric-difference.m @@ -0,0 +1,25 @@ +NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + +NSSet* setA = [NSSet setWithObjects:@"John", @"Serena", @"Bob", @"Mary", @"Serena", nil]; +NSSet* setB = [NSSet setWithObjects:@"Jim", @"Mary", @"John", @"Jim", @"Bob", nil]; + +// Present our initial data set +NSLog(@"In set A: %@", setA); +NSLog(@"In set B: %@", setB); + +// Get our individual differences. +NSMutableSet* notInSetA = [NSMutableSet setWithSet:setB]; +[notInSetA minusSet:setA]; +NSMutableSet* notInSetB = [NSMutableSet setWithSet:setA]; +[notInSetB minusSet:setB]; + +// The symmetric difference is the concatenation of the two individual differences +NSMutableSet* symmetricDifference = [NSMutableSet setWithSet:notInSetA]; +[symmetricDifference unionSet:notInSetB]; + +// Present our results +NSLog(@"Not in set A: %@", notInSetA); +NSLog(@"Not in set B: %@", notInSetB); +NSLog(@"Symmetric Difference: %@", symmetricDifference); + +[pool drain]; diff --git a/Task/Symmetric-difference/Oz/symmetric-difference-1.oz b/Task/Symmetric-difference/Oz/symmetric-difference-1.oz new file mode 100644 index 0000000000..6069ad1e23 --- /dev/null +++ b/Task/Symmetric-difference/Oz/symmetric-difference-1.oz @@ -0,0 +1,32 @@ +declare + fun {SymDiff A B} + {Union {Diff A B} {Diff B A}} + end + + %% implement sets in terms of lists + fun {MakeSet Xs} + set({Nub2 Xs nil}) + end + + fun {Diff set(A) set(B)} + set({FoldL B List.subtract A}) + end + + fun {Union set(A) set(B)} + set({Append A B}) + end + + %% -- + fun {Nub2 Xs Ls} + case Xs of nil then nil + [] X|Xr andthen {Member X Ls} then {Nub2 Xr Ls} + [] X|Xr then X|{Nub2 Xr X|Ls} + end + end +in + {Show {SymDiff + {MakeSet [john bob mary serena]} + {MakeSet [jim mary john bob]}}} + {Show {SymDiff + {MakeSet [john serena bob mary serena]} + {MakeSet [jim mary john jim bob]}}} diff --git a/Task/Symmetric-difference/Oz/symmetric-difference-2.oz b/Task/Symmetric-difference/Oz/symmetric-difference-2.oz new file mode 100644 index 0000000000..6ba5381e68 --- /dev/null +++ b/Task/Symmetric-difference/Oz/symmetric-difference-2.oz @@ -0,0 +1,9 @@ +declare + fun {SymDiff A B} + {FS.union {FS.diff A B} {FS.diff B A}} + end + + A = {FS.value.make [1 2 3 4]} + B = {FS.value.make [5 3 1 2]} +in + {Show {SymDiff A B}} diff --git a/Task/Symmetric-difference/PARI-GP/symmetric-difference.pari b/Task/Symmetric-difference/PARI-GP/symmetric-difference.pari new file mode 100644 index 0000000000..cdaba493a4 --- /dev/null +++ b/Task/Symmetric-difference/PARI-GP/symmetric-difference.pari @@ -0,0 +1,9 @@ +sd(u,v)={ + my(r=List()); + u=vecsort(u,,8); + v=vecsort(v,,8); + for(i=1,#u,if(!setsearch(v,u[i]),listput(r,u[i]))); + for(i=1,#v,if(!setsearch(u,v[i]),listput(r,v[i]))); + Vec(r) +}; +sd(["John", "Serena", "Bob", "Mary", "Serena"],["Jim", "Mary", "John", "Jim", "Bob"]) diff --git a/Task/Symmetric-difference/PHP/symmetric-difference.php b/Task/Symmetric-difference/PHP/symmetric-difference.php new file mode 100644 index 0000000000..365c35579d --- /dev/null +++ b/Task/Symmetric-difference/PHP/symmetric-difference.php @@ -0,0 +1,22 @@ + diff --git a/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 b/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 new file mode 100644 index 0000000000..7317074d78 --- /dev/null +++ b/Task/Symmetric-difference/Perl-6/symmetric-difference.pl6 @@ -0,0 +1,5 @@ +use Set; +my $A = set ; +my $B = set ; + +say $A (^) $B; diff --git a/Task/Symmetric-difference/Perl/symmetric-difference.pl b/Task/Symmetric-difference/Perl/symmetric-difference.pl new file mode 100644 index 0000000000..055cd71cac --- /dev/null +++ b/Task/Symmetric-difference/Perl/symmetric-difference.pl @@ -0,0 +1,17 @@ +sub symm_diff { + # two lists passed in as references + my %in_a = map(($_=>1), @{+shift}); + my %in_b = map(($_=>1), @{+shift}); + + my @a = grep { !$in_b{$_} } keys %in_a; + my @b = grep { !$in_a{$_} } keys %in_b; + + # return A-B, B-A, A xor B as ref to lists + return \@a, \@b, [ @a, @b ] +} + +my @a = qw(John Serena Bob Mary Serena); +my @b = qw(Jim Mary John Jim Bob ); + +my ($a, $b, $s) = symm_diff(\@a, \@b); +print "A\\B: @$a\nB\\A: @$b\nSymm: @$s\n"; diff --git a/Task/Symmetric-difference/PicoLisp/symmetric-difference.l b/Task/Symmetric-difference/PicoLisp/symmetric-difference.l new file mode 100644 index 0000000000..5e6078ffe2 --- /dev/null +++ b/Task/Symmetric-difference/PicoLisp/symmetric-difference.l @@ -0,0 +1,2 @@ +(de symdiff (A B) + (uniq (conc (diff A B) (diff B A))) ) diff --git a/Task/Symmetric-difference/Pike/symmetric-difference-1.pike b/Task/Symmetric-difference/Pike/symmetric-difference-1.pike new file mode 100644 index 0000000000..6bcad1dad8 --- /dev/null +++ b/Task/Symmetric-difference/Pike/symmetric-difference-1.pike @@ -0,0 +1,5 @@ +> multiset(string) A = (< "John", "Serena", "Bob", "Mary", "Bob", "Serena" >); +> multiset(string) B = (< "Jim", "Mary", "Mary", "John", "Bob", "Jim" >); + +> A^B; +Result: (< "Bob", "Serena", "Serena", "Mary", "Jim", "Jim" >) diff --git a/Task/Symmetric-difference/Pike/symmetric-difference-2.pike b/Task/Symmetric-difference/Pike/symmetric-difference-2.pike new file mode 100644 index 0000000000..39cbec3ae0 --- /dev/null +++ b/Task/Symmetric-difference/Pike/symmetric-difference-2.pike @@ -0,0 +1,7 @@ +> array(string) A = ({ "John", "Serena", "Bob", "Mary", "Serena", "Bob" }); +> array(string) B = ({ "Jim", "Mary", "John", "Jim", "Bob", "Mary" }); +> A^B; +Result: ({ "Serena", "Serena", "Bob", "Jim", "Jim", "Mary"}) + +> Array.uniq((A-B)+(B-A)); +Result: ({ "Serena", "Jim" }) diff --git a/Task/Symmetric-difference/Pike/symmetric-difference-3.pike b/Task/Symmetric-difference/Pike/symmetric-difference-3.pike new file mode 100644 index 0000000000..9fda30d1c0 --- /dev/null +++ b/Task/Symmetric-difference/Pike/symmetric-difference-3.pike @@ -0,0 +1,5 @@ +> mapping(string:int) A = ([ "John":1, "Serena":1, "Bob":1, "Mary":1 ]); +> mapping(string:int) B = ([ "Jim":1, "Mary":1, "John":1, "Bob":1 ]); + +> A^B; +Result: ([ "Jim": 1, "Serena": 1 ]) diff --git a/Task/Symmetric-difference/Pike/symmetric-difference-4.pike b/Task/Symmetric-difference/Pike/symmetric-difference-4.pike new file mode 100644 index 0000000000..1685c67379 --- /dev/null +++ b/Task/Symmetric-difference/Pike/symmetric-difference-4.pike @@ -0,0 +1,4 @@ +> ADT.Set A = ADT.Set((< "John", "Serena", "Bob", "Mary", "Serena", "Bob" >)); +> ADT.Set B = ADT.Set((< "Jim", "Mary", "John", "Jim", "Bob", "Mary" >)); +> (A-B)+(B-A); +Result: ADT.Set({ "Serena", "Jim" }) diff --git a/Task/Symmetric-difference/Prolog/symmetric-difference.pro b/Task/Symmetric-difference/Prolog/symmetric-difference.pro new file mode 100644 index 0000000000..9ab0b4100e --- /dev/null +++ b/Task/Symmetric-difference/Prolog/symmetric-difference.pro @@ -0,0 +1,15 @@ +sym_diff :- + A = ['John', 'Serena', 'Bob', 'Mary', 'Serena'], + B = ['Jim', 'Mary', 'John', 'Jim', 'Bob'], + format('A : ~w~n', [A]), + format('B : ~w~n', [B]), + list_to_set(A, SA), + list_to_set(B, SB), + format('set from A : ~w~n', [SA]), + format('set from B : ~w~n', [SB]), + subtract(SA, SB, DAB), + format('difference A\\B : ~w~n', [DAB]), + subtract(SB, SA, DBA), + format('difference B\\A : ~w~n', [DBA]), + union(DAB, DBA, Diff), + format('symetric difference : ~w~n', [Diff]). diff --git a/Task/Symmetric-difference/PureBasic/symmetric-difference-1.purebasic b/Task/Symmetric-difference/PureBasic/symmetric-difference-1.purebasic new file mode 100644 index 0000000000..6dad9f9672 --- /dev/null +++ b/Task/Symmetric-difference/PureBasic/symmetric-difference-1.purebasic @@ -0,0 +1,25 @@ +Dim A.s(3) +Dim B.s(3) + +A(0)="John": A(1)="Bob": A(2)="Mary": A(3)="Serena" +B(0)="Jim": B(1)="Mary":B(2)="John": B(3)="Bob" + +For a=0 To ArraySize(A()) ; A-B + For b=0 To ArraySize(B()) + If A(a)=B(b) + Break + ElseIf b=ArraySize(B()) + Debug A(a) + EndIf + Next b +Next a + +For b=0 To ArraySize(B()) ; B-A + For a=0 To ArraySize(A()) + If A(a)=B(b) + Break + ElseIf a=ArraySize(A()) + Debug B(b) + EndIf + Next a +Next b diff --git a/Task/Symmetric-difference/PureBasic/symmetric-difference-2.purebasic b/Task/Symmetric-difference/PureBasic/symmetric-difference-2.purebasic new file mode 100644 index 0000000000..a02bba84ed --- /dev/null +++ b/Task/Symmetric-difference/PureBasic/symmetric-difference-2.purebasic @@ -0,0 +1,73 @@ +DataSection + SetA: + Data.i 4 + Data.s "John", "Bob", "Mary", "Serena" + ; Data.i 5 + ; Data.s "John", "Serena", "Bob", "Mary", "Serena" + SetB: + Data.i 4 + Data.s "Jim", "Mary", "John", "Bob" + ; Data.i 5 + ; Data.s "Jim", "Mary", "John", "Jim", "Bob" +EndDataSection + +Procedure addElementsToSet(List x.s()) + ;requires the read pointer to be set prior to calling by using 'Restore' + Protected i, count + + Read.i count + For i = 1 To count + AddElement(x()) + Read.s x() + Next +EndProcedure + +Procedure displaySet(List x.s()) + Protected i, count = ListSize(x()) + FirstElement(x()) + For i = 1 To count + Print(x()) + NextElement(x()) + If i <> count: Print(", "): EndIf + Next + PrintN("") +EndProcedure + +Procedure symmetricDifference(List a.s(), List b.s(), List result.s()) + Protected ACount = ListSize(a()), BCount = ListSize(b()), prev.s + + ;this may leave set a and b in a different order + SortList(a(),#PB_Sort_Ascending) + SortList(b(),#PB_Sort_Ascending) + + FirstElement(a()) + FirstElement(b()) + LastElement(result()) ;add to end of result() + While ACount > 0 Or BCount > 0 + If ACount <> 0 And BCount <> 0 And a() = b() + ACount - 1: NextElement(a()) + BCount - 1: NextElement(b()) + ElseIf BCount = 0 Or (ACount <> 0 And a() < b()) + AddElement(result()): result() = a() + prev = a(): Repeat: ACount - 1: NextElement(a()): Until ACount = 0 Or (a() <> prev) + ElseIf ACount = 0 Or (BCount <> 0 And a() > b()) + AddElement(result()): result() = b() + prev = b(): Repeat: BCount - 1: NextElement(b()): Until BCount = 0 Or (b() <> prev) + EndIf + Wend +EndProcedure + +If OpenConsole() + NewList a.s(): Restore SetA: addElementsToSet(a()) + NewList b.s(): Restore SetB: addElementsToSet(b()) + Print("Set A: "): displaySet(a()) + Print("Set B: "): displaySet(b()) + + NewList sd.s() + symmetricDifference(a(), b(), sd()) + Print("Symmetric Difference: "): displaySet(sd()) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Symmetric-difference/Python/symmetric-difference-1.py b/Task/Symmetric-difference/Python/symmetric-difference-1.py new file mode 100644 index 0000000000..a148c04946 --- /dev/null +++ b/Task/Symmetric-difference/Python/symmetric-difference-1.py @@ -0,0 +1,9 @@ +>>> setA = {"John", "Bob", "Mary", "Serena"} +>>> setB = {"Jim", "Mary", "John", "Bob"} +>>> setA ^ setB # symmetric difference of A and B +{'Jim', 'Serena'} +>>> setA - setB # elements in A that are not in B +{'Serena'} +>>> setB - setA # elements in B that are not in A +{'Jim'} +>>> diff --git a/Task/Symmetric-difference/Python/symmetric-difference-2.py b/Task/Symmetric-difference/Python/symmetric-difference-2.py new file mode 100644 index 0000000000..ef605e2269 --- /dev/null +++ b/Task/Symmetric-difference/Python/symmetric-difference-2.py @@ -0,0 +1,8 @@ +>>> setA = set(["John", "Bob", "Mary", "Serena"]) +>>> setB = set(["Jim", "Mary", "John", "Bob"]) +>>> setA ^ setB # symmetric difference of A and B +set(['Jim', 'Serena']) +>>> setA - setB # elements in A that are not in B +set(['Serena']) +>>> setB - setA # elements in B that are not in A +set(['Jim']) diff --git a/Task/Symmetric-difference/R/symmetric-difference-1.r b/Task/Symmetric-difference/R/symmetric-difference-1.r new file mode 100644 index 0000000000..e6c4bf70ae --- /dev/null +++ b/Task/Symmetric-difference/R/symmetric-difference-1.r @@ -0,0 +1,7 @@ +a <- c( "John", "Bob", "Mary", "Serena" ) +b <- c( "Jim", "Mary", "John", "Bob" ) +c(setdiff(b, a), setdiff(a, b)) + +a <- c("John", "Serena", "Bob", "Mary", "Serena") +b <- c("Jim", "Mary", "John", "Jim", "Bob") +c(setdiff(b, a), setdiff(a, b)) diff --git a/Task/Symmetric-difference/R/symmetric-difference-2.r b/Task/Symmetric-difference/R/symmetric-difference-2.r new file mode 100644 index 0000000000..11e7cebf01 --- /dev/null +++ b/Task/Symmetric-difference/R/symmetric-difference-2.r @@ -0,0 +1 @@ +[1] "Jim" "Serena" diff --git a/Task/Symmetric-difference/REBOL/symmetric-difference.rebol b/Task/Symmetric-difference/REBOL/symmetric-difference.rebol new file mode 100644 index 0000000000..ee867438d5 --- /dev/null +++ b/Task/Symmetric-difference/REBOL/symmetric-difference.rebol @@ -0,0 +1,3 @@ +a: [John Serena Bob Mary Serena] +b: [Jim Mary John Jim Bob] +difference a b diff --git a/Task/Symmetric-difference/REXX/symmetric-difference.rexx b/Task/Symmetric-difference/REXX/symmetric-difference.rexx new file mode 100644 index 0000000000..ae2c67e39b --- /dev/null +++ b/Task/Symmetric-difference/REXX/symmetric-difference.rexx @@ -0,0 +1,46 @@ +/*REXX program to find the symmetric difference (between two strings). */ +a.=0 /*falisify all the a.k._ booleans. */ +a= '["John", "Serena", "Bob", "Mary", "Serena"]' +b= '["Jim", "Mary", "John", "Jim", "Bob"]' +a.1=a; say '──────────────list A =' a +a.2=b; say '──────────────list B =' b +SD= ; SA= /*Sym. Diff, Sym "And"*/ +SD.=0; SA.=0 /*falsify SD & SA bool*/ + + do k=1 for 2 /*process both lists (stemmed array).*/ + a.k=strip(strip(a.k,,"["),,']') /*strip leading and trailing brackets*/ + + do j=1 until a.k='' /*parse names, they may have blanks. */ + a.k=strip(a.k,,',') /*strip comma (if any)*/ + parse var a.k '"' _ '"' a.k /*get the list's name.*/ + a.k.j=_ /*store the list name.*/ + a.k._=1 /*make a boolean val. */ + end /*j*/ + a.k.0=j-1 /*number of list names*/ + end /*k*/ +/*══════════════════════════════════════════════════find symmetric diff.*/ + do k=1 for 2 /*process both lists. */ + ko=word(2 1,k) /*point to other list.*/ + + do j=1 for a.k.0; _=a.k.j /*process list names. */ + if \a.ko._ & \SD._ then do /*if not in both... */ + SD=SD '"'_'",' /*add to sym diff list*/ + SD._=1 /*"trueify" a boolean.*/ + end + end /*j*/ + end /*k*/ + +SD= "["strip(space(SD),'T',",")']' /*clean up and bracket*/ +say; say 'symmetric difference =' SD /*show and tell the SD*/ + +/*══════════════════════════════════════════════════find symmetric AND. */ + do j=1 for a.1.0; _=a.1.j /*process A list names*/ + if a.1._ & a.2._ & \SA._ then do /*if common to both...*/ + SA=SA '"'_'",' /*add to sym AND list.*/ + SA._=1 /*"trueify" a boolean.*/ + end + end /*j*/ + +SA="["strip(space(SA),'T',",")']' /*clean up and bracket*/ +say; say ' symmetric AND =' SA /*show and tell the SA*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Symmetric-difference/Racket/symmetric-difference.rkt b/Task/Symmetric-difference/Racket/symmetric-difference.rkt new file mode 100644 index 0000000000..b692a2e958 --- /dev/null +++ b/Task/Symmetric-difference/Racket/symmetric-difference.rkt @@ -0,0 +1,7 @@ +#lang racket +(define A (set "John" "Bob" "Mary" "Serena")) +(define B (set "Jim" "Mary" "John" "Bob")) + +(set-symmetric-difference A B) +(set-subtract A B) +(set-subtract B A) diff --git a/Task/Symmetric-difference/Ruby/symmetric-difference-1.rb b/Task/Symmetric-difference/Ruby/symmetric-difference-1.rb new file mode 100644 index 0000000000..ccf125fb8b --- /dev/null +++ b/Task/Symmetric-difference/Ruby/symmetric-difference-1.rb @@ -0,0 +1,10 @@ +# with sets +require 'set' +a = Set["John", "Serena", "Bob", "Mary", "Serena"] +b = Set["Jim", "Mary", "John", "Jim", "Bob"] + +# or, with arrays +a = ["John", "Serena", "Bob", "Mary", "Serena"] +b = ["Jim", "Mary", "John", "Jim", "Bob"] +a.uniq! +b.uniq! diff --git a/Task/Symmetric-difference/Ruby/symmetric-difference-2.rb b/Task/Symmetric-difference/Ruby/symmetric-difference-2.rb new file mode 100644 index 0000000000..8dc3319acb --- /dev/null +++ b/Task/Symmetric-difference/Ruby/symmetric-difference-2.rb @@ -0,0 +1,3 @@ +a_not_b = a - b +b_not_a = b - a +sym_diff = a_not_b + b_not_a diff --git a/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb b/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb new file mode 100644 index 0000000000..c9ce2f0723 --- /dev/null +++ b/Task/Symmetric-difference/Ruby/symmetric-difference-3.rb @@ -0,0 +1 @@ +sym_diff = a ^ b diff --git a/Task/Symmetric-difference/SQL/symmetric-difference-1.sql b/Task/Symmetric-difference/SQL/symmetric-difference-1.sql new file mode 100644 index 0000000000..75b922f986 --- /dev/null +++ b/Task/Symmetric-difference/SQL/symmetric-difference-1.sql @@ -0,0 +1,14 @@ +create or replace function arrxor(anyarray,anyarray) returns anyarray as $$ +select ARRAY( + ( + select r.elements + from ( + (select 1,unnest($1)) + union all + (select 2,unnest($2)) + ) as r (arr, elements) + group by 1 + having min(arr) = max(arr) + ) +) +$$ language sql strict immutable; diff --git a/Task/Symmetric-difference/SQL/symmetric-difference-2.sql b/Task/Symmetric-difference/SQL/symmetric-difference-2.sql new file mode 100644 index 0000000000..c31ac590fe --- /dev/null +++ b/Task/Symmetric-difference/SQL/symmetric-difference-2.sql @@ -0,0 +1 @@ +select arrxor('{this,is,a,test}'::text[],'{also,part,of,a,test}'::text[]); diff --git a/Task/Symmetric-difference/Scala/symmetric-difference.scala b/Task/Symmetric-difference/Scala/symmetric-difference.scala new file mode 100644 index 0000000000..c2794a8c0a --- /dev/null +++ b/Task/Symmetric-difference/Scala/symmetric-difference.scala @@ -0,0 +1,8 @@ +scala> val s1 = Set("John", "Serena", "Bob", "Mary", "Serena") +s1: scala.collection.immutable.Set[java.lang.String] = Set(John, Serena, Bob, Mary) + +scala> val s2 = Set("Jim", "Mary", "John", "Jim", "Bob") +s2: scala.collection.immutable.Set[java.lang.String] = Set(Jim, Mary, John, Bob) + +scala> (s1 diff s2) union (s2 diff s1) +res46: scala.collection.immutable.Set[java.lang.String] = Set(Serena, Jim) diff --git a/Task/Symmetric-difference/Seed7/symmetric-difference.seed7 b/Task/Symmetric-difference/Seed7/symmetric-difference.seed7 new file mode 100644 index 0000000000..c8e2850828 --- /dev/null +++ b/Task/Symmetric-difference/Seed7/symmetric-difference.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + +const type: striSet is set of string; + +enable_output(striSet); + +const proc: main is func + local + const striSet: setA is {"John", "Bob" , "Mary", "Serena"}; + const striSet: setB is {"Jim" , "Mary", "John", "Bob" }; + begin + writeln(setA >< setB); + end func; diff --git a/Task/Symmetric-difference/Smalltalk/symmetric-difference.st b/Task/Symmetric-difference/Smalltalk/symmetric-difference.st new file mode 100644 index 0000000000..05cd3401e6 --- /dev/null +++ b/Task/Symmetric-difference/Smalltalk/symmetric-difference.st @@ -0,0 +1,7 @@ +|A B| +A := Set new. +B := Set new. +A addAll: #( 'John' 'Bob' 'Mary' 'Serena' ). +B addAll: #( 'Jim' 'Mary' 'John' 'Bob' ). + +( (A - B) + (B - A) ) displayNl. diff --git a/Task/Symmetric-difference/TUSCRIPT/symmetric-difference.tuscript b/Task/Symmetric-difference/TUSCRIPT/symmetric-difference.tuscript new file mode 100644 index 0000000000..5743bc6749 --- /dev/null +++ b/Task/Symmetric-difference/TUSCRIPT/symmetric-difference.tuscript @@ -0,0 +1,22 @@ +$$ MODE TUSCRIPT +a="John'Bob'Mary'Serena" +b="Jim'Mary'John'Bob" + +DICT names CREATE + +SUBMACRO checknames +!var,val +PRINT val,": ",var + LOOP n=var + DICT names APPEND/QUIET n,num,cnt,val;" " + ENDLOOP +ENDSUBMACRO + +CALL checknames (a,"a") +CALL checknames (b,"b") + +DICT names UNLOAD names,num,cnt,val + +LOOP n=names,v=val +PRINT n," in: ",v +ENDLOOP diff --git a/Task/Symmetric-difference/Tcl/symmetric-difference.tcl b/Task/Symmetric-difference/Tcl/symmetric-difference.tcl new file mode 100644 index 0000000000..69f05d0482 --- /dev/null +++ b/Task/Symmetric-difference/Tcl/symmetric-difference.tcl @@ -0,0 +1,15 @@ +package require struct::set + +set A {John Bob Mary Serena} +set B {Jim Mary John Bob} + +set AnotB [struct::set difference $A $B] +set BnotA [struct::set difference $B $A] +set SymDiff [struct::set union $AnotB $BnotA] + +puts "A\\B = $AnotB" +puts "B\\A = $BnotA" +puts "A\u2296B = $SymDiff" + +# Of course, the library already has this operation directly... +puts "Direct Check: [struct::set symdiff $A $B]" diff --git a/Task/Symmetric-difference/UNIX-Shell/symmetric-difference.sh b/Task/Symmetric-difference/UNIX-Shell/symmetric-difference.sh new file mode 100644 index 0000000000..edda044ea0 --- /dev/null +++ b/Task/Symmetric-difference/UNIX-Shell/symmetric-difference.sh @@ -0,0 +1,43 @@ +uniq() { + u=("$@") + for ((i=0;i<${#u[@]};i++)); do + for ((j=i+1;j<=${#u[@]};j++)); do + [ "${u[$i]}" = "${u[$j]}" ] && unset u[$i] + done + done + u=("${u[@]}") +} + +a=(John Serena Bob Mary Serena) +b=(Jim Mary John Jim Bob) + +uniq "${a[@]}" +au=("${u[@]}") +uniq "${b[@]}" +bu=("${u[@]}") + +ab=("${au[@]}") +for ((i=0;i<=${#au[@]};i++)); do + for ((j=0;j<=${#bu[@]};j++)); do + [ "${ab[$i]}" = "${bu[$j]}" ] && unset ab[$i] + done +done +ab=("${ab[@]}") + +ba=("${bu[@]}") +for ((i=0;i<=${#bu[@]};i++)); do + for ((j=0;j<=${#au[@]};j++)); do + [ "${ba[$i]}" = "${au[$j]}" ] && unset ba[$i] + done +done +ba=("${ba[@]}") + +sd=("${ab[@]}" "${ba[@]}") + +echo "Set A = ${a[@]}" +echo " = ${au[@]}" +echo "Set B = ${b[@]}" +echo " = ${bu[@]}" +echo "A - B = ${ab[@]}" +echo "B - A = ${ba[@]}" +echo "Symmetric difference = ${sd[@]}" diff --git a/Task/Symmetric-difference/Ursala/symmetric-difference.ursala b/Task/Symmetric-difference/Ursala/symmetric-difference.ursala new file mode 100644 index 0000000000..6fb7678a14 --- /dev/null +++ b/Task/Symmetric-difference/Ursala/symmetric-difference.ursala @@ -0,0 +1,13 @@ +a = <'John','Bob','Mary','Serena'> +b = <'Jim','Mary','John','Bob'> + +#cast %sLm + +main = + +< + 'a': a, + 'b': b, + 'a not b': ~&j/a b, + 'b not a': ~&j/b a, + 'symmetric difference': ~&jrljTs/a b> diff --git a/Task/Synchronous-concurrency/0DESCRIPTION b/Task/Synchronous-concurrency/0DESCRIPTION new file mode 100644 index 0000000000..4ab46b15fd --- /dev/null +++ b/Task/Synchronous-concurrency/0DESCRIPTION @@ -0,0 +1,6 @@ +{{omit from|BBC BASIC}} +The goal of this task is to create two concurrent activities ("[[Thread|Threads]]" or "Tasks", not [[Process|processes]].) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the [[Linux]]/[[UNIX]]/[[Windows|Win32]] pipe command, as communication should be between threads, not processes. + +One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit. + +This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program. diff --git a/Task/Synchronous-concurrency/1META.yaml b/Task/Synchronous-concurrency/1META.yaml new file mode 100644 index 0000000000..0ff53e9fd2 --- /dev/null +++ b/Task/Synchronous-concurrency/1META.yaml @@ -0,0 +1,4 @@ +--- +note: Concurrency +requires: +- Concurrency diff --git a/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg b/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg new file mode 100644 index 0000000000..0840a8bed7 --- /dev/null +++ b/Task/Synchronous-concurrency/ALGOL-68/synchronous-concurrency.alg @@ -0,0 +1,32 @@ +( + STRING line; + INT count := 0, errno; + BOOL input complete := FALSE; + SEMA output throttle = LEVEL 0, input throttle = LEVEL 1; +� + FILE input txt; + errno := open(input txt, "input.txt", stand in channel); +� + PROC call back done = (REF FILE f) BOOL: ( input complete := TRUE ); + on logical file end(input txt, call back done); +� + PAR ( + WHILE + DOWN input throttle; + get(input txt,(line, new line)); + UP output throttle; + NOT input complete + DO + count+:=1 + OD + , + WHILE + DOWN output throttle; + NOT input complete + DO + print((line, new line)); + UP input throttle + OD + ); + print((count)) +) diff --git a/Task/Synchronous-concurrency/Ada/synchronous-concurrency-1.ada b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-1.ada new file mode 100644 index 0000000000..b52a66e580 --- /dev/null +++ b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-1.ada @@ -0,0 +1,6 @@ +package Synchronous_Concurrent is + task Printer is + entry Put(Item : in String); + entry Get_Count(Count : out Natural); + end Printer; +end Synchronous_Concurrent; diff --git a/Task/Synchronous-concurrency/Ada/synchronous-concurrency-2.ada b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-2.ada new file mode 100644 index 0000000000..e6cc745fe0 --- /dev/null +++ b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-2.ada @@ -0,0 +1,26 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + +package body Synchronous_Concurrent is + + task body Printer is + Num_Iter : Natural := 0; + Line : Unbounded_String; + begin + loop + select + accept Put(Item : in String) do + Line := To_Unbounded_String(Item); + end Put; + Put_Line(To_String(Line)); + Num_Iter := Num_Iter + 1; + or + accept Get_Count(Count : out Natural) do + Count := Num_Iter; + end Get_Count; + or terminate; + end select; + end loop; + end Printer; + +end Synchronous_Concurrent; diff --git a/Task/Synchronous-concurrency/Ada/synchronous-concurrency-3.ada b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-3.ada new file mode 100644 index 0000000000..3eb01a3f28 --- /dev/null +++ b/Task/Synchronous-concurrency/Ada/synchronous-concurrency-3.ada @@ -0,0 +1,19 @@ +with Synchronous_Concurrent; use Synchronous_Concurrent; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Synchronous_Concurrent_Main is + Num_Strings : Natural; + The_File : File_Type; + Line : String(1..255); + Length : Natural; +begin + Open(File => The_File, Mode => In_File, Name => "input.txt"); + while not End_Of_File(The_File) loop + Get_Line(File => The_File, Item => Line, Last => Length); + Printer.Put(Line(1..Length)); + end loop; + Close(The_File); + Printer.Get_Count(Num_Strings); + New_Line; + Put_Line("The task wrote" & Natural'Image(Num_Strings) & " strings."); +end Synchronous_Concurrent_Main; diff --git a/Task/Synchronous-concurrency/Aikido/synchronous-concurrency.aikido b/Task/Synchronous-concurrency/Aikido/synchronous-concurrency.aikido new file mode 100644 index 0000000000..eb89df7db6 --- /dev/null +++ b/Task/Synchronous-concurrency/Aikido/synchronous-concurrency.aikido @@ -0,0 +1,48 @@ +monitor Queue { + var items = [] + public function put (item) { + items.append (item) + notify() + } + + public function get() { + while (items.size() == 0) { + wait() + } + var item = items[0] + items <<= 1 + return item + } + + public function close { + items.append (none) + } +} + +thread reader (queue) { + var numlines = 0 + for (;;) { + var line = queue.get() + if (typeof(line) == "none") { + break + } + print (line) + numlines++ + } + println ("Number of lines: " + numlines) +} + +thread writer (queue, lines) { + foreach line lines { + queue.put (line) + } + queue.close() +} + +var queue = new Queue() +var lines = readfile ("input.txt") +var r = reader(queue) +var w = writer(queue, lines) + +join (r) +join (w) diff --git a/Task/Synchronous-concurrency/BCPL/synchronous-concurrency.bcpl b/Task/Synchronous-concurrency/BCPL/synchronous-concurrency.bcpl new file mode 100644 index 0000000000..dfc254949b --- /dev/null +++ b/Task/Synchronous-concurrency/BCPL/synchronous-concurrency.bcpl @@ -0,0 +1,139 @@ +// This is a BCPL implementation of the Rosettacode synchronous +// concurrency test using BCPL coroutines and a coroutine implementation +// of a Occum-style channels. +// BCPL is freely available from www.cl.cam.ac.uk/users/mr10 + +SECTION "coinout" + +GET "libhdr.h" + +GLOBAL { + tracing: ug +} + +LET start() = VALOF +{ LET argv = VEC 50 + LET in_co, out_co = 0, 0 + LET channel = 0 + LET filename = "input.txt" + + UNLESS rdargs("-f,-t/S", argv, 50) DO + { writef("Bad arguments for coinout*n") + RESULTIS 0 + } + + IF argv!0 DO filename := argv!0 // -f the source file + tracing := argv!1 // -t/S tracing option + + in_co := initco(infn, 500, @channel) + out_co := initco(outfn, 500, @channel) + + UNLESS in_co & out_co DO + { writef("Trouble creating the coroutines*n") + GOTO fin + } + + IF tracing DO writef("*nBoth in and out coroutines created*n*n") + + callco(in_co, filename) + +fin: + IF in_co DO deleteco(in_co) + IF out_co DO deleteco(out_co) + + IF tracing DO writef("Both in and out coroutines deleted*n*n") + + RESULTIS 0 +} + +AND readline(line) = VALOF +{ LET ch, i = 0, 0 + line%0 := 0 + + { ch := rdch() + IF ch=endstreamch RESULTIS FALSE + i := i+1 + line%0, line%i := i, ch + IF ch='*n' | i=255 BREAK + } REPEAT + + RESULTIS TRUE +} + +AND infn(args) BE +{ LET channelptr = args!0 + LET name = cowait() // Get the file name + LET instream = findinput(name) + LET line = VEC 256/bytesperword + + UNLESS instream DO + { writef("*nTrouble with file: %s*n", name) + RETURN + } + + selectinput(instream) + + { LET ok = readline(line) + UNLESS ok BREAK + IF tracing DO + writef("inco: Sending a line to outco*n") + cowrite(channelptr, line) + } REPEAT + + IF tracing DO + writef("inco: Sending zero to outco*n") + + writef("*nNumber of lines written was %n*n", cowrite(channelptr, 0)) + + endstream(instream) +} + +AND outfn(args) BE +{ LET channelptr = args!0 + LET linecount = 0 + + { LET line = coread(channelptr) + UNLESS line BREAK + IF tracing DO writef("outfn: Received a line*n") + writes(line) + linecount := linecount + 1 + } REPEAT + + IF tracing DO + writef("outfn: Received zero, so sent count=%n back to inco*n", + linecount) + + cowait(linecount) +} + +// The following functions are a implementation of Occum-style channels +// using coroutines. + +// The first coroutine to request a transfer through a channel becomes +// suspended and the second causes the data to be transfers and then allows +// both coroutines to resume (in some order). The channel word is either +// zero or points to a suspended (read or write) cocoutine. + +// The use of resumeco in coread is somewhat subtle! + +AND coread(ptr) = VALOF +{ LET cptr = !ptr + TEST cptr + THEN { !ptr := 0 // Clear the channel word + RESULTIS resumeco(cptr, currco) + } + ELSE { !ptr := currco // Set channel word to this coroutine + RESULTIS cowait() // Wait for value from cowrite + } +} + +AND cowrite(ptr, val) BE +{ LET cptr = !ptr + TEST cptr + THEN { !ptr := 0 + callco(cptr, val) // Send val to coread + } + ELSE { !ptr := currco + callco(cowait(), val) + } +} diff --git a/Task/Synchronous-concurrency/C/synchronous-concurrency.c b/Task/Synchronous-concurrency/C/synchronous-concurrency.c new file mode 100644 index 0000000000..209f2f1d77 --- /dev/null +++ b/Task/Synchronous-concurrency/C/synchronous-concurrency.c @@ -0,0 +1,112 @@ +#include /* malloc(), realloc(), free() */ +#include /* fopen(), fgetc(), fwrite(), printf() */ + +#include /* co_create(), co_switch() */ + +void +fail(const char *message) { + perror(message); + exit(1); +} + +/* + * These are global variables of this process. All cothreads of this + * process will share these global variables. + */ +cothread_t reader; +cothread_t printer; +struct { + char *buf; /* Not a C string. No terminating '\0'. */ + size_t len; /* Length of line in buffer. */ + size_t cap; /* Maximum capacity of buffer. */ +} line; +size_t count; /* Number of lines printed. */ + +/* + * The reader cothread reads every line of an input file, passes each + * line to the printer cothread, and reports the number of lines. + */ +void +reader_entry(void) +{ + FILE *input; + size_t newcap; + int c, eof, eol; + char *newbuf; + + input = fopen("input.txt", "r"); + if (input == NULL) + fail("fopen"); + + line.buf = malloc(line.cap = 4096); /* New buffer. */ + if (line.buf == NULL) + fail("malloc"); + line.len = 0; /* Start with an empty line. */ + + do { + c = fgetc(input); /* Read next character. */ + if (ferror(input)) + fail("fgetc"); + + eof = (c == EOF); + if (eof) { + /* + * End of file is also end of line, + ` * unless the line would be empty. + */ + eol = (line.len > 0); + } else { + /* Append c to the buffer. */ + if (line.len == line.cap) { + /* Need a bigger buffer! */ + newcap = line.cap * 2; + newbuf = realloc(line.buf, newcap); + if (newbuf == NULL) + fail("realloc"); + line.buf = newbuf; + line.cap = newcap; + } + line.buf[line.len++] = c; + + /* '\n' is end of line. */ + eol = (c == '\n'); + } + + if (eol) { + /* Pass our complete line to the printer. */ + co_switch(printer); + line.len = 0; /* Destroy our line. */ + } + } while (!eof); + + free(line.buf); + line.buf = NULL; /* Stops a loop in the printer. */ + + printf("Printed %zu lines.\n", count); + co_switch(printer); +} + +/* + * The printer cothread starts the reader cothread, prints every line + * line from the reader cothread, and counts the number of lines. + */ +int +main() +{ + reader = co_create(4096, reader_entry); + printer = co_active(); + count = 0; + + for (;;) { + co_switch(reader); + if (line.buf == NULL) + break; + + /* Print this line. Count it. */ + fwrite(line.buf, 1, line.len, stdout); + count++; + } + + co_delete(reader); + return 0; +} diff --git a/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-1.clj b/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-1.clj new file mode 100644 index 0000000000..838c7dbe0f --- /dev/null +++ b/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-1.clj @@ -0,0 +1,7 @@ +(use '[clojure.java.io :as io]) + +(def writer (agent 0)) + +(defn write-line [state line] + (println line) + (inc state)) diff --git a/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-2.clj b/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-2.clj new file mode 100644 index 0000000000..bf3ff11f0d --- /dev/null +++ b/Task/Synchronous-concurrency/Clojure/synchronous-concurrency-2.clj @@ -0,0 +1,6 @@ +(with-open [r (io/reader "input.txt")] + (doseq [line (line-seq r)] + (send writer write-line line))) +(await writer) +(println "lines written:" @writer) +(shutdown-agents) diff --git a/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-1.lisp b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-1.lisp new file mode 100644 index 0000000000..64fc6d056c --- /dev/null +++ b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-1.lisp @@ -0,0 +1,59 @@ +(defvar *self*) + +(defclass queue () + ((condition :initform (make-condition-variable) + :reader condition-of) + (mailbox :initform '() + :accessor mailbox-of) + (lock :initform (make-lock) + :reader lock-of))) + +(defun message (recipient name &rest message) + (with-lock-held ((lock-of recipient)) + ;; it would have been better to implement tail-consing or a LIFO + (setf (mailbox-of recipient) + (nconc (mailbox-of recipient) + (list (list* name message)))) + (condition-notify (condition-of recipient))) + message) + +(defun mklist (x) + (if (listp x) + x + (list x))) + +(defun slurp-message () + (with-lock-held ((lock-of *self*)) + (if (not (endp (mailbox-of *self*))) + (pop (mailbox-of *self*)) + (progn (condition-wait (condition-of *self*) + (lock-of *self*)) + (assert (not (endp (mailbox-of *self*)))) + (pop (mailbox-of *self*)))))) + +(defmacro receive-message (&body cases) + (let ((msg-name (gensym "MESSAGE")) + (block-name (gensym "BLOCK"))) + `(let ((,msg-name (slurp-message))) + (block ,block-name + ,@(loop for i in cases + for ((name . case) . body) = (cons (mklist (car i)) + (cdr i)) + when (typep i '(or (cons (eql quote) + t) + (cons (cons (eql quote) t) + t))) + do (warn "~S is a quoted form" i) + collect `(when ,(if (null name) + 't + `(eql ',name (car ,msg-name))) + (destructuring-bind ,case + (cdr ,msg-name) + (return-from ,block-name + (progn ,@body))))) + (error "Unknown message: ~S" ,msg-name))))) + +(defmacro receive-one-message (message &body body) + `(receive-message (,message . ,body))) + +(defun queue () (make-instance 'queue)) diff --git a/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-2.lisp b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-2.lisp new file mode 100644 index 0000000000..c323a378ca --- /dev/null +++ b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-2.lisp @@ -0,0 +1,33 @@ +(defun reader (pathname writer) + (with-open-file (stream pathname) + (loop for line = (read-line stream nil) + while line + do (message writer '|here's a line for you| line) + finally + (message writer '|how many lines?|) + (receive-one-message (|line count| count) + (format t "line count: ~D~%" count)) + (message writer '|looks like i've got no more lines|)))) + +(defun writer (stream reader) + ;; that would work better with ITERATE + (loop with line-count = 0 do + (receive-message + ((|here's a line for you| line) + (write-line line stream) + (incf line-count)) + (|looks like i've got no more lines| + (return)) + (|how many lines?| + (message reader '|line count| line-count))))) + +(defmacro thread (queue &body body) + `(make-thread (lambda (&aux (*self* ,queue)) + ,@body))) + +(defun synchronous-concurrency (&key (pathname "input.txt")) + (let ((reader (queue)) + (writer (queue))) + (thread reader (reader pathname writer)) + (thread writer (writer *standard-output* reader))) + (values)) diff --git a/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-3.lisp b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-3.lisp new file mode 100644 index 0000000000..475629b5ff --- /dev/null +++ b/Task/Synchronous-concurrency/Common-Lisp/synchronous-concurrency-3.lisp @@ -0,0 +1,7 @@ +CL-USER> (synchronous-concurrency :pathname "/tmp/input.txt") +foo +bar +baz +xenu 666 +line count: 4 +; No value diff --git a/Task/Synchronous-concurrency/D/synchronous-concurrency.d b/Task/Synchronous-concurrency/D/synchronous-concurrency.d new file mode 100644 index 0000000000..3cd9be8477 --- /dev/null +++ b/Task/Synchronous-concurrency/D/synchronous-concurrency.d @@ -0,0 +1,32 @@ +import tools.threads, std.stdio, std.stream, std.thread; + +void main() { + // line or EOF + struct InputLine { + string data; + bool eof; + static InputLine opCall(string s) { InputLine res; res.data = s; return res; } + static InputLine EOF() { InputLine res; res.eof = true; return res; } + } + auto LineCh = new MessageChannel!(InputLine), + ResultCh = new MessageChannel!(int); + auto printer = new Thread({ + int count; + while (true) { + auto line = LineCh.get(); + if (line.eof) break; + count ++; + writefln(count, ": ", line.data); + } + ResultCh.put(count); + return 0; + }); + printer.start; + auto file = new File("input.txt"); + while (!file.eof()) { + auto line = file.readLine(); + LineCh.put(InputLine(line)); + } + LineCh.put(InputLine.EOF()); + writefln("Count: ", ResultCh.get()); +} diff --git a/Task/Synchronous-concurrency/Delphi/synchronous-concurrency.delphi b/Task/Synchronous-concurrency/Delphi/synchronous-concurrency.delphi new file mode 100644 index 0000000000..941890ea6f --- /dev/null +++ b/Task/Synchronous-concurrency/Delphi/synchronous-concurrency.delphi @@ -0,0 +1,168 @@ +program Project2; + +{$APPTYPE CONSOLE} + +uses + SysUtils, Classes, Windows; + +type + EThreadStackFinalized = class(Exception); + + PLine = ^TLine; + TLine = record + Text: string; + end; + + TThreadQueue = class + private + FFinalized: Boolean; + FQueue: THandle; + public + constructor Create; + destructor Destroy; override; + procedure Finalize; + procedure Push(Data: Pointer); + function Pop(var Data: Pointer): Boolean; + property Finalized: Boolean read FFinalized; + end; + + TPrintThread = class(TThread) + private + FCount: Integer; + FTreminateEvent: THandle; + FDoneEvent: THandle; + FQueue: TThreadQueue; + public + constructor Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue); + procedure Execute; override; + + property Count: Integer read FCount; + end; + +{ TThreadQueue } + +constructor TThreadQueue.Create; +begin + FQueue := CreateIOCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); + FFinalized := False; +end; + +destructor TThreadQueue.Destroy; +begin + if FQueue <> 0 then + CloseHandle(FQueue); + inherited; +end; + +procedure TThreadQueue.Finalize; +begin + PostQueuedCompletionStatus(FQueue, 0, 0, Pointer($FFFFFFFF)); + FFinalized := True; +end; + +function TThreadQueue.Pop(var Data: Pointer): Boolean; +var + A: Cardinal; + OL: POverLapped; +begin + Result := True; + if not FFinalized then + GetQueuedCompletionStatus(FQueue, A, Cardinal(Data), OL, INFINITE); + + if FFinalized or (OL = Pointer($FFFFFFFF)) then begin + Data := nil; + Result := False; + Finalize; + end; +end; + +procedure TThreadQueue.Push(Data: Pointer); +begin + if FFinalized then + raise EThreadStackFinalized.Create('Stack is finalized'); + + PostQueuedCompletionStatus(FQueue, 0, Cardinal(Data), nil); +end; + +{ TPrintThread } + +constructor TPrintThread.Create(aTreminateEvent, aDoneEvent: THandle; aQueue: TThreadQueue); +begin + inherited Create(True); + FCount := 0; + FreeOnTerminate := True; + FTreminateEvent := aTreminateEvent; + FDoneEvent := aDoneEvent; + FQueue := aQueue; +end; + +procedure TPrintThread.Execute; +var + data: Pointer; + line: PLine; +begin + repeat + if FQueue.Pop(data) then begin + line := data; + try + Writeln(line^.Text); + if line^.Text = #0 then + SetEvent(FDoneEvent); + Inc(FCount); + finally + Dispose(line); + end; + end; + + until False; + WaitForSingleObject(FTreminateEvent, INFINITE); +end; + +var + PrintThread: TPrintThread; + Queue: TThreadQueue; + lines: TStrings; + i: Integer; + line: PLine; + TreminateEvent, DoneEvent: THandle; +begin + Queue := TThreadQueue.Create; + try + TreminateEvent := CreateEvent(nil, False, False, 'TERMINATE_EVENT'); + DoneEvent := CreateEvent(nil, False, False, 'DONE_EVENT'); + try + PrintThread := TPrintThread.Create(TreminateEvent, DoneEvent, Queue); + PrintThread.Start; + lines := TStringList.Create; + try + lines.LoadFromFile('input.txt'); + for i := 0 to lines.Count - 1 do begin + New(line); + line^.Text := lines[i]; + Queue.Push(line); + end; + + New(line); + line^.Text := #0; + Queue.Push(line); + + WaitForSingleObject(DoneEvent, INFINITE); + + New(line); + line^.Text := IntToStr(PrintThread.Count); + Queue.Push(line); + + SetEvent(TreminateEvent); + finally + lines.Free; + end; + finally + CloseHandle(TreminateEvent); + CloseHandle(DoneEvent) + end; + + Readln; + finally + Queue.Free; + end; +end. diff --git a/Task/Synchronous-concurrency/E/synchronous-concurrency.e b/Task/Synchronous-concurrency/E/synchronous-concurrency.e new file mode 100644 index 0000000000..9af5a63e12 --- /dev/null +++ b/Task/Synchronous-concurrency/E/synchronous-concurrency.e @@ -0,0 +1,30 @@ +def printer := { + var count := 0 + def printer { + to run(item) { + count += 1 + println(item) + } + to getCount() { + return count + } + } +} + +def sender(lines) { + switch (lines) { + match [] { + when (def count := printer <- getCount()) -> { + println(`$count lines were printed.`) + } + } + match [line] + rest { + when (printer <- run(line)) -> { + sender(rest) + } + } + } +} + +# Stream IO in E is not finished yet, so this example just uses a list. +sender(.getText().split("\n")) diff --git a/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl b/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl new file mode 100644 index 0000000000..4e7931c658 --- /dev/null +++ b/Task/Synchronous-concurrency/Erlang/synchronous-concurrency.erl @@ -0,0 +1,35 @@ +-module(cc). +-export([start/0, reader/2]). + +start() -> + Pid = spawn(cc,reader,[self(), 0]), + case file:open("input.txt", read) of + {error, Any} -> io:fwrite("Error ~p~n",[Any]); + {ok, Io} -> + process(Io, Pid), + file:close(Io) + end, + ok. + +process(Io, Pid) -> + case io:get_line(Io,"") of + eof -> + Pid ! count, + wait(); + Any -> + Pid ! Any, + process(Io, Pid) + end. + +wait() -> + receive + I -> io:fwrite("Count:~p~n", [I]) + end. + +reader(Pid, C) -> + receive + count -> Pid ! C; + Any -> + io:fwrite("~s", [Any]), + reader(Pid, C+1) + end. diff --git a/Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.euphoria b/Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.euphoria new file mode 100644 index 0000000000..bd6585090f --- /dev/null +++ b/Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.euphoria @@ -0,0 +1,58 @@ +sequence lines +sequence count +lines = {} +count = {} + +procedure read(integer fn) + object line + while 1 do + line = gets(fn) + if atom(line) then + exit + else + lines = append(lines, line) + task_yield() + end if + end while + + lines = append(lines,0) + while length(count) = 0 do + task_yield() + end while + + printf(1,"Count: %d\n",count[1]) +end procedure + +procedure write(integer fn) + integer n + object line + n = 0 + while 1 do + while length(lines) = 0 do + task_yield() + end while + + line = lines[1] + lines = lines[2..$] + if atom(line) then + exit + else + puts(fn,line) + n += 1 + end if + end while + count = append(count,n) +end procedure + +integer fn +atom reader, writer +constant stdout = 1 +fn = open("input.txt","r") +reader = task_create(routine_id("read"),{fn}) +writer = task_create(routine_id("write"),{stdout}) +task_schedule(writer,1) +task_schedule(reader,1) + +while length(task_list()) > 1 do + task_yield() +end while diff --git a/Task/Synchronous-concurrency/Go/synchronous-concurrency.go b/Task/Synchronous-concurrency/Go/synchronous-concurrency.go new file mode 100644 index 0000000000..cc670d070a --- /dev/null +++ b/Task/Synchronous-concurrency/Go/synchronous-concurrency.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "bufio" + "io" + "os" +) + +// main, one of two goroutines used, will function as the "reading unit" +func main() { + // get file open first + f, err := os.Open("input.txt") + if err != nil { + fmt.Println(err) + return + } + defer f.Close() + lr := bufio.NewReader(f) + + // that went ok, now create communication channels, + // and start second goroutine as the "printing unit" + lines := make(chan string) + count := make(chan int) + go printer(lines, count) + + for { + line, prefix, err := lr.ReadLine() + switch { + case err == io.EOF: + case err != nil: + fmt.Println(err) + case prefix: + fmt.Println("unexpected long line") + default: + lines <- string(line) + continue + } + break + } + // this represents the request for the printer to send the count + close(lines) + // wait for the count from the printer, then print it, then exit + fmt.Println("Number of lines:", <-count) +} + +func printer(in <-chan string, count chan<- int) { + c := 0 + // loop as long as in channel stays open + for s := range in { + fmt.Println(s) + c++ + } + // make count available on count channel, then return (terminate goroutine) + count <- c +} diff --git a/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-1.hs b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-1.hs new file mode 100644 index 0000000000..7dda3068bc --- /dev/null +++ b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-1.hs @@ -0,0 +1,15 @@ +import Control.Concurrent +import Control.Concurrent.MVar + +main = + do lineVar <- newEmptyMVar + countVar <- newEmptyMVar + + let takeLine = takeMVar lineVar + putLine = putMVar lineVar . Just + putEOF = putMVar lineVar Nothing + takeCount = takeMVar countVar + putCount = putMVar countVar + + forkIO $ writer takeLine putCount + reader putLine putEOF takeCount diff --git a/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-2.hs b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-2.hs new file mode 100644 index 0000000000..8c7bb66e5d --- /dev/null +++ b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-2.hs @@ -0,0 +1,6 @@ +reader putLine putEOF takeCount = + do ls <- fmap lines (readFile "input.txt") + mapM putLine ls + putEOF + n <- takeCount + print n diff --git a/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-3.hs b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-3.hs new file mode 100644 index 0000000000..464d33a141 --- /dev/null +++ b/Task/Synchronous-concurrency/Haskell/synchronous-concurrency-3.hs @@ -0,0 +1,6 @@ +writer takeLine putCount = loop 0 + where loop n = do l <- takeLine + case l of + Just x -> do putStrLn x + loop (n+1) + Nothing -> putCount n diff --git a/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon b/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon new file mode 100644 index 0000000000..8a7f3fd959 --- /dev/null +++ b/Task/Synchronous-concurrency/Icon/synchronous-concurrency.icon @@ -0,0 +1,28 @@ +procedure main() + local prod, cons + prod := create producer("input.txt") + cons := create consumer(prod) + @cons +end + +procedure producer(fname) + local f + f := open(fname) | stop("Unable to open ", fname) + # send what we read [read(f)] to the consumer (&source) + while read(f) @ &source + # send it 'null' which we use as a signal to request count + write("count = ", &null @ &source) +end + +procedure consumer(p) + local value, i + i := 1 + value := @p + while \value do { + write("=> ",value) + value := @ &source + i := i + 1 + } + # send producer our count + i @ &source +end diff --git a/Task/Synchronous-concurrency/Java/synchronous-concurrency.java b/Task/Synchronous-concurrency/Java/synchronous-concurrency.java new file mode 100644 index 0000000000..b06b920b2b --- /dev/null +++ b/Task/Synchronous-concurrency/Java/synchronous-concurrency.java @@ -0,0 +1,52 @@ +import java.io.BufferedReader; +import java.io.FileReader; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +class SynchronousConcurrency +{ + public static void main(String[] args) throws Exception + { + final AtomicLong lineCount = new AtomicLong(0); + final BlockingQueue queue = new LinkedBlockingQueue(); + final String EOF = new String(); + + final Thread writerThread = new Thread(new Runnable() { + public void run() + { + long linesWrote = 0; + while (true) + { + try + { + String line = queue.take(); + // Reference equality + if (line == EOF) + break; + System.out.println(line); + linesWrote++; + } + catch (InterruptedException ie) + { } + } + lineCount.set(linesWrote); + } + } + ); + writerThread.start(); + + // No need to start a third thread for the reader, just use this thread + BufferedReader br = new BufferedReader(new FileReader("input.txt")); + String line; + while ((line = br.readLine()) != null) + queue.put(line); + br.close(); + queue.put(EOF); + writerThread.join(); + // AtomicLong is not needed here due to memory barrier created by thread join, but still need a mutable long since lineCount must be final to access it from an anonymous class + System.out.println("Line count: " + lineCount.get()); + return; + } +} diff --git a/Task/Synchronous-concurrency/Lua/synchronous-concurrency.lua b/Task/Synchronous-concurrency/Lua/synchronous-concurrency.lua new file mode 100644 index 0000000000..4e9067a0f5 --- /dev/null +++ b/Task/Synchronous-concurrency/Lua/synchronous-concurrency.lua @@ -0,0 +1,18 @@ +function ReadFile() + local fp = io.open( "input.txt" ) + assert( fp ~= nil ) + + for line in fp:lines() do + coroutine.yield( line ) + end + + fp:close() +end + +co = coroutine.create( ReadFile ) + +while true do + local status, val = coroutine.resume( co ) + if coroutine.status( co ) == "dead" then break end + print( val ) +end diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ocaml new file mode 100644 index 0000000000..b185178ade --- /dev/null +++ b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ocaml @@ -0,0 +1 @@ +open Event diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ocaml new file mode 100644 index 0000000000..084506e63d --- /dev/null +++ b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ocaml @@ -0,0 +1,12 @@ +let reader count_source lines_dest = + let file = open_in "input.txt" in + let rec aux () = + let line = try Some (input_line file) + with End_of_file -> None in + sync (send lines_dest line); + match line with + | Some _ -> aux () + | None -> let printed = sync (receive count_source) in + Printf.printf "The task wrote %i strings\n" printed; + close_in file + in aux () diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ocaml new file mode 100644 index 0000000000..b43bc80a31 --- /dev/null +++ b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ocaml @@ -0,0 +1,6 @@ +let printer lines_source count_target = + let rec aux i = + match sync (receive lines_source) with + | Some line -> print_endline line; aux ( i + 1 ) + | None -> sync (send count_target i) + in aux 0 diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ocaml new file mode 100644 index 0000000000..88a9ba9ada --- /dev/null +++ b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ocaml @@ -0,0 +1,6 @@ +let _ = + let count = new_channel () + and lines = new_channel () + in + let _ = Thread.create (printer lines) count + in reader count lines diff --git a/Task/Synchronous-concurrency/Oz/synchronous-concurrency.oz b/Task/Synchronous-concurrency/Oz/synchronous-concurrency.oz new file mode 100644 index 0000000000..9ba37e0e0f --- /dev/null +++ b/Task/Synchronous-concurrency/Oz/synchronous-concurrency.oz @@ -0,0 +1,49 @@ +declare + %% Helper function to read a file lazily. + %% Returns a lazy list of lines. + fun {ReadLines FN} + F = {New class $ from Open.file Open.text end init(name:FN)} + fun lazy {ReadNext} + case {F getS($)} of + false then nil + [] Line then + Line|{ReadNext} + end + end + in + %% close file when handle becomes unreachable + {Finalize.register F proc {$ F} {F close} end} + {ReadNext} + end + + Count %% Will receive the number of lines + PrinterPort +in + %% Printer thread + thread + Stream + Counter = {NewCell 0} %% mutable variable + in + PrinterPort = {NewPort ?Stream} + for Line in Stream do + case Line of eof then + Count = @Counter + else + {System.showInfo Line} + Counter := @Counter + 1 + end + end + end + + %% Send all lines to printer thread; make sure that eof is sent. + try + for Line in {ReadLines "input.txt"} do + {Send PrinterPort Line} + end + finally + {Send PrinterPort eof} + end + + %% Sync on Count and print its value. + {Wait Count} + {Show Count} diff --git a/Task/Synchronous-concurrency/Perl-6/synchronous-concurrency.pl6 b/Task/Synchronous-concurrency/Perl-6/synchronous-concurrency.pl6 new file mode 100644 index 0000000000..aa37e3853a --- /dev/null +++ b/Task/Synchronous-concurrency/Perl-6/synchronous-concurrency.pl6 @@ -0,0 +1,13 @@ +sub MAIN ($infile) { + $infile.IO.lines ==> printer() ==> my $count; + say "printed $count lines"; +} + +sub printer(*@lines) { + my $lines; + for @lines { + .say; + ++$lines; + } + $lines; +} diff --git a/Task/Synchronous-concurrency/Perl/synchronous-concurrency.pl b/Task/Synchronous-concurrency/Perl/synchronous-concurrency.pl new file mode 100644 index 0000000000..3cb068e8df --- /dev/null +++ b/Task/Synchronous-concurrency/Perl/synchronous-concurrency.pl @@ -0,0 +1,33 @@ +use threads; +use Thread::Queue qw(); + +my $q1 = Thread::Queue->new; +my $q2 = Thread::Queue->new; + +my $reader = threads->create(sub { + my $q1 = shift; + my $q2 = shift; + + open my $fh, '<', 'input.txt'; + $q1->enqueue($_) while <$fh>; + close $fh; + $q1->enqueue(undef); + + print $q2->dequeue; +}, $q1, $q2); + +my $printer = threads->create(sub { + my $q1 = shift; + my $q2 = shift; + + my $count; + while (my $line = $q1->dequeue) { + print $line; + $count++; + }; + + $q2->enqueue($count); +}, $q1, $q2); + +$reader->join; +$printer->join; diff --git a/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-1.l b/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-1.l new file mode 100644 index 0000000000..9cedf8af6a --- /dev/null +++ b/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-1.l @@ -0,0 +1,21 @@ +# Reading task (synchronous) +(task (open "input.txt") + (let Fd @ + (if (in Fd (line T)) # More lines? + (udp "localhost" 4444 @) # Yes: Send next line + (task (port T 4445) # Else install handler + (prinl (udp @) " lines") # to receive and print count + (task (close @)) ) + (udp "localhost" 4444 T) # Send 'T' for "Done" + (task (close Fd)) ) ) ) # Stop the task + +# Printing task (asynchronous) +(sigio (setq "Sock" (port T 4444)) + (job '((Cnt . 0)) + (let? X (udp "Sock") + (if (=T X) # Done? + (prog + (udp "localhost" 4445 Cnt) # Yes: Send count + (sigio (close "Sock")) ) # and stop the task + (println X) # Else print line to stdout + (inc 'Cnt) ) ) ) ) # and increment count diff --git a/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-2.l b/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-2.l new file mode 100644 index 0000000000..3f2048e3d4 --- /dev/null +++ b/Task/Synchronous-concurrency/PicoLisp/synchronous-concurrency-2.l @@ -0,0 +1,15 @@ +(co 'unit1 + (yield) # Allow 'unit2' to start + (in "input.txt" # Read the file + (while (line T) # Send each line + (yield @ 'unit2) ) ) # to 'unit2' + (prinl + (yield NIL 'unit2) # Send 'NIL' for "Done", receive count + " lines" ) ) + +(co 'unit2 + (let Cnt 0 # Init counter + (while (yield NIL 'unit1) # Receive line + (println @) # Print it + (inc 'Cnt) ) # Increment count + (yield Cnt 'unit1) ) ) # Send count to 'unit1' diff --git a/Task/Synchronous-concurrency/PureBasic/synchronous-concurrency.purebasic b/Task/Synchronous-concurrency/PureBasic/synchronous-concurrency.purebasic new file mode 100644 index 0000000000..24dd0ee430 --- /dev/null +++ b/Task/Synchronous-concurrency/PureBasic/synchronous-concurrency.purebasic @@ -0,0 +1,45 @@ +Enumeration + #Write + #Done +EndEnumeration + +Structure commblock + txtline.s + Order.i +EndStructure + +Global MessageSent=CreateSemaphore() +Global LineWritten=CreateSemaphore() +Global LinesWritten, com.commblock + +Procedure Writer(arg) + Repeat + WaitSemaphore(MessageSent) + If com\Order=#Write + PrintN(com\txtline) + LinesWritten+1 + EndIf + SignalSemaphore(LineWritten) + Until com\Order=#Done +EndProcedure + +Procedure Reader(arg) + Protected File=ReadFile(#PB_Any,OpenFileRequester("","input.txt","",0)) + While file And Not Eof(file) + com\txtline=ReadString(File) + com\Order=#Write + SignalSemaphore(MessageSent) + WaitSemaphore(LineWritten) + Wend + com\Order=#Done + SignalSemaphore(MessageSent) + WaitSemaphore(LineWritten) + PrintN(Str(LinesWritten)+" lines written.") +EndProcedure + +If OpenConsole() + Define Thread1=CreateThread(@Reader(),0) + Define Thread2=CreateThread(@Writer(),0) + WaitThread(Thread1) And WaitThread(Thread2) + Print("Press Enter to exit"):Input() +EndIf diff --git a/Task/Synchronous-concurrency/Python/synchronous-concurrency-1.py b/Task/Synchronous-concurrency/Python/synchronous-concurrency-1.py new file mode 100644 index 0000000000..4b60b83409 --- /dev/null +++ b/Task/Synchronous-concurrency/Python/synchronous-concurrency-1.py @@ -0,0 +1,31 @@ +import sys +from Queue import Queue +from threading import Thread + +lines = Queue(1) +count = Queue(1) + +def read(file): + try: + for line in file: + lines.put(line) + finally: + lines.put(None) + print count.get() + +def write(file): + n = 0 + while 1: + line = lines.get() + if line is None: + break + file.write(line) + n += 1 + count.put(n) + +reader = Thread(target=read, args=(open('input.txt'),)) +writer = Thread(target=write, args=(sys.stdout,)) +reader.start() +writer.start() +reader.join() +writer.join() diff --git a/Task/Synchronous-concurrency/Python/synchronous-concurrency-2.py b/Task/Synchronous-concurrency/Python/synchronous-concurrency-2.py new file mode 100644 index 0000000000..b02466bff6 --- /dev/null +++ b/Task/Synchronous-concurrency/Python/synchronous-concurrency-2.py @@ -0,0 +1,12 @@ +count = 0 + +def reader(): + for line in open('input.txt'): + yield line.rstrip() + print('Printed %d lines.' % count) + +r = reader() +# printer +for line in r: + print(line) + count += 1 diff --git a/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py b/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py new file mode 100644 index 0000000000..507b516628 --- /dev/null +++ b/Task/Synchronous-concurrency/Python/synchronous-concurrency-3.py @@ -0,0 +1,16 @@ +def reader(): + for line in open('input.txt'): + yield line.rstrip() + count = yield None + print('Printed %d lines.' % count) + +r = reader() +# printer +count = 0 +while True: + line = next(r) + if not line: + break + print(line) + count += 1 +r.send(count) diff --git a/Task/Synchronous-concurrency/Racket/synchronous-concurrency.rkt b/Task/Synchronous-concurrency/Racket/synchronous-concurrency.rkt new file mode 100644 index 0000000000..753f3ffb38 --- /dev/null +++ b/Task/Synchronous-concurrency/Racket/synchronous-concurrency.rkt @@ -0,0 +1,29 @@ +(define reader->printer-channel (make-channel)) +(define printer->reader-channel (make-channel)) + +(define (sync-line-counter filename) + (define (reader) + (define file-port (open-input-file filename)) + (let loop ([line (read-line file-port)]) + (when (not (eof-object? line)) + (begin + (channel-put reader->printer-channel line) + (loop (read-line file-port))))) + (channel-put reader->printer-channel eof) + (let ([num-lines (channel-get printer->reader-channel)]) + (printf "Number of lines printed = ~a~%" num-lines))) + + (define (printer) + (define count 0) + (let loop ([line (channel-get reader->printer-channel)]) + (when (not (eof-object? line)) + (begin + (printf "~a~%" line) + (set! count (add1 count)) + (loop (channel-get reader->printer-channel))))) + (channel-put printer->reader-channel count)) + + (thread reader) + (thread printer)) + +(sync-line-counter "input.txt") diff --git a/Task/Synchronous-concurrency/Raven/synchronous-concurrency.raven b/Task/Synchronous-concurrency/Raven/synchronous-concurrency.raven new file mode 100644 index 0000000000..c844abaaa6 --- /dev/null +++ b/Task/Synchronous-concurrency/Raven/synchronous-concurrency.raven @@ -0,0 +1,28 @@ +'input.txt' as src_file + +class Queue + + new list as items + condition as ready + + define item_put + items push ready notify + + define item_get + items empty if ready wait + items shift + +Queue as lines +Queue as count + +thread reader + "file://r:%(src_file)s" open each lines.item_put + NULL lines.item_put count.item_get "reader: %d\n" print + +thread writer + 0 repeat lines.item_get dup while + "writer: %s" print 1+ + drop count.item_put + +reader as r +writer as w diff --git a/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-1.rb b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-1.rb new file mode 100644 index 0000000000..e2d3f0b682 --- /dev/null +++ b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-1.rb @@ -0,0 +1,3 @@ +count = 0 +IO.foreach("input.txt") { |line| print line; count += 1 } +puts "Printed #{count} lines." diff --git a/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-2.rb b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-2.rb new file mode 100644 index 0000000000..b61757ae3c --- /dev/null +++ b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-2.rb @@ -0,0 +1,12 @@ +count = 0 +reader = Fiber.new do + IO.foreach("input.txt") { |line| Fiber.yield line } + puts "Printed #{count} lines." + nil +end + +# printer +while line = reader.resume + print line + count += 1 +end diff --git a/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-3.rb b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-3.rb new file mode 100644 index 0000000000..c33d701cf2 --- /dev/null +++ b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-3.rb @@ -0,0 +1,15 @@ +require 'continuation' unless defined? Continuation + +count = 0 +reader = proc do |cont| + IO.foreach("input.txt") { |line| cont = callcc { |cc| cont[cc, line] }} + puts "Printed #{count} lines." + cont[nil] +end + +# printer +while array = callcc { |cc| reader[cc] } + reader, line = array + print line + count += 1 +end diff --git a/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-4.rb b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-4.rb new file mode 100644 index 0000000000..c64234b93c --- /dev/null +++ b/Task/Synchronous-concurrency/Ruby/synchronous-concurrency-4.rb @@ -0,0 +1,26 @@ +require 'thread' + +counts = Queue.new +lines = Queue.new +reader = Thread.new do + begin + File.foreach("input.txt") { |line| lines << line } + lines << :EOF + puts "Printed #{counts.pop} lines." + ensure + lines << nil + end +end + +# writer +count = 0 +while line = lines.pop + case line + when String + print line + count += 1 + when :EOF + counts << count + end +end +reader.join diff --git a/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala b/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala new file mode 100644 index 0000000000..9343825bfe --- /dev/null +++ b/Task/Synchronous-concurrency/Scala/synchronous-concurrency.scala @@ -0,0 +1,23 @@ +case class HowMany(asker:Actor) + +val printer = actor { + var count = 0 + while(true){ + receive{ + case line:String => print(line); count = count + 1 + case HowMany(asker:Actor) => asker ! count ; exit() + } + } +} + +def reader(printer:Actor) { + scala.io.Source.fromFile("c:\\input.txt").getLines foreach {printer ! _ } + printer ! HowMany( + actor { + receive{ + case count:Int => println("line count = "+count) + } + }) +} + +reader(printer) diff --git a/Task/Synchronous-concurrency/SystemVerilog/synchronous-concurrency.v b/Task/Synchronous-concurrency/SystemVerilog/synchronous-concurrency.v new file mode 100644 index 0000000000..222f8eae1e --- /dev/null +++ b/Task/Synchronous-concurrency/SystemVerilog/synchronous-concurrency.v @@ -0,0 +1,37 @@ +program main; + + mailbox#(bit) p2c_cmd = new; + mailbox#(string) p2c_data = new; + mailbox#(int) c2p_data = new; + + initial begin + int fh = $fopen("input.txt", "r"); + string line; + int count; + while ($fgets(line, fh)) begin + p2c_cmd.put(0); + p2c_data.put(line); + end + p2c_cmd.put(1); + c2p_data.get(count); + $display( "COUNT: %0d", count ); + end + + initial begin + bit done; + int count; + while (!done) begin + p2c_cmd.get(done); + if (done) begin + c2p_data.put(count); + end + else begin + string line; + p2c_data.get(line); + $display( "LINE: %s", line); + count++; + end + end + end + +endprogram diff --git a/Task/Synchronous-concurrency/Tcl/synchronous-concurrency.tcl b/Task/Synchronous-concurrency/Tcl/synchronous-concurrency.tcl new file mode 100644 index 0000000000..e68495a921 --- /dev/null +++ b/Task/Synchronous-concurrency/Tcl/synchronous-concurrency.tcl @@ -0,0 +1,28 @@ +package require Thread + +# Define the input thread +set input [thread::create { + proc readFile {filename receiver} { + set f [open $filename] + while {[gets $f line] >= 0} { + thread::send $receiver [list line $line] + } + close $f + thread::send $receiver lineCount lines + puts "got $lines lines" + } + thread::wait +}] +# Define the output thread +set output [thread::create { + set lines 0 + proc line {string} { + puts $string + incr ::lines + } + proc lineCount {} {return $::lines} + thread::wait +}] + +# Connect everything together and start the processing +thread::send $input [list readFile "input.txt" $output] diff --git a/Task/Synchronous-concurrency/UnixPipes/synchronous-concurrency.unixpipes b/Task/Synchronous-concurrency/UnixPipes/synchronous-concurrency.unixpipes new file mode 100644 index 0000000000..436f62d879 --- /dev/null +++ b/Task/Synchronous-concurrency/UnixPipes/synchronous-concurrency.unixpipes @@ -0,0 +1,2 @@ +rm -f node ; mkfifo node +cat file | tee >(wc -l > node ) | cat - node diff --git a/Task/Synchronous-concurrency/Visual-Basic-.NET/synchronous-concurrency.visual b/Task/Synchronous-concurrency/Visual-Basic-.NET/synchronous-concurrency.visual new file mode 100644 index 0000000000..62e48199f0 --- /dev/null +++ b/Task/Synchronous-concurrency/Visual-Basic-.NET/synchronous-concurrency.visual @@ -0,0 +1,65 @@ +Imports System.Threading + +Module Module1 + + Sub Main() + Dim t1 As New Thread(AddressOf Reader) + Dim t2 As New Thread(AddressOf Writer) + t1.Start() + t2.Start() + t1.Join() + t2.Join() + End Sub + + Sub Reader() + For Each line In IO.File.ReadAllLines("input.txt") + m_WriterQueue.Enqueue(line) + Next + m_WriterQueue.Enqueue(Nothing) + + Dim result As Integer + Do Until m_ReaderQueue.TryDequeue(result) + Thread.Sleep(10) + Loop + + Console.WriteLine(result) + + End Sub + + Sub Writer() + Dim count = 0 + Dim line As String = Nothing + Do + Do Until m_WriterQueue.TryDequeue(line) + Thread.Sleep(10) + Loop + If line IsNot Nothing Then + Console.WriteLine(line) + count += 1 + Else + m_ReaderQueue.Enqueue(count) + Exit Do + End If + Loop + End Sub + + Private m_WriterQueue As New SafeQueue(Of String) + Private m_ReaderQueue As New SafeQueue(Of Integer) + +End Module + +Class SafeQueue(Of T) + Private m_list As New Queue(Of T) + Public Function TryDequeue(ByRef result As T) As Boolean + SyncLock m_list + If m_list.Count = 0 Then Return False + result = m_list.Dequeue + Return True + End SyncLock + End Function + Public Sub Enqueue(ByVal value As T) + SyncLock m_list + m_list.Enqueue(value) + End SyncLock + End Sub +End Class diff --git a/Task/System-time/0DESCRIPTION b/Task/System-time/0DESCRIPTION new file mode 100644 index 0000000000..4578ea26d7 --- /dev/null +++ b/Task/System-time/0DESCRIPTION @@ -0,0 +1,5 @@ +Output the system time (any units will do as long as they are noted) either by a [[Execute a System Command|system command]] or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. + +'''See Also''' +* [[Date format]] +* [[wp:System time#Retrieving system time|Retrieving system time (wiki)]] diff --git a/Task/System-time/1META.yaml b/Task/System-time/1META.yaml new file mode 100644 index 0000000000..f6d82c59ad --- /dev/null +++ b/Task/System-time/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming environment operations diff --git a/Task/System-time/ALGOL-68/system-time.alg b/Task/System-time/ALGOL-68/system-time.alg new file mode 100644 index 0000000000..c69941151a --- /dev/null +++ b/Task/System-time/ALGOL-68/system-time.alg @@ -0,0 +1,5 @@ +FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,", \ + minutes="2d,", seconds="2d,", day of week="d,", \ + daylight-saving-time flag="dl$; +printf((time repr, local time)); +printf((time repr, utc time)) diff --git a/Task/System-time/AWK/system-time.awk b/Task/System-time/AWK/system-time.awk new file mode 100644 index 0000000000..5911f9de55 --- /dev/null +++ b/Task/System-time/AWK/system-time.awk @@ -0,0 +1,2 @@ +$ awk 'BEGIN{print systime(),strftime()}' +1242401632 Fri May 15 17:33:52 2009 diff --git a/Task/System-time/Ada/system-time.ada b/Task/System-time/Ada/system-time.ada new file mode 100644 index 0000000000..1947804a63 --- /dev/null +++ b/Task/System-time/Ada/system-time.ada @@ -0,0 +1,10 @@ +with Ada.Calendar; use Ada.Calendar; +with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; +with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones; +with Ada.Text_Io; use Ada.Text_Io; + +procedure System_Time is + Now : Time := Clock; +begin + Put_line(Image(Date => Now, Time_Zone => -7*60)); +end System_Time; diff --git a/Task/System-time/Aime/system-time.aime b/Task/System-time/Aime/system-time.aime new file mode 100644 index 0000000000..6eb84b186c --- /dev/null +++ b/Task/System-time/Aime/system-time.aime @@ -0,0 +1,16 @@ +date d; + +d_now(d); + +o_integer(d_year(d)); +o_byte('-'); +o_fxinteger(2, 10, d_y_month(d)); +o_byte('-'); +o_fxinteger(2, 10, d_m_day(d)); +o_byte(' '); +o_fxinteger(2, 10, d_d_hour(d)); +o_byte(':'); +o_fxinteger(2, 10, d_h_minute(d)); +o_byte(':'); +o_fxinteger(2, 10, d_m_second(d)); +o_byte('\n'); diff --git a/Task/System-time/AppleScript/system-time.applescript b/Task/System-time/AppleScript/system-time.applescript new file mode 100644 index 0000000000..71a828eacc --- /dev/null +++ b/Task/System-time/AppleScript/system-time.applescript @@ -0,0 +1 @@ +display dialog (current date) diff --git a/Task/System-time/AutoHotkey/system-time.ahk b/Task/System-time/AutoHotkey/system-time.ahk new file mode 100644 index 0000000000..091033ff34 --- /dev/null +++ b/Task/System-time/AutoHotkey/system-time.ahk @@ -0,0 +1,2 @@ +FormatTime, t +MsgBox,% t diff --git a/Task/System-time/AutoIt/system-time.autoit b/Task/System-time/AutoIt/system-time.autoit new file mode 100644 index 0000000000..94a722cd52 --- /dev/null +++ b/Task/System-time/AutoIt/system-time.autoit @@ -0,0 +1 @@ +MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC) diff --git a/Task/System-time/BASIC/system-time-1.basic b/Task/System-time/BASIC/system-time-1.basic new file mode 100644 index 0000000000..df6aeb9e57 --- /dev/null +++ b/Task/System-time/BASIC/system-time-1.basic @@ -0,0 +1 @@ +PRINT TIMER diff --git a/Task/System-time/BASIC/system-time-2.basic b/Task/System-time/BASIC/system-time-2.basic new file mode 100644 index 0000000000..ba733d7b36 --- /dev/null +++ b/Task/System-time/BASIC/system-time-2.basic @@ -0,0 +1 @@ +PRINT TIME$ diff --git a/Task/System-time/BBC-BASIC/system-time-1.bbc b/Task/System-time/BBC-BASIC/system-time-1.bbc new file mode 100644 index 0000000000..4b5ee81add --- /dev/null +++ b/Task/System-time/BBC-BASIC/system-time-1.bbc @@ -0,0 +1 @@ + PRINT TIME$ diff --git a/Task/System-time/BBC-BASIC/system-time-2.bbc b/Task/System-time/BBC-BASIC/system-time-2.bbc new file mode 100644 index 0000000000..e75aceb4ec --- /dev/null +++ b/Task/System-time/BBC-BASIC/system-time-2.bbc @@ -0,0 +1 @@ + PRINT RIGHT$(TIME$,8) diff --git a/Task/System-time/Batch-File/system-time-1.bat b/Task/System-time/Batch-File/system-time-1.bat new file mode 100644 index 0000000000..1e93d77d6f --- /dev/null +++ b/Task/System-time/Batch-File/system-time-1.bat @@ -0,0 +1,2 @@ +date /t +time /t diff --git a/Task/System-time/Batch-File/system-time-2.bat b/Task/System-time/Batch-File/system-time-2.bat new file mode 100644 index 0000000000..abdeb74723 --- /dev/null +++ b/Task/System-time/Batch-File/system-time-2.bat @@ -0,0 +1 @@ +echo %DATE% %TIME% diff --git a/Task/System-time/C++/system-time.cpp b/Task/System-time/C++/system-time.cpp new file mode 100644 index 0000000000..d21c008b54 --- /dev/null +++ b/Task/System-time/C++/system-time.cpp @@ -0,0 +1,8 @@ +#include +#include + +int main( ) { + boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ; + std::cout << to_simple_string( t ) << std::endl ; + return 0 ; +} diff --git a/Task/System-time/C/system-time.c b/Task/System-time/C/system-time.c new file mode 100644 index 0000000000..22e423b2ea --- /dev/null +++ b/Task/System-time/C/system-time.c @@ -0,0 +1,8 @@ +#include +#include +#include +int main(){ + time_t my_time = time(NULL); + printf("%s", ctime(&my_time)); + return 0; +} diff --git a/Task/System-time/Clojure/system-time.clj b/Task/System-time/Clojure/system-time.clj new file mode 100644 index 0000000000..79064a8c94 --- /dev/null +++ b/Task/System-time/Clojure/system-time.clj @@ -0,0 +1,7 @@ +(import '[java.util Date]) +; the current system date time string +(print (new Date)) +; the system time as milliseconds since 1970 +(print (. (new Date) getTime)) +; or +(print (System/currentTimeMillis)) diff --git a/Task/System-time/Common-Lisp/system-time.lisp b/Task/System-time/Common-Lisp/system-time.lisp new file mode 100644 index 0000000000..b6de81e0e2 --- /dev/null +++ b/Task/System-time/Common-Lisp/system-time.lisp @@ -0,0 +1,2 @@ +(multiple-value-bind (second minute hour day month year) (get-decoded-time) + (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second)) diff --git a/Task/System-time/D/system-time.d b/Task/System-time/D/system-time.d new file mode 100644 index 0000000000..534d94ae74 --- /dev/null +++ b/Task/System-time/D/system-time.d @@ -0,0 +1 @@ +Stdout(Clock.now.span.days / 365).newline; diff --git a/Task/System-time/DWScript/system-time.dwscript b/Task/System-time/DWScript/system-time.dwscript new file mode 100644 index 0000000000..7b7e898842 --- /dev/null +++ b/Task/System-time/DWScript/system-time.dwscript @@ -0,0 +1 @@ +PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now)); diff --git a/Task/System-time/Delphi/system-time.delphi b/Task/System-time/Delphi/system-time.delphi new file mode 100644 index 0000000000..2e36a28a81 --- /dev/null +++ b/Task/System-time/Delphi/system-time.delphi @@ -0,0 +1 @@ +lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now); diff --git a/Task/System-time/E/system-time.e b/Task/System-time/E/system-time.e new file mode 100644 index 0000000000..802f58efee --- /dev/null +++ b/Task/System-time/E/system-time.e @@ -0,0 +1 @@ +println(timer.now()) diff --git a/Task/System-time/Erlang/system-time-1.erl b/Task/System-time/Erlang/system-time-1.erl new file mode 100644 index 0000000000..84d766f0fb --- /dev/null +++ b/Task/System-time/Erlang/system-time-1.erl @@ -0,0 +1,2 @@ +1> os:timestamp(). +{1250,222584,635452} diff --git a/Task/System-time/Erlang/system-time-2.erl b/Task/System-time/Erlang/system-time-2.erl new file mode 100644 index 0000000000..cb66cb601a --- /dev/null +++ b/Task/System-time/Erlang/system-time-2.erl @@ -0,0 +1,6 @@ +2> calendar:now_to_datetime(os:timestamp()). +{{2009,8,14},{4,3,24}} +3> calendar:now_to_universal_time(os:timestamp()). +{{2009,8,14},{4,3,40}} +4> calendar:now_to_local_time(os:timestamp()). +{{2009,8,14},{0,7,01}} diff --git a/Task/System-time/Factor/system-time.factor b/Task/System-time/Factor/system-time.factor new file mode 100644 index 0000000000..2be6bd0bbe --- /dev/null +++ b/Task/System-time/Factor/system-time.factor @@ -0,0 +1,3 @@ +USE: calendar + +now . diff --git a/Task/System-time/Fantom/system-time.fantom b/Task/System-time/Fantom/system-time.fantom new file mode 100644 index 0000000000..e24a515c76 --- /dev/null +++ b/Task/System-time/Fantom/system-time.fantom @@ -0,0 +1,6 @@ +fansh> DateTime.nowTicks +351823905158000000 +fansh> DateTime.now +2011-02-24T00:51:47.066Z London +fansh> DateTime.now.toJava +1298508885979 diff --git a/Task/System-time/Forth/system-time.fth b/Task/System-time/Forth/system-time.fth new file mode 100644 index 0000000000..6f146729d8 --- /dev/null +++ b/Task/System-time/Forth/system-time.fth @@ -0,0 +1,18 @@ +[UNDEFINED] MS@ [IF] \ Win32Forth (rolls over daily) + [DEFINED] ?MS [IF] ( -- ms ) + : ms@ ?MS ; \ iForth + [ELSE] [DEFINED] cputime [IF] ( -- Dusec ) + : ms@ cputime d+ 1000 um/mod nip ; \ gforth: Anton Ertl + [ELSE] [DEFINED] timer@ [IF] ( -- Dusec ) + : ms@ timer@ >us 1000 um/mod nip ; \ bigForth + [ELSE] [DEFINED] gettimeofday [IF] ( -- usec sec ) + : ms@ gettimeofday 1000 MOD 1000 * SWAP 1000 / + ; \ PFE + [ELSE] [DEFINED] counter [IF] + : ms@ counter ; \ SwiftForth + [ELSE] [DEFINED] GetTickCount [IF] + : ms@ GetTickCount ; \ VFX Forth + [ELSE] [DEFINED] MICROSECS [IF] + : ms@ microsecs 1000 UM/MOD nip ; \ MacForth +[THEN] [THEN] [THEN] [THEN] [THEN] [THEN] [THEN] + +MS@ . \ print millisecond counter diff --git a/Task/System-time/Fortran/system-time-1.f b/Task/System-time/Fortran/system-time-1.f new file mode 100644 index 0000000000..940df9d244 --- /dev/null +++ b/Task/System-time/Fortran/system-time-1.f @@ -0,0 +1,13 @@ +integer :: start, stop, rate +real :: result + +! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!) +! optional 2nd integer argument (COUNT_RATE) is clock cycles per second +! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value +call system_clock( start, rate ) + +result = do_timed_work() + +call system_clock( stop ) + +print *, "elapsed time: ", real(stop - start) / real(rate) diff --git a/Task/System-time/Fortran/system-time-2.f b/Task/System-time/Fortran/system-time-2.f new file mode 100644 index 0000000000..2998950f28 --- /dev/null +++ b/Task/System-time/Fortran/system-time-2.f @@ -0,0 +1,11 @@ +real :: start, stop +real :: result + +! System clock value interpreted as floating point seconds +call cpu_time( start ) + +result = do_timed_work() + +call cpu_time( stop ) + +print *, "elapsed time: ", stop - start diff --git a/Task/System-time/GUISS/system-time.guiss b/Task/System-time/GUISS/system-time.guiss new file mode 100644 index 0000000000..479f2083fc --- /dev/null +++ b/Task/System-time/GUISS/system-time.guiss @@ -0,0 +1 @@ +Taskbar diff --git a/Task/System-time/Go/system-time.go b/Task/System-time/Go/system-time.go new file mode 100644 index 0000000000..fa55eea51f --- /dev/null +++ b/Task/System-time/Go/system-time.go @@ -0,0 +1,10 @@ +package main + +import "time" +import "fmt" + +func main() { + t := time.Now() + fmt.Println(t) // default format + fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format +} diff --git a/Task/System-time/Groovy/system-time.groovy b/Task/System-time/Groovy/system-time.groovy new file mode 100644 index 0000000000..232d12520e --- /dev/null +++ b/Task/System-time/Groovy/system-time.groovy @@ -0,0 +1,2 @@ +def nowMillis = new Date().time +println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis diff --git a/Task/System-time/Haskell/system-time-1.hs b/Task/System-time/Haskell/system-time-1.hs new file mode 100644 index 0000000000..ad6db90abc --- /dev/null +++ b/Task/System-time/Haskell/system-time-1.hs @@ -0,0 +1,7 @@ +import System.Time +import System.Locale + +main = do ct <- getClockTime + print ct -- print default format, or + cal <- toCalendarTime ct + putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal diff --git a/Task/System-time/Haskell/system-time-2.hs b/Task/System-time/Haskell/system-time-2.hs new file mode 100644 index 0000000000..31da76c2e4 --- /dev/null +++ b/Task/System-time/Haskell/system-time-2.hs @@ -0,0 +1,6 @@ +import Data.Time +import System.Locale + +main = do zt <- getZonedTime + print zt -- print default format, or + putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt diff --git a/Task/System-time/HicEst/system-time.hicest b/Task/System-time/HicEst/system-time.hicest new file mode 100644 index 0000000000..26db9d934c --- /dev/null +++ b/Task/System-time/HicEst/system-time.hicest @@ -0,0 +1,4 @@ +seconds_since_midnight = TIME() ! msec as fraction + +seconds_since_midnight = TIME(Year=yr, Day=day, WeekDay=wday, Gregorian=gday) + ! other options e.g. Excel, YYYYMMDD (num or text) diff --git a/Task/System-time/Icon/system-time.icon b/Task/System-time/Icon/system-time.icon new file mode 100644 index 0000000000..b6f1c99124 --- /dev/null +++ b/Task/System-time/Icon/system-time.icon @@ -0,0 +1,11 @@ +procedure main() + + write("&time - milliseconds of CPU time = ",&time) + write("&clock - Time of day as hh:mm:ss (24-hour format) = ",&clock) + write("&date - current date in yyyy/mm/dd format = ",&date) + write("&dateline - timestamp with day of the week, date, and current time to the minute = ",&dateline) + + if find("Unicon",&version) then + write("&now - time in seconds since the epoch = ", &now) # Unicon only + +end diff --git a/Task/System-time/Io/system-time-1.io b/Task/System-time/Io/system-time-1.io new file mode 100644 index 0000000000..248ed1b723 --- /dev/null +++ b/Task/System-time/Io/system-time-1.io @@ -0,0 +1 @@ +Date now println diff --git a/Task/System-time/Io/system-time-2.io b/Task/System-time/Io/system-time-2.io new file mode 100644 index 0000000000..007fcca316 --- /dev/null +++ b/Task/System-time/Io/system-time-2.io @@ -0,0 +1 @@ +2008-08-26 00:15:52 EDT diff --git a/Task/System-time/J/system-time-1.j b/Task/System-time/J/system-time-1.j new file mode 100644 index 0000000000..6dbe7030f6 --- /dev/null +++ b/Task/System-time/J/system-time-1.j @@ -0,0 +1,2 @@ + 6!:0 '' +2008 1 23 12 52 10.341 diff --git a/Task/System-time/J/system-time-2.j b/Task/System-time/J/system-time-2.j new file mode 100644 index 0000000000..8f7a675daa --- /dev/null +++ b/Task/System-time/J/system-time-2.j @@ -0,0 +1,2 @@ + 6!:0 'YYYY-MM-DD hh:mm:ss.sss' +2009-08-26 10:38:53.171 diff --git a/Task/System-time/Java/system-time-1.java b/Task/System-time/Java/system-time-1.java new file mode 100644 index 0000000000..660ebeeabc --- /dev/null +++ b/Task/System-time/Java/system-time-1.java @@ -0,0 +1,5 @@ +public class SystemTime{ + public static void main(String[] args){ + System.out.format("%tc%n", System.currentTimeMillis()); + } +} diff --git a/Task/System-time/Java/system-time-2.java b/Task/System-time/Java/system-time-2.java new file mode 100644 index 0000000000..a96e2ed0d5 --- /dev/null +++ b/Task/System-time/Java/system-time-2.java @@ -0,0 +1,11 @@ +import java.util.Date; + +public class SystemTime{ + public static void main(String[] args){ + Date now = new Date(); + System.out.println(now); // string representation + + System.out.println(now.getTime()); // Unix time (# of milliseconds since Jan 1 1970) + //System.currentTimeMillis() returns the same value + } +} diff --git a/Task/System-time/JavaScript/system-time.js b/Task/System-time/JavaScript/system-time.js new file mode 100644 index 0000000000..a2df645b86 --- /dev/null +++ b/Task/System-time/JavaScript/system-time.js @@ -0,0 +1,3 @@ +console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT + +console.log(Date.now()) // => 1306571005417 // Unix epoch diff --git a/Task/System-time/Liberty-BASIC/system-time.liberty b/Task/System-time/Liberty-BASIC/system-time.liberty new file mode 100644 index 0000000000..f9596adff3 --- /dev/null +++ b/Task/System-time/Liberty-BASIC/system-time.liberty @@ -0,0 +1,4 @@ +print time$() 'time now as string "16:21:44" +print time$("seconds") 'seconds since midnight as number 32314 +print time$("milliseconds") 'milliseconds since midnight as number 33221342 +print time$("ms") 'milliseconds since midnight as number 33221342 diff --git a/Task/System-time/Locomotive-Basic/system-time.locomotive b/Task/System-time/Locomotive-Basic/system-time.locomotive new file mode 100644 index 0000000000..3605e5b4c8 --- /dev/null +++ b/Task/System-time/Locomotive-Basic/system-time.locomotive @@ -0,0 +1,2 @@ +print time +print time/300;"s since last reboot" diff --git a/Task/System-time/Logo/system-time.logo b/Task/System-time/Logo/system-time.logo new file mode 100644 index 0000000000..2d63736a6b --- /dev/null +++ b/Task/System-time/Logo/system-time.logo @@ -0,0 +1,7 @@ +to time + output first first shell [date +%s] +end + +make "start time +wait 300 ; 60ths of a second +print time - :start ; 5 diff --git a/Task/System-time/Lua/system-time.lua b/Task/System-time/Lua/system-time.lua new file mode 100644 index 0000000000..50fb7a9b31 --- /dev/null +++ b/Task/System-time/Lua/system-time.lua @@ -0,0 +1 @@ +print(os.date()) diff --git a/Task/System-time/MATLAB/system-time-1.m b/Task/System-time/MATLAB/system-time-1.m new file mode 100644 index 0000000000..b023b0bc8b --- /dev/null +++ b/Task/System-time/MATLAB/system-time-1.m @@ -0,0 +1 @@ + datestr(now) diff --git a/Task/System-time/MATLAB/system-time-2.m b/Task/System-time/MATLAB/system-time-2.m new file mode 100644 index 0000000000..49d8548606 --- /dev/null +++ b/Task/System-time/MATLAB/system-time-2.m @@ -0,0 +1 @@ + clock diff --git a/Task/System-time/MUMPS/system-time.mumps b/Task/System-time/MUMPS/system-time.mumps new file mode 100644 index 0000000000..00556ee315 --- /dev/null +++ b/Task/System-time/MUMPS/system-time.mumps @@ -0,0 +1,6 @@ +SYSTIME + NEW PH + SET PH=$PIECE($HOROLOG,",",2) + WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60 + KILL PH + QUIT diff --git a/Task/System-time/Mathematica/system-time.math b/Task/System-time/Mathematica/system-time.math new file mode 100644 index 0000000000..41dbc832fc --- /dev/null +++ b/Task/System-time/Mathematica/system-time.math @@ -0,0 +1,2 @@ +Print[DateList[]] +Print[AbsoluteTime[]] diff --git a/Task/System-time/Maxima/system-time.maxima b/Task/System-time/Maxima/system-time.maxima new file mode 100644 index 0000000000..5afb58a028 --- /dev/null +++ b/Task/System-time/Maxima/system-time.maxima @@ -0,0 +1,10 @@ +/* Time and date in a formatted string */ +timedate(); +"2012-08-27 20:26:23+10:00" + +/* Time in seconds elapsed since 1900/1/1 0:0:0 */ +absolute_real_time(); + +/* Time in seconds since Maxima was started */ +elapsed_real_time(); +elapsed_run_time(); diff --git a/Task/System-time/Modula-3/system-time.mod3 b/Task/System-time/Modula-3/system-time.mod3 new file mode 100644 index 0000000000..fafd7c2cdd --- /dev/null +++ b/Task/System-time/Modula-3/system-time.mod3 @@ -0,0 +1,7 @@ +MODULE MyTime EXPORTS Main; + +IMPORT IO, FmtTime, Time; + +BEGIN + IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n"); +END MyTime. diff --git a/Task/System-time/NetRexx/system-time.netrexx b/Task/System-time/NetRexx/system-time.netrexx new file mode 100644 index 0000000000..60038e3271 --- /dev/null +++ b/Task/System-time/NetRexx/system-time.netrexx @@ -0,0 +1,2 @@ +import java.text.SimpleDateFormat +say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date()) diff --git a/Task/System-time/OCaml/system-time.ocaml b/Task/System-time/OCaml/system-time.ocaml new file mode 100644 index 0000000000..93365d911c --- /dev/null +++ b/Task/System-time/OCaml/system-time.ocaml @@ -0,0 +1,12 @@ +#load "unix.cma";; +open Unix;; +let {tm_sec = sec; + tm_min = min; + tm_hour = hour; + tm_mday = mday; + tm_mon = mon; + tm_year = year; + tm_wday = wday; + tm_yday = yday; + tm_isdst = isdst} = localtime (time ());; +Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hour min sec;; diff --git a/Task/System-time/Objeck/system-time.objeck b/Task/System-time/Objeck/system-time.objeck new file mode 100644 index 0000000000..342685f290 --- /dev/null +++ b/Task/System-time/Objeck/system-time.objeck @@ -0,0 +1,4 @@ +function : Time() ~ Nil { + t := Time->New(); + IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds()); +} diff --git a/Task/System-time/Objective-C/system-time-1.m b/Task/System-time/Objective-C/system-time-1.m new file mode 100644 index 0000000000..ac3d89af6b --- /dev/null +++ b/Task/System-time/Objective-C/system-time-1.m @@ -0,0 +1 @@ +NSLog(@"%@", [NSDate date]); diff --git a/Task/System-time/Objective-C/system-time-2.m b/Task/System-time/Objective-C/system-time-2.m new file mode 100644 index 0000000000..3283d4098b --- /dev/null +++ b/Task/System-time/Objective-C/system-time-2.m @@ -0,0 +1 @@ +NSLog(@"%@", [NSCalendarDate calendarDate]); diff --git a/Task/System-time/Oz/system-time.oz b/Task/System-time/Oz/system-time.oz new file mode 100644 index 0000000000..9ba2c0bd39 --- /dev/null +++ b/Task/System-time/Oz/system-time.oz @@ -0,0 +1,8 @@ +{Show {OS.time}} %% posix time (seconds since 1970-01-01) +{Show {OS.gmTime}} %% current UTC as a record +{Show {OS.localTime}} %% current local time as record + +%% Also interesting: undocumented module OsTime +%% When did posix time reach 1 billion? +{Show {OsTime.gmtime 1000000000}} +{Show {OsTime.localtime 1000000000}} diff --git a/Task/System-time/PARI-GP/system-time.pari b/Task/System-time/PARI-GP/system-time.pari new file mode 100644 index 0000000000..324854ad25 --- /dev/null +++ b/Task/System-time/PARI-GP/system-time.pari @@ -0,0 +1 @@ +system("date") diff --git a/Task/System-time/PHP/system-time-1.php b/Task/System-time/PHP/system-time-1.php new file mode 100644 index 0000000000..5896f438f5 --- /dev/null +++ b/Task/System-time/PHP/system-time-1.php @@ -0,0 +1 @@ +echo time(), "\n"; diff --git a/Task/System-time/PHP/system-time-2.php b/Task/System-time/PHP/system-time-2.php new file mode 100644 index 0000000000..5ce460cbf9 --- /dev/null +++ b/Task/System-time/PHP/system-time-2.php @@ -0,0 +1 @@ +echo microtime(), "\n"; diff --git a/Task/System-time/PHP/system-time-3.php b/Task/System-time/PHP/system-time-3.php new file mode 100644 index 0000000000..7cfab6425a --- /dev/null +++ b/Task/System-time/PHP/system-time-3.php @@ -0,0 +1,6 @@ +echo date('D M j H:i:s Y'), "\n"; // custom format; see format characters here: + // http://us3.php.net/manual/en/function.date.php +echo date('c'), "\n"; // ISO 8601 format +echo date('r'), "\n"; // RFC 2822 format +echo date(DATE_RSS), "\n"; // can also use one of the predefined formats here: + // http://us3.php.net/manual/en/class.datetime.php#datetime.constants.types diff --git a/Task/System-time/PL-I/system-time.pli b/Task/System-time/PL-I/system-time.pli new file mode 100644 index 0000000000..d4d14bc919 --- /dev/null +++ b/Task/System-time/PL-I/system-time.pli @@ -0,0 +1,4 @@ +put (datetime()); /* writes out the date and time */ + /* The time is given to thousandths of a second, */ + /* in the format hhmiss999 */ +put (time()); /* gives the time in the format hhmiss999. */ diff --git a/Task/System-time/Pascal/system-time.pascal b/Task/System-time/Pascal/system-time.pascal new file mode 100644 index 0000000000..ca57727540 --- /dev/null +++ b/Task/System-time/Pascal/system-time.pascal @@ -0,0 +1,43 @@ +program systime; +uses DOS; + +{ Format digit with leading zero } +function lz(w: word): string; +var + s: string; +begin + str(w,s); + if length(s) = 1 then + s := '0' + s; + lz := s; +end; + +var + h,m,s,c: word; + yr,mo,da,dw: word; + dt: datetime; + t,ssm: longint; + regs: registers; + +begin + + { Time and Date } + GetTime(h,m,s,c); + writeln(lz(h),':',lz(m),':',lz(s),'.',c); + GetDate(yr,mo,da,dw); + writeln(yr,'-',lz(mo),'-',lz(da)); + + { Turbo Epoch, seconds } + with dt do begin + year := yr; month := mo; day := da; + hour := h; min := m; sec := s; + end; + packtime(dt,t); + writeln(t); + + { Seconds since midnight, PC-BIOS 1Ah } + regs.ah := 0; Intr($1A,regs); + ssm := round((regs.cx * 65536 + regs.dx) * (65536 / 1192180)); + writeln(ssm); + +end. diff --git a/Task/System-time/Perl-6/system-time.pl6 b/Task/System-time/Perl-6/system-time.pl6 new file mode 100644 index 0000000000..63efb72392 --- /dev/null +++ b/Task/System-time/Perl-6/system-time.pl6 @@ -0,0 +1 @@ +say DateTime.now; diff --git a/Task/System-time/Perl/system-time-1.pl b/Task/System-time/Perl/system-time-1.pl new file mode 100644 index 0000000000..05642f5af2 --- /dev/null +++ b/Task/System-time/Perl/system-time-1.pl @@ -0,0 +1 @@ +print scalar localtime, "\n"; diff --git a/Task/System-time/Perl/system-time-2.pl b/Task/System-time/Perl/system-time-2.pl new file mode 100644 index 0000000000..20b4e8035f --- /dev/null +++ b/Task/System-time/Perl/system-time-2.pl @@ -0,0 +1,2 @@ +($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime; +printf("%04d-%02d-%02d %02d:%02d:%02d\n", $year + 1900, $mon + 1, $mday, $hour, $min, $sec); diff --git a/Task/System-time/Perl/system-time-3.pl b/Task/System-time/Perl/system-time-3.pl new file mode 100644 index 0000000000..4ef86d07e3 --- /dev/null +++ b/Task/System-time/Perl/system-time-3.pl @@ -0,0 +1,5 @@ +use DateTime; +my $dt = DateTime->now; +my $d = $dt->ymd; +my $t = $dt->hms; +print "$d $t\n"; diff --git a/Task/System-time/Perl/system-time-4.pl b/Task/System-time/Perl/system-time-4.pl new file mode 100644 index 0000000000..15811e6553 --- /dev/null +++ b/Task/System-time/Perl/system-time-4.pl @@ -0,0 +1,4 @@ +use POSIX qw(strftime); + +$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; +print "$now_string\n"; diff --git a/Task/System-time/Perl/system-time-5.pl b/Task/System-time/Perl/system-time-5.pl new file mode 100644 index 0000000000..580d3327a9 --- /dev/null +++ b/Task/System-time/Perl/system-time-5.pl @@ -0,0 +1,6 @@ +use DateTime; +my $dt = DateTime->now; +say $dt->iso8601(); +say $dt->year_with_christian_era(); +say $dt->year_with_secular_era(); +# etc. diff --git a/Task/System-time/Perl/system-time-6.pl b/Task/System-time/Perl/system-time-6.pl new file mode 100644 index 0000000000..4734b7a416 --- /dev/null +++ b/Task/System-time/Perl/system-time-6.pl @@ -0,0 +1 @@ +print time; diff --git a/Task/System-time/PicoLisp/system-time.l b/Task/System-time/PicoLisp/system-time.l new file mode 100644 index 0000000000..ba04349c3c --- /dev/null +++ b/Task/System-time/PicoLisp/system-time.l @@ -0,0 +1 @@ +(stamp) diff --git a/Task/System-time/PowerShell/system-time-1.psh b/Task/System-time/PowerShell/system-time-1.psh new file mode 100644 index 0000000000..ca730cb4a0 --- /dev/null +++ b/Task/System-time/PowerShell/system-time-1.psh @@ -0,0 +1 @@ +Get-Date diff --git a/Task/System-time/PowerShell/system-time-2.psh b/Task/System-time/PowerShell/system-time-2.psh new file mode 100644 index 0000000000..e53815001e --- /dev/null +++ b/Task/System-time/PowerShell/system-time-2.psh @@ -0,0 +1 @@ +[DateTime]::Now diff --git a/Task/System-time/PureBasic/system-time.purebasic b/Task/System-time/PureBasic/system-time.purebasic new file mode 100644 index 0000000000..08df227872 --- /dev/null +++ b/Task/System-time/PureBasic/system-time.purebasic @@ -0,0 +1,6 @@ +time=Date() ; Unix timestamp +time$=FormatDate("%mm.%dd.%yyyy %hh:%ii:%ss",time) + +; following value is only reasonable accurate, on Windows it can differ by +/- 20 ms +ms_counter=ElapsedMilliseconds() +; could use API like QueryPerformanceCounter_() on Windows for more accurate values diff --git a/Task/System-time/Python/system-time.py b/Task/System-time/Python/system-time.py new file mode 100644 index 0000000000..513d9a94ab --- /dev/null +++ b/Task/System-time/Python/system-time.py @@ -0,0 +1,2 @@ +import time +print time.ctime() diff --git a/Task/System-time/Q/system-time.q b/Task/System-time/Q/system-time.q new file mode 100644 index 0000000000..ea5f4d1ae1 --- /dev/null +++ b/Task/System-time/Q/system-time.q @@ -0,0 +1,12 @@ +q).z.D +2010.01.25 +q).z.N +0D14:17:45.519682000 +q).z.P +2010.01.25D14:17:46.962375000 +q).z.T +14:17:47.817 +q).z.Z +2010.01.25T14:17:48.711 +q).z.z +2010.01.25T19:17:59.445 diff --git a/Task/System-time/R/system-time.r b/Task/System-time/R/system-time.r new file mode 100644 index 0000000000..44ee0d4167 --- /dev/null +++ b/Task/System-time/R/system-time.r @@ -0,0 +1 @@ +Sys.time() diff --git a/Task/System-time/REBOL/system-time.rebol b/Task/System-time/REBOL/system-time.rebol new file mode 100644 index 0000000000..a6ec70b1c1 --- /dev/null +++ b/Task/System-time/REBOL/system-time.rebol @@ -0,0 +1,2 @@ +now +print rejoin [now/year "-" now/month "-" now/day " " now/time] diff --git a/Task/System-time/REXX/system-time.rexx b/Task/System-time/REXX/system-time.rexx new file mode 100644 index 0000000000..4f4ffc29b1 --- /dev/null +++ b/Task/System-time/REXX/system-time.rexx @@ -0,0 +1,11 @@ +say time() /* hh:mm:ss (hh is 00 --> 23). */ +say time('n') /* (same as above) */ +say time('N') /* (same as above) */ +say time('Normal') /* (same as above) */ +say time('nitPick') /* (same as above) */ + +say time('C') /* hh:mmam or hh:mmpm (hh is 0 --> 12). */ +say time('Civil') /* (same as above) */ + +say time('L') /* hh:mm:ss.ffffff (hh is ---> 23). */ +say time('Long') /* (same as above) */ diff --git a/Task/System-time/Racket/system-time-1.rkt b/Task/System-time/Racket/system-time-1.rkt new file mode 100644 index 0000000000..fafe62751d --- /dev/null +++ b/Task/System-time/Racket/system-time-1.rkt @@ -0,0 +1,3 @@ +#lang racket +(require racket/date) +(date->string (current-date)) diff --git a/Task/System-time/Racket/system-time-2.rkt b/Task/System-time/Racket/system-time-2.rkt new file mode 100644 index 0000000000..06299627c2 --- /dev/null +++ b/Task/System-time/Racket/system-time-2.rkt @@ -0,0 +1,2 @@ +#lang racket +(current-seconds) diff --git a/Task/System-time/Retro/system-time.retro b/Task/System-time/Retro/system-time.retro new file mode 100644 index 0000000000..5e717fdffa --- /dev/null +++ b/Task/System-time/Retro/system-time.retro @@ -0,0 +1 @@ +time putn diff --git a/Task/System-time/Ruby/system-time.rb b/Task/System-time/Ruby/system-time.rb new file mode 100644 index 0000000000..92d77bbb0c --- /dev/null +++ b/Task/System-time/Ruby/system-time.rb @@ -0,0 +1,10 @@ +t = Time.now + +# textual +puts t # => Wed Aug 05 20:14:50 -0400 2009 + +# epoch time +puts t.to_i # => 1249517690 + +# epoch time with fractional seconds +puts t.to_f # => 1249517690.74388 diff --git a/Task/System-time/SNOBOL4/system-time.sno b/Task/System-time/SNOBOL4/system-time.sno new file mode 100644 index 0000000000..2f0f27a020 --- /dev/null +++ b/Task/System-time/SNOBOL4/system-time.sno @@ -0,0 +1,2 @@ + OUTPUT = DATE() +END diff --git a/Task/System-time/Scala/system-time.scala b/Task/System-time/Scala/system-time.scala new file mode 100644 index 0000000000..26d8129d7a --- /dev/null +++ b/Task/System-time/Scala/system-time.scala @@ -0,0 +1 @@ +println(new java.util.Date) diff --git a/Task/System-time/Scheme/system-time.ss b/Task/System-time/Scheme/system-time.ss new file mode 100644 index 0000000000..01e1b945fe --- /dev/null +++ b/Task/System-time/Scheme/system-time.ss @@ -0,0 +1,2 @@ +(use posix) +(seconds->string (current-seconds)) diff --git a/Task/System-time/Seed7/system-time.seed7 b/Task/System-time/Seed7/system-time.seed7 new file mode 100644 index 0000000000..3af984611d --- /dev/null +++ b/Task/System-time/Seed7/system-time.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "time.s7i"; + +const proc: main is func + begin + writeln(time(NOW)); + end func; diff --git a/Task/System-time/Smalltalk/system-time-1.st b/Task/System-time/Smalltalk/system-time-1.st new file mode 100644 index 0000000000..e87bef6976 --- /dev/null +++ b/Task/System-time/Smalltalk/system-time-1.st @@ -0,0 +1 @@ +DateTime now displayNl. diff --git a/Task/System-time/Smalltalk/system-time-2.st b/Task/System-time/Smalltalk/system-time-2.st new file mode 100644 index 0000000000..f337db67dd --- /dev/null +++ b/Task/System-time/Smalltalk/system-time-2.st @@ -0,0 +1 @@ +DateAndTime now diff --git a/Task/System-time/Standard-ML/system-time.ml b/Task/System-time/Standard-ML/system-time.ml new file mode 100644 index 0000000000..e5b65b9382 --- /dev/null +++ b/Task/System-time/Standard-ML/system-time.ml @@ -0,0 +1 @@ +print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n") diff --git a/Task/System-time/TI-89-BASIC/system-time.ti-89 b/Task/System-time/TI-89-BASIC/system-time.ti-89 new file mode 100644 index 0000000000..f835e444f0 --- /dev/null +++ b/Task/System-time/TI-89-BASIC/system-time.ti-89 @@ -0,0 +1,2 @@ +■ getTime() {13 28 55} +■ getDate() {2009 8 13} diff --git a/Task/System-time/TUSCRIPT/system-time.tuscript b/Task/System-time/TUSCRIPT/system-time.tuscript new file mode 100644 index 0000000000..bfdc6281bf --- /dev/null +++ b/Task/System-time/TUSCRIPT/system-time.tuscript @@ -0,0 +1,3 @@ +$$ MODE TUSCRIPT +time=time() +PRINT time diff --git a/Task/System-time/Tcl/system-time-1.tcl b/Task/System-time/Tcl/system-time-1.tcl new file mode 100644 index 0000000000..9ee626994a --- /dev/null +++ b/Task/System-time/Tcl/system-time-1.tcl @@ -0,0 +1 @@ +puts [clock seconds] diff --git a/Task/System-time/Tcl/system-time-2.tcl b/Task/System-time/Tcl/system-time-2.tcl new file mode 100644 index 0000000000..be81a0144e --- /dev/null +++ b/Task/System-time/Tcl/system-time-2.tcl @@ -0,0 +1 @@ +puts [clock format [clock seconds]] diff --git a/Task/System-time/UNIX-Shell/system-time.sh b/Task/System-time/UNIX-Shell/system-time.sh new file mode 100644 index 0000000000..f6e0ace44b --- /dev/null +++ b/Task/System-time/UNIX-Shell/system-time.sh @@ -0,0 +1,3 @@ +date # Thu Dec 3 15:38:06 PST 2009 + +date +%s # 1259883518, seconds since the epoch, like C stdlib time(0) diff --git a/Task/System-time/Ursala/system-time.ursala b/Task/System-time/Ursala/system-time.ursala new file mode 100644 index 0000000000..af46fc380f --- /dev/null +++ b/Task/System-time/Ursala/system-time.ursala @@ -0,0 +1,5 @@ +#import cli + +#cast %s + +main = now 0 diff --git a/Task/System-time/Vala/system-time.vala b/Task/System-time/Vala/system-time.vala new file mode 100644 index 0000000000..8cba82713e --- /dev/null +++ b/Task/System-time/Vala/system-time.vala @@ -0,0 +1,2 @@ +var now = new DateTime.now_local(); +string now_string = now.to_string(); diff --git a/Task/System-time/XPL0/system-time.xpl0 b/Task/System-time/XPL0/system-time.xpl0 new file mode 100644 index 0000000000..482e8277fe --- /dev/null +++ b/Task/System-time/XPL0/system-time.xpl0 @@ -0,0 +1,21 @@ +include c:\cxpl\codes; \include intrinsic 'code' declarations + +proc NumOut(N); \Output a 2-digit number, including leading zero +int N; +[if N <= 9 then ChOut(0, ^0); +IntOut(0, N); +]; \NumOut + +int Reg; +[Reg:= GetReg; \get address of array with copy of CPU registers +Reg(0):= $2C00; \call DOS function 2C (hex) +SoftInt($21); \DOS calls are interrupt 21 (hex) +NumOut(Reg(2) >> 8); \the high byte of register CX contains the hours +ChOut(0, ^:); +NumOut(Reg(2) & $00FF); \the low byte of CX contains the minutes +ChOut(0, ^:); +NumOut(Reg(3) >> 8); \the high byte of DX contains the seconds +ChOut(0, ^.); +NumOut(Reg(3) & $00FF); \the low byte of DX contains hundreths +CrLf(0); +] diff --git a/Task/Table-creation-Postal-addresses/0DESCRIPTION b/Task/Table-creation-Postal-addresses/0DESCRIPTION new file mode 100644 index 0000000000..113ef2a598 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/0DESCRIPTION @@ -0,0 +1,3 @@ +In this task, the goal is to create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field. + +For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table. diff --git a/Task/Table-creation-Postal-addresses/1META.yaml b/Task/Table-creation-Postal-addresses/1META.yaml new file mode 100644 index 0000000000..7fec23b86a --- /dev/null +++ b/Task/Table-creation-Postal-addresses/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Database operations diff --git a/Task/Table-creation-Postal-addresses/ALGOL-68/table-creation-postal-addresses.alg b/Task/Table-creation-Postal-addresses/ALGOL-68/table-creation-postal-addresses.alg new file mode 100644 index 0000000000..109e632ef3 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/ALGOL-68/table-creation-postal-addresses.alg @@ -0,0 +1,46 @@ +MODE ADDRESS = STRUCT( + INT page, + FLEX[50]CHAR street, + FLEX[25]CHAR city, + FLEX[2]CHAR state, + FLEX[10]CHAR zip +); +FORMAT address repr = $"Page: "gl"Street: "gl"City: "gl"State: "gl"Zip: "gll$; + +INT errno; +FILE sequence; errno := open(sequence, "sequence.txt", stand back channel); +SEMA sequence sema := LEVEL 1; + +OP NEXTVAL = ([]CHAR table name)INT: ( + INT out; + # INT table page = 0; # # only one sequence implemented # + # DOWN sequence sema; # # NO interprocess concurrency protection # + on open error(sequence, + (REF FILE f)BOOL: ( + reset(sequence); #set(table page,1,1);# + put(sequence, 0); + try again; + FALSE + ) + ); + try again: + reset(sequence); #set(table page,1,1);# get(sequence,out); + out +:=1; + reset(sequence); #set(table page,1,1);# put(sequence,out); + # UP sequence sema; # + out +); + +OP INIT = (REF ADDRESS self)REF ADDRESS: ( page OF self := NEXTVAL "address"; self); + +REF ADDRESS john brown = INIT LOC ADDRESS; + +john brown := (page OF john brown, "10 Downing Street","London","England","SW1A 2AA"); + +printf((address repr, john brown)); + +FILE address table; +errno := open(address table,"address.txt",stand back channel); +# set(address table, page OF john brown,1,1); - standard set page not available in a68g # +put bin(address table, john brown); +close(address table) diff --git a/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk b/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk new file mode 100644 index 0000000000..a52539d64b --- /dev/null +++ b/Task/Table-creation-Postal-addresses/AWK/table-creation-postal-addresses.awk @@ -0,0 +1,33 @@ +#!/bin/sh -f +awk ' +BEGIN { + print "Creating table..."; + dbExec("address.db", "create table address (street, city, state, zip);"); + print "Done."; + exit; +} + +function dbExec(db, qry, result) { + dbMakeQuery(db, qry) | getline result + dbErrorCheck(result); +} + +function dbMakeQuery(db, qry, q) { + q = dbEscapeQuery(qry) ";"; + return "echo \"" q "\" | sqlite3 " db +} + +function dbEscapeQuery(qry, q) { + q = qry; + gsub(/"/, "\\\"", q); + return q; +} + +function dbErrorCheck(res) { + if (res ~ "SQL error") { + print res; + exit; + } +} + +' diff --git a/Task/Table-creation-Postal-addresses/C/table-creation-postal-addresses.c b/Task/Table-creation-Postal-addresses/C/table-creation-postal-addresses.c new file mode 100644 index 0000000000..3ac75decda --- /dev/null +++ b/Task/Table-creation-Postal-addresses/C/table-creation-postal-addresses.c @@ -0,0 +1,32 @@ +#include +#include +#include + +const char *code = +"CREATE TABLE address (\n" +" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n" +" addrStreet TEXT NOT NULL,\n" +" addrCity TEXT NOT NULL,\n" +" addrState TEXT NOT NULL,\n" +" addrZIP TEXT NOT NULL)\n" ; + +int main() +{ + sqlite3 *db = NULL; + char *errmsg; + + if ( sqlite3_open("address.db", &db) == SQLITE_OK ) { + if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) { + fprintf(stderr, errmsg); + sqlite3_free(errmsg); + sqlite3_close(db); + exit(EXIT_FAILURE); + } + sqlite3_close(db); + } else { + fprintf(stderr, "cannot open db...\n"); + sqlite3_close(db); + exit(EXIT_FAILURE); + } + return EXIT_SUCCESS; +} diff --git a/Task/Table-creation-Postal-addresses/J/table-creation-postal-addresses.j b/Task/Table-creation-Postal-addresses/J/table-creation-postal-addresses.j new file mode 100644 index 0000000000..d94baffe40 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/J/table-creation-postal-addresses.j @@ -0,0 +1,7 @@ + Create__hd 'Address';noun define +addrID autoid; +addrStreet varchar +addrCity varchar +addrState char +addrZip char +) diff --git a/Task/Table-creation-Postal-addresses/Mathematica/table-creation-postal-addresses.math b/Task/Table-creation-Postal-addresses/Mathematica/table-creation-postal-addresses.math new file mode 100644 index 0000000000..248efe24e0 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Mathematica/table-creation-postal-addresses.math @@ -0,0 +1,8 @@ +TableCreation="CREATE TABLE address ( +addrID INTEGER PRIMARY KEY AUTOINCREMENT, +addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL, +addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )"; + +Needs["DatabaseLink`"] +conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"] +SQLExecute[ conn, TableCreation] diff --git a/Task/Table-creation-Postal-addresses/MySQL/table-creation-postal-addresses.sql b/Task/Table-creation-Postal-addresses/MySQL/table-creation-postal-addresses.sql new file mode 100644 index 0000000000..484b6ca630 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/MySQL/table-creation-postal-addresses.sql @@ -0,0 +1,8 @@ +CREATE TABLE `Address` ( + `addrID` int(11) NOT NULL auto_increment, + `addrStreet` varchar(50) NOT NULL default '', + `addrCity` varchar(25) NOT NULL default '', + `addrState` char(2) NOT NULL default '', + `addrZIP` char(10) NOT NULL default '', + PRIMARY KEY (`addrID`) +); diff --git a/Task/Table-creation-Postal-addresses/NetRexx/table-creation-postal-addresses.netrexx b/Task/Table-creation-Postal-addresses/NetRexx/table-creation-postal-addresses.netrexx new file mode 100644 index 0000000000..ed6af20e43 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/NetRexx/table-creation-postal-addresses.netrexx @@ -0,0 +1,60 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import java.sql.Connection +import java.sql.Statement +import java.sql.SQLException +import java.sql.DriverManager + +class RTableCreate01 public + properties private constant + addressDDL = String '' - + ' create table Address' - + ' (' - + ' addrID integer primary key generated by default as identity,' - + ' addrStreet varchar(50) not null,' - + ' addrCity varchar(50) not null,' - + ' addrState char(2) not null,' - + ' addrZip char(10) not null' - + ' )' + driver = String 'org.apache.derby.jdbc.EmbeddedDriver' + dbName = String 'db/rosetta_code' + + method createTable() public static + connectionURL = String + conn = java.sql.Connection + sqlStatement = java.sql.Statement + do + Class.forName(driver) + connectionURL = 'jdbc:derby:' || dbName || ';' || 'create=true' + conn = DriverManager.getConnection(connectionURL) + sqlStatement = conn.createStatement() + say 'Creating table' + sqlStatement.execute(addressDDL) + say 'Table creation complete' + sqlStatement.close() + conn.close() + do + -- In embedded mode, an application should shut down Derby. + -- Shutdown throws the XJ015 exception to confirm success. + connectionURL = 'jdbc:derby:' || ';' || 'shutdown=true' + DriverManager.getConnection(connectionURL) + catch sex = SQLException + if sex.getSQLState().equals("XJ015") then do + say 'Database shut down normally' + end + else do + say 'Database did not shut down normally' + signal sex + end + end + catch sex = SQLException + sex.printStackTrace() + catch ex = ClassNotFoundException + ex.printStackTrace() + end + return + + method main(args = String[]) public static + createTable() + return diff --git a/Task/Table-creation-Postal-addresses/Oz/table-creation-postal-addresses.oz b/Task/Table-creation-Postal-addresses/Oz/table-creation-postal-addresses.oz new file mode 100644 index 0000000000..208f529b82 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Oz/table-creation-postal-addresses.oz @@ -0,0 +1,22 @@ +declare + [Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']} + + DB = {Sqlite.open 'test.db'} +in + try + + {Sqlite.exec DB + "CREATE TABLE address (" + #"addrID INTEGER PRIMARY KEY," + #"addrStreet TEXT NOT NULL," + #"addrCity TEXT NOT NULL," + #"addrState TEXT NOT NULL," + #"addrZIP TEXT NOT NULL" + #")" _} + + catch E then + {Inspector.configure widgetShowStrings true} + {Inspect E} + finally + {Sqlite.close DB} + end diff --git a/Task/Table-creation-Postal-addresses/PHP/table-creation-postal-addresses.php b/Task/Table-creation-Postal-addresses/PHP/table-creation-postal-addresses.php new file mode 100644 index 0000000000..cc7348ed25 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/PHP/table-creation-postal-addresses.php @@ -0,0 +1,12 @@ +exec(" + CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL + ) +"); +?> diff --git a/Task/Table-creation-Postal-addresses/Perl/table-creation-postal-addresses.pl b/Task/Table-creation-Postal-addresses/Perl/table-creation-postal-addresses.pl new file mode 100644 index 0000000000..509709203f --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Perl/table-creation-postal-addresses.pl @@ -0,0 +1,17 @@ +use DBI; + +my $db = DBI->connect('DBI:mysql:database:server','login','password'); + +my $statment = <prepare($statment); +$exec->execute; diff --git a/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-1.l b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-1.l new file mode 100644 index 0000000000..1ff397a4f1 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-1.l @@ -0,0 +1,12 @@ +(class +Adr +Entity) +(rel nm (+Sn +Idx +String)) # Name [Soundex index] +(rel str (+String)) # Street +(rel zip (+Ref +String)) # ZIP [Non-unique index] +(rel cit (+Fold +Idx +String)) # City [Folded substring index] +(rel st (+String)) # State +(rel tel (+Fold +Ref +String)) # Phone [Folded non-unique index] +(rel em (+Ref +String)) # EMail [Non-unique index] +(rel txt (+Blob)) # Memo +(rel jpg (+Blob)) # Photo + +(pool "address.db") # Create database diff --git a/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-2.l b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-2.l new file mode 100644 index 0000000000..a5ee5e7b6c --- /dev/null +++ b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-2.l @@ -0,0 +1,6 @@ +(show + (new! '(+Adr) # Create a record + 'nm "FSF Inc." + 'str "51 Franklin St" + 'st "Boston, MA" + 'zip "02110-1301" ) ) diff --git a/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-3.l b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-3.l new file mode 100644 index 0000000000..ba4d5cab94 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/PicoLisp/table-creation-postal-addresses-3.l @@ -0,0 +1 @@ +(select nm zip +Adr nm "FSF") # Select name, zip from Adr where name = FSF* diff --git a/Task/Table-creation-Postal-addresses/PureBasic/table-creation-postal-addresses.purebasic b/Task/Table-creation-Postal-addresses/PureBasic/table-creation-postal-addresses.purebasic new file mode 100644 index 0000000000..a97e17eda7 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/PureBasic/table-creation-postal-addresses.purebasic @@ -0,0 +1,22 @@ +UseSQLiteDatabase() +Procedure CheckDatabaseUpdate(Database, Query$) + Result = DatabaseUpdate(Database, Query$) + If Result = 0 + Print(DatabaseError()) + EndIf + ProcedureReturn Result +EndProcedure +openconsole() +DatabaseFile$ = GetCurrentDirectory()+"/rosettadb.sdb" +If CreateFile(0, DatabaseFile$) + CloseFile(0) + If OpenDatabase(0, DatabaseFile$, "", "") + CheckDatabaseUpdate(0,"CREATE TABLE address ( addrID INTEGER PRIMARY KEY AUTOINCREMENT, addrStreet TEXT Not NULL, addrCity TEXT Not NULL, addrState TEXT Not NULL, addrZIP TEXT Not NULL)") + CloseDatabase(0) + Else + print("Can't open database !") + EndIf +Else + print("Can't create the database file !") +EndIf +closeconsole() diff --git a/Task/Table-creation-Postal-addresses/Python/table-creation-postal-addresses.py b/Task/Table-creation-Postal-addresses/Python/table-creation-postal-addresses.py new file mode 100644 index 0000000000..f83fd88883 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Python/table-creation-postal-addresses.py @@ -0,0 +1,11 @@ +>>> import sqlite3 +>>> conn = sqlite3.connect(':memory:') +>>> conn.execute('''CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL + )''') + +>>> 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 new file mode 100644 index 0000000000..b51922fb90 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses.rexx @@ -0,0 +1,84 @@ +/*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/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-1.rb b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-1.rb new file mode 100644 index 0000000000..3f8aceaa58 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-1.rb @@ -0,0 +1,10 @@ +require 'pstore' +require 'set' + +Address = Struct.new :id, :street, :city, :state, :zip + +db = PStore.new("addresses.pstore") +db.transaction do + db[:next] ||= 0 # Next available Address#id + db[:ids] ||= Set[] # Set of all ids in db +end diff --git a/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-2.rb b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-2.rb new file mode 100644 index 0000000000..e1357e2f4e --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-2.rb @@ -0,0 +1,7 @@ +db.transaction do + id = (db[:next] += 1) + db[id] = Address.new(id, + "1600 Pennsylvania Avenue NW", + "Washington", "DC", 20500) + db[:ids].add id +end diff --git a/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-3.rb b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-3.rb new file mode 100644 index 0000000000..469cd1ea50 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Ruby/table-creation-postal-addresses-3.rb @@ -0,0 +1,12 @@ +require 'sqlite3' + +db = SQLite3::Database.new(':memory:') +db.execute(" + CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL + ) +") diff --git a/Task/Table-creation-Postal-addresses/Run-BASIC/table-creation-postal-addresses.run b/Task/Table-creation-Postal-addresses/Run-BASIC/table-creation-postal-addresses.run new file mode 100644 index 0000000000..3e310eedef --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Run-BASIC/table-creation-postal-addresses.run @@ -0,0 +1,10 @@ +sqliteconnect #mem, ":memory:" ' make handle #mem +mem$ = " +CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL +)" +#mem execute(mem$) diff --git a/Task/Table-creation-Postal-addresses/SAS/table-creation-postal-addresses.sas b/Task/Table-creation-Postal-addresses/SAS/table-creation-postal-addresses.sas new file mode 100644 index 0000000000..013e6affb6 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/SAS/table-creation-postal-addresses.sas @@ -0,0 +1,4 @@ +DATA address; + LENGTH addrID 8. street 50$ city 25$ state 2$ zip 20$; + STOP; +RUN; diff --git a/Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.ss b/Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.ss new file mode 100644 index 0000000000..683c09c6b9 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.ss @@ -0,0 +1,16 @@ +(use sql-de-lite) + +(define *db* (open-database "addresses")) + +(exec ; create and run the SQL statement + (sql *db* + "CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL + )" +)) + +(close-database *db*) ; finally, close database diff --git a/Task/Table-creation-Postal-addresses/Tcl/table-creation-postal-addresses.tcl b/Task/Table-creation-Postal-addresses/Tcl/table-creation-postal-addresses.tcl new file mode 100644 index 0000000000..01f6af4208 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Tcl/table-creation-postal-addresses.tcl @@ -0,0 +1,12 @@ +package require sqlite3 + +sqlite3 db address.db +db eval { + CREATE TABLE address ( + addrID INTEGER PRIMARY KEY AUTOINCREMENT, + addrStreet TEXT NOT NULL, + addrCity TEXT NOT NULL, + addrState TEXT NOT NULL, + addrZIP TEXT NOT NULL + ) +} diff --git a/Task/Table-creation-Postal-addresses/Transact-SQL/table-creation-postal-addresses.sql b/Task/Table-creation-Postal-addresses/Transact-SQL/table-creation-postal-addresses.sql new file mode 100644 index 0000000000..80ef1ec9f8 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Transact-SQL/table-creation-postal-addresses.sql @@ -0,0 +1,8 @@ +CREATE TABLE #Address ( + addrID int NOT NULL Identity(1,1) PRIMARY KEY, + addrStreet varchar(50) NOT NULL , + addrCity varchar(25) NOT NULL , + addrState char(2) NOT NULL , + addrZIP char(10) NOT NULL +) +drop table #Address diff --git a/Task/Take-notes-on-the-command-line/0DESCRIPTION b/Task/Take-notes-on-the-command-line/0DESCRIPTION new file mode 100644 index 0000000000..35a4e6f7ad --- /dev/null +++ b/Task/Take-notes-on-the-command-line/0DESCRIPTION @@ -0,0 +1 @@ +{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]][[Category:Programming environment operations]]Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created. diff --git a/Task/Take-notes-on-the-command-line/1META.yaml b/Task/Take-notes-on-the-command-line/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/Take-notes-on-the-command-line/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/Take-notes-on-the-command-line/Ada/take-notes-on-the-command-line.ada b/Task/Take-notes-on-the-command-line/Ada/take-notes-on-the-command-line.ada new file mode 100644 index 0000000000..14c9cf1fdb --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Ada/take-notes-on-the-command-line.ada @@ -0,0 +1,51 @@ +with Ada.Calendar.Formatting; +with Ada.Characters.Latin_1; +with Ada.Command_Line; +with Ada.IO_Exceptions; +with Ada.Text_IO; +procedure Notes is + Notes_Filename : constant String := "notes.txt"; + Notes_File : Ada.Text_IO.File_Type; + Argument_Count : Natural := Ada.Command_Line.Argument_Count; +begin + if Argument_Count = 0 then + begin + Ada.Text_IO.Open + (File => Notes_File, + Mode => Ada.Text_IO.In_File, + Name => Notes_Filename); + while not Ada.Text_IO.End_Of_File (File => Notes_File) loop + Ada.Text_IO.Put_Line (Ada.Text_IO.Get_Line (File => Notes_File)); + end loop; + exception + when Ada.IO_Exceptions.Name_Error => + null; + end; + else + begin + Ada.Text_IO.Open + (File => Notes_File, + Mode => Ada.Text_IO.Append_File, + Name => Notes_Filename); + exception + when Ada.IO_Exceptions.Name_Error => + Ada.Text_IO.Create (File => Notes_File, Name => Notes_Filename); + end; + Ada.Text_IO.Put_Line + (File => Notes_File, + Item => Ada.Calendar.Formatting.Image (Date => Ada.Calendar.Clock)); + Ada.Text_IO.Put (File => Notes_File, Item => Ada.Characters.Latin_1.HT); + for I in 1 .. Argument_Count loop + Ada.Text_IO.Put + (File => Notes_File, + Item => Ada.Command_Line.Argument (I)); + if I /= Argument_Count then + Ada.Text_IO.Put (File => Notes_File, Item => ' '); + end if; + end loop; + Ada.Text_IO.Flush (File => Notes_File); + end if; + if Ada.Text_IO.Is_Open (File => Notes_File) then + Ada.Text_IO.Close (File => Notes_File); + end if; +end Notes; diff --git a/Task/Take-notes-on-the-command-line/AutoHotkey/take-notes-on-the-command-line.ahk b/Task/Take-notes-on-the-command-line/AutoHotkey/take-notes-on-the-command-line.ahk new file mode 100644 index 0000000000..9cce59eebf --- /dev/null +++ b/Task/Take-notes-on-the-command-line/AutoHotkey/take-notes-on-the-command-line.ahk @@ -0,0 +1,23 @@ +Notes := "Notes.txt" + +If 0 = 0 ; no arguments +{ + If FileExist(Notes) { + FileRead, Content, %Notes% + MsgBox, %Content% + } Else + MsgBox, %Notes% does not exist + Goto, EOF +} + +; date and time, colon, newline (CRLF), tab +Date := A_DD "/" A_MM "/" A_YYYY +Time := A_Hour ":" A_Min ":" A_Sec "." A_MSec +FileAppend, %Date% %Time%:`r`n%A_Tab%, %Notes% + +; command line parameters, trailing newline (CRLF) +Loop, %0% + FileAppend, % %A_Index% " ", %Notes% +FileAppend, `r`n, %Notes% + +EOF: diff --git a/Task/Take-notes-on-the-command-line/BASIC/take-notes-on-the-command-line.basic b/Task/Take-notes-on-the-command-line/BASIC/take-notes-on-the-command-line.basic new file mode 100644 index 0000000000..b4dab5315c --- /dev/null +++ b/Task/Take-notes-on-the-command-line/BASIC/take-notes-on-the-command-line.basic @@ -0,0 +1,16 @@ +IF LEN(COMMAND$) THEN + OPEN "notes.txt" FOR APPEND AS 1 + PRINT #1, DATE$, TIME$ + PRINT #1, CHR$(9); COMMAND$ + CLOSE +ELSE + d$ = DIR$("notes.txt") + IF LEN(d$) THEN + OPEN d$ FOR INPUT AS 1 + WHILE NOT EOF(1) + LINE INPUT #1, i$ + PRINT i$ + WEND + CLOSE + END IF +END IF diff --git a/Task/Take-notes-on-the-command-line/BBC-BASIC/take-notes-on-the-command-line.bbc b/Task/Take-notes-on-the-command-line/BBC-BASIC/take-notes-on-the-command-line.bbc new file mode 100644 index 0000000000..6765358d91 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/BBC-BASIC/take-notes-on-the-command-line.bbc @@ -0,0 +1,29 @@ + REM!Exefile C:\NOTES.EXE, encrypt, console + REM!Embed + LF = 10 + + SYS "GetStdHandle", -10 TO @hfile%(1) + SYS "GetStdHandle", -11 TO @hfile%(2) + SYS "SetConsoleMode", @hfile%(1), 0 + *INPUT 13 + *OUTPUT 14 + ON ERROR PRINT REPORT$ : QUIT ERR + + notes% = OPENUP(@dir$ + "NOTES.TXT") + IF notes% = 0 notes% = OPENOUT(@dir$ + "NOTES.TXT") + IF notes% = 0 PRINT "Cannot open or create NOTES.TXT" : QUIT 1 + + IF @cmd$ = "" THEN + WHILE NOT EOF#notes% + INPUT #notes%, text$ + IF ASC(text$) = LF text$ = MID$(text$,2) + PRINT text$ + ENDWHILE + ELSE + PTR#notes% = EXT#notes% + PRINT #notes%,TIME$ : BPUT#notes%,LF + PRINT #notes%,CHR$(9) + @cmd$ : BPUT#notes%,LF + ENDIF + + CLOSE #notes% + QUIT diff --git a/Task/Take-notes-on-the-command-line/Batch-File/take-notes-on-the-command-line.bat b/Task/Take-notes-on-the-command-line/Batch-File/take-notes-on-the-command-line.bat new file mode 100644 index 0000000000..60927c1db9 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Batch-File/take-notes-on-the-command-line.bat @@ -0,0 +1,7 @@ +@echo off +if %1@==@ ( + if exist notes.txt more notes.txt + goto :eof +) +echo %date% %time%:>>notes.txt +echo %*>>notes.txt diff --git a/Task/Take-notes-on-the-command-line/C++/take-notes-on-the-command-line.cpp b/Task/Take-notes-on-the-command-line/C++/take-notes-on-the-command-line.cpp new file mode 100644 index 0000000000..cf2b207741 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/C++/take-notes-on-the-command-line.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +#define note_file "NOTES.TXT" + +int main(int argc, char **argv) +{ + if(argc>1) + { + ofstream Notes(note_file, ios::app); + time_t timer = time(NULL); + if(Notes.is_open()) + { + Notes << asctime(localtime(&timer)) << '\t'; + for(int i=1;i +#include + +#define note_file "NOTES.TXT" + +int main(int argc, char**argv) +{ + FILE *note = 0; + time_t tm; + int i; + char *p; + + if (argc < 2) { + if ((note = fopen(note_file, "r"))) + while ((i = fgetc(note)) != EOF) + putchar(i); + + } else if ((note = fopen(note_file, "a"))) + tm = time(0); + p = ctime(&tm); + + /* skip the newline */ + while (*p) fputc(*p != '\n'?*p:'\t', note), p++; + + for (i = 1; i < argc; i++) + fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n'); + } + + if (note) fclose(note); + return 0; +} diff --git a/Task/Take-notes-on-the-command-line/Clojure/take-notes-on-the-command-line.clj b/Task/Take-notes-on-the-command-line/Clojure/take-notes-on-the-command-line.clj new file mode 100644 index 0000000000..9347627aeb --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Clojure/take-notes-on-the-command-line.clj @@ -0,0 +1,13 @@ +(ns rosettacode.notes + (:use [clojure.string :only [join]])) + +(defn notes [notes] + (if (seq notes) + (spit + "NOTES.txt" + (str (java.util.Date.) "\n" "\t" + (join " " notes) "\n") + :append true) + (println (slurp "NOTES.txt")))) + +(notes *command-line-args*) diff --git a/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d b/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d new file mode 100644 index 0000000000..496fd13b27 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/D/take-notes-on-the-command-line.d @@ -0,0 +1,14 @@ +import std.stdio, std.file, std.string, std.datetime; + +void main(string[] args) { + immutable filename = "NOTES.TXT"; + + if (args.length == 1) { + if (exists(filename) && isFile(filename)) + writefln("%-(%s\n%)", filename.File.byLine); + } else { + auto f = File(filename, "a+"); + f.writefln("%s", cast(DateTime)Clock.currTime); + f.writefln("\t%s", args[1 .. $].join(" ")); + } +} diff --git a/Task/Take-notes-on-the-command-line/E/take-notes-on-the-command-line.e b/Task/Take-notes-on-the-command-line/E/take-notes-on-the-command-line.e new file mode 100644 index 0000000000..3b556d1d30 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/E/take-notes-on-the-command-line.e @@ -0,0 +1,17 @@ +#!/usr/bin/env rune + +def f := +def date := makeCommand("date") + +switch (interp.getArgs()) { + match [] { + if (f.exists()) { + for line in f { print(line) } + } + } + match noteArgs { + def w := f.textWriter(true) + w.print(date()[0], "\t", " ".rjoin(noteArgs), "\n") + w.close() + } +} diff --git a/Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.euphoria b/Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.euphoria new file mode 100644 index 0000000000..08d01131f1 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.euphoria @@ -0,0 +1,32 @@ +constant cmd = command_line() +constant filename = "notes.txt" +integer fn +object line +sequence date_time + +if length(cmd) < 3 then + fn = open(filename,"r") + if fn != -1 then + while 1 do + line = gets(fn) + if atom(line) then + exit + end if + puts(1,line) + end while + close(fn) + end if +else + fn = open(filename,"a") -- if such file doesn't exist it will be created + date_time = date() + date_time = date_time[1..6] + date_time[1] += 1900 + printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date_time) + line = "\t" + for n = 3 to length(cmd) do + line &= cmd[n] & ' ' + end for + line[$] = '\n' + puts(fn,line) + close(fn) +end if diff --git a/Task/Take-notes-on-the-command-line/Factor/take-notes-on-the-command-line.factor b/Task/Take-notes-on-the-command-line/Factor/take-notes-on-the-command-line.factor new file mode 100644 index 0000000000..232c669188 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Factor/take-notes-on-the-command-line.factor @@ -0,0 +1,13 @@ +#! /usr/bin/env factor +USING: kernel calendar calendar.format io io.encodings.utf8 io.files +sequences command-line namespaces ; + +command-line get [ + "notes.txt" utf8 file-contents print +] [ + " " join "\t" prepend + "notes.txt" utf8 [ + now timestamp>ymdhms print + print flush + ] with-file-appender +] if-empty diff --git a/Task/Take-notes-on-the-command-line/Fantom/take-notes-on-the-command-line.fantom b/Task/Take-notes-on-the-command-line/Fantom/take-notes-on-the-command-line.fantom new file mode 100644 index 0000000000..905d10120c --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Fantom/take-notes-on-the-command-line.fantom @@ -0,0 +1,25 @@ +class Notes +{ + public static Void main (Str[] args) + { + notesFile := File(`notes.txt`) // the backticks make a URI + if (args.isEmpty) + { + if (notesFile.exists) + { + notesFile.eachLine |line| { echo (line) } + } + } + else + { + // notice the following uses a block so the 'printLine/close' + // operations are all applied to the same output stream for notesFile + notesFile.out(true) // 'true' to append to file + { + printLine ( DateTime.now.toLocale("DD-MM-YY hh:mm:ss").toStr ) + printLine ( "\t" + args.join(" ") ) + close + } + } + } +} diff --git a/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-1.fth b/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-1.fth new file mode 100644 index 0000000000..09419a122c --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-1.fth @@ -0,0 +1,44 @@ +vocabulary note-words +get-current also note-words definitions + +\ -- notes.txt +variable file +: open s" notes.txt" r/w open-file if + s" notes.txt" r/w create-file throw then file ! ; +: appending file @ file-size throw file @ reposition-file throw ; +: write file @ write-file throw ; +: close file @ close-file throw ; + +\ -- SwiftForth console workaround +9 constant TAB +: type ( c-addr u -- ) + bounds ?do + i c@ dup TAB = if drop 8 spaces else emit then + loop ; + +\ -- dump notes.txt +create buf 4096 allot +: dump ( -- ) + cr begin buf 4096 file @ read-file throw dup while + buf swap type + repeat drop ; + +\ -- time and date +: time @time (time) ; +: date @date (date) ; + +\ -- add note +: cr s\" \n" write ; +: tab s\" \t" write ; +: space s" " write ; +: add-note ( c-addr u -- ) appending + date write space time write cr + tab ( note ) write cr ; + +set-current + +\ -- note +: note ( "note" -- ) + open 0 parse dup if add-note + else 2drop dump then close ; +previous diff --git a/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-2.fth b/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-2.fth new file mode 100644 index 0000000000..d4c63d5228 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Forth/take-notes-on-the-command-line-2.fth @@ -0,0 +1,29 @@ +\ -- notes.txt +include lib/argopen.4th +include lib/ansfacil.4th + +\ -- dump notes.txt +4096 buffer: buf +: dump ( -- ) + input 1 arg-open + begin buf dup 4096 accept dup while type repeat + drop drop close ; + +\ -- time and date +: :00 <# # # [char] : hold #> type ; +: -00 <# # # [char] - hold #> type ; +: .time 0 .r :00 :00 ; +: .date 0 .r -00 -00 ; + +\ -- add note +: add-note ( c-addr u -- ) + output append [+] 1 arg-open -rot + time&date .date space .time cr + 9 emit type cr close ; + +\ -- note +: note ( "note" -- ) + argn 2 < abort" Usage: notes filename" + refill drop 0 parse dup if add-note else 2drop dump then ; + +note diff --git a/Task/Take-notes-on-the-command-line/Go/take-notes-on-the-command-line.go b/Task/Take-notes-on-the-command-line/Go/take-notes-on-the-command-line.go new file mode 100644 index 0000000000..ad58d8e01a --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Go/take-notes-on-the-command-line.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + "io" + "os" + "strings" + "time" +) + +const fn = "NOTES.TXT" + +func main() { + if len(os.Args) == 1 { + f, err := os.Open(fn) + if err != nil { + // don't report "file does not exist" as an error, but + // if it seems to be there but just can't be opened for + // some reason, print original error from open attempt. + if _, statErr := os.Stat(fn); statErr == nil { + fmt.Println(err) + } + return + } + if _, err = io.Copy(os.Stdout, f); err != nil { + fmt.Println(err) + } + if cErr := f.Close(); err == nil && cErr != nil { + fmt.Println(err) + } + return + } + f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) + if err != nil { + fmt.Println(err) + return + } + _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), + "\n\t", strings.Join(os.Args[1:], " "), "\n") + if err != nil { + fmt.Println(err) + } + if cErr := f.Close(); err == nil && cErr != nil { + fmt.Println(cErr) + } +} diff --git a/Task/Take-notes-on-the-command-line/Haskell/take-notes-on-the-command-line.hs b/Task/Take-notes-on-the-command-line/Haskell/take-notes-on-the-command-line.hs new file mode 100644 index 0000000000..ba0b769f88 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Haskell/take-notes-on-the-command-line.hs @@ -0,0 +1,12 @@ +import System.Environment (getArgs) +import System.Time (getClockTime) + +main :: IO () +main = do + args <- getArgs + if null args + then catch (readFile "notes.txt" >>= putStr) + (\_ -> return ()) + else + do ct <- getClockTime + appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n" diff --git a/Task/Take-notes-on-the-command-line/HicEst/take-notes-on-the-command-line.hicest b/Task/Take-notes-on-the-command-line/HicEst/take-notes-on-the-command-line.hicest new file mode 100644 index 0000000000..b17e7cac51 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/HicEst/take-notes-on-the-command-line.hicest @@ -0,0 +1,20 @@ +SYSTEM(RUN) ! start this script in RUN-mode + +CHARACTER notes="Notes.txt", txt*1000 + +! Remove file name from the global variable $CMD_LINE: +EDIT(Text=$CMD_LINE, Mark1, Right=".hic ", Right=4, Mark2, Delete) + +IF($CMD_LINE == ' ') THEN + READ(FIle=notes, LENgth=Lnotes) + IF( Lnotes ) THEN + WINDOW(WINdowhandle=hdl, TItle=notes) + WRITE(Messagebox="?Y") "Finished ?" + ENDIF +ELSE + WRITE(Text=txt, Format="UWWW CCYY-MM-DD HH:mm:SS, A") 0, $CRLF//$TAB//TRIM($CMD_LINE)//$CRLF + OPEN(FIle=notes, APPend) + WRITE(FIle=notes, CLoSe=1) txt +ENDIF + +ALARM(999) ! quit HicEst immediately diff --git a/Task/Take-notes-on-the-command-line/Icon/take-notes-on-the-command-line.icon b/Task/Take-notes-on-the-command-line/Icon/take-notes-on-the-command-line.icon new file mode 100644 index 0000000000..26d536e9c4 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Icon/take-notes-on-the-command-line.icon @@ -0,0 +1,20 @@ +procedure write_out_notes (filename) + file := open (filename, "rt") | stop ("no notes file yet") + every write (!file) +end + +procedure add_to_notes (filename, strs) + file := open (filename, "at") | # append to file if it exists + open (filename, "cat") | # create the file if not there + stop ("unable to open " || filename) + writes (file, ctime(&now) || "\n\t") + every writes (file, !strs || " ") + write (file, "") +end + +procedure main (args) + notes_file := "notes.txt" + if *args = 0 + then write_out_notes (notes_file) + else add_to_notes (notes_file, args) +end diff --git a/Task/Take-notes-on-the-command-line/J/take-notes-on-the-command-line.j b/Task/Take-notes-on-the-command-line/J/take-notes-on-the-command-line.j new file mode 100644 index 0000000000..4f00220034 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/J/take-notes-on-the-command-line.j @@ -0,0 +1,13 @@ +require 'files strings' + +notes=: monad define + if. #y do. + now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY' + 'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y + elseif. -. _1 -: txt=. fread 'notes.txt' do. + smoutput txt + end. +) + +notes 2}.ARGV +exit 0 diff --git a/Task/Take-notes-on-the-command-line/Java/take-notes-on-the-command-line.java b/Task/Take-notes-on-the-command-line/Java/take-notes-on-the-command-line.java new file mode 100644 index 0000000000..b7a4cff212 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Java/take-notes-on-the-command-line.java @@ -0,0 +1,21 @@ +import java.io.*; +import java.nio.channels.*; +import java.util.Date; + +public class TakeNotes { + public static void main(String[] args) throws IOException { + if (args.length > 0) { + PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true)); + ps.println(new Date()); + ps.print("\t" + args[0]); + for (int i = 1; i < args.length; i++) + ps.print(" " + args[i]); + ps.println(); + ps.close(); + } else { + FileChannel fc = new FileInputStream("notes.txt").getChannel(); + fc.transferTo(0, fc.size(), Channels.newChannel(System.out)); + fc.close(); + } + } +} diff --git a/Task/Take-notes-on-the-command-line/JavaScript/take-notes-on-the-command-line.js b/Task/Take-notes-on-the-command-line/JavaScript/take-notes-on-the-command-line.js new file mode 100644 index 0000000000..afc2fa97c6 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/JavaScript/take-notes-on-the-command-line.js @@ -0,0 +1,26 @@ +var notes = 'NOTES.TXT'; + +var args = WScript.Arguments; +var fso = new ActiveXObject("Scripting.FileSystemObject"); +var ForReading = 1, ForWriting = 2, ForAppending = 8; + +if (args.length == 0) { + if (fso.FileExists(notes)) { + var f = fso.OpenTextFile(notes, ForReading); + WScript.Echo(f.ReadAll()); + f.Close(); + } +} +else { + var f = fso.OpenTextFile(notes, ForAppending, true); + var d = new Date(); + f.WriteLine(d.toLocaleString()); + f.Write("\t"); + // note that WScript.Arguments is not an array, it is a "collection" + // it does not have a join() method. + for (var i = 0; i < args.length; i++) { + f.Write(args(i) + " "); + } + f.WriteLine(); + f.Close(); +} diff --git a/Task/Take-notes-on-the-command-line/Lua/take-notes-on-the-command-line.lua b/Task/Take-notes-on-the-command-line/Lua/take-notes-on-the-command-line.lua new file mode 100644 index 0000000000..896268bce7 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Lua/take-notes-on-the-command-line.lua @@ -0,0 +1,21 @@ +filename = "NOTES.TXT" + +if #arg == 0 then + fp = io.open( filename, "r" ) + if fp ~= nil then + print( fp:read( "*all*" ) ) + fp:close() + end +else + fp = io.open( filename, "a+" ) + + fp:write( os.date( "%x %X\n" ) ) + + fp:write( "\t" ) + for i = 1, #arg do + fp:write( arg[i], " " ) + end + fp:write( "\n" ) + + fp:close() +end diff --git a/Task/Take-notes-on-the-command-line/MATLAB/take-notes-on-the-command-line.m b/Task/Take-notes-on-the-command-line/MATLAB/take-notes-on-the-command-line.m new file mode 100644 index 0000000000..c181a355d2 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/MATLAB/take-notes-on-the-command-line.m @@ -0,0 +1,26 @@ + function notes(varargin) + % NOTES can be used for taking notes + % usage: + % notes displays the content of the file NOTES.TXT + % notes arg1 arg2 ... + % add the current date, time and arg# to NOTES.TXT + % + + filename = 'NOTES.TXT'; + if nargin==0 + fid = fopen(filename,'rt'); + if fid<0, return; end; + while ~feof(fid) + fprintf('%s\n',fgetl(fid)); + end; + fclose(fid); + else + fid = fopen(filename,'a+'); + if fid<0, error('cannot open %s\n',filename); end; + fprintf(fid, '%s\n\t%s', datestr(now),varargin{1}); + for k=2:length(varargin) + fprintf(fid, ', %s', varargin{k}); + end; + fprintf(fid,'\n'); + fclose(fid); + end; diff --git a/Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ocaml b/Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ocaml new file mode 100644 index 0000000000..87bd720291 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ocaml @@ -0,0 +1,31 @@ +#! /usr/bin/env ocaml +#load "unix.cma" + +let notes_file = "notes.txt" + +let take_notes() = + let gmt = Unix.gmtime (Unix.time()) in + let date = + Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d" + (1900 + gmt.Unix.tm_year) (1 + gmt.Unix.tm_mon) gmt.Unix.tm_mday + gmt.Unix.tm_hour gmt.Unix.tm_min gmt.Unix.tm_sec + in + let oc = open_out_gen [Open_append; Open_creat; Open_text] 0o644 notes_file in + output_string oc (date ^ "\t"); + output_string oc (String.concat " " (List.tl(Array.to_list Sys.argv))); + output_string oc "\n"; +;; + +let dump_notes() = + if not(Sys.file_exists notes_file) + then (prerr_endline "no local notes found"; exit 1); + let ic = open_in notes_file in + try while true do + print_endline (input_line ic) + done with End_of_file -> + close_in ic + +let () = + if Array.length Sys.argv = 1 + then dump_notes() + else take_notes() diff --git a/Task/Take-notes-on-the-command-line/Oz/take-notes-on-the-command-line.oz b/Task/Take-notes-on-the-command-line/Oz/take-notes-on-the-command-line.oz new file mode 100644 index 0000000000..48ea9f05e6 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Oz/take-notes-on-the-command-line.oz @@ -0,0 +1,34 @@ +functor +import + Application + Open + OS + System +define + fun {TimeStamp} + N = {OS.localTime} + in + (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec + end + + fun {Join X|Xr Sep} + {FoldL Xr fun {$ Z X} Z#Sep#X end X} + end + + case {Application.getArgs plain} + of nil then + try + F = {New Open.file init(name:"notes.txt")} + in + {System.printInfo {F read(list:$ size:all)}} + {F close} + catch _ then skip end + [] Args then + F = {New Open.file init(name:"notes.txt" flags:[write text create append])} + in + {F write(vs:{TimeStamp}#"\n")} + {F write(vs:"\t"#{Join Args " "}#"\n")} + {F close} + end + {Application.exit 0} +end diff --git a/Task/Take-notes-on-the-command-line/PHP/take-notes-on-the-command-line.php b/Task/Take-notes-on-the-command-line/PHP/take-notes-on-the-command-line.php new file mode 100644 index 0000000000..dc48c6c908 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/PHP/take-notes-on-the-command-line.php @@ -0,0 +1,10 @@ +#!/usr/bin/php + 1) + file_put_contents( + 'notes.txt', + date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", + FILE_APPEND + ); +else + @readfile('notes.txt'); diff --git a/Task/Take-notes-on-the-command-line/Perl-6/take-notes-on-the-command-line.pl6 b/Task/Take-notes-on-the-command-line/Perl-6/take-notes-on-the-command-line.pl6 new file mode 100644 index 0000000000..4e494dd6b7 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Perl-6/take-notes-on-the-command-line.pl6 @@ -0,0 +1,11 @@ +my $file = 'notes.txt'; + +multi MAIN() { + print slurp($file); +} + +multi MAIN(*@note) { + my $fh = open($file, :a); + $fh.say: DateTime.now, "\n\t", @note; + $fh.close; +} diff --git a/Task/Take-notes-on-the-command-line/Perl/take-notes-on-the-command-line.pl b/Task/Take-notes-on-the-command-line/Perl/take-notes-on-the-command-line.pl new file mode 100644 index 0000000000..770c2b1f0d --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Perl/take-notes-on-the-command-line.pl @@ -0,0 +1,9 @@ +my $file = 'notes.txt'; +if ( @ARGV ) { + open NOTES, '>>', $file or die "Can't append to file $file: $!"; + print NOTES scalar localtime, "\n\t@ARGV\n"; +} else { + open NOTES, '<', $file or die "Can't read file $file: $!"; + print ; +} +close NOTES; diff --git a/Task/Take-notes-on-the-command-line/PicoLisp/take-notes-on-the-command-line.l b/Task/Take-notes-on-the-command-line/PicoLisp/take-notes-on-the-command-line.l new file mode 100644 index 0000000000..bf83e995d2 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/PicoLisp/take-notes-on-the-command-line.l @@ -0,0 +1,7 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(load "@lib/misc.l") +(if (argv) + (out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @))) + (and (info "notes.txt") (in "notes.txt" (echo))) ) +(bye) diff --git a/Task/Take-notes-on-the-command-line/PowerShell/take-notes-on-the-command-line.psh b/Task/Take-notes-on-the-command-line/PowerShell/take-notes-on-the-command-line.psh new file mode 100644 index 0000000000..92d15f10a1 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/PowerShell/take-notes-on-the-command-line.psh @@ -0,0 +1,9 @@ +$notes = "notes.txt" +if (($args).length -eq 0) { + if(Test-Path $notes) { + Get-Content $notes + } +} else { + Get-Date | Add-Content $notes + "`t" + $args -join " " | Add-Content $notes +} diff --git a/Task/Take-notes-on-the-command-line/PureBasic/take-notes-on-the-command-line.purebasic b/Task/Take-notes-on-the-command-line/PureBasic/take-notes-on-the-command-line.purebasic new file mode 100644 index 0000000000..d96de2f719 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/PureBasic/take-notes-on-the-command-line.purebasic @@ -0,0 +1,24 @@ +#FileName="notes.txt" +Define argc=CountProgramParameters() +If OpenConsole() + If argc=0 + If ReadFile(0,#FileName) + While Eof(0)=0 + PrintN(ReadString(0)) ; No new notes, so present the old + Wend + CloseFile(0) + EndIf + Else ; e.g. we have some arguments + Define d$=FormatDate("%yyyy-%mm-%dd %hh:%ii:%ss",date()) + If OpenFile(0,#FileName) + Define args$="" + While argc + args$+" "+ProgramParameter() ; Read all arguments + argc-1 + Wend + FileSeek(0,Lof(0)) ; Go to the end of this file + WriteStringN(0,d$+#CRLF$+#TAB$+args$) ; Append date & note + CloseFile(0) + EndIf + EndIf +EndIf diff --git a/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py b/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py new file mode 100644 index 0000000000..dd2b7a4516 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Python/take-notes-on-the-command-line.py @@ -0,0 +1,15 @@ +import sys, datetime, shutil + +#sys.argv[1:] = 'go for it'.split() +if len(sys.argv) == 1: + try: + f = open('notes.txt', 'r') + shutil.copyfileobj(f, sys.stdout) + f.close() + except IOError: + pass +else: + f = open('notes.txt', 'a') + f.write(datetime.datetime.now().isoformat() + '\n') + f.write("\t%s\n" % ' '.join(sys.argv[1:])) + f.close() diff --git a/Task/Take-notes-on-the-command-line/R/take-notes-on-the-command-line.r b/Task/Take-notes-on-the-command-line/R/take-notes-on-the-command-line.r new file mode 100644 index 0000000000..06dba716e3 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/R/take-notes-on-the-command-line.r @@ -0,0 +1,12 @@ +#!/usr/bin/env Rscript --default-packages=methods + +args <- commandArgs(trailingOnly=TRUE) + +if (length(args) == 0) { + conn <- file("notes.txt", 'r') + cat(readLines(conn), sep="\n") +} else { + conn <- file("notes.txt", 'a') + cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="") +} +close(conn) diff --git a/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol b/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol new file mode 100644 index 0000000000..c5c49111cc --- /dev/null +++ b/Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol @@ -0,0 +1,14 @@ +REBOL [ + Title: "Notes" + Author: oofoe + Date: 2010-10-04 + URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line +] + +notes: %notes.txt + +either any [none? args: system/script/args empty? args] [ + if exists? notes [print read notes] +] [ + write/binary/append notes rejoin [now lf tab args lf] +] diff --git a/Task/Take-notes-on-the-command-line/REXX/take-notes-on-the-command-line.rexx b/Task/Take-notes-on-the-command-line/REXX/take-notes-on-the-command-line.rexx new file mode 100644 index 0000000000..6410c9f087 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/REXX/take-notes-on-the-command-line.rexx @@ -0,0 +1,15 @@ +/*REXX program implements the "NOTES" command (append text to a file).*/ +timestamp=right(date(),11,0) time() date('W') /*create date/time stamp.*/ +nFID = 'NOTES.TXT' /*the fileID of the "notes" file.*/ + +if 'f0'x==0 then tab='05'x /*this is an EBCDIC system. */ + else tab='09'x /* " " " ASCII " */ + +if arg()==0 then do while lines(nFID) /*No args? Then show the file. */ + say linein(Nfid) /*show a line of file ──► screen.*/ + end /*while*/ + else do + call lineout nFID,timestamp /*append the timestamp. */ + call lineout nFID,tab||arg(1) /*append the "note" text*/ + end + /*stick a fork in it, we're done.*/ diff --git a/Task/Take-notes-on-the-command-line/Ruby/take-notes-on-the-command-line.rb b/Task/Take-notes-on-the-command-line/Ruby/take-notes-on-the-command-line.rb new file mode 100644 index 0000000000..a22f247a73 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Ruby/take-notes-on-the-command-line.rb @@ -0,0 +1,6 @@ +notes = 'NOTES.TXT' +if ARGV.empty? + File.copy_stream(notes, $stdout) rescue nil +else + File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]} +end diff --git a/Task/Take-notes-on-the-command-line/SNOBOL4/take-notes-on-the-command-line.sno b/Task/Take-notes-on-the-command-line/SNOBOL4/take-notes-on-the-command-line.sno new file mode 100644 index 0000000000..c45ba3eb9a --- /dev/null +++ b/Task/Take-notes-on-the-command-line/SNOBOL4/take-notes-on-the-command-line.sno @@ -0,0 +1,12 @@ +#! /usr/local/bin/snobol4 -b + a = 2 ;* skip '-b' parameter + notefile = "notes.txt" +while args = args host(2,a = a + 1) " " :s(while) + ident(args) :f(append) +noparms input(.notes,io_findunit(),,notefile) :s(display)f(end) +display output = notes :s(display) + endfile(notes) :(end) +append output(.notes,io_findunit(),"A",notefile) :f(end) + notes = date() + notes = char(9) args +end diff --git a/Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.ss b/Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.ss new file mode 100644 index 0000000000..afc24037b1 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.ss @@ -0,0 +1,20 @@ +#lang racket +(require racket/date) +(define *notes* "NOTES.TXT") + +(let ([a (vector->list (current-command-line-arguments))]) + (cond + [(empty? a) + (with-handlers ([exn:fail? void]) + (call-with-input-file *notes* + (lambda (fi) + (copy-port fi (current-output-port))))) + ] + [else + (call-with-output-file *notes* + (lambda (fo) + (let ([ln (apply string-append (add-between a " "))] + [dt (date->string (current-date))]) + (fprintf fo "~a~n\t~a~n" dt ln))) + #:mode 'text #:exists 'append) + ])) diff --git a/Task/Take-notes-on-the-command-line/Seed7/take-notes-on-the-command-line.seed7 b/Task/Take-notes-on-the-command-line/Seed7/take-notes-on-the-command-line.seed7 new file mode 100644 index 0000000000..9b9e333518 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Seed7/take-notes-on-the-command-line.seed7 @@ -0,0 +1,23 @@ +$ include "seed7_05.s7i"; +$ include "getf.s7i"; +$ include "time.s7i"; + +const string: noteFileName is "NOTES.TXT"; + +const proc: main is func + local + var file: note is STD_NULL; + begin + if length(argv(PROGRAM)) = 0 then + # write NOTES.TXT + write(getf(noteFileName)); + else + # Write date & time to NOTES.TXT, and then arguments + note := open(noteFileName, "a"); + if note <> STD_NULL then + writeln(note, truncToSecond(time(NOW))); + writeln(note, "\t" <& join(argv(PROGRAM), " ")); + close(note); + end if; + end if; + end func; diff --git a/Task/Take-notes-on-the-command-line/Tcl/take-notes-on-the-command-line.tcl b/Task/Take-notes-on-the-command-line/Tcl/take-notes-on-the-command-line.tcl new file mode 100644 index 0000000000..9525913036 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Tcl/take-notes-on-the-command-line.tcl @@ -0,0 +1,17 @@ +# Make it easier to change the name of the notes file +set notefile notes.txt + +if {$argc} { + # Write a message to the file + set msg [clock format [clock seconds]]\n\t[join $argv " "] + set f [open $notefile a] + puts $f $msg + close $f +} else { + # Print the contents of the file + catch { + set f [open $notefile] + fcopy $f stdout + close $f + } +} diff --git a/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh new file mode 100644 index 0000000000..0cfc9f4a0a --- /dev/null +++ b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh @@ -0,0 +1,8 @@ +# +NOTES=$HOME/notes.txt +if [[ $# -eq 0 ]] ; then + [[ -r $NOTES ]] && more $NOTES +else + date >> $NOTES + echo " $*" >> $NOTES +fi diff --git a/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-2.sh b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-2.sh new file mode 100644 index 0000000000..e75d28ed9b --- /dev/null +++ b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-2.sh @@ -0,0 +1 @@ +N=~/notes.txt;[[ $# -gt 0 ]] && { date ; echo " $*"; exit 0; } >> $N || [[ -r $N ]] && cat $N diff --git a/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-3.sh b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-3.sh new file mode 100644 index 0000000000..1b5afe72f9 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-3.sh @@ -0,0 +1,11 @@ +NOTES=$HOME/notes.txt +if test "x$*" = "x" +then + if test -r $NOTES + then + more $NOTES + fi +else + date >> $NOTES + echo " $*" >> $NOTES +fi diff --git a/Task/Take-notes-on-the-command-line/Visual-Basic-.NET/take-notes-on-the-command-line.visual b/Task/Take-notes-on-the-command-line/Visual-Basic-.NET/take-notes-on-the-command-line.visual new file mode 100644 index 0000000000..34d2835137 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Visual-Basic-.NET/take-notes-on-the-command-line.visual @@ -0,0 +1,19 @@ +Imports System.IO + +Module Notes + Function Main(ByVal cmdArgs() As String) As Integer + Try + If cmdArgs.Length = 0 Then + Using sr As New StreamReader("NOTES.TXT") + Console.WriteLine(sr.ReadToEnd) + End Using + Else + Using sw As New StreamWriter("NOTES.TXT", True) + sw.WriteLine(Date.Now.ToString()) + sw.WriteLine("{0}{1}", ControlChars.Tab, String.Join(" ", cmdArgs)) + End Using + End If + Catch + End Try + End Function +End Module diff --git a/Task/Temperature-conversion/0DESCRIPTION b/Task/Temperature-conversion/0DESCRIPTION new file mode 100644 index 0000000000..188566a99c --- /dev/null +++ b/Task/Temperature-conversion/0DESCRIPTION @@ -0,0 +1,24 @@ +There are quite a number of temperature scales. For this task we will concentrate on 4 of the perhaps best-known ones: [[wp:Kelvin|Kelvin]], [[wp:Degree Celsius|Celcius]], [[wp:Fahrenheit|Fahrenheit]] and [[wp:Degree Rankine|Rankine]]. + +The Celcius and Kelvin scales have the same magnitude, but different null points. + +:0 degrees Celcius corresponds to '''273.15''' kelvin. +:0 kelvin is absolute zero. + +The Fahrenheit and Rankine scales also have the same magnitude, but different null points. + +:0 degrees Fahrenheit corresponds to '''459.67''' degrees Rankine. +:0 degrees Rankine is absolute zero. + +The Celcius/Kelvin and Fahrenheit/Rankine scales have a ratio of '''5 : 9'''. + +Write code that accepts a value of kelvin, converts it to values on the three other scales and prints the result. For instance: +
+K  21.00
+
+C  -252.15
+
+F  -421.87
+
+R  37.80
+
diff --git a/Task/Temperature-conversion/AWK/temperature-conversion.awk b/Task/Temperature-conversion/AWK/temperature-conversion.awk new file mode 100644 index 0000000000..6a074f45eb --- /dev/null +++ b/Task/Temperature-conversion/AWK/temperature-conversion.awk @@ -0,0 +1,19 @@ +# syntax: AWK -f TEMPERATURE_CONVERSION.AWK +BEGIN { + while (1) { + printf("\nKelvin degrees? ") + getline K + if (K ~ /^$/) { + break + } + if (K < 0) { + print("K must be > 0") + continue + } + printf("K = %.2f\n",K) + printf("C = %.2f\n",K - 273.15) + printf("F = %.2f\n",K * 1.8 - 459.67) + printf("R = %.2f\n",K * 1.8) + } + exit(0) +} diff --git a/Task/Temperature-conversion/BASIC/temperature-conversion.basic b/Task/Temperature-conversion/BASIC/temperature-conversion.basic new file mode 100644 index 0000000000..b3f0ae68bd --- /dev/null +++ b/Task/Temperature-conversion/BASIC/temperature-conversion.basic @@ -0,0 +1,11 @@ +10 REM TRANSLATION OF AWK VERSION +20 INPUT "KELVIN DEGREES",K +30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM +40 LET C = K - 273.15 +50 LET F = K * 1.8 - 459.67 +60 LET R = K * 1.8 +70 PRINT K; " KELVIN IS EQUIVALENT TO" +80 PRINT C; " DEGREES CELCIUS" +90 PRINT F; " DEGREES FAHRENHEIT" +100 PRINT R; " DEGREES RANKINE" +110 GOTO 20 diff --git a/Task/Temperature-conversion/C/temperature-conversion.c b/Task/Temperature-conversion/C/temperature-conversion.c new file mode 100644 index 0000000000..c8d06cf00e --- /dev/null +++ b/Task/Temperature-conversion/C/temperature-conversion.c @@ -0,0 +1,29 @@ +#include +#include + +double kelvinToCelsius(double k){ + return k - 273.15; +} + +double kelvinToFahrenheit(double k){ + return k * 1.8 - 459.67; +} + +double kelvinToRankine(double k){ + return k * 1.8; +} +void convertKelvin(double kelvin) { + printf("K %.2f\n", kelvin); + printf("C %.2f\n", kelvinToCelsius(kelvin)); + printf("F %.2f\n", kelvinToFahrenheit(kelvin)); + printf("R %.2f", kelvinToRankine(kelvin)); +} + +int main(int argc, const char * argv[]) +{ + if (argc > 1) { + double kelvin = atof(argv[1]); + convertKelvin(kelvin); + } + return 0; +} diff --git a/Task/Temperature-conversion/D/temperature-conversion.d b/Task/Temperature-conversion/D/temperature-conversion.d new file mode 100644 index 0000000000..03ec547a8e --- /dev/null +++ b/Task/Temperature-conversion/D/temperature-conversion.d @@ -0,0 +1,33 @@ +double kelvinToCelsius(in double k) pure nothrow @safe { + return k - 273.15; +} + +double kelvinToFahrenheit(in double k) pure nothrow @safe { + return k * 1.8 - 459.67; +} + +double kelvinToRankine(in double k) pure nothrow @safe { + return k * 1.8; +} + +unittest { + import std.math: approxEqual; + assert(approxEqual(kelvinToCelsius(21.0), -252.15)); + assert(approxEqual(kelvinToFahrenheit(21.0), -421.87)); + assert(approxEqual(kelvinToRankine(21.0), 37.8)); +} + +void main(string[] args) { + import std.stdio, std.conv, std.string; + + if (args.length == 2 && isNumeric(args[1])) { + immutable kelvin = to!double(args[1]); + if (kelvin >= 0) { + writefln("K %2.2f", kelvin); + writefln("C %2.2f", kelvinToCelsius(kelvin)); + writefln("F %2.2f", kelvinToFahrenheit(kelvin)); + writefln("R %2.2f", kelvinToRankine(kelvin)); + } else + writefln("%2.2f K is below absolute zero", kelvin); + } +} diff --git a/Task/Temperature-conversion/J/temperature-conversion-1.j b/Task/Temperature-conversion/J/temperature-conversion-1.j new file mode 100644 index 0000000000..3c8a1d45cc --- /dev/null +++ b/Task/Temperature-conversion/J/temperature-conversion-1.j @@ -0,0 +1,11 @@ + NB. Temp conversions are all linear polynomials + K2K =: 0 1 NB. K = (1 *k) + 0 + K2C =: _273 1 NB. C = (1 *k) - 273 + K2F =: _459.67 1.8 NB. F = (1.8*k) - 459.67 + K2R =: 0 1.8 NB. R = (1.8*k) + 0 + + NB. Do all conversions at once (eval + NB. polynomials in parallel). This is the + NB. numeric matrix J programs would manipulate + NB. directly. + k2KCFR =: (K2K , K2C , K2F ,: K2R) p./ ] diff --git a/Task/Temperature-conversion/J/temperature-conversion-2.j b/Task/Temperature-conversion/J/temperature-conversion-2.j new file mode 100644 index 0000000000..dfe68051b3 --- /dev/null +++ b/Task/Temperature-conversion/J/temperature-conversion-2.j @@ -0,0 +1,34 @@ + NB. Format matrix for printing + fmt =: '0.2' 8!:0 k2KCFR + + NB. Tag each temp with scale, for human + NB. legibility. + kcfr =: 0 _1 |: 'KCFR' ,"0 1"_1 >@:fmt + + kcfr 21 +K 21.00 +C-252.00 +F-421.87 +R 37.80 + + kcfr 0 NB. Absolute zero +K 0.00 +C-273.00 +F-459.67 +R 0.00 + + kcfr 21 100 300 NB. List of temps works fine +K 21.00 +C-252.00 +F-421.87 +R 37.80 + +K 100.00 +C-173.00 +F-279.67 +R 180.00 + +K 300.00 +C 27.00 +F 80.33 +R 540.00 diff --git a/Task/Temperature-conversion/Java/temperature-conversion.java b/Task/Temperature-conversion/Java/temperature-conversion.java new file mode 100644 index 0000000000..67385e43e7 --- /dev/null +++ b/Task/Temperature-conversion/Java/temperature-conversion.java @@ -0,0 +1,31 @@ +public class TemperatureConversion { + public static void main(String args[]) { + if (args.length == 1) { + try { + double kelvin = Double.parseDouble(args[0]); + if (kelvin >= 0) { + System.out.printf("K %2.2f\n", kelvin); + System.out.printf("C %2.2f\n", kelvinToCelcius(kelvin)); + System.out.printf("F %2.2f\n", kelvinToFahrenheit(kelvin)); + System.out.printf("R %2.2f\n", kelvinToRankine(kelvin)); + } else { + System.out.printf("%2.2f K is below absolute zero", kelvin); + } + } catch (NumberFormatException e) { + System.out.println(e); + } + } + } + + public static double kelvinToCelcius(double k) { + return k + 273.15; + } + + public static double kelvinToFahrenheit(double k) { + return k * 1.8 - 459.67; + } + + public static double kelvinToRankine(double k) { + return k * 1.8; + } +} diff --git a/Task/Temperature-conversion/Julia/temperature-conversion.julia b/Task/Temperature-conversion/Julia/temperature-conversion.julia new file mode 100644 index 0000000000..e122340525 --- /dev/null +++ b/Task/Temperature-conversion/Julia/temperature-conversion.julia @@ -0,0 +1 @@ +cfr(k) = print("Kelvin: $k, Celsius: $(round(k-273.15,2)), Fahrenheit: $(round(k*1.8-459.67,2)), Rankine: $(round(k*1.8,2))") diff --git a/Task/Temperature-conversion/Mathematica/temperature-conversion.math b/Task/Temperature-conversion/Mathematica/temperature-conversion.math new file mode 100644 index 0000000000..9412c3ca58 --- /dev/null +++ b/Task/Temperature-conversion/Mathematica/temperature-conversion.math @@ -0,0 +1,5 @@ +tempConvert[t_] := +Grid[Transpose@{{"K", "C", "F", "R"}, +Round[{t, t - 273.15, 9 t/5 - 459.67, 9 t/5}, .01]}] + +tempConvert[21] diff --git a/Task/Temperature-conversion/Objeck/temperature-conversion.objeck b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck new file mode 100644 index 0000000000..207757cf30 --- /dev/null +++ b/Task/Temperature-conversion/Objeck/temperature-conversion.objeck @@ -0,0 +1,25 @@ +class Temperature { + function : Main(args : String[]) ~ Nil { + k := System.IO.Console->ReadString()->ToFloat(); + c := KelvinToCelcius(k); + f := KelvinToFahrenheit(k); + r := KelvinToRankine(k); + + "K: {$k}"->PrintLine(); + "C: {$c}"->PrintLine(); + "F: {$f}"->PrintLine(); + "R: {$r}"->PrintLine(); + } + + function : KelvinToCelcius(k : Float) ~ Float { + return k - 273.15; + } + + function : KelvinToFahrenheit(k : Float) ~ Float { + return k * 1.8 - 459.67; + } + + function : KelvinToRankine(k : Float) ~ Float { + return k * 1.8; + } +} diff --git a/Task/Temperature-conversion/Objective-C/temperature-conversion.m b/Task/Temperature-conversion/Objective-C/temperature-conversion.m new file mode 100644 index 0000000000..45879b124e --- /dev/null +++ b/Task/Temperature-conversion/Objective-C/temperature-conversion.m @@ -0,0 +1,19 @@ +#import + +int main(int argc, const char * argv[]) +{ + @autoreleasepool { + if(argc > 1) + { + NSString *arg1 = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding]; + // encoding shouldn't matter in this case + double kelvin = [arg1 doubleValue]; + + NSLog(@"K %.2f",kelvin); + NSLog(@"C %.2f\n", kelvin - 273.15); + NSLog(@"F %.2f\n", (kelvin * 1.8) - 459.67); + NSLog(@"R %.2f", kelvin * 1.8); + } + } + return 0; +} diff --git a/Task/Temperature-conversion/PARI-GP/temperature-conversion.pari b/Task/Temperature-conversion/PARI-GP/temperature-conversion.pari new file mode 100644 index 0000000000..9ea2ca6868 --- /dev/null +++ b/Task/Temperature-conversion/PARI-GP/temperature-conversion.pari @@ -0,0 +1 @@ +f(x)=[x,x-273.15,1.8*x-459.67,1.8*x] diff --git a/Task/Temperature-conversion/PHP/temperature-conversion.php b/Task/Temperature-conversion/PHP/temperature-conversion.php new file mode 100644 index 0000000000..35253ac339 --- /dev/null +++ b/Task/Temperature-conversion/PHP/temperature-conversion.php @@ -0,0 +1,20 @@ +error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING )); + +while (true) { + echo "\nEnter a value in kelvin (q to quit): "; + if (($kelvin = trim(fgets(STDIN))) !== false) { + if ($kelvin == 'q') { + echo 'quitting'; + break; + } + if (is_numeric($kelvin)) { + $kelvin = floatVal($kelvin); + if ($kelvin >= 0) { + printf(" K %2.2f\n", $kelvin); + printf(" C %2.2f\n", $kelvin - 273.15); + printf(" F %2.2f\n", $kelvin * 1.8 - 459.67); + printf(" R %2.2f\n", $kelvin * 1.8); + } else printf(" %2.2f K is below absolute zero\n", $kelvin); + } + } +} diff --git a/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 b/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 new file mode 100644 index 0000000000..2903905fbc --- /dev/null +++ b/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 @@ -0,0 +1,13 @@ +while '' ne my $answer = prompt 'Temperature: ' { + my $k = do given $answer { + when s/:i C $// { $_ + 273.15 } + when s/:i F $// { ($_ + 459.67) / 1.8 } + when s/:i R $// { $_ / 1.8 } + when s/:i K $// { $_ } + default { $_ } + } + say " { $k }K"; + say " { $k - 273.15 }℃"; + say " { $k * 1.8 - 459.67 }℉"; + say " { $k * 1.8 }R"; +} diff --git a/Task/Temperature-conversion/Python/temperature-conversion-1.py b/Task/Temperature-conversion/Python/temperature-conversion-1.py new file mode 100644 index 0000000000..dd24963aa5 --- /dev/null +++ b/Task/Temperature-conversion/Python/temperature-conversion-1.py @@ -0,0 +1,11 @@ +>>> while True: + k = float(input('K ? ')) + print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees." + % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8)) + + +K ? 21.0 +21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees. +K ? 222.2 +222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. +K ? diff --git a/Task/Temperature-conversion/Python/temperature-conversion-2.py b/Task/Temperature-conversion/Python/temperature-conversion-2.py new file mode 100644 index 0000000000..3022b956a0 --- /dev/null +++ b/Task/Temperature-conversion/Python/temperature-conversion-2.py @@ -0,0 +1,20 @@ +>>> toK = {'C': (lambda c: c + 273.15), + 'F': (lambda f: (f + 459.67) / 1.8), + 'R': (lambda r: r / 1.8), + 'K': (lambda k: k) } +>>> while True: + magnitude, unit = input(' ? ').split() + k = toK[unit](float(magnitude)) + print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees." + % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8)) + + + ? 222.2 K +222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. + ? -50.95 C +222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. + ? -59.71 F +222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. + ? 399.96 R +222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees. + ? diff --git a/Task/Temperature-conversion/REXX/temperature-conversion.rexx b/Task/Temperature-conversion/REXX/temperature-conversion.rexx new file mode 100644 index 0000000000..7e2326e352 --- /dev/null +++ b/Task/Temperature-conversion/REXX/temperature-conversion.rexx @@ -0,0 +1,55 @@ +/*REXX program converts temperature for: C, D, F, N, Ra, Re, Ro, and K.*/ +parse arg tList /*get specified temperature lists*/ + + do until tList='' /*process a list of temperatures.*/ + parse var tList x ',' tList /*temps are separated by commas. */ + x=space(x); parse var x z '(' /*handle any comments (if any). */ + if z=='' then call serr 'no arguments were specified.' + _=verify(z, '+-.0123456789') /*a list of valid number thingys.*/ + n=z + if _\==0 then do + if _==1 then call serr 'illegal temperature:' z + n=left(z, _-1) /*pick off the number (hopefully)*/ + u=strip(substr(z, _)) /*pick off the temperature unit. */ + end + else u='k' /*assume Kelvin as per task req.*/ + + uU=translate(u,'EE',"éÉ"); upper uU /*uppercase version of temp unit.*/ + if left(uU,7)=='DEGREES' then uU=substr(uU,8) /*redundant "degrees"? */ + if left(uU,5)=='DEGREE' then uU=substr(uU,7) /* " "degree" ? */ + uU=strip(uU) + if \datatype(n,'N') then call serr 'illegal number:' n + /*accept alternate spellings. */ + select /*convert ──► ºF temperatures. */ + when abbrev('CENTIGRADE', uU) |, + abbrev('CENTESIMAL', uU) |, + abbrev('CELSIUS' , uU) |, + abbrev('CELCIUS' , uU) then F=n * 9/5 + 32 + when abbrev('DELISLE' , uU) then F=212 -(n * 6/5) + when abbrev('FAHRENHEIT', uU) then F=n + when abbrev('KELVIN' , uU) then F=n * 9/5 - 459.67 + when abbrev('NEWTON' , uU) then F=n * 60/11 + 32 + when abbrev('RANKINE' , uU) then F=n - 459.67 + when abbrev('REAUMUR' , uU, 2) then F=n * 9/4 + 32 + when abbrev('ROEMER' , uU, 2) |, + abbrev('ROMER' , uU, 2) then F=(n-7.5) * 27/4 + 32 + otherwise call serr 'illegal temperature scale:' u + end /*select*/ + say right(' ' x,55,"─") + say Tform( ( F - 32 ) * 5/9 ) 'Celcius' + say Tform( ( 212 - F ) * 5/6 ) 'Delisle' + say Tform( F ) 'Fahrenheit' + say Tform( ( F + 459.67 ) * 5/9 ) 'Kelvin' + say Tform( ( F - 32 ) * 11/60 ) 'Newton' + say Tform( F + 459.67 ) 'Rankine' + say Tform( ( F - 32 ) * 4/9 ) 'Reaumur' + say Tform( ( F - 32 ) * 7/24 + 7.5 ) 'Romer' + end /*until tlist=''*/ + +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TFORM subroutine────────────────────*/ +Tform: procedure; showDig=8; _=format(arg(1),,showDig)/1; p=pos('.',_) +if p==0 then _=_ || left('',showDig+1) + else _=_ || left('',showDig-length(_)+p); return right(_,20) +/*──────────────────────────────────SERR subroutine─────────────────────*/ +serr: say; say '***error!***'; say; say arg(1); say; exit 13 diff --git a/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run b/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run new file mode 100644 index 0000000000..a5d397fcba --- /dev/null +++ b/Task/Temperature-conversion/Run-BASIC/temperature-conversion.run @@ -0,0 +1,8 @@ +[loop] +input "Lelvin Degrees";kelvin +if kelvin <= 0 then end ' zero or less ends the program +celcius = kelvin - 273.15 +fahrenheit = kelvin * 1.8 - 459.67 +rankine = kelvin * 1.8 +print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine" +goto [loop] diff --git a/Task/Temperature-conversion/Tcl/temperature-conversion-1.tcl b/Task/Temperature-conversion/Tcl/temperature-conversion-1.tcl new file mode 100644 index 0000000000..232c9f9cc6 --- /dev/null +++ b/Task/Temperature-conversion/Tcl/temperature-conversion-1.tcl @@ -0,0 +1,6 @@ +proc temps {k} { + set c [expr {$k - 273.15}] + set r [expr {$k / 5.0 * 9.0}] + set f [expr {$r - 459.67}] + list $k $c $f $r +} diff --git a/Task/Temperature-conversion/Tcl/temperature-conversion-2.tcl b/Task/Temperature-conversion/Tcl/temperature-conversion-2.tcl new file mode 100644 index 0000000000..f7ad3eb913 --- /dev/null +++ b/Task/Temperature-conversion/Tcl/temperature-conversion-2.tcl @@ -0,0 +1,7 @@ +puts -nonewline "Enter a temperature in K: " +flush stdout +lassign [temps [gets stdin]] k c f r +puts [format "K: %.2f" $k] +puts [format "C: %.2f" $c] +puts [format "F: %.2f" $f] +puts [format "R: %.2f" $r] diff --git a/Task/Temperature-conversion/XPL0/temperature-conversion.xpl0 b/Task/Temperature-conversion/XPL0/temperature-conversion.xpl0 new file mode 100644 index 0000000000..db469fa7cd --- /dev/null +++ b/Task/Temperature-conversion/XPL0/temperature-conversion.xpl0 @@ -0,0 +1,10 @@ +include c:\cxpl\codes; +real K, C, F, R; +[ChOut(0, ^K); K:= RlIn(0); +C:= K - 273.15; +ChOut(0, ^C); RlOut(0, C); CrLf(0); +F:= 1.8*C + 32.0; +ChOut(0, ^F); RlOut(0, F); CrLf(0); +R:= F + 459.67; +ChOut(0, ^R); RlOut(0, R); CrLf(0); +] diff --git a/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx new file mode 100644 index 0000000000..e792ba8bc2 --- /dev/null +++ b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.zx @@ -0,0 +1,11 @@ +10 REM Translation of traditional basic version +20 INPUT "Kelvin Degrees? ";k +30 IF k <= 0 THEN STOP: REM A value of zero or less will end program +40 LET c = k - 273.15 +50 LET f = k * 1.8 - 459.67 +60 LET r = k * 1.8 +70 PRINT k; " Kelvin is equivalent to" +80 PRINT c; " Degrees Celcius" +90 PRINT f; " Degrees Fahrenheit" +100 PRINT r; " Degrees Rankine" +110 GO TO 20 diff --git a/Task/Terminal-control-Clear-the-screen/0DESCRIPTION b/Task/Terminal-control-Clear-the-screen/0DESCRIPTION new file mode 100644 index 0000000000..62305c6412 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/0DESCRIPTION @@ -0,0 +1,2 @@ +Clear the terminal window. +[[Terminal Control::task| ]] diff --git a/Task/Terminal-control-Clear-the-screen/1META.yaml b/Task/Terminal-control-Clear-the-screen/1META.yaml new file mode 100644 index 0000000000..181b40ba75 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Initialization +note: Terminal control diff --git a/Task/Terminal-control-Clear-the-screen/AWK/terminal-control-clear-the-screen.awk b/Task/Terminal-control-Clear-the-screen/AWK/terminal-control-clear-the-screen.awk new file mode 100644 index 0000000000..5b03b08eeb --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/AWK/terminal-control-clear-the-screen.awk @@ -0,0 +1 @@ +system("clear") diff --git a/Task/Terminal-control-Clear-the-screen/Ada/terminal-control-clear-the-screen.ada b/Task/Terminal-control-Clear-the-screen/Ada/terminal-control-clear-the-screen.ada new file mode 100644 index 0000000000..ff9ad6c422 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Ada/terminal-control-clear-the-screen.ada @@ -0,0 +1,5 @@ +with Ada.Text_IO; +procedure CLS is +begin + Ada.Text_IO.Put(ASCII.ESC & "[2J"); +end CLS; diff --git a/Task/Terminal-control-Clear-the-screen/AutoHotkey/terminal-control-clear-the-screen.ahk b/Task/Terminal-control-Clear-the-screen/AutoHotkey/terminal-control-clear-the-screen.ahk new file mode 100644 index 0000000000..5a844fa6ee --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/AutoHotkey/terminal-control-clear-the-screen.ahk @@ -0,0 +1 @@ +RunWait %comspec% /c cls diff --git a/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen.basic b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen.basic new file mode 100644 index 0000000000..df55db4c29 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen.basic @@ -0,0 +1 @@ +CLS diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc new file mode 100644 index 0000000000..1990de62cc --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-1.bbc @@ -0,0 +1 @@ + CLS diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc new file mode 100644 index 0000000000..747b079d8b --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-2.bbc @@ -0,0 +1 @@ + VDU 12 diff --git a/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc new file mode 100644 index 0000000000..a311bea00d --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/BBC-BASIC/terminal-control-clear-the-screen-3.bbc @@ -0,0 +1 @@ + PRINT CHR$(12); diff --git a/Task/Terminal-control-Clear-the-screen/Batch-File/terminal-control-clear-the-screen.bat b/Task/Terminal-control-Clear-the-screen/Batch-File/terminal-control-clear-the-screen.bat new file mode 100644 index 0000000000..df55db4c29 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Batch-File/terminal-control-clear-the-screen.bat @@ -0,0 +1 @@ +CLS diff --git a/Task/Terminal-control-Clear-the-screen/Blast/terminal-control-clear-the-screen.blast b/Task/Terminal-control-Clear-the-screen/Blast/terminal-control-clear-the-screen.blast new file mode 100644 index 0000000000..5b4f8bb605 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Blast/terminal-control-clear-the-screen.blast @@ -0,0 +1 @@ +clear diff --git a/Task/Terminal-control-Clear-the-screen/Bracmat/terminal-control-clear-the-screen.bracmat b/Task/Terminal-control-Clear-the-screen/Bracmat/terminal-control-clear-the-screen.bracmat new file mode 100644 index 0000000000..974487d746 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Bracmat/terminal-control-clear-the-screen.bracmat @@ -0,0 +1 @@ +sys$cls& diff --git a/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-1.c b/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-1.c new file mode 100644 index 0000000000..211458b66a --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-1.c @@ -0,0 +1,4 @@ +void cls(void) { + int printf(char*,...); + printf("%c[2J",27); +} diff --git a/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-2.c b/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-2.c new file mode 100644 index 0000000000..9743125f95 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/C/terminal-control-clear-the-screen-2.c @@ -0,0 +1,9 @@ +#include +#include + +void main() +{ + printf ("clearing screen"); + getchar(); + System("cls"); +} diff --git a/Task/Terminal-control-Clear-the-screen/D/terminal-control-clear-the-screen.d b/Task/Terminal-control-Clear-the-screen/D/terminal-control-clear-the-screen.d new file mode 100644 index 0000000000..01dc24369f --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/D/terminal-control-clear-the-screen.d @@ -0,0 +1,13 @@ +extern (C) nothrow { + void disp_open(); + void disp_move(int, int); + void disp_eeop(); + void disp_close(); +} + +void main() { + disp_open(); + disp_move(0, 0); + disp_eeop(); + disp_close(); +} diff --git a/Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.euphoria b/Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.euphoria new file mode 100644 index 0000000000..72aa8458b1 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.euphoria @@ -0,0 +1 @@ +clear_screen() diff --git a/Task/Terminal-control-Clear-the-screen/Forth/terminal-control-clear-the-screen.fth b/Task/Terminal-control-Clear-the-screen/Forth/terminal-control-clear-the-screen.fth new file mode 100644 index 0000000000..f522bd472a --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Forth/terminal-control-clear-the-screen.fth @@ -0,0 +1 @@ +page diff --git a/Task/Terminal-control-Clear-the-screen/GUISS/terminal-control-clear-the-screen.guiss b/Task/Terminal-control-Clear-the-screen/GUISS/terminal-control-clear-the-screen.guiss new file mode 100644 index 0000000000..fe6640cb4b --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/GUISS/terminal-control-clear-the-screen.guiss @@ -0,0 +1 @@ +Window:Terminal,Type:clear[enter] diff --git a/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic b/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic new file mode 100644 index 0000000000..d8ed2b0aef --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/GW-BASIC/terminal-control-clear-the-screen.gw-basic @@ -0,0 +1 @@ +10 CLS diff --git a/Task/Terminal-control-Clear-the-screen/Go/terminal-control-clear-the-screen.go b/Task/Terminal-control-Clear-the-screen/Go/terminal-control-clear-the-screen.go new file mode 100644 index 0000000000..fed6d021a6 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Go/terminal-control-clear-the-screen.go @@ -0,0 +1,12 @@ +package main + +import ( + "os" + "os/exec" +) + +func main() { + c := exec.Command("clear") + c.Stdout = os.Stdout + c.Run() +} diff --git a/Task/Terminal-control-Clear-the-screen/Icon/terminal-control-clear-the-screen.icon b/Task/Terminal-control-Clear-the-screen/Icon/terminal-control-clear-the-screen.icon new file mode 100644 index 0000000000..70ee343973 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Icon/terminal-control-clear-the-screen.icon @@ -0,0 +1,4 @@ +procedure main () + if &features == "MS Windows" then system("cls") # Windows + else if &features == "UNIX" then system("clear") # Unix +end diff --git a/Task/Terminal-control-Clear-the-screen/J/terminal-control-clear-the-screen.j b/Task/Terminal-control-Clear-the-screen/J/terminal-control-clear-the-screen.j new file mode 100644 index 0000000000..87f7ce60ae --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/J/terminal-control-clear-the-screen.j @@ -0,0 +1 @@ +smwrite_jijs_ '' diff --git a/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-1.logo b/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-1.logo new file mode 100644 index 0000000000..af7fd11ef0 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-1.logo @@ -0,0 +1 @@ +cleartext diff --git a/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-2.logo b/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-2.logo new file mode 100644 index 0000000000..7e342d9305 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Logo/terminal-control-clear-the-screen-2.logo @@ -0,0 +1,3 @@ +clearscreen +cs ; abbreviation for clearscreen +clean ; like cs, but doesn't reset turtle position 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 new file mode 100644 index 0000000000..f24fd1daad --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen.lua @@ -0,0 +1 @@ +os.execute( "clear" ) diff --git a/Task/Terminal-control-Clear-the-screen/Mathematica/terminal-control-clear-the-screen.math b/Task/Terminal-control-Clear-the-screen/Mathematica/terminal-control-clear-the-screen.math new file mode 100644 index 0000000000..4e6a8479c5 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Mathematica/terminal-control-clear-the-screen.math @@ -0,0 +1 @@ +Run["clear"]; diff --git a/Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ocaml b/Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ocaml new file mode 100644 index 0000000000..a36beeeecf --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ocaml @@ -0,0 +1,7 @@ +#load "unix.cma" +#directory "+ANSITerminal" +#load "ANSITerminal.cma" +open ANSITerminal + +let () = + erase Screen diff --git a/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-1.octave b/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-1.octave new file mode 100644 index 0000000000..3e14068c86 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-1.octave @@ -0,0 +1 @@ + system clear; diff --git a/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-2.octave b/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-2.octave new file mode 100644 index 0000000000..89d1b332be --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Octave/terminal-control-clear-the-screen-2.octave @@ -0,0 +1 @@ + system('clear'); diff --git a/Task/Terminal-control-Clear-the-screen/Pascal/terminal-control-clear-the-screen.pascal b/Task/Terminal-control-Clear-the-screen/Pascal/terminal-control-clear-the-screen.pascal new file mode 100644 index 0000000000..adf9829c2a --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Pascal/terminal-control-clear-the-screen.pascal @@ -0,0 +1 @@ +clrscr; diff --git a/Task/Terminal-control-Clear-the-screen/Perl-6/terminal-control-clear-the-screen.pl6 b/Task/Terminal-control-Clear-the-screen/Perl-6/terminal-control-clear-the-screen.pl6 new file mode 100644 index 0000000000..1962b83821 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Perl-6/terminal-control-clear-the-screen.pl6 @@ -0,0 +1,2 @@ +sub clear { print state $ = qx[clear] } +clear; diff --git a/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-1.pl b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-1.pl new file mode 100644 index 0000000000..5f811a4b81 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-1.pl @@ -0,0 +1 @@ +system('clear') diff --git a/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-2.pl b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-2.pl new file mode 100644 index 0000000000..74b35c8620 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-2.pl @@ -0,0 +1,3 @@ +$clear = `clear`; # clear simply prints some escape sequence, cache it +#... later: +print $clear; diff --git a/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-3.pl b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-3.pl new file mode 100644 index 0000000000..b0fdbc9bd7 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Perl/terminal-control-clear-the-screen-3.pl @@ -0,0 +1,5 @@ +use Term::Cap; + +$terminal = Term::Cap->Tgetent(); +$clear = $terminal->Tputs('cl'); +print $clear; diff --git a/Task/Terminal-control-Clear-the-screen/PicoLisp/terminal-control-clear-the-screen.l b/Task/Terminal-control-Clear-the-screen/PicoLisp/terminal-control-clear-the-screen.l new file mode 100644 index 0000000000..b668fd8b1e --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/PicoLisp/terminal-control-clear-the-screen.l @@ -0,0 +1 @@ +(call 'clear) diff --git a/Task/Terminal-control-Clear-the-screen/PowerShell/terminal-control-clear-the-screen.psh b/Task/Terminal-control-Clear-the-screen/PowerShell/terminal-control-clear-the-screen.psh new file mode 100644 index 0000000000..0ebc7b74e9 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/PowerShell/terminal-control-clear-the-screen.psh @@ -0,0 +1 @@ +Clear-Host diff --git a/Task/Terminal-control-Clear-the-screen/ProDOS/terminal-control-clear-the-screen.dos b/Task/Terminal-control-Clear-the-screen/ProDOS/terminal-control-clear-the-screen.dos new file mode 100644 index 0000000000..11f364ab86 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/ProDOS/terminal-control-clear-the-screen.dos @@ -0,0 +1 @@ +clearscurrentscreentext diff --git a/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic b/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic new file mode 100644 index 0000000000..c7e42b6386 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/PureBasic/terminal-control-clear-the-screen.purebasic @@ -0,0 +1 @@ +ClearConsole() diff --git a/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-1.py b/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-1.py new file mode 100644 index 0000000000..c2c486c6fb --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-1.py @@ -0,0 +1,2 @@ +import os +os.system('clear') diff --git a/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-2.py b/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-2.py new file mode 100644 index 0000000000..e2fb7cb5e9 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Python/terminal-control-clear-the-screen-2.py @@ -0,0 +1 @@ +print "%c[2J" % (27) diff --git a/Task/Terminal-control-Clear-the-screen/Retro/terminal-control-clear-the-screen.retro b/Task/Terminal-control-Clear-the-screen/Retro/terminal-control-clear-the-screen.retro new file mode 100644 index 0000000000..5b4f8bb605 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Retro/terminal-control-clear-the-screen.retro @@ -0,0 +1 @@ +clear diff --git a/Task/Terminal-control-Clear-the-screen/Ruby/terminal-control-clear-the-screen.rb b/Task/Terminal-control-Clear-the-screen/Ruby/terminal-control-clear-the-screen.rb new file mode 100644 index 0000000000..cb4916aff8 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Ruby/terminal-control-clear-the-screen.rb @@ -0,0 +1 @@ +system 'clear' diff --git a/Task/Terminal-control-Clear-the-screen/Seed7/terminal-control-clear-the-screen.seed7 b/Task/Terminal-control-Clear-the-screen/Seed7/terminal-control-clear-the-screen.seed7 new file mode 100644 index 0000000000..7f14ca2c5d --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Seed7/terminal-control-clear-the-screen.seed7 @@ -0,0 +1,14 @@ +$ include "seed7_05.s7i"; + include "console.s7i"; + +const proc: main is func + local + var text: console is STD_NULL; + begin + console := open(CONSOLE); + clear(console); + # Terminal windows often restore the previous + # content, when a program is terminated. Therefore + # the program waits until Return/Enter is pressed. + readln; + end func; diff --git a/Task/Terminal-control-Clear-the-screen/Smalltalk/terminal-control-clear-the-screen.st b/Task/Terminal-control-Clear-the-screen/Smalltalk/terminal-control-clear-the-screen.st new file mode 100644 index 0000000000..cf3fd5f0b9 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Smalltalk/terminal-control-clear-the-screen.st @@ -0,0 +1 @@ +Transcript clear. diff --git a/Task/Terminal-control-Clear-the-screen/Tcl/terminal-control-clear-the-screen.tcl b/Task/Terminal-control-Clear-the-screen/Tcl/terminal-control-clear-the-screen.tcl new file mode 100644 index 0000000000..5bfe18d179 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Tcl/terminal-control-clear-the-screen.tcl @@ -0,0 +1,2 @@ +puts -nonewline "\033\[2J" +flush stdout diff --git a/Task/Terminal-control-Clear-the-screen/UNIX-Shell/terminal-control-clear-the-screen.sh b/Task/Terminal-control-Clear-the-screen/UNIX-Shell/terminal-control-clear-the-screen.sh new file mode 100644 index 0000000000..251db64244 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/UNIX-Shell/terminal-control-clear-the-screen.sh @@ -0,0 +1,4 @@ +clear + +# Alternative method using tput +tput clear diff --git a/Task/Terminal-control-Clear-the-screen/XPL0/terminal-control-clear-the-screen.xpl0 b/Task/Terminal-control-Clear-the-screen/XPL0/terminal-control-clear-the-screen.xpl0 new file mode 100644 index 0000000000..815de7a9c8 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/XPL0/terminal-control-clear-the-screen.xpl0 @@ -0,0 +1,2 @@ +code Clear=40; +Clear; diff --git a/Task/Terminal-control-Coloured-text/0DESCRIPTION b/Task/Terminal-control-Coloured-text/0DESCRIPTION new file mode 100644 index 0000000000..2742445f98 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/0DESCRIPTION @@ -0,0 +1,7 @@ +The task is to display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. + +Optionally demonstrate: + +* How the system should determine if the terminal supports colour +* Setting of the background colour +* How to cause blinking or flashing (if supported by the terminal) diff --git a/Task/Terminal-control-Coloured-text/1META.yaml b/Task/Terminal-control-Coloured-text/1META.yaml new file mode 100644 index 0000000000..069491832d --- /dev/null +++ b/Task/Terminal-control-Coloured-text/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Terminal control diff --git a/Task/Terminal-control-Coloured-text/AutoHotkey/terminal-control-coloured-text.ahk b/Task/Terminal-control-Coloured-text/AutoHotkey/terminal-control-coloured-text.ahk new file mode 100644 index 0000000000..5bf871a4f4 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/AutoHotkey/terminal-control-coloured-text.ahk @@ -0,0 +1,18 @@ +DllCall( "AllocConsole" ) ; create a console if not launched from one +hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) +Loop 15 + SetConsoleTextAttribute(hConsole, A_Index) + ,WriteConsole(hConsole, "AutoHotkey`n") + +MsgBox + +SetConsoleTextAttribute(hConsole, Attributes){ + return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes) +} +WriteConsole(hConsole, text){ + VarSetCapacity(out, 16) + If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text) + , UPtrP, out, uint, 0 ) + return out + return 0 +} diff --git a/Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text.basic b/Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text.basic new file mode 100644 index 0000000000..df168ae7db --- /dev/null +++ b/Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text.basic @@ -0,0 +1,4 @@ +FOR n = 1 TO 15 + COLOR n + PRINT "Rosetta Code" +NEXT diff --git a/Task/Terminal-control-Coloured-text/BBC-BASIC/terminal-control-coloured-text.bbc b/Task/Terminal-control-Coloured-text/BBC-BASIC/terminal-control-coloured-text.bbc new file mode 100644 index 0000000000..a03f694e90 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/BBC-BASIC/terminal-control-coloured-text.bbc @@ -0,0 +1,5 @@ + FOR col% = 0 TO 14 + COLOUR col% : REM foreground + COLOUR 128+(15-col%) : REM background + PRINT "Rosetta Code" + NEXT diff --git a/Task/Terminal-control-Coloured-text/C/terminal-control-coloured-text.c b/Task/Terminal-control-Coloured-text/C/terminal-control-coloured-text.c new file mode 100644 index 0000000000..c6987354a5 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/C/terminal-control-coloured-text.c @@ -0,0 +1,30 @@ +#include + +void table(const char *title, const char *mode) +{ + int f, b; + printf("\n\033[1m%s\033[m\n bg\t fg\n", title); + for (b = 40; b <= 107; b++) { + if (b == 48) b = 100; + printf("%3d\t\033[%s%dm", b, mode, b); + for (f = 30; f <= 97; f++) { + if (f == 38) f = 90; + printf("\033[%dm%3d ", f, f); + } + puts("\033[m"); + } +} + +int main(void) +{ + int fg, bg, blink, inverse; + + table("normal ( ESC[22m or ESC[m )", "22;"); + table("bold ( ESC[1m )", "1;"); + table("faint ( ESC[2m ), not well supported", "2;"); + table("italic ( ESC[3m ), not well supported", "3;"); + table("underline ( ESC[4m ), support varies", "4;"); + table("blink ( ESC[5m )", "5;"); + table("inverted ( ESC[7m )", "7;"); + return 0; +} diff --git a/Task/Terminal-control-Coloured-text/Haskell/terminal-control-coloured-text.hs b/Task/Terminal-control-Coloured-text/Haskell/terminal-control-coloured-text.hs new file mode 100644 index 0000000000..0dd344f6a6 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Haskell/terminal-control-coloured-text.hs @@ -0,0 +1,17 @@ +#!/usr/bin/runhaskell + +import System.Console.ANSI + +colorStrLn :: ColorIntensity -> Color -> ColorIntensity -> Color -> String -> IO () +colorStrLn fgi fg bgi bg str = do + setSGR [SetColor Foreground fgi fg, SetColor Background bgi bg] + putStr str + setSGR [] + putStrLn "" + +main = do + colorStrLn Vivid White Vivid Red "This is red on white." + colorStrLn Vivid White Dull Blue "This is white on blue." + colorStrLn Vivid Green Dull Black "This is green on black." + colorStrLn Vivid Yellow Dull Black "This is yellow on black." + colorStrLn Dull Black Vivid Blue "This is black on light blue." diff --git a/Task/Terminal-control-Coloured-text/J/terminal-control-coloured-text.j b/Task/Terminal-control-Coloured-text/J/terminal-control-coloured-text.j new file mode 100644 index 0000000000..5d55e691da --- /dev/null +++ b/Task/Terminal-control-Coloured-text/J/terminal-control-coloured-text.j @@ -0,0 +1,28 @@ +NB. relies on an vt100 terminal + +CSI=: 27 91 { a. +'BLACK BLUE CYAN WHITE'=: 0 4 6 7 +'OFF REVERSEVIDEO'=: 0 7 + +HIDECURSOR=: CSI,'?25l' +SHOWCURSOR=: CSI,'?25h' + +csi=: (,~ (CSI , (' '&=)`(,:&';')}@:":))~ +clear=: csi&'J' +attributes=: csi&'m' +color=: BLACK&$: : (attributes@:(40 30 + ,)) NB. BACKGROUND color FOREGROUND +move=: csi&'H' + +upward=: csi&'A' +downward=: csi&'B' +foreward=: csi&'C' +backward=: csi&'D' + +DB=: (downward , backward) '' + +NB. J is character vector to simulate the J icon. +J=: (BLUE color WHITE[CYAN) +J=: J , (backward 1),' T ',(backward 1),DB,,3#,:'|',DB +J=: J , (backward 5),'* |',DB +J=: J , (backward 5),'\____/' +smoutput(color BLACK),(clear 2),(move 8 22),J,(WHITE color BLACK),(downward 2) diff --git a/Task/Terminal-control-Coloured-text/Mathematica/terminal-control-coloured-text.math b/Task/Terminal-control-Coloured-text/Mathematica/terminal-control-coloured-text.math new file mode 100644 index 0000000000..88e70d9e35 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Mathematica/terminal-control-coloured-text.math @@ -0,0 +1,3 @@ +Run["tput setaf 1"]; Print["Coloured Text"]; +Run["tput setaf 2"]; Print["Coloured Text"]; +Run["tput setaf 3"]; Print["Coloured Text"] diff --git a/Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ocaml b/Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ocaml new file mode 100644 index 0000000000..e9870f828d --- /dev/null +++ b/Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ocaml @@ -0,0 +1,6 @@ +$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma + +# open ANSITerminal ;; +# print_string [cyan; on_blue] "Hello\n" ;; +Hello +- : unit = () diff --git a/Task/Terminal-control-Coloured-text/PicoLisp/terminal-control-coloured-text.l b/Task/Terminal-control-Coloured-text/PicoLisp/terminal-control-coloured-text.l new file mode 100644 index 0000000000..a8ace9322a --- /dev/null +++ b/Task/Terminal-control-Coloured-text/PicoLisp/terminal-control-coloured-text.l @@ -0,0 +1,15 @@ +(unless (member (sys "TERM") '("linux" "xterm" "xterm-color" "rxvt")) + (quit "This application requires a colour terminal") ) + +# Coloured text +(for X '((1 . "Red") (4 . "Blue") (3 . "Yellow")) + (call 'tput "setaf" (car X)) + (prinl (cdr X)) ) + +# Blinking +(out '(tput "-S") + (prinl "setab 1^Jsetaf 3^Jblink") ) +(prin "Flashing text") + +(call 'tput 'sgr0) # reset +(prinl) diff --git a/Task/Terminal-control-Coloured-text/PureBasic/terminal-control-coloured-text.purebasic b/Task/Terminal-control-Coloured-text/PureBasic/terminal-control-coloured-text.purebasic new file mode 100644 index 0000000000..ceb651b86a --- /dev/null +++ b/Task/Terminal-control-Coloured-text/PureBasic/terminal-control-coloured-text.purebasic @@ -0,0 +1,20 @@ +If OpenConsole() + PrintN("Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15") + PrintN(" -----------------------------------------------") + Define Foreground, Background + For Foreground = 0 To 15 + ConsoleColor(7, 0) ;grey foreground, black background + Print("Foreground color# " + RSet(Str(Foreground), 2, "0") + " ") + For Background = 0 To 15 + ConsoleColor(Foreground, Background) + Print(RSet(Str(Foreground), 2, "0")) + ConsoleColor(7, 0) ;grey foreground, black background + Print(" ") + Next + PrintN("") + Next + + ConsoleColor(7, 0) ;grey foreground, black background + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf 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 new file mode 100644 index 0000000000..330f53bf48 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text.py @@ -0,0 +1,11 @@ +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/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx b/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx new file mode 100644 index 0000000000..630baf2dba --- /dev/null +++ b/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx @@ -0,0 +1,34 @@ +/*REXX program to display sixteen lines, each of a different color. */ +parse arg !; if !all() then exit /*exit if documentation specified*/ +if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */ +if \!pcrexx then exit /*if this isn't PC/REXX, exit. */ + +color.0 = 'black' /*┌─────────────────────────────┐*/ +color.1 = 'dark blue' /*│ Normally, all programs issue│*/ +color.2 = 'dark green' /*│ the (above) error messages │*/ +color.3 = 'dark cyan/turquois' /*│ through another REXX program│*/ +color.4 = 'dark red' /*│ ($ERR) which has more │*/ +color.5 = 'dark pink/magenta' /*│ verbage and explanations, │*/ +color.6 = 'dark yellow (orange)' /*│ and issues the error text in│*/ +color.7 = 'dark white' /*│ red (if color is available).│*/ +color.8 = 'brite black (grey/gray)' /*└─────────────────────────────┘*/ +color.9 = 'bright blue' +color.10 = 'bright green' +color.11 = 'bright cyan/turquois' +color.12 = 'bright red' +color.13 = 'bright pink/magenta' +color.14 = 'bright yellow' +color.15 = 'bright white' + + do j=0 to 15 /*show all sixteen color codes. */ + call scrwrite ,,'color code=['right(j,2)"]" color.j,,,j; say + end /*j*/ /*the "SAY" forces a NEWLINE. */ +exit /*stick a fork in it, we're done.*/ +/*══════════════════════════════════general 1-line subs═════════════════*/ +!all:!!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 +!cal:if symbol('!CALL')\=="VAR" then !call=;return !call +!env:!env='ENVIRONMENT';if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM';if !os2 then !env='OS2'!env;!ebcdic=1=='f0'x;return +!fid:parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;call !sys;if !dos then do;_=lastpos('\',!fn);!fm=left(!fn,_);!fn=substr(!fn,_+1);parse var !fn !fn '.' !ft;end;return word(0 !fn !ft !fm,1+('0'arg(1))) +!rex:parse upper version !ver !vernum !verdate .;!brexx='BY'==!vernum;!kexx='KEXX'==!ver;!pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver;!r4='REXX-R4'==!ver;!regina='REXX-REGINA'==left(!ver,11);!roo='REXX-ROO'==!ver;call !env;return +!sys:!cms=!sys=='CMS';!os2=!sys=='OS2';!tso=!sys=='TSO'|!sys=='MVS';!vse=!sys=='VSE';!dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD';call !rex;return +!var:call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env)) diff --git a/Task/Terminal-control-Coloured-text/Ruby/terminal-control-coloured-text.rb b/Task/Terminal-control-Coloured-text/Ruby/terminal-control-coloured-text.rb new file mode 100644 index 0000000000..3919737608 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Ruby/terminal-control-coloured-text.rb @@ -0,0 +1,24 @@ +#!/usr/bin/ruby -w +require 'rubygems' +require 'colored' + +print 'Colors are'.bold +print ' black'.black +print ' blue'.blue +print ' cyan'.cyan +print ' green'.green +print ' magenta'.magenta +print ' red'.red +print ' white '.white +print 'and'.underline, ' yellow'.yellow, "\n" +puts 'black on blue'.black_on_blue +puts 'black on cyan'.black_on_cyan +puts 'black on green'.black_on_green +puts 'black on magenta'.black_on_magenta +puts 'black on red'.black_on_red +puts 'white on black'.white_on_black +puts 'white on blue'.white_on_blue +puts 'white on cyan'.white_on_cyan +puts 'white on green'.white_on_green +puts 'white on magenta'.white_on_magenta +puts 'white on red'.white_on_red diff --git a/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-1.tcl b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-1.tcl new file mode 100644 index 0000000000..6ede84c262 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-1.tcl @@ -0,0 +1,26 @@ +# Utility interfaces to the low-level command +proc capability cap {expr {![catch {exec tput -S << $cap}]}} +proc colorterm {} {expr {[capability setaf] && [capability setab]}} +proc tput args {exec tput -S << $args >/dev/tty} +array set color {black 0 red 1 green 2 yellow 3 blue 4 magenta 5 cyan 6 white 7} +proc foreground x {exec tput -S << "setaf $::color($x)" > /dev/tty} +proc background x {exec tput -S << "setab $::color($x)" > /dev/tty} +proc reset {} {exec tput sgr0 > /dev/tty} + +# Demonstration of use +if {[colorterm]} { + foreground blue + background yellow + puts "Color output" + reset +} else { + puts "Monochrome only" +} + +if {[capability blink]} { + tput blink + puts "Blinking output" + reset +} else { + puts "Steady only" +} diff --git a/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-2.tcl b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-2.tcl new file mode 100644 index 0000000000..e9c461c25a --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-2.tcl @@ -0,0 +1,12 @@ +--color red +This is red +--color green +This is green +--color blue +This is blue +--color cyan +This is cyan +--color magenta +This is magenta +--color yellow +This is yellow diff --git a/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-3.tcl b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-3.tcl new file mode 100644 index 0000000000..de1908f948 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Tcl/terminal-control-coloured-text-3.tcl @@ -0,0 +1,43 @@ +#!/bin/sh +# Check if the terminal supports colour + +# We should know from the TERM evironment variable whether the system +# is comfigured for a colour terminal or not, but we can also check the +# tput utility to check the terminal capability records. + +COLORS=8 # Assume initially that the system supports eight colours +case $TERM in + linux) + ;; # We know this is a colour terminal + rxvt) + ;; # We know this is a colour terminal + *) + COLORS=`tput colors 2> /dev/null` # Get the number of colours from the termcap file +esac +if [ -z $COLORS ] ; then + COLORS=1 # Watch out for an empty returned value +fi + +if [ $COLORS -le 2 ] ; then + # The terminal is not colour + echo "HW65000 This application requires a colour terminal" >&2 + exit 252 #ERLHW incompatible hardware +fi + +# We know at this point that the terminal is colour + +# Coloured text +tput setaf 1 #red +echo "Red" +tput setaf 4 #blue +echo "Blue" +tput setaf 3 # yellow +echo "Yellow" + +# Blinking +tput setab 1 # red background +tput setaf 3 # yellow foreground +#tput blink # enable blinking (but does not work on some terminals) +echo "Flashing text" + +tput sgr0 # reset everything before exiting diff --git a/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 b/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 new file mode 100644 index 0000000000..d30d1a0167 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-1.xpl0 @@ -0,0 +1,15 @@ +code ChOut=8, Attrib=69; +def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors + Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette +[ChOut(6,^C); \default white on black background +Attrib(Red<<4+White); \white on red +ChOut(6,^o); +Attrib(Green<<4+Red); \red on green +ChOut(6,^l); +Attrib(Blue<<4+LGreen); \light green on blue +ChOut(6,^o); +Attrib(LRed<<4+White); \flashing white on (standard/dim) red +ChOut(6,^u); +Attrib(Cyan<<4+Black); \black on cyan +ChOut(6,^r); +] diff --git a/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-2.xpl0 b/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-2.xpl0 new file mode 100644 index 0000000000..9f9518b6af --- /dev/null +++ b/Task/Terminal-control-Coloured-text/XPL0/terminal-control-coloured-text-2.xpl0 @@ -0,0 +1,13 @@ +10 FOR l=0 TO 7 +20 READ c$: REM get our text for display +30 INK l: REM set the text colour +40 PRINT c$ +50 NEXT l +60 PAPER 2: REM red background +70 INK 6: REM yellow forground +80 FLASH 1: REM activate flashing +90 PRINT "Flashing!": REM this will flash red and yellow (alternating inverse) +100 PAPER 7: INK 0: FLASH 0: REM normalize colours before exit +110 STOP + +900 DATA "Black","Blue","Red","Magenta","Green","Cyan","Yellow","White" diff --git a/Task/Terminal-control-Cursor-movement/0DESCRIPTION b/Task/Terminal-control-Cursor-movement/0DESCRIPTION new file mode 100644 index 0000000000..7797fd3ebf --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/0DESCRIPTION @@ -0,0 +1,16 @@ +The task is to demonstrate how to achieve movement of the terminal cursor: + +* Demonstrate how to move the cursor one position to the left +* Demonstrate how to move the cursor one position to the right +* Demonstrate how to move the cursor up one line (without affecting its horizontal position) +* Demonstrate how to move the cursor down one line (without affecting its horizontal position) +* Demonstrate how to move the cursor to the beginning of the line +* Demonstrate how to move the cursor to the end of the line +* Demonstrate how to move the cursor to the top left corner of the screen +* Demonstrate how to move the cursor to the bottom right corner of the screen + +For the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right). + +;Handling of out of bounds locomotion + +This task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behaviour fits best in terms of the chosen language. Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted. diff --git a/Task/Terminal-control-Cursor-movement/1META.yaml b/Task/Terminal-control-Cursor-movement/1META.yaml new file mode 100644 index 0000000000..9c15565476 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Terminal control diff --git a/Task/Terminal-control-Cursor-movement/BASIC/terminal-control-cursor-movement.basic b/Task/Terminal-control-Cursor-movement/BASIC/terminal-control-cursor-movement.basic new file mode 100644 index 0000000000..466add93d8 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/BASIC/terminal-control-cursor-movement.basic @@ -0,0 +1,16 @@ +10 'move left +20 LOCATE , POS(0) - 1 +30 'move right +40 LOCATE , POS(0) + 1 +50 'move up +60 LOCATE CSRLIN - 1 +70 'move down +80 LOCATE CSRLIN + 1 +900 'beginning of line +100 LOCATE , 1 +110 'end of line; requires previous knowledge of screen width -- typically 80 +120 LOCATE , 80 +130 'top left corner +140 LOCATE 1, 1 +150 'bottom right corner; requires knowledge of screen dimensions (80x25 here) +160 LOCATE 25, 80 diff --git a/Task/Terminal-control-Cursor-movement/BBC-BASIC/terminal-control-cursor-movement.bbc b/Task/Terminal-control-Cursor-movement/BBC-BASIC/terminal-control-cursor-movement.bbc new file mode 100644 index 0000000000..c2f1c3275c --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/BBC-BASIC/terminal-control-cursor-movement.bbc @@ -0,0 +1,10 @@ + VDU 8 : REM Move one position to the left + VDU 9 : REM Move one position to the right + VDU 11 : REM Move up one line + VDU 10 : REM Move down one line + VDU 13 : REM Move to the beginning of the line + VDU 30 : REM Move to the top left corner + VDU 23,16,16;0;0;0; : REM Disable scrolling + VDU 13,8,10 : REM Move to the end of the line + VDU 30,8 : REM Move to the bottom right corner + VDU 23,16,0;0;0;0; : REM Enable scrolling diff --git a/Task/Terminal-control-Cursor-movement/Mathematica/terminal-control-cursor-movement.math b/Task/Terminal-control-Cursor-movement/Mathematica/terminal-control-cursor-movement.math new file mode 100644 index 0000000000..5724d9481a --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Mathematica/terminal-control-cursor-movement.math @@ -0,0 +1,13 @@ +Run["tput cub1"] (* one position to the left *) +Run["tput cuf1" ] (* one position to the right *) +Run["tput cuu1" ] (* up one line *) +Run["tput cud1"] (* down one line *) +Run["tput cr"] (* beginning of line *) +Run["tput home"] (* top left corner *) + + +WIDTH=RunThrough["tput cols", ""]; +HEIGHT=RunThrough["tput lines", ""]; + +Run["tput hpa "<>WIDTH] (* end of line *) +Run["tput cup "<>HEIGHT<>" "<> WIDTH] (* bottom right corner *) diff --git a/Task/Terminal-control-Cursor-movement/PicoLisp/terminal-control-cursor-movement.l b/Task/Terminal-control-Cursor-movement/PicoLisp/terminal-control-cursor-movement.l new file mode 100644 index 0000000000..89ba9376a9 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/PicoLisp/terminal-control-cursor-movement.l @@ -0,0 +1,8 @@ +(call 'tput "cub1") # one position to the left +(call 'tput "cuf1") # one position to the right +(call 'tput "cuu1") # up one line +(call 'tput "cud1") # down one line +(call 'tput "cr") # beginning of the line +(call 'tput "hpa" (sys "COLUMNS")) # end of the line +(call 'tput "home") # top left corner +(call 'tput "cup" (sys "LINES") (sys "COLUMNS")) # bottom right corner diff --git a/Task/Terminal-control-Cursor-movement/REXX/terminal-control-cursor-movement.rexx b/Task/Terminal-control-Cursor-movement/REXX/terminal-control-cursor-movement.rexx new file mode 100644 index 0000000000..76202316f6 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/REXX/terminal-control-cursor-movement.rexx @@ -0,0 +1,23 @@ +/*REXX pgm demonstrates how to achieve movement of the terminal cursor. */ + +parse value scrsize() with sd sw /*find the display screen size. */ +parse value cursor() with row col /*find where the cursor is now. */ + +colL=col-1; if colL==0 then colL=sw /*prepare to move cursor to left.*/ +call cursor row,colL /*move cursor to the left (wrap).*/ + +colR=col+1; if colR>sw then colL=1 /*prepare to move cursor to right*/ +call cursor row,colR /*move cursor to the right (wrap)*/ + +rowU=row-1; if rowU==0 then rowU=sd /*prepare to move cursor up. */ +call cursor rowU,col /*move cursor up (with wrap). */ + +rowD=row+1; if rowD>sd then rowD=1 /*prepare to move cursor down. */ +call cursor rowD,col /*move cursor down (with wrap). */ + +call cursor row,1 /*move cursor to beginning of row*/ +call cursor row,sw /*move cursor to end of row*/ +call cursor 1,1 /*move cursor to top left corner.*/ +call cursor sd,sw /*move cursor to bot right corner*/ + + /*stick a fork in it, we're done.*/ diff --git a/Task/Terminal-control-Cursor-movement/Tcl/terminal-control-cursor-movement.tcl b/Task/Terminal-control-Cursor-movement/Tcl/terminal-control-cursor-movement.tcl new file mode 100644 index 0000000000..f0f19faaf6 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Tcl/terminal-control-cursor-movement.tcl @@ -0,0 +1,18 @@ +# Simplification wrapper for when we're actually affecting the terminal +proc tput args { + exec tput {*}$args >@stdout <@stdin +} + +tput cub1; # one position to the left +tput cuf1; # one position to the right +tput cuu1; # up one line +tput cud1; # down one line +tput cr; # beginning of line +tput home; # top left corner + +# For line ends and bottom, we need to determine size of terminal +set width [exec tput cols] +set height [exec tput lines] + +tput hpa $width; # end of line +tput cpu $height $width; # bottom right corner diff --git a/Task/Terminal-control-Cursor-movement/UNIX-Shell/terminal-control-cursor-movement.sh b/Task/Terminal-control-Cursor-movement/UNIX-Shell/terminal-control-cursor-movement.sh new file mode 100644 index 0000000000..b86bf84648 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/UNIX-Shell/terminal-control-cursor-movement.sh @@ -0,0 +1,14 @@ +tput cub1 # one position to the left +tput cuf1 # one position to the right +tput cuu1 # up one line +tput cud1 # down one line +tput cr # beginning of line +tput home # top left corner + +# For line ends and bottom, we need to determine size +# of terminal +WIDTH=`tput cols` +HEIGHT=`tput lines` + +tput hpa $WIDTH # end of line +tput cup $HEIGHT $WIDTH # bottom right corner diff --git a/Task/Terminal-control-Cursor-movement/XPL0/terminal-control-cursor-movement.xpl0 b/Task/Terminal-control-Cursor-movement/XPL0/terminal-control-cursor-movement.xpl0 new file mode 100644 index 0000000000..791bdf8a17 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/XPL0/terminal-control-cursor-movement.xpl0 @@ -0,0 +1,25 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +int I, X, Y, W, H; +[Cursor(10, 13); \set cursor to arbitrary location on screen +I:= ChIn(1); \wait for keystroke (no echo to display) +ChOut(0, $08\BS\); \backspace moves one position right +I:= ChIn(1); +X:= Peek($40, $50); \get cursor location from BIOS data +Y:= Peek($40, $51); +Cursor(X+1, Y); \move one position right +I:= ChIn(1); +Cursor(X+1, Y-1); \move up one line +I:= ChIn(1); +ChOut(0, $0A\LF\); \line feed moves down one line +I:= ChIn(1); +ChOut(0, $0D\CR\); \carriage return moves to beginning of current line +I:= ChIn(1); +W:= Peek($40, $4A); \get width of display (standard = 80; mine = 94) +Cursor(W-1, Y); \move to end of current line +I:= ChIn(1); +Cursor(0, 0); \move to top left corner +I:= ChIn(1); +H:= Peek($40, $84) + 1; \get height of display (standard = 25; mine = 50) +Cursor(W-1, H-1); \move to bottom right corner +I:= ChIn(1); +] diff --git a/Task/Terminal-control-Cursor-movement/ZX-Spectrum-Basic/terminal-control-cursor-movement.zx b/Task/Terminal-control-Cursor-movement/ZX-Spectrum-Basic/terminal-control-cursor-movement.zx new file mode 100644 index 0000000000..3cee600423 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/ZX-Spectrum-Basic/terminal-control-cursor-movement.zx @@ -0,0 +1,27 @@ +10 PRINT CHR$(8);:REM cursor one position left +20 PRINT CHR$(9);:REM cursor one position right +30 GO SUB 500: REM get cursor position +40 IF cr>0 THEN LET cr=cr-1: GO SUB 550: REM cursor up one line +50 IF cr<22 THEN LET cr=cr+1: GO SUB 550: REM cursor down one line +60 POKE 23688,33: REM cursor to beginning of the line +70 POKE 23688,0: REM cursor to end of line +80 POKE 23688,33:POKE 23689,24: REM cursor to top left +90 REM bottom two rows are reserved for input and errors +100 REM so we reserve those lines here +110 POKE 23688,0: POKE 23689,2: REM bottom right + +499 STOP: REM do not overrun into subroutines + +500 REM get cursor position +510 LET cc=33-PEEK 23688:REM current column +520 LET cr=24-PEEK 23689:REM current row +530 RETURN + +550 REM set cursor position +560 PRINT AT cr,cc; +570 RETURN + +600 REM alternative set cursor position +610 POKE 23688,33-cc +620 POKE 23689,24-cr +630 RETURN diff --git a/Task/Terminal-control-Cursor-positioning/0DESCRIPTION b/Task/Terminal-control-Cursor-positioning/0DESCRIPTION new file mode 100644 index 0000000000..cf37713d11 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/0DESCRIPTION @@ -0,0 +1,2 @@ +Move the cursor to column 3, row 6 and display the word "Hello", so that the letter H is in column 3 on row 6. +[[Terminal Control::task| ]] diff --git a/Task/Terminal-control-Cursor-positioning/1META.yaml b/Task/Terminal-control-Cursor-positioning/1META.yaml new file mode 100644 index 0000000000..9c15565476 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Terminal control diff --git a/Task/Terminal-control-Cursor-positioning/Ada/terminal-control-cursor-positioning.ada b/Task/Terminal-control-Cursor-positioning/Ada/terminal-control-cursor-positioning.ada new file mode 100644 index 0000000000..0597a020d0 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Ada/terminal-control-cursor-positioning.ada @@ -0,0 +1,9 @@ +with Ada.Text_IO; + +procedure Cursor_Pos is + +begin + Ada.Text_IO.Set_Line(6); + Ada.Text_IO.Set_Col(3); + Ada.Text_IO.Put("Hello"); +end Cursor_Pos; diff --git a/Task/Terminal-control-Cursor-positioning/AutoHotkey/terminal-control-cursor-positioning.ahk b/Task/Terminal-control-Cursor-positioning/AutoHotkey/terminal-control-cursor-positioning.ahk new file mode 100644 index 0000000000..a6f5807c35 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/AutoHotkey/terminal-control-cursor-positioning.ahk @@ -0,0 +1,15 @@ +DllCall( "AllocConsole" ) ; create a console if not launched from one +hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) + +DllCall("SetConsoleCursorPosition", UPtr, hConsole, UInt, (6 << 16) | 3) +WriteConsole(hConsole, "Hello") + +MsgBox + +WriteConsole(hConsole, text){ + VarSetCapacity(out, 16) + If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text) + , UPtrP, out, uint, 0 ) + return out + return 0 +} diff --git a/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-1.basic b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-1.basic new file mode 100644 index 0000000000..bf7629821e --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-1.basic @@ -0,0 +1,2 @@ + 10 VTAB 6: HTAB 3 + 20 PRINT "HELLO" diff --git a/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-2.basic b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-2.basic new file mode 100644 index 0000000000..71ec0aeccb --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-2.basic @@ -0,0 +1,2 @@ + 10 LOCATE 3,6 + 20 PRINT "Hello" diff --git a/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-3.basic b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-3.basic new file mode 100644 index 0000000000..e1639915d0 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/BASIC/terminal-control-cursor-positioning-3.basic @@ -0,0 +1,3 @@ + 10 REM The top left corner is at position 0,0 + 20 REM So we subtract one from the coordinates + 30 PRINT AT 5,2 "Hello" diff --git a/Task/Terminal-control-Cursor-positioning/BBC-BASIC/terminal-control-cursor-positioning.bbc b/Task/Terminal-control-Cursor-positioning/BBC-BASIC/terminal-control-cursor-positioning.bbc new file mode 100644 index 0000000000..b9a3a5baa1 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/BBC-BASIC/terminal-control-cursor-positioning.bbc @@ -0,0 +1 @@ +PRINT TAB(2,5);"Hello" diff --git a/Task/Terminal-control-Cursor-positioning/Blast/terminal-control-cursor-positioning.blast b/Task/Terminal-control-Cursor-positioning/Blast/terminal-control-cursor-positioning.blast new file mode 100644 index 0000000000..d50a20c76f --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Blast/terminal-control-cursor-positioning.blast @@ -0,0 +1,6 @@ +# This will display a message at a specific position on the terminal screen +.begin +cursor 6,3 +display "Hello!" +return +# This is the end of the script diff --git a/Task/Terminal-control-Cursor-positioning/C/terminal-control-cursor-positioning.c b/Task/Terminal-control-Cursor-positioning/C/terminal-control-cursor-positioning.c new file mode 100644 index 0000000000..7f79697022 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/C/terminal-control-cursor-positioning.c @@ -0,0 +1,6 @@ +#include +int main() +{ + printf("\033[6;3HHello\n"); + return 0; +} diff --git a/Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.euphoria b/Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.euphoria new file mode 100644 index 0000000000..63f97d9a9e --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.euphoria @@ -0,0 +1,2 @@ +position(6,3) +puts(1,"Hello") diff --git a/Task/Terminal-control-Cursor-positioning/Forth/terminal-control-cursor-positioning.fth b/Task/Terminal-control-Cursor-positioning/Forth/terminal-control-cursor-positioning.fth new file mode 100644 index 0000000000..65f8b9401b --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Forth/terminal-control-cursor-positioning.fth @@ -0,0 +1 @@ +2 5 at-xy ." Hello" diff --git a/Task/Terminal-control-Cursor-positioning/J/terminal-control-cursor-positioning.j b/Task/Terminal-control-Cursor-positioning/J/terminal-control-cursor-positioning.j new file mode 100644 index 0000000000..8aa27cd9d9 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/J/terminal-control-cursor-positioning.j @@ -0,0 +1 @@ +'Hello',~move 6 3 diff --git a/Task/Terminal-control-Cursor-positioning/Liberty-BASIC/terminal-control-cursor-positioning.liberty b/Task/Terminal-control-Cursor-positioning/Liberty-BASIC/terminal-control-cursor-positioning.liberty new file mode 100644 index 0000000000..9c8cc06bff --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Liberty-BASIC/terminal-control-cursor-positioning.liberty @@ -0,0 +1,2 @@ +locate 3, 6 +print "Hello" diff --git a/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-1.logo b/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-1.logo new file mode 100644 index 0000000000..1c9a194f50 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-1.logo @@ -0,0 +1,2 @@ +setcursor [2 5] +type "Hello diff --git a/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-2.logo b/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-2.logo new file mode 100644 index 0000000000..0a09bb7daa --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Logo/terminal-control-cursor-positioning-2.logo @@ -0,0 +1,3 @@ +setpos [20 50] +setxy 20 30 ; alternate way to set position +label "Hello diff --git a/Task/Terminal-control-Cursor-positioning/Mathematica/terminal-control-cursor-positioning.math b/Task/Terminal-control-Cursor-positioning/Mathematica/terminal-control-cursor-positioning.math new file mode 100644 index 0000000000..5c78462e86 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Mathematica/terminal-control-cursor-positioning.math @@ -0,0 +1,2 @@ +Run["tput cup 6 3"] +Print["Hello"] diff --git a/Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ocaml b/Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ocaml new file mode 100644 index 0000000000..66559c66df --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ocaml @@ -0,0 +1,11 @@ +#load "unix.cma" +#directory "+ANSITerminal" +#load "ANSITerminal.cma" + +module Trm = ANSITerminal + +let () = + Trm.erase Trm.Screen; + Trm.set_cursor 3 6; + Trm.print_string [] "Hello"; +;; diff --git a/Task/Terminal-control-Cursor-positioning/Pascal/terminal-control-cursor-positioning.pascal b/Task/Terminal-control-Cursor-positioning/Pascal/terminal-control-cursor-positioning.pascal new file mode 100644 index 0000000000..915463b5d4 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Pascal/terminal-control-cursor-positioning.pascal @@ -0,0 +1,6 @@ +program cursor_pos; +uses crt; +begin + gotoxy(6,3); + write('Hello'); +end. diff --git a/Task/Terminal-control-Cursor-positioning/Perl-6/terminal-control-cursor-positioning.pl6 b/Task/Terminal-control-Cursor-positioning/Perl-6/terminal-control-cursor-positioning.pl6 new file mode 100644 index 0000000000..285468884c --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Perl-6/terminal-control-cursor-positioning.pl6 @@ -0,0 +1,2 @@ +print "\e[6;3H"; +print 'Hello'; diff --git a/Task/Terminal-control-Cursor-positioning/PicoLisp/terminal-control-cursor-positioning.l b/Task/Terminal-control-Cursor-positioning/PicoLisp/terminal-control-cursor-positioning.l new file mode 100644 index 0000000000..0a5423faab --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/PicoLisp/terminal-control-cursor-positioning.l @@ -0,0 +1,2 @@ +(call 'tput "cup" 6 3) +(prin "Hello") diff --git a/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-1.psh b/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-1.psh new file mode 100644 index 0000000000..6634d24e95 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-1.psh @@ -0,0 +1,2 @@ +$Host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates 2,5 +$Host.UI.Write('Hello') diff --git a/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-2.psh b/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-2.psh new file mode 100644 index 0000000000..817bb9e6b5 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-2.psh @@ -0,0 +1,2 @@ +[Console]::SetCursorPosition(2,5) +[Console]::Write('Hello') diff --git a/Task/Terminal-control-Cursor-positioning/PureBasic/terminal-control-cursor-positioning.purebasic b/Task/Terminal-control-Cursor-positioning/PureBasic/terminal-control-cursor-positioning.purebasic new file mode 100644 index 0000000000..2c5dfa15e9 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/PureBasic/terminal-control-cursor-positioning.purebasic @@ -0,0 +1,3 @@ +EnableGraphicalConsole(#True) +ConsoleLocate(3,6) +Print("Hello") diff --git a/Task/Terminal-control-Cursor-positioning/Python/terminal-control-cursor-positioning.py b/Task/Terminal-control-Cursor-positioning/Python/terminal-control-cursor-positioning.py new file mode 100644 index 0000000000..b7247af0be --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Python/terminal-control-cursor-positioning.py @@ -0,0 +1 @@ +print("\033[6;3HHello") diff --git a/Task/Terminal-control-Cursor-positioning/REXX/terminal-control-cursor-positioning.rexx b/Task/Terminal-control-Cursor-positioning/REXX/terminal-control-cursor-positioning.rexx new file mode 100644 index 0000000000..760ba5e03e --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/REXX/terminal-control-cursor-positioning.rexx @@ -0,0 +1,8 @@ +/*REXX program demonstrates cursor position and writing of text to same.*/ + +call cursor 3,6 /*move the cursor to row 3, col 6*/ +say 'Hello' /*write the text at that location*/ + +call scrwrite 30,50,'Hello.' /*another method. */ + +call scrwrite 40,60,'Hello.',,,14 /*another ... in yellow.*/ diff --git a/Task/Terminal-control-Cursor-positioning/Retro/terminal-control-cursor-positioning.retro b/Task/Terminal-control-Cursor-positioning/Retro/terminal-control-cursor-positioning.retro new file mode 100644 index 0000000000..1b956733bc --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Retro/terminal-control-cursor-positioning.retro @@ -0,0 +1,2 @@ +with console' +: hello 3 6 at-xy "Hello" puts ; diff --git a/Task/Terminal-control-Cursor-positioning/Ruby/terminal-control-cursor-positioning.rb b/Task/Terminal-control-Cursor-positioning/Ruby/terminal-control-cursor-positioning.rb new file mode 100644 index 0000000000..26fb5f0c89 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Ruby/terminal-control-cursor-positioning.rb @@ -0,0 +1,11 @@ +require 'curses' + +Curses.init_screen +begin + Curses.setpos(6, 3) # column 6, row 3 + Curses.addstr("Hello") + + Curses.getch # Wait until user presses some key. +ensure + Curses.close_screen +end diff --git a/Task/Terminal-control-Cursor-positioning/Seed7/terminal-control-cursor-positioning.seed7 b/Task/Terminal-control-Cursor-positioning/Seed7/terminal-control-cursor-positioning.seed7 new file mode 100644 index 0000000000..faab77696a --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Seed7/terminal-control-cursor-positioning.seed7 @@ -0,0 +1,15 @@ +$ include "seed7_05.s7i"; + include "console.s7i"; + +const proc: main is func + local + var text: console is STD_NULL; + begin + console := open(CONSOLE); + setPos(console, 6, 3); + write(console, "Hello"); + # Terminal windows often restore the previous + # content, when a program is terminated. Therefore + # the program waits until Return/Enter is pressed. + readln; + end func; diff --git a/Task/Terminal-control-Cursor-positioning/Tcl/terminal-control-cursor-positioning.tcl b/Task/Terminal-control-Cursor-positioning/Tcl/terminal-control-cursor-positioning.tcl new file mode 100644 index 0000000000..8d4154d145 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Tcl/terminal-control-cursor-positioning.tcl @@ -0,0 +1,2 @@ +exec tput cup 5 2 >/dev/tty +puts "Hello" diff --git a/Task/Terminal-control-Cursor-positioning/UNIX-Shell/terminal-control-cursor-positioning.sh b/Task/Terminal-control-Cursor-positioning/UNIX-Shell/terminal-control-cursor-positioning.sh new file mode 100644 index 0000000000..fe59ae8e29 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/UNIX-Shell/terminal-control-cursor-positioning.sh @@ -0,0 +1,3 @@ +# The tput utility numbers from zero, so we have subtracted 1 from row and column +# number to obtain correct positioning. +tput cup 5 2 diff --git a/Task/Terminal-control-Cursor-positioning/XPL0/terminal-control-cursor-positioning.xpl0 b/Task/Terminal-control-Cursor-positioning/XPL0/terminal-control-cursor-positioning.xpl0 new file mode 100644 index 0000000000..d5e805ec46 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/XPL0/terminal-control-cursor-positioning.xpl0 @@ -0,0 +1,5 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +[Cursor(2, 5); \3rd column, 6th row +Text(0, "Hello"); \upper-left corner is coordinate 0, 0 +] diff --git a/Task/Terminal-control-Dimensions/0DESCRIPTION b/Task/Terminal-control-Dimensions/0DESCRIPTION new file mode 100644 index 0000000000..41db81ed2b --- /dev/null +++ b/Task/Terminal-control-Dimensions/0DESCRIPTION @@ -0,0 +1,2 @@ +Determine the height and width of the terminal, and store this information into variables for subsequent use. +[[Terminal Control::task| ]] diff --git a/Task/Terminal-control-Dimensions/1META.yaml b/Task/Terminal-control-Dimensions/1META.yaml new file mode 100644 index 0000000000..181b40ba75 --- /dev/null +++ b/Task/Terminal-control-Dimensions/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Initialization +note: Terminal control diff --git a/Task/Terminal-control-Dimensions/AutoHotkey/terminal-control-dimensions.ahk b/Task/Terminal-control-Dimensions/AutoHotkey/terminal-control-dimensions.ahk new file mode 100644 index 0000000000..9f6fde8059 --- /dev/null +++ b/Task/Terminal-control-Dimensions/AutoHotkey/terminal-control-dimensions.ahk @@ -0,0 +1,15 @@ +DllCall( "AllocConsole" ) ; create a console if not launched from one +hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) + +MsgBox Resize the console... + +VarSetCapacity(csbi, 22) ; CONSOLE_SCREEN_BUFFER_INFO structure +DllCall("GetConsoleScreenBufferInfo", UPtr, hConsole, UPtr, &csbi) +Left := NumGet(csbi, 10, "short") +Top := NumGet(csbi, 12, "short") +Right := NumGet(csbi, 14, "short") +Bottom := NumGet(csbi, 16, "short") + +columns := right - left + 1 +rows := bottom - top + 1 +MsgBox %columns% columns and %rows% rows diff --git a/Task/Terminal-control-Dimensions/BBC-BASIC/terminal-control-dimensions.bbc b/Task/Terminal-control-Dimensions/BBC-BASIC/terminal-control-dimensions.bbc new file mode 100644 index 0000000000..9335504436 --- /dev/null +++ b/Task/Terminal-control-Dimensions/BBC-BASIC/terminal-control-dimensions.bbc @@ -0,0 +1,2 @@ + dx% = @vdu.tr%-@vdu.tl% : REM Width of text viewport in pixels + dy% = @vdu.tb%-@vdu.tt% : REM Height of text viewport in pixels diff --git a/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-1.c b/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-1.c new file mode 100644 index 0000000000..463bad027d --- /dev/null +++ b/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-1.c @@ -0,0 +1,27 @@ +#include /* ioctl, TIOCGWINSZ */ +#include /* err */ +#include /* open */ +#include /* printf */ +#include /* close */ + +int +main() +{ + struct winsize ws; + int fd; + + /* Open the controlling terminal. */ + fd = open("/dev/tty", O_RDWR); + if (fd < 0) + err(1, "/dev/tty"); + + /* Get window size of terminal. */ + if (ioctl(fd, TIOCGWINSZ, &ws) < 0) + err(1, "/dev/tty"); + + printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col); + printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel); + + close(fd); + return 0; +} diff --git a/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-2.c b/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-2.c new file mode 100644 index 0000000000..f744148f50 --- /dev/null +++ b/Task/Terminal-control-Dimensions/C/terminal-control-dimensions-2.c @@ -0,0 +1,28 @@ +#include +#include + +int +main() +{ + HANDLE console; + CONSOLE_SCREEN_BUFFER_INFO info; + short rows; + short columns; + /* Create a handle to the console screen. */ + console = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + 0, NULL); + if (console == INVALID_HANDLE_VALUE) + return 1; + + /* Calculate the size of the console window. */ + if (GetConsoleScreenBufferInfo(console, &info) == 0) + return 1; + CloseHandle(console); + columns = info.srWindow.Right - info.srWindow.Left + 1; + rows = info.srWindow.Bottom - info.srWindow.Top + 1; + + wprintf(L"%d columns by %d rows\n", columns, rows); + + return 0; +} diff --git a/Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.euphoria b/Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.euphoria new file mode 100644 index 0000000000..11295681d5 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.euphoria @@ -0,0 +1,12 @@ +include graphics.e + +sequence vc +integer term_height, term_width + +vc = video_config() + +term_height = vc[VC_LINES] +term_width = vc[VC_COLUMNS] + +printf(1,"Terminal height is %d\n",term_height) +printf(1,"Terminal width is %d\n",term_width) diff --git a/Task/Terminal-control-Dimensions/Forth/terminal-control-dimensions.fth b/Task/Terminal-control-Dimensions/Forth/terminal-control-dimensions.fth new file mode 100644 index 0000000000..73ec3c1184 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Forth/terminal-control-dimensions.fth @@ -0,0 +1,9 @@ +variable term-width +variable term-height + +s" gforth" environment? [if] + 2drop form ( height width ) +[else] \ SwiftForth + get-size ( width height ) swap +[then] +term-width ! term-height ! diff --git a/Task/Terminal-control-Dimensions/J/terminal-control-dimensions.j b/Task/Terminal-control-Dimensions/J/terminal-control-dimensions.j new file mode 100644 index 0000000000..03891936e9 --- /dev/null +++ b/Task/Terminal-control-Dimensions/J/terminal-control-dimensions.j @@ -0,0 +1 @@ +_2 {.qsmsize_jijs_'' diff --git a/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-1.locomotive b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-1.locomotive new file mode 100644 index 0000000000..0ca7023ec9 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-1.locomotive @@ -0,0 +1,8 @@ +4000 d5 push de +4001 e5 push hl +4002 cd 69 bb call &bb69 +4005 ed 53 20 40 ld (&4020),de +4009 22 22 40 ld (&4022),hl +400c e1 pop hl +400d d1 pop de +400e c9 ret diff --git a/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-2.locomotive b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-2.locomotive new file mode 100644 index 0000000000..524e68b9cc --- /dev/null +++ b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-2.locomotive @@ -0,0 +1,7 @@ +10 s=&4000:SYMBOL AFTER 256:MEMORY s-1 +20 FOR i=0 to 14:READ a:POKE s+i,a:NEXT +30 DATA &d5,&e5,&cd,&69,&bb,&ed,&53,&20,&40,&22,&22,&40,&e1,&d1,&c9 +40 CALL s +50 h=PEEK(&4020)-PEEK(&4022)+1 +60 w=PEEK(&4021)-PEEK(&4023)+1 +70 PRINT "window width:"; w; ", height:"; h diff --git a/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-3.locomotive b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-3.locomotive new file mode 100644 index 0000000000..f2c5761e1e --- /dev/null +++ b/Task/Terminal-control-Dimensions/Locomotive-Basic/terminal-control-dimensions-3.locomotive @@ -0,0 +1,3 @@ +10 w%=0:h%=0 ' initialize and force integer type +20 |getwh,@w%,@h% ' call RSX and pass variables as pointers +30 PRINT "window width:"; w%; ", height:"; h% diff --git a/Task/Terminal-control-Dimensions/Mathematica/terminal-control-dimensions.math b/Task/Terminal-control-Dimensions/Mathematica/terminal-control-dimensions.math new file mode 100644 index 0000000000..b292babdce --- /dev/null +++ b/Task/Terminal-control-Dimensions/Mathematica/terminal-control-dimensions.math @@ -0,0 +1,2 @@ +WIDTH=RunThrough["tput cols", ""]; +HEIGHT=RunThrough["tput lines", ""]; diff --git a/Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ocaml b/Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ocaml new file mode 100644 index 0000000000..2fc480ca53 --- /dev/null +++ b/Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ocaml @@ -0,0 +1,5 @@ +$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma + +# let width, height = ANSITerminal.size () ;; +val width : int = 126 +val height : int = 47 diff --git a/Task/Terminal-control-Dimensions/Perl-6/terminal-control-dimensions.pl6 b/Task/Terminal-control-Dimensions/Perl-6/terminal-control-dimensions.pl6 new file mode 100644 index 0000000000..7e8ec7a683 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Perl-6/terminal-control-dimensions.pl6 @@ -0,0 +1,4 @@ +my $stty = qx[stty -a]; +my $lines = $stty.match(/ 'rows ' <( \d+/); +my $cols = $stty.match(/ 'columns ' <( \d+/); +say "$lines $cols"; diff --git a/Task/Terminal-control-Dimensions/Perl/terminal-control-dimensions.pl b/Task/Terminal-control-Dimensions/Perl/terminal-control-dimensions.pl new file mode 100644 index 0000000000..e53656ec63 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Perl/terminal-control-dimensions.pl @@ -0,0 +1,4 @@ +use Term::Size; + +($cols, $rows) = Term::Size::chars; +print "The terminal has $cols columns and $rows lines\n"; diff --git a/Task/Terminal-control-Dimensions/PicoLisp/terminal-control-dimensions.l b/Task/Terminal-control-Dimensions/PicoLisp/terminal-control-dimensions.l new file mode 100644 index 0000000000..4352e3a6e9 --- /dev/null +++ b/Task/Terminal-control-Dimensions/PicoLisp/terminal-control-dimensions.l @@ -0,0 +1,3 @@ +(setq + Width (in '(tput cols) (read)) + Height (in '(tput lines) (read)) ) diff --git a/Task/Terminal-control-Dimensions/PureBasic/terminal-control-dimensions.purebasic b/Task/Terminal-control-Dimensions/PureBasic/terminal-control-dimensions.purebasic new file mode 100644 index 0000000000..fcef13d946 --- /dev/null +++ b/Task/Terminal-control-Dimensions/PureBasic/terminal-control-dimensions.purebasic @@ -0,0 +1,25 @@ +Macro ConsoleHandle() + GetStdHandle_( #STD_OUTPUT_HANDLE ) +EndMacro + +Procedure ConsoleWidth() + Protected CBI.CONSOLE_SCREEN_BUFFER_INFO + Protected hConsole = ConsoleHandle() + GetConsoleScreenBufferInfo_( hConsole, @CBI ) + ProcedureReturn CBI\srWindow\right - CBI\srWindow\left + 1 +EndProcedure + +Procedure ConsoleHeight() + Protected CBI.CONSOLE_SCREEN_BUFFER_INFO + Protected hConsole = ConsoleHandle() + GetConsoleScreenBufferInfo_( hConsole, @CBI ) + ProcedureReturn CBI\srWindow\bottom - CBI\srWindow\top + 1 +EndProcedure + +If OpenConsole() + x$=Str(ConsoleWidth()) + y$=Str(ConsoleHeight()) + PrintN("This window is "+x$+"x"+y$+ " chars.") + ; + Print(#CRLF$+"Press ENTER to exit"):Input() +EndIf diff --git a/Task/Terminal-control-Dimensions/Python/terminal-control-dimensions.py b/Task/Terminal-control-Dimensions/Python/terminal-control-dimensions.py new file mode 100644 index 0000000000..ba99dd8135 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Python/terminal-control-dimensions.py @@ -0,0 +1,26 @@ +import os + +def get_windows_terminal(): + from ctypes import windll, create_string_buffer + h = windll.kernel32.GetStdHandle(-12) + csbi = create_string_buffer(22) + res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) + + #return default size if actual size can't be determined + if not res: return 80, 25 + + import struct + (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\ + = struct.unpack("hhhhHhhhhhh", csbi.raw) + width = right - left + 1 + height = bottom - top + 1 + + return width, height + +def get_linux_terminal(): + width = os.popen('tput cols', 'r').readline() + height = os.popen('tput lines', 'r').readline() + + return int(width), int(height) + +print get_linux_terminal() if os.name == 'posix' else get_windows_terminal() diff --git a/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-1.rexx b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-1.rexx new file mode 100644 index 0000000000..3dfaf23549 --- /dev/null +++ b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-1.rexx @@ -0,0 +1,5 @@ +width = 'tput'( 'cols' ) +height = 'tput'( 'lines' ) + +say 'The terminal is' width 'characters wide' +say 'and has' height 'lines' diff --git a/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-2.rexx b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-2.rexx new file mode 100644 index 0000000000..5d3ff272de --- /dev/null +++ b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-2.rexx @@ -0,0 +1 @@ +width=linesize() diff --git a/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-3.rexx b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-3.rexx new file mode 100644 index 0000000000..fb08d59b0c --- /dev/null +++ b/Task/Terminal-control-Dimensions/REXX/terminal-control-dimensions-3.rexx @@ -0,0 +1 @@ + parse value scrsize() with sd sw diff --git a/Task/Terminal-control-Dimensions/Retro/terminal-control-dimensions.retro b/Task/Terminal-control-Dimensions/Retro/terminal-control-dimensions.retro new file mode 100644 index 0000000000..b5d104b0fb --- /dev/null +++ b/Task/Terminal-control-Dimensions/Retro/terminal-control-dimensions.retro @@ -0,0 +1,2 @@ +-3 5 out wait 5 in !cw +-4 5 out wait 5 in !ch diff --git a/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-1.rb b/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-1.rb new file mode 100644 index 0000000000..8c0a673398 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-1.rb @@ -0,0 +1,12 @@ +def winsize + # Ruby 1.9.3 added 'io/console' to the standard library. + require 'io/console' + IO.console.winsize +rescue LoadError + # This works with older Ruby, but only with systems + # that have a tput(1) command, such as Unix clones. + [Integer(`tput li`), Integer(`tput co`)] +end + +rows, cols = winsize +printf "%d rows by %d columns\n", rows, cols diff --git a/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-2.rb b/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-2.rb new file mode 100644 index 0000000000..a41d55d59d --- /dev/null +++ b/Task/Terminal-control-Dimensions/Ruby/terminal-control-dimensions-2.rb @@ -0,0 +1,13 @@ +require 'curses' + +begin + Curses.init_screen + + r, c = Curses.lines, Curses.cols + + Curses.setpos r / 2, 0 + Curses.addstr "#{r} rows by #{c} columns".center(c) + Curses.getch +ensure + Curses.close_screen +end diff --git a/Task/Terminal-control-Dimensions/Seed7/terminal-control-dimensions.seed7 b/Task/Terminal-control-Dimensions/Seed7/terminal-control-dimensions.seed7 new file mode 100644 index 0000000000..27d9e570a2 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Seed7/terminal-control-dimensions.seed7 @@ -0,0 +1,15 @@ +$ include "seed7_05.s7i"; + include "console.s7i"; + +const proc: main is func + local + var text: console is STD_NULL; + begin + console := open(CONSOLE); + writeln(console, "height: " <& height(console) lpad 3); + writeln(console, "width: " <& width(console) lpad 3); + # Terminal windows often restore the previous + # content, when a program is terminated. Therefore + # the program waits until Return/Enter is pressed. + readln; + end func; diff --git a/Task/Terminal-control-Dimensions/Tcl/terminal-control-dimensions.tcl b/Task/Terminal-control-Dimensions/Tcl/terminal-control-dimensions.tcl new file mode 100644 index 0000000000..93e0d6f2f7 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Tcl/terminal-control-dimensions.tcl @@ -0,0 +1,3 @@ +set width [exec tput cols] +set height [exec tput lines] +puts "The terminal is $width characters wide and has $height lines" diff --git a/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-1.sh b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-1.sh new file mode 100644 index 0000000000..173eb9d23d --- /dev/null +++ b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-1.sh @@ -0,0 +1,4 @@ +#!/bin/sh +WIDTH=`tput cols` +HEIGHT=`tput lines` +echo "The terminal is $WIDTH characters wide and has $HEIGHT lines." diff --git a/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-2.sh b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-2.sh new file mode 100644 index 0000000000..167e838f2f --- /dev/null +++ b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-2.sh @@ -0,0 +1,4 @@ +#!/bin/sh +WIDTH=`tput co` +HEIGHT=`tput li` +echo "The terminal is $WIDTH characters wide and has $HEIGHT lines." diff --git a/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-3.sh b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-3.sh new file mode 100644 index 0000000000..160368828f --- /dev/null +++ b/Task/Terminal-control-Dimensions/UNIX-Shell/terminal-control-dimensions-3.sh @@ -0,0 +1,4 @@ +#!/bin/csh -f +set WIDTH=`tput cols` +set HEIGHT=`tput lines` +echo "The terminal is $WIDTH characters wide and has $HEIGHT lines." diff --git a/Task/Terminal-control-Dimensions/XPL0/terminal-control-dimensions.xpl0 b/Task/Terminal-control-Dimensions/XPL0/terminal-control-dimensions.xpl0 new file mode 100644 index 0000000000..d648681033 --- /dev/null +++ b/Task/Terminal-control-Dimensions/XPL0/terminal-control-dimensions.xpl0 @@ -0,0 +1,7 @@ +include c:\cxpl\codes; +int W, H; +[W:= Peek($40, $4A); \IBM-PC BIOS data + H:= Peek($40, $84) + 1; +Text(0, "Terminal width and height = "); +IntOut(0, W); ChOut(0, ^x); IntOut(0, H); +] diff --git a/Task/Terminal-control-Display-an-extended-character/0DESCRIPTION b/Task/Terminal-control-Display-an-extended-character/0DESCRIPTION new file mode 100644 index 0000000000..71c5339d81 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/0DESCRIPTION @@ -0,0 +1 @@ +The task is to display an extended (non ASCII) character onto the terminal. For this task, we will display a £ (GBP currency sign). diff --git a/Task/Terminal-control-Display-an-extended-character/1META.yaml b/Task/Terminal-control-Display-an-extended-character/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/Terminal-control-Display-an-extended-character/ACL2/terminal-control-display-an-extended-character.acl2 b/Task/Terminal-control-Display-an-extended-character/ACL2/terminal-control-display-an-extended-character.acl2 new file mode 100644 index 0000000000..4ad4a2f787 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/ACL2/terminal-control-display-an-extended-character.acl2 @@ -0,0 +1 @@ +(cw "£") diff --git a/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-1.awk b/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-1.awk new file mode 100644 index 0000000000..017a7f49a6 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-1.awk @@ -0,0 +1 @@ +BEGIN { print "£" } diff --git a/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-2.awk b/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-2.awk new file mode 100644 index 0000000000..2630c67832 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/AWK/terminal-control-display-an-extended-character-2.awk @@ -0,0 +1 @@ +BEGIN { print "\302\243" } # if your terminal is utf-8 diff --git a/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-1.ada b/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-1.ada new file mode 100644 index 0000000000..eafad443f4 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-1.ada @@ -0,0 +1,7 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Characters.Latin_1; + +procedure Pound is +begin + Put(Ada.Characters.Latin_1.Pound_Sign); +end Pound; diff --git a/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-2.ada b/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-2.ada new file mode 100644 index 0000000000..fc3553075c --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-2.ada @@ -0,0 +1,6 @@ +with Ada.Wide_Text_IO; use Ada.Wide_Text_IO; + +procedure Unicode is +begin + Put("札幌"); +end Unicode; diff --git a/Task/Terminal-control-Display-an-extended-character/BASIC/terminal-control-display-an-extended-character.basic b/Task/Terminal-control-Display-an-extended-character/BASIC/terminal-control-display-an-extended-character.basic new file mode 100644 index 0000000000..b0e30bd3bf --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/BASIC/terminal-control-display-an-extended-character.basic @@ -0,0 +1 @@ +10 PRINT CHR$(96); diff --git a/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-1.bbc b/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-1.bbc new file mode 100644 index 0000000000..561513e8ed --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-1.bbc @@ -0,0 +1 @@ + PRINT "£" diff --git a/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-2.bbc b/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-2.bbc new file mode 100644 index 0000000000..444f7d2bc4 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/BBC-BASIC/terminal-control-display-an-extended-character-2.bbc @@ -0,0 +1,2 @@ + VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 mode + PRINT CHR$(&C2) CHR$(&A3) : REM UTF-8 encoding for £ diff --git a/Task/Terminal-control-Display-an-extended-character/C++/terminal-control-display-an-extended-character.cpp b/Task/Terminal-control-Display-an-extended-character/C++/terminal-control-display-an-extended-character.cpp new file mode 100644 index 0000000000..90dd451a75 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/C++/terminal-control-display-an-extended-character.cpp @@ -0,0 +1,7 @@ +#include + +int main() +{ + std::cout << static_cast(163); // pound sign + return 0; +} diff --git a/Task/Terminal-control-Display-an-extended-character/C-sharp/terminal-control-display-an-extended-character.cs b/Task/Terminal-control-Display-an-extended-character/C-sharp/terminal-control-display-an-extended-character.cs new file mode 100644 index 0000000000..4c787c772f --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/C-sharp/terminal-control-display-an-extended-character.cs @@ -0,0 +1,7 @@ +class Program +{ + static void Main() + { + System.Console.WriteLine("£"); + } +} diff --git a/Task/Terminal-control-Display-an-extended-character/C/terminal-control-display-an-extended-character.c b/Task/Terminal-control-Display-an-extended-character/C/terminal-control-display-an-extended-character.c new file mode 100644 index 0000000000..e2cb1386c6 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/C/terminal-control-display-an-extended-character.c @@ -0,0 +1,9 @@ +#include + +int +main() +{ + puts("£"); + puts("\302\243"); /* if your terminal is utf-8 */ + return 0; +} diff --git a/Task/Terminal-control-Display-an-extended-character/D/terminal-control-display-an-extended-character.d b/Task/Terminal-control-Display-an-extended-character/D/terminal-control-display-an-extended-character.d new file mode 100644 index 0000000000..ac74128704 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/D/terminal-control-display-an-extended-character.d @@ -0,0 +1,5 @@ +import std.stdio; + +void main() { + writeln('\u00A3'); +} diff --git a/Task/Terminal-control-Display-an-extended-character/Forth/terminal-control-display-an-extended-character.fth b/Task/Terminal-control-Display-an-extended-character/Forth/terminal-control-display-an-extended-character.fth new file mode 100644 index 0000000000..55c2b4ed9b --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Forth/terminal-control-display-an-extended-character.fth @@ -0,0 +1,2 @@ +163 xemit \ £, or +s" £" type diff --git a/Task/Terminal-control-Display-an-extended-character/Go/terminal-control-display-an-extended-character.go b/Task/Terminal-control-Display-an-extended-character/Go/terminal-control-display-an-extended-character.go new file mode 100644 index 0000000000..aa86105bf5 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Go/terminal-control-display-an-extended-character.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("£") +} diff --git a/Task/Terminal-control-Display-an-extended-character/Haskell/terminal-control-display-an-extended-character.hs b/Task/Terminal-control-Display-an-extended-character/Haskell/terminal-control-display-an-extended-character.hs new file mode 100644 index 0000000000..5c7fea1eda --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Haskell/terminal-control-display-an-extended-character.hs @@ -0,0 +1,4 @@ +module Main where +main = do + putStrLn "£" + putStrLn "札幌" diff --git a/Task/Terminal-control-Display-an-extended-character/Icon/terminal-control-display-an-extended-character.icon b/Task/Terminal-control-Display-an-extended-character/Icon/terminal-control-display-an-extended-character.icon new file mode 100644 index 0000000000..67ea212d02 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Icon/terminal-control-display-an-extended-character.icon @@ -0,0 +1,3 @@ +procedure main () + write ("£ " || char (163)) # £ +end diff --git a/Task/Terminal-control-Display-an-extended-character/J/terminal-control-display-an-extended-character.j b/Task/Terminal-control-Display-an-extended-character/J/terminal-control-display-an-extended-character.j new file mode 100644 index 0000000000..7399ef5de1 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/J/terminal-control-display-an-extended-character.j @@ -0,0 +1,4 @@ + '£' +£ + '札幌' +札幌 diff --git a/Task/Terminal-control-Display-an-extended-character/Java/terminal-control-display-an-extended-character.java b/Task/Terminal-control-Display-an-extended-character/Java/terminal-control-display-an-extended-character.java new file mode 100644 index 0000000000..7f275b2b05 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Java/terminal-control-display-an-extended-character.java @@ -0,0 +1,12 @@ +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; + +public class Main +{ + public static void main(String[] args) throws UnsupportedEncodingException + { + PrintStream writer = new PrintStream(System.out, true, "UTF-8"); + writer.println("£"); + writer.println("札幌"); + } +} diff --git a/Task/Terminal-control-Display-an-extended-character/Locomotive-Basic/terminal-control-display-an-extended-character.locomotive b/Task/Terminal-control-Display-an-extended-character/Locomotive-Basic/terminal-control-display-an-extended-character.locomotive new file mode 100644 index 0000000000..e62afed952 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Locomotive-Basic/terminal-control-display-an-extended-character.locomotive @@ -0,0 +1 @@ +10 PRINT CHR$(163) diff --git a/Task/Terminal-control-Display-an-extended-character/Mathematica/terminal-control-display-an-extended-character.math b/Task/Terminal-control-Display-an-extended-character/Mathematica/terminal-control-display-an-extended-character.math new file mode 100644 index 0000000000..f22adab42a --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Mathematica/terminal-control-display-an-extended-character.math @@ -0,0 +1 @@ +FromCharacterCode[{163}] diff --git a/Task/Terminal-control-Display-an-extended-character/PL-I/terminal-control-display-an-extended-character.pli b/Task/Terminal-control-Display-an-extended-character/PL-I/terminal-control-display-an-extended-character.pli new file mode 100644 index 0000000000..e39d8f4297 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/PL-I/terminal-control-display-an-extended-character.pli @@ -0,0 +1,2 @@ + declare pound character (1) static initial ('9c'x); + put skip list (pound); diff --git a/Task/Terminal-control-Display-an-extended-character/Pascal/terminal-control-display-an-extended-character.pascal b/Task/Terminal-control-Display-an-extended-character/Pascal/terminal-control-display-an-extended-character.pascal new file mode 100644 index 0000000000..78194aafa3 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Pascal/terminal-control-display-an-extended-character.pascal @@ -0,0 +1,5 @@ +program pound; +uses crt; +begin + write(chr( 163 )); +end. diff --git a/Task/Terminal-control-Display-an-extended-character/Perl-6/terminal-control-display-an-extended-character.pl6 b/Task/Terminal-control-Display-an-extended-character/Perl-6/terminal-control-display-an-extended-character.pl6 new file mode 100644 index 0000000000..74b35b4842 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Perl-6/terminal-control-display-an-extended-character.pl6 @@ -0,0 +1,4 @@ +say '£'; +say "\x[FFE1]"; +say "\c[FULLWIDTH POUND SIGN]"; +0xffe1.chr.say; diff --git a/Task/Terminal-control-Display-an-extended-character/PicoLisp/terminal-control-display-an-extended-character.l b/Task/Terminal-control-Display-an-extended-character/PicoLisp/terminal-control-display-an-extended-character.l new file mode 100644 index 0000000000..50f85cefd7 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/PicoLisp/terminal-control-display-an-extended-character.l @@ -0,0 +1 @@ +(prinl (char 26413) (char 24140)) # Sapporo diff --git a/Task/Terminal-control-Display-an-extended-character/PureBasic/terminal-control-display-an-extended-character.purebasic b/Task/Terminal-control-Display-an-extended-character/PureBasic/terminal-control-display-an-extended-character.purebasic new file mode 100644 index 0000000000..c631bc10eb --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/PureBasic/terminal-control-display-an-extended-character.purebasic @@ -0,0 +1 @@ +Print(Chr(163)) diff --git a/Task/Terminal-control-Display-an-extended-character/Python/terminal-control-display-an-extended-character.py b/Task/Terminal-control-Display-an-extended-character/Python/terminal-control-display-an-extended-character.py new file mode 100644 index 0000000000..fab149a08e --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Python/terminal-control-display-an-extended-character.py @@ -0,0 +1 @@ +print u'\u00a3' diff --git a/Task/Terminal-control-Display-an-extended-character/REXX/terminal-control-display-an-extended-character.rexx b/Task/Terminal-control-Display-an-extended-character/REXX/terminal-control-display-an-extended-character.rexx new file mode 100644 index 0000000000..e137128203 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/REXX/terminal-control-display-an-extended-character.rexx @@ -0,0 +1,3 @@ +/*REXX program to demonstrate displaying an extended character. */ + +say d2c(163) /*assuming the pound sign is 163 on the display codepage*/ diff --git a/Task/Terminal-control-Display-an-extended-character/Seed7/terminal-control-display-an-extended-character.seed7 b/Task/Terminal-control-Display-an-extended-character/Seed7/terminal-control-display-an-extended-character.seed7 new file mode 100644 index 0000000000..975776d042 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Seed7/terminal-control-display-an-extended-character.seed7 @@ -0,0 +1,14 @@ +$ include "seed7_05.s7i"; + include "console.s7i"; + +const proc: main is func + local + var text: console is STD_NULL; + begin + console := open(CONSOLE); + write(console, "£"); + # Terminal windows often restore the previous + # content, when a program is terminated. Therefore + # the program waits until Return/Enter is pressed. + readln; + end func; diff --git a/Task/Terminal-control-Display-an-extended-character/Tcl/terminal-control-display-an-extended-character.tcl b/Task/Terminal-control-Display-an-extended-character/Tcl/terminal-control-display-an-extended-character.tcl new file mode 100644 index 0000000000..3cb5e81546 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Tcl/terminal-control-display-an-extended-character.tcl @@ -0,0 +1 @@ +puts \u00a3 diff --git a/Task/Terminal-control-Display-an-extended-character/XPL0/terminal-control-display-an-extended-character.xpl0 b/Task/Terminal-control-Display-an-extended-character/XPL0/terminal-control-display-an-extended-character.xpl0 new file mode 100644 index 0000000000..a36c1cc7fe --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/XPL0/terminal-control-display-an-extended-character.xpl0 @@ -0,0 +1,2 @@ +code ChOut=8; +ChOut(0, $9C) \code for IBM PC's extended (OEM) character set diff --git a/Task/Terminal-control-Hiding-the-cursor/0DESCRIPTION b/Task/Terminal-control-Hiding-the-cursor/0DESCRIPTION new file mode 100644 index 0000000000..ae1d1296f4 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/0DESCRIPTION @@ -0,0 +1 @@ +The task is to hide the cursor and show it again. diff --git a/Task/Terminal-control-Hiding-the-cursor/1META.yaml b/Task/Terminal-control-Hiding-the-cursor/1META.yaml new file mode 100644 index 0000000000..d3f138f1fa --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Terminal control +note: Terminal control diff --git a/Task/Terminal-control-Hiding-the-cursor/AutoHotkey/terminal-control-hiding-the-cursor.ahk b/Task/Terminal-control-Hiding-the-cursor/AutoHotkey/terminal-control-hiding-the-cursor.ahk new file mode 100644 index 0000000000..cf6ba8d040 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/AutoHotkey/terminal-control-hiding-the-cursor.ahk @@ -0,0 +1,16 @@ +DllCall("AllocConsole") ; Create a console if not launched from one +hConsole := DllCall("GetStdHandle", UInt, STDOUT := -11) + +VarSetCapacity(cci, 8) ; CONSOLE_CURSOR_INFO structure +DllCall("GetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci) +NumPut(0, cci, 4) +DllCall("SetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci) + +FileAppend, Cursor hidden for 3 seconds..., CONOUT$ ; Prints to stdout +Sleep 3000 + +NumPut(1, cci, 4) +DllCall("SetConsoleCursorInfo", UPtr, hConsole, UPtr, &cci) + +FileAppend, `nCursor shown, CONOUT$ +MsgBox diff --git a/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor.basic b/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor.basic new file mode 100644 index 0000000000..9bc80b2daa --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/BASIC/terminal-control-hiding-the-cursor.basic @@ -0,0 +1,6 @@ +'hide the cursor: +LOCATE , , 0 +'wait for a keypress... +SLEEP +'show the cursor: +LOCATE , , 1 diff --git a/Task/Terminal-control-Hiding-the-cursor/BBC-BASIC/terminal-control-hiding-the-cursor.bbc b/Task/Terminal-control-Hiding-the-cursor/BBC-BASIC/terminal-control-hiding-the-cursor.bbc new file mode 100644 index 0000000000..cea626693b --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/BBC-BASIC/terminal-control-hiding-the-cursor.bbc @@ -0,0 +1,3 @@ + OFF : REM Hide the cursor (caret) + WAIT 400 + ON : REM Show the cursor again diff --git a/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c b/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c new file mode 100644 index 0000000000..71236ef49a --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/C/terminal-control-hiding-the-cursor.c @@ -0,0 +1,21 @@ +/*30th August,2012 +Abhishek Ghosh + +Please note that curs_set is terminal dependent.*/ + +#include +#include + +int +main () +{ + printf + ("At the end of this line you will see the cursor, process will sleep for 5 seconds."); + napms (5000); + curs_set (0); + printf + ("\nAt the end of this line you will NOT see the cursor, process will again sleep for 5 seconds."); + napms (5000); + printf ("\nGoodbye."); + return 0; +} diff --git a/Task/Terminal-control-Hiding-the-cursor/J/terminal-control-hiding-the-cursor.j b/Task/Terminal-control-Hiding-the-cursor/J/terminal-control-hiding-the-cursor.j new file mode 100644 index 0000000000..3c6c73d725 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/J/terminal-control-hiding-the-cursor.j @@ -0,0 +1,3 @@ +smoutput HIDECURSOR +usleep(4e6) NB. wait 4 seconds +smoutput SHOWCURSOR diff --git a/Task/Terminal-control-Hiding-the-cursor/Locomotive-Basic/terminal-control-hiding-the-cursor.locomotive b/Task/Terminal-control-Hiding-the-cursor/Locomotive-Basic/terminal-control-hiding-the-cursor.locomotive new file mode 100644 index 0000000000..1e555f03ed --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Locomotive-Basic/terminal-control-hiding-the-cursor.locomotive @@ -0,0 +1,4 @@ +10 CURSOR 0: REM hide cursor +20 FOR l = 1 TO 2000: REM delay +30 NEXT l +40 CURSOR 1: REM show cursor diff --git a/Task/Terminal-control-Hiding-the-cursor/Mathematica/terminal-control-hiding-the-cursor.math b/Task/Terminal-control-Hiding-the-cursor/Mathematica/terminal-control-hiding-the-cursor.math new file mode 100644 index 0000000000..f2e24366af --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Mathematica/terminal-control-hiding-the-cursor.math @@ -0,0 +1,3 @@ +Run["tput civis"] (* Cursor hidden *) +Pause[2] +Run["tput cvvis"] (* Cursor Visible *) diff --git a/Task/Terminal-control-Hiding-the-cursor/Perl-6/terminal-control-hiding-the-cursor.pl6 b/Task/Terminal-control-Hiding-the-cursor/Perl-6/terminal-control-hiding-the-cursor.pl6 new file mode 100644 index 0000000000..6b3c1771eb --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Perl-6/terminal-control-hiding-the-cursor.pl6 @@ -0,0 +1,3 @@ +run 'tput', 'civis'; +sleep 5; +run 'tput', 'cvvis'; diff --git a/Task/Terminal-control-Hiding-the-cursor/PicoLisp/terminal-control-hiding-the-cursor.l b/Task/Terminal-control-Hiding-the-cursor/PicoLisp/terminal-control-hiding-the-cursor.l new file mode 100644 index 0000000000..1e0a2d5b26 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/PicoLisp/terminal-control-hiding-the-cursor.l @@ -0,0 +1,3 @@ +(call "tput" "civis") # Invisible +(wait 1000) +(call "tput" "cvvis") # Visible diff --git a/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor.purebasic b/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor.purebasic new file mode 100644 index 0000000000..ac9824e325 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/PureBasic/terminal-control-hiding-the-cursor.purebasic @@ -0,0 +1,14 @@ +#cursorSize = 10 ;use a full sized cursor + +If OpenConsole() + Print("Press any key to toggle cursor: ") + EnableGraphicalConsole(1) + height = #cursorSize + ConsoleCursor(height) + Repeat + If Inkey() + height ! #cursorSize + ConsoleCursor(height) + EndIf + ForEver +EndIf diff --git a/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-1.tcl b/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-1.tcl new file mode 100644 index 0000000000..89e820a411 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-1.tcl @@ -0,0 +1,9 @@ +proc cursor {{state "normal"}} { + switch -- $state { + "normal" {set op "cnorm"} + "invisible" {set op "civis"} + "visible" {set op "cvvis"} + } + # Should be just: “exec tput $op” but it's not actually supported on my terminal... + exec sh -c "tput $op || true" +} diff --git a/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-2.tcl b/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-2.tcl new file mode 100644 index 0000000000..5bab17302c --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Tcl/terminal-control-hiding-the-cursor-2.tcl @@ -0,0 +1,12 @@ +cursor normal +puts "normal cursor" +after 3000 +cursor invisible +puts "invisible cursor" +after 3000 +cursor visible +puts "very visible cursor" +after 3000 +cursor normal +puts "back to normal" +after 1000 diff --git a/Task/Terminal-control-Hiding-the-cursor/UNIX-Shell/terminal-control-hiding-the-cursor.sh b/Task/Terminal-control-Hiding-the-cursor/UNIX-Shell/terminal-control-hiding-the-cursor.sh new file mode 100644 index 0000000000..7d14926a91 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/UNIX-Shell/terminal-control-hiding-the-cursor.sh @@ -0,0 +1,3 @@ +tput civis # Hide the cursor +sleep 5 # Sleep for 5 seconds +tput cnorm # Show the cursor diff --git a/Task/Terminal-control-Hiding-the-cursor/XPL0/terminal-control-hiding-the-cursor.xpl0 b/Task/Terminal-control-Hiding-the-cursor/XPL0/terminal-control-hiding-the-cursor.xpl0 new file mode 100644 index 0000000000..094534c852 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/XPL0/terminal-control-hiding-the-cursor.xpl0 @@ -0,0 +1,15 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +proc ShowCur(On); \Turn flashing cursor on or off +int On; \true = cursor on; false = cursor off +int CpuReg; +[CpuReg:= GetReg; \access CPU registers +CpuReg(0):= $0100; \AX:= $0100 +CpuReg(2):= if On then $0007 else $2000; +SoftInt($10); \Call BIOS interrupt $10 +]; \ShowCur + +[ShowCur(false); \turn off flashing cursor +if ChIn(1) then []; \wait for keystroke +ShowCur(true); \turn on flashing cursor +] diff --git a/Task/Terminal-control-Inverse-video/0DESCRIPTION b/Task/Terminal-control-Inverse-video/0DESCRIPTION new file mode 100644 index 0000000000..142b3fe378 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/0DESCRIPTION @@ -0,0 +1 @@ +The task is to display a word in inverse video (or reverse video) followed by a word in normal video. diff --git a/Task/Terminal-control-Inverse-video/1META.yaml b/Task/Terminal-control-Inverse-video/1META.yaml new file mode 100644 index 0000000000..d3f138f1fa --- /dev/null +++ b/Task/Terminal-control-Inverse-video/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Terminal control +note: Terminal control diff --git a/Task/Terminal-control-Inverse-video/AWK/terminal-control-inverse-video.awk b/Task/Terminal-control-Inverse-video/AWK/terminal-control-inverse-video.awk new file mode 100644 index 0000000000..701dacbccd --- /dev/null +++ b/Task/Terminal-control-Inverse-video/AWK/terminal-control-inverse-video.awk @@ -0,0 +1,6 @@ +BEGIN { +system ("tput rev") +print "foo" +system ("tput sgr0") +print "bar" +} diff --git a/Task/Terminal-control-Inverse-video/AutoHotkey/terminal-control-inverse-video.ahk b/Task/Terminal-control-Inverse-video/AutoHotkey/terminal-control-inverse-video.ahk new file mode 100644 index 0000000000..f61c62d537 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/AutoHotkey/terminal-control-inverse-video.ahk @@ -0,0 +1,14 @@ +DllCall( "AllocConsole" ) ; create a console if not launched from one +hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) + +SetConsoleTextAttribute(hConsole, 0x70) ; gray background, black foreground +FileAppend, Reversed`n, CONOUT$ ; print to stdout + +SetConsoleTextAttribute(hConsole, 0x07) ; black background, gray foreground +FileAppend, Normal, CONOUT$ + +MsgBox + +SetConsoleTextAttribute(hConsole, Attributes){ + return DllCall( "SetConsoleTextAttribute", UPtr, hConsole, UShort, Attributes) +} diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic new file mode 100644 index 0000000000..51bf9d9664 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-1.basic @@ -0,0 +1,2 @@ +10 CALL &bb9c:PRINT "inverse"; +20 CALL &bb9c:PRINT "normal" diff --git a/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic new file mode 100644 index 0000000000..5df2772b6d --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-2.basic @@ -0,0 +1,4 @@ +10 INVERSE 1 +20 PRINT "FOO"; +30 INVERSE 0 +40 PRINT "BAR" diff --git a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc new file mode 100644 index 0000000000..68cc00506e --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-1.bbc @@ -0,0 +1,6 @@ + COLOUR 128 : REM Black background + COLOUR 15 : REM White foreground + PRINT "Inverse"; + COLOUR 128+15 : REM White background + COLOUR 0 : REM Black foreground + PRINT " video" diff --git a/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc new file mode 100644 index 0000000000..1b6f4e4bb8 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/BBC-BASIC/terminal-control-inverse-video-2.bbc @@ -0,0 +1,3 @@ + inverse$ = CHR$(17)+CHR$(128)+CHR$(17)+CHR$(15) + normal$ = CHR$(17)+CHR$(128+15)+CHR$(17)+CHR$(0) + PRINT inverse$ + "Inverse" + normal$ + " video" diff --git a/Task/Terminal-control-Inverse-video/C/terminal-control-inverse-video.c b/Task/Terminal-control-Inverse-video/C/terminal-control-inverse-video.c new file mode 100644 index 0000000000..3c2a60034e --- /dev/null +++ b/Task/Terminal-control-Inverse-video/C/terminal-control-inverse-video.c @@ -0,0 +1,8 @@ +#include + +int main() +{ + printf("\033[7mReversed\033[m Normal\n"); + + return 0; +} diff --git a/Task/Terminal-control-Inverse-video/J/terminal-control-inverse-video.j b/Task/Terminal-control-Inverse-video/J/terminal-control-inverse-video.j new file mode 100644 index 0000000000..9a5f596c1b --- /dev/null +++ b/Task/Terminal-control-Inverse-video/J/terminal-control-inverse-video.j @@ -0,0 +1,5 @@ + ;:';:,#.*."3,(C.A.)/\/&.:;:' NB. some output beforehand + attributes REVERSEVIDEO NB. does as it says + 2 o.^:a:0 NB. solve the fixed point equation cos(x) == x + attributes OFF NB. no more blinky flashy + parseFrench=:;:,#.*."3,(C.A.)/\/&.:;: NB. just kidding! More output. diff --git a/Task/Terminal-control-Inverse-video/Mathematica/terminal-control-inverse-video.math b/Task/Terminal-control-Inverse-video/Mathematica/terminal-control-inverse-video.math new file mode 100644 index 0000000000..bd82243181 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Mathematica/terminal-control-inverse-video.math @@ -0,0 +1,4 @@ +Run["tput mr"] +Run["echo foo"] (* is displayed in reverse mode *) +Run["tput me"] +Run["echo bar"] diff --git a/Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ocaml b/Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ocaml new file mode 100644 index 0000000000..d9305a9761 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ocaml @@ -0,0 +1,6 @@ +$ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma + +# open ANSITerminal ;; +# print_string [Inverse] "Hello\n" ;; +Hello +- : unit = () diff --git a/Task/Terminal-control-Inverse-video/Perl-6/terminal-control-inverse-video.pl6 b/Task/Terminal-control-Inverse-video/Perl-6/terminal-control-inverse-video.pl6 new file mode 100644 index 0000000000..258d64a49c --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Perl-6/terminal-control-inverse-video.pl6 @@ -0,0 +1,5 @@ +say "normal"; +run "tput", "rev"; +say "reversed"; +run "tput", "sgr0"; +say "normal"; diff --git a/Task/Terminal-control-Inverse-video/PicoLisp/terminal-control-inverse-video.l b/Task/Terminal-control-Inverse-video/PicoLisp/terminal-control-inverse-video.l new file mode 100644 index 0000000000..4d3ca6ddb1 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/PicoLisp/terminal-control-inverse-video.l @@ -0,0 +1,5 @@ +(prin "abc") +(call "tput" "rev") +(prin "def") # These three chars are displayed in reverse video +(call "tput" "sgr0") +(prinl "ghi") diff --git a/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic b/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic new file mode 100644 index 0000000000..f917ae3d6e --- /dev/null +++ b/Task/Terminal-control-Inverse-video/PureBasic/terminal-control-inverse-video.purebasic @@ -0,0 +1,9 @@ +If OpenConsole() + ConsoleColor(0, 15) ;use the colors black (background) and white (forground) + PrintN("Inverse Video") + ConsoleColor(15, 0) ;use the colors white (background) and black (forground) + PrintN("Normal Video") + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Terminal-control-Inverse-video/Python/terminal-control-inverse-video.py b/Task/Terminal-control-Inverse-video/Python/terminal-control-inverse-video.py new file mode 100644 index 0000000000..55d6264d44 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Python/terminal-control-inverse-video.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python + +print "\033[7mReversed\033[m Normal" diff --git a/Task/Terminal-control-Inverse-video/REXX/terminal-control-inverse-video.rexx b/Task/Terminal-control-Inverse-video/REXX/terminal-control-inverse-video.rexx new file mode 100644 index 0000000000..f3f600e33c --- /dev/null +++ b/Task/Terminal-control-Inverse-video/REXX/terminal-control-inverse-video.rexx @@ -0,0 +1,6 @@ +/*REXX program to demonstrate reverse video. */ +@day = 'day' +@night = 'night' +call scrwrite , 1, @day, , , 7 /*white on black.*/ +call scrwrite , 1+length(@day), @night, , , 112 /*black on white.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run b/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run new file mode 100644 index 0000000000..35efdfc74b --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Run-BASIC/terminal-control-inverse-video.run @@ -0,0 +1,8 @@ +' ---------- foo is reverse -------------- +x$ = shell$("tput mr +echo 'foo'") + +' ---------- bar is normal -------------- +x$ = shell$("tput me +echo 'bar'") +wait diff --git a/Task/Terminal-control-Inverse-video/TPP/terminal-control-inverse-video.tpp b/Task/Terminal-control-Inverse-video/TPP/terminal-control-inverse-video.tpp new file mode 100644 index 0000000000..e098d46d37 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/TPP/terminal-control-inverse-video.tpp @@ -0,0 +1,4 @@ +--revon +This is inverse +--revoff +This is normal diff --git a/Task/Terminal-control-Inverse-video/Tcl/terminal-control-inverse-video.tcl b/Task/Terminal-control-Inverse-video/Tcl/terminal-control-inverse-video.tcl new file mode 100644 index 0000000000..277604cc23 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Tcl/terminal-control-inverse-video.tcl @@ -0,0 +1,14 @@ +# Get how the terminal wants to do things... +set videoSeq(reverse) [exec tput rev] +set videoSeq(normal) [exec tput rmso] +proc reverseVideo str { + global videoSeq + return "$videoSeq(reverse)${str}$videoSeq(normal)" +} + +# The things to print +set inReverse "foo" +set inNormal "bar" + +# Print those words +puts "[reverseVideo $inReverse] $inNormal" diff --git a/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-1.sh b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-1.sh new file mode 100644 index 0000000000..7e48511dc5 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-1.sh @@ -0,0 +1,5 @@ +#!/bin/sh +tput mr # foo is reversed +echo 'foo' +tput me # bar is normal video +echo 'bar' diff --git a/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-2.sh b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-2.sh new file mode 100644 index 0000000000..e7e2c7aeba --- /dev/null +++ b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-2.sh @@ -0,0 +1,2 @@ +$ TERM=dumb tput mr +tput: Unknown terminfo capability `mr' diff --git a/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-3.sh b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-3.sh new file mode 100644 index 0000000000..d203dc06a8 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-3.sh @@ -0,0 +1,4 @@ +tput so # enter standout mode +echo 'foo' +tput se # exit standout mode +echo 'bar' diff --git a/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-4.sh b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-4.sh new file mode 100644 index 0000000000..336d1890c9 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/UNIX-Shell/terminal-control-inverse-video-4.sh @@ -0,0 +1,4 @@ +tput mr +echo 'foo' +tput me +echo 'bar' diff --git a/Task/Terminal-control-Inverse-video/XPL0/terminal-control-inverse-video.xpl0 b/Task/Terminal-control-Inverse-video/XPL0/terminal-control-inverse-video.xpl0 new file mode 100644 index 0000000000..4e4cce6073 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/XPL0/terminal-control-inverse-video.xpl0 @@ -0,0 +1,7 @@ +include c:\cxpl\codes; +[Attrib($70); +Text(6, "Inverse"); +Attrib($07); +Text(6, " Video"); +CrLf(6); +] diff --git a/Task/Terminal-control-Positional-read/0DESCRIPTION b/Task/Terminal-control-Positional-read/0DESCRIPTION new file mode 100644 index 0000000000..a1f1ea6faf --- /dev/null +++ b/Task/Terminal-control-Positional-read/0DESCRIPTION @@ -0,0 +1,2 @@ +[[Terminal Control::task| ]] +Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language. diff --git a/Task/Terminal-control-Positional-read/1META.yaml b/Task/Terminal-control-Positional-read/1META.yaml new file mode 100644 index 0000000000..9c15565476 --- /dev/null +++ b/Task/Terminal-control-Positional-read/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Terminal control diff --git a/Task/Terminal-control-Positional-read/AutoHotkey/terminal-control-positional-read.ahk b/Task/Terminal-control-Positional-read/AutoHotkey/terminal-control-positional-read.ahk new file mode 100644 index 0000000000..26359f7a64 --- /dev/null +++ b/Task/Terminal-control-Positional-read/AutoHotkey/terminal-control-positional-read.ahk @@ -0,0 +1,37 @@ +DllCall( "AllocConsole" ) ; create a console if not launched from one +hConsole := DllCall( "GetStdHandle", int, STDOUT := -11 ) +Loop 10 +{ + Loop 10 + { + Random, asc, % asc("A"), % Asc("Z") + WriteConsole(hConsole, Chr(asc)) + } + WriteConsole(hConsole, "`n") +} + +MsgBox % ReadConsoleOutputCharacter(hConsole, 1, 3, 6) + +; === The below simply wraps part of the WinAPI === + +WriteConsole(hConsole, text){ + VarSetCapacity(out, 16) + If DllCall( "WriteConsole", UPtr, hConsole, Str, text, UInt, StrLen(text) + , UPtrP, out, uint, 0 ) + return out + return 0 +} +ReadConsoleOutputCharacter(hConsole, length, x, y){ + VarSetCapacity(out, length * (1 << !!A_IsUnicode)) + VarSetCapacity(n, 16) + if DllCall( "ReadConsoleOutputCharacter" + , UPtr, hConsole + , Str, out + , UInt, length + , UInt, x | (y << 16) + , UPtrP, n ) + + && VarSetCapacity(out, -1) + return out + return 0 +} diff --git a/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-1.basic b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-1.basic new file mode 100644 index 0000000000..2e2512a000 --- /dev/null +++ b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-1.basic @@ -0,0 +1,2 @@ +10 LOCATE 3,6 +20 a$=COPYCHR$(#0) diff --git a/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-2.basic b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-2.basic new file mode 100644 index 0000000000..5cafcc3c19 --- /dev/null +++ b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-2.basic @@ -0,0 +1 @@ +c$ = CHR$(SCREEN(6, 3)) diff --git a/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-3.basic b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-3.basic new file mode 100644 index 0000000000..0606843ce8 --- /dev/null +++ b/Task/Terminal-control-Positional-read/BASIC/terminal-control-positional-read-3.basic @@ -0,0 +1,3 @@ + 10 REM The top left corner is at position 0,0 + 20 REM So we subtract one from the coordinates + 30 LET c$ = SCREEN$(5,2) diff --git a/Task/Terminal-control-Positional-read/BBC-BASIC/terminal-control-positional-read.bbc b/Task/Terminal-control-Positional-read/BBC-BASIC/terminal-control-positional-read.bbc new file mode 100644 index 0000000000..af455ea261 --- /dev/null +++ b/Task/Terminal-control-Positional-read/BBC-BASIC/terminal-control-positional-read.bbc @@ -0,0 +1,3 @@ + PRINT TAB(2,5) "Here" + char$ = GET$(2,5) + PRINT ''"Character at column 3 row 6 was " char$ diff --git a/Task/Terminal-control-Positional-read/C/terminal-control-positional-read.c b/Task/Terminal-control-Positional-read/C/terminal-control-positional-read.c new file mode 100644 index 0000000000..d07254131a --- /dev/null +++ b/Task/Terminal-control-Positional-read/C/terminal-control-positional-read.c @@ -0,0 +1,33 @@ +#include +#include + +int +main() +{ + CONSOLE_SCREEN_BUFFER_INFO info; + COORD pos; + HANDLE conout; + long len; + wchar_t c; + + /* Create a handle to the console screen. */ + conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + 0, NULL); + if (conout == INVALID_HANDLE_VALUE) + return 1; + + /* Where is the display window? */ + if (GetConsoleScreenBufferInfo(conout, &info) == 0) + return 1; + + /* c = character at position. */ + pos.X = info.srWindow.Left + 3; /* Column */ + pos.Y = info.srWindow.Top + 6; /* Row */ + if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 || + len <= 0) + return 1; + + wprintf(L"Character at (3, 6) had been '%lc'\n", c); + return 0; +} diff --git a/Task/Terminal-control-Positional-read/REXX/terminal-control-positional-read.rexx b/Task/Terminal-control-Positional-read/REXX/terminal-control-positional-read.rexx new file mode 100644 index 0000000000..8e038c4769 --- /dev/null +++ b/Task/Terminal-control-Positional-read/REXX/terminal-control-positional-read.rexx @@ -0,0 +1,9 @@ +/*REXX program demonstrates reading a char at specific screen location.*/ +row = 6 /*point to row six. */ +col = 3 /*point to column three. */ +howMany = 1 /*read one character. */ + +stuff = scrRead(row, col, howMany) /*this'll do it. */ + +other = scrRead(40, 6, 1) /*same thing, but for row forty. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Terminal-control-Positional-read/XPL0/terminal-control-positional-read.xpl0 b/Task/Terminal-control-Positional-read/XPL0/terminal-control-positional-read.xpl0 new file mode 100644 index 0000000000..a7ebbcb673 --- /dev/null +++ b/Task/Terminal-control-Positional-read/XPL0/terminal-control-positional-read.xpl0 @@ -0,0 +1,6 @@ +include c:\cxpl\stdlib; +int C; +[Cursor(3, 6); \move cursor to column 3, row 6 (top left = 0,0) +\Call BIOS interrupt routine to read character (& attribute) at cursor position +C:= CallInt($10, $0800, 0) & $00FF; \mask off attribute, leaving the character +] diff --git a/Task/Terminal-control-Preserve-screen/0DESCRIPTION b/Task/Terminal-control-Preserve-screen/0DESCRIPTION new file mode 100644 index 0000000000..c9c903ff8a --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/0DESCRIPTION @@ -0,0 +1,2 @@ +[[Terminal Control::task| ]] +The task is to clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved. If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit. diff --git a/Task/Terminal-control-Preserve-screen/1META.yaml b/Task/Terminal-control-Preserve-screen/1META.yaml new file mode 100644 index 0000000000..9c15565476 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Terminal control diff --git a/Task/Terminal-control-Preserve-screen/BBC-BASIC/terminal-control-preserve-screen.bbc b/Task/Terminal-control-Preserve-screen/BBC-BASIC/terminal-control-preserve-screen.bbc new file mode 100644 index 0000000000..c083af5797 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/BBC-BASIC/terminal-control-preserve-screen.bbc @@ -0,0 +1,7 @@ + PRINT "This is the original screen" + OSCLI "GSAVE """ + @tmp$ + "bbcsave""" + WAIT 200 + CLS + PRINT "This is the new screen, following a CLS" + WAIT 200 + OSCLI "DISPLAY """ + @tmp$ + "bbcsave""" diff --git a/Task/Terminal-control-Preserve-screen/C/terminal-control-preserve-screen.c b/Task/Terminal-control-Preserve-screen/C/terminal-control-preserve-screen.c new file mode 100644 index 0000000000..0ca18b44fe --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/C/terminal-control-preserve-screen.c @@ -0,0 +1,17 @@ +#include +#include + +int main() +{ + int i; + printf("\033[?1049h\033[H"); + printf("Alternate screen buffer\n"); + for (i = 5; i; i--) { + printf("\rgoing back in %d...", i); + fflush(stdout); + sleep(1); + } + printf("\033[?1049l"); + + return 0; +} diff --git a/Task/Terminal-control-Preserve-screen/JavaScript/terminal-control-preserve-screen.js b/Task/Terminal-control-Preserve-screen/JavaScript/terminal-control-preserve-screen.js new file mode 100644 index 0000000000..6b3e414aac --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/JavaScript/terminal-control-preserve-screen.js @@ -0,0 +1,10 @@ +(function() { + var orig= document.body.innerHTML + document.body.innerHTML= ''; + setTimeout(function() { + document.body.innerHTML= 'something'; + setTimeout(function() { + document.body.innerHTML= orig; + }, 1000); + }, 1000); +})(); diff --git a/Task/Terminal-control-Preserve-screen/Mathematica/terminal-control-preserve-screen.math b/Task/Terminal-control-Preserve-screen/Mathematica/terminal-control-preserve-screen.math new file mode 100644 index 0000000000..4158838696 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Mathematica/terminal-control-preserve-screen.math @@ -0,0 +1,4 @@ +Run["tput smcup"] (* Save the display *) +Run["echo Hello"] +Pause[5] (* Wait five seconds *) +Run["tput rmcup"] diff --git a/Task/Terminal-control-Preserve-screen/PicoLisp/terminal-control-preserve-screen.l b/Task/Terminal-control-Preserve-screen/PicoLisp/terminal-control-preserve-screen.l new file mode 100644 index 0000000000..3f862b89b7 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/PicoLisp/terminal-control-preserve-screen.l @@ -0,0 +1,8 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(call 'tput "smcup") +(prinl "something") +(wait 3000) +(call 'tput "rmcup") + +(bye) diff --git a/Task/Terminal-control-Preserve-screen/Python/terminal-control-preserve-screen.py b/Task/Terminal-control-Preserve-screen/Python/terminal-control-preserve-screen.py new file mode 100644 index 0000000000..a35abda260 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Python/terminal-control-preserve-screen.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +import time + +print "\033[?1049h\033[H" +print "Alternate buffer!" + +for i in xrange(5, 0, -1): + print "Going back in:", i + time.sleep(1) + +print "\033[?1049l" diff --git a/Task/Terminal-control-Preserve-screen/REXX/terminal-control-preserve-screen.rexx b/Task/Terminal-control-Preserve-screen/REXX/terminal-control-preserve-screen.rexx new file mode 100644 index 0000000000..f73ec52ec4 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/REXX/terminal-control-preserve-screen.rexx @@ -0,0 +1,16 @@ +/*REXX pgm saves the screen contents, clear it, write +++, restore orig.*/ +parse value scrsize() with sd sw . /*determine how big the screen is*/ +parse value cursor(1,1) with r_ c_ /*find where the cursor is also. */ + do original=1 for sd /*get the original screen content*/ + @line.original=scrread(original,1,sw) + end +'CLS' /*start with a clean slate. */ + do 20 + say copies('$',60) /*write a score of sixty bucks. */ + end +'CLS' /*start with a clean slate, again*/ + do restore=1 for sd /*restore the original screen. */ + call scrwrite restore,1,strip(@line.restore,'T') + end +call cursor r_,c_ /*restore the original cursor pos*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Terminal-control-Preserve-screen/Tcl/terminal-control-preserve-screen.tcl b/Task/Terminal-control-Preserve-screen/Tcl/terminal-control-preserve-screen.tcl new file mode 100644 index 0000000000..a46aa2aca4 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Tcl/terminal-control-preserve-screen.tcl @@ -0,0 +1,12 @@ +# A helper to make code more readable +proc terminal {args} { + exec /usr/bin/tput {*}$args >/dev/tty +} + +# Save the screen with the "enter_ca_mode" capability, a.k.a. 'smcup' +terminal smcup +# Some indication to users what is happening... +puts "This is the top of a blank screen. Press Return/Enter to continue..." +gets stdin +# Restore the screen with the "exit_ca_mode" capability, a.k.a. 'rmcup' +terminal rmcup diff --git a/Task/Terminal-control-Preserve-screen/UNIX-Shell/terminal-control-preserve-screen.sh b/Task/Terminal-control-Preserve-screen/UNIX-Shell/terminal-control-preserve-screen.sh new file mode 100644 index 0000000000..23be09861d --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/UNIX-Shell/terminal-control-preserve-screen.sh @@ -0,0 +1,5 @@ +#!/bin/sh +tput smcup # Save the display +echo 'Hello' +sleep 5 # Wait five seconds +tput rmcup # Restore the display diff --git a/Task/Terminal-control-Preserve-screen/XPL0/terminal-control-preserve-screen.xpl0 b/Task/Terminal-control-Preserve-screen/XPL0/terminal-control-preserve-screen.xpl0 new file mode 100644 index 0000000000..3bfd95e560 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/XPL0/terminal-control-preserve-screen.xpl0 @@ -0,0 +1,16 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +proc SetPage(P); \Select active display page for video screen +int P; +int CpuReg; +[CpuReg:= GetReg; \access CPU registers +CpuReg(0):= $0500 + P; \call BIOS interrupt $10, function 5 +SoftInt($10); +]; \SetPage + +[SetPage(1); \enable page 1 text display screen +Clear; \clear screen and output something +Text(0, "Hit any key to restore original screen. "); +if ChIn(1) then []; \wait for keystroke +SetPage(0); \restore original, default text screen, page 0 +] diff --git a/Task/Terminal-control-Preserve-screen/Z80-Assembly/terminal-control-preserve-screen.z80 b/Task/Terminal-control-Preserve-screen/Z80-Assembly/terminal-control-preserve-screen.z80 new file mode 100644 index 0000000000..26c16b7df2 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Z80-Assembly/terminal-control-preserve-screen.z80 @@ -0,0 +1,45 @@ + org $3000 + +txt_output: equ $bb5a +scr_clear: equ $bc14 +wait_char: equ $bb06 +scr_get_loc: equ $bc0b +scr_set_off: equ $bc05 + + push bc + push de + push hl + push af + + call scr_get_loc ; save this value just in case the + push hl ; original screen has been scrolled vertically + + ld hl,$c000 ; copy screen to block 1 + ld de,$4000 + ld bc,$4000 + ldir + + call scr_clear + ld hl,text + +print: ld a,(hl) + cp 0 + jr z,key + call txt_output + inc hl + jr print + +key: call wait_char + pop hl + call scr_set_off + ld hl,$4000 ; restore screen + ld de,$c000 + ld bc,$4000 + ldir + pop af + pop hl + pop de + pop bc + ret + +text: defm "This is some text. Please press a key.\0" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/0DESCRIPTION b/Task/Terminal-control-Ringing-the-terminal-bell/0DESCRIPTION new file mode 100644 index 0000000000..60edde54fb --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/0DESCRIPTION @@ -0,0 +1,4 @@ +[[Terminal Control::task| ]] +Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usually used to indicate a problem where a wrong character has been typed. + +In most terminals, if the [[wp:Bell character|Bell character]] (ASCII code 7, \a in C) is printed by the program, it will cause the terminal to ring its bell. This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out. diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/1META.yaml b/Task/Terminal-control-Ringing-the-terminal-bell/1META.yaml new file mode 100644 index 0000000000..9c15565476 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Terminal control diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800 b/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800 new file mode 100644 index 0000000000..5c12bd8865 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/6800-Assembly/terminal-control-ringing-the-terminal-bell.6800 @@ -0,0 +1,23 @@ + .cr 6800 + .tf bel6800.obj,AP1 + .lf bel6800 +;=====================================================; +; Ring the Bell for the Motorola 6800 ; +; by barrym 2013-03-31 ; +;-----------------------------------------------------; +; Rings the bell of an ascii terminal (console) ; +; connected to a 1970s vintage SWTPC 6800 system, ; +; which is the target device for this assembly. ; +; Many thanks to: ; +; swtpc.com for hosting Michael Holley's documents! ; +; sbprojects.com for a very nice assembler! ; +; swtpcemu.com for a very capable emulator! ; +; reg a holds the ascii char to be output ; +;-----------------------------------------------------; +outeee = $e1d1 ROM: console putchar routine + .or $0f00 +;-----------------------------------------------------; +main ldaa #7 Load the ascii BEL char + jsr outeee and print it + swi Return to the monitor + .en diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/AWK/terminal-control-ringing-the-terminal-bell.awk b/Task/Terminal-control-Ringing-the-terminal-bell/AWK/terminal-control-ringing-the-terminal-bell.awk new file mode 100644 index 0000000000..f8cf37d8c1 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/AWK/terminal-control-ringing-the-terminal-bell.awk @@ -0,0 +1,3 @@ +BEGIN { +print "\a" # Ring the bell +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Ada/terminal-control-ringing-the-terminal-bell.ada b/Task/Terminal-control-Ringing-the-terminal-bell/Ada/terminal-control-ringing-the-terminal-bell.ada new file mode 100644 index 0000000000..20e87aaf1b --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Ada/terminal-control-ringing-the-terminal-bell.ada @@ -0,0 +1,7 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Characters.Latin_1; + +procedure Bell is +begin + Put(Ada.Characters.Latin_1.BEL); +end Bell; diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/AutoHotkey/terminal-control-ringing-the-terminal-bell.ahk b/Task/Terminal-control-Ringing-the-terminal-bell/AutoHotkey/terminal-control-ringing-the-terminal-bell.ahk new file mode 100644 index 0000000000..c3c3964cb5 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/AutoHotkey/terminal-control-ringing-the-terminal-bell.ahk @@ -0,0 +1 @@ +fileappend, `a, * diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-1.basic b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-1.basic new file mode 100644 index 0000000000..451cc99710 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-1.basic @@ -0,0 +1 @@ + 10 PRINT CHR$ (7); diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-2.basic b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-2.basic new file mode 100644 index 0000000000..8f5acf8400 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-2.basic @@ -0,0 +1,2 @@ + 10 PRINT "";: REM ^G IN QUOTES + 20 END diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-3.basic b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-3.basic new file mode 100644 index 0000000000..931c55b5a7 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-3.basic @@ -0,0 +1 @@ +10 PRINT CHR$(7) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-4.basic b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-4.basic new file mode 100644 index 0000000000..205d718a25 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/BASIC/terminal-control-ringing-the-terminal-bell-4.basic @@ -0,0 +1 @@ +BEEP 0.2,0 diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/BBC-BASIC/terminal-control-ringing-the-terminal-bell.bbc b/Task/Terminal-control-Ringing-the-terminal-bell/BBC-BASIC/terminal-control-ringing-the-terminal-bell.bbc new file mode 100644 index 0000000000..86c98f5440 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/BBC-BASIC/terminal-control-ringing-the-terminal-bell.bbc @@ -0,0 +1 @@ +VDU 7 diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Befunge/terminal-control-ringing-the-terminal-bell.bf b/Task/Terminal-control-Ringing-the-terminal-bell/Befunge/terminal-control-ringing-the-terminal-bell.bf new file mode 100644 index 0000000000..6c417df8e7 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Befunge/terminal-control-ringing-the-terminal-bell.bf @@ -0,0 +1 @@ +7,@ diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Brainf---/terminal-control-ringing-the-terminal-bell.bf b/Task/Terminal-control-Ringing-the-terminal-bell/Brainf---/terminal-control-ringing-the-terminal-bell.bf new file mode 100644 index 0000000000..d383f67d33 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Brainf---/terminal-control-ringing-the-terminal-bell.bf @@ -0,0 +1,6 @@ + I + + + + + + +++ ++-+-+ + . diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/C/terminal-control-ringing-the-terminal-bell.c b/Task/Terminal-control-Ringing-the-terminal-bell/C/terminal-control-ringing-the-terminal-bell.c new file mode 100644 index 0000000000..d94de50915 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/C/terminal-control-ringing-the-terminal-bell.c @@ -0,0 +1,5 @@ +#include +int main() { + printf("\a"); + return 0; +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.delphi b/Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.delphi new file mode 100644 index 0000000000..d928e59c4b --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.delphi @@ -0,0 +1,7 @@ +program TerminalBell; + +{$APPTYPE CONSOLE} + +begin + Writeln(#7); +end. diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/E/terminal-control-ringing-the-terminal-bell.e b/Task/Terminal-control-Ringing-the-terminal-bell/E/terminal-control-ringing-the-terminal-bell.e new file mode 100644 index 0000000000..fef410e07c --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/E/terminal-control-ringing-the-terminal-bell.e @@ -0,0 +1 @@ +print("\u0007") diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Emacs-Lisp/terminal-control-ringing-the-terminal-bell.l b/Task/Terminal-control-Ringing-the-terminal-bell/Emacs-Lisp/terminal-control-ringing-the-terminal-bell.l new file mode 100644 index 0000000000..1a868c1e4f --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Emacs-Lisp/terminal-control-ringing-the-terminal-bell.l @@ -0,0 +1,2 @@ +(ding) ;; ring the bell +(beep) ;; the same thing diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-1.fth b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-1.fth new file mode 100644 index 0000000000..9871dcd4ea --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-1.fth @@ -0,0 +1 @@ +7 emit diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-2.fth b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-2.fth new file mode 100644 index 0000000000..a8fffd791d --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-2.fth @@ -0,0 +1 @@ +#bell emit diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-3.fth b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-3.fth new file mode 100644 index 0000000000..101490fd4e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Forth/terminal-control-ringing-the-terminal-bell-3.fth @@ -0,0 +1 @@ +^G emit diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Go/terminal-control-ringing-the-terminal-bell.go b/Task/Terminal-control-Ringing-the-terminal-bell/Go/terminal-control-ringing-the-terminal-bell.go new file mode 100644 index 0000000000..c8f37ad22a --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Go/terminal-control-ringing-the-terminal-bell.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Print("\a") +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Groovy/terminal-control-ringing-the-terminal-bell.groovy b/Task/Terminal-control-Ringing-the-terminal-bell/Groovy/terminal-control-ringing-the-terminal-bell.groovy new file mode 100644 index 0000000000..ded5a0ee58 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Groovy/terminal-control-ringing-the-terminal-bell.groovy @@ -0,0 +1 @@ +println '\7' diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Haskell/terminal-control-ringing-the-terminal-bell.hs b/Task/Terminal-control-Ringing-the-terminal-bell/Haskell/terminal-control-ringing-the-terminal-bell.hs new file mode 100644 index 0000000000..2cfa3035ab --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Haskell/terminal-control-ringing-the-terminal-bell.hs @@ -0,0 +1 @@ +main = putStr "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Icon/terminal-control-ringing-the-terminal-bell.icon b/Task/Terminal-control-Ringing-the-terminal-bell/Icon/terminal-control-ringing-the-terminal-bell.icon new file mode 100644 index 0000000000..9fc413e158 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Icon/terminal-control-ringing-the-terminal-bell.icon @@ -0,0 +1,3 @@ +procedure main () + write ("\7") # ASCII 7 rings the bell under Bash +end diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/J/terminal-control-ringing-the-terminal-bell.j b/Task/Terminal-control-Ringing-the-terminal-bell/J/terminal-control-ringing-the-terminal-bell.j new file mode 100644 index 0000000000..dcab26102b --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/J/terminal-control-ringing-the-terminal-bell.j @@ -0,0 +1 @@ + 7{a. NB. noun a. is a complete ASCII ordered character vector. diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Java/terminal-control-ringing-the-terminal-bell.java b/Task/Terminal-control-Ringing-the-terminal-bell/Java/terminal-control-ringing-the-terminal-bell.java new file mode 100644 index 0000000000..e118b95de7 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Java/terminal-control-ringing-the-terminal-bell.java @@ -0,0 +1,9 @@ +public class Bell{ + public static void main(String[] args){ + java.awt.Toolkit.getDefaultToolkit().beep(); + + //or + + System.out.println((char)7); + } +} diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Logo/terminal-control-ringing-the-terminal-bell.logo b/Task/Terminal-control-Ringing-the-terminal-bell/Logo/terminal-control-ringing-the-terminal-bell.logo new file mode 100644 index 0000000000..3fb7f85161 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Logo/terminal-control-ringing-the-terminal-bell.logo @@ -0,0 +1 @@ +type char 7 diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Mathematica/terminal-control-ringing-the-terminal-bell.math b/Task/Terminal-control-Ringing-the-terminal-bell/Mathematica/terminal-control-ringing-the-terminal-bell.math new file mode 100644 index 0000000000..b4e1f4e7ea --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Mathematica/terminal-control-ringing-the-terminal-bell.math @@ -0,0 +1 @@ +Print["\007"] diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Objeck/terminal-control-ringing-the-terminal-bell.objeck b/Task/Terminal-control-Ringing-the-terminal-bell/Objeck/terminal-control-ringing-the-terminal-bell.objeck new file mode 100644 index 0000000000..b8fe6261cf --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Objeck/terminal-control-ringing-the-terminal-bell.objeck @@ -0,0 +1 @@ +7->As(Char)->PrintLine(); diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PL-I/terminal-control-ringing-the-terminal-bell.pli b/Task/Terminal-control-Ringing-the-terminal-bell/PL-I/terminal-control-ringing-the-terminal-bell.pli new file mode 100644 index 0000000000..4906157e7a --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PL-I/terminal-control-ringing-the-terminal-bell.pli @@ -0,0 +1,3 @@ + declare bell character (1); + unspec (bell) = '00000111'b; + put edit (bell) (a); diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Perl-6/terminal-control-ringing-the-terminal-bell.pl6 b/Task/Terminal-control-Ringing-the-terminal-bell/Perl-6/terminal-control-ringing-the-terminal-bell.pl6 new file mode 100644 index 0000000000..725d118938 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Perl-6/terminal-control-ringing-the-terminal-bell.pl6 @@ -0,0 +1 @@ +print 7.chr; diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Perl/terminal-control-ringing-the-terminal-bell.pl b/Task/Terminal-control-Ringing-the-terminal-bell/Perl/terminal-control-ringing-the-terminal-bell.pl new file mode 100644 index 0000000000..410dbeaf23 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Perl/terminal-control-ringing-the-terminal-bell.pl @@ -0,0 +1 @@ +print "\a"; diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PicoLisp/terminal-control-ringing-the-terminal-bell.l b/Task/Terminal-control-Ringing-the-terminal-bell/PicoLisp/terminal-control-ringing-the-terminal-bell.l new file mode 100644 index 0000000000..31c0c395ec --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PicoLisp/terminal-control-ringing-the-terminal-bell.l @@ -0,0 +1 @@ +(beep) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PostScript/terminal-control-ringing-the-terminal-bell.ps b/Task/Terminal-control-Ringing-the-terminal-bell/PostScript/terminal-control-ringing-the-terminal-bell.ps new file mode 100644 index 0000000000..2241f91171 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PostScript/terminal-control-ringing-the-terminal-bell.ps @@ -0,0 +1 @@ +(\007) print diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-1.psh b/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-1.psh new file mode 100644 index 0000000000..8192af04e4 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-1.psh @@ -0,0 +1 @@ +"`a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-2.psh b/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-2.psh new file mode 100644 index 0000000000..5e36a36efa --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-2.psh @@ -0,0 +1 @@ +[Console]::Beep() diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/PureBasic/terminal-control-ringing-the-terminal-bell.purebasic b/Task/Terminal-control-Ringing-the-terminal-bell/PureBasic/terminal-control-ringing-the-terminal-bell.purebasic new file mode 100644 index 0000000000..48aba3d197 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/PureBasic/terminal-control-ringing-the-terminal-bell.purebasic @@ -0,0 +1 @@ +Print(#BEL$) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Python/terminal-control-ringing-the-terminal-bell.py b/Task/Terminal-control-Ringing-the-terminal-bell/Python/terminal-control-ringing-the-terminal-bell.py new file mode 100644 index 0000000000..3fde07b32e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Python/terminal-control-ringing-the-terminal-bell.py @@ -0,0 +1 @@ +print "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/R/terminal-control-ringing-the-terminal-bell.r b/Task/Terminal-control-Ringing-the-terminal-bell/R/terminal-control-ringing-the-terminal-bell.r new file mode 100644 index 0000000000..b6fe1d12ff --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/R/terminal-control-ringing-the-terminal-bell.r @@ -0,0 +1 @@ +alarm() diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/REXX/terminal-control-ringing-the-terminal-bell.rexx b/Task/Terminal-control-Ringing-the-terminal-bell/REXX/terminal-control-ringing-the-terminal-bell.rexx new file mode 100644 index 0000000000..f74e4b7118 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/REXX/terminal-control-ringing-the-terminal-bell.rexx @@ -0,0 +1,7 @@ +call beep(freq [,duration]) /*supported (kinda) by Regina. */ + +call sound(freq [,duration ]) /*supported by PC/REXX. */ + +say '07'x /*works under the Windows DOS shell.*/ + +say copies('07'x,100) /*as above, but much more annoying. */ diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Retro/terminal-control-ringing-the-terminal-bell.retro b/Task/Terminal-control-Ringing-the-terminal-bell/Retro/terminal-control-ringing-the-terminal-bell.retro new file mode 100644 index 0000000000..754f7a0f43 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Retro/terminal-control-ringing-the-terminal-bell.retro @@ -0,0 +1 @@ +7 putc diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Ruby/terminal-control-ringing-the-terminal-bell.rb b/Task/Terminal-control-Ringing-the-terminal-bell/Ruby/terminal-control-ringing-the-terminal-bell.rb new file mode 100644 index 0000000000..3fde07b32e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Ruby/terminal-control-ringing-the-terminal-bell.rb @@ -0,0 +1 @@ +print "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/SNUSP/terminal-control-ringing-the-terminal-bell.snusp b/Task/Terminal-control-Ringing-the-terminal-bell/SNUSP/terminal-control-ringing-the-terminal-bell.snusp new file mode 100644 index 0000000000..4660a1c387 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/SNUSP/terminal-control-ringing-the-terminal-bell.snusp @@ -0,0 +1 @@ +$+++++++.# diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Tcl/terminal-control-ringing-the-terminal-bell.tcl b/Task/Terminal-control-Ringing-the-terminal-bell/Tcl/terminal-control-ringing-the-terminal-bell.tcl new file mode 100644 index 0000000000..0502bbe9c8 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Tcl/terminal-control-ringing-the-terminal-bell.tcl @@ -0,0 +1 @@ +puts -nonewline "\a";flush stdout diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/UNIX-Shell/terminal-control-ringing-the-terminal-bell.sh b/Task/Terminal-control-Ringing-the-terminal-bell/UNIX-Shell/terminal-control-ringing-the-terminal-bell.sh new file mode 100644 index 0000000000..ce02beacfa --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/UNIX-Shell/terminal-control-ringing-the-terminal-bell.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# Ring the terminal bell +# echo "\a" # does not work in some shells +tput bel diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/X86-Assembly/terminal-control-ringing-the-terminal-bell.x86 b/Task/Terminal-control-Ringing-the-terminal-bell/X86-Assembly/terminal-control-ringing-the-terminal-bell.x86 new file mode 100644 index 0000000000..48e8f68cec --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/X86-Assembly/terminal-control-ringing-the-terminal-bell.x86 @@ -0,0 +1,9 @@ +;Assemble with: tasm; tlink /t + .model tiny + .code + org 100h ;.com files start here +start: mov ah, 02h ;character output + mov dl, 07h ;bell code + int 21h ;call MS-DOS + ret ;return to MS-DOS + end start diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/XPL0/terminal-control-ringing-the-terminal-bell.xpl0 b/Task/Terminal-control-Ringing-the-terminal-bell/XPL0/terminal-control-ringing-the-terminal-bell.xpl0 new file mode 100644 index 0000000000..d7eb45c260 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/XPL0/terminal-control-ringing-the-terminal-bell.xpl0 @@ -0,0 +1,2 @@ +code ChOut=8; +ChOut(0,7) diff --git a/Task/Terminal-control-Unicode-output/0DESCRIPTION b/Task/Terminal-control-Unicode-output/0DESCRIPTION new file mode 100644 index 0000000000..394d380199 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/0DESCRIPTION @@ -0,0 +1,3 @@ +The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. + +Note that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility. diff --git a/Task/Terminal-control-Unicode-output/1META.yaml b/Task/Terminal-control-Unicode-output/1META.yaml new file mode 100644 index 0000000000..9a62075737 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Terminal control +- Unicode diff --git a/Task/Terminal-control-Unicode-output/AWK/terminal-control-unicode-output.awk b/Task/Terminal-control-Unicode-output/AWK/terminal-control-unicode-output.awk new file mode 100644 index 0000000000..46b65a3b7c --- /dev/null +++ b/Task/Terminal-control-Unicode-output/AWK/terminal-control-unicode-output.awk @@ -0,0 +1,25 @@ +#!/usr/bin/awk -f +BEGIN { + unicodeterm=1 # Assume Unicode support + if (ENVIRON["LC_ALL"] !~ "UTF") { + if (ENVIRON["LC_ALL"] != "" + unicodeterm=0 # LC_ALL is the boss, and it says nay + else { + # Check other locale settings if LC_ALL override not set + if (ENVIRON["LC_CTYPE"] !~ "UTF") { + if (ENVIRON["LANG"] !~ "UTF") + unicodeterm=0 # This terminal does not support Unicode + } + } + } + + if (unicodeterm) { + # This terminal supports Unicode + # We need a Unicode compatible printf, so we source this externally + # printf might not know \u or \x, so use octal. + # U+25B3 => UTF-8 342 226 263 + "/usr/bin/printf \\342\\226\\263\\n" + } else { + print "HW65001 This program requires a Unicode compatible terminal"|"cat 1>&2" + exit 252 # Incompatible hardware + } diff --git a/Task/Terminal-control-Unicode-output/BBC-BASIC/terminal-control-unicode-output.bbc b/Task/Terminal-control-Unicode-output/BBC-BASIC/terminal-control-unicode-output.bbc new file mode 100644 index 0000000000..0541a11a77 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/BBC-BASIC/terminal-control-unicode-output.bbc @@ -0,0 +1,3 @@ + VDU 23,22,640;512;8,16,16,128+8 : REM Enable UTF-8 mode + *FONT Arial Unicode MS,36 + PRINT CHR$(&E2)+CHR$(&96)+CHR$(&B3) diff --git a/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c b/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c new file mode 100644 index 0000000000..9ad4084237 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/C/terminal-control-unicode-output.c @@ -0,0 +1,29 @@ +/*30th August, 2012 +Abhishek Ghosh*/ + +#include +#include + +int +main () +{ + int i; + char *str = getenv ("LANG"); + + for (i = 0; str[i + 2] != 00; i++) + { + if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') + || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) + { + printf + ("Unicode is supported on this terminal and U+25B3 is : \u25b3"); + i = -1; + break; + } + } + + if (i != -1) + printf ("Unicode is not supported on this terminal."); + + return 0; +} diff --git a/Task/Terminal-control-Unicode-output/Mathematica/terminal-control-unicode-output.math b/Task/Terminal-control-Unicode-output/Mathematica/terminal-control-unicode-output.math new file mode 100644 index 0000000000..122ce59197 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Mathematica/terminal-control-unicode-output.math @@ -0,0 +1,2 @@ +If[StringMatchQ[$CharacterEncoding, "UTF*"], Print[FromCharacterCode[30000]], Print["UTF-8 capable terminal required"]] +->田 diff --git a/Task/Terminal-control-Unicode-output/Perl-6/terminal-control-unicode-output.pl6 b/Task/Terminal-control-Unicode-output/Perl-6/terminal-control-unicode-output.pl6 new file mode 100644 index 0000000000..f7b210dc86 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Perl-6/terminal-control-unicode-output.pl6 @@ -0,0 +1,3 @@ +die "Terminal can't handle UTF-8" + unless first(*.defined, %*ENV) ~~ /:i 'utf-8'/; +say "△"; diff --git a/Task/Terminal-control-Unicode-output/PicoLisp/terminal-control-unicode-output.l b/Task/Terminal-control-Unicode-output/PicoLisp/terminal-control-unicode-output.l new file mode 100644 index 0000000000..09a2683f35 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/PicoLisp/terminal-control-unicode-output.l @@ -0,0 +1,3 @@ +(if (sub? "UTF-8" (or (sys "LC_ALL") (sys "LC_CTYPE") (sys "LANG"))) + (prinl (char (hex "25b3"))) + (quit "UTF-8 capable terminal required") ) diff --git a/Task/Terminal-control-Unicode-output/Tcl/terminal-control-unicode-output.tcl b/Task/Terminal-control-Unicode-output/Tcl/terminal-control-unicode-output.tcl new file mode 100644 index 0000000000..ca1a6272b8 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Tcl/terminal-control-unicode-output.tcl @@ -0,0 +1,6 @@ +# Check if we're using one of the UTF or "unicode" encodings +if {[string match utf-* [encoding system]] || [string match *unicode* [encoding system]]} { + puts "\u25b3" +} else { + error "terminal does not support unicode (probably)" +} diff --git a/Task/Terminal-control-Unicode-output/UNIX-Shell/terminal-control-unicode-output.sh b/Task/Terminal-control-Unicode-output/UNIX-Shell/terminal-control-unicode-output.sh new file mode 100644 index 0000000000..2799426ccb --- /dev/null +++ b/Task/Terminal-control-Unicode-output/UNIX-Shell/terminal-control-unicode-output.sh @@ -0,0 +1,24 @@ +unicode_tty() { + # LC_ALL supersedes LC_CTYPE, which supersedes LANG. + # Set $1 to environment value. + case y in + ${LC_ALL:+y}) set -- "$LC_ALL";; + ${LC_CTYPE:+y}) set -- "$LC_CTYPE";; + ${LANG:+y}) set -- "$LANG";; + y) return 1;; # Assume "C" locale not UTF-8. + esac + # We use 'case' to perform pattern matching against a string. + case "$1" in + *UTF-8*) return 0;; + *) return 1;; + esac +} + +if unicode_tty; then + # printf might not know \u or \x, so use octal. + # U+25B3 => UTF-8 342 226 263 + printf "\342\226\263\n" +else + echo "HW65001 This program requires a Unicode compatible terminal" >&2 + exit 252 # Incompatible hardware +fi diff --git a/Task/Terminal-control-Unicode-output/ZX-Spectrum-Basic/terminal-control-unicode-output.zx b/Task/Terminal-control-Unicode-output/ZX-Spectrum-Basic/terminal-control-unicode-output.zx new file mode 100644 index 0000000000..b27d559965 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/ZX-Spectrum-Basic/terminal-control-unicode-output.zx @@ -0,0 +1,10 @@ +10 REM There is no Unicode delta in ROM +20 REM So we first define a custom character +30 FOR l=0 TO 7 +40 READ n +50 POKE USR "d"+l,n +60 NEXT l +70 REM our custom character is a user defined d +80 PRINT CHR$(147): REM this outputs our delta +9500 REM data for our custom delta +9510 DATA 0,0,8,20,34,65,127,0 diff --git a/Task/Ternary-logic/0DESCRIPTION b/Task/Ternary-logic/0DESCRIPTION new file mode 100644 index 0000000000..83e9ec59c4 --- /dev/null +++ b/Task/Ternary-logic/0DESCRIPTION @@ -0,0 +1,80 @@ +{{wikipedia|Ternary logic}} +In [[wp:logic|logic]], a '''three-valued logic''' (also '''trivalent''', '''ternary''', or '''trinary logic''', sometimes abbreviated '''3VL''') is any of several [[wp:many-valued logic|many-valued logic]] systems in which there are three [[wp:truth value|truth value]]s indicating ''true'', ''false'' and some indeterminate third value. This is contrasted with the more commonly known [[wp:Principle of bivalence|bivalent]] logics (such as classical sentential or [[wp:boolean logic|boolean logic]]) which provide only for ''true'' and ''false''. Conceptual form and basic ideas were initially created by [[wp:Jan Łukasiewicz|Łukasiewicz]], [[wp:C. I. Lewis|Lewis]] and [[wp:Sulski|Sulski]]. These were then re-formulated by [[wp:Grigore Moisil|Grigore Moisil]] in an axiomatic algebraic form, and also extended to ''n''-valued logics in 1945. +{| +|+'''Example ''Ternary Logic Operators'' in ''Truth Tables'':''' +|- +| +{| class=wikitable +|+''not'' a +|- +! colspan=2 | ¬ +|- +| True || False +|- +| Maybe || Maybe +|- +| False || True +|} +|| +{| class=wikitable +|+a ''and'' b +|- +! ∧ +| True || Maybe || False +|- +| True || True || Maybe || False +|- +| Maybe || Maybe || Maybe || False +|- +| False || False || False || False +|} +|| +{| class=wikitable +|- +|+a ''or'' b +|- +! ∨ +| True || Maybe || False +|- +| True || True || True || True +|- +| Maybe || True || Maybe || Maybe +|- +| False || True || Maybe || False +|} +|- +|| +{| class=wikitable +|- +|+''if'' a ''then'' b +|- +! ⊃ +| True || Maybe || False +|- +| True || True || Maybe || False +|- +| Maybe || True || Maybe || Maybe +|- +| False || True || True || True +|} +|| +{| class=wikitable +|- +|+a ''is equivalent to'' b +|- +! ≡ +| True || Maybe || False +|- +| True || True || Maybe || False +|- +| Maybe || Maybe || Maybe || Maybe +|- +| False || False || Maybe || True +|} +|} +'''Task:''' +* Define a new type that emulates ''ternary logic'' by storing data '''trits'''. +* Given all the binary logic operators of the original programming language, reimplement these operators for the new ''Ternary logic'' type '''trit'''. +* Generate a sampling of results using '''trit''' variables. +* [[wp:Kudos|Kudos]] for actually thinking up a test case algorithm where ''ternary logic'' is intrinsically useful, optimises the test case algorithm and is preferable to binary logic. +Note: '''[[wp:Setun|Setun]]''' (Сетунь) was a [[wp:balanced ternary|balanced ternary]] computer developed in 1958 at [[wp:Moscow State University|Moscow State University]]. The device was built under the lead of [[wp:Sergei Sobolev|Sergei Sobolev]] and [[wp:Nikolay Brusentsov|Nikolay Brusentsov]]. It was the only modern [[wp:ternary computer|ternary computer]], using three-valued [[wp:ternary logic|ternary logic]] diff --git a/Task/Ternary-logic/1META.yaml b/Task/Ternary-logic/1META.yaml new file mode 100644 index 0000000000..b648829ba0 --- /dev/null +++ b/Task/Ternary-logic/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Logic diff --git a/Task/Ternary-logic/ALGOL-68/ternary-logic-1.alg b/Task/Ternary-logic/ALGOL-68/ternary-logic-1.alg new file mode 100644 index 0000000000..5ab30bbe54 --- /dev/null +++ b/Task/Ternary-logic/ALGOL-68/ternary-logic-1.alg @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- # + +INT trit width = 1, trit base = 3; +MODE TRIT = STRUCT(BITS trit); +CO FORMAT trit fmt = $c("?","⌈","⌊",#|"~"#)$; CO + +# These values treated are as per "Balanced ternary" # +# eg true=1, maybe=0, false=-1 # +TRIT true =INITTRIT 4r1, maybe=INITTRIT 4r0, + false=INITTRIT 4r2; + +# Warning: redefines standard builtins flip & flop # +LONGCHAR flap="?", flip="⌈", flop="⌊"; + +OP REPR = (TRIT t)LONGCHAR: + []LONGCHAR(flap, flip, flop)[1+ABS trit OF t]; + +############################################ +# Define some OPerators for coercing MODES # +############################################ +OP INITTRIT = (BOOL in)TRIT: + (in|true|false); + +OP INITBOOL = (TRIT in)BOOL: + (trit OF in=trit OF true|TRUE|:trit OF in=trit OF false|FALSE| + raise value error(("vague TRIT to BOOL coercion: """, REPR in,""""));~ + ); +OP B = (TRIT in)BOOL: INITBOOL in; + +# These values treated are as per "Balanced ternary" # +# n.b true=1, maybe=0, false=-1 # +# Warning: BOOL ABS FALSE (0) is not the same as TRIT ABS false (-1) # + +OP INITINT = (TRIT t)INT: + CASE 1+ABS trit OF t + IN #maybe# 0, #true # 1, #false#-1 + OUT raise value error(("invalid TRIT value",REPR t)); ~ + ESAC; + +OP INITTRIT = (INT in)TRIT: ( + TRIT out; + trit OF out:= trit OF + CASE 2+in + IN false, maybe, true + OUT raise value error(("invalid TRIT value",in)); ~ + ESAC; + out +); + +OP INITTRIT = (BITS b)TRIT: + (TRIT out; trit OF out:=b; out); + +################################################## +# Define the LOGICAL OPerators for the TRIT MODE # +################################################## +MODE LOGICAL = TRIT; +PR READ "Template_operators_logical_mixin.a68" PR + +COMMENT + Kleene logic truth tables: +END COMMENT + +OP AND = (TRIT a,b)TRIT: ( + [,]TRIT( + # ∧ ## false, maybe, true # + #false# (false, false, false), + #maybe# (false, maybe, maybe), + #true # (false, maybe, true ) + )[@-1,@-1][INITINT a, INITINT b] +); + +OP OR = (TRIT a,b)TRIT: ( + [,]TRIT( + # ∨ ## false, maybe, true # + #false# (false, maybe, true), + #maybe# (maybe, maybe, true), + #true # (true, true, true) + )[@-1,@-1][INITINT a, INITINT b] +); + +PRIO IMPLIES = 1; # PRIO = 1.9 # +OP IMPLIES = (TRIT a,b)TRIT: ( + [,]TRIT( + # ⊃ ## false, maybe, true # + #false# (true, true, true), + #maybe# (maybe, maybe, true), + #true # (false, maybe, true) + )[@-1,@-1][INITINT a, INITINT b] +); + +PRIO EQV = 1; # PRIO = 1.8 # +OP EQV = (TRIT a,b)TRIT: ( + [,]TRIT( + # ≡ ## false, maybe, true # + #false# (true, maybe, false), + #maybe# (maybe, maybe, maybe), + #true # (false, maybe, true ) + )[@-1,@-1][INITINT a, INITINT b] +); diff --git a/Task/Ternary-logic/ALGOL-68/ternary-logic-2.alg b/Task/Ternary-logic/ALGOL-68/ternary-logic-2.alg new file mode 100644 index 0000000000..69cfd46056 --- /dev/null +++ b/Task/Ternary-logic/ALGOL-68/ternary-logic-2.alg @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- # + +OP & = (LOGICAL a,b)LOGICAL: a AND b; +CO # not included as they are treated as SCALAR # +OP EQ = (LOGICAL a,b)LOGICAL: a = b, + NE = (LOGICAL a,b)LOGICAL: a /= b, + ≠ = (TRIT a,b)TRIT: a /= b, + ¬= = (TRIT a,b)TRIT: a /= b; +END CO + +#IF html entities possible THEN +¢ "parked" operators for completeness ¢ +OP ¬ = (LOGICAL a)LOGICAL: NOT a, + ∧ = (LOGICAL a,b)LOGICAL: a AND b, + /\ = (LOGICAL a,b)LOGICAL: a AND b, + ∨ = (LOGICAL a,b)LOGICAL: a OR b, + \/ = (LOGICAL a,b)LOGICAL: a OR b, + ⊃ = (TRIT a,b)TRIT: a IMPLIES b, + ≡ = (TRIT a,b)TRIT: a EQV b; +FI# + +#IF algol68c THEN +OP ~ = (LOGICAL a)LOGICAL: NOT a, + ~= = (LOGICAL a,b)LOGICAL: a /= b; SCALAR! +FI# diff --git a/Task/Ternary-logic/ALGOL-68/ternary-logic-3.alg b/Task/Ternary-logic/ALGOL-68/ternary-logic-3.alg new file mode 100644 index 0000000000..3b69a74180 --- /dev/null +++ b/Task/Ternary-logic/ALGOL-68/ternary-logic-3.alg @@ -0,0 +1,70 @@ +#!/usr/local/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/general.a68" PR +PR READ "Ternary_logic.a68" PR + +[]TRIT trits = (false, maybe, true); + +FORMAT + col fmt = $" "g" "$, + row fmt = $l3(f(col fmt)"|")f(col fmt)$, + row sep fmt = $l3("---+")"---"l$; + +PROC row sep = VOID: + printf(row sep fmt); + +PROC title = (STRING op name, LONGCHAR op char)VOID:( + print(("Operator: ",op name)); + printf((row fmt,op char,REPR false, REPR maybe, REPR true)) +); + +PROC print trit op table = (LONGCHAR op char, STRING op name, PROC(TRIT,TRIT)TRIT op)VOID: ( + printf($l$); + title(op name, op char); + FOR i FROM LWB trits TO UPB trits DO + row sep; + TRIT ti = trits[i]; + printf((col fmt, REPR ti)); + FOR j FROM LWB trits TO UPB trits DO + TRIT tj = trits[j]; + printf(($"|"$, col fmt, REPR op(ti,tj))) + OD + OD; + printf($l$) +); + +printf(( + $"Comparitive table of coercions:"l$, + $" TRIT BOOL INT"l$ +)); + +FOR it FROM LWB trits TO UPB trits DO + TRIT t = trits[it]; + printf(( $" "g" "$, REPR t, + IF trit OF t = trit OF maybe THEN " " ELSE B t FI, + INITINT t, $l$)) +OD; + +printf(( + $l"Specific test of the IMPLIES operator:"l$, + $" "g" implies "g" is "b("not ","")"a contradiction!"l$, + B false, B false, B(false IMPLIES false), + B false, B true, B(false IMPLIES true), + B false, REPR maybe, B(false IMPLIES maybe), + B true, B false, B(true IMPLIES false), + B true, B true, B(true IMPLIES true), + REPR maybe, Btrue, B(maybe IMPLIES true), + $" "g" implies "g" is "g" a contradiction!"l$, + B true, REPR maybe, REPR (true IMPLIES maybe), + REPR maybe, B false, REPR (maybe IMPLIES false), + REPR maybe, REPR maybe, REPR (maybe IMPLIES maybe), + $l$ +)); + +printf($"Kleene logic truth table samples:"l$); + +print trit op table("≡","EQV", (TRIT a,b)TRIT: a EQV b); +print trit op table("⊃","IMPLIES", (TRIT a,b)TRIT: a IMPLIES b); +print trit op table("∧","AND", (TRIT a,b)TRIT: a AND b); +print trit op table("∨","OR", (TRIT a,b)TRIT: a OR b) diff --git a/Task/Ternary-logic/Ada/ternary-logic-1.ada b/Task/Ternary-logic/Ada/ternary-logic-1.ada new file mode 100644 index 0000000000..41daf737a6 --- /dev/null +++ b/Task/Ternary-logic/Ada/ternary-logic-1.ada @@ -0,0 +1,15 @@ +package Logic is + type Ternary is (True, Unknown, False); + + -- logic functions + function "and"(Left, Right: Ternary) return Ternary; + function "or"(Left, Right: Ternary) return Ternary; + function "not"(T: Ternary) return Ternary; + function Equivalent(Left, Right: Ternary) return Ternary; + function Implies(Condition, Conclusion: Ternary) return Ternary; + + -- conversion functions + function To_Bool(X: Ternary) return Boolean; + function To_Ternary(B: Boolean) return Ternary; + function Image(Value: Ternary) return Character; +end Logic; diff --git a/Task/Ternary-logic/Ada/ternary-logic-2.ada b/Task/Ternary-logic/Ada/ternary-logic-2.ada new file mode 100644 index 0000000000..2268f5149a --- /dev/null +++ b/Task/Ternary-logic/Ada/ternary-logic-2.ada @@ -0,0 +1,62 @@ +package body Logic is + -- type Ternary is (True, Unknown, False); + + function Image(Value: Ternary) return Character is + begin + case Value is + when True => return 'T'; + when False => return 'F'; + when Unknown => return '?'; + end case; + end Image; + + function "and"(Left, Right: Ternary) return Ternary is + begin + return Ternary'max(Left, Right); + end "and"; + + function "or"(Left, Right: Ternary) return Ternary is + begin + return Ternary'min(Left, Right); + end "or"; + + function "not"(T: Ternary) return Ternary is + begin + case T is + when False => return True; + when Unknown => return Unknown; + when True => return False; + end case; + end "not"; + + function To_Bool(X: Ternary) return Boolean is + begin + case X is + when True => return True; + when False => return False; + when Unknown => raise Constraint_Error; + end case; + end To_Bool; + + function To_Ternary(B: Boolean) return Ternary is + begin + if B then + return True; + else + return False; + end if; + end To_Ternary; + + function Equivalent(Left, Right: Ternary) return Ternary is + begin + return To_Ternary(To_Bool(Left) = To_Bool(Right)); + exception + when Constraint_Error => return Unknown; + end Equivalent; + + function Implies(Condition, Conclusion: Ternary) return Ternary is + begin + return (not Condition) or Conclusion; + end Implies; + +end Logic; diff --git a/Task/Ternary-logic/Ada/ternary-logic-3.ada b/Task/Ternary-logic/Ada/ternary-logic-3.ada new file mode 100644 index 0000000000..f970be9705 --- /dev/null +++ b/Task/Ternary-logic/Ada/ternary-logic-3.ada @@ -0,0 +1,35 @@ +with Ada.Text_IO, Logic; + +procedure Test_Tri_Logic is + + use Logic; + + type F2 is access function(Left, Right: Ternary) return Ternary; + type F1 is access function(Trit: Ternary) return Ternary; + + procedure Truth_Table(F: F1; Name: String) is + begin + Ada.Text_IO.Put_Line("X | " & Name & "(X)"); + for T in Ternary loop + Ada.Text_IO.Put_Line(Image(T) & " | " & Image(F(T))); + end loop; + end Truth_Table; + + procedure Truth_Table(F: F2; Name: String) is + begin + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line("X | Y | " & Name & "(X,Y)"); + for X in Ternary loop + for Y in Ternary loop + Ada.Text_IO.Put_Line(Image(X) & " | " & Image(Y) & " | " & Image(F(X,Y))); + end loop; + end loop; + end Truth_Table; + +begin + Truth_Table(F => "not"'Access, Name => "Not"); + Truth_Table(F => "and"'Access, Name => "And"); + Truth_Table(F => "or"'Access, Name => "Or"); + Truth_Table(F => Equivalent'Access, Name => "Eq"); + Truth_Table(F => Implies'Access, Name => "Implies"); +end Test_Tri_Logic; diff --git a/Task/Ternary-logic/BBC-BASIC/ternary-logic.bbc b/Task/Ternary-logic/BBC-BASIC/ternary-logic.bbc new file mode 100644 index 0000000000..5a47a0ac7e --- /dev/null +++ b/Task/Ternary-logic/BBC-BASIC/ternary-logic.bbc @@ -0,0 +1,46 @@ + INSTALL @lib$ + "CLASSLIB" + + REM Create a ternary class: + DIM trit{tor, tand, teqv, tnot, tnor, s, v} + DEF PRIVATE trit.s (t&) LOCAL t$():DIM t$(2):t$()="FALSE","MAYBE","TRUE":=t$(t&) + DEF PRIVATE trit.v (t$) = INSTR("FALSE MAYBE TRUE", t$) DIV 6 + DEF trit.tnot (t$) = FN(trit.s)(2 - FN(trit.v)(t$)) + DEF trit.tor (a$,b$) LOCAL t:t=FN(trit.v)(a$)ORFN(trit.v)(b$):=FN(trit.s)(t+(t>2)) + DEF trit.tnor (a$,b$) = FN(trit.tnot)(FN(trit.tor)(a$,b$)) + DEF trit.tand (a$,b$) = FN(trit.tnor)(FN(trit.tnot)(a$),FN(trit.tnot)(b$)) + DEF trit.teqv (a$,b$) = FN(trit.tor)(FN(trit.tand)(a$,b$),FN(trit.tnor)(a$,b$)) + PROC_class(trit{}) + + PROC_new(mytrit{}, trit{}) + + REM Test it: + PRINT "Testing NOT:" + PRINT "NOT FALSE = " FN(mytrit.tnot)("FALSE") + PRINT "NOT MAYBE = " FN(mytrit.tnot)("MAYBE") + PRINT "NOT TRUE = " FN(mytrit.tnot)("TRUE") + + PRINT '"Testing OR:" + PRINT "FALSE OR FALSE = " FN(mytrit.tor)("FALSE","FALSE") + PRINT "FALSE OR MAYBE = " FN(mytrit.tor)("FALSE","MAYBE") + PRINT "FALSE OR TRUE = " FN(mytrit.tor)("FALSE","TRUE") + PRINT "MAYBE OR MAYBE = " FN(mytrit.tor)("MAYBE","MAYBE") + PRINT "MAYBE OR TRUE = " FN(mytrit.tor)("MAYBE","TRUE") + PRINT "TRUE OR TRUE = " FN(mytrit.tor)("TRUE","TRUE") + + PRINT '"Testing AND:" + PRINT "FALSE AND FALSE = " FN(mytrit.tand)("FALSE","FALSE") + PRINT "FALSE AND MAYBE = " FN(mytrit.tand)("FALSE","MAYBE") + PRINT "FALSE AND TRUE = " FN(mytrit.tand)("FALSE","TRUE") + PRINT "MAYBE AND MAYBE = " FN(mytrit.tand)("MAYBE","MAYBE") + PRINT "MAYBE AND TRUE = " FN(mytrit.tand)("MAYBE","TRUE") + PRINT "TRUE AND TRUE = " FN(mytrit.tand)("TRUE","TRUE") + + PRINT '"Testing EQV (similar to EOR):" + PRINT "FALSE EQV FALSE = " FN(mytrit.teqv)("FALSE","FALSE") + PRINT "FALSE EQV MAYBE = " FN(mytrit.teqv)("FALSE","MAYBE") + PRINT "FALSE EQV TRUE = " FN(mytrit.teqv)("FALSE","TRUE") + PRINT "MAYBE EQV MAYBE = " FN(mytrit.teqv)("MAYBE","MAYBE") + PRINT "MAYBE EQV TRUE = " FN(mytrit.teqv)("MAYBE","TRUE") + PRINT "TRUE EQV TRUE = " FN(mytrit.teqv)("TRUE","TRUE") + + PROC_discard(mytrit{}) diff --git a/Task/Ternary-logic/C/ternary-logic-1.c b/Task/Ternary-logic/C/ternary-logic-1.c new file mode 100644 index 0000000000..797dd8f618 --- /dev/null +++ b/Task/Ternary-logic/C/ternary-logic-1.c @@ -0,0 +1,71 @@ +#include + +typedef enum { + TRITTRUE, /* In this enum, equivalent to integer value 0 */ + TRITMAYBE, /* In this enum, equivalent to integer value 1 */ + TRITFALSE /* In this enum, equivalent to integer value 2 */ +} trit; + +/* We can trivially find the result of the operation by passing + the trinary values as indeces into the lookup tables' arrays. */ +trit tritNot[3] = {TRITFALSE , TRITMAYBE, TRITTRUE}; +trit tritAnd[3][3] = { {TRITTRUE, TRITMAYBE, TRITFALSE}, + {TRITMAYBE, TRITMAYBE, TRITFALSE}, + {TRITFALSE, TRITFALSE, TRITFALSE} }; + +trit tritOr[3][3] = { {TRITTRUE, TRITTRUE, TRITTRUE}, + {TRITTRUE, TRITMAYBE, TRITMAYBE}, + {TRITTRUE, TRITMAYBE, TRITFALSE} }; + +trit tritThen[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE}, + { TRITTRUE, TRITMAYBE, TRITMAYBE}, + { TRITTRUE, TRITTRUE, TRITTRUE } }; + +trit tritEquiv[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE}, + { TRITMAYBE, TRITMAYBE, TRITMAYBE}, + { TRITFALSE, TRITMAYBE, TRITTRUE } }; + +/* Everything beyond here is just demonstration */ + +const char* tritString[3] = {"T", "?", "F"}; + +void demo_binary_op(trit operator[3][3], const char* name) +{ + trit operand1 = TRITTRUE; /* Declare. Initialize for CYA */ + trit operand2 = TRITTRUE; /* Declare. Initialize for CYA */ + + /* Blank line */ + printf("\n"); + + /* Demo this operator */ + for( operand1 = TRITTRUE; operand1 <= TRITFALSE; ++operand1 ) + { + for( operand2 = TRITTRUE; operand2 <= TRITFALSE; ++operand2 ) + { + printf("%s %s %s: %s\n", tritString[operand1], + name, + tritString[operand2], + tritString[operator[operand1][operand2]]); + } + } + +} + +int main() +{ + trit op1 = TRITTRUE; /* Declare. Initialize for CYA */ + trit op2 = TRITTRUE; /* Declare. Initialize for CYA */ + + /* Demo 'not' */ + for( op1 = TRITTRUE; op1 <= TRITFALSE; ++op1 ) + { + printf("Not %s: %s\n", tritString[op1], tritString[tritNot[op1]]); + } + demo_binary_op(tritAnd, "And"); + demo_binary_op(tritOr, "Or"); + demo_binary_op(tritThen, "Then"); + demo_binary_op(tritEquiv, "Equiv"); + + + return 0; +} diff --git a/Task/Ternary-logic/C/ternary-logic-2.c b/Task/Ternary-logic/C/ternary-logic-2.c new file mode 100644 index 0000000000..78e10066d0 --- /dev/null +++ b/Task/Ternary-logic/C/ternary-logic-2.c @@ -0,0 +1,43 @@ +Not T: F +Not ?: ? +Not F: T + +T And T: T +T And ?: ? +T And F: F +? And T: ? +? And ?: ? +? And F: F +F And T: F +F And ?: F +F And F: F + +T Or T: T +T Or ?: T +T Or F: T +? Or T: T +? Or ?: ? +? Or F: ? +F Or T: T +F Or ?: ? +F Or F: F + +T Then T: T +T Then ?: ? +T Then F: F +? Then T: T +? Then ?: ? +? Then F: ? +F Then T: T +F Then ?: T +F Then F: T + +T Equiv T: T +T Equiv ?: ? +T Equiv F: F +? Equiv T: ? +? Equiv ?: ? +? Equiv F: ? +F Equiv T: F +F Equiv ?: ? +F Equiv F: T diff --git a/Task/Ternary-logic/C/ternary-logic-3.c b/Task/Ternary-logic/C/ternary-logic-3.c new file mode 100644 index 0000000000..7501f7a992 --- /dev/null +++ b/Task/Ternary-logic/C/ternary-logic-3.c @@ -0,0 +1,36 @@ +#include + +typedef enum { t_F = -1, t_M, t_T } trit; + +trit t_not (trit a) { return -a; } +trit t_and (trit a, trit b) { return a < b ? a : b; } +trit t_or (trit a, trit b) { return a > b ? a : b; } +trit t_eq (trit a, trit b) { return a * b; } +trit t_imply(trit a, trit b) { return -a > b ? -a : b; } +char t_s(trit a) { return "F?T"[a + 1]; } + +#define forall(a) for(a = t_F; a <= t_T; a++) +void show_op(trit (*f)(trit, trit), const char *name) { + trit a, b; + printf("\n[%s]\n F ? T\n -------", name); + forall(a) { + printf("\n%c |", t_s(a)); + forall(b) printf(" %c", t_s(f(a, b))); + } + puts(""); +} + +int main(void) +{ + trit a; + + puts("[Not]"); + forall(a) printf("%c | %c\n", t_s(a), t_s(t_not(a))); + + show_op(t_and, "And"); + show_op(t_or, "Or"); + show_op(t_eq, "Equiv"); + show_op(t_imply, "Imply"); + + return 0; +} diff --git a/Task/Ternary-logic/C/ternary-logic-4.c b/Task/Ternary-logic/C/ternary-logic-4.c new file mode 100644 index 0000000000..0a2aba2181 --- /dev/null +++ b/Task/Ternary-logic/C/ternary-logic-4.c @@ -0,0 +1,32 @@ +[Not] +F | T +? | ? +T | F + +[And] + F ? T + ------- +F | F F F +? | F ? ? +T | F ? T + +[Or] + F ? T + ------- +F | F ? T +? | ? ? T +T | T T T + +[Equiv] + F ? T + ------- +F | T ? F +? | ? ? ? +T | F ? T + +[Imply] + F ? T + ------- +F | T T T +? | ? ? T +T | F ? T diff --git a/Task/Ternary-logic/C/ternary-logic-5.c b/Task/Ternary-logic/C/ternary-logic-5.c new file mode 100644 index 0000000000..1f006597f3 --- /dev/null +++ b/Task/Ternary-logic/C/ternary-logic-5.c @@ -0,0 +1,55 @@ +#include +#include + +typedef double half_truth, maybe; + +inline maybe not3(maybe a) { return 1 - a; } + +inline maybe +and3(maybe a, maybe b) { return a * b; } + +inline maybe +or3(maybe a, maybe b) { return a + b - a * b; } + +inline maybe +eq3(maybe a, maybe b) { return 1 - a - b + 2 * a * b; } + +inline maybe +imply3(maybe a, maybe b) { return or3(not3(a), b); } + +#define true3(x) ((x) * RAND_MAX > rand()) +#define if3(x) if (true3(x)) + +int main() +{ + maybe roses_are_red = 0.25; /* they can be white or black, too */ + maybe violets_are_blue = 1; /* aren't they just */ + int i; + + puts("Verifying flowery truth for 40 times:\n"); + + puts("Rose is NOT red:"); /* chance: .75 */ + for (i = 0; i < 40 || !puts("\n"); i++) + printf( true3( not3(roses_are_red) ) ? "T" : "_"); + + /* pick a rose and a violet; */ + puts("Rose is red AND violet is blue:"); + /* chance of rose being red AND violet being blue is .25 */ + for (i = 0; i < 40 || !puts("\n"); i++) + printf( true3( and3(roses_are_red, violets_are_blue) ) + ? "T" : "_"); + + /* chance of rose being red OR violet being blue is 1 */ + puts("Rose is red OR violet is blue:"); + for (i = 0; i < 40 || !puts("\n"); i++) + printf( true3( or3(roses_are_red, violets_are_blue) ) + ? "T" : "_"); + + /* pick two roses; chance of em being both red or both not red is .625 */ + puts("This rose is as red as that rose:"); + for (i = 0; i < 40 || !puts("\n"); i++) + if3(eq3(roses_are_red, roses_are_red)) putchar('T'); + else putchar('_'); + + return 0; +} diff --git a/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp b/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp new file mode 100644 index 0000000000..f6f438c50a --- /dev/null +++ b/Task/Ternary-logic/Common-Lisp/ternary-logic-1.lisp @@ -0,0 +1,31 @@ +(defun tri-not (x) (- 1 x)) +(defun tri-and (&rest x) (apply #'* x)) +(defun tri-or (&rest x) (tri-not (apply #'* (mapcar #'tri-not x)))) +(defun tri-eq (x y) (+ (tri-and x y) (tri-and (- 1 x) (- 1 y)))) +(defun tri-imply (x y) (tri-or (tri-not x) y)) + +(defun tri-test (x) (< (random 1e0) x)) +(defun tri-string (x) (if (= x 1) "T" (if (= x 0) "F" "?"))) + +;; to say (tri-if (condition) (yes) (no)) +(defmacro tri-if (tri ifcase &optional elsecase) + `(if (tri-test ,tri) ,ifcase ,elsecase)) + +(defun print-table (func header) + (let ((vals '(1 .5 0))) + (format t "~%~a:~%" header) + (format t " ~{~a ~^~}~%---------~%" (mapcar #'tri-string vals)) + (loop for row in vals do + (format t "~a | " (tri-string row)) + (loop for col in vals do + (format t "~a " (tri-string (funcall func row col)))) + (write-line "")))) + +(write-line "NOT:") +(loop for row in '(1 .5 0) do + (format t "~a | ~a~%" (tri-string row) (tri-string (tri-not row)))) + +(print-table #'tri-and "AND") +(print-table #'tri-or "OR") +(print-table #'tri-imply "IMPLY") +(print-table #'tri-eq "EQUAL") diff --git a/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp b/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp new file mode 100644 index 0000000000..d46f97b47f --- /dev/null +++ b/Task/Ternary-logic/Common-Lisp/ternary-logic-2.lisp @@ -0,0 +1,32 @@ +NOT: +T | F +? | ? +F | T + +AND: + T ? F +--------- +T | T ? F +? | ? ? F +F | F F F + +OR: + T ? F +--------- +T | T T T +? | T ? ? +F | T ? F + +IMPLY: + T ? F +--------- +T | T ? F +? | T ? ? +F | T T T + +EQUAL: + T ? F +--------- +T | T ? F +? | ? ? ? +F | F ? T diff --git a/Task/Ternary-logic/D/ternary-logic.d b/Task/Ternary-logic/D/ternary-logic.d new file mode 100644 index 0000000000..4755915c7c --- /dev/null +++ b/Task/Ternary-logic/D/ternary-logic.d @@ -0,0 +1,68 @@ +import std.stdio; + +struct Trit { + private enum Val : byte { F = -1, M, T } + private Val t; + alias t this; + static immutable Trit[3] vals = [{Val.F}, {Val.M}, {Val.T}]; + static immutable F = Trit(Val.F); // Not necessary but handy. + static immutable M = Trit(Val.M); + static immutable T = Trit(Val.T); + + string toString() const pure nothrow { + return "F?T"[t + 1 .. t + 2]; + } + + Trit opUnary(string op)() const pure nothrow + if (op == "~") { + return Trit(-t); + } + + Trit opBinary(string op)(in Trit b) const pure nothrow + if (op == "&") { + return t < b ? this : b; + } + + Trit opBinary(string op)(in Trit b) const pure nothrow + if (op == "|") { + return t > b ? this : b; + } + + Trit opBinary(string op)(in Trit b) const pure nothrow + if (op == "^") { + return ~(this == b); + } + + Trit opEquals(in Trit b) const pure nothrow { + return Trit(cast(Val)(t * b)); + } + + Trit imply(in Trit b) const pure nothrow { + return -t > b ? ~this : b; + } +} + +void showOperation(string op)(in string opName) { + writef("\n[%s]\n F ? T\n -------", opName); + foreach (immutable a; Trit.vals) { + writef("\n%s |", a); + foreach (immutable b; Trit.vals) + static if (op == "==>") + writef(" %s", a.imply(b)); + else + writef(" %s", mixin("a " ~ op ~ " b")); + } + writeln(); +} + +void main() { + writeln("[Not]"); + foreach (const a; Trit.vals) + writefln("%s | %s", a, ~a); + + showOperation!"&"("And"); + showOperation!"|"("Or"); + showOperation!"^"("Xor"); + showOperation!"=="("Equiv"); + showOperation!"==>"("Imply"); +} diff --git a/Task/Ternary-logic/Delphi/ternary-logic-1.delphi b/Task/Ternary-logic/Delphi/ternary-logic-1.delphi new file mode 100644 index 0000000000..02bab61419 --- /dev/null +++ b/Task/Ternary-logic/Delphi/ternary-logic-1.delphi @@ -0,0 +1,56 @@ +unit TrinaryLogic; + +interface + +//Define our own type for ternary logic. +//This is actually still a Boolean, but the compiler will use distinct RTTI information. +type + TriBool = type Boolean; + +const + TTrue:TriBool = True; + TFalse:TriBool = False; + TMaybe:TriBool = TriBool(2); + +function TVL_not(Value: TriBool): TriBool; +function TVL_and(A, B: TriBool): TriBool; +function TVL_or(A, B: TriBool): TriBool; +function TVL_xor(A, B: TriBool): TriBool; +function TVL_eq(A, B: TriBool): TriBool; + +implementation + +Uses + SysUtils; + +function TVL_not(Value: TriBool): TriBool; +begin + if Value = True Then + Result := TFalse + else If Value = False Then + Result := TTrue + else + Result := Value; +end; + +function TVL_and(A, B: TriBool): TriBool; +begin + Result := TriBool(Iff(Integer(A * B) > 1, Integer(TMaybe), A * B)); +end; + +function TVL_or(A, B: TriBool): TriBool; +begin + Result := TVL_not(TVL_and(TVL_not(A), TVL_not(B))); +end; + +function TVL_xor(A, B: TriBool): TriBool; +begin + Result := TVL_and(TVL_or(A, B), TVL_not(TVL_or(A, B))); +end; + +function TVL_eq(A, B: TriBool): TriBool; +begin + Result := TVL_not(TVL_xor(A, B)); +end; + +end. diff --git a/Task/Ternary-logic/Delphi/ternary-logic-2.delphi b/Task/Ternary-logic/Delphi/ternary-logic-2.delphi new file mode 100644 index 0000000000..f0dd2cf970 --- /dev/null +++ b/Task/Ternary-logic/Delphi/ternary-logic-2.delphi @@ -0,0 +1 @@ +type TriBool = (tbFalse, tbMaybe, tbTrue); diff --git a/Task/Ternary-logic/Delphi/ternary-logic-3.delphi b/Task/Ternary-logic/Delphi/ternary-logic-3.delphi new file mode 100644 index 0000000000..724f7e852b --- /dev/null +++ b/Task/Ternary-logic/Delphi/ternary-logic-3.delphi @@ -0,0 +1,22 @@ +const + tvl_not: array[TriBool] = (tbTrue, tbMaybe, tbFalse); + tvl_and: array[TriBool, TriBool] = ( + (tbFalse, tbFalse, tbFalse), + (tbFalse, tbMaybe, tbMaybe), + (tbFalse, tbMaybe, tbTrue), + ); + tvl_or: array[TriBool, TriBool] = ( + (tbFalse, tbMaybe, tbTrue), + (tbMaybe, tbMaybe, tbTrue), + (tbTrue, tbTrue, tbTrue), + ); + tvl_xor: array[TriBool, TriBool] = ( + (tbFalse, tbMaybe, tbTrue), + (tbMaybe, tbMaybe, tbMaybe), + (tbTrue, tbMaybe, tbFalse), + ); + tvl_eq: array[TriBool, TriBool] = ( + (tbTrue, tbMaybe, tbFalse), + (tbMaybe, tbMaybe, tbMaybe), + (tbFalse, tbMaybe, tbTrue), + ); diff --git a/Task/Ternary-logic/Delphi/ternary-logic-4.delphi b/Task/Ternary-logic/Delphi/ternary-logic-4.delphi new file mode 100644 index 0000000000..2888599a20 --- /dev/null +++ b/Task/Ternary-logic/Delphi/ternary-logic-4.delphi @@ -0,0 +1 @@ +Result := tvl_and[A, B]; diff --git a/Task/Ternary-logic/Factor/ternary-logic-1.factor b/Task/Ternary-logic/Factor/ternary-logic-1.factor new file mode 100644 index 0000000000..8de92aadf9 --- /dev/null +++ b/Task/Ternary-logic/Factor/ternary-logic-1.factor @@ -0,0 +1,41 @@ +! rosettacode/ternary/ternary.factor +! http://rosettacode.org/wiki/Ternary_logic +USING: combinators kernel ; +IN: rosettacode.ternary + +SINGLETON: m +UNION: trit t m POSTPONE: f ; + +GENERIC: >trit ( object -- trit ) +M: trit >trit ; + +: tnot ( trit1 -- trit ) + >trit { { t [ f ] } { m [ m ] } { f [ t ] } } case ; + +: tand ( trit1 trit2 -- trit ) + >trit { + { t [ >trit ] } + { m [ >trit { { t [ m ] } { m [ m ] } { f [ f ] } } case ] } + { f [ >trit drop f ] } + } case ; + +: tor ( trit1 trit2 -- trit ) + >trit { + { t [ >trit drop t ] } + { m [ >trit { { t [ t ] } { m [ m ] } { f [ m ] } } case ] } + { f [ >trit ] } + } case ; + +: txor ( trit1 trit2 -- trit ) + >trit { + { t [ tnot ] } + { m [ >trit drop m ] } + { f [ >trit ] } + } case ; + +: t= ( trit1 trit2 -- trit ) + { + { t [ >trit ] } + { m [ >trit drop m ] } + { f [ tnot ] } + } case ; diff --git a/Task/Ternary-logic/Factor/ternary-logic-2.factor b/Task/Ternary-logic/Factor/ternary-logic-2.factor new file mode 100644 index 0000000000..373a81b103 --- /dev/null +++ b/Task/Ternary-logic/Factor/ternary-logic-2.factor @@ -0,0 +1,11 @@ +( scratchpad ) CONSTANT: trits { t m f } +( scratchpad ) trits [ tnot ] map . +{ f m t } +( scratchpad ) trits [ trits swap [ tand ] curry map ] map . +{ { t m f } { m m f } { f f f } } +( scratchpad ) trits [ trits swap [ tor ] curry map ] map . +{ { t t t } { t m m } { t m f } } +( scratchpad ) trits [ trits swap [ txor ] curry map ] map . +{ { f m t } { m m m } { t m f } } +( scratchpad ) trits [ trits swap [ t= ] curry map ] map . +{ { t m f } { m m m } { f m t } } diff --git a/Task/Ternary-logic/Go/ternary-logic.go b/Task/Ternary-logic/Go/ternary-logic.go new file mode 100644 index 0000000000..88d51c41c5 --- /dev/null +++ b/Task/Ternary-logic/Go/ternary-logic.go @@ -0,0 +1,75 @@ +package main + +import "fmt" + +type trit int8 + +const ( + trFalse = iota - 1 + trMaybe + trTrue +) + +func (t trit) String() string { + switch t { + case trFalse: + return "False" + case trMaybe: + return "Maybe" + case trTrue: + return "True " + } + panic("Invalid trit") +} + +func trNot(t trit) trit { + return -t +} + +func trAnd(s, t trit) trit { + if s < t { + return s + } + return t +} + +func trOr(s, t trit) trit { + if s > t { + return s + } + return t +} + +func trEq(s, t trit) trit { + return s * t +} + +func main() { + trSet := []trit{trFalse, trMaybe, trTrue} + + fmt.Println("t not t") + for _, t := range trSet { + fmt.Println(t, trNot(t)) + } + + fmt.Println("\ns t s and t") + for _, s := range trSet { + for _, t := range trSet { + fmt.Println(s, t, trAnd(s, t)) + } + } + + fmt.Println("\ns t s or t") + for _, s := range trSet { + for _, t := range trSet { + fmt.Println(s, t, trOr(s, t)) + } + } + + fmt.Println("\ns t s eq t") + for _, s := range trSet { + for _, t := range trSet { + fmt.Println(s, t, trEq(s, t)) + } + } +} diff --git a/Task/Ternary-logic/Groovy/ternary-logic-1.groovy b/Task/Ternary-logic/Groovy/ternary-logic-1.groovy new file mode 100644 index 0000000000..21bdd38b16 --- /dev/null +++ b/Task/Ternary-logic/Groovy/ternary-logic-1.groovy @@ -0,0 +1,18 @@ +enum Trit { + TRUE, MAYBE, FALSE + + private Trit nand(Trit that) { + switch ([this,that]) { + case { FALSE in it }: return TRUE + case { MAYBE in it }: return MAYBE + default : return FALSE + } + } + private Trit nor(Trit that) { this.or(that).not() } + + Trit and(Trit that) { this.nand(that).not() } + Trit or(Trit that) { this.not().nand(that.not()) } + Trit not() { this.nand(this) } + Trit imply(Trit that) { this.nand(that.not()) } + Trit equiv(Trit that) { this.and(that).or(this.nor(that)) } +} diff --git a/Task/Ternary-logic/Groovy/ternary-logic-2.groovy b/Task/Ternary-logic/Groovy/ternary-logic-2.groovy new file mode 100644 index 0000000000..81433eecc3 --- /dev/null +++ b/Task/Ternary-logic/Groovy/ternary-logic-2.groovy @@ -0,0 +1,40 @@ +printf 'AND\n ' +Trit.values().each { b -> printf ('%6s', b) } +println '\n ----- ----- -----' +Trit.values().each { a -> + printf ('%6s | ', a) + Trit.values().each { b -> printf ('%6s', a.and(b)) } + println() +} + +printf '\nOR\n ' +Trit.values().each { b -> printf ('%6s', b) } +println '\n ----- ----- -----' +Trit.values().each { a -> + printf ('%6s | ', a) + Trit.values().each { b -> printf ('%6s', a.or(b)) } + println() +} + +println '\nNOT' +Trit.values().each { + printf ('%6s | %6s\n', it, it.not()) +} + +printf '\nIMPLY\n ' +Trit.values().each { b -> printf ('%6s', b) } +println '\n ----- ----- -----' +Trit.values().each { a -> + printf ('%6s | ', a) + Trit.values().each { b -> printf ('%6s', a.imply(b)) } + println() +} + +printf '\nEQUIV\n ' +Trit.values().each { b -> printf ('%6s', b) } +println '\n ----- ----- -----' +Trit.values().each { a -> + printf ('%6s | ', a) + Trit.values().each { b -> printf ('%6s', a.equiv(b)) } + println() +} diff --git a/Task/Ternary-logic/Haskell/ternary-logic.hs b/Task/Ternary-logic/Haskell/ternary-logic.hs new file mode 100644 index 0000000000..b4b83075fc --- /dev/null +++ b/Task/Ternary-logic/Haskell/ternary-logic.hs @@ -0,0 +1,37 @@ +import Prelude hiding (Bool(..), not, (&&), (||), (==)) + +main = mapM_ (putStrLn . unlines . map unwords) + [ table "not" $ unary not + , table "and" $ binary (&&) + , table "or" $ binary (||) + , table "implies" $ binary (=->) + , table "equals" $ binary (==) + ] + +data Trit = False | Maybe | True deriving (Show) + +False `nand` _ = True +_ `nand` False = True +True `nand` True = False +_ `nand` _ = Maybe + +not a = nand a a + +a && b = not $ a `nand` b + +a || b = not a `nand` not b + +a =-> b = a `nand` not b + +a == b = (a && b) || (not a && not b) + +inputs1 = [True, Maybe, False] +inputs2 = [(a,b) | a <- inputs1, b <- inputs1] + +unary f = map (\a -> [a, f a]) inputs1 +binary f = map (\(a,b) -> [a, b, f a b]) inputs2 + +table name xs = map (map pad) . (header :) $ map (map show) xs + where header = map (:[]) (take ((length $ head xs) - 1) ['A'..]) ++ [name] + +pad s = s ++ replicate (5 - length s) ' ' diff --git a/Task/Ternary-logic/Icon/ternary-logic.icon b/Task/Ternary-logic/Icon/ternary-logic.icon new file mode 100644 index 0000000000..369a3851b4 --- /dev/null +++ b/Task/Ternary-logic/Icon/ternary-logic.icon @@ -0,0 +1,62 @@ +$define TRUE 1 +$define FALSE -1 +$define UNKNOWN 0 + +invocable all +link printf + +procedure main() # demonstrate ternary logic + +ufunc := ["not3"] +bfunc := ["and3", "or3", "xor3", "eq3", "ifthen3"] + +every f := !ufunc do { # display unary functions + printf("\nunary function=%s:\n",f) + every t1 := (TRUE | FALSE | UNKNOWN) do + printf(" %s : %s\n",showtrit(t1),showtrit(not3(t1))) + } + + +every f := !bfunc do { # display binary functions + printf("\nbinary function=%s:\n ",f) + every t1 := (&null | TRUE | FALSE | UNKNOWN) do { + printf(" %s : ",showtrit(\t1)) + every t2 := (TRUE | FALSE | UNKNOWN | &null) do { + if /t1 then printf(" %s",showtrit(\t2)|"\n") + else printf(" %s",showtrit(f(t1,\t2))|"\n") + } + } + } +end + +procedure showtrit(a) #: return printable trit of error if invalid +return case a of {TRUE:"T";FALSE:"F";UNKNOWN:"?";default:runerr(205,a)} +end + +procedure istrit(a) #: return value of trit or error if invalid +return (TRUE|FALSE|UNKNOWN|runerr(205,a)) = a +end + +procedure not3(a) #: not of trit or error if invalid +return FALSE * istrit(a) +end + +procedure and3(a,b) #: and of two trits or error if invalid +return min(istrit(a),istrit(b)) +end + +procedure or3(a,b) #: or of two trits or error if invalid +return max(istrit(a),istrit(b)) +end + +procedure eq3(a,b) #: equals of two trits or error if invalid +return istrit(a) * istrit(b) +end + +procedure ifthen3(a,b) #: if trit then trit or error if invalid +return case istrit(a) of { TRUE: istrit(b) ; UNKNOWN: or3(a,b); FALSE: TRUE } +end + +procedure xor3(a,b) #: xor of two trits or error if invalid +return not3(eq3(a,b)) +end diff --git a/Task/Ternary-logic/J/ternary-logic-1.j b/Task/Ternary-logic/J/ternary-logic-1.j new file mode 100644 index 0000000000..1a0badb25f --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-1.j @@ -0,0 +1,5 @@ +not=: -. +and=: <. +or =: >. +if =: (>. -.)"0~ +eq =: (<.&-. >. <.)"0 diff --git a/Task/Ternary-logic/J/ternary-logic-2.j b/Task/Ternary-logic/J/ternary-logic-2.j new file mode 100644 index 0000000000..a54ef58117 --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-2.j @@ -0,0 +1,22 @@ + not 0 0.5 1 +1 0.5 0 + + 0 0.5 1 and/ 0 0.5 1 +0 0 0 +0 0.5 0.5 +0 0.5 1 + + 0 0.5 1 or/ 0 0.5 1 + 0 0.5 1 +0.5 0.5 1 + 1 1 1 + + 0 0.5 1 if/ 0 0.5 1 + 1 1 1 +0.5 0.5 1 + 0 0.5 1 + + 0 0.5 1 eq/ 0 0.5 1 + 1 0.5 0 +0.5 0.5 0.5 + 0 0.5 1 diff --git a/Task/Ternary-logic/J/ternary-logic-3.j b/Task/Ternary-logic/J/ternary-logic-3.j new file mode 100644 index 0000000000..7674295f3d --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-3.j @@ -0,0 +1,5 @@ +not=: -. +and=: * +or=: *&.-. +if =: (or -.)"0~ +eq =: (*&-. or *)"0 diff --git a/Task/Ternary-logic/J/ternary-logic-4.j b/Task/Ternary-logic/J/ternary-logic-4.j new file mode 100644 index 0000000000..7c4f84eb25 --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-4.j @@ -0,0 +1,22 @@ + not 0 0.5 1 +1 0.5 0 + + 0 0.5 1 and/ 0 0.5 1 +0 0 0 +0 0.25 0.5 +0 0.5 1 + + 0 0.5 1 or/ 0 0.5 1 + 0 0.5 1 +0.5 0.75 1 + 1 1 1 + + 0 0.5 1 if/ 0 0.5 1 + 1 1 1 +0.5 0.75 1 + 0 0.5 1 + + 0 0.5 1 eq/ 0 0.5 1 + 1 0.5 0 +0.5 0.4375 0.5 + 0 0.5 1 diff --git a/Task/Ternary-logic/J/ternary-logic-5.j b/Task/Ternary-logic/J/ternary-logic-5.j new file mode 100644 index 0000000000..e0394bbd32 --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-5.j @@ -0,0 +1,2 @@ +and=: *. +or=: +. diff --git a/Task/Ternary-logic/J/ternary-logic-6.j b/Task/Ternary-logic/J/ternary-logic-6.j new file mode 100644 index 0000000000..6b42f323ba --- /dev/null +++ b/Task/Ternary-logic/J/ternary-logic-6.j @@ -0,0 +1,9 @@ + 0 0.5 1 and/ 0 0.5 1 +0 0 0 +0 0.5 1 +0 1 1 + + 0 0.5 1 or/ 0 0.5 1 + 0 0.5 1 +0.5 0.5 0.5 + 1 0.5 1 diff --git a/Task/Ternary-logic/Java/ternary-logic.java b/Task/Ternary-logic/Java/ternary-logic.java new file mode 100644 index 0000000000..d6d54b2745 --- /dev/null +++ b/Task/Ternary-logic/Java/ternary-logic.java @@ -0,0 +1,68 @@ +public class Logic{ + public static enum Trit{ + TRUE, MAYBE, FALSE; + + public Trit and(Trit other){ + if(this == TRUE){ + return other; + }else if(this == MAYBE){ + return (other == FALSE) ? FALSE : MAYBE; + }else{ + return FALSE; + } + } + + public Trit or(Trit other){ + if(this == TRUE){ + return TRUE; + }else if(this == MAYBE){ + return (other == TRUE) ? TRUE : MAYBE; + }else{ + return other; + } + } + + public Trit tIf(Trit other){ + if(this == TRUE){ + return other; + }else if(this == MAYBE){ + return (other == TRUE) ? TRUE : MAYBE; + }else{ + return TRUE; + } + } + + public Trit not(){ + if(this == TRUE){ + return FALSE; + }else if(this == MAYBE){ + return MAYBE; + }else{ + return TRUE; + } + } + + public Trit equals(Trit other){ + if(this == TRUE){ + return other; + }else if(this == MAYBE){ + return MAYBE; + }else{ + return other.not(); + } + } + } + public static void main(String[] args){ + for(Trit a:Trit.values()){ + System.out.println("not " + a + ": " + a.not()); + } + for(Trit a:Trit.values()){ + for(Trit b:Trit.values()){ + System.out.println(a+" and "+b+": "+a.and(b)+ + "\t "+a+" or "+b+": "+a.or(b)+ + "\t "+a+" implies "+b+": "+a.tIf(b)+ + "\t "+a+" = "+b+": "+a.equals(b)); + } + } + } +} diff --git a/Task/Ternary-logic/Liberty-BASIC/ternary-logic.liberty b/Task/Ternary-logic/Liberty-BASIC/ternary-logic.liberty new file mode 100644 index 0000000000..41c32ebe16 --- /dev/null +++ b/Task/Ternary-logic/Liberty-BASIC/ternary-logic.liberty @@ -0,0 +1,70 @@ +'ternary logic +'0 1 2 +'F ? T +'False Don't know True +'LB has NOT AND OR XOR, so we implement them. +'LB has no EQ, but XOR could be expressed via EQ. In 'normal' boolean at least. + +global tFalse, tDontKnow, tTrue +tFalse = 0 +tDontKnow = 1 +tTrue = 2 + +print "Short and long names for ternary logic values" +for i = tFalse to tTrue + print shortName3$(i);" ";longName3$(i) +next +print + +print "Single parameter functions" +print "x";" ";"=x";" ";"not(x)" +for i = tFalse to tTrue + print shortName3$(i);" ";shortName3$(i);" ";shortName3$(not3(i)) +next +print + +print "Double parameter fuctions" +print "x";" ";"y";" ";"x AND y";" ";"x OR y";" ";"x EQ y";" ";"x XOR y" +for a = tFalse to tTrue + for b = tFalse to tTrue + print shortName3$(a);" ";shortName3$(b);" "; _ + shortName3$(and3(a,b));" "; shortName3$(or3(a,b));" "; _ + shortName3$(eq3(a,b));" "; shortName3$(xor3(a,b)) + next +next + +function and3(a,b) + and3 = min(a,b) +end function + +function or3(a,b) + or3 = max(a,b) +end function + +function eq3(a,b) + select case + case a=tDontKnow or b=tDontKnow + eq3 = tDontKnow + case a=b + eq3 = tTrue + case else + eq3 = tFalse + end select +end function + +function xor3(a,b) + xor3 = not3(eq3(a,b)) +end function + +function not3(b) + not3 = 2-b +end function + +'------------------------------------------------ +function shortName3$(i) + shortName3$ = word$("F ? T", i+1) +end function + +function longName3$(i) + longName3$ = word$("False,Don't know,True", i+1, ",") +end function diff --git a/Task/Ternary-logic/Mathematica/ternary-logic-1.math b/Task/Ternary-logic/Mathematica/ternary-logic-1.math new file mode 100644 index 0000000000..4b5c8275d9 --- /dev/null +++ b/Task/Ternary-logic/Mathematica/ternary-logic-1.math @@ -0,0 +1,2 @@ +Maybe /: ! Maybe = Maybe; +Maybe /: (And | Or | Nand | Nor | Xor | Xnor | Implies | Equivalent)[Maybe, Maybe] = Maybe; diff --git a/Task/Ternary-logic/Mathematica/ternary-logic-2.math b/Task/Ternary-logic/Mathematica/ternary-logic-2.math new file mode 100644 index 0000000000..77c889ecc1 --- /dev/null +++ b/Task/Ternary-logic/Mathematica/ternary-logic-2.math @@ -0,0 +1,9 @@ +trits = {True, Maybe, False}; +Print@Grid[ + ArrayFlatten[{{{{Not}}, {{Null}}}, {List /@ trits, + List /@ Not /@ trits}}]]; +Do[Print@Grid[ + ArrayFlatten[{{{{operator}}, {{Null, Null, + Null}}}, {{{Null}}, {trits}}, {List /@ trits, + Outer[operator, trits, trits]}}]], {operator, {And, Or, Nand, + Nor, Xor, Xnor, Implies, Equivalent}}] diff --git a/Task/Ternary-logic/OCaml/ternary-logic-1.ocaml b/Task/Ternary-logic/OCaml/ternary-logic-1.ocaml new file mode 100644 index 0000000000..40e4ff6f45 --- /dev/null +++ b/Task/Ternary-logic/OCaml/ternary-logic-1.ocaml @@ -0,0 +1,44 @@ +type trit = True | False | Maybe + +let t_not = function + | True -> False + | False -> True + | Maybe -> Maybe + +let t_and a b = match (a,b) with + | (True,True) -> True + | (False,_) | (_,False) -> False + | _ -> Maybe + +let t_or a b = t_not (t_and (t_not a) (t_not b)) + +let t_eq a b = match (a,b) with + | (True,True) | (False,False) -> True + | (False,True) | (True,False) -> False + | _ -> Maybe + +let t_imply a b = t_or (t_not a) b + +let string_of_trit = function + | True -> "True" + | False -> "False" + | Maybe -> "Maybe" + +let () = + let values = [| True; Maybe; False |] in + let f = string_of_trit in + Array.iter (fun v -> Printf.printf "Not %s: %s\n" (f v) (f (t_not v))) values; + print_newline (); + let print op str = + Array.iter (fun a -> + Array.iter (fun b -> + Printf.printf "%s %s %s: %s\n" (f a) str (f b) (f (op a b)) + ) values + ) values; + print_newline () + in + print t_and "And"; + print t_or "Or"; + print t_imply "Then"; + print t_eq "Equiv"; +;; diff --git a/Task/Ternary-logic/OCaml/ternary-logic-2.ocaml b/Task/Ternary-logic/OCaml/ternary-logic-2.ocaml new file mode 100644 index 0000000000..0e3945ccf7 --- /dev/null +++ b/Task/Ternary-logic/OCaml/ternary-logic-2.ocaml @@ -0,0 +1,40 @@ +type trit = True | False | Maybe + +let to_bin = function True -> [true] | False -> [false] | Maybe -> [true;false] + +let eval f x = + List.fold_left (fun l c -> List.fold_left (fun m d -> ((d c) :: m)) l f) [] x + +let rec from_bin = + function [true] -> True | [false] -> False + | h :: t -> (match (h, from_bin t) with + (true,True) -> True | (false,False) -> False | _ -> Maybe) + | _ -> Maybe + +let to_ternary1 uop = fun x -> from_bin (eval [uop] (to_bin x)) +let to_ternary2 bop = fun x y -> from_bin (eval (eval [bop] (to_bin x)) (to_bin y)) + +let t_not = to_ternary1 (not) +let t_and = to_ternary2 (&&) +let t_or = to_ternary2 (||) +let t_equiv = to_ternary2 (=) +let t_imply = to_ternary2 (fun p q -> (not p) || q) + +let str = function True -> "True " | False -> "False" | Maybe -> "Maybe" +let iterv f = List.iter f [True; False; Maybe] + +let table1 s u = + print_endline ("\n"^s^":"); + iterv (fun v -> print_endline (" "^(str v)^" -> "^(str (u v))));; + +let table2 s b = + print_endline ("\n"^s^":"); + iterv (fun u -> + iterv (fun v -> + print_endline (" "^(str u)^" "^(str v)^" -> "^(str (b u v)))));; + +table1 "not" t_not;; +table2 "and" t_and;; +table2 "or" t_or;; +table2 "equiv" t_equiv;; +table2 "implies" t_imply;; diff --git a/Task/Ternary-logic/Pascal/ternary-logic.pascal b/Task/Ternary-logic/Pascal/ternary-logic.pascal new file mode 100644 index 0000000000..36c57d2592 --- /dev/null +++ b/Task/Ternary-logic/Pascal/ternary-logic.pascal @@ -0,0 +1,91 @@ +Program TernaryLogic (output); + +type + trit = (terTrue, terMayBe, terFalse); + +function terNot (a: trit): trit; + begin + case a of + terTrue: terNot := terFalse; + terMayBe: terNot := terMayBe; + terFalse: terNot := terTrue; + end; + end; + +function terAnd (a, b: trit): trit; + begin + terAnd := terMayBe; + if (a = terFalse) or (b = terFalse) then + terAnd := terFalse + else + if (a = terTrue) and (b = terTrue) then + terAnd := terTrue; + end; + +function terOr (a, b: trit): trit; + begin + terOr := terMayBe; + if (a = terTrue) or (b = terTrue) then + terOr := terTrue + else + if (a = terFalse) and (b = terFalse) then + terOr := terFalse; + end; + +function terEquals (a, b: trit): trit; + begin + if a = b then + terEquals := terTrue + else + if a <> b then + terEquals := terFalse; + if (a = terMayBe) or (b = terMayBe) then + terEquals := terMayBe; + end; + +function terIfThen (a, b: trit): trit; + begin + terIfThen := terMayBe; + if (a = terTrue) or (b = terFalse) then + terIfThen := terTrue + else + if (a = terFalse) and (b = terTrue) then + terIfThen := terFalse; + end; + +function terToStr(a: trit): string; + begin + case a of + terTrue: terToStr := 'True '; + terMayBe: terToStr := 'Maybe'; + terFalse: terToStr := 'False'; + end; + end; + +begin + writeln('Ternary logic test:'); + writeln; + writeln('NOT ', ' True ', ' Maybe', ' False'); + writeln(' ', terToStr(terNot(terTrue)), ' ', terToStr(terNot(terMayBe)), ' ', terToStr(terNot(terFalse))); + writeln; + writeln('AND ', ' True ', ' Maybe', ' False'); + writeln('True ', terToStr(terAnd(terTrue,terTrue)), ' ', terToStr(terAnd(terMayBe,terTrue)), ' ', terToStr(terAnd(terFalse,terTrue))); + writeln('Maybe ', terToStr(terAnd(terTrue,terMayBe)), ' ', terToStr(terAnd(terMayBe,terMayBe)), ' ', terToStr(terAnd(terFalse,terMayBe))); + writeln('False ', terToStr(terAnd(terTrue,terFalse)), ' ', terToStr(terAnd(terMayBe,terFalse)), ' ', terToStr(terAnd(terFalse,terFalse))); + writeln; + writeln('OR ', ' True ', ' Maybe', ' False'); + writeln('True ', terToStr(terOR(terTrue,terTrue)), ' ', terToStr(terOR(terMayBe,terTrue)), ' ', terToStr(terOR(terFalse,terTrue))); + writeln('Maybe ', terToStr(terOR(terTrue,terMayBe)), ' ', terToStr(terOR(terMayBe,terMayBe)), ' ', terToStr(terOR(terFalse,terMayBe))); + writeln('False ', terToStr(terOR(terTrue,terFalse)), ' ', terToStr(terOR(terMayBe,terFalse)), ' ', terToStr(terOR(terFalse,terFalse))); + writeln; + writeln('IFTHEN', ' True ', ' Maybe', ' False'); + writeln('True ', terToStr(terIfThen(terTrue,terTrue)), ' ', terToStr(terIfThen(terMayBe,terTrue)), ' ', terToStr(terIfThen(terFalse,terTrue))); + writeln('Maybe ', terToStr(terIfThen(terTrue,terMayBe)), ' ', terToStr(terIfThen(terMayBe,terMayBe)), ' ', terToStr(terIfThen(terFalse,terMayBe))); + writeln('False ', terToStr(terIfThen(terTrue,terFalse)), ' ', terToStr(terIfThen(terMayBe,terFalse)), ' ', terToStr(terIfThen(terFalse,terFalse))); + writeln; + writeln('EQUAL ', ' True ', ' Maybe', ' False'); + writeln('True ', terToStr(terEquals(terTrue,terTrue)), ' ', terToStr(terEquals(terMayBe,terTrue)), ' ', terToStr(terEquals(terFalse,terTrue))); + writeln('Maybe ', terToStr(terEquals(terTrue,terMayBe)), ' ', terToStr(terEquals(terMayBe,terMayBe)), ' ', terToStr(terEquals(terFalse,terMayBe))); + writeln('False ', terToStr(terEquals(terTrue,terFalse)), ' ', terToStr(terEquals(terMayBe,terFalse)), ' ', terToStr(terEquals(terFalse,terFalse))); + writeln; +end. diff --git a/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 b/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 new file mode 100644 index 0000000000..7926aebd61 --- /dev/null +++ b/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 @@ -0,0 +1,9 @@ +enum Trit ; + +sub prefix:<¬> (Trit $a) { Trit(1-($a-1)) } + +sub infix:<∧> is equiv(&infix:<*>) (Trit $a, Trit $b) { $a min $b } +sub infix:<∨> is equiv(&infix:<+>) (Trit $a, Trit $b) { $a max $b } + +sub infix:<→> is equiv(&infix:<..>) (Trit $a, Trit $b) { ¬$a max $b } +sub infix:<≡> is equiv(&infix:) (Trit $a, Trit $b) { Trit(1 + ($a-1) * ($b-1)) } diff --git a/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 b/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 new file mode 100644 index 0000000000..197cf8046f --- /dev/null +++ b/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 @@ -0,0 +1,35 @@ +say '¬'; +say "Too {¬Too}"; +say "Moo {¬Moo}"; +say "Foo {¬Foo}"; + +sub tbl (&op,$name) { + say ''; + say "$name Too Moo Foo"; + say " ╔═══════════"; + say "Too║{op Too,Too} {op Too,Moo} {op Too,Foo}"; + say "Moo║{op Moo,Too} {op Moo,Moo} {op Moo,Foo}"; + say "Foo║{op Foo,Too} {op Foo,Moo} {op Foo,Foo}"; +} + +tbl(&infix:<∧>, '∧'); +tbl(&infix:<∨>, '∨'); +tbl(&infix:<→>, '→'); +tbl(&infix:<≡>, '≡'); + +say ''; +say 'Precedence tests should all print "Too":'; +say ~( + Foo ∧ Too ∨ Too ≡ Too, + Foo ∧ (Too ∨ Too) ≡ Foo, + Too ∨ Too ∧ Foo ≡ Too, + (Too ∨ Too) ∧ Foo ≡ Foo, + + ¬Too ∧ Too ∨ Too ≡ Too, + ¬Too ∧ (Too ∨ Too) ≡ ¬Too, + Too ∨ Too ∧ ¬Too ≡ Too, + (Too ∨ Too) ∧ ¬Too ≡ ¬Too, + + Foo ∧ Too ∨ Foo → Foo ≡ Too, + Foo ∧ Too ∨ Too → Foo ≡ Foo, +); diff --git a/Task/Ternary-logic/Perl/ternary-logic-1.pl b/Task/Ternary-logic/Perl/ternary-logic-1.pl new file mode 100644 index 0000000000..de12ba3737 --- /dev/null +++ b/Task/Ternary-logic/Perl/ternary-logic-1.pl @@ -0,0 +1,70 @@ +package Trit; + +# -1 = false ; 0 = maybe ; 1 = true + +use Exporter 'import'; + +our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe); +our %EXPORT_TAGS = ( + all => \@EXPORT_OK, + const => [qw(TRUE FALSE MAYBE)], + bool => [qw(is_true is_false is_maybe)], +); + +use List::Util qw(min max); + +use overload +'=' => sub { $_[0]->clone() }, +'<=>'=> sub { $_[0]->cmp($_[1]) }, +'cmp'=> sub { $_[0]->cmp($_[1]) }, +'==' => sub { ${$_[0]} == ${$_[1]} }, +'eq' => sub { $_[0]->equiv($_[1]) }, +'>' => sub { ${$_[0]} > ${$_[1]} }, +'<' => sub { ${$_[0]} < ${$_[1]} }, +'>=' => sub { ${$_[0]} >= ${$_[1]} }, +'<=' => sub { ${$_[0]} <= ${$_[1]} }, +'|' => sub { $_[0]->or($_[1]) }, +'&' => sub { $_[0]->and($_[1]) }, +'!' => sub { $_[0]->not() }, +'~' => sub { $_[0]->not() }, +'""' => sub { $_[0]->tostr() }, +'0+' => sub { $_[0]->tonum() }, +; + +sub new +{ + my ($class, $v) = @_; + my $ret = + !defined($v) ? 0 : + $v eq 'true' ? 1 : + $v eq 'false'? -1 : + $v eq 'maybe'? 0 : + $v > 0 ? 1 : + $v < 0 ? -1 : + 0; + return bless \$ret, $class; +} + +sub TRUE() { new Trit( 1) } +sub FALSE() { new Trit(-1) } +sub MAYBE() { new Trit( 0) } + +sub clone +{ + my $ret = ${$_[0]}; + return bless \$ret, ref($_[0]); +} + +sub tostr { ${$_[0]} > 0 ? "true" : ${$_[0]} < 0 ? "false" : "maybe" } +sub tonum { ${$_[0]} } + +sub is_true { ${$_[0]} > 0 } +sub is_false { ${$_[0]} < 0 } +sub is_maybe { ${$_[0]} == 0 } + +sub cmp { ${$_[0]} <=> ${$_[1]} } +sub not { new Trit(-${$_[0]}) } +sub and { new Trit(min(${$_[0]}, ${$_[1]}) ) } +sub or { new Trit(max(${$_[0]}, ${$_[1]}) ) } + +sub equiv { new Trit( ${$_[0]} * ${$_[1]} ) } diff --git a/Task/Ternary-logic/Perl/ternary-logic-2.pl b/Task/Ternary-logic/Perl/ternary-logic-2.pl new file mode 100644 index 0000000000..dc10816d87 --- /dev/null +++ b/Task/Ternary-logic/Perl/ternary-logic-2.pl @@ -0,0 +1,43 @@ +use Trit ':all'; + +my @a = (TRUE(), MAYBE(), FALSE()); + +print "\na\tNOT a\n"; +print "$_\t".(!$_)."\n" for @a; # Example of use of prefix operator NOT. Tilde ~ also can be used. + + +print "\nAND\t".join("\t",@a)."\n"; +for my $a (@a) { + print $a; + for my $b (@a) { + print "\t".($a & $b); # Example of use of infix & (and) + } + print "\n"; +} + +print "\nOR\t".join("\t",@a)."\n"; +for my $a (@a) { + print $a; + for my $b (@a) { + print "\t".($a | $b); # Example of use of infix | (or) + } + print "\n"; +} + +print "\nEQV\t".join("\t",@a)."\n"; +for my $a (@a) { + print $a; + for my $b (@a) { + print "\t".($a eq $b); # Example of use of infix eq (equivalence) + } + print "\n"; +} + +print "\n==\t".join("\t",@a)."\n"; +for my $a (@a) { + print $a; + for my $b (@a) { + print "\t".($a == $b); # Example of use of infix == (equality) + } + print "\n"; +} diff --git a/Task/Ternary-logic/PicoLisp/ternary-logic-1.l b/Task/Ternary-logic/PicoLisp/ternary-logic-1.l new file mode 100644 index 0000000000..e5c9178f53 --- /dev/null +++ b/Task/Ternary-logic/PicoLisp/ternary-logic-1.l @@ -0,0 +1,25 @@ +(de 3not (A) + (or (=0 A) (not A)) ) + +(de 3and (A B) + (cond + ((=T A) B) + ((=0 A) (and B 0)) ) ) + +(de 3or (A B) + (cond + ((=T A) T) + ((=0 A) (or (=T B) 0)) + (T B) ) ) + +(de 3impl (A B) + (cond + ((=T A) B) + ((=0 A) (or (=T B) 0)) + (T T) ) ) + +(de 3equiv (A B) + (cond + ((=T A) B) + ((=0 A) 0) + (T (3not B)) ) ) diff --git a/Task/Ternary-logic/PicoLisp/ternary-logic-2.l b/Task/Ternary-logic/PicoLisp/ternary-logic-2.l new file mode 100644 index 0000000000..fc9b36af89 --- /dev/null +++ b/Task/Ternary-logic/PicoLisp/ternary-logic-2.l @@ -0,0 +1,7 @@ +(for X '(T 0 NIL) + (println 'not X '-> (3not X)) ) + +(for Fun '((and . 3and) (or . 3or) (implies . 3impl) (equivalent . 3equiv)) + (for X '(T 0 NIL) + (for Y '(T 0 NIL) + (println X (car Fun) Y '-> ((cdr Fun) X Y)) ) ) ) diff --git a/Task/Ternary-logic/Python/ternary-logic.py b/Task/Ternary-logic/Python/ternary-logic.py new file mode 100644 index 0000000000..f10c2d4b34 --- /dev/null +++ b/Task/Ternary-logic/Python/ternary-logic.py @@ -0,0 +1,129 @@ +class Trit(int): + def __new__(cls, value): + if value == 'TRUE': + value = 1 + elif value == 'FALSE': + value = 0 + elif value == 'MAYBE': + value = -1 + return super(Trit, cls).__new__(cls, value // (abs(value) or 1)) + + def __repr__(self): + if self > 0: + return 'TRUE' + elif self == 0: + return 'FALSE' + return 'MAYBE' + + def __str__(self): + return repr(self) + + def __bool__(self): + if self > 0: + return True + elif self == 0: + return False + else: + raise ValueError("invalid literal for bool(): '%s'" % self) + + def __or__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][1] + else: + try: + return _ttable[(self, Trit(bool(other)))][1] + except: + return NotImplemented + + def __ror__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][1] + else: + try: + return _ttable[(self, Trit(bool(other)))][1] + except: + return NotImplemented + + def __and__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][0] + else: + try: + return _ttable[(self, Trit(bool(other)))][0] + except: + return NotImplemented + + def __rand__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][0] + else: + try: + return _ttable[(self, Trit(bool(other)))][0] + except: + return NotImplemented + + def __xor__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][2] + else: + try: + return _ttable[(self, Trit(bool(other)))][2] + except: + return NotImplemented + + def __rxor__(self, other): + if isinstance(other, Trit): + return _ttable[(self, other)][2] + else: + try: + return _ttable[(self, Trit(bool(other)))][2] + except: + return NotImplemented + + def __invert__(self): + return _ttable[self] + + def __getattr__(self, name): + if name in ('_n', 'flip'): + # So you can do x._n == x.flip; the inverse of x + # In Python 'not' is strictly boolean so we can't write `not x` + # Same applies to keywords 'and' and 'or'. + return _ttable[self] + else: + raise AttributeError + + + +TRUE, FALSE, MAYBE = Trit(1), Trit(0), Trit(-1) + +_ttable = { + # A: -> flip_A + TRUE: FALSE, + FALSE: TRUE, + MAYBE: MAYBE, + # (A, B): -> (A_and_B, A_or_B, A_xor_B) + (MAYBE, MAYBE): (MAYBE, MAYBE, MAYBE), + (MAYBE, FALSE): (FALSE, MAYBE, MAYBE), + (MAYBE, TRUE): (MAYBE, TRUE, MAYBE), + (FALSE, MAYBE): (FALSE, MAYBE, MAYBE), + (FALSE, FALSE): (FALSE, FALSE, FALSE), + (FALSE, TRUE): (FALSE, TRUE, TRUE), + ( TRUE, MAYBE): (MAYBE, TRUE, MAYBE), + ( TRUE, FALSE): (FALSE, TRUE, TRUE), + ( TRUE, TRUE): ( TRUE, TRUE, FALSE), + } + + +values = ('FALSE', 'TRUE ', 'MAYBE') + +print("\nTrit logical inverse, '~'") +for a in values: + expr = '~%s' % a + print(' %s = %s' % (expr, eval(expr))) + +for op, ophelp in (('&', 'and'), ('|', 'or'), ('^', 'exclusive-or')): + print("\nTrit logical %s, '%s'" % (ophelp, op)) + for a in values: + for b in values: + expr = '%s %s %s' % (a, op, b) + print(' %s = %s' % (expr, eval(expr))) diff --git a/Task/Ternary-logic/REXX/ternary-logic.rexx b/Task/Ternary-logic/REXX/ternary-logic.rexx new file mode 100644 index 0000000000..3c6aa10bb0 --- /dev/null +++ b/Task/Ternary-logic/REXX/ternary-logic.rexx @@ -0,0 +1,196 @@ +/*REXX program displays a ternary truth table [true, false, maybe] */ +/* for the variables and one or more expressions. */ +/*Infix notation is supported with one character propositional constants*/ +/*variables (propositional constants) allowed: A──►Z, a──►z except u. */ +/*All propositional constants are case insensative (except lowercase v).*/ + +parse arg expression /*get expression from the C. L. */ +if expression\='' then do /*Got one? Then show user's stuff*/ + call truthTable expression /*show and tell T.T.*/ + exit /*we're all done with truth table*/ + end + +call truthTable "a & b ; AND" +call truthTable "a | b ; OR" +call truthTable "a ^ b ; XOR" +call truthTable "a ! b ; NOR" +call truthTable "a ¡ b ; NAND" +call truthTable "a xnor b ; XNOR" /*XNOR is the same as NXOR. */ +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────────truthTable subroutine────────────*/ +truthTable: procedure; parse arg $ ';' comm 1 $o; $o=strip($o) +$=translate(strip($),'|',"v"); $u=$; upper $u +$u=translate($u,'()()()',"[]{}«»"); $$.=0; PCs=; hdrPCs= +@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU + +@='ff'x /*─────────infix operators───────*/ +op.= /*a single quote (') wasn't */ + /* implemented for negation. */ +op.0 ='false boolFALSE' /*unconditionally FALSE */ +op.1 ='and and & *' /* AND, conjunction */ +op.2 ='naimpb NaIMPb' /*not A implies B */ +op.3 ='boolb boolB' /*B (value of) */ +op.4 ='nbimpa NbIMPa' /*not B implies A */ +op.5 ='boola boolA' /*A (value of) */ +op.6 ='xor xor && % ^' /* XOR, exclusive OR */ +op.7 ='or or | + v' /* OR, disjunction */ +op.8 ='nor nor ! ↓' /* NOR, not OR, Pierce operator */ +op.9 ='xnor xnor nxor' /*NXOR, not exclusive OR, not XOR*/ +op.10='notb notB' /*not B (value of) */ +op.11='bimpa bIMPa' /* B implies A */ +op.12='nota notA' /*not A (value of) */ +op.13='aimpb aIMPb' /* A implies B */ +op.14='nand nand ¡ ↑' /*NAND, not AND, Sheffer operator*/ +op.15='true boolTRUE' /*unconditionally TRUE */ + /*alphabetic names need changing.*/ +op.16='\ NOT ~ ─ . ¬' /* NOT, negation */ +op.17='> GT' /*conditional */ +op.18='>= GE ─> => ──> ==>' "1a"x /*conditional */ +op.19='< LT' /*conditional */ +op.20='<= LE <─ <= <── <==' /*conditional */ +op.21='\= NE ~= ─= .= ¬=' /*conditional */ +op.22='= EQ EQUAL EQUALS =' "1b"x /*biconditional */ +op.23='0 boolTRUE' /*TRUEness */ +op.24='1 boolFALSE' /*FALSEness */ + +op.25='NOT NOT NEG' /*not, neg */ + + do jj=0 while op.jj\=='' | jj<16 /*change opers──►what REXX likes.*/ + new=word(op.jj,1) + do kk=2 to words(op.jj) /*handle each token separately. */ + _=word(op.jj,kk); upper _ + if wordpos(_,$u)==0 then iterate /*no such animal in this string. */ + if datatype(new,'m') then new!=@ /*expresion needs transcribing. */ + else new!=new + $u=changestr(_,$u,new!) /*transcribe the function (maybe)*/ + if new!==@ then $u=changeFunc($u,@,new) /*use internal bool name.*/ + end /*kk*/ + end /*jj*/ + +$u=translate($u, '()', "{}") /*finish cleaning up transcribing*/ + do jj=1 for length(@abcU) /*see what variables are used. */ + _=substr(@abcU,jj,1) /*use available upercase alphabet*/ + if pos(_,$u)==0 then iterate /*found one? No, keep looking. */ + $$.jj=2 /*found: set upper bound for it.*/ + PCs=PCs _ /*also, add to propositional cons*/ + hdrPCs=hdrPCS center(_,length('false')) /*build a PC header.*/ + end /*jj*/ +$u=PCs '('$u")" /*separate PCs from expression. */ +ptr='_────►_' /*a pointer for the truth table. */ +hdrPCs=substr(hdrPCs,2) /*create a header for the PCs. */ +say hdrPCs left('',length(ptr)-1) $o /*display PC header + expression.*/ +say copies('───── ',words(PCs)) left('',length(ptr)-2) copies('─',length($o)) + /*Note: "true"s: right─justified*/ + do a=0 to $$.1 + do b=0 to $$.2 + do c=0 to $$.3 + do d=0 to $$.4 + do e=0 to $$.5 + do f=0 to $$.6 + do g=0 to $$.7 + do h=0 to $$.8 + do i=0 to $$.9 + do j=0 to $$.10 + do k=0 to $$.11 + do l=0 to $$.12 + do m=0 to $$.13 + do n=0 to $$.14 + do o=0 to $$.15 + do p=0 to $$.16 + do q=0 to $$.17 + do r=0 to $$.18 + do s=0 to $$.19 + do t=0 to $$.20 + do u=0 to $$.21 + do !=0 to $$.22 + do w=0 to $$.23 + do x=0 to $$.24 + do y=0 to $$.25 + do z=0 to $$.26 + interpret '_=' $u /*evaluate truth T.*/ + _=changestr(0,_,'false') /*convert 0──►false*/ + _=changestr(1,_,'_true') /*convert 1──►_true*/ + _=changestr(2,_,'maybe') /*convert 2──►maybe*/ + _=insert(ptr,_,wordindex(_,words(_))-1) /*──►*/ + say translate(_,,'_') /*display truth tab*/ + end /*z*/ + end /*y*/ + end /*x*/ + end /*w*/ + end /*v*/ + end /*u*/ + end /*t*/ + end /*s*/ + end /*r*/ + end /*q*/ + end /*p*/ + end /*o*/ + end /*n*/ + end /*m*/ + end /*l*/ + end /*k*/ + end /*j*/ + end /*i*/ + end /*h*/ + end /*g*/ + end /*f*/ + end /*e*/ + end /*d*/ + end /*c*/ + end /*b*/ + end /*a*/ + +say; return +/*─────────────────────────────────────SCAN subroutine──────────────────*/ +scan: procedure; parse arg x,at; L=length(x); t=L; lp=0; apost=0; quote=0 +if at<0 then do; t=1; x=translate(x,'()',")("); end + do j=abs(at) to t by sign(at); _=substr(x,j,1); __=substr(x,j,2) + if quote then do; if _\=='"' then iterate + if __=='""' then do; j=j+1; iterate; end + quote=0; iterate + end + if apost then do; if _\=="'" then iterate + if __=="''" then do; j=j+1; iterate; end + apost=0; iterate + end + if _=='"' then do; quote=1; iterate; end + if _=="'" then do; apost=1; iterate; end + if _==' ' then iterate + if _=='(' then do; lp=lp+1; iterate; end + if lp\==0 then do; if _==')' then lp=lp-1; iterate; end + if datatype(_,'U') then return j-(at<0) + if at<0 then return j+1 + end /*j*/ +return min(j,L) +/*─────────────────────────────────────changeFunc subroutine────────────*/ +changeFunc: procedure; parse arg z,fC,newF; funcPos=0 + do forever + funcPos=pos(fC,z,funcPos+1); if funcPos==0 then return z + origPos=funcPos + z=changestr(fC,z,",'"newF"',") + funcPos=funcPos+length(newF)+4 + where=scan(z, funcPos) ; z=insert( '}', z, where) + where=scan(z, 1-origPos) ; z=insert('trit{', z, where) + end /*forever*/ +/*─────────────────────────────────────TRIT subroutine──────────────────*/ +trit: procedure; arg a,$,b; v=\(a==2|b==2); o= a==1|b==1; z= a==0|b==0 + select + when $=='FALSE' then return 0 + when $=='AND' then if v then return a & b; else return 2 + when $=='NAIMPB' then if v then return \(\a & \b); else return 2 + when $=='BOOLB' then return b + when $=='NBIMPA' then if v then return \(\b & \a); else return 2 + when $=='BOOLA' then return a + when $=='XOR' then if v then return a && b ; else return 2 + when $=='OR' then if v then return a | b ; else + if o then return 1; else return 2 + when $=='NOR' then if v then return \(a | b) ; else return 2 + when $=='XNOR' then if v then return \(a && b) ; else return 2 + when $=='NOTB' then if v then return \b ; else return 2 + when $=='NOTA' then if v then return \a ; else return 2 + when $=='AIMPB' then if v then return \(a & \b) ; else return 2 + when $=='NAND' then if v then return \(a & b) ; else + if z then return 1; else return 2 + when $=='TRUE' then return 1 + otherwise return -13 /*error, unknown function.*/ + end /*select*/ diff --git a/Task/Ternary-logic/Racket/ternary-logic.rkt b/Task/Ternary-logic/Racket/ternary-logic.rkt new file mode 100644 index 0000000000..729d4eac68 --- /dev/null +++ b/Task/Ternary-logic/Racket/ternary-logic.rkt @@ -0,0 +1,62 @@ +#lang typed/racket + +; we can't add a maybe which is special in the same way as #t and #f, +; so we'll just use symbols to make our own +(define-type trit (U 'true 'false 'maybe)) + +(: not (trit -> trit)) +(define (not a) + (case a + [(true) 'false] + [(maybe) 'maybe] + [(false) 'true])) + +(: and (trit trit -> trit)) +(define (and a b) + (case a + [(false) 'false] + [(maybe) (case b + [(false) 'false] + [else 'maybe])] + [(true) (case b + [(true) 'true] + [(maybe) 'maybe] + [(false) 'false])])) + +(: or (trit trit -> trit)) +(define (or a b) + (case a + [(true) 'true] + [(maybe) (case b + [(true) 'true] + [else 'maybe])] + [(false) (case b + [(true) 'true] + [(maybe) 'maybe] + [(false) 'false])])) + +(: ifthen (trit trit -> trit)) +(define (ifthen a b) + (case b + [(true) 'true] + [(maybe) (case a + [(false) 'true] + [else 'maybe])] + [(false) (case a + [(true) 'false] + [(maybe) 'maybe] + [(false) 'true])])) + +(: iff (trit trit -> trit)) +(define (iff a b) + (case a + [(maybe) 'maybe] + [(true) b] + [(false) (not b)])) + +(for: : Void ([a (in-list '(true maybe false))]) + (printf "~a ~a = ~a~n" (object-name not) a (not a))) +(for: : Void ([proc (in-list (list and or ifthen iff))]) + (for*: : Void ([a (in-list '(true maybe false))] + [b (in-list '(true maybe false))]) + (printf "~a ~a ~a = ~a~n" a (object-name proc) b (proc a b)))) diff --git a/Task/Ternary-logic/Ruby/ternary-logic-1.rb b/Task/Ternary-logic/Ruby/ternary-logic-1.rb new file mode 100644 index 0000000000..e9f0588a26 --- /dev/null +++ b/Task/Ternary-logic/Ruby/ternary-logic-1.rb @@ -0,0 +1,85 @@ +# trit.rb - ternary logic +# http://rosettacode.org/wiki/Ternary_logic + +require 'singleton' + +# MAYBE, the only instance of MaybeClass, enables a system of ternary +# logic using TrueClass#trit, MaybeClass#trit and FalseClass#trit. +# +# !a.trit # ternary not +# a.trit & b # ternary and +# a.trit | b # ternary or +# a.trit ^ b # ternary exclusive or +# a.trit == b # ternary equal +# +# Though +true+ and +false+ are internal Ruby values, +MAYBE+ is not. +# Programs may want to assign +maybe = MAYBE+ in scopes that use +# ternary logic. Then programs can use +true+, +maybe+ and +false+. +class MaybeClass + include Singleton + + # maybe.to_s # => "maybe" + def to_s; "maybe"; end +end + +MAYBE = MaybeClass.instance + +class TrueClass + TritMagic = Object.new + class << TritMagic + def index; 0; end + def !; false; end + def & other; other; end + def | other; true; end + def ^ other; [false, MAYBE, true][other.trit.index]; end + def == other; other; end + end + + # Performs ternary logic. See MaybeClass. + # !true.trit # => false + # true.trit & obj # => obj + # true.trit | obj # => true + # true.trit ^ obj # => false, maybe or true + # true.trit == obj # => obj + def trit; TritMagic; end +end + +class MaybeClass + TritMagic = Object.new + class << TritMagic + def index; 1; end + def !; MAYBE; end + def & other; [MAYBE, MAYBE, false][other.trit.index]; end + def | other; [true, MAYBE, MAYBE][other.trit.index]; end + def ^ other; MAYBE; end + def == other; MAYBE; end + end + + # Performs ternary logic. See MaybeClass. + # !maybe.trit # => maybe + # maybe.trit & obj # => maybe or false + # maybe.trit | obj # => true or maybe + # maybe.trit ^ obj # => maybe + # maybe.trit == obj # => maybe + def trit; TritMagic; end +end + +class FalseClass + TritMagic = Object.new + class << TritMagic + def index; 2; end + def !; true; end + def & other; false; end + def | other; other; end + def ^ other; other; end + def == other; [false, MAYBE, true][other.trit.index]; end + end + + # Performs ternary logic. See MaybeClass. + # !false.trit # => true + # false.trit & obj # => false + # false.trit | obj # => obj + # false.trit ^ obj # => obj + # false.trit == obj # => false, maybe or true + def trit; TritMagic; end +end diff --git a/Task/Ternary-logic/Ruby/ternary-logic-2.rb b/Task/Ternary-logic/Ruby/ternary-logic-2.rb new file mode 100644 index 0000000000..ac885f81eb --- /dev/null +++ b/Task/Ternary-logic/Ruby/ternary-logic-2.rb @@ -0,0 +1,17 @@ +$ irb +irb(main):001:0> require './trit' +=> true +irb(main):002:0> maybe = MAYBE +=> maybe +irb(main):003:0> !true.trit +=> false +irb(main):004:0> !maybe.trit +=> maybe +irb(main):005:0> maybe.trit & false +=> false +irb(main):006:0> maybe.trit | true +=> true +irb(main):007:0> false.trit == true +=> false +irb(main):008:0> false.trit == maybe +=> maybe diff --git a/Task/Ternary-logic/Ruby/ternary-logic-3.rb b/Task/Ternary-logic/Ruby/ternary-logic-3.rb new file mode 100644 index 0000000000..bbd4043a3d --- /dev/null +++ b/Task/Ternary-logic/Ruby/ternary-logic-3.rb @@ -0,0 +1,8 @@ +require 'trit' +maybe = MAYBE + +[true, maybe, false].each do |a| + [true, maybe, false].each do |b| + printf "%5s ^ %5s => %5s\n", a, b, a.trit ^ b + end +end diff --git a/Task/Ternary-logic/Run-BASIC/ternary-logic.run b/Task/Ternary-logic/Run-BASIC/ternary-logic.run new file mode 100644 index 0000000000..acce5391bf --- /dev/null +++ b/Task/Ternary-logic/Run-BASIC/ternary-logic.run @@ -0,0 +1,58 @@ +testFalse = 0 ' F +testDoNotKnow = 1 ' ? +testTrue = 2 ' T + +print "Short and long names for ternary logic values" +for i = testFalse to testTrue + print shortName3$(i);" ";longName3$(i) +next i +print + +print "Single parameter functions" +print "x";" ";"=x";" ";"not(x)" +for i = testFalse to testTrue + print shortName3$(i);" ";shortName3$(i);" ";shortName3$(not3(i)) +next +print + +print "Double parameter fuctions" +html "" +for a = testFalse to testTrue + for b = testFalse to testTrue + html "" + next +next +html "
xyx AND yx OR yx EQ yx XOR y
" + html shortName3$(a); "";shortName3$(b); "" + html shortName3$(and3(a,b));"";shortName3$(or3(a,b)); "" + html shortName3$(eq3(a,b)); "";shortName3$(xor3(a,b));"
" +function and3(a,b) + and3 = min(a,b) +end function + +function or3(a,b) + or3 = max(a,b) +end function + +function eq3(a,b) + eq3 = testFalse + if a = tDontKnow or b = tDontKnow then eq3 = tDontKnow + if a = b then eq3 = testTrue +end function + +function xor3(a,b) + xor3 = not3(eq3(a,b)) +end function + +function not3(b) + not3 = 2-b +end function + +'------------------------------------------------ +function shortName3$(i) + shortName3$ = word$("F ? T", i+1) +end function + +function longName3$(i) + longName3$ = word$("False,Don't know,True", i+1, ",") +end function diff --git a/Task/Ternary-logic/Scala/ternary-logic.scala b/Task/Ternary-logic/Scala/ternary-logic.scala new file mode 100644 index 0000000000..11a7a9a9ee --- /dev/null +++ b/Task/Ternary-logic/Scala/ternary-logic.scala @@ -0,0 +1,33 @@ +sealed trait Trit { self => + def nand(that:Trit):Trit=(this,that) match { + case (TFalse, _) => TTrue + case (_, TFalse) => TTrue + case (TMaybe, _) => TMaybe + case (_, TMaybe) => TMaybe + case _ => TFalse + } + + def nor(that:Trit):Trit = this.or(that).not() + def and(that:Trit):Trit = this.nand(that).not() + def or(that:Trit):Trit = this.not().nand(that.not()) + def not():Trit = this.nand(this) + def imply(that:Trit):Trit = this.nand(that.not()) + def equiv(that:Trit):Trit = this.and(that).or(this.nor(that)) +} +case object TTrue extends Trit +case object TMaybe extends Trit +case object TFalse extends Trit + +object TernaryLogic extends App { + val v=List(TTrue, TMaybe, TFalse) + println("- NOT -") + for(a<-v) println("%6s => %6s".format(a, a.not)) + println("\n- AND -") + for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a and b)) + println("\n- OR -") + for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a or b)) + println("\n- Imply -") + for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a imply b)) + println("\n- Equiv -") + for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a equiv b)) +} diff --git a/Task/Ternary-logic/Seed7/ternary-logic.seed7 b/Task/Ternary-logic/Seed7/ternary-logic.seed7 new file mode 100644 index 0000000000..6c4cda63aa --- /dev/null +++ b/Task/Ternary-logic/Seed7/ternary-logic.seed7 @@ -0,0 +1,120 @@ +$ include "seed7_05.s7i"; + +const type: trit is new enum + False, Maybe, True + end enum; + +# Enum types define comparisons (=, <, >, <=, >=, <>) and +# the conversions ord and conv. + +const func string: str (in trit: aTrit) is + return [] ("False", "Maybe", "True")[succ(ord(aTrit))]; + +enable_output(trit); # Allow writing trit values + +const array trit: tritNot is [] (True, Maybe, False); +const array array trit: tritAnd is [] ( + [] (False, False, False), + [] (False, Maybe, Maybe), + [] (False, Maybe, True )); +const array array trit: tritOr is [] ( + [] (False, Maybe, True ), + [] (Maybe, Maybe, True ), + [] (True, True, True )); +const array array trit: tritXor is [] ( + [] (False, Maybe, True ), + [] (Maybe, Maybe, Maybe), + [] (True, Maybe, False)); +const array array trit: tritImplies is [] ( + [] (True, True, True ), + [] (Maybe, Maybe, True ), + [] (False, Maybe, True )); +const array array trit: tritEquiv is [] ( + [] (True, Maybe, False), + [] (Maybe, Maybe, Maybe), + [] (False, Maybe, True )); + +const func trit: not (in trit: aTrit) is + return tritNot[succ(ord(aTrit))]; + +const func trit: (in trit: aTrit1) and (in trit: aTrit2) is + return tritAnd[succ(ord(aTrit1))][succ(ord(aTrit2))]; + +const func trit: (in trit: aTrit1) and (ref func trit: aTrit2) is func + result + var trit: res is False; + begin + if aTrit1 = True then + res := aTrit2; + elsif aTrit1 = Maybe and aTrit2 <> False then + res := Maybe; + end if; + end func; + +const func trit: (in trit: aTrit1) or (in trit: aTrit2) is + return tritOr[succ(ord(aTrit1))][succ(ord(aTrit2))]; + +const func trit: (in trit: aTrit1) or (ref func trit: aTrit2) is func + result + var trit: res is True; + begin + if aTrit1 = False then + res := aTrit2; + elsif aTrit1 = Maybe and aTrit2 <> True then + res := Maybe; + end if; + end func; + +$ syntax expr: .().xor.() is -> 15; +const func trit: (in trit: aTrit1) xor (in trit: aTrit2) is + return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))]; + +const func trit: (in trit: aTrit1) -> (in trit: aTrit2) is + return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))]; + +const func trit: (in trit: aTrit1) == (in trit: aTrit2) is + return tritEquiv[succ(ord(aTrit1))][succ(ord(aTrit2))]; + +const func trit: rand (in trit: low, in trit: high) is + return trit conv (rand(ord(low), ord(high))); + +const func integer: compare (in trit: aTrit1, in trit: aTrit2) is + return compare(ord(aTrit1), ord(aTrit2)); + +const func integer: hashCode (in trit: aTrit) is + return hashCode(ord(aTrit)); + +# Begin of test code + +var trit: operand1 is False; +var trit: operand2 is False; + +const proc: writeTable (ref func trit: tritExpr, in string: name) is func + begin + writeln; + writeln(" " <& name rpad 7 <& " | False Maybe True"); + writeln("---------+---------------------"); + for operand1 range False to True do + write(" " <& operand1 rpad 7 <& " | "); + for operand2 range False to True do + write(tritExpr rpad 7); + end for; + writeln; + end for; + end func; + +const proc: main is func + begin + writeln(" not" rpad 8 <& " | False Maybe True"); + writeln("---------+---------------------"); + write(" | "); + for operand1 range False to True do + write(not operand1 rpad 7); + end for; + writeln; + writeTable(operand1 and operand2, "and"); + writeTable(operand1 or operand2, "or"); + writeTable(operand1 xor operand2, "xor"); + writeTable(operand1 -> operand2, "->"); + writeTable(operand1 == operand2, "=="); + end func; diff --git a/Task/Ternary-logic/Tcl/ternary-logic-1.tcl b/Task/Ternary-logic/Tcl/ternary-logic-1.tcl new file mode 100644 index 0000000000..76d2385797 --- /dev/null +++ b/Task/Ternary-logic/Tcl/ternary-logic-1.tcl @@ -0,0 +1,67 @@ +package require Tcl 8.5 +namespace eval ternary { + # Code generator + proc maketable {name count values} { + set sep "" + for {set i 0; set c 97} {$i<$count} {incr i;incr c} { + set v [format "%c" $c] + lappend args $v; append key $sep "$" $v + set sep "," + } + foreach row [split $values \n] { + if {[llength $row]>1} { + lassign $row from to + lappend table $from [list return $to] + } + } + proc $name $args \ + [list ckargs $args]\;[concat [list switch -glob --] $key [list $table]] + namespace export $name + } + # Helper command to check argument syntax + proc ckargs argList { + foreach var $argList { + upvar 1 $var v + switch -exact -- $v { + true - maybe - false { + continue + } + default { + return -level 2 -code error "bad ternary value \"$v\"" + } + } + } + } + + # The "truth" tables; “*” means “anything” + maketable not 1 { + true false + maybe maybe + false true + } + maketable and 2 { + true,true true + false,* false + *,false false + * maybe + } + maketable or 2 { + true,* true + *,true true + false,false false + * maybe + } + maketable implies 2 { + false,* true + *,true true + true,false false + * maybe + } + maketable equiv 2 { + *,maybe maybe + maybe,* maybe + true,true true + false,false true + * false + } +} diff --git a/Task/Ternary-logic/Tcl/ternary-logic-2.tcl b/Task/Ternary-logic/Tcl/ternary-logic-2.tcl new file mode 100644 index 0000000000..350c36989e --- /dev/null +++ b/Task/Ternary-logic/Tcl/ternary-logic-2.tcl @@ -0,0 +1,10 @@ +namespace import ternary::* +puts "x /\\ y == x \\/ y" +puts " x | y || result" +puts "-------+-------++--------" +foreach x {true maybe false} { + foreach y {true maybe false} { + set z [equiv [and $x $y] [or $x $y]] + puts [format " %-5s | %-5s || %-5s" $x $y $z] + } +} diff --git a/Task/Test-a-function/0DESCRIPTION b/Task/Test-a-function/0DESCRIPTION new file mode 100644 index 0000000000..dcc74924ed --- /dev/null +++ b/Task/Test-a-function/0DESCRIPTION @@ -0,0 +1,2 @@ +{{omit from|BBC BASIC}} +Using a well known testing specific library/module/suite for your language, write some tests for your language's entry in [[Palindrome]]. If your language does not have a testing specific library well known to the language's community then state this or omit the language. diff --git a/Task/Test-a-function/1META.yaml b/Task/Test-a-function/1META.yaml new file mode 100644 index 0000000000..85a4119666 --- /dev/null +++ b/Task/Test-a-function/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Testing diff --git a/Task/Test-a-function/ACL2/test-a-function.acl2 b/Task/Test-a-function/ACL2/test-a-function.acl2 new file mode 100644 index 0000000000..a8720c385f --- /dev/null +++ b/Task/Test-a-function/ACL2/test-a-function.acl2 @@ -0,0 +1,36 @@ +(defun reverse-split-at-r (xs i ys) + (if (zp i) + (mv xs ys) + (reverse-split-at-r (rest xs) (1- i) + (cons (first xs) ys)))) + +(defun reverse-split-at (xs i) + (reverse-split-at-r xs i nil)) + +(defun is-palindrome (str) + (let* ((lngth (length str)) + (idx (floor lngth 2))) + (mv-let (xs ys) + (reverse-split-at (coerce str 'list) idx) + (if (= (mod lngth 2) 1) + (equal (rest xs) ys) + (equal xs ys))))) + +(include-book "testing" :dir :teachpacks) + +(check-expect (is-palindrome "abba") t) +(check-expect (is-palindrome "mom") t) +(check-expect (is-palindrome "dennis sinned") t) +(check-expect (is-palindrome "palindrome") nil) +(check-expect (is-palindrome "racecars") nil) + +(include-book "doublecheck" :dir :teachpacks) + +(defrandom random-palindrome () + (let ((chars (random-list-of (random-char)))) + (coerce (append chars (reverse chars)) + 'string))) + +(defproperty palindrome-test + (p :value (random-palindrome)) + (is-palindrome p)) diff --git a/Task/Test-a-function/Ada/test-a-function.ada b/Task/Test-a-function/Ada/test-a-function.ada new file mode 100644 index 0000000000..14415f06c4 --- /dev/null +++ b/Task/Test-a-function/Ada/test-a-function.ada @@ -0,0 +1,28 @@ +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/Test-a-function/AutoHotkey/test-a-function-1.ahk b/Task/Test-a-function/AutoHotkey/test-a-function-1.ahk new file mode 100644 index 0000000000..1eacd066d6 --- /dev/null +++ b/Task/Test-a-function/AutoHotkey/test-a-function-1.ahk @@ -0,0 +1,38 @@ +; assert.ahk +;; assert(a, b, test=2) +assert(a, b="blank", test=0) +{ + if (b = "blank") +{ + if !a + msgbox % "blank value" + return 0 +} + if equal_list(a, b, "`n") + return 0 + else + msgbox % test . ":`n" . a . "`nexpected:`n" . b +} + +!r::reload + +;; equal_list(a, b, delimiter) +equal_list(a, b, delimiter) +{ + loop, parse, b, %delimiter% + { + if instr(a, A_LoopField) + continue + else + return 0 + } + loop, parse, a, %delimiter% + { + if instr(b, A_LoopField) + continue + else + return 0 + } + + return 1 +} diff --git a/Task/Test-a-function/AutoHotkey/test-a-function-2.ahk b/Task/Test-a-function/AutoHotkey/test-a-function-2.ahk new file mode 100644 index 0000000000..77c563fdf9 --- /dev/null +++ b/Task/Test-a-function/AutoHotkey/test-a-function-2.ahk @@ -0,0 +1,21 @@ +assert(isPalindrome("in girum imus nocte et consumimur igni"), 1 +, "palindrome test") +assert(broken("in girum imus nocte et consumimur igni"), "works" +, "broken test") +/* +output: +--------------------------- +testPalindrome.ahk +--------------------------- +broken test: +broken +expected: +works +*/ + +broken(x){ +return "broken" +} + +#Include assert.ahk +#Include palindrome.ahk diff --git a/Task/Test-a-function/Brat/test-a-function.brat b/Task/Test-a-function/Brat/test-a-function.brat new file mode 100644 index 0000000000..c5b661adaf --- /dev/null +++ b/Task/Test-a-function/Brat/test-a-function.brat @@ -0,0 +1,24 @@ +include :assert + +palindrome? = { str | + str = str.downcase.sub /\s+/ "" + str == str.reverse +} + +setup name: "palindrome test" { + test "is a palindrome" { + assert { palindrome? "abba" } + } + + test "is not a palindrome" { + assert_false { palindrome? "abb" } + } + + test "is not a string" { + assert_fail { palindrome? 1001 } + } + + test "this test fails" { + assert { palindrome? "blah blah" } + } +} diff --git a/Task/Test-a-function/C-sharp/test-a-function-1.cs b/Task/Test-a-function/C-sharp/test-a-function-1.cs new file mode 100644 index 0000000000..bc047dbc04 --- /dev/null +++ b/Task/Test-a-function/C-sharp/test-a-function-1.cs @@ -0,0 +1,34 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PalindromeDetector.ConsoleApp; + +namespace PalindromeDetector.VisualStudioTests +{ + [TestClass] + public class VSTests + { + [TestMethod] + public void PalindromeDetectorCanUnderstandPalindrome() + { + //Microsoft.VisualStudio.QualityTools.UnitTestFramework v4.0.30319 + bool expected = true; + bool actual; + actual = Program.IsPalindrome("1"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindromeNonRecursive("1"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindrome("ingirumimusnocteetconsumimurigni"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindromeNonRecursive("ingirumimusnocteetconsumimurigni"); + Assert.AreEqual(expected, actual); + } + [TestMethod] + public void PalindromeDetecotryCanUnderstandNonPalindrome() + { + bool notExpected = true; + bool actual = Program.IsPalindrome("ThisIsNotAPalindrome"); + Assert.AreNotEqual(notExpected, actual); + actual = Program.IsPalindromeNonRecursive("ThisIsNotAPalindrome"); + Assert.AreNotEqual(notExpected, actual); + } + } +} diff --git a/Task/Test-a-function/C-sharp/test-a-function-2.cs b/Task/Test-a-function/C-sharp/test-a-function-2.cs new file mode 100644 index 0000000000..0617d4a384 --- /dev/null +++ b/Task/Test-a-function/C-sharp/test-a-function-2.cs @@ -0,0 +1,35 @@ +using NUnit.Framework; +using PalindromeDetector.ConsoleApp; + +namespace PalindromeDetector.VisualStudioTests +{ + [TestFixture] + public class NunitTests + { + [Test] + public void PalindromeDetectorCanUnderstandPalindrome() + { + //nunit.framework v2.0.50727 + bool expected = true; + bool actual; + actual = Program.IsPalindrome("1"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindromeNonRecursive("1"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindrome("ingirumimusnocteetconsumimurigni"); + Assert.AreEqual(expected, actual); + actual = Program.IsPalindromeNonRecursive("ingirumimusnocteetconsumimurigni"); + Assert.AreEqual(expected, actual); + } + [Test] + public void PalindromeDetectorUnderstandsNonPalindrome() + { + bool notExpected = true; + bool actual; + actual = Program.IsPalindrome("NotAPalindrome"); + Assert.AreEqual(notExpected, actual); + actual = Program.IsPalindromeNonRecursive("NotAPalindrome"); + Assert.AreEqual(notExpected, actual); + } + } +} diff --git a/Task/Test-a-function/C/test-a-function.c b/Task/Test-a-function/C/test-a-function.c new file mode 100644 index 0000000000..48e2fa9a88 --- /dev/null +++ b/Task/Test-a-function/C/test-a-function.c @@ -0,0 +1,8 @@ +#include +int IsPalindrome(char *Str); + +int main() +{ + assert(IsPalindrome("racecar")); + assert(IsPalindrome("alice")); +} diff --git a/Task/Test-a-function/Clojure/test-a-function.clj b/Task/Test-a-function/Clojure/test-a-function.clj new file mode 100644 index 0000000000..c2427d08fe --- /dev/null +++ b/Task/Test-a-function/Clojure/test-a-function.clj @@ -0,0 +1,7 @@ +(use 'clojure.test) + +(deftest test-palindrome? + (is (= true (palindrome? "amanaplanacanalpanama"))) + (is (= false (palindrome? "Test 1, 2, 3")))) + +(run-tests) diff --git a/Task/Test-a-function/D/test-a-function.d b/Task/Test-a-function/D/test-a-function.d new file mode 100644 index 0000000000..544434d8e5 --- /dev/null +++ b/Task/Test-a-function/D/test-a-function.d @@ -0,0 +1,5 @@ +unittest { + assert(isPalindrome("racecar")); + assert(isPalindrome("bob")); + assert(!isPalindrome("alice")); +} diff --git a/Task/Test-a-function/Delphi/test-a-function-1.delphi b/Task/Test-a-function/Delphi/test-a-function-1.delphi new file mode 100644 index 0000000000..6d579be540 --- /dev/null +++ b/Task/Test-a-function/Delphi/test-a-function-1.delphi @@ -0,0 +1,3 @@ + Assert(IsPalindrome('salàlas'), 'salàlas is a valid palindrome'); + Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome'); + Assert(not IsPalindrome('123'), '123 is not a valid palindrome'); diff --git a/Task/Test-a-function/Delphi/test-a-function-2.delphi b/Task/Test-a-function/Delphi/test-a-function-2.delphi new file mode 100644 index 0000000000..cbb40ae9a7 --- /dev/null +++ b/Task/Test-a-function/Delphi/test-a-function-2.delphi @@ -0,0 +1,3 @@ + Check(IsPalindrome('salàlas'), 'salàlas is a valid palindrome'); + Check(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome'); + Check(not IsPalindrome('123'), '123 is not a valid palindrome'); diff --git a/Task/Test-a-function/E/test-a-function.e b/Task/Test-a-function/E/test-a-function.e new file mode 100644 index 0000000000..5679eb3fbd --- /dev/null +++ b/Task/Test-a-function/E/test-a-function.e @@ -0,0 +1,50 @@ +#!/usr/bin/env rune + +? def isPalindrome(string :String) { +> def upper := string.toUpperCase() +> def last := upper.size() - 1 +> for i => c ? (upper[last - i] != c) in upper(0, upper.size() // 2) { +> return false +> } +> return true +> } + +? isPalindrome("") +# value: true + +? isPalindrome("a") +# value: true + +? isPalindrome("aa") +# value: true + +? isPalindrome("baa") +# value: false + +? isPalindrome("baab") +# value: true + +? isPalindrome("ba_ab") +# value: true + +? isPalindrome("ba_ ab") +# value: false + +? isPalindrome("ba _ ab") +# value: true + +? isPalindrome("ab"*2) +# value: false + +? def x := "ab" * 2**15; null + +? x.size() +# value: 65536 + +? def xreversed := "ba" * 2**15; null + +? isPalindrome(x + xreversed) +# value: true + +? (x + xreversed).size() +# value: 131072 diff --git a/Task/Test-a-function/Euphoria/test-a-function.euphoria b/Task/Test-a-function/Euphoria/test-a-function.euphoria new file mode 100644 index 0000000000..24b497289b --- /dev/null +++ b/Task/Test-a-function/Euphoria/test-a-function.euphoria @@ -0,0 +1,10 @@ +--unittest in standard library 4.0+ +include std/unittest.e +include palendrome.e --routines to be tested + +object p = "12321" + +test_equal("12321", 1, isPalindrome(p)) +test_equal("r12321", 1, isPalindrome(reverse(p))) + +test_report() diff --git a/Task/Test-a-function/Factor/test-a-function-1.factor b/Task/Test-a-function/Factor/test-a-function-1.factor new file mode 100644 index 0000000000..bf4b5bc244 --- /dev/null +++ b/Task/Test-a-function/Factor/test-a-function-1.factor @@ -0,0 +1,4 @@ +USING: kernel sequences ; +IN: palindrome + +: palindrome? ( string -- ? ) dup reverse = ; diff --git a/Task/Test-a-function/Factor/test-a-function-2.factor b/Task/Test-a-function/Factor/test-a-function-2.factor new file mode 100644 index 0000000000..cecf11961c --- /dev/null +++ b/Task/Test-a-function/Factor/test-a-function-2.factor @@ -0,0 +1,5 @@ +USING: palindrome tools.test ; +IN: palindrome.tests + +[ t ] [ "racecar" palindrome? ] unit-test +[ f ] [ "ferrari" palindrome? ] unit-test diff --git a/Task/Test-a-function/Factor/test-a-function-3.factor b/Task/Test-a-function/Factor/test-a-function-3.factor new file mode 100644 index 0000000000..1440c1efae --- /dev/null +++ b/Task/Test-a-function/Factor/test-a-function-3.factor @@ -0,0 +1 @@ +( scratchpad ) "palindrome" test diff --git a/Task/Test-a-function/Fantom/test-a-function.fantom b/Task/Test-a-function/Fantom/test-a-function.fantom new file mode 100644 index 0000000000..31324f2df8 --- /dev/null +++ b/Task/Test-a-function/Fantom/test-a-function.fantom @@ -0,0 +1,13 @@ +class TestPalindrome : Test +{ + public Void testIsPalindrome () + { + verify(Palindrome.isPalindrome("")) + verify(Palindrome.isPalindrome("a")) + verify(Palindrome.isPalindrome("aa")) + verify(Palindrome.isPalindrome("aba")) + verifyFalse(Palindrome.isPalindrome("abb")) + verify(Palindrome.isPalindrome("salàlas")) + verify(Palindrome.isPalindrome("In girum imus nocte et consumimur igni".lower.replace(" ",""))) + } +} diff --git a/Task/Test-a-function/Go/test-a-function.go b/Task/Test-a-function/Go/test-a-function.go new file mode 100644 index 0000000000..b1a4493160 --- /dev/null +++ b/Task/Test-a-function/Go/test-a-function.go @@ -0,0 +1,31 @@ +package pal + +import "testing" + +func TestPals(t *testing.T) { + pals := []string{ + "", + ".", + "11", + "ere", + "ingirumimusnocteetconsumimurigni", + } + for _, s := range pals { + if !IsPal(s) { + t.Error("IsPal returned false on palindrome,", s) + } + } +} + +func TestNonPals(t *testing.T) { + nps := []string{ + "no", + "odd", + "salàlas", + } + for _, s := range nps { + if IsPal(s) { + t.Error("IsPal returned true on non-palindrome,", s) + } + } +} diff --git a/Task/Test-a-function/Haskell/test-a-function.hs b/Task/Test-a-function/Haskell/test-a-function.hs new file mode 100644 index 0000000000..9fc8545549 --- /dev/null +++ b/Task/Test-a-function/Haskell/test-a-function.hs @@ -0,0 +1,20 @@ +import Test.QuickCheck + +isPalindrome :: String -> Bool +isPalindrome x = x == reverse x + +{- There is no built-in definition of how to generate random characters; + here we just specify ASCII characters. Generating strings then automatically + follows from the definition of String as list of Char. -} +instance Arbitrary Char where + arbitrary = choose ('\32', '\127') + +-- /------------------------- the randomly-generated parameters +-- | /------------------ the constraint on the test values +-- | | /- the condition which should be true +-- v v v +main = do + putStr "Even palindromes: " >> quickCheck (\s -> isPalindrome (s ++ reverse s)) + putStr "Odd palindromes: " >> quickCheck (\s -> not (null s) ==> isPalindrome (s ++ (tail.reverse) s)) + putStr "Non-palindromes: " >> quickCheck (\i s -> not (null s) && 0 <= i && i < length s && i*2 /= length s + ==> not (isPalindrome (take i s ++ "•" ++ drop i s))) diff --git a/Task/Test-a-function/J/test-a-function-1.j b/Task/Test-a-function/J/test-a-function-1.j new file mode 100644 index 0000000000..0aa3d3ca81 --- /dev/null +++ b/Task/Test-a-function/J/test-a-function-1.j @@ -0,0 +1,16 @@ +NB. Contents of palindrome_test.ijs + +NB. Basic testing +test_palinA=: monad define + assert isPalin0 'abcba' + assert isPalin0 'aa' + assert isPalin0 '' + assert -. isPalin0 'ab' + assert -. isPalin0 'abcdba' +) + +NB. Can test for expected failure instead +palinB_expect=: 'assertion failure' +test_palinB=: monad define + assert isPalin0 'ab' +) diff --git a/Task/Test-a-function/J/test-a-function-2.j b/Task/Test-a-function/J/test-a-function-2.j new file mode 100644 index 0000000000..fea04d185b --- /dev/null +++ b/Task/Test-a-function/J/test-a-function-2.j @@ -0,0 +1,5 @@ + require 'general/unittest' + unittest 'c:\mypath\palindrome_test.ijs' +Test: c:\mypath\palindrome_test.ijs +palinA .................................. OK +palinB .................................. OK diff --git a/Task/Test-a-function/Java/test-a-function-1.java b/Task/Test-a-function/Java/test-a-function-1.java new file mode 100644 index 0000000000..ba02977e62 --- /dev/null +++ b/Task/Test-a-function/Java/test-a-function-1.java @@ -0,0 +1,48 @@ +import static ExampleClass.pali; // or from wherever it is defined +import static ExampleClass.rPali; // or from wherever it is defined +import org.junit.*; +public class PalindromeTest extends junit.framework.TestCase { + @Before + public void setUp(){ + //runs before each test + //set up instance variables, network connections, etc. needed for all tests + } + @After + public void tearDown(){ + //runs after each test + //clean up instance variables (close files, network connections, etc.). + } + + /** + * Test the pali(...) method. + */ + @Test + public void testNonrecursivePali() throws Exception { + assertTrue(pali("abcba")); + assertTrue(pali("aa")); + assertTrue(pali("a")); + assertTrue(pali("")); + assertFalse(pali("ab")); + assertFalse(pali("abcdba")); + } + /** + * Test the rPali(...) method. + */ + @Test + public void testRecursivePali() throws Exception { + assertTrue(rPali("abcba")); + assertTrue(rPali("aa")); + assertTrue(rPali("a")); + assertTrue(rPali("")); + assertFalse(rPali("ab")); + assertFalse(rPali("abcdba")); + } + + /** + * Expect a WhateverExcpetion + */ + @Test(expected=WhateverException.class) + public void except(){ + //some code that should throw a WhateverException + } +} diff --git a/Task/Test-a-function/Java/test-a-function-2.java b/Task/Test-a-function/Java/test-a-function-2.java new file mode 100644 index 0000000000..036b66cf40 --- /dev/null +++ b/Task/Test-a-function/Java/test-a-function-2.java @@ -0,0 +1,5 @@ +public class RunTests{ + public static main(String[] args){ + org.junit.runner.JUnitCore.runClasses(PalindromeTest.class/*, other classes here if you have more*/); + } +} diff --git a/Task/Test-a-function/Lua/test-a-function.lua b/Task/Test-a-function/Lua/test-a-function.lua new file mode 100644 index 0000000000..fc14a4a872 --- /dev/null +++ b/Task/Test-a-function/Lua/test-a-function.lua @@ -0,0 +1,2 @@ +assert( ispalindrome("ABCBA") ) +assert( ispalindrome("ABCDE") ) diff --git a/Task/Test-a-function/Mathematica/test-a-function.math b/Task/Test-a-function/Mathematica/test-a-function.math new file mode 100644 index 0000000000..4bd6672adf --- /dev/null +++ b/Task/Test-a-function/Mathematica/test-a-function.math @@ -0,0 +1,2 @@ +myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]] +On[Assert];myFun[1.0] diff --git a/Task/Test-a-function/NetRexx/test-a-function.netrexx b/Task/Test-a-function/NetRexx/test-a-function.netrexx new file mode 100644 index 0000000000..276d846cdd --- /dev/null +++ b/Task/Test-a-function/NetRexx/test-a-function.netrexx @@ -0,0 +1,43 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +import junit.framework.TestCase +import RCPalindrome + +class RCTestAFunction public final extends TestCase + +method setUp public + return + +method tearDown public + return + +method testIsPal public signals AssertionError + + assertTrue(RCPalindrome.isPal(Rexx 'abcba')) + assertTrue(RCPalindrome.isPal(Rexx 'aa')) + assertTrue(RCPalindrome.isPal(Rexx 'a')) + assertTrue(RCPalindrome.isPal(Rexx '')) + assertFalse(RCPalindrome.isPal(Rexx 'ab')) + assertFalse(RCPalindrome.isPal(Rexx 'abcdba')) + + return + +method except signals RuntimeException + signal RuntimeException() + +method main(args = String[]) public constant + + testResult = org.junit.runner.JUnitCore.runClasses([RCTestAFunction.class]) + + secs = Rexx testResult.getRunTime / 1000.0 + + if testResult.wasSuccessful then say 'Tests successful' + else say 'Tests failed' + say ' failure count:' testResult.getFailureCount + say ' ignore count:' testResult.getIgnoreCount + say ' run count:' testResult.getRunCount + say ' run time:' secs.format(null, 3) + + return diff --git a/Task/Test-a-function/OCaml/test-a-function.ocaml b/Task/Test-a-function/OCaml/test-a-function.ocaml new file mode 100644 index 0000000000..36bd07d2e7 --- /dev/null +++ b/Task/Test-a-function/OCaml/test-a-function.ocaml @@ -0,0 +1,26 @@ +open OUnit +open Palindrome + +let test_palindrome_1 _ = + assert_equal true (is_palindrome "aba") + +let test_palindrome_2 _ = + assert_equal true (is_palindrome "abba") + +let test_palindrome_3 _ = + assert_equal true (is_palindrome "abacidAdicaba") + +let test_palindrome_4 _ = + assert_equal false (is_palindrome "xREty5kgPMO") + +let test_palindrome_5 _ = + assert_equal true (is_palindrome(rem_space "in girum imus nocte et consumimur igni")) + + +let suite = "Test Palindrome" >::: ["test_palindrome_1" >:: test_palindrome_1; + "test_palindrome_2" >:: test_palindrome_2; + "test_palindrome_3" >:: test_palindrome_3; + "test_palindrome_4" >:: test_palindrome_4; + "test_palindrome_5" >:: test_palindrome_5] +let _ = + run_test_tt_main suite diff --git a/Task/Test-a-function/Perl-6/test-a-function.pl6 b/Task/Test-a-function/Perl-6/test-a-function.pl6 new file mode 100644 index 0000000000..1664e804b5 --- /dev/null +++ b/Task/Test-a-function/Perl-6/test-a-function.pl6 @@ -0,0 +1,17 @@ +use Test; + +my %tests = + 'A man, a plan, a canal: Panama.' => True, + 'My dog has fleas' => False, + "Madam, I'm Adam." => True, + '1 on 1' => False, + 'In girum imus nocte et consumimur igni' => True, + '' => True, + ; + +plan %tests.elems; + +for %tests.kv -> $test, $expected-result { + is palin($test), $expected-result, + "\"$test\" is {$expected-result??''!!'not '}a palindrome."; +} diff --git a/Task/Test-a-function/Perl/test-a-function.pl b/Task/Test-a-function/Perl/test-a-function.pl new file mode 100644 index 0000000000..a0a3f3fd5a --- /dev/null +++ b/Task/Test-a-function/Perl/test-a-function.pl @@ -0,0 +1,37 @@ +# ptest.t +use strict; +use warnings; + +use Test; + +my %tests; +BEGIN { + # plan tests before loading Palindrome.pm + %tests = ( + 'A man, a plan, a canal: Panama.' => 1, + 'My dog has fleas' => 0, + "Madam, I'm Adam." => 1, + '1 on 1' => 0, + 'In girum imus nocte et consumimur igni' => 1, + '' => 1, + ); + + # plan 4 tests per string + plan tests => (keys(%tests) * 4); +} + +use Palindrome; + +for my $key (keys %tests) { + $_ = lc $key; # convert to lowercase + s/[\W_]//g; # keep only alphanumeric characters + + my $expect = $tests{$key}; + my $note = ("\"$key\" should " . ($expect ? '' : 'not ') . + "be a palindrome."); + + ok palindrome == $expect, 1, "palindrome: $note"; + ok palindrome_c == $expect, 1, "palindrome_c: $note"; + ok palindrome_r == $expect, 1, "palindrome_r: $note"; + ok palindrome_e == $expect, 1, "palindrome_e: $note"; +} diff --git a/Task/Test-a-function/PicoLisp/test-a-function.l b/Task/Test-a-function/PicoLisp/test-a-function.l new file mode 100644 index 0000000000..bb72283fda --- /dev/null +++ b/Task/Test-a-function/PicoLisp/test-a-function.l @@ -0,0 +1,5 @@ +(de palindrome? (S) + (= (setq S (chop S)) (reverse S)) ) + +(test T (palindrome? "racecar")) +(test NIL (palindrome? "ferrari")) diff --git a/Task/Test-a-function/PureBasic/test-a-function.purebasic b/Task/Test-a-function/PureBasic/test-a-function.purebasic new file mode 100644 index 0000000000..26efc8cf23 --- /dev/null +++ b/Task/Test-a-function/PureBasic/test-a-function.purebasic @@ -0,0 +1,27 @@ +Macro DoubleQuote + ; Needed for the Assert-Macro below + " ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution! +EndMacro +Macro Assert(TEST,MSG="") + CompilerIf #PB_Compiler_Debugger + If Not (TEST) + If MSG<>"": Debug MSG: EndIf + Temp$="Fail: "+DoubleQuote#TEST#DoubleQuote + Debug Temp$+", Line="+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File + CallDebugger + EndIf + CompilerEndIf +EndMacro + +Procedure IsPalindrome(StringToTest.s) + If StringToTest=ReverseString(StringToTest) + ProcedureReturn 1 + Else + ProcedureReturn 0 + EndIf +EndProcedure + +text1$="racecar" +text2$="wisconsin" +Assert(IsPalindrome(text1$), "Catching this would be a fail") +Assert(IsPalindrome(text2$), "Catching this is correct") diff --git a/Task/Test-a-function/Python/test-a-function.py b/Task/Test-a-function/Python/test-a-function.py new file mode 100644 index 0000000000..751924360f --- /dev/null +++ b/Task/Test-a-function/Python/test-a-function.py @@ -0,0 +1,39 @@ +def is_palindrome(s): + ''' + >>> is_palindrome('') + True + >>> is_palindrome('a') + True + >>> is_palindrome('aa') + True + >>> is_palindrome('baa') + False + >>> is_palindrome('baab') + True + >>> is_palindrome('ba_ab') + True + >>> is_palindrome('ba_ ab') + False + >>> is_palindrome('ba _ ab') + True + >>> is_palindrome('ab'*2) + False + >>> x = 'ab' *2**15 + >>> len(x) + 65536 + >>> xreversed = x[::-1] + >>> is_palindrome(x+xreversed) + True + >>> len(x+xreversed) + 131072 + >>> + ''' + return s == s[::-1] + +def _test(): + import doctest + doctest.testmod() + #doctest.testmod(verbose=True) + +if __name__ == "__main__": + _test() diff --git a/Task/Test-a-function/R/test-a-function.r b/Task/Test-a-function/R/test-a-function.r new file mode 100644 index 0000000000..f66fb686e5 --- /dev/null +++ b/Task/Test-a-function/R/test-a-function.r @@ -0,0 +1,4 @@ +checkTrue(palindroc("aba")) # TRUE +checkTrue(!palindroc("ab")) # TRUE +checkException(palindroc()) # TRUE +checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function diff --git a/Task/Test-a-function/REXX/test-a-function-1.rexx b/Task/Test-a-function/REXX/test-a-function-1.rexx new file mode 100644 index 0000000000..67abb4af9d --- /dev/null +++ b/Task/Test-a-function/REXX/test-a-function-1.rexx @@ -0,0 +1,10 @@ +/* This REXX uses a lot of REXX keywords as variables. */ + +signal=(interpret=value);value=(interpretlist (string-downcase str))] + [slst (remove* '(#\space) lst)]) + (string=? (list->string (reverse slst)) (list->string slst)))) + +;; this test module is not loaded unless it is +;; specifically requested for testing, allowing internal +;; unit test specification +(module+ test + (check-true (palindromb "racecar")) + (check-true (palindromb "avoova")) + (check-false (palindromb "potato"))) diff --git a/Task/Test-a-function/Retro/test-a-function.retro b/Task/Test-a-function/Retro/test-a-function.retro new file mode 100644 index 0000000000..c7e7178881 --- /dev/null +++ b/Task/Test-a-function/Retro/test-a-function.retro @@ -0,0 +1,10 @@ +needs assertion' +needs hash' + +: palindrome? ( $-f ) dup ^hash'hash [ ^strings'reverse ^hash'hash ] dip = ; + +with assertion' +: t0 ( - ) "hello" palindrome? 0 assert= ; assertion +: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion +: test ( - ) t0 t1 ; +test diff --git a/Task/Test-a-function/Ruby/test-a-function-1.rb b/Task/Test-a-function/Ruby/test-a-function-1.rb new file mode 100644 index 0000000000..f4d92a1b35 --- /dev/null +++ b/Task/Test-a-function/Ruby/test-a-function-1.rb @@ -0,0 +1,26 @@ +def palindrome?(s) + s == s.reverse +end + +require 'test/unit' +class MyTests < Test::Unit::TestCase + def test_palindrome_ok + assert(palindrome? "aba") + end + + def test_palindrome_nok + assert_equal(false, palindrome?("ab")) + end + + def test_object_without_reverse + assert_raise(NoMethodError) {palindrome? 42} + end + + def test_wrong_number_args + assert_raise(ArgumentError) {palindrome? "a", "b"} + end + + def test_show_failing_test + assert(palindrome?("ab"), "this test case fails on purpose") + end +end diff --git a/Task/Test-a-function/Ruby/test-a-function-2.rb b/Task/Test-a-function/Ruby/test-a-function-2.rb new file mode 100644 index 0000000000..b2c67edf50 --- /dev/null +++ b/Task/Test-a-function/Ruby/test-a-function-2.rb @@ -0,0 +1,28 @@ +# palindrome.rb +def palindrome?(s) + s == s.reverse +end + +require 'minitest/spec' +require 'minitest/autorun' +describe "palindrome? function" do + it "returns true if arg is a palindrome" do + (palindrome? "aba").must_equal true + end + + it "returns false if arg is not a palindrome" do + palindrome?("ab").must_equal false + end + + it "raises NoMethodError if arg is without #reverse" do + proc { palindrome? 42 }.must_raise NoMethodError + end + + it "raises ArgumentError if wrong number of args" do + proc { palindrome? "a", "b" }.must_raise ArgumentError + end + + it "passes a failing test" do + palindrome?("ab").must_equal true, "this test case fails on purpose" + end +end diff --git a/Task/Test-a-function/Scala/test-a-function.scala b/Task/Test-a-function/Scala/test-a-function.scala new file mode 100644 index 0000000000..350c4320c4 --- /dev/null +++ b/Task/Test-a-function/Scala/test-a-function.scala @@ -0,0 +1,18 @@ +import org.scalacheck._ +import Prop._ +import Gen._ + +object PalindromeCheck extends Properties("Palindrome") { + property("A string concatenated with its reverse is a palindrome") = + forAll { s: String => isPalindrome(s + s.reverse) } + + property("A string concatenated with any character and its reverse is a palindrome") = + forAll { (s: String, c: Char) => isPalindrome(s + c + s.reverse) } + + property("If the first half of a string is equal to the reverse of its second half, it is a palindrome") = + forAll { (s: String) => s.take(s.length / 2) != s.drop((s.length + 1) / 2).reverse || isPalindrome(s) } + + property("If the first half of a string is different than the reverse of its second half, it isn't a palindrome") = + forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) } + +} diff --git a/Task/Test-a-function/Tcl/test-a-function.tcl b/Task/Test-a-function/Tcl/test-a-function.tcl new file mode 100644 index 0000000000..bb2604f28e --- /dev/null +++ b/Task/Test-a-function/Tcl/test-a-function.tcl @@ -0,0 +1,14 @@ +package require tcltest 2 +source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’ + +tcltest::test palindrome-1 {check for palindromicity} -body { + palindrome abcdedcba +} -result 1 +tcltest::test palindrome-2 {check for non-palindromicity} -body { + palindrome abcdef +} -result 0 +tcltest::test palindrome-3 {check for palindrome error} -body { + palindrome +} -returnCodes error -result "wrong # args: should be \"palindrome s\"" + +tcltest::cleanupTests diff --git a/Task/Text-processing-1/0DESCRIPTION b/Task/Text-processing-1/0DESCRIPTION new file mode 100644 index 0000000000..270b47fe99 --- /dev/null +++ b/Task/Text-processing-1/0DESCRIPTION @@ -0,0 +1,34 @@ +{{Template:clarify task}} + +Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is [http://www.google.co.uk/search?q=%22data+munging%22 often] used in programming circles for this task. + +A [http://groups.google.co.uk/group/comp.lang.awk/msg/0ecba3a3fbf247d8?hl=en request] on the comp.lang.awk newsgroup lead to a typical data munging task: +
I have to analyse data files that have the following format:
+Each row corresponds to 1 day and the field logic is: $1 is the date,
+followed by 24 value/flag pairs, representing measurements at 01:00,
+02:00 ... 24:00 of the respective day. In short:
+
+     ...   
+
+Some test data is available at:
+... (nolonger available at original location)
+
+I have to sum up the values (per day and only valid data, i.e. with
+flag>0) in order to calculate the mean. That's not too difficult.
+However, I also need to know what the "maximum data gap" is, i.e. the
+longest period with successive invalid measurements (i.e values with
+flag<=0)
+ +The data is [http://www.eea.europa.eu/help/eea-help-centre/faqs/how-do-i-obtain-eea-reports free to download and use] and is of this format: +
+1991-03-30	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1
+1991-03-31	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	20.000	1	20.000	1	20.000	1	35.000	1	50.000	1	60.000	1	40.000	1	30.000	1	30.000	1	30.000	1	25.000	1	20.000	1	20.000	1	20.000	1	20.000	1	20.000	1	35.000	1
+1991-03-31	40.000	1	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2
+1991-04-01	0.000	-2	13.000	1	16.000	1	21.000	1	24.000	1	22.000	1	20.000	1	18.000	1	29.000	1	44.000	1	50.000	1	43.000	1	38.000	1	27.000	1	27.000	1	24.000	1	23.000	1	18.000	1	12.000	1	13.000	1	14.000	1	15.000	1	13.000	1	10.000	1
+1991-04-02	8.000	1	9.000	1	11.000	1	12.000	1	12.000	1	12.000	1	27.000	1	26.000	1	27.000	1	33.000	1	32.000	1	31.000	1	29.000	1	31.000	1	25.000	1	25.000	1	24.000	1	21.000	1	17.000	1	14.000	1	15.000	1	12.000	1	12.000	1	10.000	1
+1991-04-03	10.000	1	9.000	1	10.000	1	10.000	1	9.000	1	10.000	1	15.000	1	24.000	1	28.000	1	24.000	1	18.000	1	14.000	1	12.000	1	13.000	1	14.000	1	15.000	1	14.000	1	15.000	1	13.000	1	13.000	1	13.000	1	12.000	1	10.000	1	10.000	1
+
+ +Only a sample of the data showing its format is given above. The full example file may be downloaded [http://rosettacode.org/resources/readings.zip here]. + +Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary. diff --git a/Task/Text-processing-1/1META.yaml b/Task/Text-processing-1/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/Text-processing-1/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/Text-processing-1/ALGOL-68/text-processing-1.alg b/Task/Text-processing-1/ALGOL-68/text-processing-1.alg new file mode 100644 index 0000000000..ca9e9f46b4 --- /dev/null +++ b/Task/Text-processing-1/ALGOL-68/text-processing-1.alg @@ -0,0 +1,95 @@ +INT no data := 0; # Current run of consecutive flags<0 in lines of file # +INT no data max := -1; # Max consecutive flags<0 in lines of file # +FLEX[0]STRING no data max line; # ... and line number(s) where it occurs # + +REAL tot file := 0; # Sum of file data # +INT num file := 0; # Number of file data items with flag>0 # + +# CHAR fs = " "; # +INT nf = 24; + +INT upb list := nf; +FORMAT list repr = $n(upb list-1)(g", ")g$; + +PROC exception = ([]STRING args)VOID:( + putf(stand error, ($"Exception"$, $", "g$, args, $l$)); + stop +); + +PROC raise io error = (STRING message)VOID:exception(("io error", message)); + +OP +:= = (REF FLEX []STRING rhs, STRING append)REF FLEX[]STRING: ( + HEAP [UPB rhs+1]STRING out rhs; + out rhs[:UPB rhs] := rhs; + out rhs[UPB rhs+1] := append; + rhs := out rhs; + out rhs +); + +INT upb opts = 3; # these are "a68g" "./Data_Munging.a68" & "-" # +[argc - upb opts]STRING in files; +FOR arg TO UPB in files DO in files[arg] := argv(upb opts + arg) OD; + +MODE FIELD = STRUCT(REAL data, INT flag); +FORMAT field repr = $2(g)$; + +FOR index file TO UPB in files DO + STRING file name = in files[index file], FILE file; + IF open(file, file name, stand in channel) NE 0 THEN + raise io error("Cannot open """+file name+"""") FI; + on logical file end(file, (REF FILE f)BOOL: logical file end done); + REAL tot line, INT num line; + # make term(file, ", ") for CSV data # + STRING date; + DO + tot line := 0; # sum of line data # + num line := 0; # number of line data items with flag>0 # + # extract field info # + [nf]FIELD data; + getf(file, ($10a$, date, field repr, data, $l$)); + + FOR key TO UPB data DO + FIELD field = data[key]; + IF flag OF field<1 THEN + no data +:= 1 + ELSE + # check run of data-absent data # + IF no data max = no data AND no data>0 THEN + no data max line +:= date FI; + IF no data max0 THEN + no data max := no data; + no data max line := date FI; + # re-initialise run of no data counter # + no data := 0; + # gather values for averaging # + tot line +:= data OF field; + num line +:= 1 + FI + OD; + + # totals for the file so far # + tot file +:= tot line; + num file +:= num line; + + printf(($"Line: "g" Reject: "g(-2)" Accept: "g(-2)" Line tot: "g(-14, 3)" Line avg: "g(-14, 3)l$, + date, + UPB(data) -num line, + num line, tot line, + IF num line>0 THEN tot line/num line ELSE 0 FI)) + OD; + logical file end done: + close(file) +OD; + +FORMAT plural = $b(" ", "s")$, + p = $b("", "s")$; + +upb list := UPB in files; +printf(($l"File"f(plural)" = "$, upb list = 1, list repr, in files, $l$, + $"Total = "g(-0, 3)l$, tot file, + $"Readings = "g(-0)l$, num file, + $"Average = "g(-0, 3)l$, tot file / num file)); + +upb list := UPB no data max line; +printf(($l"Maximum run"f(p)" of "g(-0)" consecutive false reading"f(p)" ends at line starting with date"f(p)": "$, + upb list = 1, no data max, no data max = 0, upb list = 1, list repr, no data max line, $l$)) diff --git a/Task/Text-processing-1/AWK/text-processing-1.awk b/Task/Text-processing-1/AWK/text-processing-1.awk new file mode 100644 index 0000000000..0f8547f1ef --- /dev/null +++ b/Task/Text-processing-1/AWK/text-processing-1.awk @@ -0,0 +1,63 @@ +BEGIN{ + nodata = 0; # Current run of consecutive flags<0 in lines of file + nodata_max=-1; # Max consecutive flags<0 in lines of file + nodata_maxline="!"; # ... and line number(s) where it occurs +} +FNR==1 { + # Accumulate input file names + if(infiles){ + infiles = infiles "," infiles + } else { + infiles = FILENAME + } +} +{ + tot_line=0; # sum of line data + num_line=0; # number of line data items with flag>0 + + # extract field info, skipping initial date field + for(field=2; field<=NF; field+=2){ + datum=$field; + flag=$(field+1); + if(flag<1){ + nodata++ + }else{ + # check run of data-absent fields + if(nodata_max==nodata && (nodata>0)){ + nodata_maxline=nodata_maxline ", " $1 + } + if(nodata_max0)){ + nodata_max=nodata + nodata_maxline=$1 + } + # re-initialise run of nodata counter + nodata=0; + # gather values for averaging + tot_line+=datum + num_line++; + } + } + + # totals for the file so far + tot_file += tot_line + num_file += num_line + + printf "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f\n", \ + $1, ((NF -1)/2) -num_line, num_line, tot_line, (num_line>0)? tot_line/num_line: 0 + + # debug prints of original data plus some of the computed values + #printf "%s %15.3g %4i\n", $0, tot_line, num_line + #printf "%s\n %15.3f %4i %4i %4i %s\n", $0, tot_line, num_line, nodata, nodata_max, nodata_maxline + + +} + +END{ + printf "\n" + printf "File(s) = %s\n", infiles + printf "Total = %10.3f\n", tot_file + printf "Readings = %6i\n", num_file + printf "Average = %10.3f\n", tot_file / num_file + + printf "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s\n", nodata_max, nodata_maxline +} diff --git a/Task/Text-processing-1/Ada/text-processing-1.ada b/Task/Text-processing-1/Ada/text-processing-1.ada new file mode 100644 index 0000000000..c6225ec9c8 --- /dev/null +++ b/Task/Text-processing-1/Ada/text-processing-1.ada @@ -0,0 +1,76 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit; use Strings_Edit; +with Strings_Edit.Floats; use Strings_Edit.Floats; +with Strings_Edit.Integers; use Strings_Edit.Integers; + +procedure Data_Munging is + Syntax_Error : exception; + type Gap_Data is record + Count : Natural := 0; + Line : Natural := 0; + Pointer : Integer; + Year : Integer; + Month : Integer; + Day : Integer; + end record; + File : File_Type; + Max : Gap_Data; + This : Gap_Data; + Current : Gap_Data; + Count : Natural := 0; + Sum : Float := 0.0; +begin + Open (File, In_File, "readings.txt"); + loop + declare + Line : constant String := Get_Line (File); + Pointer : Integer := Line'First; + Flag : Integer; + Data : Float; + begin + Current.Line := Current.Line + 1; + Get (Line, Pointer, SpaceAndTab); + Get (Line, Pointer, Current.Year); + Get (Line, Pointer, Current.Month); + Get (Line, Pointer, Current.Day); + while Pointer <= Line'Last loop + Get (Line, Pointer, SpaceAndTab); + Current.Pointer := Pointer; + Get (Line, Pointer, Data); + Get (Line, Pointer, SpaceAndTab); + Get (Line, Pointer, Flag); + if Flag < 0 then + if This.Count = 0 then + This := Current; + end if; + This.Count := This.Count + 1; + else + if This.Count > 0 and then Max.Count < This.Count then + Max := This; + end if; + This.Count := 0; + Count := Count + 1; + Sum := Sum + Data; + end if; + end loop; + exception + when End_Error => + raise Syntax_Error; + end; + end loop; +exception + when End_Error => + Close (File); + if This.Count > 0 and then Max.Count < This.Count then + Max := This; + end if; + Put_Line ("Average " & Image (Sum / Float (Count)) & " over " & Image (Count)); + if Max.Count > 0 then + Put ("Max. " & Image (Max.Count) & " false readings start at "); + Put (Image (Max.Line) & ':' & Image (Max.Pointer) & " stamped "); + Put_Line (Image (Max.Year) & Image (Max.Month) & Image (Max.Day)); + end if; + when others => + Close (File); + Put_Line ("Syntax error at " & Image (Current.Line) & ':' & Image (Max.Pointer)); +end Data_Munging; diff --git a/Task/Text-processing-1/Aime/text-processing-1.aime b/Task/Text-processing-1/Aime/text-processing-1.aime new file mode 100644 index 0000000000..2165338a8c --- /dev/null +++ b/Task/Text-processing-1/Aime/text-processing-1.aime @@ -0,0 +1,48 @@ +integer bads, count, max_bads; +file f; +list l; +real s; +text bad_day, worst_day; + +f_affix(f, "/dev/stdin"); + +max_bads = 0; +count = 0; +bads = 0; +s = 0; + +while (f_list(f, l, 0) ^ -1) { + integer e, i; + + i = 2; + while (i < 49) { + e = atoi(l_q_text(l, i)); + if (0 < e) { + count += 1; + s += atof(l_q_text(l, i - 1)); + if (max_bads < bads) { + max_bads = bads; + worst_day = bad_day; + } + bads = 0; + } else { + if (!bads) { + bad_day = l_q_text(l, 0); + } + bads += 1; + } + i += 2; + } +} + +o_text("Averaged "); +o_real(3, s / count); +o_text(" over "); +o_integer(count); +o_text(" readings.\n"); + +o_text("Longest bad run "); +o_integer(max_bads); +o_text(", started "); +o_text(worst_day); +o_text(".\n"); diff --git a/Task/Text-processing-1/AutoHotkey/text-processing-1.ahk b/Task/Text-processing-1/AutoHotkey/text-processing-1.ahk new file mode 100644 index 0000000000..37504b3022 --- /dev/null +++ b/Task/Text-processing-1/AutoHotkey/text-processing-1.ahk @@ -0,0 +1,74 @@ +# Author AlephX Aug 17 2011 + +SetFormat, float, 4.2 +SetFormat, FloatFast, 4.2 + +data = %A_scriptdir%\readings.txt +result = %A_scriptdir%\results.txt +totvalid := 0 +totsum := 0 +totavg:= 0 + +Loop, Read, %data%, %result% + { + sum := 0 + Valid := 0 + Couples := 0 + Lines := A_Index + Loop, parse, A_LoopReadLine, %A_Tab% + { + ;MsgBox, Field number %A_Index% is %A_LoopField% + if A_index = 1 + { + Date := A_LoopField + Counter := 0 + } + else + { + Counter++ + couples := Couples + 0.5 + if Counter = 1 + { + value := A_LoopField / 1 + } + else + { + if A_loopfield > 0 + { + Sum := Sum + value + Valid++ + + if (wrong > maxwrong) + { + maxwrong := wrong + lastwrongdate := currwrongdate + startwrongdate := firstwrongdate + startoccurrence := firstoccurrence + lastoccurrence := curroccurrence + } + wrong := 0 + } + else + { + wrong++ + currwrongdate := date + curroccurrence := (A_index-1) / 2 + if (wrong = 1) + { + firstwrongdate := date + firstoccurrence := curroccurrence + } + } + Counter := 0 + } + } + } + avg := sum / valid + TotValid := Totvalid+valid + TotSum := Totsum+sum + FileAppend, Day: %date% sum: %sum% avg: %avg% Readings: %valid%/%couples%`n + } + +Totavg := TotSum / TotValid +FileAppend, `n`nDays %Lines%`nMaximal wrong readings: %maxwrong% from %startwrongdate% at %startoccurrence% to %lastwrongdate% at %lastoccurrence%`n`n, %result% +FileAppend, Valid readings: %TotValid%`nTotal Value: %TotSUm%`nAverage: %TotAvg%, %result% diff --git a/Task/Text-processing-1/BBC-BASIC/text-processing-1.bbc b/Task/Text-processing-1/BBC-BASIC/text-processing-1.bbc new file mode 100644 index 0000000000..8ebd664722 --- /dev/null +++ b/Task/Text-processing-1/BBC-BASIC/text-processing-1.bbc @@ -0,0 +1,43 @@ + file% = OPENIN("readings.txt") + IF file% = 0 THEN PRINT "Could not open test data file" : END + + Total = 0 + Count% = 0 + BadMax% = 0 + bad% = 0 + WHILE NOT EOF#file% + text$ = GET$#file% + IF text$<>"" THEN + tab% = INSTR(text$, CHR$(9)) + date$ = LEFT$(text$, tab% - 1) + acc = 0 + cnt% = 0 + FOR field% = 1 TO 24 + dval = VALMID$(text$, tab%+1) + tab% = INSTR(text$, CHR$(9), tab%+1) + flag% = VALMID$(text$, tab%+1) + tab% = INSTR(text$, CHR$(9), tab%+1) + IF flag% > 0 THEN + acc += dval + cnt% += 1 + bad% = 0 + ELSE + bad% += 1 + IF bad% > BadMax% BadMax% = bad% : BadDate$ = date$ + ENDIF + NEXT field% + @% = &90A + PRINT "Date: " date$ " Good = "; cnt%, " Bad = "; 24-cnt%, ; + @% = &20308 + IF cnt% THEN PRINT " Total = " acc " Mean = " acc / cnt% ; + PRINT + Total += acc + Count% += cnt% + ENDIF + ENDWHILE + CLOSE #file% + PRINT ' "Grand total = " ; Total + PRINT "Number of valid readings = " ; STR$(Count%) + PRINT "Overall mean = " ; Total / Count% + @% = &90A + PRINT '"Longest run of bad readings = " ; BadMax% " ending " BadDate$ diff --git a/Task/Text-processing-1/Batch-File/text-processing-1.bat b/Task/Text-processing-1/Batch-File/text-processing-1.bat new file mode 100644 index 0000000000..933b2a7f41 --- /dev/null +++ b/Task/Text-processing-1/Batch-File/text-processing-1.bat @@ -0,0 +1,67 @@ +@echo off +setlocal ENABLEDELAYEDEXPANSION +set maxrun= 0 +set maxstart= +set maxend= +set notok=0 +set inputfile=%1 +for /F "tokens=1,*" %%i in (%inputfile%) do ( + set date=%%i + call :processline %%j +) + +echo\ +echo max false: %maxrun% from %maxstart% until %maxend% + +goto :EOF + +:processline +set sum=0000 +set count=0 +set hour=1 +:loop +if "%1"=="" goto :result +set num=%1 +if "%2"=="1" ( + if "%notok%" NEQ "0" ( + set notok= !notok! + if /I "!notok:~-5!" GTR "%maxrun%" ( + set maxrun=!notok:~-5! + set maxstart=%nok0date% %nok0hour% + set maxend=%nok1date% %nok1hour% + ) + set notok=0 + ) + set /a sum+=%num:.=% + set /a count+=1 +) else ( + if "%notok%" EQU "0" ( + set nok0date=%date% + set nok0hour=%hour% + ) else ( + set nok1date=%date% + set nok1hour=%hour% + ) + set /a notok+=1 +) +shift +shift +set /a hour+=1 +goto :loop + +:result +if "%count%"=="0" ( + set mean=0 +) else ( + set /a mean=%sum%/%count% +) +if "%mean%"=="0" set mean=0000 +if "%sum%"=="0" set sum=0000 +set mean=%mean:~0,-3%.%mean:~-3% +set sum=%sum:~0,-3%.%sum:~-3% +set count= %count% +set sum= %sum% +set mean= %mean% +echo Line: %date% Accept: %count:~-3% tot: %sum:~-8% avg: %mean:~-8% + +goto :EOF diff --git a/Task/Text-processing-1/C++/text-processing-1.cpp b/Task/Text-processing-1/C++/text-processing-1.cpp new file mode 100644 index 0000000000..c0588a0791 --- /dev/null +++ b/Task/Text-processing-1/C++/text-processing-1.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +#include + +using std::cout; +using std::endl; +const int NumFlags = 24; + +int main() +{ + std::fstream file("readings.txt"); + + int badCount = 0; + std::string badDate; + int badCountMax = 0; + while(true) + { + std::string line; + getline(file, line); + if(!file.good()) + break; + + std::vector tokens; + boost::algorithm::split(tokens, line, boost::is_space()); + + if(tokens.size() != NumFlags * 2 + 1) + { + cout << "Bad input file." << endl; + return 0; + } + + double total = 0.0; + int accepted = 0; + for(size_t i = 1; i < tokens.size(); i += 2) + { + double val = boost::lexical_cast(tokens[i]); + int flag = boost::lexical_cast(tokens[i+1]); + if(flag > 0) + { + total += val; + ++accepted; + badCount = 0; + } + else + { + ++badCount; + if(badCount > badCountMax) + { + badCountMax = badCount; + badDate = tokens[0]; + } + } + } + + cout << tokens[0]; + cout << " Reject: " << std::setw(2) << (NumFlags - accepted); + cout << " Accept: " << std::setw(2) << accepted; + cout << " Average: " << std::setprecision(5) << total / accepted << endl; + } + cout << endl; + cout << "Maximum number of consecutive bad readings is " << badCountMax << endl; + cout << "Ends on date " << badDate << endl; +} diff --git a/Task/Text-processing-1/C/text-processing-1.c b/Task/Text-processing-1/C/text-processing-1.c new file mode 100644 index 0000000000..18efef4f0c --- /dev/null +++ b/Task/Text-processing-1/C/text-processing-1.c @@ -0,0 +1,85 @@ +#include +#include +#include + +static int badHrs, maxBadHrs; + +static double hrsTot = 0.0; +static int rdgsTot = 0; +char bhEndDate[40]; + +int mungeLine( char *line, int lno, FILE *fout ) +{ + char date[40], *tkn; + int dHrs, flag, hrs2, hrs; + double hrsSum; + int hrsCnt = 0; + double avg; + + tkn = strtok(line, "."); + if (tkn) { + int n = sscanf(tkn, "%s %d", &date, &hrs2); + if (n<2) { + printf("badly formated line - %d %s\n", lno, tkn); + return 0; + } + hrsSum = 0.0; + while( tkn= strtok(NULL, ".")) { + n = sscanf(tkn,"%d %d %d", &dHrs, &flag, &hrs); + if (n>=2) { + if (flag > 0) { + hrsSum += 1.0*hrs2 + .001*dHrs; + hrsCnt += 1; + if (maxBadHrs < badHrs) { + maxBadHrs = badHrs; + strcpy(bhEndDate, date); + } + badHrs = 0; + } + else { + badHrs += 1; + } + hrs2 = hrs; + } + else { + printf("bad file syntax line %d: %s\n",lno, tkn); + } + } + avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0; + fprintf(fout, "%s Reject: %2d Accept: %2d Average: %7.3f\n", + date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt); + hrsTot += hrsSum; + rdgsTot += hrsCnt; + } + return 1; +} + +int main() +{ + FILE *infile, *outfile; + int lineNo = 0; + char line[512]; + const char *ifilename = "readings.txt"; + outfile = fopen("V0.txt", "w"); + + infile = fopen(ifilename, "rb"); + if (!infile) { + printf("Can't open %s\n", ifilename); + exit(1); + } + while (NULL != fgets(line, 512, infile)) { + lineNo += 1; + if (0 == mungeLine(line, lineNo, outfile)) + printf("Bad line at %d",lineNo); + } + fclose(infile); + + fprintf(outfile, "File: %s\n", ifilename); + fprintf(outfile, "Total: %.3f\n", hrsTot); + fprintf(outfile, "Readings: %d\n", rdgsTot); + fprintf(outfile, "Average: %.3f\n", hrsTot/rdgsTot); + fprintf(outfile, "\nMaximum number of consecutive bad readings is %d\n", maxBadHrs); + fprintf(outfile, "Ends on date %s\n", bhEndDate); + fclose(outfile); + return 0; +} diff --git a/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp b/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp new file mode 100644 index 0000000000..76c35d5a70 --- /dev/null +++ b/Task/Text-processing-1/Common-Lisp/text-processing-1.lisp @@ -0,0 +1,101 @@ +(defstruct (measurement + (:conc-name "MEASUREMENT-") + (:constructor make-measurement (counter line date flag value))) + (counter 0 :type (integer 0)) + (line 0 :type (integer 0)) + (date nil :type symbol) + (flag 0 :type integer) + (value 0 :type real)) + +(defun measurement-valid-p (m) + (> (measurement-flag m) 0)) + +(defun map-data-stream (function stream) + (flet ((scan (&optional (errorp t)) (read stream errorp nil))) + (loop + :with global-count = 0 + :for date = (scan nil) :then (scan nil) + :for line-number :upfrom 1 + :while date + :do (loop + :for count :upfrom 0 :below 24 + :do (let* ((value (scan)) (flag (scan))) + (funcall function (make-measurement global-count line-number date flag value)) + (incf global-count))) + :finally (return global-count)))) + +(defun map-data-file (function pathname) + (with-open-file (stream pathname + :element-type 'character + :direction :input + :if-does-not-exist :error) + (map-data-stream function stream))) + +(defmacro do-data-stream ((variable stream) &body body) + `(map-data-stream + (lambda (,variable) ,@body) + ,stream)) + +(defmacro do-data-file ((variable file) &body body) + `(map-data-file + (lambda (,variable) ,@body) + ,file)) + +(let ((current-day nil) + (current-line 0) + (beginning-of-misreadings nil) + (current-length 0) + (worst-beginning nil) + (worst-length 0) + (sum-of-day 0) + (count-of-day 0)) + + (flet ((write-end-of-day-report () + (when current-day + (format t "Line ~5D Date ~A: Accepted ~2D Total ~8,3F Average ~8,3F~%" + current-line current-day count-of-day sum-of-day + (if (> count-of-day 0) (/ sum-of-day count-of-day) sum-of-day))))) + + (do-data-file (m #P"D:/Scratch/data.txt") + + (let* ((date (measurement-date m)) + (line-number (measurement-line m)) + (validp (measurement-valid-p m)) + (day-changed-p (/= current-line line-number)) + (value (measurement-value m))) + + (when day-changed-p + (write-end-of-day-report) + (setf current-day date) + (setf current-line line-number) + (setf sum-of-day 0) + (setf count-of-day 0)) + + (if (not validp) + (if beginning-of-misreadings + (incf current-length) + (progn + (setf beginning-of-misreadings m) + (setf current-length 1))) + (progn + (when beginning-of-misreadings + (if (> current-length worst-length) + (progn + (setf worst-beginning beginning-of-misreadings) + (setf worst-length current-length)) + (progn + (setf beginning-of-misreadings nil) + (setf current-length 0)))) + (incf sum-of-day value) + (incf count-of-day))))) + + (when (and beginning-of-misreadings (> current-length worst-length)) + (setf worst-beginning beginning-of-misreadings) + (setf worst-length current-length)) + + (write-end-of-day-report)) + + (format t "Worst run started ~A (~D) and has length ~D~%" + (measurement-date worst-beginning) + (measurement-counter worst-beginning) + worst-length)) diff --git a/Task/Text-processing-1/D/text-processing-1.d b/Task/Text-processing-1/D/text-processing-1.d new file mode 100644 index 0000000000..d5742ab410 --- /dev/null +++ b/Task/Text-processing-1/D/text-processing-1.d @@ -0,0 +1,75 @@ +import std.stdio, std.conv, std.string; + +void main(string[] args) { + /*const*/ auto fileNames = (args.length == 1) ? ["readings.txt"] : + args[1 .. $]; + + int noData, noDataMax = -1; + string[] noDataMaxLine; + + double fileTotal = 0.0; + int fileValues; + + foreach (fileName; fileNames) { + foreach (char[] line; File(fileName).byLine()) { + double lineTotal = 0.0; + int lineValues; + + // Extract field info + const parts = line.split(); + const date = parts[0]; + const fields = parts[1 .. $]; + assert(fields.length % 2 == 0, + format("Expected even number of fields, not %d.", + fields.length)); + + for (int i; i < fields.length; i += 2) { + immutable value = to!double(fields[i]); + immutable flag = to!int(fields[i + 1]); + + if (flag < 1) { + noData++; + continue; + } + + // Check run of data-absent fields + if (noDataMax == noData && noData > 0) + noDataMaxLine ~= date.idup; + + if (noDataMax < noData && noData > 0) { + noDataMax = noData; + noDataMaxLine.length = 1; + noDataMaxLine[0] = date.idup; + } + + // Re-initialise run of noData counter + noData = 0; + + // Gather values for averaging + lineTotal += value; + lineValues++; + } + + // Totals for the file so far + fileTotal += lineTotal; + fileValues += lineValues; + + writefln("Line: %11s Reject: %2d Accept: %2d" ~ + " Line_tot: %10.3f Line_avg: %10.3f", + date, + fields.length / 2 - lineValues, + lineValues, + lineTotal, + (lineValues > 0) ? lineTotal / lineValues : 0.0); + } + } + + writeln("\nFile(s) = ", fileNames.join(", ")); + writefln("Total = %10.3f", fileTotal); + writefln("Readings = %6d", fileValues); + writefln("Average = %10.3f", fileTotal / fileValues); + + writefln("\nMaximum run(s) of %d consecutive false " ~ + "readings ends at line starting with date(s): %s", + noDataMax, join(noDataMaxLine, ", ")); +} diff --git a/Task/Text-processing-1/Forth/text-processing-1.fth b/Task/Text-processing-1/Forth/text-processing-1.fth new file mode 100644 index 0000000000..d1fec600d7 --- /dev/null +++ b/Task/Text-processing-1/Forth/text-processing-1.fth @@ -0,0 +1,93 @@ +\ data munging + +\ 1991-03-30[\t10.000\t[-]1]*24 + +\ 1. mean of valid (flag > 0) values per day and overall +\ 2. length of longest run of invalid values, and when it happened + +fvariable day-sum +variable day-n + +fvariable total-sum +variable total-n + +10 constant date-size \ yyyy-mm-dd +create cur-date date-size allot + +create bad-date date-size allot +variable bad-n + +create worst-date date-size allot +variable worst-n + +: split ( buf len char -- buf' l2 buf l1 ) \ where buf'[0] = char, l1 = len-l2 + >r 2dup r> scan + 2swap 2 pick - ; + +: next-sample ( buf len -- buf' len' fvalue flag ) + #tab split >float drop 1 /string + #tab split snumber? drop >r 1 /string r> ; + +: ok? 0> ; + +: add-sample ( value -- ) + day-sum f@ f+ day-sum f! + 1 day-n +! ; + +: add-day + day-sum f@ total-sum f@ f+ total-sum f! + day-n @ total-n +! ; + +: add-bad-run + bad-n @ 0= if + cur-date bad-date date-size move + then + 1 bad-n +! ; + +: check-worst-run + bad-n @ worst-n @ > if + bad-n @ worst-n ! + bad-date worst-date date-size move + then + 0 bad-n ! ; + +: hour ( buf len -- buf' len' ) + next-sample ok? if + add-sample + check-worst-run + else + fdrop + add-bad-run + then ; + +: .mean ( sum count -- ) 0 d>f f/ f. ; + +: day ( line len -- ) + 2dup + #tab swap c! 1+ \ append tab for parsing + #tab split cur-date swap move 1 /string \ skip date + 0e day-sum f! + 0 day-n ! + 24 0 do hour loop 2drop + cur-date date-size type ." mean = " + day-sum f@ day-n @ .mean cr + add-day ; + +stdin value input + +: main + s" input.txt" r/o open-file throw to input + 0e total-sum f! + 0 total-n ! + 0 worst-n ! + begin pad 512 input read-line throw + while pad swap day + repeat + input close-file throw + worst-n @ if + ." Longest interruption: " worst-n @ . + ." hours starting " worst-date date-size type cr + then + ." Total mean = " + total-sum f@ total-n @ .mean cr ; + +main bye diff --git a/Task/Text-processing-1/Go/text-processing-1.go b/Task/Text-processing-1/Go/text-processing-1.go new file mode 100644 index 0000000000..cc74f689c9 --- /dev/null +++ b/Task/Text-processing-1/Go/text-processing-1.go @@ -0,0 +1,101 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +var fn = "readings.txt" + +func main() { + f, err := os.Open(fn) + if err != nil { + fmt.Println(err) + return + } + defer f.Close() + var ( + badRun, maxRun int + badDate, maxDate string + fileSum float64 + fileAccept int + ) + for lr := bufio.NewReader(f); ; { + line, pref, err := lr.ReadLine() + if err == io.EOF { + break + } + if err != nil { + fmt.Println(err) + return + } + if pref { + fmt.Println("Unexpected long line.") + return + } + f := strings.Fields(string(line)) + if len(f) != 49 { + fmt.Println("unexpected format,", len(f), "fields.") + return + } + var accept int + var sum float64 + for i := 1; i < 49; i += 2 { + flag, err := strconv.Atoi(f[i+1]) + if err != nil { + fmt.Println(err) + return + } + if flag > 0 { // value is good + if badRun > 0 { // terminate bad run + if badRun > maxRun { + maxRun = badRun + maxDate = badDate + } + badRun = 0 + } + value, err := strconv.ParseFloat(f[i], 64) + if err != nil { + fmt.Println(err) + return + } + sum += value + accept++ + } else { // value is bad + if badRun == 0 { + badDate = f[0] + } + badRun++ + } + } + fmt.Printf("Line: %s Reject %2d Accept: %2d Line_tot:%9.3f", + f[0], 24-accept, accept, sum) + if accept > 0 { + fmt.Printf(" Line_avg:%8.3f\n", sum/float64(accept)) + } else { + fmt.Println("") + } + fileSum += sum + fileAccept += accept + } + fmt.Println("\nFile =", fn) + fmt.Printf("Total = %.3f\n", fileSum) + fmt.Println("Readings = ", fileAccept) + if fileAccept > 0 { + fmt.Printf("Average = %.3f\n", fileSum/float64(fileAccept)) + } + if badRun > 0 && badRun > maxRun { + maxRun = badRun + maxDate = badDate + } + if maxRun == 0 { + fmt.Println("\nAll data valid.") + } else { + fmt.Printf("\nMax data gap = %d, beginning on line %s.\n", + maxRun, maxDate) + } +} diff --git a/Task/Text-processing-1/Haskell/text-processing-1-1.hs b/Task/Text-processing-1/Haskell/text-processing-1-1.hs new file mode 100644 index 0000000000..604275ca93 --- /dev/null +++ b/Task/Text-processing-1/Haskell/text-processing-1-1.hs @@ -0,0 +1,47 @@ +import Data.List +import Numeric +import Control.Arrow +import Control.Monad +import Text.Printf +import System.Environment +import Data.Function + +type Date = String +type Value = Double +type Flag = Bool + +readFlg :: String -> Flag +readFlg = (> 0).read + +readNum :: String -> Value +readNum = fst.head.readFloat + +take2 = takeWhile(not.null).unfoldr (Just.splitAt 2) + +parseData :: [String] -> (Date,[(Value,Flag)]) +parseData = head &&& map(readNum.head &&& readFlg.last).take2.tail + +sumAccs :: (Date,[(Value,Flag)]) -> (Date, ((Value,Int),[Flag])) +sumAccs = second (((sum &&& length).concat.uncurry(zipWith(\v f -> [v|f])) &&& snd).unzip) + +maxNAseq :: [Flag] -> [(Int,Int)] +maxNAseq = head.groupBy((==) `on` fst).sortBy(flip compare) + . concat.uncurry(zipWith(\i (r,b)->[(r,i)|not b])) + . first(init.scanl(+)0). unzip + . map ((fst &&& id).(length &&& head)). group + +main = do + file:_ <- getArgs + f <- readFile file + let dat :: [(Date,((Value,Int),[Flag]))] + dat = map (sumAccs. parseData. words).lines $ f + summ = ((sum *** sum). unzip *** maxNAseq.concat). unzip $ map snd dat + totalFmt = "\nSummary\t\t accept: %d\t total: %.3f \taverage: %6.3f\n\n" + lineFmt = "%8s\t accept: %2d\t total: %11.3f \taverage: %6.3f\n" + maxFmt = "Maximum of %d consecutive false readings, starting on line /%s/ and ending on line /%s/\n" +-- output statistics + putStrLn "\nSome lines:\n" + mapM_ (\(d,((v,n),_)) -> printf lineFmt d n v (v/fromIntegral n)) $ take 4 $ drop 2200 dat + (\(t,n) -> printf totalFmt n t (t/fromIntegral n)) $ fst summ + mapM_ ((\(l, d1,d2) -> printf maxFmt l d1 d2) + . (\(a,b)-> (a,(fst.(dat!!).(`div`24))b,(fst.(dat!!).(`div`24))(a+b)))) $ snd summ diff --git a/Task/Text-processing-1/Haskell/text-processing-1-2.hs b/Task/Text-processing-1/Haskell/text-processing-1-2.hs new file mode 100644 index 0000000000..707ef7c5c3 --- /dev/null +++ b/Task/Text-processing-1/Haskell/text-processing-1-2.hs @@ -0,0 +1 @@ +*Main> :main ["./RC/readings.txt"] diff --git a/Task/Text-processing-1/Icon/text-processing-1.icon b/Task/Text-processing-1/Icon/text-processing-1.icon new file mode 100644 index 0000000000..420720b541 --- /dev/null +++ b/Task/Text-processing-1/Icon/text-processing-1.icon @@ -0,0 +1,51 @@ +record badrun(count,fromdate,todate) # record to track bad runs + +procedure main() +return mungetask1("readings1-input.txt","readings1-output.txt") +end + +procedure mungetask1(fin,fout) + +fin := open(fin) | stop("Unable to open input file ",fin) +fout := open(fout,"w") | stop("Unable to open output file ",fout) + +F_tot := F_acc := F_rej := 0 # data set totals +rejmax := badrun(-1) # longest reject runs +rejcur := badrun(0) # current reject runs + +while line := read(fin) do { + line ? { + ldate := tab(many(&digits ++ '-')) # date (poorly checked) + fields := tot := rej := 0 # record counters & totals + + while tab(many(' \t')) do { # whitespace before every pair + value := real(tab(many(&digits++'-.'))) | stop("Bad value in ",ldate) + tab(many(' \t')) + flag := integer(tab(many(&digits++'-'))) | stop("Bad flag in ",ldate) + fields +:= 1 + + if flag > 0 then { # good data, ends a bad run + if rejcur.count > rejmax.count then rejmax := rejcur + rejcur := badrun(0) + tot +:= value + } + else { # bad (flagged) data + if rejcur.count = 0 then rejcur.fromdate := ldate + rejcur.todate := ldate + rejcur.count +:= 1 + rej +:= 1 + } + } + } + F_tot +:= tot + F_acc +:= acc := fields - rej + F_rej +:= rej + write(fout,"Line: ",ldate," Reject: ", rej," Accept: ", acc," Line_tot: ",tot," Line_avg: ", if acc > 0 then tot / acc else 0) + } + +write(fout,"\nTotal = ",F_tot,"\nReadings = ",F_acc,"\nRejects = ",F_rej,"\nAverage = ",F_tot / F_acc) +if rejmax.count > 0 then + write(fout,"Maximum run of bad data was ",rejmax.count," readings from ",rejmax.fromdate," to ",rejmax.todate) +else + write(fout,"No bad runs of data") +end diff --git a/Task/Text-processing-1/J/text-processing-1-1.j b/Task/Text-processing-1/J/text-processing-1-1.j new file mode 100644 index 0000000000..aad9239cf7 --- /dev/null +++ b/Task/Text-processing-1/J/text-processing-1-1.j @@ -0,0 +1,14 @@ + load 'files' + parseLine=: 10&({. ,&< (_99&".;._1)@:}.) NB. custom parser + summarize=: # , +/ , +/ % # NB. count,sum,mean + filter=: #~ 0&< NB. keep valid measurements + + 'Dates dat'=: |: parseLine;._2 CR -.~ fread jpath '~temp/readings.txt' + Vals=: (+: i.24){"1 dat + Flags=: (>: +: i.24){"1 dat + DailySummary=: Vals summarize@filter"1 Flags + RunLengths=: ([: #(;.1) 0 , }. *. }:) , 0 >: Flags + ]MaxRun=: >./ RunLengths +589 + ]StartDates=: Dates {~ (>:@I.@e.&MaxRun (24 <.@%~ +/)@{. ]) RunLengths +1993-03-05 diff --git a/Task/Text-processing-1/J/text-processing-1-2.j b/Task/Text-processing-1/J/text-processing-1-2.j new file mode 100644 index 0000000000..c1ac8c2706 --- /dev/null +++ b/Task/Text-processing-1/J/text-processing-1-2.j @@ -0,0 +1,11 @@ +formatDailySumry=: dyad define + labels=. , ];.2 'Line: Accept: Line_tot: Line_avg: ' + labels , x ,. 7j0 10j3 10j3 ": y +) +formatFileSumry=: dyad define + labels=. ];.2 'Total: Readings: Average: ' + sumryvals=. (, %/) 1 0{ +/y + out=. labels ,. 12j3 12j0 12j3 ":&> sumryvals + 'maxrun dates'=. x + out=. out,LF,'Maximum run(s) of ',(": maxrun),' consecutive false readings ends at line(s) starting with date(s): ',dates +) diff --git a/Task/Text-processing-1/J/text-processing-1-3.j b/Task/Text-processing-1/J/text-processing-1-3.j new file mode 100644 index 0000000000..a98291b685 --- /dev/null +++ b/Task/Text-processing-1/J/text-processing-1-3.j @@ -0,0 +1,13 @@ + (_4{.Dates) formatDailySumry _4{. DailySummary +Line: Accept: Line_tot: Line_avg: +2004-12-28 23 77.800 3.383 +2004-12-29 23 56.300 2.448 +2004-12-30 23 65.300 2.839 +2004-12-31 23 47.300 2.057 + + (MaxRun;StartDates) formatFileSumry DailySummary +Total: 1358393.400 +Readings: 129403 +Average: 10.497 + +Maximum run(s) of 589 consecutive false readings ends at line(s) starting with date(s): 1993-03-05 diff --git a/Task/Text-processing-1/JavaScript/text-processing-1.js b/Task/Text-processing-1/JavaScript/text-processing-1.js new file mode 100644 index 0000000000..0c0ad02ff0 --- /dev/null +++ b/Task/Text-processing-1/JavaScript/text-processing-1.js @@ -0,0 +1,69 @@ +var filename = 'readings.txt'; +var show_lines = 5; +var file_stats = { + 'num_readings': 0, + 'total': 0, + 'reject_run': 0, + 'reject_run_max': 0, + 'reject_run_date': '' +}; + +var fh = new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1); // 1 = for reading +while ( ! fh.atEndOfStream) { + var line = fh.ReadLine(); + line_stats(line, (show_lines-- > 0)); +} +fh.close(); + +WScript.echo( + "\nFile(s) = " + filename + "\n" + + "Total = " + dec3(file_stats.total) + "\n" + + "Readings = " + file_stats.num_readings + "\n" + + "Average = " + dec3(file_stats.total / file_stats.num_readings) + "\n\n" + + "Maximum run of " + file_stats.reject_run_max + + " consecutive false readings ends at " + file_stats.reject_run_date +); + +function line_stats(line, print_line) { + var readings = 0; + var rejects = 0; + var total = 0; + var fields = line.split('\t'); + var date = fields.shift(); + + while (fields.length > 0) { + var value = parseFloat(fields.shift()); + var flag = parseInt(fields.shift(), 10); + readings++; + if (flag <= 0) { + rejects++; + file_stats.reject_run++; + } + else { + total += value; + if (file_stats.reject_run > file_stats.reject_run_max) { + file_stats.reject_run_max = file_stats.reject_run; + file_stats.reject_run_date = date; + } + file_stats.reject_run = 0; + } + } + + file_stats.num_readings += readings - rejects; + file_stats.total += total; + + if (print_line) { + WScript.echo( + "Line: " + date + "\t" + + "Reject: " + rejects + "\t" + + "Accept: " + (readings - rejects) + "\t" + + "Line_tot: " + dec3(total) + "\t" + + "Line_avg: " + ((readings == rejects) ? "0.0" : dec3(total / (readings - rejects))) + ); + } +} + +// round a number to 3 decimal places +function dec3(value) { + return Math.round(value * 1e3) / 1e3; +} diff --git a/Task/Text-processing-1/Lua/text-processing-1.lua b/Task/Text-processing-1/Lua/text-processing-1.lua new file mode 100644 index 0000000000..9fb810c572 --- /dev/null +++ b/Task/Text-processing-1/Lua/text-processing-1.lua @@ -0,0 +1,49 @@ +filename = "readings.txt" +io.input( filename ) + +file_sum, file_cnt_data, file_lines = 0, 0, 0 +max_rejected, n_rejected = 0, 0 +max_rejected_date, rejected_date = "", "" + +while true do + data = io.read("*line") + if data == nil then break end + + date = string.match( data, "%d+%-%d+%-%d+" ) + if date == nil then break end + + val = {} + for w in string.gmatch( data, "%s%-*%d+[%.%d]*" ) do + val[#val+1] = tonumber(w) + end + + sum, cnt = 0, 0 + for i = 1, #val, 2 do + if val[i+1] > 0 then + sum = sum + val[i] + cnt = cnt + 1 + n_rejected = 0 + else + if n_rejected == 0 then + rejected_date = date + end + n_rejected = n_rejected + 1 + if n_rejected > max_rejected then + max_rejected = n_rejected + max_rejected_date = rejected_date + end + end + end + + file_sum = file_sum + sum + file_cnt_data = file_cnt_data + cnt + file_lines = file_lines + 1 + + print( string.format( "%s:\tRejected: %d\tAccepted: %d\tLine_total: %f\tLine_average: %f", date, #val/2-cnt, cnt, sum, sum/cnt ) ) +end + +print( string.format( "\nFile:\t %s", filename ) ) +print( string.format( "Total:\t %f", file_sum ) ) +print( string.format( "Readings: %d", file_lines ) ) +print( string.format( "Average: %f", file_sum/file_cnt_data ) ) +print( string.format( "Maximum %d consecutive false readings starting at %s.", max_rejected, max_rejected_date ) ) diff --git a/Task/Text-processing-1/Mathematica/text-processing-1.math b/Task/Text-processing-1/Mathematica/text-processing-1.math new file mode 100644 index 0000000000..8c251dbe46 --- /dev/null +++ b/Task/Text-processing-1/Mathematica/text-processing-1.math @@ -0,0 +1,16 @@ +FileName = "Readings.txt"; data = Import[FileName,"TSV"]; + +Scan[(a=Position[#[[3;;All;;2]],1]; +Print["Line:",#[[1]] ,"\tReject:", 24 - Length[a], "\t Accept:", Length[a], "\tLine_tot:", +Total@Part[#, Flatten[2*a]] , "\tLine_avg:", Total@Part[#, Flatten[2*a]]/Length[a]])&, data] + +GlobalSum = Nb = Running = MaxRunRecorded = 0; MaxRunTime = {}; +Scan[ For[i = 3, i < 50, i = i + 2, + If[#[[i]] == 1, + Running=0; GlobalSum += #[[i-1]]; Nb++;, + Running ++; If[MaxRunRecorded < Running, MaxRunRecorded = Running;MaxRunTime={ #[[1]]}; ]; + ]] &, data ] + +Print["\nFile(s) : ",FileName,"\nTotal : ",AccountingForm@GlobalSum,"\nReadings : ",Nb, +"\nAverage : ",GlobalSum/Nb,"\n\nMaximum run(s) of ",MaxRunRecorded, +" consecutive false readings ends at line starting with date(s):",MaxRunTime] diff --git a/Task/Text-processing-1/OCaml/text-processing-1.ocaml b/Task/Text-processing-1/OCaml/text-processing-1.ocaml new file mode 100644 index 0000000000..7dceba1c2a --- /dev/null +++ b/Task/Text-processing-1/OCaml/text-processing-1.ocaml @@ -0,0 +1,67 @@ +let input_line ic = + try Some(input_line ic) + with End_of_file -> None + +let fold_input f ini ic = + let rec fold ac = + match input_line ic with + | Some line -> fold (f ac line) + | None -> ac + in + fold ini + +let ic = open_in "readings.txt" + +let scan line = + Scanf.sscanf line "%s\ + \t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\ + \t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\ + \t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\ + \t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d\t%f\t%d" + (fun date + v1 f1 v2 f2 v3 f3 v4 f4 v5 f5 v6 f6 + v7 f7 v8 f8 v9 f9 v10 f10 v11 f11 v12 f12 + v13 f13 v14 f14 v15 f15 v16 f16 v17 f17 v18 f18 + v19 f19 v20 f20 v21 f21 v22 f22 v23 f23 v24 f24 -> + (date), + [ (v1, f1 ); (v2, f2 ); (v3, f3 ); (v4, f4 ); (v5, f5 ); (v6, f6 ); + (v7, f7 ); (v8, f8 ); (v9, f9 ); (v10, f10); (v11, f11); (v12, f12); + (v13, f13); (v14, f14); (v15, f15); (v16, f16); (v17, f17); (v18, f18); + (v19, f19); (v20, f20); (v21, f21); (v22, f22); (v23, f23); (v24, f24); ]) + +let tot_file, num_file, _, nodata_max, nodata_maxline = + fold_input + (fun (tot_file, num_file, nodata, nodata_max, nodata_maxline) line -> + let date, datas = scan line in + let _datas = List.filter (fun (_, flag) -> flag > 0) datas in + let ok = List.length _datas in + let tot = List.fold_left (fun ac (value, _) -> ac +. value) 0.0 _datas in + let nodata, nodata_max, nodata_maxline = + List.fold_left + (fun (nodata, nodata_max, nodata_maxline) (_, flag) -> + if flag <= 0 + then (succ nodata, nodata_max, nodata_maxline) + else + if nodata_max = nodata && nodata > 0 + then (0, nodata_max, date::nodata_maxline) + else if nodata_max < nodata && nodata > 0 + then (0, nodata, [date]) + else (0, nodata_max, nodata_maxline) + ) + (nodata, nodata_max, nodata_maxline) datas in + Printf.printf "Line: %s" date; + Printf.printf " Reject: %2d Accept: %2d" (24 - ok) ok; + Printf.printf "\tLine_tot: %8.3f" tot; + Printf.printf "\tLine_avg: %8.3f\n" (tot /. float ok); + (tot_file +. tot, num_file + ok, nodata, nodata_max, nodata_maxline)) + (0.0, 0, 0, 0, []) + ic ;; + +close_in ic ;; + +Printf.printf "Total = %f\n" tot_file; +Printf.printf "Readings = %d\n" num_file; +Printf.printf "Average = %f\n" (tot_file /. float num_file); +Printf.printf "Maximum run(s) of %d consecutive false readings \ + ends at line starting with date(s): %s\n" + nodata_max (String.concat ", " nodata_maxline); diff --git a/Task/Text-processing-1/PL-I/text-processing-1.pli b/Task/Text-processing-1/PL-I/text-processing-1.pli new file mode 100644 index 0000000000..999bda36f9 --- /dev/null +++ b/Task/Text-processing-1/PL-I/text-processing-1.pli @@ -0,0 +1,54 @@ +text1: procedure options (main); /* 13 May 2010 */ + + declare line character (2000) varying; + declare 1 pairs(24), + 2 value fixed (10,4), + 2 flag fixed; + declare date character (12) varying; + declare no_items fixed decimal (10); + declare (nv, sum, line_no, ndud_values, max_ndud_values) fixed; + declare (i, k) fixed binary; + declare in file input; + + open file (in) title ('/TEXT1.DAT,TYPE(TEXT),RECSIZE(2000)' ); + + on endfile (in) go to finish_up; + + line_no = 0; +loop: + do forever; + get file (in) edit (line) (L); + /* put skip list (line); */ + line = translate(line, ' ', '09'x); + line_no = line_no + 1; + line = trim(line); + no_items = tally(line, ' ') - tally(line, ' ') + 1; + if no_items ^= 49 then + do; put skip list ('There are not 49 items on this line'); iterate loop; end; + k = index(line, ' '); /* Find the first blank in the line. */ + date = substr(line, 1, k); + line = substr(line, k) || ' '; + on conversion go to loop; + get string (line) list (pairs); + sum, nv, ndud_values, max_ndud_values = 0; + do i = 1 to 24; + if flag(i) > 0 then + do; sum = sum + value(i); nv = nv + 1; + ndud_values = 0; /* reset the counter of dud values */ + end; + else + do; /* we have a dud reading. */ + ndud_values = ndud_values + 1; + if ndud_values > max_ndud_values then + max_ndud_values = ndud_values; + end; + end; + if nv = 0 then iterate; + put skip list ('Line ' || trim(line_no) || ' average=', divide(sum, nv, 10,4) ); + if max_ndud_values > 0 then + put skip list ('Maximum run of dud readings =', max_ndud_values); + end; + +finish_up: + +end text1; diff --git a/Task/Text-processing-1/Perl-6/text-processing-1.pl6 b/Task/Text-processing-1/Perl-6/text-processing-1.pl6 new file mode 100644 index 0000000000..1c18344e45 --- /dev/null +++ b/Task/Text-processing-1/Perl-6/text-processing-1.pl6 @@ -0,0 +1,33 @@ +my @gaps; +my $previous = 'valid'; + +for $*IN.lines -> $line { + my ($date, @readings) = split /\s+/, $line; + my @valid; + my $hour = 0; + for @readings -> $reading, $flag { + if $flag > 0 { + @valid.push($reading); + if $previous eq 'invalid' { + @gaps[*-1]{'end'} = "$date $hour:00"; + $previous = 'valid'; + } + } + else + { + if $previous eq 'valid' { + @gaps.push( {start => "$date $hour:00"} ); + } + @gaps[*-1]{'count'}++; + $previous = 'invalid'; + } + $hour++; + } + say "$date: { ( +@valid ?? ( ( [+] @valid ) / +@valid ).fmt("%.3f") !! 0 ).fmt("%8s") }", + " mean from { (+@valid).fmt("%2s") } valid."; +}; + +my $longest = @gaps.sort({-$^a})[0]; + +say "Longest period of invalid readings was {$longest} hours,\n", + "from {$longest} till {$longest}." diff --git a/Task/Text-processing-1/Perl/text-processing-1-1.pl b/Task/Text-processing-1/Perl/text-processing-1-1.pl new file mode 100644 index 0000000000..f878246917 --- /dev/null +++ b/Task/Text-processing-1/Perl/text-processing-1-1.pl @@ -0,0 +1,59 @@ +use strict; +use warnings; + +my $nodata = 0; # Current run of consecutive flags<0 in lines of file +my $nodata_max = -1; # Max consecutive flags<0 in lines of file +my $nodata_maxline = "!"; # ... and line number(s) where it occurs + +my $infiles = join ", ", @ARGV; + +my $tot_file = 0; +my $num_file = 0; + +while (<>) { + chomp; + my $tot_line = 0; # sum of line data + my $num_line = 0; # number of line data items with flag>0 + my $rejects = 0; + + # extract field info, skipping initial date field + my ($date, @fields) = split; + while (@fields and my ($datum, $flag) = splice @fields, 0, 2) { + if ($flag+1 < 2) { + $nodata++; + $rejects++; + next; + } + + # check run of data-absent fields + if($nodata_max == $nodata and $nodata > 0){ + $nodata_maxline = "$nodata_maxline, $date"; + } + if($nodata_max < $nodata and $nodata > 0){ + $nodata_max = $nodata; + $nodata_maxline = $date; + } + # re-initialise run of nodata counter + $nodata = 0; + # gather values for averaging + $tot_line += $datum; + $num_line++; + } + + # totals for the file so far + $tot_file += $tot_line; + $num_file += $num_line; + + printf "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f\n", + $date, $rejects, $num_line, $tot_line, ($num_line>0)? $tot_line/$num_line: 0; + +} + +printf "\n"; +printf "File(s) = %s\n", $infiles; +printf "Total = %10.3f\n", $tot_file; +printf "Readings = %6i\n", $num_file; +printf "Average = %10.3f\n", $tot_file / $num_file; + +printf "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s\n", + $nodata_max, $nodata_maxline; diff --git a/Task/Text-processing-1/Perl/text-processing-1-2.pl b/Task/Text-processing-1/Perl/text-processing-1-2.pl new file mode 100644 index 0000000000..f09dd4bdea --- /dev/null +++ b/Task/Text-processing-1/Perl/text-processing-1-2.pl @@ -0,0 +1,115 @@ +use strict; +use warnings; + +use constant RESULT_TEMPLATE => "%-19s = %12.3f / %-6u = %.3f\n"; + +my $parser = Parser->new; + +# parse lines and print results +printf RESULT_TEMPLATE, $parser->parse(split) + while <>; + +$parser->finish; + +# print total and summary +printf "\n".RESULT_TEMPLATE."\n", $parser->result; +printf "the maximum of %u consecutive bad values was reached %u time(s)\n", + $parser->bad_max, scalar $parser->bad_ranges; + +# print bad ranges +print for map { ' '.join(' - ', @$_)."\n" } $parser->bad_ranges; + +BEGIN { + package main::Parser; + + sub new { + my $obj = { + SUM => 0, + COUNT => 0, + CURRENT_DATE => undef, + BAD_DATE => undef, + BAD_RANGES => [], + BAD_MAX => 0, + BAD_COUNT => 0 + }; + + return bless $obj; + } + + sub _average { + my ($sum, $count) = @_; + return ($sum, $count, $count && $sum / $count); + } + + sub _push_bad_range_if_necessary { + my ($parser) = @_; + my ($count, $max) = @$parser{qw(BAD_COUNT BAD_MAX)}; + + return if $count < $max; + + if ($count > $max) { + $parser->{BAD_RANGES} = []; + $parser->{BAD_MAX} = $count; + } + + push @{$parser->{BAD_RANGES}}, [ @$parser{qw(BAD_DATE CURRENT_DATE)} ]; + } + + sub _check { + my ($parser, $flag) = @_; + if ($flag <= 0) { + ++$parser->{BAD_COUNT}; + $parser->{BAD_DATE} = $parser->{CURRENT_DATE} + unless defined $parser->{BAD_DATE}; + + return 0; + } + else { + $parser->_push_bad_range_if_necessary; + $parser->{BAD_COUNT} = 0; + $parser->{BAD_DATE} = undef; + return 1; + } + } + + sub bad_max { + my ($parser) = @_; + return $parser->{BAD_MAX} + } + + sub bad_ranges { + my ($parser) = @_; + return @{$parser->{BAD_RANGES}} + } + + sub parse { + my $parser = shift; + my $date = shift; + + $parser->{CURRENT_DATE} = $date; + + my $sum = 0; + my $count = 0; + + while (my ($value, $flag) = splice @_, 0, 2) { + next unless $parser->_check($flag); + $sum += $value; + ++$count; + } + + $parser->{SUM} += $sum; + $parser->{COUNT} += $count; + + return ("average($date)", _average($sum, $count)); + } + + sub result { + my ($parser) = @_; + return ('total-average', _average(@$parser{qw(SUM COUNT)})); + } + + sub finish { + my ($parser) = @_; + $parser->_push_bad_range_if_necessary + } +} diff --git a/Task/Text-processing-1/PicoLisp/text-processing-1.l b/Task/Text-processing-1/PicoLisp/text-processing-1.l new file mode 100644 index 0000000000..0f1751986c --- /dev/null +++ b/Task/Text-processing-1/PicoLisp/text-processing-1.l @@ -0,0 +1,43 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(let (NoData 0 NoDataMax -1 NoDataMaxline "!" TotFile 0 NumFile 0) + (let InFiles + (glue "," + (mapcar + '((File) + (in File + (while (split (line) "^I") + (let (Len (length @) Date (car @) TotLine 0 NumLine 0) + (for (L (cdr @) L (cddr L)) + (if (> 1 (format (cadr L))) + (inc 'NoData) + (when (gt0 NoData) + (when (= NoDataMax NoData) + (setq NoDataMaxline (pack NoDataMaxline ", " Date)) ) + (when (> NoData NoDataMax) + (setq NoDataMax NoData NoDataMaxline Date) ) ) + (zero NoData) + (inc 'TotLine (format (car L) 3)) + (inc 'NumLine) ) ) + (inc 'TotFile TotLine) + (inc 'NumFile NumLine) + (tab (-7 -12 -7 3 -9 3 -11 11 -11 11) + "Line:" Date + "Reject:" (- (/ (dec Len) 2) NumLine) + " Accept:" NumLine + " Line_tot:" (format TotLine 3) + " Line_avg:" + (and (gt0 NumLine) (format (*/ TotLine @) 3)) ) ) ) ) + File ) + (argv) ) ) + (prinl) + (prinl "File(s) = " InFiles) + (prinl "Total = " (format TotFile 3)) + (prinl "Readings = " NumFile) + (prinl "Average = " (format (*/ TotFile NumFile) 3)) + (prinl) + (prinl + "Maximum run(s) of " NoDataMax + " consecutive false readings ends at line starting with date(s): " NoDataMaxline ) ) ) + +(bye) diff --git a/Task/Text-processing-1/PureBasic/text-processing-1.purebasic b/Task/Text-processing-1/PureBasic/text-processing-1.purebasic new file mode 100644 index 0000000000..4ce1ec27e2 --- /dev/null +++ b/Task/Text-processing-1/PureBasic/text-processing-1.purebasic @@ -0,0 +1,47 @@ +#TASK="Text processing/1" +Define File$, InLine$, Part$, i, Out$, ErrEnds$, Errcnt, ErrMax +Define lsum.d, tsum.d, rejects, val.d, readings + +File$=OpenFileRequester(#TASK,"readings.txt","",0) +If OpenConsole() And ReadFile(0,File$) + While Not Eof(0) + InLine$=ReadString(0) + For i=1 To 1+2*24 + Part$=StringField(InLine$,i,#TAB$) + If i=1 ; Date + Out$=Part$: lsum=0: rejects=0 + ElseIf i%2=0 ; Recorded value + val=ValD(Part$) + Else ; Status part + If Val(Part$)>0 + Errcnt=0 : readings+1 + lsum+val : tsum+val + Else + rejects+1: Errcnt+1 + If Errcnt>ErrMax + ErrMax=Errcnt + ErrEnds$=Out$ + EndIf + EndIf + EndIf + Next i + Out$+" Rejects: " + Str(rejects) + Out$+" Accepts: " + Str(24-rejects) + Out$+" Line_tot: "+ StrD(lsum,3) + If rejects<24 + Out$+" Line_avg: "+StrD(lsum/(24-rejects),3) + Else + Out$+" Line_avg: N/A" + EndIf + PrintN("Line: "+Out$) + Wend + PrintN(#CRLF$+"File = "+GetFilePart(File$)) + PrintN("Total = "+ StrD(tsum,3)) + PrintN("Readings = "+ Str(readings)) + PrintN("Average = "+ StrD(tsum/readings,3)) + Print(#CRLF$+"Maximum of "+Str(ErrMax)) + PrintN(" consecutive false readings, ends at "+ErrEnds$) + CloseFile(0) + ; + Print("Press ENTER to exit"): Input() +EndIf diff --git a/Task/Text-processing-1/Python/text-processing-1.py b/Task/Text-processing-1/Python/text-processing-1.py new file mode 100644 index 0000000000..cba387217a --- /dev/null +++ b/Task/Text-processing-1/Python/text-processing-1.py @@ -0,0 +1,56 @@ +import fileinput +import sys + +nodata = 0; # Current run of consecutive flags<0 in lines of file +nodata_max=-1; # Max consecutive flags<0 in lines of file +nodata_maxline=[]; # ... and line number(s) where it occurs + +tot_file = 0 # Sum of file data +num_file = 0 # Number of file data items with flag>0 + +infiles = sys.argv[1:] + +for line in fileinput.input(): + tot_line=0; # sum of line data + num_line=0; # number of line data items with flag>0 + + # extract field info + field = line.split() + date = field[0] + data = [float(f) for f in field[1::2]] + flags = [int(f) for f in field[2::2]] + + for datum, flag in zip(data, flags): + if flag<1: + nodata += 1 + else: + # check run of data-absent fields + if nodata_max==nodata and nodata>0: + nodata_maxline.append(date) + if nodata_max0: + nodata_max=nodata + nodata_maxline=[date] + # re-initialise run of nodata counter + nodata=0; + # gather values for averaging + tot_line += datum + num_line += 1 + + # totals for the file so far + tot_file += tot_line + num_file += num_line + + print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( + date, + len(data) -num_line, + num_line, tot_line, + tot_line/num_line if (num_line>0) else 0) + +print "" +print "File(s) = %s" % (", ".join(infiles),) +print "Total = %10.3f" % (tot_file,) +print "Readings = %6i" % (num_file,) +print "Average = %10.3f" % (tot_file / num_file,) + +print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( + nodata_max, ", ".join(nodata_maxline)) diff --git a/Task/Text-processing-1/R/text-processing-1.r b/Task/Text-processing-1/R/text-processing-1.r new file mode 100644 index 0000000000..a307fe4c17 --- /dev/null +++ b/Task/Text-processing-1/R/text-processing-1.r @@ -0,0 +1,9 @@ +#Read in data from file +dfr <- read.delim("readings.txt") +#Calculate daily means +flags <- as.matrix(dfr[,seq(3,49,2)])>0 +vals <- as.matrix(dfr[,seq(2,49,2)]) +daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags) +#Calculate time between good measurements +times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*seq(1,24*nrow(dfr),1) +hours.between.good.measurements <- diff(times[t(flags)])/3600 diff --git a/Task/Text-processing-1/REXX/text-processing-1.rexx b/Task/Text-processing-1/REXX/text-processing-1.rexx new file mode 100644 index 0000000000..d96b5c6c49 --- /dev/null +++ b/Task/Text-processing-1/REXX/text-processing-1.rexx @@ -0,0 +1,72 @@ +/*REXX program to process instrument data from a data file. */ +numeric digits 20 /*allow for bigger numbers. */ +ifid='READINGS.TXT' /*the input file. */ +ofid='READINGS.OUT' /*the outut file. */ +grandSum=0 /*grand sum of whole file. */ +grandflg=0 /*grand num of flagged data. */ +grandOKs=0 +longFlag=0 /*longest period of flagged data.*/ +contFlag=0 /*longest continous flagged data.*/ +w=16 /*width of fields when displayed.*/ + + do recs=1 while lines(ifid)\==0 /*read until finished. */ + rec=linein(ifid) /*read the next record (line). */ + parse var rec datestamp Idata /*pick off the dateStamp & data. */ + sum=0 + flg=0 + OKs=0 + + do j=1 until Idata='' /*process the instrument data. */ + parse var Idata data.j flag.j Idata + + if flag.j>0 then do /*if good data, ... */ + OKs=OKs+1 + sum=sum+data.j + if contFlag>longFlag then do + longdate=datestamp + longFlag=contFlag + end + contFlag=0 + end + else do /*flagged data ... */ + flg=flg+1 + contFlag=contFlag+1 + end + end /*j*/ + + if OKs\==0 then avg=format(sum/OKs,,3) + else avg='[n/a]' + grandOKs=grandOKs+OKs + _=right(comma(avg),w) + grandSum=grandSum+sum + grandFlg=grandFlg+flg + if flg==0 then call sy datestamp ' average='_ + else call sy datestamp ' average='_ ' flagged='right(flg,2) + end /*recs*/ + +recs=recs-1 /*adjust for reading end-of-file.*/ +if grandOKs\==0 then Gavg=format(grandsum/grandOKs,,3) + else Gavg='[n/a]' +call sy +call sy copies('═',60) +call sy ' records read:' right(comma(recs),w) +call sy ' grand sum:' right(comma(grandSum),w+4) +call sy ' grand average:' right(comma(Gavg),w+4) +call sy ' grand OK data:' right(comma(grandOKs),w) +call sy ' grand flagged:' right(comma(grandFlg),w) +if longFlag\==0 then +call sy ' longest flagged:' right(comma(longFlag),w) " ending at " longdate +call sy copies('═',60) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SY subroutine───────────────────────*/ +sy: procedure; parse arg stuff; say stuff + if 1==0 then call lineout ofid,stuff + return +/*──────────────────────────────────COMMA subroutine────────────────────*/ +comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1) + if cu=='BLANK' then c=' ';o=word(p 3,1);p=abs(o);t=word(t 999999999,1) + if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _;n=_'.9' + #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _ + e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end + do j=e to b by -p while knumber vs.ss) ...)) + (let get-line-pairs + ((vs.ss vs.ss) (line-N 0) (reject 0) (line-sum 0) (consecutive-false consecutive-false) + (max-consecutive-false max-consecutive-false) (max-false-tags max-false-tags)) + (match vs.ss + ['() + (print-line-info tag reject line-N line-sum) + (values (+ N line-N) (+ sum line-sum) consecutive-false max-consecutive-false max-false-tags)] + [(list-rest v (? positive?) tl) + (get-line-pairs tl (add1 line-N) reject (+ line-sum v) 0 max-consecutive-false max-false-tags)] + [(list-rest _ _ tl) + (apply get-line-pairs tl line-N (add1 reject) line-sum + (handle-and-tag-max consecutive-false tag max-consecutive-false max-false-tags))]))] + (x (fprintf (current-error-port) "mismatch ~s~%" x) + (values N sum consecutive-false max-consecutive-false max-false-tags))))) + + (for/fold ((N 0) (sum 0) (consecutive-false 0) (max-consecutive-false 0) (max-false-tags null)) + ((f files-to-read)) + (with-input-from-file f + (lambda () (sub-t-p/1 N sum consecutive-false max-consecutive-false max-false-tags))))) + +(let ((files (vector->list (current-command-line-arguments)))) + (let-values (([N sum consecutive-false max-consecutive-false max-false-tags] (text-processing/1 files))) + (srfi/48:format #t "~%File(s) = ~a~%Total = ~10,3F~%Readings = ~6F~%" (string-join files) sum N) + (unless (zero? N) (srfi/48:format #t "Average = ~10,3F~%" (/ sum N))) + (srfi/48:format #t "~%Maximum run(s) of ~a consecutive false readings ends at line starting with date(s): ~a~%" + max-consecutive-false (string-join max-false-tags)))) diff --git a/Task/Text-processing-1/Ruby/text-processing-1.rb b/Task/Text-processing-1/Ruby/text-processing-1.rb new file mode 100644 index 0000000000..c52179e9f8 --- /dev/null +++ b/Task/Text-processing-1/Ruby/text-processing-1.rb @@ -0,0 +1,43 @@ +filename = "readings.txt" +total = { "num_readings" => 0, "num_good_readings" => 0, "sum_readings" => 0.0 } +invalid_count = 0 +max_invalid_count = 0 +invalid_run_end = "" + +File.new(filename).each do |line| + num_readings = 0 + num_good_readings = 0 + sum_readings = 0.0 + + fields = line.split + fields[1..-1].each_slice(2) do |reading, flag| + num_readings += 1 + if Integer(flag) > 0 + num_good_readings += 1 + sum_readings += Float(reading) + invalid_count = 0 + else + invalid_count += 1 + if invalid_count > max_invalid_count + max_invalid_count = invalid_count + invalid_run_end = fields[0] + end + end + end + + printf "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f\n", + fields[0], num_readings - num_good_readings, num_good_readings, sum_readings, + num_good_readings > 0 ? sum_readings/num_good_readings : 0.0 + + total["num_readings"] += num_readings + total["num_good_readings"] += num_good_readings + total["sum_readings"] += sum_readings +end + +puts "" +puts "File(s) = #{filename}" +printf "Total = %.3f\n", total['sum_readings'] +puts "Readings = #{total['num_good_readings']}" +printf "Average = %.3f\n", total['sum_readings']/total['num_good_readings'] +puts "" +puts "Maximum run(s) of #{max_invalid_count} consecutive false readings ends at #{invalid_run_end}" diff --git a/Task/Text-processing-1/Scala/text-processing-1-1.scala b/Task/Text-processing-1/Scala/text-processing-1-1.scala new file mode 100644 index 0000000000..71f664d242 --- /dev/null +++ b/Task/Text-processing-1/Scala/text-processing-1-1.scala @@ -0,0 +1,58 @@ +object DataMunging { + import scala.io.Source + + def spans[A](list: List[A]) = list.tail.foldLeft(List((list.head, 1))) { + case ((a, n) :: tail, b) if a == b => (a, n + 1) :: tail + case (l, b) => (b, 1) :: l + } + + type Flag = ((Boolean, Int), String) + type Flags = List[Flag] + type LineIterator = Iterator[Option[(Double, Int, Flags)]] + + val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r; + + def linesIterator(file: java.io.File) = Source.fromFile(file).getLines().map( + pattern findFirstMatchIn _ map ( + _.subgroups match { + case List(date, rawData @ _*) => + val dataset = (rawData map (_ toDouble) iterator) grouped 2 toList; + val valid = dataset filter (_.last > 0) map (_.head) + val validSize = valid length; + val validSum = valid sum; + val flags = spans(dataset map (_.last > 0)) map ((_, date)) + println("Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f" format + (date, 24 - validSize, validSize, validSum, validSum / validSize)) + (validSum, validSize, flags) + } + ) + ) + + def totalizeLines(fileIterator: LineIterator) = + fileIterator.foldLeft(0.0, 0, List[Flag]()) { + case ((totalSum, totalSize, ((flag, size), date) :: tail), Some((validSum, validSize, flags))) => + val ((firstFlag, firstSize), _) = flags.last + if (firstFlag == flag) { + (totalSum + validSum, totalSize + validSize, flags.init ::: ((flag, size + firstSize), date) :: tail) + } else { + (totalSum + validSum, totalSize + validSize, flags ::: ((flag, size), date) :: tail) + } + case ((_, _, Nil), Some(partials)) => partials + case (totals, None) => totals + } + + def main(args: Array[String]) { + val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead) + val lines = files.iterator flatMap linesIterator + val (totalSum, totalSize, flags) = totalizeLines(lines) + val ((_, invalidCount), startDate) = flags.filter(!_._1._1).max + val report = """| + |File(s) = %s + |Total = %10.3f + |Readings = %6d + |Average = %10.3f + | + |Maximum run(s) of %d consecutive false readings began at %s""".stripMargin + println(report format (files mkString " ", totalSum, totalSize, totalSum / totalSize, invalidCount, startDate)) + } +} diff --git a/Task/Text-processing-1/Scala/text-processing-1-2.scala b/Task/Text-processing-1/Scala/text-processing-1-2.scala new file mode 100644 index 0000000000..8e79ce8095 --- /dev/null +++ b/Task/Text-processing-1/Scala/text-processing-1-2.scala @@ -0,0 +1,42 @@ +object AltDataMunging { + def main(args: Array[String]) { + var totalSum = 0.0 + var totalSize = 0 + var maxInvalidDate = "" + var maxInvalidCount = 0 + var invalidDate = "" + var invalidCount = 0 + val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead) + + files.iterator flatMap (file => Source fromFile file getLines ()) map (_.trim split "\\s+") foreach { + case Array(date, rawData @ _*) => + val dataset = (rawData map (_ toDouble) iterator) grouped 2 toList; + val valid = dataset filter (_.last > 0) map (_.head) + val flags = spans(dataset map (_.last > 0)) map ((_, date)) + println("Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f" format + (date, 24 - valid.size, valid.size, valid.sum, valid.sum / valid.size)) + totalSum += valid.sum + totalSize += valid.size + dataset foreach { + case _ :: flag :: Nil if flag > 0 => + if (invalidCount > maxInvalidCount) { + maxInvalidDate = invalidDate + maxInvalidCount = invalidCount + } + invalidCount = 0 + case _ => + if (invalidCount == 0) invalidDate = date + invalidCount += 1 + } + } + + val report = """| + |File(s) = %s + |Total = %10.3f + |Readings = %6d + |Average = %10.3f + | + |Maximum run(s) of %d consecutive false readings began at %s""".stripMargin + println(report format (files mkString " ", totalSum, totalSize, totalSum / totalSize, maxInvalidCount, maxInvalidDate)) + } +} diff --git a/Task/Text-processing-1/Tcl/text-processing-1.tcl b/Task/Text-processing-1/Tcl/text-processing-1.tcl new file mode 100644 index 0000000000..a2dcfa4c24 --- /dev/null +++ b/Task/Text-processing-1/Tcl/text-processing-1.tcl @@ -0,0 +1,41 @@ +set max_invalid_run 0 +set max_invalid_run_end "" +set tot_file 0 +set num_file 0 + +set linefmt "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f" + +set filename readings.txt +set fh [open $filename] +while {[gets $fh line] != -1} { + set tot_line [set count [set num_line 0]] + set fields [regexp -all -inline {\S+} $line] + set date [lindex $fields 0] + foreach {val flag} [lrange $fields 1 end] { + incr count + if {$flag > 0} { + incr num_line + incr num_file + set tot_line [expr {$tot_line + $val}] + set invalid_run_count 0 + } else { + incr invalid_run_count + if {$invalid_run_count > $max_invalid_run} { + set max_invalid_run $invalid_run_count + set max_invalid_run_end $date + } + } + } + set tot_file [expr {$tot_file + $tot_line}] + puts [format $linefmt $date [expr {$count - $num_line}] $num_line $tot_line \ + [expr {$num_line > 0 ? $tot_line / $num_line : 0}]] +} +close $fh + +puts "" +puts "File(s) = $filename" +puts "Total = [format %.3f $tot_file]" +puts "Readings = $num_file" +puts "Average = [format %.3f [expr {$tot_file / $num_file}]]" +puts "" +puts "Maximum run(s) of $max_invalid_run consecutive false readings ends at $max_invalid_run_end" diff --git a/Task/Text-processing-1/Ursala/text-processing-1.ursala b/Task/Text-processing-1/Ursala/text-processing-1.ursala new file mode 100644 index 0000000000..1b323643d6 --- /dev/null +++ b/Task/Text-processing-1/Ursala/text-processing-1.ursala @@ -0,0 +1,21 @@ +#import std +#import nat +#import flo + +parsed_data = ^|A(~&,* ^|/%ep@iNC ~&h==`1)*htK27K28pPCS (sep 9%cOi&)*FyS readings_dot_txt + +daily_stats = + +* ^|A(~&,@rFlS ^/length ^/plus:-0. ||0.! ~&i&& mean); mat` + <. + ~&n, + 'accept: '--+ @ml printf/'%7.0f'+ float, + 'total: '--+ @mrl printf/'%10.1f', + 'average: '--+ @mrr printf/'%7.3f'> + +long_run = + +-+ + ~&i&& ^|TNC('maximum of '--@h+ %nP,' consecutive false readings ending on line '--), + @nmrSPDSL -&~&,leql$^; ^/length ~&zn&-@hrZPF+ rlc both ~&rZ+- + +main = ^T(daily_stats^lrNCT/~& @mSL 'summary ':,long_run) parsed_data diff --git a/Task/Text-processing-1/Vedit-macro-language/text-processing-1.vedit b/Task/Text-processing-1/Vedit-macro-language/text-processing-1.vedit new file mode 100644 index 0000000000..dc353ab7ca --- /dev/null +++ b/Task/Text-processing-1/Vedit-macro-language/text-processing-1.vedit @@ -0,0 +1,68 @@ +#50 = Buf_Num // Current edit buffer (source data) +File_Open("output.txt") +#51 = Buf_Num // Edit buffer for output file +Buf_Switch(#50) +#10 = 0 // total sum of file data +#11 = 0 // number of valid data items in file +#12 = 0 // Current run of consecutive flags<0 in lines of file +#13 = -1 // Max consecutive flags<0 in lines of file +Reg_Empty(15) // ... and date tag(s) at line(s) where it occurs + +While(!At_EOF) { + #20 = 0 // sum of line data + #21 = 0 // number of line data items with flag>0 + #22 = 0 // number of line data items with flag<0 + Reg_Copy_Block(14, Cur_Pos, Cur_Pos+10) // date field + + // extract field info, skipping initial date field + Repeat(ALL) { + Search("|{|T,|N}", ADVANCE+ERRBREAK) // next Tab or Newline + if (Match_Item==2) { Break } // end of line + #30 = Num_Eval(ADVANCE) * 1000 // #30 = value + Char // fixed point, 3 decimal digits + #30 += Num_Eval(ADVANCE+SUPPRESS) + #31 = Num_Eval(ADVANCE) // #31 = flag + if (#31 < 1) { // not valid field? + #12++ + #22++ + } else { // valid field + // check run of data-absent fields + if(#13 == #12 && #12 > 0) { + Reg_Set(15, ", ", APPEND) + Reg_Set(15, @14, APPEND) + } + if(#13 < #12 && #12 > 0) { + #13 = #12 + Reg_Set(15, @14) + } + + // re-initialise run of nodata counter + #12 = 0 + // gather values for averaging + #20 += #30 + #21++ + } + } + + // totals for the file so far + #10 += #20 + #11 += #21 + + Buf_Switch(#51) // buffer for output data + IT("Line: ") Reg_Ins(14) + IT(" Reject:") Num_Ins(#22, COUNT, 3) + IT(" Accept:") Num_Ins(#21, COUNT, 3) + IT(" Line tot:") Num_Ins(#20, COUNT, 8) Char(-3) IC('.') EOL + IT(" Line avg:") Num_Ins((#20+#21/2)/#21, COUNT, 7) Char(-3) IC('.') EOL IN + Buf_Switch(#50) // buffer for input data +} + +Buf_Switch(#51) // buffer for output data +IN +IT("Total: ") Num_Ins(#10, FORCE+NOCR) Char(-3) IC('.') EOL IN +IT("Readings: ") Num_Ins(#11, FORCE) +IT("Average: ") Num_Ins((#10+#11/2)/#11, FORCE+NOCR) Char(-3) IC('.') EOL IN +IN +IT("Maximum run(s) of ") Num_Ins(#13, LEFT+NOCR) +IT(" consecutive false readings ends at line starting with date(s): ") Reg_Ins(15) +IN diff --git a/Task/Text-processing-2/0DESCRIPTION b/Task/Text-processing-2/0DESCRIPTION new file mode 100644 index 0000000000..40125f7251 --- /dev/null +++ b/Task/Text-processing-2/0DESCRIPTION @@ -0,0 +1,22 @@ +The following data shows a few lines from the file readings.txt (as used in the [[Data Munging]] task). + +The data comes from a pollution monitoring station with twenty four instruments monitoring twenty four aspects of pollution in the air. Periodically a record is added to the file constituting a line of 49 white-space separated fields, where white-space can be one or more space or tab characters. + +The fields (from the left) are: + DATESTAMP [ VALUEn FLAGn ] * 24 +i.e. a datestamp followed by twenty four repetitions of a floating point instrument value and that instruments associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with that instrument, in which case that instrument's value should be ignored. + +A sample from the full data file [http://rosettacode.org/resources/readings.zip readings.txt] is: +
+1991-03-30	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1
+1991-03-31	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	20.000	1	20.000	1	20.000	1	35.000	1	50.000	1	60.000	1	40.000	1	30.000	1	30.000	1	30.000	1	25.000	1	20.000	1	20.000	1	20.000	1	20.000	1	20.000	1	35.000	1
+1991-03-31	40.000	1	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2	0.000	-2
+1991-04-01	0.000	-2	13.000	1	16.000	1	21.000	1	24.000	1	22.000	1	20.000	1	18.000	1	29.000	1	44.000	1	50.000	1	43.000	1	38.000	1	27.000	1	27.000	1	24.000	1	23.000	1	18.000	1	12.000	1	13.000	1	14.000	1	15.000	1	13.000	1	10.000	1
+1991-04-02	8.000	1	9.000	1	11.000	1	12.000	1	12.000	1	12.000	1	27.000	1	26.000	1	27.000	1	33.000	1	32.000	1	31.000	1	29.000	1	31.000	1	25.000	1	25.000	1	24.000	1	21.000	1	17.000	1	14.000	1	15.000	1	12.000	1	12.000	1	10.000	1
+1991-04-03	10.000	1	9.000	1	10.000	1	10.000	1	9.000	1	10.000	1	15.000	1	24.000	1	28.000	1	24.000	1	18.000	1	14.000	1	12.000	1	13.000	1	14.000	1	15.000	1	14.000	1	15.000	1	13.000	1	13.000	1	13.000	1	12.000	1	10.000	1	10.000	1
+
+ +The task: +# Confirm the general field format of the file +# Identify any DATESTAMPs that are duplicated. +# What number of records have good readings for all instruments. diff --git a/Task/Text-processing-2/1META.yaml b/Task/Text-processing-2/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/Text-processing-2/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/Text-processing-2/AWK/text-processing-2-1.awk b/Task/Text-processing-2/AWK/text-processing-2-1.awk new file mode 100644 index 0000000000..5c56ec1e7c --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-1.awk @@ -0,0 +1,2 @@ +bash$ awk '/[eE]/' readings.txt +bash$ diff --git a/Task/Text-processing-2/AWK/text-processing-2-2.awk b/Task/Text-processing-2/AWK/text-processing-2-2.awk new file mode 100644 index 0000000000..08eccca223 --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-2.awk @@ -0,0 +1,2 @@ +bash$ awk 'NF != 49' readings.txt +bash$ diff --git a/Task/Text-processing-2/AWK/text-processing-2-3.awk b/Task/Text-processing-2/AWK/text-processing-2-3.awk new file mode 100644 index 0000000000..8c6a1d02b5 --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-3.awk @@ -0,0 +1,2 @@ +bash$ awk '!(/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]([ \t]+[-]?[0-9]+\.[0-9]+[\t ]+[-]?[0-9]+)+$/ && NF==49)' readings.txt +bash$ diff --git a/Task/Text-processing-2/AWK/text-processing-2-4.awk b/Task/Text-processing-2/AWK/text-processing-2-4.awk new file mode 100644 index 0000000000..18a9c5d52b --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-4.awk @@ -0,0 +1,2 @@ +bash$ awk --re-interval '!(/^[0-9]{4}-[0-9]{2}-[0-9]{2}([ \t]+[-]?[0-9]+\.[0-9]+[\t ]+[-]?[0-9]+){24}+$/ )' readings.txt +bash$ diff --git a/Task/Text-processing-2/AWK/text-processing-2-5.awk b/Task/Text-processing-2/AWK/text-processing-2-5.awk new file mode 100644 index 0000000000..e7abf52591 --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-5.awk @@ -0,0 +1,7 @@ +bash$ awk '++count[$1]==2{print $1}' readings.txt +1990-03-25 +1991-03-31 +1992-03-29 +1993-03-28 +1995-03-26 +bash$ diff --git a/Task/Text-processing-2/AWK/text-processing-2-6.awk b/Task/Text-processing-2/AWK/text-processing-2-6.awk new file mode 100644 index 0000000000..9265affa69 --- /dev/null +++ b/Task/Text-processing-2/AWK/text-processing-2-6.awk @@ -0,0 +1,3 @@ +bash$ awk '{rec++;ok=1; for(i=0;i<24;i++){if($(2*i+3)<1){ok=0}}; recordok += ok} END {print "Total records",rec,"OK records", recordok, "or", recordok/rec*100,"%"}' readings.txt +Total records 5471 OK records 5017 or 91.7017 % +bash$ diff --git a/Task/Text-processing-2/Ada/text-processing-2.ada b/Task/Text-processing-2/Ada/text-processing-2.ada new file mode 100644 index 0000000000..78bf820e63 --- /dev/null +++ b/Task/Text-processing-2/Ada/text-processing-2.ada @@ -0,0 +1,63 @@ +with Ada.Calendar; use Ada.Calendar; +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit; use Strings_Edit; +with Strings_Edit.Floats; use Strings_Edit.Floats; +with Strings_Edit.Integers; use Strings_Edit.Integers; + +with Generic_Map; + +procedure Data_Munging_2 is + package Time_To_Line is new Generic_Map (Time, Natural); + use Time_To_Line; + File : File_Type; + Line_No : Natural := 0; + Count : Natural := 0; + Stamps : Map; +begin + Open (File, In_File, "readings.txt"); + loop + declare + Line : constant String := Get_Line (File); + Pointer : Integer := Line'First; + Flag : Integer; + Year, Month, Day : Integer; + Data : Float; + Stamp : Time; + Valid : Boolean := True; + begin + Line_No := Line_No + 1; + Get (Line, Pointer, SpaceAndTab); + Get (Line, Pointer, Year); + Get (Line, Pointer, Month); + Get (Line, Pointer, Day); + Stamp := Time_Of (Year_Number (Year), Month_Number (-Month), Day_Number (-Day)); + begin + Add (Stamps, Stamp, Line_No); + exception + when Constraint_Error => + Put (Image (Year) & Image (Month) & Image (Day) & ": record at " & Image (Line_No)); + Put_Line (" duplicates record at " & Image (Get (Stamps, Stamp))); + end; + Get (Line, Pointer, SpaceAndTab); + for Reading in 1..24 loop + Get (Line, Pointer, Data); + Get (Line, Pointer, SpaceAndTab); + Get (Line, Pointer, Flag); + Get (Line, Pointer, SpaceAndTab); + Valid := Valid and then Flag >= 1; + end loop; + if Pointer <= Line'Last then + Put_Line ("Unrecognized tail at " & Image (Line_No) & ':' & Image (Pointer)); + elsif Valid then + Count := Count + 1; + end if; + exception + when End_Error | Data_Error | Constraint_Error | Time_Error => + Put_Line ("Syntax error at " & Image (Line_No) & ':' & Image (Pointer)); + end; + end loop; +exception + when End_Error => + Close (File); + Put_Line ("Valid records " & Image (Count) & " of " & Image (Line_No) & " total"); +end Data_Munging_2; diff --git a/Task/Text-processing-2/AutoHotkey/text-processing-2.ahk b/Task/Text-processing-2/AutoHotkey/text-processing-2.ahk new file mode 100644 index 0000000000..237b46144d --- /dev/null +++ b/Task/Text-processing-2/AutoHotkey/text-processing-2.ahk @@ -0,0 +1,52 @@ +; Author: AlephX Aug 17 2011 +data = %A_scriptdir%\readings.txt + +Loop, Read, %data% + { + Lines := A_Index + StringReplace, dummy, A_LoopReadLine, %A_Tab%,, All UseErrorLevel + + Loop, parse, A_LoopReadLine, %A_Tab% + { + wrong := 0 + if A_index = 1 + { + Date := A_LoopField + if (Date == OldDate) + { + WrongDates = %WrongDates%%OldDate% at %Lines%`n + TotwrongDates++ + Wrong := 1 + break + } + } + else + { + if (A_loopfield/1 < 0) + { + Wrong := 1 + break + } + + } + } + + if (wrong == 1) + totwrong++ + else + valid++ + + if (errorlevel <> 48) + { + if (wrong == 0) + { + totwrong++ + valid-- + } + unvalidformat++ + } + + olddate := date + } + +msgbox, Duplicate Dates:`n%wrongDates%`nRead Lines: %lines%`nValid Lines: %valid%`nwrong lines: %totwrong%`nDuplicates: %TotWrongDates%`nWrong Formatted: %unvalidformat%`n diff --git a/Task/Text-processing-2/C++/text-processing-2.cpp b/Task/Text-processing-2/C++/text-processing-2.cpp new file mode 100644 index 0000000000..c22b41311b --- /dev/null +++ b/Task/Text-processing-2/C++/text-processing-2.cpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std ; + +boost::regex e ( "\\s+" ) ; + +int main( int argc , char *argv[ ] ) { + ifstream infile( argv[ 1 ] ) ; + vector duplicates ; + set datestamps ; //for the datestamps + if ( ! infile.is_open( ) ) { + cerr << "Can't open file " << argv[ 1 ] << '\n' ; + return 1 ; + } + int all_ok = 0 ;//all_ok for lines in the given pattern e + int pattern_ok = 0 ; //overall field pattern of record is ok + while ( infile ) { + string eingabe ; + getline( infile , eingabe ) ; + boost::sregex_token_iterator i ( eingabe.begin( ), eingabe.end( ) , e , -1 ), j ;//we tokenize on empty fields + vector fields( i, j ) ; + if ( fields.size( ) == 49 ) //we expect 49 fields in a record + pattern_ok++ ; + else + cout << "Format not ok!\n" ; + if ( datestamps.insert( fields[ 0 ] ).second ) { //not duplicated + int howoften = ( fields.size( ) - 1 ) / 2 ;//number of measurement + //devices and values + for ( int n = 1 ; atoi( fields[ 2 * n ].c_str( ) ) >= 1 ; n++ ) { + if ( n == howoften ) { + all_ok++ ; + break ; + } + } + } + else { + duplicates.push_back( fields[ 0 ] ) ;//first field holds datestamp + } + } + infile.close( ) ; + cout << "The following " << duplicates.size() << " datestamps were duplicated:\n" ; + copy( duplicates.begin( ) , duplicates.end( ) , + ostream_iterator( cout , "\n" ) ) ; + cout << all_ok << " records were complete and ok!\n" ; + return 0 ; +} diff --git a/Task/Text-processing-2/C/text-processing-2-1.c b/Task/Text-processing-2/C/text-processing-2-1.c new file mode 100644 index 0000000000..d01d5f98e8 --- /dev/null +++ b/Task/Text-processing-2/C/text-processing-2-1.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include +#include +#include + +typedef struct { const char *s; int ln, bad; } rec_t; +int cmp_rec(const void *aa, const void *bb) +{ + const rec_t *a = aa, *b = bb; + return a->s == b->s ? 0 : !a->s ? 1 : !b->s ? -1 : strncmp(a->s, b->s, 10); +} + +int read_file(const char *fn) +{ + int fd = open(fn, O_RDONLY); + if (fd == -1) return 0; + + struct stat s; + fstat(fd, &s); + + char *txt = malloc(s.st_size); + read(fd, txt, s.st_size); + close(fd); + + int i, j, lines = 0, k, di, bad; + for (i = lines = 0; i < s.st_size; i++) + if (txt[i] == '\n') { + txt[i] = '\0'; + lines++; + } + + rec_t *rec = calloc(sizeof(rec_t), lines); + const char *ptr, *end; + rec[0].s = txt; + rec[0].ln = 1; + for (i = 0; i < lines; i++) { + if (i + 1 < lines) { + rec[i + 1].s = rec[i].s + strlen(rec[i].s) + 1; + rec[i + 1].ln = i + 2; + } + if (sscanf(rec[i].s, "%4d-%2d-%2d", &di, &di, &di) != 3) { + printf("bad line %d: %s\n", i, rec[i].s); + rec[i].s = 0; + continue; + } + ptr = rec[i].s + 10; + + for (j = k = 0; j < 25; j++) { + if (!strtod(ptr, (char**)&end) && end == ptr) break; + k++, ptr = end; + if (!(di = strtol(ptr, (char**)&end, 10)) && end == ptr) break; + k++, ptr = end; + if (di < 1) rec[i].bad = 1; + } + + if (k != 48) { + printf("bad format at line %d: %s\n", i, rec[i].s); + rec[i].s = 0; + } + } + + qsort(rec, lines, sizeof(rec_t), cmp_rec); + for (i = 1, bad = rec[0].bad, j = 0; i < lines && rec[i].s; i++) { + if (rec[i].bad) bad++; + if (strncmp(rec[i].s, rec[j].s, 10)) { + j = i; + } else + printf("dup line %d: %.10s\n", rec[i].ln, rec[i].s); + } + + free(rec); + free(txt); + printf("\n%d out %d lines good\n", lines - bad, lines); + return 0; +} + +int main() +{ + read_file("readings.txt"); + return 0; +} diff --git a/Task/Text-processing-2/C/text-processing-2-2.c b/Task/Text-processing-2/C/text-processing-2-2.c new file mode 100644 index 0000000000..76da1176b6 --- /dev/null +++ b/Task/Text-processing-2/C/text-processing-2-2.c @@ -0,0 +1,7 @@ +dup line 85: 1990-03-25 +dup line 456: 1991-03-31 +dup line 820: 1992-03-29 +dup line 1184: 1993-03-28 +dup line 1911: 1995-03-26 + +5017 out 5471 lines good diff --git a/Task/Text-processing-2/D/text-processing-2.d b/Task/Text-processing-2/D/text-processing-2.d new file mode 100644 index 0000000000..736730d709 --- /dev/null +++ b/Task/Text-processing-2/D/text-processing-2.d @@ -0,0 +1,38 @@ +import std.stdio, std.array, std.string, std.regex, std.conv, + std.algorithm; + +void main() { + // works but eats lot of RAM in DMD 2.059 + //const rxDate = ctRegex!(`^\d\d\d\d-\d\d-\d\d$`); + auto rxDate = regex(`^\d\d\d\d-\d\d-\d\d$`); + + int[string] repeatedDates; + int goodReadings; + foreach (string line; lines(File("readings.txt"))) { + try { + auto parts = line.split(); + if (parts.length != 49) + throw new Exception("Wrong column count"); + if (match(parts[0], rxDate).empty) + throw new Exception("Date is wrong"); + repeatedDates[parts[0]]++; + bool noProblem = true; + for (int i = 1; i < 48; i += 2) { + if (to!int(parts[i + 1]) < 1) + // don't break loop because it's validation too. + noProblem = false; + if (!isNumeric(parts[i])) + throw new Exception("Reading is wrong: "~parts[i]); + } + if (noProblem) + goodReadings++; + } catch(Exception ex) { + writefln(`Problem in line "%s": %s`, line, ex); + } + } + + writeln("Duplicated timestamps: ", + repeatedDates.keys.filter!(k => repeatedDates[k] > 1)(). + join(", ")); + writeln("Good reading records: ", goodReadings); +} diff --git a/Task/Text-processing-2/Go/text-processing-2.go b/Task/Text-processing-2/Go/text-processing-2.go new file mode 100644 index 0000000000..6a11daef21 --- /dev/null +++ b/Task/Text-processing-2/Go/text-processing-2.go @@ -0,0 +1,81 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +var fn = "readings.txt" + +func main() { + f, err := os.Open(fn) + if err != nil { + fmt.Println(err) + return + } + defer f.Close() + var allGood, uniqueGood int + // map records not only dates seen, but also if an all-good record was + // seen for the key date. + m := make(map[string]bool) + for lr := bufio.NewReader(f); ; { + line, pref, err := lr.ReadLine() + if err == io.EOF { + break + } + if err != nil { + fmt.Println(err) + return + } + if pref { + fmt.Println("Unexpected long line.") + return + } + f := strings.Fields(string(line)) + if len(f) != 49 { + fmt.Println("unexpected format,", len(f), "fields.") + return + } + good := true + for i := 1; i < 49; i += 2 { + flag, err := strconv.Atoi(f[i+1]) + if err != nil { + fmt.Println(err) + return + } + if flag > 0 { // value is good + _, err := strconv.ParseFloat(f[i], 64) + if err != nil { + fmt.Println(err) + return + } + } else { // value is bad + good = false + } + } + if good { + allGood++ + } + previouslyGood, seen := m[f[0]] + if seen { + fmt.Println("Duplicate datestamp:", f[0]) + if !previouslyGood && good { + m[string([]byte(f[0]))] = true + uniqueGood++ + } + } else { + m[string([]byte(f[0]))] = good + if good { + uniqueGood++ + } + } + } + fmt.Println("\nData format valid.") + fmt.Println(allGood, "records with good readings for all instruments.") + fmt.Println(uniqueGood, + "unique dates with good readings for all instruments.") +} diff --git a/Task/Text-processing-2/Haskell/text-processing-2.hs b/Task/Text-processing-2/Haskell/text-processing-2.hs new file mode 100644 index 0000000000..0a8acd0277 --- /dev/null +++ b/Task/Text-processing-2/Haskell/text-processing-2.hs @@ -0,0 +1,18 @@ +import Data.List (nub, (\\)) + +data Record = Record {date :: String, recs :: [(Double, Int)]} + +duplicatedDates rs = rs \\ nub rs + +goodRecords = filter ((== 24) . length . filter ((>= 1) . snd) . recs) + +parseLine l = let ws = words l in Record (head ws) (mapRecords (tail ws)) + +mapRecords [] = [] +mapRecords [_] = error "invalid data" +mapRecords (value:flag:tail) = (read value, read flag) : mapRecords tail + +main = do + inputs <- (map parseLine . lines) `fmap` readFile "readings.txt" + putStr (unlines ("duplicated dates:": duplicatedDates (map date inputs))) + putStrLn ("number of good records: " ++ show (length $ goodRecords inputs)) diff --git a/Task/Text-processing-2/J/text-processing-2.j b/Task/Text-processing-2/J/text-processing-2.j new file mode 100644 index 0000000000..c27d7ef765 --- /dev/null +++ b/Task/Text-processing-2/J/text-processing-2.j @@ -0,0 +1,20 @@ + require 'tables/dsv dates' + dat=: TAB readdsv jpath '~temp/readings.txt' + Dates=: getdate"1 >{."1 dat + Vals=: _99 ". >(1 + +: i.24){"1 dat + Flags=: _99 ". >(2 + +: i.24){"1 dat + + # Dates NB. Total # lines +5471 + +/ *./"1 ] 0 = Dates NB. # lines with invalid date formats +0 + +/ _99 e."1 Vals,.Flags NB. # lines with invalid value or flag formats +0 + +/ *./"1 [0 < Flags NB. # lines with only valid flags +5017 + ~. (#~ (i.~ ~: i:~)) Dates NB. Duplicate dates +1990 3 25 +1991 3 31 +1992 3 29 +1993 3 28 +1995 3 26 diff --git a/Task/Text-processing-2/Java/text-processing-2.java b/Task/Text-processing-2/Java/text-processing-2.java new file mode 100644 index 0000000000..5c67ab9d64 --- /dev/null +++ b/Task/Text-processing-2/Java/text-processing-2.java @@ -0,0 +1,44 @@ +import java.util.*; +import java.util.regex.*; +import java.io.*; + +public class DataMunging2 { + + public static final Pattern e = Pattern.compile("\\s+"); + + public static void main(String[] args) { + try { + BufferedReader infile = new BufferedReader(new FileReader(args[0])); + List duplicates = new ArrayList(); + Set datestamps = new HashSet(); //for the datestamps + + String eingabe; + int all_ok = 0;//all_ok for lines in the given pattern e + while ((eingabe = infile.readLine()) != null) { + String[] fields = e.split(eingabe); //we tokenize on empty fields + if (fields.length != 49) //we expect 49 fields in a record + System.out.println("Format not ok!"); + if (datestamps.add(fields[0])) { //not duplicated + int howoften = (fields.length - 1) / 2 ; //number of measurement + //devices and values + for (int n = 1; Integer.parseInt(fields[2*n]) >= 1; n++) { + if (n == howoften) { + all_ok++ ; + break ; + } + } + } else { + duplicates.add(fields[0]); //first field holds datestamp + } + } + infile.close(); + System.out.println("The following " + duplicates.size() + " datestamps were duplicated:"); + for (String x : duplicates) + System.out.println(x); + System.out.println(all_ok + " records were complete and ok!"); + } catch (IOException e) { + System.err.println("Can't open file " + args[0]); + System.exit(1); + } + } +} diff --git a/Task/Text-processing-2/JavaScript/text-processing-2.js b/Task/Text-processing-2/JavaScript/text-processing-2.js new file mode 100644 index 0000000000..9011481a7c --- /dev/null +++ b/Task/Text-processing-2/JavaScript/text-processing-2.js @@ -0,0 +1,50 @@ +// wrap up the counter variables in a closure. +function analyze_func(filename) { + var dates_seen = {}; + var format_bad = 0; + var records_all = 0; + var records_good = 0; + return function() { + var fh = new ActiveXObject("Scripting.FileSystemObject").openTextFile(filename, 1); // 1 = for reading + while ( ! fh.atEndOfStream) { + records_all ++; + var allOK = true; + var line = fh.ReadLine(); + var fields = line.split('\t'); + if (fields.length != 49) { + format_bad ++; + continue; + } + + var date = fields.shift(); + if (has_property(dates_seen, date)) + WScript.echo("duplicate date: " + date); + else + dates_seen[date] = 1; + + while (fields.length > 0) { + var value = parseFloat(fields.shift()); + var flag = parseInt(fields.shift(), 10); + if (isNaN(value) || isNaN(flag)) { + format_bad ++; + } + else if (flag <= 0) { + allOK = false; + } + } + if (allOK) + records_good ++; + } + fh.close(); + WScript.echo("total records: " + records_all); + WScript.echo("Wrong format: " + format_bad); + WScript.echo("records with no bad readings: " + records_good); + } +} + +function has_property(obj, propname) { + return typeof(obj[propname]) == "undefined" ? false : true; +} + +var analyze = analyze_func('readings.txt'); +analyze(); diff --git a/Task/Text-processing-2/Lua/text-processing-2.lua b/Task/Text-processing-2/Lua/text-processing-2.lua new file mode 100644 index 0000000000..e7680645e4 --- /dev/null +++ b/Task/Text-processing-2/Lua/text-processing-2.lua @@ -0,0 +1,44 @@ +filename = "readings.txt" +io.input( filename ) + +dates = {} +duplicated, bad_format = {}, {} +num_good_records, lines_total = 0, 0 + +while true do + line = io.read( "*line" ) + if line == nil then break end + + lines_total = lines_total + 1 + + date = string.match( line, "%d+%-%d+%-%d+" ) + if dates[date] ~= nil then + duplicated[#duplicated+1] = date + end + dates[date] = 1 + + count_pairs, bad_values = 0, false + for v, w in string.gmatch( line, "%s(%d+[%.%d+]*)%s(%-?%d)" ) do + count_pairs = count_pairs + 1 + if tonumber(w) <= 0 then + bad_values = true + end + end + if count_pairs ~= 24 then + bad_format[#bad_format+1] = date + end + if not bad_values then + num_good_records = num_good_records + 1 + end +end + +print( "Lines read:", lines_total ) +print( "Valid records: ", num_good_records ) +print( "Duplicate dates:" ) +for i = 1, #duplicated do + print( " ", duplicated[i] ) +end +print( "Bad format:" ) +for i = 1, #bad_format do + print( " ", bad_format[i] ) +end diff --git a/Task/Text-processing-2/MATLAB/text-processing-2.m b/Task/Text-processing-2/MATLAB/text-processing-2.m new file mode 100644 index 0000000000..2c2974d102 --- /dev/null +++ b/Task/Text-processing-2/MATLAB/text-processing-2.m @@ -0,0 +1,29 @@ +function [val,count] = readdat(configfile) +% READDAT reads readings.txt file +% +% The value of boolean parameters can be tested with +% exist(parameter,'var') + +if nargin<1, + filename = 'readings.txt'; +end; + +fid = fopen(filename); +if fid<0, error('cannot open file %s\n',a); end; +[val,count] = fscanf(fid,'%04d-%02d-%02d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d %f %d \n'); +fclose(fid); + +count = count/51; + +if (count<1) || count~=floor(count), + error('file has incorrect format\n') +end; + +val = reshape(val,51,count)'; % make matrix with 51 rows and count columns, then transpose it. + +d = datenum(val(:,1:3)); % compute timestamps + +printf('The following records are followed by a duplicate:'); +dix = find(diff(d)==0) % check for to consequtive timestamps with zero difference + +printf('number of valid records: %i\n ', sum( all( val(:,5:2:end) >= 1, 2) ) ); diff --git a/Task/Text-processing-2/Mathematica/text-processing-2.math b/Task/Text-processing-2/Mathematica/text-processing-2.math new file mode 100644 index 0000000000..b7707ce6db --- /dev/null +++ b/Task/Text-processing-2/Mathematica/text-processing-2.math @@ -0,0 +1,4 @@ +data = Import["Readings.txt","TSV"]; Print["duplicated dates: "]; +Select[Tally@data[[;;,1]], #[[2]]>1&][[;;,1]]//Column +Print["number of good records: ", Count[(Times@@#[[3;;All;;2]])& /@ data, 1], +" (out of a total of ", Length[data], ")"] diff --git a/Task/Text-processing-2/OCaml/text-processing-2.ocaml b/Task/Text-processing-2/OCaml/text-processing-2.ocaml new file mode 100644 index 0000000000..38fba2b270 --- /dev/null +++ b/Task/Text-processing-2/OCaml/text-processing-2.ocaml @@ -0,0 +1,68 @@ +#load "str.cma" +open Str + +let strip_cr str = + let last = pred(String.length str) in + if str.[last] <> '\r' then (str) else (String.sub str 0 last) + +let map_records = + let rec aux acc = function + | value::flag::tail -> + let e = (float_of_string value, int_of_string flag) in + aux (e::acc) tail + | [_] -> invalid_arg "invalid data" + | [] -> (List.rev acc) + in + aux [] ;; + +let duplicated_dates = + let same_date (d1,_) (d2,_) = (d1 = d2) in + let date (d,_) = d in + let rec aux acc = function + | a::b::tl when same_date a b -> + aux (date a::acc) tl + | _::tl -> + aux acc tl + | [] -> + (List.rev acc) + in + aux [] ;; + +let record_ok (_,record) = + let is_ok (_,v) = (v >= 1) in + let sum_ok = + List.fold_left (fun sum this -> + if is_ok this then succ sum else sum) 0 record + in + (sum_ok = 24) + +let num_good_records = + List.fold_left (fun sum record -> + if record_ok record then succ sum else sum) 0 ;; + +let parse_line line = + let li = split (regexp "[ \t]+") line in + let records = map_records (List.tl li) + and date = (List.hd li) in + (date, records) + +let () = + let ic = open_in "readings.txt" in + let rec read_loop acc = + try + let line = strip_cr(input_line ic) in + read_loop ((parse_line line) :: acc) + with End_of_file -> + close_in ic; + (List.rev acc) + in + let inputs = read_loop [] in + + Printf.printf "%d total lines\n" (List.length inputs); + + Printf.printf "duplicated dates:\n"; + let dups = duplicated_dates inputs in + List.iter print_endline dups; + + Printf.printf "number of good records: %d\n" (num_good_records inputs); +;; diff --git a/Task/Text-processing-2/PHP/text-processing-2.php b/Task/Text-processing-2/PHP/text-processing-2.php new file mode 100644 index 0000000000..639035841e --- /dev/null +++ b/Task/Text-processing-2/PHP/text-processing-2.php @@ -0,0 +1,35 @@ +$handle = fopen("readings.txt", "rb"); +$missformcount = 0; +$totalcount = 0; +$dates = array(); +while (!feof($handle)) { + $buffer = fgets($handle); + $line = preg_replace('/\s+/',' ',$buffer); + $line = explode(' ',trim($line)); + $datepattern = '/^\d{4}-\d{2}-\d{2}$/'; + $valpattern = '/^\d+\.{1}\d{3}$/'; + $flagpattern = '/^[1-9]{1}$/'; + + if(count($line) != 49) $missformcount++; + if(!preg_match($datepattern,$line[0],$check)) $missformcount++; + else $dates[$totalcount+1] = $check[0]; + + $errcount = 0; + for($i=1;$i'; +echo 'Duplicates :
'; +foreach ($duplicates as $key => $val){ + echo $val . ' at Line : ' . $key . '
'; +} diff --git a/Task/Text-processing-2/PL-I/text-processing-2.pli b/Task/Text-processing-2/PL-I/text-processing-2.pli new file mode 100644 index 0000000000..8cdb5e6215 --- /dev/null +++ b/Task/Text-processing-2/PL-I/text-processing-2.pli @@ -0,0 +1,52 @@ +/* To process readings produced by automatic reading stations. */ + +check: procedure options (main); + declare 1 date, 2 (yy, mm, dd) character (2), + (j1, j2) character (1); + declare old_date character (6); + declare line character (330) varying; + declare R(24) fixed decimal, Machine(24) fixed binary; + declare (i, k, n, faulty static initial (0)) fixed binary; + declare input file; + + open file (input) title ('/READINGS.TXT,TYPE(CRLF),RECSIZE(300)'); + + on endfile (input) go to done; + + old_date = ''; + k = 0; + do forever; + k = k + 1; + + get file (input) edit (line) (L); + get string(line) edit (yy, j1, mm, j2, dd) (a(4), a(1), a(2), a(1), a(2)); + + line = substr(line, 11); + + do i = 1 to length(line); + if substr(line, i, 1) = '09'x then substr(line, i, 1) = ' '; + end; + line = trim(line); + n = tally(line, ' ') - tally (line, ' ') + 1; + + if n ^= 48 then + do; + put skip list ('There are ' || n || ' readings in line ' || k); + end; + + n = n/2; + line = line || ' '; + + get string(line) list ((R(i), Machine(i) do i = 1 to n)); + + if any(Machine < 1) ^= '0'B then + faulty = faulty + 1; + if old_date ^= ' ' then if old_date = string(date) then + put skip list ('Dates are the same at line' || k); + old_date = string(date); + end; +done: + put skip list ('There were ' || k || ' sets of readings'); + put skip list ('There were ' || faulty || ' faulty readings' ); + put skip list ('There were ' || k-faulty || ' good readings' ); +end check; diff --git a/Task/Text-processing-2/Perl-6/text-processing-2-1.pl6 b/Task/Text-processing-2/Perl-6/text-processing-2-1.pl6 new file mode 100644 index 0000000000..11b257d0b4 --- /dev/null +++ b/Task/Text-processing-2/Perl-6/text-processing-2-1.pl6 @@ -0,0 +1,22 @@ +my $fields = 49; + +my ($good-records, %dates) = 0; +for 1 .. * Z $*IN.lines -> $line, $s { + my @fs = split /\s+/, $s; + @fs == $fields or die "$line: Bad number of fields"; + given shift @fs { + m/\d**4 \- \d**2 \- \d**2/ or die "$line: Bad date format"; + ++%dates{$_}; + } + my $all-flags-okay = True; + for @fs -> $val, $flag { + $val ~~ /\d+ \. \d+/ or die "$line: Bad value format"; + $flag ~~ /^ \-? \d+/ or die "$line: Bad flag format"; + $flag < 1 and $all-flags-okay = False; + } + $all-flags-okay and ++$good-records; +} + +say 'Good records: ', $good-records; +say 'Repeated timestamps:'; +say ' ', $_ for grep { %dates{$_} > 1 }, sort keys %dates; diff --git a/Task/Text-processing-2/Perl-6/text-processing-2-2.pl6 b/Task/Text-processing-2/Perl-6/text-processing-2-2.pl6 new file mode 100644 index 0000000000..3f2051159b --- /dev/null +++ b/Task/Text-processing-2/Perl-6/text-processing-2-2.pl6 @@ -0,0 +1,19 @@ +my $good-records; +my $line; +my %dates; + +for lines() { + $line++; + / ^ + (\d ** 4 '-' \d\d '-' \d\d) + [ \h+ \d+'.'\d+ \h+ ('-'?\d+) ] ** 24 + $ / + or note "Bad format at line $line" and next; + %dates.push: $0 => $line; + $good-records++ if $1.all >= 1; +} + +say "$good-records good records out of $line total"; + +say 'Repeated timestamps (with line numbers):'; +.say for sort %dates.pairs.grep: *.value.elems > 1; diff --git a/Task/Text-processing-2/Perl/text-processing-2.pl b/Task/Text-processing-2/Perl/text-processing-2.pl new file mode 100644 index 0000000000..9a8c988700 --- /dev/null +++ b/Task/Text-processing-2/Perl/text-processing-2.pl @@ -0,0 +1,28 @@ +use List::MoreUtils 'natatime'; +use constant FIELDS => 49; + +binmode STDIN, ':crlf'; + # Read the newlines properly even if we're not running on + # Windows. + +my ($line, $good_records, %dates) = (0, 0); +while (<>) + {++$line; + my @fs = split /\s+/; + @fs == FIELDS or die "$line: Bad number of fields.\n"; + for (shift @fs) + {/\d{4}-\d{2}-\d{2}/ or die "$line: Bad date format.\n"; + ++$dates{$_};} + my $iterator = natatime 2, @fs; + my $all_flags_okay = 1; + while ( my ($val, $flag) = $iterator->() ) + {$val =~ /\d+\.\d+/ or die "$line: Bad value format.\n"; + $flag =~ /\A-?\d+/ or die "$line: Bad flag format.\n"; + $flag < 1 and $all_flags_okay = 0;} + $all_flags_okay and ++$good_records;} + +print "Good records: $good_records\n", + "Repeated timestamps:\n", + map {" $_\n"} + grep {$dates{$_} > 1} + sort keys %dates; diff --git a/Task/Text-processing-2/PicoLisp/text-processing-2.l b/Task/Text-processing-2/PicoLisp/text-processing-2.l new file mode 100644 index 0000000000..f95425a396 --- /dev/null +++ b/Task/Text-processing-2/PicoLisp/text-processing-2.l @@ -0,0 +1,24 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(load "@lib/misc.l") + +(in (opt) + (until (eof) + (let Lst (split (line) "^I") + (unless + (and + (= 49 (length Lst)) # Check total length + ($dat (car Lst) "-") # Check for valid date + (not + (find # Check data format + '((L F) + (not + (if F # Alternating: + (format L 3) # Number + (>= 9 (format L) -9) ) ) ) # or flag + (cdr Lst) + '(T NIL .) ) ) ) + (prinl "Bad line format: " (glue " " Lst)) + (bye 1) ) ) ) ) + +(bye) diff --git a/Task/Text-processing-2/PowerShell/text-processing-2-1.psh b/Task/Text-processing-2/PowerShell/text-processing-2-1.psh new file mode 100644 index 0000000000..a31b1e78a9 --- /dev/null +++ b/Task/Text-processing-2/PowerShell/text-processing-2-1.psh @@ -0,0 +1,23 @@ +$dateHash = @{} +$goodLineCount = 0 +get-content c:\temp\readings.txt | + ForEach-Object { + $line = $_.split(" |`t",2) + if ($dateHash.containskey($line[0])) { + $line[0] + " is duplicated" + } else { + $dateHash.add($line[0], $line[1]) + } + $readings = $line[1].split() + $goodLine = $true + if ($readings.count -ne 48) { $goodLine = $false; "incorrect line length : $line[0]" } + for ($i=0; $i -lt $readings.count; $i++) { + if ($i % 2 -ne 0) { + if ([int]$readings[$i] -lt 1) { + $goodLine = $false + } + } + } + if ($goodLine) { $goodLineCount++ } + } +[string]$goodLineCount + " good lines" diff --git a/Task/Text-processing-2/PowerShell/text-processing-2-2.psh b/Task/Text-processing-2/PowerShell/text-processing-2-2.psh new file mode 100644 index 0000000000..b463b17d4f --- /dev/null +++ b/Task/Text-processing-2/PowerShell/text-processing-2-2.psh @@ -0,0 +1,20 @@ +$dateHash = @{} +$goodLineCount = 0 +ForEach ($rawLine in ( get-content c:\temp\readings.txt) ){ + $line = $rawLine.split(" |`t",2) + if ($dateHash.containskey($line[0])) { + $line[0] + " is duplicated" + } else { + $dateHash.add($line[0], $line[1]) + } + $readings = [regex]::matches($line[1],"\d+\.\d+\s-?\d") + if ($readings.count -ne 24) { "incorrect number of readings for date " + $line[0] } + $goodLine = $true + foreach ($flagMatch in [regex]::matches($line[1],"\d\.\d*\s(?-?\d)")) { + if ([int][string]$flagMatch.groups["flag"].value -lt 1) { + $goodLine = $false + } + } + if ($goodLine) { $goodLineCount++} +} +[string]$goodLineCount + " good lines" diff --git a/Task/Text-processing-2/PureBasic/text-processing-2.purebasic b/Task/Text-processing-2/PureBasic/text-processing-2.purebasic new file mode 100644 index 0000000000..198236f94c --- /dev/null +++ b/Task/Text-processing-2/PureBasic/text-processing-2.purebasic @@ -0,0 +1,72 @@ +Define filename.s = "readings.txt" +#instrumentCount = 24 + +Enumeration + #exp_date + #exp_instruments + #exp_instrumentStatus +EndEnumeration + +Structure duplicate + date.s + firstLine.i + line.i +EndStructure + +NewMap dates() ;records line date occurs first +NewList duplicated.duplicate() +NewList syntaxError() +Define goodRecordCount, totalLines, line.s, i +Dim inputDate.s(0) +Dim instruments.s(0) + +If ReadFile(0, filename) + CreateRegularExpression(#exp_date, "\d+-\d+-\d+") + CreateRegularExpression(#exp_instruments, "(\t|\x20)+(\d+\.\d+)(\t|\x20)+\-?\d") + CreateRegularExpression(#exp_instrumentStatus, "(\t|\x20)+(\d+\.\d+)(\t|\x20)+") + Repeat + line = ReadString(0, #PB_Ascii) + If line = "": Break: EndIf + totalLines + 1 + + ExtractRegularExpression(#exp_date, line, inputDate()) + If FindMapElement(dates(), inputDate(0)) + AddElement(duplicated()) + duplicated()\date = inputDate(0) + duplicated()\firstLine = dates() + duplicated()\line = totalLines + Else + dates(inputDate(0)) = totalLines + EndIf + + ExtractRegularExpression(#exp_instruments, Mid(line, Len(inputDate(0)) + 1), instruments()) + Define pairsCount = ArraySize(instruments()), containsBadValues = #False + For i = 0 To pairsCount + If Val(ReplaceRegularExpression(#exp_instrumentStatus, instruments(i), "")) < 1 + containsBadValues = #True + Break + EndIf + Next + + If pairsCount <> #instrumentCount - 1 + AddElement(syntaxError()): syntaxError() = totalLines + EndIf + If Not containsBadValues + goodRecordCount + 1 + EndIf + ForEver + CloseFile(0) + + If OpenConsole() + ForEach duplicated() + PrintN("Duplicate date: " + duplicated()\date + " occurs on lines " + Str(duplicated()\line) + " and " + Str(duplicated()\firstLine) + ".") + Next + ForEach syntaxError() + PrintN( "Syntax error in line " + Str(syntaxError())) + Next + PrintN(#CRLF$ + Str(goodRecordCount) + " of " + Str(totalLines) + " lines read were valid records.") + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() + EndIf +EndIf diff --git a/Task/Text-processing-2/Python/text-processing-2-1.py b/Task/Text-processing-2/Python/text-processing-2-1.py new file mode 100644 index 0000000000..e80182b0d6 --- /dev/null +++ b/Task/Text-processing-2/Python/text-processing-2-1.py @@ -0,0 +1,41 @@ +import re +import zipfile +import StringIO + +def munge2(readings): + + datePat = re.compile(r'\d{4}-\d{2}-\d{2}') + valuPat = re.compile(r'[-+]?\d+\.\d+') + statPat = re.compile(r'-?\d+') + allOk, totalLines = 0, 0 + datestamps = set([]) + for line in readings: + totalLines += 1 + fields = line.split('\t') + date = fields[0] + pairs = [(fields[i],fields[i+1]) for i in range(1,len(fields),2)] + + lineFormatOk = datePat.match(date) and \ + all( valuPat.match(p[0]) for p in pairs ) and \ + all( statPat.match(p[1]) for p in pairs ) + if not lineFormatOk: + print 'Bad formatting', line + continue + + if len(pairs)!=24 or any( int(p[1]) < 1 for p in pairs ): + print 'Missing values', line + continue + + if date in datestamps: + print 'Duplicate datestamp', line + continue + datestamps.add(date) + allOk += 1 + + print 'Lines with all readings: ', allOk + print 'Total records: ', totalLines + +#zfs = zipfile.ZipFile('readings.zip','r') +#readings = StringIO.StringIO(zfs.read('readings.txt')) +readings = open('readings.txt','r') +munge2(readings) diff --git a/Task/Text-processing-2/Python/text-processing-2-2.py b/Task/Text-processing-2/Python/text-processing-2-2.py new file mode 100644 index 0000000000..cf6046480b --- /dev/null +++ b/Task/Text-processing-2/Python/text-processing-2-2.py @@ -0,0 +1,45 @@ +import re +import zipfile +import StringIO + +def munge2(readings, debug=False): + + datePat = re.compile(r'\d{4}-\d{2}-\d{2}') + valuPat = re.compile(r'[-+]?\d+\.\d+') + statPat = re.compile(r'-?\d+') + totalLines = 0 + dupdate, badform, badlen, badreading = set(), set(), set(), 0 + datestamps = set([]) + for line in readings: + totalLines += 1 + fields = line.split('\t') + date = fields[0] + pairs = [(fields[i],fields[i+1]) for i in range(1,len(fields),2)] + + lineFormatOk = datePat.match(date) and \ + all( valuPat.match(p[0]) for p in pairs ) and \ + all( statPat.match(p[1]) for p in pairs ) + if not lineFormatOk: + if debug: print 'Bad formatting', line + badform.add(date) + + if len(pairs)!=24 or any( int(p[1]) < 1 for p in pairs ): + if debug: print 'Missing values', line + if len(pairs)!=24: badlen.add(date) + if any( int(p[1]) < 1 for p in pairs ): badreading += 1 + + if date in datestamps: + if debug: print 'Duplicate datestamp', line + dupdate.add(date) + + datestamps.add(date) + + print 'Duplicate dates:\n ', '\n '.join(sorted(dupdate)) + print 'Bad format:\n ', '\n '.join(sorted(badform)) + print 'Bad number of fields:\n ', '\n '.join(sorted(badlen)) + print 'Records with good readings: %i = %5.2f%%\n' % ( + totalLines-badreading, (totalLines-badreading)/float(totalLines)*100 ) + print 'Total records: ', totalLines + +readings = open('readings.txt','r') +munge2(readings) diff --git a/Task/Text-processing-2/R/text-processing-2.r b/Task/Text-processing-2/R/text-processing-2.r new file mode 100644 index 0000000000..0057095b5a --- /dev/null +++ b/Task/Text-processing-2/R/text-processing-2.r @@ -0,0 +1,13 @@ +# Read in data from file +dfr <- read.delim("d:/readings.txt", colClasses=c("character", rep(c("numeric", "integer"), 24))) +dates <- strptime(dfr[,1], "%Y-%m-%d") + +# Any bad values? +dfr[which(is.na(dfr))] + +# Any duplicated dates +dates[duplicated(dates)] + +# Number of rows with no bad values +flags <- as.matrix(dfr[,seq(3,49,2)])>0 +sum(apply(flags, 1, all)) diff --git a/Task/Text-processing-2/REXX/text-processing-2.rexx b/Task/Text-processing-2/REXX/text-processing-2.rexx new file mode 100644 index 0000000000..b3bb62b853 --- /dev/null +++ b/Task/Text-processing-2/REXX/text-processing-2.rexx @@ -0,0 +1,148 @@ +/*REXX program to process instrument data from a data file. */ +numeric digits 20 /*allow for bigger numbers. */ +ifid='READINGS.TXT' /*the input file. */ +ofid='READINGS.OUT' /*the outut file. */ +grandSum=0 /*grand sum of whole file. */ +grandflg=0 /*grand num of flagged data. */ +grandOKs=0 +longFlag=0 /*longest period of flagged data.*/ +contFlag=0 /*longest continous flagged data.*/ +oldDate =0 /*placeholder of penutilmate date*/ +w =16 /*width of fields when displayed.*/ +dupDates=0 /*count of duplicated timestamps.*/ +badflags=0 /*count of bad flags (¬ integer).*/ +badDates=0 /*count of bad dates (bad format)*/ +badData =0 /*count of bad datas (¬ numeric).*/ +ignoredR=0 /*count of ignored records (bad).*/ +maxInstruments=24 /*maximum number of instruments. */ +yyyyCurr=right(date(),4) /*get the current year (today). */ +monDD. =31 /*number of days in every month. */ + /*February is figured on the fly.*/ +monDD.4 =30 +monDD.6 =30 +monDD.9 =30 +monDD.11=30 + + do records=1 while lines(ifid)\==0 /*read until finished. */ + rec=linein(ifid) /*read the next record (line). */ + parse var rec datestamp Idata /*pick off the dateStamp & data. */ + if datestamp==oldDate then do /*found a duplicate timestamp. */ + dupDates=dupDates+1 /*bump the counter.*/ + call sy datestamp copies('~',30), + 'is a duplicate of the', + "previous datestamp." + ignoredR=ignoredR+1 /*bump ignoredRecs.*/ + iterate /*ignore this duplicate record. */ + end + + parse var datestamp yyyy '-' mm '-' dd /*obtain YYYY, MM, and DD. */ + monDD.2=28+leapyear(yyyy) /*how long is February in YYYY ? */ + /*check for various bad formats. */ + if verify(yyyy||mm||dd,1234567890)\==0 |, + length(datestamp)\==10 |, + length(yyyy)\==4 |, + length(mm )\==2 |, + length(dd )\==2 |, + yyyy<1970 |, + yyyy>yyyyCurr |, + mm=0 | dd=0 |, + mm>12 | dd>monDD.mm then do + badDates=badDates+1 + call sy datestamp copies('~'), + 'has an illegal format.' + ignoredR=ignoredR+1 /*bump ignoredRecs.*/ + iterate /*ignore this bad date record. */ + end + oldDate=datestamp /*save datestamp for next read. */ + sum=0 + flg=0 + OKs=0 + + do j=1 until Idata='' /*process the instrument data. */ + parse var Idata data.j flag.j Idata + + if pos('.',flag.j)\==0 |, /*flag have a decimal point -or-*/ + \datatype(flag.j,'W') then do /*is the flag not a whole number?*/ + badflags=badflags+1 /*bump counter.*/ + call sy datestamp copies('~'), + 'instrument' j "has a bad flag:", + flag.j + iterate /*ignore it & it's data.*/ + end + + if \datatype(data.j,'N') then do /*is the flag not a whole number?*/ + badData=badData+1 /*bump counter.*/ + call sy datestamp copies('~'), + 'instrument' j "has bad data:", + data.j + iterate /*ignore it & it's flag.*/ + end + + if flag.j>0 then do /*if good data, ... */ + OKs=OKs+1 + sum=sum+data.j + if contFlag>longFlag then do + longdate=datestamp + longFlag=contFlag + end + contFlag=0 + end + else do /*flagged data ... */ + flg=flg+1 + contFlag=contFlag+1 + end + end /*j*/ + + if j>maxInstruments then do + badData=badData+1 /*bump counter.*/ + call sy datestamp copies('~'), + 'too many instrument datum' + end + + if OKs\==0 then avg=format(sum/OKs,,3) + else avg='[n/a]' + grandOKs=grandOKs+OKs + _=right(comma(avg),w) + grandSum=grandSum+sum + grandFlg=grandFlg+flg + if flg==0 then call sy datestamp ' average='_ + else call sy datestamp ' average='_ ' flagged='right(flg,2) + end /*records*/ + +records=records-1 /*adjust for reading end-of-file.*/ +if grandOKs\==0 then grandAvg=format(grandsum/grandOKs,,3) + else grandAvg='[n/a]' +call sy +call sy copies('=',60) +call sy ' records read:' right(comma(records ),w) +call sy ' records ignored:' right(comma(ignoredR),w) +call sy ' grand sum:' right(comma(grandSum),w+4) +call sy ' grand average:' right(comma(grandAvg),w+4) +call sy ' grand OK data:' right(comma(grandOKs),w) +call sy ' grand flagged:' right(comma(grandFlg),w) +call sy ' duplicate dates:' right(comma(dupDates),w) +call sy ' bad dates:' right(comma(badDates),w) +call sy ' bad data:' right(comma(badData ),w) +call sy ' bad flags:' right(comma(badflags),w) +if longFlag\==0 then +call sy ' longest flagged:' right(comma(longFlag),w) " ending at " longdate +call sy copies('=',60) +call sy +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────LEAPYEAR subroutine─────────────────*/ +leapyear: procedure; arg y /*year could be: Y, YY, YYY, YYYY*/ +if length(y)==2 then y=left(right(date(),4),2)y /*adjust for YY year.*/ +if y//4\==0 then return 0 /* not ≈ by 4? Not a leapyear.*/ +return y//100\==0 | y//400==0 /*apply 100 and 400 year rule. */ +/*──────────────────────────────────SY subroutine───────────────────────*/ +sy: procedure; parse arg stuff; say stuff + if 1==0 then call lineout ofid,stuff + return +/*──────────────────────────────────COMMA subroutine────────────────────*/ +comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1) + if cu=='BLANK' then c=' ';o=word(p 3,1);p=abs(o);t=word(t 999999999,1) + if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _;n=_'.9' + #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _ + e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end + do j=e to b by -p while k next-match-rule) (datestamp-seen! ds pos) (next-match-rule)) + + ((list-rest + _ + (app fold-into-pairs + (list (list (app string->number (and (? number?) vs)) + (app string->number (and (? integer?) statuss))) + ...))) + (=> next-match-rule) + (unless (= (length vs) 24) (next-match-rule)) + (not (for/first ((s statuss) #:unless (positive? s)) #t))) + + ;; if we don't hit an error, then the file is valid + (else (error 'match-valid-field "bad field format: ~a~%" line)))) + + (define (sub-t-p/1) + (for/sum ((line (in-lines)) + (line-number (in-naturals 1))) + (if (match-valid-field line line-number) 1 0))) + (for/sum ((file-name files-to-read)) + (with-input-from-file file-name sub-t-p/1))) + +(printf "~a records have good readings for all instruments~%" + (text-processing/2 (current-command-line-arguments))) diff --git a/Task/Text-processing-2/Ruby/text-processing-2.rb b/Task/Text-processing-2/Ruby/text-processing-2.rb new file mode 100644 index 0000000000..9229247710 --- /dev/null +++ b/Task/Text-processing-2/Ruby/text-processing-2.rb @@ -0,0 +1,53 @@ +require 'set' + +def munge2(readings, debug=false) + datePat = /^\d{4}-\d{2}-\d{2}/ + valuPat = /^[-+]?\d+\.\d+/ + statPat = /^-?\d+/ + totalLines = 0 + dupdate, badform, badlen, badreading = Set[], Set[], Set[], 0 + datestamps = Set[[]] + for line in readings + totalLines += 1 + fields = line.split(/\t/) + date = fields.shift + pairs = fields.enum_slice(2).to_a + + lineFormatOk = date =~ datePat && + pairs.all? { |x,y| x =~ valuPat && y =~ statPat } + if !lineFormatOk + puts 'Bad formatting ' + line if debug + badform << date + end + + if pairs.length != 24 || + pairs.any? { |x,y| y.to_i < 1 } + puts 'Missing values ' + line if debug + end + if pairs.length != 24 + badlen << date + end + if pairs.any? { |x,y| y.to_i < 1 } + badreading += 1 + end + + if datestamps.include?(date) + puts 'Duplicate datestamp ' + line if debug + dupdate << date + end + + datestamps << date + end + + puts 'Duplicate dates:', dupdate.sort.map { |x| ' ' + x } + puts 'Bad format:', badform.sort.map { |x| ' ' + x } + puts 'Bad number of fields:', badlen.sort.map { |x| ' ' + x } + puts 'Records with good readings: %i = %5.2f%%' % [ + totalLines-badreading, (totalLines-badreading)/totalLines.to_f*100 ] + puts + puts 'Total records: %d' % totalLines +end + +open('readings.txt','r') do |readings| + munge2(readings) +end diff --git a/Task/Text-processing-2/Scala/text-processing-2.scala b/Task/Text-processing-2/Scala/text-processing-2.scala new file mode 100644 index 0000000000..0f690eca2b --- /dev/null +++ b/Task/Text-processing-2/Scala/text-processing-2.scala @@ -0,0 +1,39 @@ +object DataMunging2 { + import scala.io.Source + import scala.collection.immutable.{TreeMap => Map} + + val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r; + + def main(args: Array[String]) { + val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead) + val (numFormatErrors, numValidRecords, dateMap) = + files.iterator.flatMap(file => Source fromFile file getLines ()). + foldLeft((0, 0, new Map[String, Int] withDefaultValue 0)) { + case ((nFE, nVR, dM), line) => pattern findFirstMatchIn line map (_.subgroups) match { + case Some(List(date, rawData @ _*)) => + val allValid = (rawData map (_ toDouble) iterator) grouped 2 forall (_.last > 0) + (nFE, nVR + (if (allValid) 1 else 0), dM(date) += 1) + case None => (nFE + 1, nVR, dM) + } + } + + dateMap foreach { + case (date, repetitions) if repetitions > 1 => println(date+": "+repetitions+" repetitions") + case _ => + } + + println("""| + |Valid records: %d + |Duplicated dates: %d + |Duplicated records: %d + |Data format errors: %d + |Invalid data records: %d + |Total records: %d""".stripMargin format ( + numValidRecords, + dateMap filter { case (_, repetitions) => repetitions > 1 } size, + dateMap.valuesIterable filter (_ > 1) map (_ - 1) sum, + numFormatErrors, + dateMap.valuesIterable.sum - numValidRecords, + dateMap.valuesIterable.sum)) + } +} diff --git a/Task/Text-processing-2/Tcl/text-processing-2-1.tcl b/Task/Text-processing-2/Tcl/text-processing-2-1.tcl new file mode 100644 index 0000000000..9c26fee7e2 --- /dev/null +++ b/Task/Text-processing-2/Tcl/text-processing-2-1.tcl @@ -0,0 +1,25 @@ +set data [lrange [split [read [open "readings.txt" "r"]] "\n"] 0 end-1] +set total [llength $data] +set correct $total +set datestamps {} + +foreach line $data { + set formatOk true + set hasAllMeasurements true + + set date [lindex $line 0] + if {[llength $line] != 49} { set formatOk false } + if {![regexp {\d{4}-\d{2}-\d{2}} $date]} { set formatOk false } + if {[lsearch $datestamps $date] != -1} { puts "Duplicate datestamp: $date" } {lappend datestamps $date} + + foreach {value flag} [lrange $line 1 end] { + if {$flag < 1} { set hasAllMeasurements false } + + if {![regexp -- {[-+]?\d+\.\d+} $value] || ![regexp -- {-?\d+} $flag]} {set formatOk false} + } + if {!$hasAllMeasurements} { incr correct -1 } + if {!$formatOk} { puts "line \"$line\" has wrong format" } +} + +puts "$correct records with good readings = [expr $correct * 100.0 / $total]%" +puts "Total records: $total" diff --git a/Task/Text-processing-2/Tcl/text-processing-2-2.tcl b/Task/Text-processing-2/Tcl/text-processing-2-2.tcl new file mode 100644 index 0000000000..3174f54a20 --- /dev/null +++ b/Task/Text-processing-2/Tcl/text-processing-2-2.tcl @@ -0,0 +1,39 @@ +set total [set good 0] +array set seen {} +set fh [open readings.txt] +while {[gets $fh line] != -1} { + incr total + set fields [regexp -inline -all {[^ \t\r\n]+} $line] + if {[llength $fields] != 49} { + puts "bad format: not 49 fields on line $total" + continue + } + if { ! [regexp {^(\d{4}-\d\d-\d\d)$} [lindex $fields 0] -> date]} { + puts "bad format: invalid date on line $total: '$date'" + continue + } + + if {[info exists seen($date)]} { + puts "duplicate date on line $total: $date" + } + incr seen($date) + + set line_format_ok true + set readings_ignored 0 + foreach {value flag} [lrange $fields 1 end] { + if { ! [string is double -strict $value]} { + puts "bad format: value not a float on line $total: '$value'" + set line_format_ok false + } + if { ! [string is int -strict $flag]} { + puts "bad format: flag not an integer on line $total: '$flag'" + set line_format_ok false + } + if {$flag < 1} {incr readings_ignored} + } + if {$line_format_ok && $readings_ignored == 0} {incr good} +} +close $fh + +puts "total: $total" +puts [format "good: %d = %5.2f%%" $good [expr {100.0 * $good / $total}]] diff --git a/Task/Text-processing-2/Ursala/text-processing-2.ursala b/Task/Text-processing-2/Ursala/text-processing-2.ursala new file mode 100644 index 0000000000..84c4735101 --- /dev/null +++ b/Task/Text-processing-2/Ursala/text-processing-2.ursala @@ -0,0 +1,14 @@ +#import std +#import nat + +readings = (*F ~&c/;digits+ rlc ==+ ~~ -={` ,9%cOi&,13%cOi&}) readings_dot_txt + +valid_format = all -&length==49,@tK27 all ~&w/`.&& ~&jZ\digits--'-.',@tK28 all ~&jZ\digits--'-'&- + +duplicate_dates = :/'duplicated dates:'+ ~&hK2tFhhPS|| -[(none)]-! + +good_readings = --' good readings'@h+ %nP+ length+ *~ @tK28 all ~='0'&& ~&wZ/`- + +#show+ + +main = valid_format?(^C/good_readings duplicate_dates,-[invalid format]-!) readings diff --git a/Task/Text-processing-2/Vedit-macro-language/text-processing-2-1.vedit b/Task/Text-processing-2/Vedit-macro-language/text-processing-2-1.vedit new file mode 100644 index 0000000000..7daa7b5cf9 --- /dev/null +++ b/Task/Text-processing-2/Vedit-macro-language/text-processing-2-1.vedit @@ -0,0 +1,48 @@ +#50 = Buf_Num // Current edit buffer (source data) +File_Open("|(PATH_ONLY)\output.txt") +#51 = Buf_Num // Edit buffer for output file +Buf_Switch(#50) + +#11 = #12 = #13 = #14 = #15 = 0 +Reg_Set(15, "xxx") + +While(!At_EOF) { + #10 = 0 + #12++ + + // Check for repeated date field + if (Match(@15) == 0) { + #20 = Cur_Line + Buf_Switch(#51) // Output file + Reg_ins(15) IT(": duplicate record at ") Num_Ins(#20) + Buf_Switch(#50) // Input file + #13++ + } + + // Check format of date field + if (Match("|d|d|d|d-|d|d-|d|d|w", ADVANCE) != 0) { + #10 = 1 + #14++ + } + Reg_Copy_Block(15, BOL_pos, Cur_Pos-1) + + // Check data fields and flags: + Repeat(24) { + if ( Match("|d|*.|d|d|d|w", ADVANCE) != 0 || Num_Eval(ADVANCE) < 1) { + #10 = 1 + #15++ + Break + } + Match("|W", ADVANCE) + } + if (#10 == 0) { #11++ } // record was OK + Line(1, ERRBREAK) +} + +Buf_Switch(#51) // buffer for output data +IN +IT("Valid records: ") Num_Ins(#11) +IT("Duplicates: ") Num_Ins(#13) +IT("Date format errors: ") Num_Ins(#14) +IT("Invalid data records:") Num_Ins(#15) +IT("Total records: ") Num_Ins(#12) diff --git a/Task/Text-processing-2/Vedit-macro-language/text-processing-2-2.vedit b/Task/Text-processing-2/Vedit-macro-language/text-processing-2-2.vedit new file mode 100644 index 0000000000..c3f3bb8b7d --- /dev/null +++ b/Task/Text-processing-2/Vedit-macro-language/text-processing-2-2.vedit @@ -0,0 +1,11 @@ +1990-03-25: duplicate record at 85 +1991-03-31: duplicate record at 456 +1992-03-29: duplicate record at 820 +1993-03-28: duplicate record at 1184 +1995-03-26: duplicate record at 1911 + +Valid records: 5017 +Duplicates: 5 +Date format errors: 0 +Invalid data records: 454 +Total records: 5471 diff --git a/Task/Text-processing-Max-licenses-in-use/0DESCRIPTION b/Task/Text-processing-Max-licenses-in-use/0DESCRIPTION new file mode 100644 index 0000000000..204c76b532 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/0DESCRIPTION @@ -0,0 +1,9 @@ +A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. + +Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file. An example of checkout and checkin events are: + License OUT @ 2008/10/03_23:51:05 for job 4974 + ... + License IN @ 2008/10/04_00:18:22 for job 4974 + + +Save the 10,000 line log file from [http://rosettacode.org/resources/mlijobs.txt here] into a local file then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs. diff --git a/Task/Text-processing-Max-licenses-in-use/1META.yaml b/Task/Text-processing-Max-licenses-in-use/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/Text-processing-Max-licenses-in-use/ALGOL-68/text-processing-max-licenses-in-use.alg b/Task/Text-processing-Max-licenses-in-use/ALGOL-68/text-processing-max-licenses-in-use.alg new file mode 100644 index 0000000000..bc83737f41 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/ALGOL-68/text-processing-max-licenses-in-use.alg @@ -0,0 +1,72 @@ +PROC report = (REF FILE file in)INT: ( + + MODE TIME = [19]CHAR; + STRUCT ([3]CHAR inout, TIME time, INT jobnum) record; + FORMAT record fmt = $"License "g" @ "g" for job "g(0)l$; + + FLEX[1]TIME max time; + + INT lic out := 0, max out := LWB max time-1, max count := LWB max time-1; + BOOL file in ended := FALSE; + on logical file end(file in, (REF FILE file in)BOOL: file in ended := TRUE); + WHILE + getf(file in, (record fmt, record)); +# WHILE # NOT file in ended DO + IF inout OF record = "OUT" THEN + lic out +:= 1 + ELIF lic out > 0 THEN # incase license already "OUT" # + lic out -:= 1 + FI; + + IF lic out > max out THEN + max out := lic out; + max count := LWB max time-1 + FI; + IF lic out = max out THEN + IF max count = UPB max time THEN + [UPB max time*2]TIME new max time; + new max time[:UPB max time] := max time; + max time := new max time + # ;putf(stand error, ($"increasing UPB max time (now it is "g(0)")"l$, UPB max time)); # + FI; + max time[max count +:= 1] := time OF record + FI + OD; + + printf(($"Maximum simultaneous license use is "g(0)" at the following times:"l$, max out)); + FOR lic out FROM LWB max time TO max count DO + printf(($gl$, max time[lic out])) + OD; + + 0 EXIT + exit report error: errno +); + +INT errno; + +COMMENT + Usage: + a68g Text_processing_3.a68 --exit Text_processing_3.dat + a68g Text_processing_3.a68 < Text_processing_3.dat +END COMMENT + +main: +( + INT argv1 := 4; + IF argc >= argv1 THEN + FOR i FROM argv1 TO argc DO + FILE file in; + errno := open(file in, argv(i), stand in channel); + IF errno /= 0 THEN + putf(stand error, ($"cannot read "gl$, argv(1))); + exit main error + ELSE + report(file in) + FI; + close(file in) + OD + ELSE + report(stand in) + FI; + exit main error: SKIP +) diff --git a/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-1.apl b/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-1.apl new file mode 100644 index 0000000000..d63c3e7ac4 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-1.apl @@ -0,0 +1,6 @@ +⍝ Copy/paste file's contents into TXT (easiest), or TXT ← ⎕NREAD + I ← TXT[;8+⎕IO] + D ← TXT[;⎕IO+14+⍳19] + lu ← +\ ¯1 * 'OI' ⍳ I + mx ← (⎕IO+⍳⍴lu)/⍨lu= max ← ⌈/ lu + ⎕ ← 'Maximum simultaneous license use is ' , ' at the following times:' ,⍨ ⍕max ⋄ ⎕←D[mx;] diff --git a/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-2.apl b/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-2.apl new file mode 100644 index 0000000000..236dfcdc75 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/APL/text-processing-max-licenses-in-use-2.apl @@ -0,0 +1,3 @@ +Maximum simultaneous license use is 99 at the following times: + 2008/10/03_08:39:34 + 2008/10/03_08:40:40 diff --git a/Task/Text-processing-Max-licenses-in-use/AWK/text-processing-max-licenses-in-use.awk b/Task/Text-processing-Max-licenses-in-use/AWK/text-processing-max-licenses-in-use.awk new file mode 100644 index 0000000000..ba8d362b63 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/AWK/text-processing-max-licenses-in-use.awk @@ -0,0 +1,14 @@ +$2=="OUT" { + count = count + 1 + time = $4 + if ( count > maxcount ) { + maxcount = count + maxtimes = time + } else { + if ( count == maxcount ) { + maxtimes = maxtimes " and " time + } + } +} +$2=="IN" { count = count - 1 } +END {print "The biggest number of licenses is " maxcount " at " maxtimes " !"} diff --git a/Task/Text-processing-Max-licenses-in-use/Ada/text-processing-max-licenses-in-use.ada b/Task/Text-processing-Max-licenses-in-use/Ada/text-processing-max-licenses-in-use.ada new file mode 100644 index 0000000000..d5b233ae06 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Ada/text-processing-max-licenses-in-use.ada @@ -0,0 +1,70 @@ +-- licenselist.adb -- +-- run under GPS 4.3-5 (Sidux/Debian) +-- process rosetta.org text_processing/3 example +-- uses linked-list to hold times +with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded, + Ada.Strings.Unbounded.Text_IO, + Ada.Containers.Doubly_Linked_Lists; +use Ada.Text_IO, Ada.Integer_Text_IO, + Ada.Strings.Unbounded, Ada.Strings.Unbounded.Text_IO, + Ada.Containers; + +procedure licenselist is + + type logrec is record -- define a record 'logrec' to place in a list + logtext : String(1..19); + end record; + + package dblist is new Doubly_Linked_Lists(logrec); + use dblist; + -- declare dblist as a list of logrec's + licenselog : list; + logtime : logrec; + -- to record the time of max OUT licenses + + infile : File_Type; -- file handle + str : Unbounded_String; -- input string buffer of unknown length + outcnt, maxoutcnt : integer := 0; + infilename : string := "license.log"; + + procedure trace_times is + -- loop thru times list and print + pntr : cursor := licenselog.first; + -- pntr is of system type cursor reference to local list 'licenselog' + begin + new_line; + while has_element(pntr) loop + put(element(pntr).logtext); new_line; + next(pntr); + end loop; + end trace_times; + +begin -- main program -- + open ( infile, + mode=> in_file, + name=> infilename ); + + loop + exit when End_of_file ( infile ); + str := get_line( infile ); + if index( str, "OUT" ) > 0 then -- test if OUT record + outcnt := outcnt +1; + else -- else assume IN record + outcnt := outcnt -1; + end if; + if outcnt > maxoutcnt then + maxoutcnt := outcnt; + logtime.logtext := slice(str,15,33); -- date_time field + licenselog.clear; -- reset list for new time(s) + licenselog.append (logtime); -- put current time into list + elsif outcnt = maxoutcnt then + logtime.logtext := slice(str,15,33); -- date_time field + licenselog.append (logtime); -- add current time into list + end if; -- have to account for possibility of equal number of OUT's + end loop; + put("The max. number of licenses OUT is ");put(maxoutcnt,5); new_line; + put(" at these times "); + + trace_times; + close ( infile ); +end licenselist; diff --git a/Task/Text-processing-Max-licenses-in-use/AutoHotkey/text-processing-max-licenses-in-use.ahk b/Task/Text-processing-Max-licenses-in-use/AutoHotkey/text-processing-max-licenses-in-use.ahk new file mode 100644 index 0000000000..40e1c78864 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/AutoHotkey/text-processing-max-licenses-in-use.ahk @@ -0,0 +1,21 @@ +IfNotExist, mlijobs.txt + UrlDownloadToFile, http://rosettacode.org/mlijobs.txt, mlijobs.txt + +out := 0, max_out := -1, max_times := "" + +Loop, Read, mlijobs.txt +{ + If InStr(A_LoopReadLine, "OUT") + out++ + Else + out-- + If (out > max_out) + max_out := out, max_times := "" + If (out = max_out) + { + StringSplit, lineArr, A_LoopReadLine, %A_Space% + max_times .= lineArr4 . "`n" + } +} + +MsgBox Maximum use is %max_out% at:`n`n%max_times% diff --git a/Task/Text-processing-Max-licenses-in-use/BBC-BASIC/text-processing-max-licenses-in-use.bbc b/Task/Text-processing-Max-licenses-in-use/BBC-BASIC/text-processing-max-licenses-in-use.bbc new file mode 100644 index 0000000000..e3cc057329 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/BBC-BASIC/text-processing-max-licenses-in-use.bbc @@ -0,0 +1,27 @@ + max% = 0 + nlicence% = 0 + file% = OPENIN("mlijobs.txt") + + WHILE NOT EOF#file% + a$ = GET$#file% + stamp$ = MID$(a$, 15, 19) + IF INSTR(a$, "OUT") THEN + nlicence% += 1 + IF nlicence% > max% THEN + max% = nlicence% + start$ = stamp$ + ENDIF + ENDIF + IF INSTR(a$, "IN") THEN + IF nlicence% = max% THEN + finish$ = previous$ + ENDIF + nlicence% -= 1 + ENDIF + previous$ = stamp$ + ENDWHILE + CLOSE #file% + + PRINT "Maximum licences checked out = " ; max% + PRINT "From " start$ " to " finish$ + END diff --git a/Task/Text-processing-Max-licenses-in-use/Bracmat/text-processing-max-licenses-in-use.bracmat b/Task/Text-processing-Max-licenses-in-use/Bracmat/text-processing-max-licenses-in-use.bracmat new file mode 100644 index 0000000000..9b6a4570f5 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Bracmat/text-processing-max-licenses-in-use.bracmat @@ -0,0 +1,19 @@ +( 0:?N:?n + & :?Ts + & @( get$("mlijobs.txt",STR) + : ? + ( "e " ?OI " @ " ?T " " ? + & ( !OI:OUT + & !n+1 + : ( >!N:?N&!T:?Ts + | !N&!Ts !T:?Ts + | ? + ) + | !n+-1 + ) + : ?n + & ~ + ) + ) +| out$(!N !Ts) +); diff --git a/Task/Text-processing-Max-licenses-in-use/C++/text-processing-max-licenses-in-use.cpp b/Task/Text-processing-Max-licenses-in-use/C++/text-processing-max-licenses-in-use.cpp new file mode 100644 index 0000000000..82b69d4c37 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/C++/text-processing-max-licenses-in-use.cpp @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include + +int main() +{ + const char logfilename[] = "mlijobs.txt"; + std::ifstream logfile(logfilename); + + if (!logfile.is_open()) + { + std::cerr << "Error opening: " << logfilename << "\n"; + return -1; + } + + int license = 0, max_license = 0; + std::vector max_timestamp; + + for (std::string logline; std::getline(logfile, logline); ) + { + std::string action(logline.substr(8,3)); + + if (action == "OUT") + { + if (++license >= max_license) + { + if (license > max_license) + { + max_license = license; + max_timestamp.clear(); + } + max_timestamp.push_back(logline.substr(14, 19)); + } + } + else if (action == "IN ") + { + --license; + } + } + + std::cout << "License count at log end: " << license + << "\nMaximum simultaneous license: " << max_license + << "\nMaximum license time(s):\n"; + + std::copy(max_timestamp.begin(), max_timestamp.end(), + std::ostream_iterator(std::cout, "\n")); +} diff --git a/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-1.c b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-1.c new file mode 100644 index 0000000000..1a6fb5d7ea --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-1.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +#define INOUT_LEN 4 +#define TIME_LEN 20 +#define MAX_MAXOUT 1000 + +char inout[INOUT_LEN]; +char time[TIME_LEN]; +uint jobnum; + +char maxtime[MAX_MAXOUT][TIME_LEN]; + +int main(int argc, char **argv) +{ + FILE *in = NULL; + int l_out = 0, maxout=-1, maxcount=0; + + if ( argc > 1 ) { + in = fopen(argv[1], "r"); + if ( in == NULL ) { + fprintf(stderr, "cannot read %s\n", argv[1]); + exit(1); + } + } else { + in = stdin; + } + + while( fscanf(in, "License %s @ %s for job %u\n", inout, time, &jobnum) != EOF ) { + + if ( strcmp(inout, "OUT") == 0 ) + l_out++; + else + l_out--; + + if ( l_out > maxout ) { + maxout = l_out; + maxcount=0; maxtime[0][0] = '\0'; + } + if ( l_out == maxout ) { + if ( maxcount < MAX_MAXOUT ) { + strncpy(maxtime[maxcount], time, TIME_LEN); + maxcount++; + } else { + fprintf(stderr, "increase MAX_MAXOUT (now it is %u)\n", MAX_MAXOUT); + exit(1); + } + } + } + + printf("Maximum simultaneous license use is %d at the following times:\n", maxout); + for(l_out=0; l_out < maxcount; l_out++) { + printf("%s\n", maxtime[l_out]); + } + + if ( in != stdin ) fclose(in); + exit(0); +} diff --git a/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-2.c b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-2.c new file mode 100644 index 0000000000..843a96d4b6 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-2.c @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + struct stat s; + int fd = open("mlijobs.txt", O_RDONLY); + int cnt, max_cnt, occur; + char *buf, *ptr; + + if (fd == -1) err(1, "open"); + fstat(fd, &s); + ptr = buf = mmap(0, s.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); + + cnt = max_cnt = 0; + while(ptr - buf < s.st_size - 33) { + if (!strncmp(ptr, "License OUT", 11) && ++cnt >= max_cnt) { + if (cnt > max_cnt) { + max_cnt = cnt; + occur = 0; + } + /* can't sprintf time stamp: might overlap */ + memmove(buf + 26 * occur, ptr + 14, 19); + sprintf(buf + 26 * occur + 19, "%6d\n", cnt); + occur++; + } else if (!strncmp(ptr, "License IN ", 11)) cnt --; + + while (ptr < buf + s.st_size && *ptr++ != '\n'); + } + + printf(buf); + munmap(buf, s.st_size); + return close(fd); +} diff --git a/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-3.c b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-3.c new file mode 100644 index 0000000000..5803d17923 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/C/text-processing-max-licenses-in-use-3.c @@ -0,0 +1,2 @@ +2008/10/03_08:39:34 99 +2008/10/03_08:40:40 99 diff --git a/Task/Text-processing-Max-licenses-in-use/Common-Lisp/text-processing-max-licenses-in-use.lisp b/Task/Text-processing-Max-licenses-in-use/Common-Lisp/text-processing-max-licenses-in-use.lisp new file mode 100644 index 0000000000..c4df7afa9d --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Common-Lisp/text-processing-max-licenses-in-use.lisp @@ -0,0 +1,18 @@ +(defun max-licenses (&optional (logfile "mlijobs.txt")) + (with-open-file (log logfile :direction :input) + (do ((current-logs 0) (max-logs 0) (max-log-times '()) + (line #1=(read-line log nil nil) #1#)) + ((null line) + (format t "~&Maximum simultaneous license use is ~w at the ~ + following time~p: ~{~% ~a~}." + max-logs (length max-log-times) (nreverse max-log-times))) + (cl-ppcre:register-groups-bind (op time) + ("License (\\b.*\\b)[ ]{1,2}@ (\\b.*\\b)" line) + (cond ((string= "OUT" op) (incf current-logs)) + ((string= "IN" op) (decf current-logs)) + (t (cerror "Ignore it." "Malformed entry ~s." line))) + (cond ((> current-logs max-logs) + (setf max-logs current-logs + max-log-times (list time))) + ((= current-logs max-logs) + (push time max-log-times))))))) diff --git a/Task/Text-processing-Max-licenses-in-use/D/text-processing-max-licenses-in-use.d b/Task/Text-processing-Max-licenses-in-use/D/text-processing-max-licenses-in-use.d new file mode 100644 index 0000000000..3fe2861078 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/D/text-processing-max-licenses-in-use.d @@ -0,0 +1,18 @@ +void main() { + import std.stdio; + int nOut, maxOut = -1; + string[] maxTimes; + + foreach (string job; lines(File("mlijobs.txt"))) { + nOut += (job[8] == 'O') ? 1 : -1; + if (nOut > maxOut) { + maxOut = nOut; + maxTimes = null; + } + if (nOut == maxOut) + maxTimes ~= job[14 .. 33]; + } + + writefln("Maximum simultaneous license use is %d at" ~ + " the following times:\n%( %s\n%)", maxOut, maxTimes); +} diff --git a/Task/Text-processing-Max-licenses-in-use/E/text-processing-max-licenses-in-use.e b/Task/Text-processing-Max-licenses-in-use/E/text-processing-max-licenses-in-use.e new file mode 100644 index 0000000000..6ad9ddf195 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/E/text-processing-max-licenses-in-use.e @@ -0,0 +1,23 @@ +var out := 0 +var maxOut := 0 +var maxTimes := [] + +def events := ["OUT " => 1, "IN " => -1] + +for line in { + def `License @{via (events.fetch) delta}@@ @time for job @num$\n` := line + + out += delta + if (out > maxOut) { + maxOut := out + maxTimes := [] + } + if (out == maxOut) { + maxTimes with= time + } +} + +println(`Maximum simultaneous license use is $maxOut at the following times:`) +for time in maxTimes { + println(` $time`) +} diff --git a/Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.euphoria b/Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.euphoria new file mode 100644 index 0000000000..b0528e2b1c --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.euphoria @@ -0,0 +1,55 @@ +function split(sequence s, integer c) + sequence out + integer first, delim + out = {} + first = 1 + while first <= length(s) do + delim = find_from(c, s, first) + if delim = 0 then + delim = length(s) + 1 + end if + out = append(out, s[first..delim-1]) + first = delim + 1 + end while + return out +end function + +include get.e +function val(sequence s) + sequence v + v = value(s) + return v[2] - v[1] * v[1] +end function + +constant fn = open("mlijobs.txt", "r") +integer maxout +sequence jobs, line, maxtime +object x +jobs = {} +maxout = 0 +while 1 do + x = gets(fn) + if atom(x) then + exit + end if + line = split(x, ' ') + line[$] = val(line[$]) + if equal(line[2], "OUT") then + jobs &= line[$] + if length(jobs) > maxout then + maxout = length(jobs) + maxtime = {line[4]} + elsif length(jobs) = maxout then + maxtime = append(maxtime, line[4]) + end if + else + jobs[find(line[$],jobs)] = jobs[$] + jobs = jobs[1..$-1] + end if +end while +close(fn) + +printf(1, "Maximum simultaneous license use is %d at the following times:\n", maxout) +for i = 1 to length(maxtime) do + printf(1, "%s\n", {maxtime[i]}) +end for diff --git a/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-1.factor b/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-1.factor new file mode 100644 index 0000000000..a130e0eb5f --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-1.factor @@ -0,0 +1,51 @@ +USING: kernel sequences splitting math accessors io.encodings.ascii +io.files math.parser io ; +IN: maxlicenses + +TUPLE: maxlicense max-count current-count times ; + + ( -- max ) -1 0 V{ } clone \ maxlicense boa ; inline + +: out? ( line -- ? ) [ "OUT" ] dip subseq? ; inline + +: line-time ( line -- time ) " " split harvest fourth ; inline + +: update-max-count ( max -- max' ) + dup [ current-count>> ] [ max-count>> ] bi > + [ dup current-count>> >>max-count V{ } clone >>times ] when ; + +: (inc-current-count) ( max ? -- max' ) + [ [ 1 + ] change-current-count ] + [ [ 1 - ] change-current-count ] + if + update-max-count ; inline + +: inc-current-count ( max ? time -- max' time ) + [ (inc-current-count) ] dip ; + +: current-max-equal? ( max -- max ? ) + dup [ current-count>> ] [ max-count>> ] bi = ; + +: update-time ( max time -- max' ) + [ current-max-equal? ] dip + swap + [ [ suffix ] curry change-times ] [ drop ] if ; + +: split-line ( line -- ? time ) [ out? ] [ line-time ] bi ; + +: process ( max line -- max ) split-line inc-current-count update-time ; + +PRIVATE> + +: find-max-licenses ( -- max ) + "resource:work/mlijobs.txt" ascii file-lines + [ process ] reduce ; + +: print-max-licenses ( max -- ) + [ times>> ] [ max-count>> ] bi + "Maximum simultaneous license use is " write + number>string write + " at the following times: " print + [ print ] each ; diff --git a/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-2.factor b/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-2.factor new file mode 100644 index 0000000000..11c64a1875 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Factor/text-processing-max-licenses-in-use-2.factor @@ -0,0 +1,5 @@ +( scratchpad ) [ find-max-licenses print-max-licenses ] time +Maximum simultaneous license use is 99 at the following times: +2008/10/03_08:39:34 +2008/10/03_08:40:40 +Running time: 0.16164423 seconds diff --git a/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-1.fth b/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-1.fth new file mode 100644 index 0000000000..c017df00a2 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-1.fth @@ -0,0 +1,33 @@ +20 constant date-size +create max-dates date-size 100 * allot +variable max-out +variable counter + +stdin value input + +: process ( addr len -- ) + 8 /string + over 3 s" OUT" compare 0= if + 1 counter +! + counter @ max-out @ > if + counter @ max-out ! + drop 5 + date-size max-dates place + else counter @ max-out @ = if + drop 5 + date-size max-dates +place + else 2drop then then + else drop 2 s" IN" compare 0= if + -1 counter +! + then then ; + +: main + 0 max-out ! + 0 counter ! + s" mlijobs.txt" r/o open-file throw to input + begin pad 80 input read-line throw + while pad swap process + repeat drop + input close-file throw + max-out @ . ." max licenses in use @" + max-dates count type cr ; + +main bye diff --git a/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-2.fth b/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-2.fth new file mode 100644 index 0000000000..89db73213c --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Forth/text-processing-max-licenses-in-use-2.fth @@ -0,0 +1,37 @@ + PROGRAM MAX_LICENSES + IMPLICIT NONE + + INTEGER :: out=0, maxout=0, maxcount=0, err + CHARACTER(50) :: line + CHARACTER(19) :: maxtime(100) + + OPEN (UNIT=5, FILE="Licenses.txt", STATUS="OLD", IOSTAT=err) + IF (err > 0) THEN + WRITE(*,*) "Error opening file Licenses.txt" + STOP + END IF + + DO + READ(5, "(A)", IOSTAT=err) line + IF (err == -1) EXIT ! EOF detected + IF (line(9:9) == "O") THEN + out = out + 1 + ELSE IF (line(9:9) == "I") THEN + out = out - 1 + END IF + IF (out > maxout ) THEN + maxout = maxout + 1 + maxcount = 1 + maxtime(maxcount) = line(15:33) + ELSE IF (out == maxout) THEN + maxcount = maxcount + 1 + maxtime(maxcount) = line(15:33) + END IF + END DO + + CLOSE(5) + + WRITE(*,"(A,I4,A)") "Maximum simultaneous license use is", maxout, " at the following times:" + WRITE(*,"(A)") maxtime(1:maxcount) + + END PROGRAM MAX_LICENSES diff --git a/Task/Text-processing-Max-licenses-in-use/Gema/text-processing-max-licenses-in-use.gema b/Task/Text-processing-Max-licenses-in-use/Gema/text-processing-max-licenses-in-use.gema new file mode 100644 index 0000000000..e6d9b5d6cc --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Gema/text-processing-max-licenses-in-use.gema @@ -0,0 +1,9 @@ +@set{count;0};@set{max;0} + +License OUT \@ * *\n=@incr{count}@testmax{${count},*} +License IN \@ * *\n=@decr{count} +\Z=@report{${max},${times${max}}} + +testmax:*,*=@cmpn{${max};$1;@set{max;$1};;}@append{times${count};$2\n} + +report:*,*=Maximum simultaneous license use is * at\n* diff --git a/Task/Text-processing-Max-licenses-in-use/Go/text-processing-max-licenses-in-use.go b/Task/Text-processing-Max-licenses-in-use/Go/text-processing-max-licenses-in-use.go new file mode 100644 index 0000000000..b6a1ad45fe --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Go/text-processing-max-licenses-in-use.go @@ -0,0 +1,60 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "bytes" +) + +var fn = "mlijobs.txt" + +func main() { + f, err := os.Open(fn) + if err != nil { + fmt.Println(err) + return + } + defer f.Close() + var ml, out int + var mlTimes []string + in := []byte("IN") + for lr := bufio.NewReader(f); ; { + line, pref, err := lr.ReadLine() + if err == io.EOF { + break + } + if err != nil { + fmt.Println(err) + return + } + if pref { + fmt.Println("Unexpected long line.") + return + } + f := bytes.Fields(line) + if len(f) != 7 { + fmt.Println("unexpected format,", len(f), "fields.") + return + } + if bytes.Equal(f[1], in) { + out-- + continue + } + out++ + if out == ml { + mlTimes = append(mlTimes, string(f[3])) + continue + } + if out > ml { + ml = out + mlTimes = append(mlTimes[:0], string(f[3])) + } + } + fmt.Println("max licenses:", ml) + fmt.Println("at:") + for _, t := range mlTimes { + fmt.Println(" ", t) + } +} diff --git a/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-1.groovy b/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-1.groovy new file mode 100644 index 0000000000..81e3009df1 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-1.groovy @@ -0,0 +1,29 @@ +def max = 0 +def dates = [] +def licenses = [:] +new File('licenseFile.txt').eachLine { line -> + (line =~ /License (\w+)\s+@ ([\d\/_:]+) for job (\d+)/).each { matcher, action, date, job -> + switch (action) { + case 'IN': + assert licenses[job] != null : "License has not been checked out for $job" + licenses.remove job + break + case 'OUT': + assert licenses[job] == null : "License has already been checked out for $job" + licenses[job] = date + def count = licenses.keySet().size() + if (count > max) { + max = count + dates = [ date ] + } else if (count == max) { + dates << date + } + break + default: + throw new IllegalArgumentException("Unsupported license action $action") + } + } +} + +println "Maximum Licenses $max" +dates.each { date -> println " $date" } diff --git a/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-2.groovy b/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-2.groovy new file mode 100644 index 0000000000..c2f81e6fbe --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Groovy/text-processing-max-licenses-in-use-2.groovy @@ -0,0 +1,9 @@ +import Data.List + +main = do + f <- readFile "./../Puzzels/Rosetta/inout.txt" + let (ioo,dt) = unzip. map ((\(_:io:_:t:_)-> (io,t)). words) . lines $ f + cio = drop 1 . scanl (\c io -> if io == "IN" then pred c else succ c) 0 $ ioo + mo = maximum cio + putStrLn $ "Maximum simultaneous license use is " ++ show mo ++ " at:" + mapM_ (putStrLn . (dt!!)) . elemIndices mo $ cio diff --git a/Task/Text-processing-Max-licenses-in-use/HicEst/text-processing-max-licenses-in-use.hicest b/Task/Text-processing-Max-licenses-in-use/HicEst/text-processing-max-licenses-in-use.hicest new file mode 100644 index 0000000000..5ec5ab9fc8 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/HicEst/text-processing-max-licenses-in-use.hicest @@ -0,0 +1,18 @@ +CHARACTER Licenses="Licenses.txt" +REAL :: counts(1), Top10(10) + +OPEN(FIle=Licenses, fmt='8x,A3,3x,A19,Nb ,', LENgth=lines) + +ALLOCATE(counts, lines) +counts(1) = 1 +DO line = 2, lines + counts(line) = counts(line-1) + 1 - 2*(Licenses(line,1)=='IN') +ENDDO + +SORT(Vector=counts, Descending=1, Index=Top10) + +DO i = 1, LEN(Top10) + WRITE() counts(Top10(i)), Licenses(Top10(i), 2) +ENDDO + +END diff --git a/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-1.icon b/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-1.icon new file mode 100644 index 0000000000..9ae30947b2 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-1.icon @@ -0,0 +1,14 @@ +procedure main(A) + maxCount := count := 0 + + every !&input ? case tab(upto('@')) of { + "License OUT ": { + maxTime := (maxCount <:= (count +:= 1), []) + put(maxTime, (maxCount = count, ="@ ", tab(find(" for ")))) + } + "License IN ": count -:= (count > 0, 1) # Error check + } + + write("There were ",maxCount," licenses out at:") + every write("\t",!maxTime) +end diff --git a/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-2.icon b/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-2.icon new file mode 100644 index 0000000000..225e9dee02 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Icon/text-processing-max-licenses-in-use-2.icon @@ -0,0 +1,7 @@ + require 'files' + 'I D' =: (8 ; 14+i.19) {"1 &.> <'m' fread 'licenses.txt' NB. read file as matrix, select columns + lu =: +/\ _1 ^ 'OI' i. I NB. Number of licenses in use at any given time + mx =: (I.@:= >./) lu NB. Indicies of maxima + + NB. Output results + (mx { D) ,~ 'Maximum simultaneous license use is ' , ' at the following times:' ,~ ": {. ,mx { lu diff --git a/Task/Text-processing-Max-licenses-in-use/Java/text-processing-max-licenses-in-use.java b/Task/Text-processing-Max-licenses-in-use/Java/text-processing-max-licenses-in-use.java new file mode 100644 index 0000000000..8cd32a543a --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Java/text-processing-max-licenses-in-use.java @@ -0,0 +1,30 @@ +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.LinkedList; + +public class License { + public static void main(String[] args) throws FileNotFoundException, IOException{ + BufferedReader in = new BufferedReader(new FileReader(args[0])); + int max = Integer.MIN_VALUE; + LinkedList dates = new LinkedList(); + String line; + int count = 0; + while((line = in.readLine()) != null){ + if(line.startsWith("License OUT ")) count++; + if(line.startsWith("License IN ")) count--; + if(count > max){ + max = count; + String date = line.split(" ")[3]; + dates.clear(); + dates.add(date); + }else if(count == max){ + String date = line.split(" ")[3]; + dates.add(date); + } + } + System.out.println("Max licenses out: "+max); + System.out.println("At time(s): "+dates); + } +} diff --git a/Task/Text-processing-Max-licenses-in-use/JavaScript/text-processing-max-licenses-in-use.js b/Task/Text-processing-Max-licenses-in-use/JavaScript/text-processing-max-licenses-in-use.js new file mode 100644 index 0000000000..d5cece47e0 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/JavaScript/text-processing-max-licenses-in-use.js @@ -0,0 +1,22 @@ +var file_system = new ActiveXObject("Scripting.FileSystemObject"); +var fh = file_system.openTextFile('mlijobs.txt', 1); // 1 == open for reading +var in_use = 0, max_in_use = -1, max_in_use_at = []; + +while ( ! fh.atEndOfStream) { + var line = fh.readline(); + if (line.substr(8,3) == "OUT") { + in_use++; + if (in_use > max_in_use) { + max_in_use = in_use; + max_in_use_at = [ line.split(' ')[3] ]; + } + else if (in_use == max_in_use) + max_in_use_at.push( line.split(' ')[3] ); + } + else if (line.substr(8,2) == "IN") + in_use--; +} + +fh.close(); + +WScript.echo("Max licenses out: " + max_in_use + "\n " + max_in_use_at.join('\n ')); diff --git a/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-1.k b/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-1.k new file mode 100644 index 0000000000..e4d02ae42a --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-1.k @@ -0,0 +1,3 @@ + r:m@&a=x:|/a:+\{:[x[8+!3]~"OUT";1;-1]}'m:0:"mlijobs.txt"; + `0:,/"Maximum simultaneous license use is ",$x; + `0:" at the following times:\n";`0:r[;14+!19] diff --git a/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-2.k b/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-2.k new file mode 100644 index 0000000000..4beacc853b --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/K/text-processing-max-licenses-in-use-2.k @@ -0,0 +1,3 @@ +Maximum simultaneous license use is 99 at the following times: +2008/10/03_08:39:34 +2008/10/03_08:40:40 diff --git a/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua b/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua new file mode 100644 index 0000000000..0c56849d95 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua @@ -0,0 +1,29 @@ +filename = "mlijobs.txt" +io.input( filename ) + +max_out, n_out = 0, 0 +occurr_dates = {} + +while true do + line = io.read( "*line" ) + if line == nil then break end + + if string.find( line, "OUT" ) ~= nil then + n_out = n_out + 1 + if n_out > max_out then + max_out = n_out + occurr_dates = {} + occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" ) + elseif n_out == max_out then + occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" ) + end + else + n_out = n_out - 1 + end +end + +print( "Maximum licenses in use:", max_out ) +print( "Occurrences:" ) +for i = 1, #occurr_dates do + print( "", occurr_dates[i] ) +end diff --git a/Task/Text-processing-Max-licenses-in-use/M4/text-processing-max-licenses-in-use.m4 b/Task/Text-processing-Max-licenses-in-use/M4/text-processing-max-licenses-in-use.m4 new file mode 100644 index 0000000000..91310e00d3 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/M4/text-processing-max-licenses-in-use.m4 @@ -0,0 +1,12 @@ +divert(-1) +define(`current',0) +define(`max',0) +define(`OUT',`define(`current',incr(current))`'ifelse(eval(current>max),1, + `define(`max',current)`'divert(-1)`'undivert(1)`'divert(1)', + `ifelse(current,max,`divert(1)undivert(1)')')') +define(`IN',`define(`current',decr(current))') +define(`for',`divert(-1)') +include(mlijobs.txt)) +divert +max +undivert(1) diff --git a/Task/Text-processing-Max-licenses-in-use/MAXScript/text-processing-max-licenses-in-use.maxscript b/Task/Text-processing-Max-licenses-in-use/MAXScript/text-processing-max-licenses-in-use.maxscript new file mode 100644 index 0000000000..10cf96be5a --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/MAXScript/text-processing-max-licenses-in-use.maxscript @@ -0,0 +1,42 @@ +fn licencesInUse = +( + local logFile = openFile "mlijobs.txt" + local out = 0 + local maxOut = -1 + local maxTimes = #() + + while not EOF logFile do + ( + line = readLine logFile + + if findString line "OUT" != undefined then + ( + out += 1 + ) + else + ( + out -= 1 + ) + + if out > maxOut then + ( + maxOut = out + maxTimes = #() + ) + + if out == maxOut then + ( + append maxTimes (filterString line " ")[4] + ) + ) + format "Maximum simultaneous license use is % at the following times:\n" maxOut + + for time in maxTimes do + ( + format "%\n" time + ) + + close logFile +) + +licencesInUse() diff --git a/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math b/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math new file mode 100644 index 0000000000..8f9ed9fd98 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Mathematica/text-processing-max-licenses-in-use.math @@ -0,0 +1,9 @@ +LC = 0; LCMax = 0; Scan[ + If[MemberQ[#, "OUT"], LC++; + If[LCMax < LC, LCMax = LC; LCMaxtimes = {};]; + If[LCMax == LC, AppendTo[LCMaxtimes, #[[4]]]], + LC--;] &, Import["mlijobs.txt", "Table"]] +Print["The maximum number of licenses used was ", LCMax, ", at ", LCMaxtimes] + +output: +-> The maximum number of licenses used was 99, at {2008/10/03_08:39:34,2008/10/03_08:40:40} diff --git a/Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ocaml b/Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ocaml new file mode 100644 index 0000000000..fc85cb3b5c --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ocaml @@ -0,0 +1,27 @@ +let () = + let out = ref 0 in + let max_out = ref(-1) in + let max_times = ref [] in + + let ic = open_in "mlijobs.txt" in + try while true do + let line = input_line ic in + let io, date, n = + Scanf.sscanf line + "License %3[IN OUT] %_c %19[0-9/:_] for job %d" + (fun io date n -> (io, date, n)) + in + if io = "OUT" then incr out else decr out; + if !out > !max_out then + ( max_out := !out; + max_times := [date]; ) + else if !out = !max_out then + max_times := date :: !max_times; + done + with End_of_file -> + close_in ic; + Printf.printf + "Maximum simultaneous license use is %d \ + at the following times:\n" !max_out; + List.iter print_endline !max_times; +;; diff --git a/Task/Text-processing-Max-licenses-in-use/Oz/text-processing-max-licenses-in-use.oz b/Task/Text-processing-Max-licenses-in-use/Oz/text-processing-max-licenses-in-use.oz new file mode 100644 index 0000000000..53d0485d24 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Oz/text-processing-max-licenses-in-use.oz @@ -0,0 +1,49 @@ +declare + fun {MaxLicenses Filename ?Times} + InUse = {NewCell 0} + MaxInUse = {NewCell 0} + MaxTimes = {NewCell nil} + in + for Job in {ReadLines Filename} do + case {List.take Job 11} of "License OUT" then + InUse := @InUse + 1 + if @InUse > @MaxInUse then + MaxInUse := @InUse + MaxTimes := nil + end + if @InUse == @MaxInUse then + JobTime = {Nth {String.tokens Job & } 4} + in + MaxTimes := JobTime|@MaxTimes + end + [] "License IN " then + InUse := @InUse - 1 + end + end + Times = {Reverse @MaxTimes} + @MaxInUse + end + + %% Helper. + %% Returns a lazy list. So we don't keep the whole logfile in memory... + fun {ReadLines Filename} + F = {New class $ from Open.file Open.text end init(name:Filename)} + fun lazy {ReadNext} + case {F getS($)} of + false then nil + [] Line then + Line|{ReadNext} + end + end + in + %% close file when handle becomes unreachable + {Finalize.register F proc {$ F} {F close} end} + {ReadNext} + end + + Times + MaxInUse = {MaxLicenses "mlijobs.txt" ?Times} +in + {System.showInfo + "Maximum simultaneous license use is "#MaxInUse#" at the following times:"} + {ForAll Times System.showInfo} diff --git a/Task/Text-processing-Max-licenses-in-use/PARI-GP/text-processing-max-licenses-in-use.pari b/Task/Text-processing-Max-licenses-in-use/PARI-GP/text-processing-max-licenses-in-use.pari new file mode 100644 index 0000000000..9bf0b77788 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/PARI-GP/text-processing-max-licenses-in-use.pari @@ -0,0 +1,18 @@ +license()={ + my(v=externstr("type mlijobs.txt"),u,cur,rec,t); + for(i=1,#v, + u=Vec(v[i]); + if(#u>9 && u[9] == "O", + if(cur++>rec, + rec=cur; + t=[v[i]] + , + if(cur == rec,t=concat(t,[v[i]])) + ) + , + cur-- + ) + ); + print(apply(s->concat(vecextract(Vec(s),"15..33")), t)); + rec +}; diff --git a/Task/Text-processing-Max-licenses-in-use/PHP/text-processing-max-licenses-in-use.php b/Task/Text-processing-Max-licenses-in-use/PHP/text-processing-max-licenses-in-use.php new file mode 100644 index 0000000000..c4e30e5a0f --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/PHP/text-processing-max-licenses-in-use.php @@ -0,0 +1,29 @@ +$handle = fopen ("mlijobs.txt", "rb"); +$maxcount = 0; +$count = 0; +$times = array(); +while (!feof($handle)) { + $buffer = fgets($handle); + $op = trim(substr($buffer,8,3)); + switch ($op){ + case 'IN': + $count--; + break; + case 'OUT': + $count++; + preg_match('/([\d|\/|_|:]+)/',$buffer,$time); + if($count>$maxcount){ + $maxcount = $count; + $times = Array($time[0]); + }elseif($count == $maxcount){ + $times[] = $time[0]; + } + break; + } +} +fclose ($handle); + +echo $maxcount . '
'; +for($i=0;$i'; +} diff --git a/Task/Text-processing-Max-licenses-in-use/PL-I/text-processing-max-licenses-in-use.pli b/Task/Text-processing-Max-licenses-in-use/PL-I/text-processing-max-licenses-in-use.pli new file mode 100644 index 0000000000..ae85e7fb21 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/PL-I/text-processing-max-licenses-in-use.pli @@ -0,0 +1,36 @@ +text3: procedure options (main); /* 19 November 2011 */ + declare line character (80) varying; + declare (nout, max_nout) fixed; + declare saveline character (80) varying controlled; + declare k fixed binary; + declare in file input; + + open file (in) title ('/TEXT-MAX.DAT,TYPE(TEXT),RECSIZE(80)' ); + + on endfile (in) go to finish_up; + + max_nout, nout = 0; + do forever; + get file (in) edit (line) (L); + if substr(line, 9, 4) = 'OUT' then nout = nout+1; + else if substr(line, 9, 3) = 'IN' then + nout = nout-1; + if nout = max_nout then + do; allocate saveline; saveline = line; end; + if nout > max_nout then + do; + do while (allocation(saveline) > 0); free saveline; end; + max_nout = nout; + allocate saveline; + saveline = line; + end; + end; + +finish_up: + put skip list ('The maximum number of licences taken out = ' || max_nout); + do while (allocation(saveline) > 0); + k = index(saveline, '@'); + if k > 0 then put skip list ('It occurred at ' || substr(saveline, k+1) ); + free saveline; + end; +end text3; diff --git a/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 b/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 new file mode 100644 index 0000000000..b2789b2f29 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Perl-6/text-processing-max-licenses-in-use.pl6 @@ -0,0 +1,29 @@ +my %licenses; + +%licenses = 0,0; + +for $*IN.lines -> $line { + my ( $license, $date_time ); + ( *, $license, *, $date_time ) = split /\s+/, $line; + if $license eq 'OUT' { + %licenses++; + if %licenses > %licenses { + %licenses = %licenses; + %licenses = [$date_time]; + } + elsif %licenses == %licenses { + %licenses.push($date_time); + } + } + else { + if %licenses == %licenses { + %licenses[*-1] ~= " through " ~ $date_time; + } + %licenses--; + } +}; + +my $plural = %licenses.elems == 1 ?? '' !! 's'; + +say "Maximum concurrent licenses in use: {%licenses}, in the time period{$plural}:"; +say join ",\n", %licenses.list; diff --git a/Task/Text-processing-Max-licenses-in-use/Perl/text-processing-max-licenses-in-use.pl b/Task/Text-processing-Max-licenses-in-use/Perl/text-processing-max-licenses-in-use.pl new file mode 100644 index 0000000000..ac2b0747bd --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Perl/text-processing-max-licenses-in-use.pl @@ -0,0 +1,27 @@ +#!/usr/bin/perl -w +use strict; + +my $out = 0; +my $max_out = -1; +my @max_times; + +open FH, ') { + chomp; + if (/OUT/) { + $out++; + } else { + $out--; + } + if ($out > $max_out) { + $max_out = $out; + @max_times = (); + } + if ($out == $max_out) { + push @max_times, (split)[3]; + } +} +close FH; + +print "Maximum simultaneous license use is $max_out at the following times:\n"; +print " $_\n" foreach @max_times; diff --git a/Task/Text-processing-Max-licenses-in-use/PicoLisp/text-processing-max-licenses-in-use.l b/Task/Text-processing-Max-licenses-in-use/PicoLisp/text-processing-max-licenses-in-use.l new file mode 100644 index 0000000000..05b1607ac2 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/PicoLisp/text-processing-max-licenses-in-use.l @@ -0,0 +1,19 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(zero Count MaxCount) + +(in (opt) + (while (split (line) " ") + (case (pack (cadr (setq Line @))) + (IN + (dec 'Count) ) + (OUT + (let Time (cadddr Line) + (cond + ((> (inc 'Count) MaxCount) + (setq MaxCount Count MaxTimes Time) ) + ((= Count MaxCount) + (setq MaxTimes (pack MaxTimes " and " Time)) ) ) ) ) ) ) ) + +(prinl "The biggest number of licenses is " MaxCount " at " MaxTimes " !") +(bye) diff --git a/Task/Text-processing-Max-licenses-in-use/PureBasic/text-processing-max-licenses-in-use.purebasic b/Task/Text-processing-Max-licenses-in-use/PureBasic/text-processing-max-licenses-in-use.purebasic new file mode 100644 index 0000000000..523cb26039 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/PureBasic/text-processing-max-licenses-in-use.purebasic @@ -0,0 +1,25 @@ +OpenConsole() + +If ReadFile(0, OpenFileRequester("Text processing/3","mlijobs.txt","All files",1)) + While Not Eof(0) + currline$=ReadString(0) + If StringField(currline$,2," ")="OUT" + counter+1 + Else + counter-1 + EndIf + If counter>max + max=counter + maxtime$=StringField(currline$,4," ") + ElseIf counter=max + maxtime$+#CRLF$+StringField(currline$,4," ") + EndIf + Wend + PrintN(Str(max)+" license(s) used at ;"+#CRLF$+maxtime$) + CloseFile(0) +Else + PrintN("Failed to open the file.") +EndIf + +PrintN(#CRLF$+"Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/Text-processing-Max-licenses-in-use/Python/text-processing-max-licenses-in-use.py b/Task/Text-processing-Max-licenses-in-use/Python/text-processing-max-licenses-in-use.py new file mode 100644 index 0000000000..43457d819d --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Python/text-processing-max-licenses-in-use.py @@ -0,0 +1,10 @@ +out, max_out, max_times = 0, -1, [] +for job in open('mlijobs.txt'): + out += 1 if "OUT" in job else -1 + if out > max_out: + max_out, max_times = out, [] + if out == max_out: + max_times.append(job.split()[3]) + +print("Maximum simultaneous license use is %i at the following times:" % max_out) +print(' ' + '\n '.join(max_times)) diff --git a/Task/Text-processing-Max-licenses-in-use/R/text-processing-max-licenses-in-use.r b/Task/Text-processing-Max-licenses-in-use/R/text-processing-max-licenses-in-use.r new file mode 100644 index 0000000000..1d4940c5a3 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/R/text-processing-max-licenses-in-use.r @@ -0,0 +1,10 @@ +# Read in data, discard useless bits +dfr <- read.table("mlijobs.txt") +dfr <- dfr[,c(2,4)] +# Find most concurrent licences, and when +n.checked.out <- cumsum(ifelse(dfr$V2=="OUT", 1, -1)) +times <- strptime(dfr$V4, "%Y/%m/%d_%H:%M:%S") +most.checked.out <- max(n.checked.out) +when.most.checked.out <- times[which(n.checked.out==most.checked.out)] +# As a bonus, plot license use +plot(times, n.checked.out, type="s") diff --git a/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-1.rexx b/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-1.rexx new file mode 100644 index 0000000000..a22fb9e94a --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-1.rexx @@ -0,0 +1,88 @@ +/*REXX program to process instrument data from a data file. */ + +numeric digits 20 /*allow for bigger numbers. */ +ifid='LICENSE.LOG' /*the input file. */ +ofid='LICENSE.REP' /*the report file. */ +monthDays.=31 /*number of days in every month. */ +monthDays.4 =30 +monthDays.6 =30 +monthDays.9 =30 +monthDays.11=30 + otime='9999 99 99 99 99 99' /*latest OUT time. */ + itime='0000 00 00 00 00 00' /*latest IN time. */ + lowjob=99999 +highjob=0 + + do while lines(ifid)\==0 /*read until finished. */ + rec=linein(ifid) /*read the next record (line). */ + parse upper var rec . InOut . datestamp . . job# /*get some stuff*/ + $datestamp=translate(datestamp,,'/:_') + if InOut=='IN' then do + in.job#=$datestamp /*<─────assign an IN record.*/ + if $datestamp>Itime then itime=$datestamp + end + else do + out.job#=$datestamp /*<─────assign an OUT record.*/ + if $datestampitime + has=inRange(qtime) + if has==maxhas then mtimeL=qtime + if has>maxhas then do + maxhas=has + mtime=qtime + mtimes=qtime + end + qtime=addAsec(qtime) + end /*DO UNTIL*/ + +call sy +parse var mtimes yy mm dd hh mn ss; _=yy'/'mm"/"dd hh':'mn":"ss +call sy 'maximum number of licenses out is ' maxhas " at " _ + +if mtimeL\=='' & mtimeL\==mtimes then + do + maxhas__=left('',length(maxhas)+5) + parse var mtimeL yy mm dd hh mn ss; _=yy'/'mm"/"dd hh':'mn":"ss + call sy ' through ' maxhas__ _ + end + +exit + +/*─────────────────────────────────────addAsec subroutine───────────────*/ +addAsec: procedure expose monthDays.; parse arg yy mm dd hh mn ss +ss=right(ss+1 ,2,0) ; if ss<60 then return yy mm dd hh mn ss +ss=right(ss-60,2,0); mn=right(mn+1,2,0); if mn<60 then return yy mm dd hh mn ss +mn=right(mn-60,2,0); hh=right(hh+1,2,0); if hh<24 then return yy mm dd hh mn ss +monthDays.2=28+leapyear(yy) +??=monthDays.mm +hh=right(hh-24,2,0); dd=right(dd+1,2,0); if dd> in.j then iterate + hases=hases+1 + end +return hases + +/*─────────────────────────────────────LEAPYEAR subroutine──────────────*/ +leapyear: procedure; arg y /*year could be: Y, YY, YYY, YYYY*/ +if length(y)==2 then y=left(right(date(),4),2)y /*adjust for YY year.*/ +if y//4\==0 then return 0 /* not ≈ by 4? Not a leapyear.*/ +return y//100\==0 | y//400==0 /*apply 100 and 400 year rule. */ + +/*─────────────────────────────────────SY subroutine────────────────────*/ +sy: procedure expose ofid; say arg(1); call lineout ofid,arg(1); return diff --git a/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-2.rexx b/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-2.rexx new file mode 100644 index 0000000000..e54691d0b2 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/REXX/text-processing-max-licenses-in-use-2.rexx @@ -0,0 +1,64 @@ +/* REXX ************************************************************** +* 19.11.2012 Walter Pachl transscribed from PL/I +* and dual-coded (for PC (Windows) and TSO) +**********************************************************************/ +Parse Source source +call time 'R' +Say source +If left(source,7)='Windows' Then Do + fid='mlijobs.txt' + Do i=1 By 1 While lines(fid)>0 + l.i=linein(fid) + End + l.0=i-1 + End +Else Do + "ALLOC FI(IN) DA(MLIJOBS.TEXT) SHR REUSE" + 'EXECIO * DISKR IN (STEM L. FINIS' + 'FREE FI(IN)' + End +store.0=0 +max_nout=0 +nout =0 +cnt=0 +cnt.=0 +do i=1 To l.0 + line=l.i + Parse Var line 9 inout +3 + Select + When inout='OUT' then nout = nout+1; + When inout='IN' then nout = nout-1; + Otherwise Iterate + End + cnt.nout=cnt.nout+1 + cnt=cnt+1 + if nout = max_nout then + Call store line + if nout > max_nout then Do + max_nout=nout + drop store. + store.0=0 + Call store + end; + end; + +Say 'The maximum number of licences taken out = ' max_nout +Do i=1 to store.0 + k=pos('@',store.i) + Say 'It occurred at 'substr(store.i,k+1) + End +limit=5 +Do nout=0 To max_nout + If nout=limit+1 Then Say '.........' + If nout<=limit | nout>=max_nout-limit Then + Say right(cnt.nout,5) right(nout,3) + End +Say right(cnt,5) 'Jobs' +Say time('E') 'seconds (elapsed)' +Exit + +store: + z=store.0+1 + store.z=line + store.0=z + Return diff --git a/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-1.rkt b/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-1.rkt new file mode 100644 index 0000000000..04fb5dd303 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-1.rkt @@ -0,0 +1,26 @@ +#lang racket +;;; reads a licence file on standard input +;;; returns max licences used and list of times this occurred +(define (count-licences) + (let inner ((ln (read-line)) (in-use 0) (max-in-use 0) (times-list null)) + (if (eof-object? ln) + (values max-in-use (reverse times-list)) + (let ((mtch (regexp-match #px"License (IN |OUT) @ (.*) for job.*" ln))) + (cond + [(string=? "OUT" (second mtch)) + (let ((in-use+1 (add1 in-use))) + (cond + [(> in-use+1 max-in-use) + (inner (read-line) in-use+1 in-use+1 (list (third mtch)))] + [(= in-use+1 max-in-use) + (inner (read-line) in-use+1 max-in-use (cons (third mtch) times-list))] + [else (inner (read-line) in-use+1 max-in-use times-list)]))] + [(string=? "IN " (second mtch)) + (inner (read-line) (sub1 in-use) max-in-use times-list)] + [else (inner (read-line) in-use max-in-use times-list)]))))) + +(define-values (max-used max-used-when) +(with-input-from-file "mlijobs.txt" count-licences)) +(printf "Maximum licences in simultaneously used is ~a at the following times:~%" + max-used) +(for-each displayln max-used-when) diff --git a/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-2.rkt b/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-2.rkt new file mode 100644 index 0000000000..cedbe50138 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Racket/text-processing-max-licenses-in-use-2.rkt @@ -0,0 +1,23 @@ +#lang racket +;;; reads a licence file on standard input +;;; returns max licences used and list of times this occurred +(define (count-licences) + (define (sub-count-licences) + (for/fold ((in-use 0) (max-in-use 0) (times-list null)) + ((ln (in-lines))) + (let ((mtch (regexp-match #px"License (IN |OUT) @ (.*) for job.*" ln))) + (cond + [(string=? "OUT" (second mtch)) + (let ((in-use+1 (add1 in-use))) + (cond + [(> in-use+1 max-in-use) (values in-use+1 in-use+1 (list (third mtch)))] + [(= in-use+1 max-in-use) (values in-use+1 max-in-use (cons (third mtch) times-list))] + [else (values in-use+1 max-in-use times-list)]))] + [(string=? "IN " (second mtch)) (values (sub1 in-use) max-in-use times-list)] + [else (values in-use max-in-use times-list)])))) + (let-values (((in-use max-in-use times-list) (sub-count-licences))) + (values max-in-use (reverse times-list)))) + +(define-values (max-used max-used-when) (with-input-from-file "mlijobs.txt" count-licences)) +(printf "Maximum licences in simultaneously used is ~a at the following times:~%" max-used) +(for-each displayln max-used-when) diff --git a/Task/Text-processing-Max-licenses-in-use/Ruby/text-processing-max-licenses-in-use.rb b/Task/Text-processing-Max-licenses-in-use/Ruby/text-processing-max-licenses-in-use.rb new file mode 100644 index 0000000000..8eb246b8b5 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Ruby/text-processing-max-licenses-in-use.rb @@ -0,0 +1,15 @@ +out = 0 +max_out = -1 +max_times = [] + +File.foreach('mlijobs.txt') do |line| + out += line.include?("OUT") ? 1 : -1 + if out > max_out + max_out = out + max_times = [] + end + max_times << line.split[3] if out == max_out +end + +puts "Maximum simultaneous license use is #{max_out} at the following times:" +max_times.each {|time| puts " #{time}"} diff --git a/Task/Text-processing-Max-licenses-in-use/Run-BASIC/text-processing-max-licenses-in-use.run b/Task/Text-processing-Max-licenses-in-use/Run-BASIC/text-processing-max-licenses-in-use.run new file mode 100644 index 0000000000..8a9d8670b4 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Run-BASIC/text-processing-max-licenses-in-use.run @@ -0,0 +1,13 @@ +open "c:\data\temp\logFile.txt" for input as #f +while not(eof(#f)) + line input #f, a$ + if word$(a$,2," ") = "IN" then count = count - 1 else count = count + 1 + maxCount = max(maxCount,count) +wend +open "c:\data\temp\logFile.txt" for input as #f +while not(eof(#f)) + line input #f, a$ + if word$(a$,2," ") = "IN" then count = count - 1 else count = count + 1 + if count = maxCount then theDate$ = theDate$ + " | " + word$(a$,4," ") + " Job:";word$(a$,7," ") +wend +print maxCount;" ";theDate$ diff --git a/Task/Text-processing-Max-licenses-in-use/Seed7/text-processing-max-licenses-in-use.seed7 b/Task/Text-processing-Max-licenses-in-use/Seed7/text-processing-max-licenses-in-use.seed7 new file mode 100644 index 0000000000..9f1754c876 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Seed7/text-processing-max-licenses-in-use.seed7 @@ -0,0 +1,33 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var file: inFile is STD_NULL; + var string: line is ""; + var integer: currLicenses is 0; + var integer: maxLicenses is 0; + var array string: maxLicenseTimes is 0 times ""; + var string: eventTime is ""; + begin + inFile := open("mlijobs.txt", "r"); + while hasNext(inFile) do + line := getln(inFile); + if line[9 len 3] = "OUT" then + incr(currLicenses); + if currLicenses >= maxLicenses then + if currLicenses > maxLicenses then + maxLicenses := currLicenses; + maxLicenseTimes := 0 times ""; + end if; + maxLicenseTimes &:= line[15 len 19]; + end if; + elsif currLicenses > 0 then + decr(currLicenses); + end if; + end while; + close(inFile); + writeln("Maximum simultaneous license use is " <& maxLicenses <& " at the following times:"); + for eventTime range maxLicenseTimes do + writeln(eventTime); + end for; + end func; diff --git a/Task/Text-processing-Max-licenses-in-use/TUSCRIPT/text-processing-max-licenses-in-use.tuscript b/Task/Text-processing-Max-licenses-in-use/TUSCRIPT/text-processing-max-licenses-in-use.tuscript new file mode 100644 index 0000000000..ca35d98413 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/TUSCRIPT/text-processing-max-licenses-in-use.tuscript @@ -0,0 +1,18 @@ +$$ MODE TUSCRIPT +joblog="mlijobs.txt",jobnrout=0 +log=FILE (joblog) +DICT jobnrout CREATE +LOOP l=log +jobout=EXTRACT (l,":License :"|,": :") + IF (jobout=="out") THEN + time=EXTRACT (l,":@ :"|,": :"), jobnrout=jobnrout+1 + DICT jobnrout APPEND/QUIET jobnrout,num,cnt,time;" " + ELSE + jobnrout=jobnrout-1 + ENDIF +ENDLOOP +DICT jobnrout UNLOAD jobnrout,num,cnt,time +DICT jobnrout SIZE maxlicout +times=SELECT (time,#maxlicout) +PRINT "The max. number of licences out is ", maxlicout +PRINT "at these times: ", times diff --git a/Task/Text-processing-Max-licenses-in-use/Tcl/text-processing-max-licenses-in-use.tcl b/Task/Text-processing-Max-licenses-in-use/Tcl/text-processing-max-licenses-in-use.tcl new file mode 100644 index 0000000000..b50505ed67 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Tcl/text-processing-max-licenses-in-use.tcl @@ -0,0 +1,23 @@ + set out 0 + set max_out -1 + set max_times {} + + foreach job [split [read [open "mlijobs.txt" "r"]] "\n"] { + if {[lindex $job 1] == "OUT"} { + incr out + } { + incr out -1 + } + if {$out > $max_out} { + set max_out $out + set max_times {} + } + if {$out == $max_out} { + lappend max_times [lindex $job 3] + } + } + + puts "Maximum simultaneous license use is $max_out at the following times:" + foreach t $max_times { + puts " $t" + } diff --git a/Task/Text-processing-Max-licenses-in-use/Ursala/text-processing-max-licenses-in-use.ursala b/Task/Text-processing-Max-licenses-in-use/Ursala/text-processing-max-licenses-in-use.ursala new file mode 100644 index 0000000000..5a251be5d9 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Ursala/text-processing-max-licenses-in-use.ursala @@ -0,0 +1,11 @@ +#import std +#import nat + +log = ^(~&hh==`O,~&tth)*FtPS sep` *F mlijobs_dot_txt +scan = @NiX ~&ar^& ^C/~&alrhr2X ~&arlh?/~&faNlCrtPXPR ~&fabt2R +search = @lSzyCrSPp leql$^&hl@lK2; ^/length@hl ~&rS +format = ^|C\~& --' licenses in use at'@h+ %nP + +#show+ + +main = format search scan log diff --git a/Task/Text-processing-Max-licenses-in-use/Vedit-macro-language/text-processing-max-licenses-in-use.vedit b/Task/Text-processing-Max-licenses-in-use/Vedit-macro-language/text-processing-max-licenses-in-use.vedit new file mode 100644 index 0000000000..36570bc468 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Vedit-macro-language/text-processing-max-licenses-in-use.vedit @@ -0,0 +1,27 @@ +File_Open("|(PATH_ONLY)\data\mlijobs.txt", BROWSE) + +#1 = 0 // Number of licenses active +#2 = 0 // Max number of active licenses found + +Repeat(ALL) { + Search("|{OUT,IN}|W@", ADVANCE+ERRBREAK) + if (Match_Item == 1) { // "OUT" + #1++ + if (#1 > #2) { // new high value + #2 = #1 + Reg_Empty(10) // empty the time list + } + if (#1 == #2) { // same as high value + Reg_Copy(10, 1, APPEND) // store time + } + } else { // "IN" + #1-- + } +} + +Message("Maximum simultaneous license use is ") +Num_Type(#2, LEFT+NOCR) +Message(" at the following times:\n") +Reg_Type(10) + +Buf_Quit(OK) diff --git a/Task/Thieles-interpolation-formula/0DESCRIPTION b/Task/Thieles-interpolation-formula/0DESCRIPTION new file mode 100644 index 0000000000..4a36a42157 --- /dev/null +++ b/Task/Thieles-interpolation-formula/0DESCRIPTION @@ -0,0 +1,20 @@ +{{Wikipedia|Thiele's interpolation formula}} +'''[[wp:Thiele's_interpolation_formula|Thiele's interpolation formula]]''' is an interpolation formula for a function ''f''(•) of a single variable. It is expressed as a [[continued fraction]]: + +: f(x) = f(x_1) + \cfrac{x-x_1}{\rho_1(x_1,x_2) + \cfrac{x-x_2}{\rho_2(x_1,x_2,x_3) - f(x_1) + \cfrac{x-x_3}{\rho_3(x_1,x_2,x_3,x_4) - \rho_1(x_1,x_2) + \cdots}}} + +ρ represents the [[wp:reciprocal difference|reciprocal difference]], demonstrated here for reference: + +:\rho_1(x_0, x_1) = \frac{x_0 - x_1}{f(x_0) - f(x_1)} + +:\rho_2(x_0, x_1, x_2) = \frac{x_0 - x_2}{\rho_1(x_0, x_1) - \rho_1(x_1, x_2)} + f(x_1) + +:\rho_n(x_0,x_1,\ldots,x_n)=\frac{x_0-x_n}{\rho_{n-1}(x_0,x_1,\ldots,x_{n-1})-\rho_{n-1}(x_1,x_2,\ldots,x_n)}+\rho_{n-2}(x_1,\ldots,x_{n-1}) + +Demonstrate Thiele's interpolation function by: +# Building a 32 row ''trig table'' of values of the trig functions ''sin'', ''cos'' and ''tan''. e.g. '''for''' x '''from''' 0 '''by''' 0.05 '''to''' 1.55... +# Using columns from this table define an inverse - using Thiele's interpolation - for each trig function; +# Finally: demonstrate the following well known trigonometric identities: +#* 6 × sin-1 ½ = π +#* 3 × cos-1 ½ = π +#* 4 × tan-1 1 = π diff --git a/Task/Thieles-interpolation-formula/1META.yaml b/Task/Thieles-interpolation-formula/1META.yaml new file mode 100644 index 0000000000..8644b2ad9b --- /dev/null +++ b/Task/Thieles-interpolation-formula/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Arithmetic operations diff --git a/Task/Thieles-interpolation-formula/ALGOL-68/thieles-interpolation-formula.alg b/Task/Thieles-interpolation-formula/ALGOL-68/thieles-interpolation-formula.alg new file mode 100644 index 0000000000..7102a5f1c2 --- /dev/null +++ b/Task/Thieles-interpolation-formula/ALGOL-68/thieles-interpolation-formula.alg @@ -0,0 +1,53 @@ +PROC raise exception = ([]STRING msg)VOID: ( putf(stand error,("Exception:", $" "g$, msg, $l$)); stop ); + +# The MODE of lx and ly here should really be a UNION of "something REAL", +"something COMPLex", and "something SYMBOLIC" ... # + +PROC thiele=([]REAL lx,ly, REAL x) REAL: +BEGIN + []REAL xx=lx[@1],yy=ly[@1]; + INT n=UPB xx; + IF UPB yy=n THEN +# Assuming that the values of xx are distinct ... # + [0:n-1,1:n]REAL p; + p[0,]:=yy[]; + FOR i TO n-1 DO p[1,i]:=(xx[i]-xx[1+i])/(p[0,i]-p[0,1+i]) OD; + FOR i FROM 2 TO n-1 DO + FOR j TO n-i DO + p[i,j]:=(xx[j]-xx[j+i])/(p[i-1,j]-p[i-1,j+1])+p[i-2,j+1] + OD + OD; + REAL a:=0; + FOR i FROM n-1 BY -1 TO 2 DO a:=(x-xx[i])/(p[i,1]-p[i-2,1]+a) OD; + yy[1]+(x-xx[1])/(p[1,1]+a) + ELSE + raise exception(("Unequal length arrays supplied: ",whole(UPB xx,0)," NE ",whole(UPB yy,0))); SKIP + FI +END; + +test:( + FORMAT real fmt = $g(0,real width-2)$; + + REAL lwb x=0, upb x=1.55, delta x = 0.05; + + [0:ENTIER ((upb x-lwb x)/delta x)]STRUCT(REAL x, sin x, cos x, tan x) trig table; + + PROC init trig table = VOID: + FOR i FROM LWB trig table TO UPB trig table DO + REAL x = lwb x+i*delta x; + trig table[i]:=(x, sin(x), cos(x), tan(x)) + OD; + + init trig table; + +# Curry the thiele function to create matching inverse trigonometric functions # + PROC (REAL)REAL inv sin = thiele(sin x OF trig table, x OF trig table,), + inv cos = thiele(cos x OF trig table, x OF trig table,), + inv tan = thiele(tan x OF trig table, x OF trig table,); + + printf(($"pi estimate using "g" interpolation: "f(real fmt)l$, + "sin", 6*inv sin(1/2), + "cos", 3*inv cos(1/2), + "tan", 4*inv tan(1) + )) +) diff --git a/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-1.ada b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-1.ada new file mode 100644 index 0000000000..88db7aa0c5 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-1.ada @@ -0,0 +1,17 @@ +with Ada.Numerics.Generic_Real_Arrays; + +generic + type Real is digits <>; +package Thiele is + package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real); + subtype Real_Array is Real_Arrays.Real_Vector; + + type Thiele_Interpolation (Length : Natural) is private; + + function Create (X, Y : Real_Array) return Thiele_Interpolation; + function Inverse (T : Thiele_Interpolation; X : Real) return Real; +private + type Thiele_Interpolation (Length : Natural) is record + X, Y, RhoX : Real_Array (1 .. Length); + end record; +end Thiele; diff --git a/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-2.ada b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-2.ada new file mode 100644 index 0000000000..3f06108c91 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-2.ada @@ -0,0 +1,56 @@ +package body Thiele is + use type Real_Array; + + function "/" (Left, Right : Real_Array) return Real_Array is + Result : Real_Array (Left'Range); + begin + if Left'Length /= Right'Length then + raise Constraint_Error with "arrays not same size"; + end if; + for I in Result'Range loop + Result (I) := Left (I) / Right (I); + end loop; + return Result; + end "/"; + + function Rho (X, Y : Real_Array) return Real_Array is + N : constant Natural := X'Length; + P : array (1 .. N) of Real_Array (1 .. N) := + (others => (others => 9.9)); + Result : Real_Array (1 .. N); + begin + P (1) (1 .. N) := Y (1 .. N); + P (2) (1 .. N - 1) := (X (1 .. N - 1) - X (2 .. N)) / + (P (1) (1 .. N - 1) - P (1) (2 .. N)); + for I in 3 .. N loop + P (I) (1 .. N - I + 1) := P (I - 2) (2 .. N - I + 2) + + (X (1 .. N - I + 1) - X (I .. N)) / + (P (I - 1) (1 .. N - I + 1) - P (I - 1) (2 .. N - I + 2)); + end loop; + for I in X'Range loop + Result (I) := P (I) (1); + end loop; + return Result; + end Rho; + + function Create (X, Y : Real_Array) return Thiele_Interpolation is + begin + if X'Length < 3 then + raise Constraint_Error with "at least 3 values"; + end if; + if X'Length /= Y'Length then + raise Constraint_Error with "input arrays not same size"; + end if; + return (Length => X'Length, X => X, Y => Y, RhoX => Rho (X, Y)); + end Create; + + function Inverse (T : Thiele_Interpolation; X : Real) return Real is + A : Real := 0.0; + begin + for I in reverse 3 .. T.Length loop + A := (X - T.X (I - 1)) / (T.RhoX (I) - T.RhoX (I - 2) + A); + end loop; + return T.Y (1) + (X - T.X (1)) / (T.RhoX (2) + A); + end Inverse; + +end Thiele; diff --git a/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-3.ada b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-3.ada new file mode 100644 index 0000000000..47bdb9657a --- /dev/null +++ b/Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-3.ada @@ -0,0 +1,43 @@ +with Ada.Text_IO; +with Ada.Numerics.Generic_Elementary_Functions; +with Thiele; + +procedure Main is + package Math is new Ada.Numerics.Generic_Elementary_Functions + (Long_Float); + package Float_Thiele is new Thiele (Long_Float); + use Float_Thiele; + + Row_Count : Natural := 32; + + X_Values : Real_Array (1 .. Row_Count); + Sin_Values : Real_Array (1 .. Row_Count); + Cos_Values : Real_Array (1 .. Row_Count); + Tan_Values : Real_Array (1 .. Row_Count); +begin + -- build table + for I in 1 .. Row_Count loop + X_Values (I) := Long_Float (I) * 0.05 - 0.05; + Sin_Values (I) := Math.Sin (X_Values (I)); + Cos_Values (I) := Math.Cos (X_Values (I)); + Tan_Values (I) := Math.Tan (X_Values (I)); + end loop; + declare + Sin : Thiele_Interpolation := Create (Sin_Values, X_Values); + Cos : Thiele_Interpolation := Create (Cos_Values, X_Values); + Tan : Thiele_Interpolation := Create (Tan_Values, X_Values); + begin + Ada.Text_IO.Put_Line + ("Internal Math.Pi: " & + Long_Float'Image (Ada.Numerics.Pi)); + Ada.Text_IO.Put_Line + ("Thiele 6*InvSin(0.5):" & + Long_Float'Image (6.0 * Inverse (Sin, 0.5))); + Ada.Text_IO.Put_Line + ("Thiele 3*InvCos(0.5):" & + Long_Float'Image (3.0 * Inverse (Cos, 0.5))); + Ada.Text_IO.Put_Line + ("Thiele 4*InvTan(1): " & + Long_Float'Image (4.0 * Inverse (Tan, 1.0))); + end; +end Main; diff --git a/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-1.c b/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-1.c new file mode 100644 index 0000000000..bcfc9852d5 --- /dev/null +++ b/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-1.c @@ -0,0 +1,64 @@ +#include +#include +#include + +#define N 32 +#define N2 (N * (N - 1) / 2) +#define STEP .05 + +double xval[N], t_sin[N], t_cos[N], t_tan[N]; + +/* rho tables, layout: + rho_{n-1}(x0) + rho_{n-2}(x0), rho_{n-1}(x1), + .... + rho_0(x0), rho_0(x1), ... rho_0(x_{n-1}) + rho_i row starts at index (n - 1 - i) * (n - i) / 2 */ +double r_sin[N2], r_cos[N2], r_tan[N2]; + +/* both rho and thiele functions recursively resolve values as decribed by + formulas. rho is cached, thiele is not. */ + +/* rho_n(x_i, x_{i+1}, ..., x_{i + n}) */ +double rho(double *x, double *y, double *r, int i, int n) +{ + if (n < 0) return 0; + if (!n) return y[i]; + + int idx = (N - 1 - n) * (N - n) / 2 + i; + if (r[idx] != r[idx]) /* only happens if value not computed yet */ + r[idx] = (x[i] - x[i + n]) + / (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) + + rho(x, y, r, i + 1, n - 2); + return r[idx]; +} + +double thiele(double *x, double *y, double *r, double xin, int n) +{ + if (n > N - 1) return 1; + return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + + (xin - x[n]) / thiele(x, y, r, xin, n + 1); +} + +#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0) +#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0) +#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0) + +int main() +{ + int i; + for (i = 0; i < N; i++) { + xval[i] = i * STEP; + t_sin[i] = sin(xval[i]); + t_cos[i] = cos(xval[i]); + t_tan[i] = t_sin[i] / t_cos[i]; + } + for (i = 0; i < N2; i++) + /* init rho tables to NaN */ + r_sin[i] = r_cos[i] = r_tan[i] = 0/0.; + + printf("%16.14f\n", 6 * i_sin(.5)); + printf("%16.14f\n", 3 * i_cos(.5)); + printf("%16.14f\n", 4 * i_tan(1.)); + return 0; +} diff --git a/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-2.c b/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-2.c new file mode 100644 index 0000000000..bd1093d310 --- /dev/null +++ b/Task/Thieles-interpolation-formula/C/thieles-interpolation-formula-2.c @@ -0,0 +1,3 @@ +3.14159265358979 +3.14159265358979 +3.14159265358979 diff --git a/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-1.lisp b/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-1.lisp new file mode 100644 index 0000000000..b88feca094 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-1.lisp @@ -0,0 +1,44 @@ +;; 256 is heavy overkill, but hey, we memoized +(defparameter *thiele-length* 256) +(defparameter *rho-cache* (make-hash-table :test #'equal)) + +(defmacro make-thele-func (f name xx0 xx1) + (let ((xv (gensym)) (yv (gensym)) + (x0 (gensym)) (x1 (gensym))) + `(let* ((,xv (make-array (1+ *thiele-length*))) + (,yv (make-array (1+ *thiele-length*))) + (,x0 ,xx0) + (,x1 ,xx1)) + (loop for i to *thiele-length* with x do + (setf x (+ ,x0 (* (/ (- ,x1 ,x0) *thiele-length*) i)) + (aref ,yv i) x + (aref ,xv i) (funcall ,f x))) + (defun ,name (x) (thiele x ,yv ,xv, 0))))) + +(defun rho (yv xv n i) + (let (hit (key (list yv xv n i))) + (if (setf hit (gethash key *rho-cache*)) + hit + (setf (gethash key *rho-cache*) + (cond ((zerop n) (aref yv i)) + ((minusp n) 0) + (t (+ (rho yv xv (- n 2) (1+ i)) + (/ (- (aref xv i) + (aref xv (+ i n))) + (- (rho yv xv (1- n) i) + (rho yv xv (1- n) (1+ i))))))))))) + +(defun thiele (x yv xv n) + (if (= n *thiele-length*) + 1 + (+ (- (rho yv xv n 1) (rho yv xv (- n 2) 1)) + (/ (- x (aref xv (1+ n))) + (thiele x yv xv (1+ n)))))) + +(make-thele-func #'sin inv-sin 0 (/ pi 2)) +(make-thele-func #'cos inv-cos 0 (/ pi 2)) +(make-thele-func #'tan inv-tan 0 (/ pi 2.1)) ; tan(pi/2) is INF + +(format t "~f~%" (* 6 (inv-sin .5))) +(format t "~f~%" (* 3 (inv-cos .5))) +(format t "~f~%" (* 4 (inv-tan 1))) diff --git a/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-2.lisp b/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-2.lisp new file mode 100644 index 0000000000..32b2fb4640 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Common-Lisp/thieles-interpolation-formula-2.lisp @@ -0,0 +1,3 @@ +3.141592653589793 +3.1415926535885172 +3.141592653589819 diff --git a/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d b/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d new file mode 100644 index 0000000000..b62c39d352 --- /dev/null +++ b/Task/Thieles-interpolation-formula/D/thieles-interpolation-formula.d @@ -0,0 +1,71 @@ +import std.stdio, std.range, std.array, std.algorithm, std.math; + +struct Domain { + real b, e, s; + + auto range() const /*pure nothrow*/ { + // return iota(b, e + s, s); + return iota(cast()b, e + s, s); + } +} + +real eval0(alias RY, alias X, alias Y)(in real x) pure nothrow { + real a = 0.0L; + foreach_reverse (i; 2 .. X.length - 3) + a = (x - X[i]) / (RY[i] - RY[i-2] + a); + return Y[1] + (x - X[1]) / (RY[1] + a); +} + +struct Thiele { + immutable real[] Y, X, rhoY, rhoX; + + this(real[] y, real[] x) /*pure nothrow*/ + in { + assert(x.length > 2, "at leat 3 values"); + assert(x.length == y.length, "input arrays not of same size"); + } body { + this.Y = y.idup; + this.X = x.idup; + rhoY = rhoN(Y, X); + rhoX = rhoN(X, Y); + } + + this(in real delegate(real) f, + Domain d=Domain(0.0L, 1.55L, 0.05L)) { + auto xrng = d.range().array(); + this(array(map!f(xrng)), xrng); + } + + auto rhoN(immutable(real)[] y, immutable(real)[] x) /*pure*/ { + int N = x.length; + real[][] p = new real[][](N, N); + p[0][] = y[]; // array/vector operation follow + p[1][0..$-1] = (x[0 .. $-1] - x[1 .. $]) / + (p[0][0 .. $-1] - p[0][1 .. $]); + foreach (int j; 2 .. N - 1) { + immutable M = N - j - 1; + p[j][0..M] = p[j-2][1..M+1] + (x[0..M] - x[j..M+j]) / + (p[j-1][0 .. M] - p[j-1][1 .. M+1]); + } + return p.map!q{a[1]}().array().idup; + } + + alias eval0!(rhoY, X, Y) eval; + alias eval0!(rhoX, Y, X) inverse; +} + +void main() { + // can't pass sin,cos,tan directly + auto tsin = Thiele((real x) => sin(x)); + auto tcos = Thiele((real x) => cos(x)); + auto ttan = Thiele((real x) => tan(x)); + + writefln(" %d interpolating points\n", tsin.X.length); + writefln("std.math.sin(0.5): %20.18f", sin(0.5L)); + writefln(" Thiele sin(0.5): %20.18f\n", tsin.eval(0.5L)); + + writefln("*%20.19f library constant", PI); + writefln(" %20.19f 6 * inv_sin(0.5)", tsin.inverse(0.5L) * 6.0L); + writefln(" %20.19f 3 * inv_cos(0.5)", tcos.inverse(0.5L) * 3.0L); + writefln(" %20.19f 4 * inv_tan(1.0)", ttan.inverse(1.0L) * 4.0L); +} diff --git a/Task/Thieles-interpolation-formula/Go/thieles-interpolation-formula.go b/Task/Thieles-interpolation-formula/Go/thieles-interpolation-formula.go new file mode 100644 index 0000000000..03b9c49178 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Go/thieles-interpolation-formula.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "math" +) + +func main() { + // task 1: build 32 row trig table + const nn = 32 + const step = .05 + xVal := make([]float64, nn) + tSin := make([]float64, nn) + tCos := make([]float64, nn) + tTan := make([]float64, nn) + for i := range xVal { + xVal[i] = float64(i) * step + tSin[i], tCos[i] = math.Sincos(xVal[i]) + tTan[i] = tSin[i] / tCos[i] + } + // task 2: define inverses + iSin := thieleInterpolator(tSin, xVal) + iCos := thieleInterpolator(tCos, xVal) + iTan := thieleInterpolator(tTan, xVal) + // task 3: demonstrate identities + fmt.Printf("%16.14f\n", 6*iSin(.5)) + fmt.Printf("%16.14f\n", 3*iCos(.5)) + fmt.Printf("%16.14f\n", 4*iTan(1)) +} + +func thieleInterpolator(x, y []float64) func(float64) float64 { + n := len(x) + ρ := make([][]float64, n) + for i := range ρ { + ρ[i] = make([]float64, n-i) + ρ[i][0] = y[i] + } + for i := 0; i < n-1; i++ { + ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) + } + for i := 2; i < n; i++ { + for j := 0; j < n-i; j++ { + ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] + } + } + // ρ0 used in closure. the rest of ρ becomes garbage. + ρ0 := ρ[0] + return func(xin float64) float64 { + var a float64 + for i := n - 1; i > 1; i-- { + a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) + } + return y[0] + (xin-x[0])/(ρ0[1]+a) + } +} diff --git a/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs b/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs new file mode 100644 index 0000000000..e589269c24 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Haskell/thieles-interpolation-formula.hs @@ -0,0 +1,26 @@ +thiele xs ys = f rho1 (tail xs) where + f _ [] _ = 1 + f r@(r0:r1:r2:rs) (x:xs) v = r2 - r0 + (v-x) / f (tail r) xs v + + rho1 = (map ((!!1).(++[0])) rho) + + rho = [0,0..] : [0,0..] : ys : rnext (tail rho) xs (tail xs) where + rnext _ _ [] = [] + rnext r@(r0:r1:rs) x xn = let z_ = zipWith in + (z_ (+) (tail r0) + (z_ (/) (z_ (-) x xn) + (z_ (-) r1 (tail r1)))) + : rnext (tail r) x (tail xn) + +-- inverted interpolation function of f +inv_interp f xs = thiele (map f xs) xs + +main = do print $ 3.21 * inv_sin (sin (pi / 3.21)) + print $ pi/1.2345 * inv_cos (cos (1.2345)) + print $ 7 * inv_tan (tan (pi / 7)) + where + inv_sin = inv_interp sin $ div_pi 2 31 + inv_cos = inv_interp cos $ div_pi 2 100 + inv_tan = inv_interp tan $ div_pi 4 1000 -- because we can + -- uniformly take n points from 0 to Pi/d + div_pi d n = map (* (pi / (d * n))) [0..n] diff --git a/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-1.j b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-1.j new file mode 100644 index 0000000000..1bcea6ec2f --- /dev/null +++ b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-1.j @@ -0,0 +1,2 @@ +span =: {. - {: NB. head - tail +spans =: span\ NB. apply span to successive infixes diff --git a/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-2.j b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-2.j new file mode 100644 index 0000000000..900751930a --- /dev/null +++ b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-2.j @@ -0,0 +1,20 @@ +NB. abscissae_of_knots coef ordinates_of_knots +NB. returns the interpolation coefficients for eval +coef =: 4 : 0 + p =. _2 _{.,:y + for_i. i. # x do. + p =. (p , ([: }. - }. p {~ _2:) + (x spans~ 2+]) % 2 spans - }. [: {: p"_) i + end. + x; , _ 1 {. p +) + +NB. unknown_abscissae eval coefficients +eval =: 4 : 0 + 'xx p' =. y + a =. 0 + i =. <: # xx + while. 0 < i=.<:i do. + a =. (x-i{xx)%-/(p{~i+2),(i{p),a + end. + (p{~>:i)+(x-i{xx)%(p{~i+2)+a +) diff --git a/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-3.j b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-3.j new file mode 100644 index 0000000000..89b370e7b7 --- /dev/null +++ b/Task/Thieles-interpolation-formula/J/thieles-interpolation-formula-3.j @@ -0,0 +1,13 @@ +thiele =: 2 : 0 + p =. _2 _{.,:n + for_i. i.#m do. + p =. (p , ([: }. - }. p {~ _2:) + (m spans~ 2+]) % 2 spans - }. [: {: p"_) i + end. + p =. , _ 1 {. p + a =. 0 + i =. <:#m + while. 0 < i=.<:i do. + a =. (y-i{m)%-/(p{~i+2),(i{p),a + end. + (p{~>:i)+(y-i{m)%a+p{~i+2 +) diff --git a/Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ocaml b/Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ocaml new file mode 100644 index 0000000000..70ba9b30ac --- /dev/null +++ b/Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ocaml @@ -0,0 +1,36 @@ +let xv, fv = fst, snd + +let rec rdiff a l r = + if l > r then 0.0 else + if l = r then fv a.(l) else + if l+1 = r then (xv a.(l) -. xv a.(r)) /. (fv a.(l) -. fv a.(r)) else + (xv a.(l) -. xv a.(r)) /. (rdiff a l (r-1) -. rdiff a (l+1) r) +. rdiff a (l+1) (r-1) + +let rec thiele x a a0 k n = + if k = n then 1.0 else + rdiff a a0 (a0+k) -. rdiff a a0 (a0+k-2) +. (x -. xv a.(a0+k)) /. thiele x a a0 (k+1) n + +let interpolate x a n = + let m = Array.length a in + let dist i = abs_float (x -. xv a.(i)) in + let nearer i j = if dist j < dist i then j else i in + let rec closest i j = if j = m then i else closest (nearer i j) (j+1) in + let c = closest 0 1 in + let c' = if c < n/2 then 0 else if c > m-n then m-n else c-(n/2) in + thiele x a c' 0 n + +let table a b n f = + let g i = + let x = a +. (b-.a)*.(float i)/.(float (n-1)) in + (f x, x) in + Array.init n g + +let [sin_tab; cos_tab; tan_tab] = List.map (table 0.0 1.55 32) [sin; cos; tan] + +let test n = + Printf.printf "\nDegree %d interpolation:\n" n; + Printf.printf "6*arcsin(0.5) = %.15f\n" (6.0*.(interpolate 0.5 sin_tab n)); + Printf.printf "3*arccos(0.5) = %.15f\n" (3.0*.(interpolate 0.5 cos_tab n)); + Printf.printf "4*arctan(1.0) = %.15f\n" (4.0*.(interpolate 1.0 tan_tab n));; + +List.iter test [8; 12; 16] diff --git a/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 new file mode 100644 index 0000000000..3c9c46f709 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 @@ -0,0 +1,53 @@ +use v6; + +# reciprocal difference: +multi sub rho($f, @x where { +@x < 1 }) { 0 } # Identity +multi sub rho($f, @x where { +@x == 1 }) { $f(@x[0]) } +multi sub rho($f, @x where { +@x > 1 }) { + my $ord = +@x; + + return + ( @x[0] - @x[* -1] ) # ( x - x[n] ) + / ( rho($f, @x[^($ord -1)]) # / ( rho[n-1](x[0], ..., x[n-1]) + - rho($f, @x[1..^($ord)]) ) # - rho[n-1](x[1], ..., x[n]) ) + + rho($f, @x[1..^($ord -1)]); # + rho[n-2](x[1], ..., x[n-1]) +} + +# Thiele: +multi sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity +multi sub thiele($x, %f, $ord) { + my $f = {%f{$^a}}; # f(x) as a table lookup + + # Caveat: depends on the fact that Rakudo maintains key order within hashes + my $a = rho($f, %f.keys[^($ord +1)]); + my $b = rho($f, %f.keys[^($ord -1)]); + + my $num = $x - %f.keys[$ord]; + my $cont = thiele($x, %f, $ord +1); + + # Thiele always takes this form: + return $a - $b + ( $num / $cont ); +} + +## Demo +sub mk-inv($fn, $d, $lim) { + my %h; + for 0..$lim { %h{ $fn($_ * $d) } = $_ * $d } + return %h; +} + +sub MAIN($tblsz) { + my %invsin = mk-inv(&sin, 0.05, $tblsz); + my %invcos = mk-inv(&cos, 0.05, $tblsz); + my %invtan = mk-inv(&tan, 0.05, $tblsz); + + my $sin_pi = 6 * thiele(0.5, %invsin, 0); + my $cos_pi = 3 * thiele(0.5, %invcos, 0); + my $tan_pi = 4 * thiele(1.0, %invtan, 0); + + say "pi = {pi}"; + say "estimations using a table of $tblsz elements:"; + say "sin interpolation: $sin_pi"; + say "cos interpolation: $cos_pi"; + say "tan interpolation: $tan_pi"; +} diff --git a/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-1.l b/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-1.l new file mode 100644 index 0000000000..b3e58c1536 --- /dev/null +++ b/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-1.l @@ -0,0 +1,54 @@ +(scl 17) +(load "@lib/math.l") + +(setq + *X-Table (range 0.0 1.55 0.05) + *SinTable (mapcar sin *X-Table) + *CosTable (mapcar cos *X-Table) + *TanTable (mapcar tan *X-Table) + *TrigRows (length *X-Table) ) + +(let N2 (>> 1 (* *TrigRows (dec *TrigRows))) + (setq + *InvSinTable (need N2) + *InvCosTable (need N2) + *InvTanTable (need N2) ) ) + +(de rho (Tbl Inv I N) + (cond + ((lt0 N) 0) + ((=0 N) (get *X-Table I)) + (T + (let Idx (+ I (>> 1 (* (- *TrigRows 1 N) (- *TrigRows N)))) + (or + (get Inv Idx) + (set (nth Inv Idx) # only happens if value not computed yet + (+ + (rho Tbl Inv (inc I) (- N 2)) + (*/ + (- (get Tbl I) (get Tbl (+ I N))) + 1.0 + (- + (rho Tbl Inv I (dec N)) + (rho Tbl Inv (inc I) (dec N)) ) ) ) ) ) ) ) ) ) + +(de thiele (Tbl Inv X N) + (if (> N *TrigRows) + 1.0 + (+ + (- + (rho Tbl Inv 1 (dec N)) + (rho Tbl Inv 1 (- N 3)) ) + (*/ + (- X (get Tbl N)) + 1.0 + (thiele Tbl Inv X (inc N)) ) ) ) ) + +(de iSin (X) + (thiele *SinTable *InvSinTable X 1) ) + +(de iCos (X) + (thiele *CosTable *InvCosTable X 1) ) + +(de iTan (X) + (thiele *TanTable *InvTanTable 1.0 1) ) diff --git a/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-2.l b/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-2.l new file mode 100644 index 0000000000..9117f245b8 --- /dev/null +++ b/Task/Thieles-interpolation-formula/PicoLisp/thieles-interpolation-formula-2.l @@ -0,0 +1,3 @@ +(prinl (round (* 6 (iSin 0.5)) 15)) +(prinl (round (* 3 (iCos 0.5)) 15)) +(prinl (round (* 4 (iTan 1.0)) 15)) diff --git a/Task/Thieles-interpolation-formula/PowerShell/thieles-interpolation-formula.psh b/Task/Thieles-interpolation-formula/PowerShell/thieles-interpolation-formula.psh new file mode 100644 index 0000000000..3ce4c75735 --- /dev/null +++ b/Task/Thieles-interpolation-formula/PowerShell/thieles-interpolation-formula.psh @@ -0,0 +1,69 @@ +Function Reciprocal-Difference( [Double[][]] $function ) +{ + $rho=@() + $rho+=0 + $funcl = $function.length + if( $funcl -gt 0 ) + { + -2..($funcl-1) | ForEach-Object { + $i=$_ + #Write-Host "$($i+1) - $($rho[$i+1]) - $($rho[$i+1].GetType())" + $rho[$i+2] = $( 0..($funcl-$i-1) | Where-Object {$_ -lt $funcl} | ForEach-Object { + $j=$_ + switch ($i) { + {$_ -lt 0 } { 0 } + {$_ -eq 0 } { $function[$j][1] } + {$_ -gt 0 } { ( $function[$j][0] - $function[$j+$i][0] ) / ( $rho[$i+1][$j] - $rho[$i+1][$j+1] ) + $rho[$i][$j+1] } + } + if( $_ -lt $funcl ) + { + $rho += 0 + } + }) + } + } + $rho +} + +Function Thiele-Interpolation ( [Double[][]] $function ) +{ + $funcl = $function.length + $invoke = "{`n`tparam([Double] `$x)`n" + if($funcl -gt 1) + { + $rho = Reciprocal-Difference $function + ($funcl-1)..0 | ForEach-Object { + $invoke += "`t" + $invoke += '$x{0} = {1} - {2}' -f $_, @($rho[$_+2])[0], @($rho[$_])[0] + if($_ -lt ($funcl-1)) + { + $invoke += ' + ( $x - {0} ) / $x{1} ' -f $function[$_][0], ($_+1) + } + $invoke += "`n" + } + $invoke+="`t`$x0`n}" + } else { + $invoke += "`t`$x`n}" + } + invoke-expression $invoke +} + +$sint=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $sint[$_] = [Math]::sin($_) } +$cost=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $cost[$_] = [Math]::cos($_) } +$tant=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $tant[$_] = [Math]::tan($_) } +$asint=New-Object 'Double[][]' 32,2; $sint.GetEnumerator() | Sort-Object Value | ForEach-Object {$i=0}{ $asint[$i][0] = $_.Value; $asint[$i][1] = $_.Name; $i++ } +$acost=New-Object 'Double[][]' 32,2; $cost.GetEnumerator() | Sort-Object Value | ForEach-Object { $i=0 }{ $acost[$i][0] = $_.Value; $acost[$i][1] = $_.Name; $i++ } +$atant=New-Object 'Double[][]' 32,2; $tant.GetEnumerator() | Sort-Object Value | ForEach-Object {$i=0}{ $atant[$i][0] = $_.Value; $atant[$i][1] = $_.Name; $i++ } + +$asin = (Thiele-Interpolation $asint) +#uncomment to see the function +#"{$asin}" +6*$asin.InvokeReturnAsIs(.5) +$acos = (Thiele-Interpolation $acost) +#uncomment to see the function +#"{$acos}" +3*$acos.InvokeReturnAsIs(.5) +$atan = (Thiele-Interpolation $atant) +#uncomment to see the function +#"{$atan}" +4*$atan.InvokeReturnAsIs(1) diff --git a/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-1.tcl b/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-1.tcl new file mode 100644 index 0000000000..2e2aa312a4 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-1.tcl @@ -0,0 +1,44 @@ +# +### Create a thiele-interpretation function with the given name that interpolates +### off the given table. +# +proc thiele {name : X -> F} { + # Sanity check + if {[llength $X] != [llength $F]} { + error "unequal length lists supplied: [llength $X] != [llength $F]" + } + + # + ### Compute the table of reciprocal differences + # + set p [lrepeat [llength $X] [lrepeat [llength $X] 0.0]] + set i 0 + foreach x0 [lrange $X 0 end-1] x1 [lrange $X 1 end] \ + f0 [lrange $F 0 end-1] f1 [lrange $F 1 end] { + lset p $i 0 $f0 + lset p $i 1 [expr {($x0 - $x1) / ($f0 - $f1)}] + lset p [incr i] 0 $f1 + } + for {set j 2} {$j<[llength $X]-1} {incr j} { + for {set i 0} {$i<[llength $X]-$j} {incr i} { + lset p $i $j [expr { + [lindex $p $i+1 $j-2] + + ([lindex $X $i] - [lindex $X $i+$j]) / + ([lindex $p $i $j-1] - [lindex $p $i+1 $j-1]) + }] + } + } + + # + ### Make pseudo-curried function that actually evaluates Thiele's formula + # + interp alias {} $name {} apply {{X rho f1 x} { + set a 0.0 + foreach Xi [lreverse [lrange $X 2 end]] \ + Ri [lreverse [lrange $rho 2 end]] \ + Ri2 [lreverse [lrange $rho 0 end-2]] { + set a [expr {($x - $Xi) / ($Ri - $Ri2 + $a)}] + } + expr {$f1 + ($x - [lindex $X 1]) / ([lindex $rho 1] + $a)} + }} $X [lindex $p 1] [lindex $F 1] +} diff --git a/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-2.tcl b/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-2.tcl new file mode 100644 index 0000000000..5d0e27f2d4 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Tcl/thieles-interpolation-formula-2.tcl @@ -0,0 +1,16 @@ +proc initThieleTest {} { + for {set i 0} {$i < 32} {incr i} { + lappend trigTable(x) [set x [expr {0.05 * $i}]] + lappend trigTable(sin) [expr {sin($x)}] + lappend trigTable(cos) [expr {cos($x)}] + lappend trigTable(tan) [expr {tan($x)}] + } + + thiele invSin : $trigTable(sin) -> $trigTable(x) + thiele invCos : $trigTable(cos) -> $trigTable(x) + thiele invTan : $trigTable(tan) -> $trigTable(x) +} +initThieleTest +puts "pi estimate using sin interpolation: [expr {6 * [invSin 0.5]}]" +puts "pi estimate using cos interpolation: [expr {3 * [invCos 0.5]}]" +puts "pi estimate using tan interpolation: [expr {4 * [invTan 1.0]}]" diff --git a/Task/Tic-tac-toe/0DESCRIPTION b/Task/Tic-tac-toe/0DESCRIPTION new file mode 100644 index 0000000000..19c33f49f4 --- /dev/null +++ b/Task/Tic-tac-toe/0DESCRIPTION @@ -0,0 +1 @@ +Play a game of [[wp:Tic-tac-toe|tic-tac-toe]]. Ensure that legal moves are played and that a winning position is notified. diff --git a/Task/Tic-tac-toe/1META.yaml b/Task/Tic-tac-toe/1META.yaml new file mode 100644 index 0000000000..a2413d963b --- /dev/null +++ b/Task/Tic-tac-toe/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Games diff --git a/Task/Tic-tac-toe/Ada/tic-tac-toe.ada b/Task/Tic-tac-toe/Ada/tic-tac-toe.ada new file mode 100644 index 0000000000..fa58b6a881 --- /dev/null +++ b/Task/Tic-tac-toe/Ada/tic-tac-toe.ada @@ -0,0 +1,124 @@ +with Ada.Text_IO, Ada.Numerics.Discrete_Random; + -- can play human-human, human-computer, computer-human or computer-computer + -- the computer isn't very clever: it just chooses a legal random move + +procedure Tic_Tac_Toe is + + type The_Range is range 1 .. 3; + type Board_Type is array (The_Range, The_Range) of Character; + + package Rand is new Ada.Numerics.Discrete_Random(The_Range); + Gen: Rand.Generator; -- required for the random moves + + procedure Show_Board(Board: Board_Type) is + use Ada.Text_IO; + begin + for Row in The_Range loop + for Column in The_Range loop + Put(Board(Row, Column)); + end loop; + Put_Line(""); + end loop; + Put_Line(""); + end Show_Board; + + function Find_Winner(Board: Board_Type) return Character is + -- if 'x' or 'o' wins, it returns that, else it returns ' ' + + function Three_Equal(A,B,C: Character) return Boolean is + begin + return (A=B) and (A=C); + end Three_Equal; + + begin -- Find_Winner + for I in The_Range loop + if Three_Equal(Board(I,1), Board(I,2), Board(I,3)) then + return Board(I,1); + elsif Three_Equal(Board(1,I), Board(2,I), Board(3,I)) then + return Board(1,I); + end if; + end loop; + if Three_Equal(Board(1,1), Board(2,2), Board (3,3)) or + Three_Equal(Board(3,1), Board(2,2), Board (1,3)) then + return Board(2,2); + end if; + return ' '; + end Find_Winner; + + procedure Do_Move(Board: in out Board_Type; + New_Char: Character; Computer_Move: Boolean) is + Done: Boolean := False; + C: Character; + use Ada.Text_IO; + + procedure Do_C_Move(Board: in out Board_Type; New_Char: Character) is + Found: Boolean := False; + X,Y: The_Range; + begin + while not Found loop + X := Rand.Random(Gen); + Y := Rand.Random(Gen); + if (Board(X,Y) /= 'x') and (Board(X,Y) /= 'o') then + Found := True; + Board(X,Y) := New_Char; + end if; + end loop; + end Do_C_Move; + + begin + if Computer_Move then + Do_C_Move(Board, New_Char); + else -- read move; + Put_Line("Choose your move, " & New_Char); + while not Done loop + Get(C); + for Row in The_Range loop + for Col in The_Range loop + if Board(Row, Col) = C then + Board(Row, Col) := New_Char; + Done := True; + end if; + end loop; + end loop; + end loop; + end if; + end Do_Move; + + The_Board : Board_Type := (('1','2','3'), ('4','5','6'), ('7','8','9')); + Cnt_Moves: Natural := 0; + Players: array(0 .. 1) of Character := ('x', 'o'); -- 'x' begins + C_Player: array(0 .. 1) of Boolean := (False, False); + Reply: Character; + +begin -- Tic_Tac_Toe + + -- firstly, ask whether the computer shall take over either player + for I in Players'Range loop + Ada.Text_IO.Put_Line("Shall " & Players(I) & + " be run by the computer? (y=yes)"); + Ada.Text_IO.Get(Reply); + if Reply='y' or Reply='Y' then + C_Player(I) := True; + Ada.Text_IO.Put_Line("Yes!"); + else + Ada.Text_IO.Put_Line("No!"); + end if; + end loop; + Rand.Reset(Gen); -- to initalize the random generator + + -- now run the game + while (Find_Winner(The_Board) = ' ') and (Cnt_Moves < 9) loop + Show_Board(The_Board); + Do_Move(The_Board, Players(Cnt_Moves mod 2), C_Player(Cnt_Moves mod 2)); + Cnt_Moves := Cnt_Moves + 1; + end loop; + Ada.Text_IO.Put_Line("This is the end!"); + + -- finally, output the outcome + Show_Board (The_Board); + if Find_Winner(The_Board) = ' ' then + Ada.Text_IO.Put_Line("Draw"); + else + Ada.Text_IO.Put_Line("The winner is: " & Find_Winner(The_Board)); + end if; +end Tic_Tac_Toe; diff --git a/Task/Tic-tac-toe/AutoHotkey/tic-tac-toe.ahk b/Task/Tic-tac-toe/AutoHotkey/tic-tac-toe.ahk new file mode 100644 index 0000000000..88015bc309 --- /dev/null +++ b/Task/Tic-tac-toe/AutoHotkey/tic-tac-toe.ahk @@ -0,0 +1,106 @@ +Gui, Add, Button, x12 y12 w30 h30 vB1 gButtonHandler, +Gui, Add, Button, x52 y12 w30 h30 vB2 gButtonHandler, +Gui, Add, Button, x92 y12 w30 h30 vB3 gButtonHandler, +Gui, Add, Button, x12 y52 w30 h30 vB4 gButtonHandler, +Gui, Add, Button, x52 y52 w30 h30 vB5 gButtonHandler, +Gui, Add, Button, x92 y52 w30 h30 vB6 gButtonHandler, +Gui, Add, Button, x12 y92 w30 h30 vB7 gButtonHandler, +Gui, Add, Button, x52 y92 w30 h30 vB8 gButtonHandler, +Gui, Add, Button, x92 y92 w30 h30 vB9 gButtonHandler, +; Generated using SmartGUI Creator 4.0 +Gui, Show, x127 y87 h150 w141, Tic-Tac-Toe +Winning_Moves := "123,456,789,147,258,369,159,357" +Return + +ButtonHandler: + ; Fired whenever the user clicks on an enabled button + Go(A_GuiControl,"X") + GoSub MyMove +Return + +MyMove: ; Loops through winning moves. First attempts to win, then to block, then a random move + Went=0 + Loop, parse, Winning_Moves,`, + { + Current_Set := A_LoopField + X:=O:=0 + Loop, parse, Current_Set + { + GuiControlGet, Char,,Button%A_LoopField% + If ( Char = "O" ) + O++ + If ( Char = "X" ) + X++ + } + If ( O = 2 and X = 0 ) or ( X = 2 and O = 0 ){ + Finish_Line(Current_Set) + Went = 1 + Break ; out of the Winning_Moves Loop to ensure the computer goes only once + } + } + If (!Went) + GoSub RandomMove +Return + +Go(Control,chr){ + GuiControl,,%Control%, %chr% + GuiControl,Disable,%Control% + GoSub, CheckWin +} + +CheckWin: + Loop, parse, Winning_Moves,`, + { + Current_Set := A_LoopField + X:=O:=0 + Loop, parse, Current_Set + { + GuiControlGet, Char,,Button%A_LoopField% + If ( Char = "O" ) + O++ + If ( Char = "X" ) + X++ + } + If ( O = 3 ){ + Msgbox O Wins! + GoSub DisableAll + Break + } + If ( X = 3 ){ + MsgBox X Wins! + GoSub DisableAll + Break + } + } +return + +DisableAll: + Loop, 9 + GuiControl, Disable, Button%A_Index% +return + +Finish_Line(Set){ ; Finish_Line is called when a line exists with 2 of the same character. It goes in the remaining spot, thereby blocking or winning. + Loop, parse, set + { + GuiControlGet, IsEnabled, Enabled, Button%A_LoopField% + Control=Button%A_LoopField% + If IsEnabled + Go(Control,"O") + } +} + +RandomMove: + Loop{ + Random, rnd, 1, 9 + GuiControlGet, IsEnabled, Enabled, Button%rnd% + If IsEnabled + { + Control=Button%rnd% + Go(Control,"O") + Break + } + } +return + +GuiClose: +ExitApp diff --git a/Task/Tic-tac-toe/C-sharp/tic-tac-toe.cs b/Task/Tic-tac-toe/C-sharp/tic-tac-toe.cs new file mode 100644 index 0000000000..cb6f9b1bc1 --- /dev/null +++ b/Task/Tic-tac-toe/C-sharp/tic-tac-toe.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace RosettaTicTacToe +{ + class Program + { + + /*================================================================ + *Pieces (players and board) + *================================================================*/ + static string[][] Players = new string[][] { + new string[] { "COMPUTER", "X" }, // computer player + new string[] { "HUMAN", "O" } // human player + }; + + const int Unplayed = -1; + const int Computer = 0; + const int Human = 1; + + // GameBoard holds index into Players[] (0 or 1) or Unplayed (-1) if location not yet taken + static int[] GameBoard = new int[9]; + + static int[] corners = new int[] { 0, 2, 6, 8 }; + + static int[][] wins = new int[][] { + new int[] { 0, 1, 2 }, new int[] { 3, 4, 5 }, new int[] { 6, 7, 8 }, + new int[] { 0, 3, 6 }, new int[] { 1, 4, 7 }, new int[] { 2, 5, 8 }, + new int[] { 0, 4, 8 }, new int[] { 2, 4, 6 } }; + + + /*================================================================ + *Main Game Loop (this is what runs/controls the game) + *================================================================*/ + static void Main(string[] args) + { + while (true) + { + Console.Clear(); + Console.WriteLine("Welcome to Rosetta Code Tic-Tac-Toe for C#."); + initializeGameBoard(); + displayGameBoard(); + int currentPlayer = rnd.Next(0, 2); // current player represented by Players[] index of 0 or 1 + Console.WriteLine("The first move goes to {0} who is playing {1}s.\n", playerName(currentPlayer), playerToken(currentPlayer)); + while (true) + { + int thisMove = getMoveFor(currentPlayer); + if (thisMove == Unplayed) + { + Console.WriteLine("{0}, you've quit the game ... am I that good?", playerName(currentPlayer)); + break; + } + playMove(thisMove, currentPlayer); + displayGameBoard(); + if (isGameWon()) + { + Console.WriteLine("{0} has won the game!", playerName(currentPlayer)); + break; + } + else if (isGameTied()) + { + Console.WriteLine("Cat game ... we have a tie."); + break; + } + currentPlayer = getNextPlayer(currentPlayer); + } + if (!playAgain()) + return; + } + } + + /*================================================================ + *Move Logic + *================================================================*/ + static int getMoveFor(int player) + { + if (player == Human) + return getManualMove(player); + else + { + //int selectedMove = getManualMove(player); + //int selectedMove = getRandomMove(player); + int selectedMove = getSemiRandomMove(player); + //int selectedMove = getBestMove(player); + Console.WriteLine("{0} selects position {1}.", playerName(player), selectedMove + 1); + return selectedMove; + } + } + + static int getManualMove(int player) + { + while (true) + { + Console.Write("{0}, enter you move (number): ", playerName(player)); + ConsoleKeyInfo keyInfo = Console.ReadKey(); + Console.WriteLine(); // keep the display pretty + if (keyInfo.Key == ConsoleKey.Escape) + return Unplayed; + if (keyInfo.Key >= ConsoleKey.D1 && keyInfo.Key <= ConsoleKey.D9) + { + int move = keyInfo.KeyChar - '1'; // convert to between 0..8, a GameBoard index position. + if (GameBoard[move] == Unplayed) + return move; + else + Console.WriteLine("Spot {0} is already taken, please select again.", move + 1); + } + else + Console.WriteLine("Illegal move, please select again.\n"); + } + } + + static int getRandomMove(int player) + { + int movesLeft = GameBoard.Count(position => position == Unplayed); + int x = rnd.Next(0, movesLeft); + for (int i = 0; i < GameBoard.Length; i++) // walk board ... + { + if (GameBoard[i] == Unplayed && x < 0) // until we reach the unplayed move. + return i; + x--; + } + return Unplayed; + } + + // plays random if no winning move or needed block. + static int getSemiRandomMove(int player) + { + int posToPlay; + if (checkForWinningMove(player, out posToPlay)) + return posToPlay; + if (checkForBlockingMove(player, out posToPlay)) + return posToPlay; + return getRandomMove(player); + } + + // purposely not implemented (this is the thinking part). + static int getBestMove(int player) + { + return -1; + } + + static bool checkForWinningMove(int player, out int posToPlay) + { + posToPlay = Unplayed; + foreach (var line in wins) + if (twoOfThreeMatchPlayer(player, line, out posToPlay)) + return true; + return false; + } + + static bool checkForBlockingMove(int player, out int posToPlay) + { + posToPlay = Unplayed; + foreach (var line in wins) + if (twoOfThreeMatchPlayer(getNextPlayer(player), line, out posToPlay)) + return true; + return false; + } + + static bool twoOfThreeMatchPlayer(int player, int[] line, out int posToPlay) + { + int cnt = 0; + posToPlay = int.MinValue; + foreach (int pos in line) + { + if (GameBoard[pos] == player) + cnt++; + else if (GameBoard[pos] == Unplayed) + posToPlay = pos; + } + return cnt == 2 && posToPlay >= 0; + } + + static void playMove(int boardPosition, int player) + { + GameBoard[boardPosition] = player; + } + + static bool isGameWon() + { + return wins.Any(line => takenBySamePlayer(line[0], line[1], line[2])); + } + + static bool takenBySamePlayer(int a, int b, int c) + { + return GameBoard[a] != Unplayed && GameBoard[a] == GameBoard[b] && GameBoard[a] == GameBoard[c]; + } + + static bool isGameTied() + { + return !GameBoard.Any(spot => spot == Unplayed); + } + + /*================================================================ + *Misc Methods + *================================================================*/ + static Random rnd = new Random(); + + static void initializeGameBoard() + { + for (int i = 0; i < GameBoard.Length; i++) + GameBoard[i] = Unplayed; + } + + static string playerName(int player) + { + return Players[player][0]; + } + + static string playerToken(int player) + { + return Players[player][1]; + } + + static int getNextPlayer(int player) + { + return (player + 1) % 2; + } + + static void displayGameBoard() + { + Console.WriteLine(" {0} | {1} | {2}", pieceAt(0), pieceAt(1), pieceAt(2)); + Console.WriteLine("---|---|---"); + Console.WriteLine(" {0} | {1} | {2}", pieceAt(3), pieceAt(4), pieceAt(5)); + Console.WriteLine("---|---|---"); + Console.WriteLine(" {0} | {1} | {2}", pieceAt(6), pieceAt(7), pieceAt(8)); + Console.WriteLine(); + } + + static string pieceAt(int boardPosition) + { + if (GameBoard[boardPosition] == Unplayed) + return (boardPosition + 1).ToString(); // display 1..9 on board rather than 0..8 + return playerToken(GameBoard[boardPosition]); + } + + private static bool playAgain() + { + Console.WriteLine("\nDo you want to play again?"); + return Console.ReadKey(false).Key == ConsoleKey.Y; + } + } + +} diff --git a/Task/Tic-tac-toe/C/tic-tac-toe.c b/Task/Tic-tac-toe/C/tic-tac-toe.c new file mode 100644 index 0000000000..a4b94a5c68 --- /dev/null +++ b/Task/Tic-tac-toe/C/tic-tac-toe.c @@ -0,0 +1,103 @@ +#include +#include + +int b[3][3]; /* board. 0: blank; -1: computer; 1: human */ + +int check_winner() +{ + int i; + for (i = 0; i < 3; i++) { + if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) + return b[i][0]; + if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) + return b[0][i]; + } + if (!b[1][1]) return 0; + + if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]; + if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]; + + return 0; +} + +void showboard() +{ + const char *t = "X O"; + int i, j; + for (i = 0; i < 3; i++, putchar('\n')) + for (j = 0; j < 3; j++) + printf("%c ", t[ b[i][j] + 1 ]); + printf("-----\n"); +} + +#define for_ij for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) +int best_i, best_j; +int test_move(int val, int depth) +{ + int i, j, score; + int best = -1, changed = 0; + + if ((score = check_winner())) return (score == val) ? 1 : -1; + + for_ij { + if (b[i][j]) continue; + + changed = b[i][j] = val; + score = -test_move(-val, depth + 1); + b[i][j] = 0; + + if (score <= best) continue; + if (!depth) { + best_i = i; + best_j = j; + } + best = score; + } + + return changed ? best : 0; +} + +const char* game(int user) +{ + int i, j, k, move, win = 0; + for_ij b[i][j] = 0; + + printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n"); + printf("You have O, I have X.\n\n"); + for (k = 0; k < 9; k++, user = !user) { + while(user) { + printf("your move: "); + if (!scanf("%d", &move)) { + scanf("%*s"); + continue; + } + if (--move < 0 || move >= 9) continue; + if (b[i = move / 3][j = move % 3]) continue; + + b[i][j] = 1; + break; + } + if (!user) { + if (!k) { /* randomize if computer opens, less boring */ + best_i = rand() % 3; + best_j = rand() % 3; + } else + test_move(-1, 0); + + b[best_i][best_j] = -1; + printf("My move: %d\n", best_i * 3 + best_j + 1); + } + + showboard(); + if ((win = check_winner())) + return win == 1 ? "You win.\n\n": "I win.\n\n"; + } + return "A draw.\n\n"; +} + +int main() +{ + int first = 0; + while (1) printf("%s", game(first = !first)); + return 0; +} diff --git a/Task/Tic-tac-toe/D/tic-tac-toe.d b/Task/Tic-tac-toe/D/tic-tac-toe.d new file mode 100644 index 0000000000..09b484b208 --- /dev/null +++ b/Task/Tic-tac-toe/D/tic-tac-toe.d @@ -0,0 +1,120 @@ +import std.stdio, std.string, std.algorithm, std.conv, + std.random, std.ascii, std.array, std.range; + +struct GameBoard { + dchar[9] board = "123456789"; + enum : char { human = 'X', computer = 'O' } + enum Game { going, humanWins, computerWins, draw } + + const pure nothrow invariant() { + foreach (i, c; board) + if (isDigit(c)) + assert(i == c - '1'); // in correct position? + else + assert(c == human || c == computer); + } + + string toString() const { + return xformat("%(%-(%s|%)\n-+-+-\n%)", + std.range.chunks(board.dup, 3)); + } + + bool isAvailable(in int i) const pure nothrow { + if (i < 0 || i >= 9) + return false; + return isDigit(board[i]); + } + + int[] availablePositions() const pure nothrow { + // not pure not nothrow: + //return iota(9).filter!(i => isDigit(board[i]))().array(); + int[] result; + foreach (i; 0 .. 9) + if (isAvailable(i)) + result ~= i; + return result; + } + + Game winner() const pure nothrow { + immutable wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], + [0, 3, 6], [1, 4, 7], [2, 5, 8], + [0, 4, 8], [2, 4, 6]]; + + foreach (const win; wins) { + immutable bw0 = board[win[0]]; + if (isDigit(bw0)) + continue; // nobody wins on this one + + if (bw0 == board[win[1]] && bw0 == board[win[2]]) + return bw0 == GameBoard.human ? + Game.humanWins : + Game.computerWins; + } + + return availablePositions().empty ? Game.draw: Game.going; + } + + bool finished() const pure nothrow { + return winner() != Game.going; + } + + int computerMove() const // random move + out(res) { + assert(res >= 0 && res < 9 && isAvailable(res)); + } body { + // return choice(availablePositions()); + return randomCover(availablePositions(), rndGen).front; + } +} + + +GameBoard playGame() { + GameBoard board; + bool playsHuman = true; + + while (!board.finished()) { + writeln(board); + + int move; + if (playsHuman) { + do { + writef("Your move (available moves: %s)? ", + board.availablePositions().map!q{ a + 1 }()); + readf("%d\n", &move); + move--; // zero based indexing + if (move < 0) + return board; + } while (!board.isAvailable(move)); + } else + move = board.computerMove(); + + assert(board.isAvailable(move)); + writefln("\n%s chose %d", playsHuman ? "You" : "I", move + 1); + board.board[move] = playsHuman ? GameBoard.human : + GameBoard.computer; + playsHuman = !playsHuman; // switch player + } + + return board; +} + + +void main() { + writeln("Tic-tac-toe game player.\n"); + immutable outcome = playGame().winner(); + + final switch (outcome) { + case GameBoard.Game.going: + writeln("Game stopped."); + break; + case GameBoard.Game.humanWins: + writeln("\nYou win!"); + break; + case GameBoard.Game.computerWins: + writeln("\nI win."); + break; + case GameBoard.Game.draw: + writeln("\nDraw"); + break; + } +} diff --git a/Task/Tic-tac-toe/Go/tic-tac-toe.go b/Task/Tic-tac-toe/Go/tic-tac-toe.go new file mode 100644 index 0000000000..88782a1490 --- /dev/null +++ b/Task/Tic-tac-toe/Go/tic-tac-toe.go @@ -0,0 +1,160 @@ +package main + +import ( + "bufio" + "fmt" + "math/rand" + "os" + "strings" +) + +var b []byte + +func printBoard() { + fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) +} + +var pScore, cScore int +var pMark, cMark byte = 'X', 'O' +var in = bufio.NewReader(os.Stdin) + +func main() { + b = make([]byte, 9) + fmt.Println("Play by entering a digit.") + for { + // start of game + for i := range b { + b[i] = '1' + byte(i) + } + computerStart := cMark == 'X' + if computerStart { + fmt.Println("I go first, playing X's") + } else { + fmt.Println("You go first, playing X's") + } + TakeTurns: + for { + if !computerStart { + if !playerTurn() { + return + } + if gameOver() { + break TakeTurns + } + + } + computerStart = false + computerTurn() + if gameOver() { + break TakeTurns + } + } + fmt.Println("Score: you", pScore, "me", cScore) + fmt.Println("\nLet's play again.") + } +} + +func playerTurn() bool { + var pm string + var err error + for i := 0; i < 3; i++ { // retry loop + printBoard() + fmt.Printf("%c's move? ", pMark) + if pm, err = in.ReadString('\n'); err != nil { + fmt.Println(err) + return false + } + pm = strings.TrimSpace(pm) + if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { + x := pm[0] - '1' + b[x] = pMark + return true + } + } + fmt.Println("You're not playing right.") + return false +} + +var choices = make([]int, 9) + +func computerTurn() { + printBoard() + var x int + defer func() { + fmt.Println("My move:", x+1) + b[x] = cMark + }() + // look for two in a row + block := -1 + for _, l := range lines { + var mine, yours int + x = -1 + for _, sq := range l { + switch b[sq] { + case cMark: + mine++ + case pMark: + yours++ + default: + x = sq + } + } + if mine == 2 && x >= 0 { + return // strategy 1: make winning move + } + if yours == 2 && x >= 0 { + block = x + } + } + if block >= 0 { + x = block // strategy 2: make blocking move + return + } + // default strategy: random move + choices = choices[:0] + for i, sq := range b { + if sq == '1'+byte(i) { + choices = append(choices, i) + } + } + x = choices[rand.Intn(len(choices))] +} + +func gameOver() bool { + // check for win + for _, l := range lines { + if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { + printBoard() + if b[l[0]] == cMark { + fmt.Println("I win!") + cScore++ + pMark, cMark = 'X', 'O' + } else { + fmt.Println("You win!") + pScore++ + pMark, cMark = 'O', 'X' + } + return true + } + } + // check for empty squares + for i, sq := range b { + if sq == '1'+byte(i) { + return false + } + } + fmt.Println("Cat game.") + pMark, cMark = cMark, pMark + return true +} + +var lines = [][]int{ + {0, 1, 2}, // rows + {3, 4, 5}, + {6, 7, 8}, + {0, 3, 6}, // columns + {1, 4, 7}, + {2, 5, 8}, + {0, 4, 8}, // diagonals + {2, 4, 6}, +} diff --git a/Task/Tic-tac-toe/Groovy/tic-tac-toe.groovy b/Task/Tic-tac-toe/Groovy/tic-tac-toe.groovy new file mode 100644 index 0000000000..3c2c6392b4 --- /dev/null +++ b/Task/Tic-tac-toe/Groovy/tic-tac-toe.groovy @@ -0,0 +1,134 @@ +class Main { + + def input = new Scanner(System.in) + + static main(args) { + Main main = new Main(); + main.play(); + } + + public void play() { + + TicTackToe game = new TicTackToe(); + game.init() + def gameOver = false + def player = game.player1 + + println "Players take turns marking a square. Only squares \n"+ + "not already marked can be picked. Once a player has \n"+ + "marked three squares in a row, column or diagonal, they win! If all squares \n"+ + "are marked and no three squares are the same, a tied game is declared.\n"+ + "Player 1 is O and Player 2 is X \n"+ + "Have Fun! \n\n" + println "${game.drawBoard()}" + + while (!gameOver && game.plays < 9) { + + player = game.currentPlayer == 1 ? game.player1 :game.player2 + def validPick = false; + while (!validPick) { + + def square + println "Next $player, enter move by selecting square's number :" + try { + square = input.nextLine(); + } catch (Exception ex) { } + + if (square.length() == 1 && Character.isDigit(square.toCharArray()[0])) { validPick = game.placeMarker(square) } + if (!validPick) { println "Select another Square" } + + } + + (game.checkWinner(player))? gameOver = true : game.switchPlayers() + println(game.drawBoard()); + + } + println "Game Over, " + ((gameOver == true)? "$player Wins" : "Draw") + } + +} + +public class TicTackToe { + + def board = new Object[3][3] + def final player1 = "player 1" + def final player2 = "player 2" + def final marker1 = 'X' + def final marker2 = 'O' + + int currentPlayer + int plays + + public TicTacToe(){ + + } + + + def init() { + int counter = 0; + (0..2).each { row -> + (0..2).each { col -> + board[row][col] = (++counter).toString(); + } + } + plays = 0 + currentPlayer =1 + } + + def switchPlayers() { + currentPlayer = (currentPlayer == 1) ? 2:1 + plays++ + } + + def placeMarker(play) { + def result = false + (0..2).each { row -> + (0..2).each { col -> + if (board[row][col].toString()==play.toString()){ + board[row][col] = (currentPlayer == 1) ? marker2 : marker1; + result = true; + } + } + } + return result; + } + + def checkWinner(player) { + char current = (player == player1)? marker2: marker1 + //Checking + return checkRows(current) || checkColumns(current) ||checkDiagonals(current); + } + + def checkRows(char current){ + (0..2).any{ line -> + board[line].every { it == current} + } + } + + + def checkColumns(char current){ + (0..2).any{i -> + (0..2).every{j -> + board[j][i]==current } + } + } + + def checkDiagonals(char current){ + def rightDiag = [board[0][0],board[1][1],board[2][2]] + def leftDiag = [board[0][2],board[1][1],board[2][0]] + return rightDiag.every{it == current} || leftDiag.every{it == current} + } + + + def drawBoard() { + StringBuilder builder = new StringBuilder("Game board: \n"); + (0..2).each { row-> + (0..2).each {col -> + builder.append("[" + board[row][col] + "]"); + } + builder.append("\n"); + } + builder.append("\n"); + return builder.toString(); + } +} diff --git a/Task/Tic-tac-toe/Haskell/tic-tac-toe.hs b/Task/Tic-tac-toe/Haskell/tic-tac-toe.hs new file mode 100644 index 0000000000..8039963093 --- /dev/null +++ b/Task/Tic-tac-toe/Haskell/tic-tac-toe.hs @@ -0,0 +1,220 @@ +module Main where + +import System.Random +import Data.List (intercalate, find, minimumBy) +import System.Environment (getArgs) +import Data.Char (digitToInt) +import Data.Maybe (listToMaybe, mapMaybe) +import Control.Monad (guard) +import Data.Ord (comparing) + +-- check if there is a horizontal, vertical or diagonal line of +-- X or O +tictactoe :: String -> Bool +tictactoe a = tictactoeFor 'X' a /= tictactoeFor 'O' a + +-- check if there is a horizontal, vertical or diagonal line +-- for the given player "n" +tictactoeFor :: Char -> String -> Bool +tictactoeFor n [a,b,c,d,e,f,g,h,i] = + [n,n,n] `elem` [[a,b,c],[d,e,f],[g,h,i],[a,d,g], + [b,e,h],[c,f,i],[a,e,i],[c,e,g]] + +-- empty game board +start :: String +start = " " + +-- check if there is an X or an O at the given position +isPossible :: Int -> String -> Bool +isPossible n game = (game !! n) `notElem` "XO" + +-- try to place an X or an O at a given position. +-- "Right" + modified board means success, "Left" + unmodified board +-- means failure +place :: Int -> Char -> String -> Either String String +place i c game = + if isPossible i game + then Right $ take i game ++ [c] ++ drop (i + 1) game + else Left game + +-- COMPUTER AI +-- get the number of movements, starting from a given non-empty board +-- and a position for the next movement, until the specified player +-- wins or no movement is possible +-- the positions are chosen sequentially, so there's not much +-- intelligence here anyway +developGame :: Bool -> Int -> Int -> Char -> String -> (Int, Char, String) +developGame iterateMore moves i player game + | i > 8 = + -- if i arrives to the last position, iterate again from 0 + -- but do it only once + if iterateMore + then developGame False moves 0 player game + -- draw game (after one iteration, still no winning moves) + else (moves, player, game) + -- draw game (game board full) or a win for the player + | moves == 9 || tictactoeFor player game = (moves, player, game) + -- make a move, if possible, and continue playing + | otherwise = case place i otherPlayer game of + -- position i is not empty. try with the next position + Left _ -> developGame iterateMore moves (i + 1) + otherPlayer game + -- position i was empty, so it was a valid move. + -- change the player and make a new move, starting at pos 0 + Right newGame -> developGame iterateMore (moves + 1) 0 + otherPlayer newGame + where + otherPlayer = changePlayer player + +-- COMPUTER AI +-- starting from a given non-empty board, try to guess which position +-- could lead the player to the fastest victory. +bestMoveFor :: Char -> String -> Int +bestMoveFor player game = bestMove + where + -- drive the game to its end for each starting position + continuations = [ (x, developGame True 0 x player game) | + x <- [0..8] ] + -- compare the number of moves of the game and take the + -- shortest one + move (_, (m, _, _)) = m + (bestMove, _) = minimumBy (comparing move) continuations + +-- canBlock checks if the opponent has two pieces in a row and the +-- other cell in the row is empty, and places the player's piece there, +-- blocking the opponent +canBlock :: Char -> String -> Maybe Int +canBlock p [a,b,c,d,e,f,g,h,i] = + listToMaybe $ mapMaybe blockable [[a,b,c],[d,e,f],[g,h,i],[a,d,g], + [b,e,h],[c,f,i],[a,e,i],[c,e,g]] + where + blockable xs = do + guard $ length (filter (== otherPlayer) xs) == 2 + x <- find (`elem` "123456789") xs + return $ digitToInt x + otherPlayer = changePlayer p + +-- format a game board for on-screen printing +showGame :: String -> String +showGame [a,b,c,d,e,f,g,h,i] = + topBottom ++ + "| | 1 | 2 | 3 |\n" ++ + topBottom ++ + row "0" [[a],[b],[c]] ++ + row "3" [[d],[e],[f]] ++ + row "6" [[g],[h],[i]] + where + topBottom = "+----+---+---+---+\n" + row n x = "| " ++ n ++ "+ | " ++ + intercalate " | " x ++ " |\n" ++ topBottom + +-- ask the user to press a numeric key and convert it to an int +enterNumber :: IO Int +enterNumber = do + c <- getChar + if c `elem` "123456789" + then do + putStrLn "" + return $ digitToInt c + else do + putStrLn "\nPlease enter a digit!" + enterNumber + +-- a human player's turn: get the number of pieces put on the board, +-- the next piece to be put (X or O) and a game board, and return +-- a new game state, checking if the piece can be placed on the board. +-- if it can't, make the user try again. +turn :: (Int, Char, String) -> IO (Int, Char, String) +turn (count, player, game) = do + putStr $ "Please tell me where you want to put an " ++ + [player] ++ ": " + pos <- enterNumber + case place (pos - 1) player game of + Left oldGame -> do + putStrLn "That place is already taken!\n" + turn (count, player, oldGame) + Right newGame -> + return (count + 1, changePlayer player, newGame) + +-- alternate between X and O players +changePlayer :: Char -> Char +changePlayer 'O' = 'X' +changePlayer 'X' = 'O' + +-- COMPUTER AI +-- make an automatic turn, placing an X or an O game board. +-- the first movement is always random. +-- first, the computer looks for two pieces of his opponent in a row +-- and tries to block. +-- otherwise, it tries to guess the best position for the next movement. +-- as a least ressource, it places a piece randomly. +autoTurn :: Bool -> (Int, Char, String) -> IO (Int, Char, String) +autoTurn forceRandom (count, player, game) = do + -- try a random position 'cause everything else failed + -- count == 0 overrides the value of forceRandom + i <- if count == 0 || forceRandom + then randomRIO (0,8) + else return $ + case canBlock player game of + -- opponent can't be blocked. try to guess + -- the best movement + Nothing -> bestMoveFor player game + -- opponent can be blocked, so just do it! + Just blockPos -> blockPos + -- if trying to place a piece at a calculated position doesn't work, + -- just try again with a random value + case place i player game of + Left oldGame -> autoTurn True (count, player, oldGame) + Right newGame -> do + putStrLn $ "It's player " ++ [player] ++ "'s turn." + return (count + 1, changePlayer player, newGame) + +-- play a game until someone wins or the board becomes full. +-- depending on the value of the variable "auto", ask the user(s) to +-- put some pieces on the board or do it automatically +play :: Int -> (Int, Char, String) -> IO () +play auto cpg@(_, player, game) = do + newcpg@(newCount, newPlayer, newGame) <- case auto of + -- if both players are human, always ask them + 0 -> turn cpg + -- if both players are computer, always play auto + 1 -> autoTurn False cpg + -- X is computer, O is human + 2 -> if player == 'X' then autoTurn False cpg else turn cpg + -- X is human, O is computer + 3 -> if player == 'O' then autoTurn False cpg else turn cpg + putStrLn $ "\n" ++ showGame newGame + if tictactoe newGame + then putStrLn $ "Player " ++ [changePlayer newPlayer] ++ " wins!\n" + else + if newCount == 9 + then putStrLn "Draw!\n" + else play auto newcpg + +-- main program: greet the user, ask for a game type, ask for the +-- player that'll start the game, and play the game beginning with an +-- empty board +main :: IO () +main = do + a <- getArgs + if null a + then usage + else do + let option = head a + if option `elem` ["0","1","2","3"] + then do + putStrLn $ "\n" ++ showGame start + let m = read option :: Int + play m (0, 'X', start) + else usage + +usage :: IO () +usage = do + putStrLn "TIC-TAC-TOE GAME\n================\n" + putStrLn "How do you want to play?" + putStrLn "Run the program with one of the following options." + putStrLn "0 : both players are human" + putStrLn "1 : both players are computer" + putStrLn "2 : player X is computer and player O is human" + putStrLn "3 : player X is human and player O is computer" + putStrLn "Player X always begins." diff --git a/Task/Tic-tac-toe/Icon/tic-tac-toe.icon b/Task/Tic-tac-toe/Icon/tic-tac-toe.icon new file mode 100644 index 0000000000..2cf174295b --- /dev/null +++ b/Task/Tic-tac-toe/Icon/tic-tac-toe.icon @@ -0,0 +1,112 @@ +# Play TicTacToe + +$define E " " # empty square +$define X "X" # X piece +$define O "O" # O piece + +# -- define a board +record Board(a, b, c, d, e, f, g, h, i) + +procedure display_board (board, player) + write ("\n===============") + write (board.a || " | " || board.b || " | " || board.c) + write ("---------") + write (board.d || " | " || board.e || " | " || board.f) + write ("---------") + write (board.g || " | " || board.h || " | " || board.i) +end + +# return a set of valid moves (empty positions) in given board +procedure empty_fields (board) + fields := set() + every i := !fieldnames(board) do + if (board[i] == E) then insert (fields, i) + return fields +end + +procedure game_start () + return Board (E, E, E, E, E, E, E, E, E) +end + +procedure game_is_drawn (board) + return *empty_fields(board) = 0 +end + +procedure game_won_by (board, player) + return (board.a == board.b == board.c == player) | + (board.d == board.e == board.f == player) | + (board.g == board.h == board.i == player) | + (board.a == board.d == board.g == player) | + (board.b == board.e == board.h == player) | + (board.c == board.f == board.i == player) | + (board.a == board.e == board.i == player) | + (board.g == board.e == board.c == player) +end + +procedure game_over (board) + return game_is_drawn (board) | game_won_by (board, O) | game_won_by (board, X) +end + +# -- players make their move on the board +# assume there is at least one empty square + +procedure human_move (board, player) + choice := "z" + options := empty_fields (board) + # keep prompting until player selects a valid square + until member (options, choice) do { + writes ("Choose one of: ") + every writes (!options || " ") + writes ("\n> ") + choice := read () + } + board[choice] := player +end + +# pick and make a move at random from empty positions +procedure random_move (board, player) + board[?empty_fields(board)] := player +end + +# -- manage the game play +procedure play_game () + # hold procedures for players' move in variables + player_O := random_move + player_X := human_move + + # randomly determine if human or computer moves first + if (?2 = 0) + then { + write ("Human plays first as O") + player_O := human_move + player_X := random_move + } + else write ("Computer plays first, human is X") + + # set up the game to start + board := game_start () + player := O + display_board (board, player) + # loop until the game is over, getting each player to move in turn + until game_over (board) do { + write (player || " to play next") + # based on player, prompt for the next move + if (player == O) + then (player_O (board, player)) + else (player_X (board, player)) + # change player to move + player := if (player == O) then X else O + display_board (board, player) + } + # finish by writing out result + if game_won_by (board, O) + then write ("O won") + else if game_won_by (board, X) + then write ("X won") + else write ("draw") # neither player won, so must be a draw +end + +# -- get things started +procedure main () + play_game () +end diff --git a/Task/Tic-tac-toe/J/tic-tac-toe.j b/Task/Tic-tac-toe/J/tic-tac-toe.j new file mode 100644 index 0000000000..70075145bf --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe.j @@ -0,0 +1,94 @@ +Note 'ttt adjudicates or plays' + + use: markers ttt characters + + characters represent the cell names. + + markers is a length 3 character vector of the + characters to use for first and second player + followed by the opponent's mark. + 'XOX' means X plays 1st, O is the other mark, + and the first strategy plays 1st. + 'XOO' means X plays 1st, O is the other mark, + and the second strategy moves first. + + The game is set up for the computer as the + first strategy (random), and human as second. + + A standard use: + 'XOX'ttt'abcdefghijkl' + + Example game reformatted w/ emacs artist-mode + to fit your display: + + '#-#'ttt'wersdfxcv' + w│e│r w│e│r .... -│e│r . -│e│# + ─┼─┼─ . ─┼─┼─ .. ─┼─┼─ .. ─┼─┼─ + s│d│f . s│#│f .. s│#│f .. -│#│f + ─┼─┼─ .. ─┼─┼─ . ─┼─┼─ ... ─┼─┼─ + x│c│v .. -│c│v . -│c│# .. -│c│# + d .. v .. r . VICTORY + w│e│r .. w│e│r .. -│e│# . + ─┼─┼─ ... ─┼─┼─ .. ─┼─┼─ . + s│#│f ... s│#│f .. s│#│f . + ─┼─┼─ .. ─┼─┼─ ... ─┼─┼─ ... + x│c│v -│c│# -│c│# + -->cell for -? -->cell for -? -->cell for -? + x w s +) + +while=: conjunction def 'u ^: v ^:_' NB. j assumes while is a verb and needs to know while is a conjunction. + +ttt=: outcome@:((display@:move) while undecided)@:display@:prepare + +blindfolded_variant=: outcome@:display@:(move while undecided)@:display@:prepare + +outcome=: {&(>;:'kitty VICTORY')@:won NB. (outcome does not pass along the state) +move=: post locate +undecided=: won nor full +prepare=: , board@:] NB. form the state vector + +Note 'locate' + is a monadic verb. y is the state vector. + returns the character of the chosen cell. + Generally: + locate=: second_strategy`first_strategy@.(first = mark) + Simplified: + locate=: human_locate NB. human versus human +) +locate=: human_locate`computer_locate@.(first = mark) + +display=: show [: (1 1,:5 5)&(];.0)@:": [: <"0 fold + +computer_locate=: [: show@{. board -. marks NB. strategy: first available +computer_locate=: [: show@({~ ?@:#) board -. marks NB. strategy: random + +human_locate=: monad define + state=. y + m=. mark state + b=. board state + cells=. b -. marks state + show '-->cell for ' , m , '?' + whilst. cell -.@:e. cells do. cell =. {. (1!:1]1) , m end. +) + +post=: 2&A.@:(3&{.)@:[ prepare mark@:[`((i.~ board)~)`(board@:[)} + +mark=: {. NB. mark of the current player from state +marks=: 2&{. NB. extract both markers from state +board=: _9&{. NB. extract board from state +first=: 2&{ NB. extract first player from state + +show=: [ smoutput + +full=: 2 = #@:~. +won=: test@:fold +fold=: 3 3 $ board +test=: [: any [: all [: infix_pairs_agree |:@:lines + +lines=: , diagonal , diagonal@:|. , |: +diagonal=: (<0 1)&|: +all=: *./ +any=: +./ +nor=: 8 b. +infix_pairs_agree=: 2&(=/\) diff --git a/Task/Tic-tac-toe/Java/tic-tac-toe.java b/Task/Tic-tac-toe/Java/tic-tac-toe.java new file mode 100644 index 0000000000..3cc0c8d41d --- /dev/null +++ b/Task/Tic-tac-toe/Java/tic-tac-toe.java @@ -0,0 +1,152 @@ +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/Tic-tac-toe/Mathematica/tic-tac-toe.math b/Task/Tic-tac-toe/Mathematica/tic-tac-toe.math new file mode 100644 index 0000000000..b890ac4725 --- /dev/null +++ b/Task/Tic-tac-toe/Mathematica/tic-tac-toe.math @@ -0,0 +1,36 @@ +DynamicModule[{board = ConstantArray[0, {3, 3}], text = "Playing...", + first, rows = + Join[#, Transpose@#, {Diagonal@#, Diagonal@Reverse@#}] &}, + Column@{Graphics[{Thickness[.02], + Table[With[{i = i, j = j}, + Button[{White, Rectangle[{i, j} - 1, {i, j}], Black, + Dynamic[Switch[board[[i, j]], 0, Black, 1, + Circle[{i, j} - .5, .3], -1, + Line[{{{i, j} - .2, {i, j} - .8}, {{i - .2, + j - .8}, {i - .8, j - .2}}}]]]}, + Which[text != "Playing...", board = ConstantArray[0, {3, 3}]; + text = "Playing...", board[[i, j]] == 0, + If[board == ConstantArray[0, {3, 3}], + first = {i, + j} /. {{2, 2} -> 1, {1 | 3, 1 | 3} -> 2, _ -> 3}]; + board[[i, j]] = 1; + FinishDynamic[]; + Which[MemberQ[rows[board], {1, 1, 1}], text = "You win.", + FreeQ[board, 0], text = "Draw.", True, + board[[Sequence @@ + SortBy[Select[Tuples[{Range@3, Range@3}], + board[[Sequence @@ #]] == + 0 &], -Total[ + Sort /@ + rows[ReplacePart[ + board, # -> -1]] /. {{-1, -1, -1} -> + 512, {-1, 1, 1} -> 64, {-1, -1, 0} -> + 8, {0, 1, 1} -> -1, {_, _, _} -> 0}] - + Switch[#, {2, 2}, 1, {1 | 3, 1 | 3}, + If[first == 2, -1, 0], _, + If[first == 2, 0, -1]] &][[1]]]] = -1; + Which[MemberQ[rows[board], {-1, -1, -1}], + text = "You lost.", FreeQ[board, 0], + text = "Draw."]]]]], {i, 1, 3}, {j, 1, 3}], Thickness[.01], + Line[{{{1, 0}, {1, 3}}, {{2, 0}, {2, 3}}, {{0, 1}, {3, 1}}, {{0, + 2}, {3, 2}}}]}], Dynamic@text}] diff --git a/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 b/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 new file mode 100644 index 0000000000..b38a268743 --- /dev/null +++ b/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 @@ -0,0 +1,48 @@ +use v6; + +my @board = 1..9; +my @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8], + [0,4,8], [6,4,2]; + +sub get-winner() { + for @winning-positions { + return (@board[$_][0], $_) if [eq] @board[$_]; + } +} + +sub free-indexes() { + @board.keys.grep: { @board[$_] eq any(1..9) } +} + +sub ai-move() { + given free-indexes.pick { + @board[$_] = 'o'; + say "I go at: { $_ + 1 }\n"; + } +} + +sub print-board() { + say @board.map({ "$^a | $^b | $^c" }).join("\n--+---+--\n"), "\n"; +} + +sub human-move() { + my $pos = prompt "Choose one of { (free-indexes >>+>> 1).join(",") }: "; + if $pos eq any(free-indexes >>+>> 1) { + @board[$pos - 1] = 'x'; + } else { + say "Sorry, you want to put your 'x' where?"; + human-move(); + } +} + +for (&ai-move, &human-move) xx * { + print-board; + .(); + last if get-winner() or not free-indexes; +} + +if get-winner() -> ($player, $across) { + say "$player wins across [", ($across >>+>> 1).join(", "), "]."; +} else { + say "How boring, a draw!"; +} diff --git a/Task/Tic-tac-toe/PicoLisp/tic-tac-toe.l b/Task/Tic-tac-toe/PicoLisp/tic-tac-toe.l new file mode 100644 index 0000000000..c4d5158c2e --- /dev/null +++ b/Task/Tic-tac-toe/PicoLisp/tic-tac-toe.l @@ -0,0 +1,67 @@ +(load "@lib/simul.l") # for 'game' function + +(de display () + (for Y (3 2 1) + (prinl " +---+---+---+") + (prin " " Y) + (for X (1 2 3) + (prin " | " (or (get *Board X Y) " ")) ) + (prinl " |") ) + (prinl " +---+---+---+") + (prinl " a b c") ) + +(de find3 (P) + (find + '((X Y DX DY) + (do 3 + (NIL (= P (get *Board X Y))) + (inc 'X DX) + (inc 'Y DY) + T ) ) + (1 1 1 1 2 3 1 1) + (1 2 3 1 1 1 1 3) + (1 1 1 0 0 0 1 1) + (0 0 0 1 1 1 1 -1) ) ) + +(de myMove () + (when + (game NIL 8 + '((Flg) # Moves + (unless (find3 (or (not Flg) 0)) + (make + (for (X . L) *Board + (for (Y . P) L + (unless P + (link + (cons + (cons X Y (or Flg 0)) + (list X Y) ) ) ) ) ) ) ) ) + '((Mov) # Move + (set (nth *Board (car Mov) (cadr Mov)) (cddr Mov)) ) + '((Flg) # Cost + (if (find3 (or Flg 0)) -100 0) ) ) + (let Mov (caadr @) + (set (nth *Board (car Mov) (cadr Mov)) 0) ) + (display) ) ) + +(de yourMove (X Y) + (and + (sym? X) + (>= 3 (setq X (- (char X) 96)) 1) + (num? Y) + (>= 3 Y 1) + (not (get *Board X Y)) + (set (nth *Board X Y) T) + (display) ) ) + +(de main () + (setq *Board (make (do 3 (link (need 3))))) + (display) ) + +(de go Args + (cond + ((not (yourMove (car Args) (cadr Args))) + "Illegal move!" ) + ((find3 T) "Congratulation, you won!") + ((not (myMove)) "No moves") + ((find3 0) "Sorry, you lost!") ) ) diff --git a/Task/Tic-tac-toe/Prolog/tic-tac-toe-1.pro b/Task/Tic-tac-toe/Prolog/tic-tac-toe-1.pro new file mode 100644 index 0000000000..7a73fe8f91 --- /dev/null +++ b/Task/Tic-tac-toe/Prolog/tic-tac-toe-1.pro @@ -0,0 +1,208 @@ +:- use_module('min-max.pl'). + +:-dynamic box/2. +:- dynamic tic_tac_toe_window/1. + +% Computer begins. +tic-tac-toe(computer) :- + V is random(9), + TTT = [_,_,_,_,_,_ ,_,_,_], + nth0(V, TTT, o), + display_tic_tac_toe(TTT). + +% Player begins +tic-tac-toe(me) :- + TTT = [_,_,_,_,_,_ ,_,_,_], + display_tic_tac_toe(TTT). + + +display_tic_tac_toe(TTT) :- + retractall(box(_,_)), + retractall(tic_tac_toe_window(_)), + new(D, window('Tic-tac-Toe')), + send(D, size, size(170,170)), + X = 10, Y = 10, + display(D, X, Y, 0, TTT), + assert(tic_tac_toe_window(D)), + send(D, open). + +display(_, _, _, _, []). + +display(D, X, Y, N, [A,B,C|R]) :- + display_line(D, X, Y, N, [A,B,C]), + Y1 is Y+50, + N3 is N+3, + display(D, X, Y1, N3, R). + + +display_line(_, _, _, _, []). +display_line(D, X, Y, N, [C|R]) :- + ( nonvar(C)-> C1 = C; C1 = ' '), + new(B, tic_tac_toe_box(C1)), + assertz(box(N, B)), + send(D, display, B, point(X, Y)), + X1 is X + 50, + N1 is N+1, + display_line(D, X1, Y, N1, R). + + + +% class tic_tac_toe_box +% display an 'x' when the player clicks +% display an 'o' when the computer plays +:- pce_begin_class(tic_tac_toe_box, box, "Graphical window with text"). + +variable(mess, any, both, "text to display"). + +initialise(P, Lbl) :-> + send(P, send_super, initialise), + send(P, slot, mess, Lbl), + WS = 50, HS = 50, + send(P, size, size(WS,HS)), + send(P, recogniser, + handler_group(new(click_gesture(left, + '', + single, + message(@receiver, my_click))))). + +% the box is clicked +my_click(B) :-> + send(B, set_val, x), + send(@prolog, play). + +% only works when the box is "free" +set_val(B, Val) :-> + get(B, slot, mess, ' '), + send(B, slot, mess, Val), + send(B, redraw), + send(B, flush). + + +% redefined method to display custom graphical objects. +'_redraw_area'(P, A:area) :-> + send(P, send_super, '_redraw_area', A), + %we display the text + get(P, slot, mess, Lbl), + new(Str1, string(Lbl)), + get_object(P, area, area(X,Y,W,H)), + send(P, draw_box, X, Y, W, H), + send(P, draw_text, Str1, + font(times, normal, 30), + X, Y, W, H, center, center). + +:- pce_end_class. + +play :- + numlist(0, 8, L), + maplist(init, L, TTT), + finished(x, TTT, Val), + ( Val = 2 -> send(@display, inform,'You win !'), + tic_tac_toe_window(D), + send(D, destroy) + ; ( Val = 1 -> send(@display, inform,'Draw !'), + tic_tac_toe_window(D), + send(D, destroy) + ; next_move(TTT, TT1), + maplist(display, L, TT1), + finished(o, TT1, V), + ( V = 2 -> send(@display, inform,'I win !'), + tic_tac_toe_window(D), + send(D, destroy) + ; ( V = 1 -> send(@display, inform,'Draw !'), + tic_tac_toe_window(D), + send(D, destroy) + ; true)))). + + +% use minmax to compute the next move +next_move(TTT, TT1) :- + minimax(o, 0, 1024, TTT, _V1- TT1). + + +% we display the new board +display(I, V) :- + nonvar(V), + box(I, V1), + send(V1, set_val, V). + +display(_I, _V). + +% we create the board for minmax +init(I, V) :- + box(I, V1), + get(V1, slot, mess, V), + V \= ' '. + +init(_I, _V). + +% winning position for the player P ? +winned(P, [A1, A2, A3, A4, A5, A6, A7, A8, A9]) :- + (is_winning_line(P, [A1, A2, A3]); + is_winning_line(P, [A4, A5, A6]); + is_winning_line(P, [A7, A8, A9]); + is_winning_line(P, [A1, A4, A7]); + is_winning_line(P, [A2 ,A5, A8]); + is_winning_line(P, [A3, A6, A9]); + is_winning_line(P, [A1, A5, A9]); + is_winning_line(P, [A3, A5, A7])). + + +is_winning_line(P, [A, B, C]) :- + nonvar(A), A = P, + nonvar(B), B = P, + nonvar(C), C = P. + +% Winning position for the player +eval(Player, Deep, TTT, V) :- + winned(Player, TTT), + ( Player = o -> V is 1000 - 50 * Deep; V is -1000+ 50 * Deep). + +% Loosing position for the player +eval(Player, Deep, TTT, V) :- + select(Player, [o,x], [Player1]), + winned(Player1, TTT), + ( Player = x -> V is 1000 - 50 * Deep; V is -1000+ 50 * Deep). + +% Draw position +eval(_Player, _Deep, TTT, 0) :- + include(var, TTT, []). + + +% we fetch the free positions of the board +possible_move(TTT, LMove) :- + new(C, chain), + forall(between(0,8, I), + ( nth0(I, TTT, X), + ( var(X) -> send(C, append, I); true))), + chain_list(C, LMove). + +% we create the new position when the player P clicks +% the box "N" +assign_move(P, TTT, N, TT1) :- + copy_term(TTT, TT1), + nth0(N, TT1, P). + +% We fetch all the possible boards obtained from board TTT +% for the player P +get_next(Player, Deep, TTT, Player1, Deep1, L):- + possible_move(TTT, LMove), + select(Player, [o,x], [Player1]), + Deep1 is Deep + 1, + maplist(assign_move(Player, TTT), LMove, L). + + +% The game is over ? +% Player P wins +finished(P, TTT, 2) :- + winned(P, TTT). + +% Draw +finished(_P, TTT, 1) :- + include(var, TTT, []). + +% the game is not over +finished(_P, _TTT, 0) . + +% minmax must knows when the computer plays +% (o for ordinateur in French) +computer(o). diff --git a/Task/Tic-tac-toe/Prolog/tic-tac-toe-2.pro b/Task/Tic-tac-toe/Prolog/tic-tac-toe-2.pro new file mode 100644 index 0000000000..fb3cc81d20 --- /dev/null +++ b/Task/Tic-tac-toe/Prolog/tic-tac-toe-2.pro @@ -0,0 +1,26 @@ +:- module('min-max.pl', [minimax/5]). + +% minimax(Player, Deep, MaxDeep, B, V-B) +% @arg1 : current player at this level +% @arg2 : current level of recursion +% @arg3 : max level of recursion (in this version of the game no use : set to 1024 !) +% @arg4 : current board +% @arg5 : B is the evaluation of the board, the result is V-B to know the new board + +% Here we get an evaluation +minimax(Player, Deep, MaxDeep, B, V-B) :- + ( eval(Player, Deep, B, V) -> true + ; % in this version of the game this second division always fails + ( Deep > MaxDeep -> V is random(1000) - 1000)). + +% here we must compute all the possible moves to know the evaluation of the board +minimax(Player, Deep, MaxDeep, B, V) :- + get_next(Player, Deep, B, Player1, Deep1, L), + maplist(minimax(Player1, Deep1, MaxDeep), L, LV), + maplist(lie, L, LV, TLV), + sort(TLV, SLVTmp), + ( computer(Player) -> reverse(SLVTmp, SLV); SLV = SLVTmp), + SLV = [V | _R]. + + +lie(TTT, V-_, V-TTT). diff --git a/Task/Tic-tac-toe/Python/tic-tac-toe-1.py b/Task/Tic-tac-toe/Python/tic-tac-toe-1.py new file mode 100644 index 0000000000..c3e9993ea8 --- /dev/null +++ b/Task/Tic-tac-toe/Python/tic-tac-toe-1.py @@ -0,0 +1,74 @@ +''' + Tic-tac-toe game player. + Input the index of where you wish to place your mark at your turn. +''' + +import random + +board = list('123456789') +wins = ((0,1,2), (3,4,5), (6,7,8), + (0,3,6), (1,4,7), (2,5,8), + (0,4,8), (2,4,6)) + +def printboard(): + print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6))) + +def score(): + for w in wins: + b = board[w[0]] + if b in 'XO' and all (board[i] == b for i in w): + return b, [i+1 for i in w] + return None, None + +def finished(): + return all (b in 'XO' for b in board) + +def space(): + return [ b for b in board if b not in 'XO'] + +def my_turn(xo): + options = space() + choice = random.choice(options) + board[int(choice)-1] = xo + return choice + +def your_turn(xo): + options = space() + while True: + choice = input(" Put your %s in any of these positions: %s " + % (xo, ''.join(options))).strip() + if choice in options: + break + print( "Whoops I don't understand the input" ) + board[int(choice)-1] = xo + return choice + +def me(xo='X'): + printboard() + print('I go at', my_turn(xo)) + return score() + assert not s[0], "\n%s wins across %s" % s + +def you(xo='O'): + printboard() + # Call my_turn(xo) below for it to play itself + print('You went at', your_turn(xo)) + return score() + assert not s[0], "\n%s wins across %s" % s + + +print(__doc__) +while not finished(): + s = me('X') + if s[0]: + printboard() + print("\n%s wins across %s" % s) + break + if not finished(): + s = you('O') + if s[0]: + printboard() + print("\n%s wins across %s" % s) + break +else: + print('\nA draw') diff --git a/Task/Tic-tac-toe/Python/tic-tac-toe-2.py b/Task/Tic-tac-toe/Python/tic-tac-toe-2.py new file mode 100644 index 0000000000..d3f2eaf16d --- /dev/null +++ b/Task/Tic-tac-toe/Python/tic-tac-toe-2.py @@ -0,0 +1,91 @@ +''' + Tic-tac-toe game player. + Input the index of where you wish to place your mark at your turn. +''' + +import random + +board = list('123456789') +wins = ((0,1,2), (3,4,5), (6,7,8), + (0,3,6), (1,4,7), (2,5,8), + (0,4,8), (2,4,6)) + +def printboard(): + print('\n-+-+-\n'.join('|'.join(board[x:x+3]) for x in(0,3,6))) + +def score(board=board): + for w in wins: + b = board[w[0]] + if b in 'XO' and all (board[i] == b for i in w): + return b, [i+1 for i in w] + return None + +def finished(): + return all (b in 'XO' for b in board) + +def space(board=board): + return [ b for b in board if b not in 'XO'] + +def my_turn(xo, board): + options = space() + choice = random.choice(options) + board[int(choice)-1] = xo + return choice + +def my_better_turn(xo, board): + 'Will return a next winning move or block your winning move if possible' + ox = 'O' if xo =='X' else 'X' + oneblock = None + options = [int(s)-1 for s in space(board)] + for choice in options: + brd = board[:] + brd[choice] = xo + if score(brd): + break + if oneblock is None: + brd[choice] = ox + if score(brd): + oneblock = choice + else: + choice = oneblock if oneblock is not None else random.choice(options) + board[choice] = xo + return choice+1 + +def your_turn(xo, board): + options = space() + while True: + choice = input("\nPut your %s in any of these positions: %s " + % (xo, ''.join(options))).strip() + if choice in options: + break + print( "Whoops I don't understand the input" ) + board[int(choice)-1] = xo + return choice + +def me(xo='X'): + printboard() + print('\nI go at', my_better_turn(xo, board)) + return score() + +def you(xo='O'): + printboard() + # Call my_turn(xo, board) below for it to play itself + print('\nYou went at', your_turn(xo, board)) + return score() + + +print(__doc__) +while not finished(): + s = me('X') + if s: + printboard() + print("\n%s wins along %s" % s) + break + if not finished(): + s = you('O') + if s: + printboard() + print("\n%s wins along %s" % s) + break +else: + print('\nA draw') diff --git a/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx new file mode 100644 index 0000000000..62481848d0 --- /dev/null +++ b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx @@ -0,0 +1,105 @@ +/*REXX program plays (with a human) the tic-tac-toe game on an NxN grid.*/ +oops =$ '***error!*** '; cell# ='cell number' /*a couple of literals*/ +$=copies('─',9) /*eyecatcher literal for messages*/ +sing='│─┼'; jam='║'; bar='═'; junc='╬'; dbl=jam || bar || junc +sw=80-1 /*LINESIZE() bif would be better.*/ +parse arg N hm cm .,@.; if N=='' then N=3; oN=N /*specifying some args?*/ +N=abs(N); NN=N*N; middle=NN%2+N%2 /*if N < 0, computer goes first.*/ +if N<2 then do; say oops 'tic-tac-toe grid is too small: ' N; exit; end +pad=copies(left('',sw%NN),1+(N<5)) /*display padding: 6x6 in 80 cols*/ +if hm=='' then hm='X'; if cm=='' then cm='O' /*markers: Human, Computer*/ +hm=aChar(hm,'human'); cm=aChar(cm,'computer') /*process the markers.*/ +if hm==cm then cm='X' /*Human wants the "O"? Sheesh! */ +if oN<0 then call Hmove middle /*comp moves 1st? Choose middling*/ + else call showGrid /*···also checks for wins & draws*/ + do forever /*'til the cows come home, by gum*/ + call CBLF /*do carbon-based lifeform's move*/ + call Hal /*figure Hal the computer's move.*/ + end /*forever····showGrid does wins & draws*/ +/*──────────────────────────────────ACHAR subroutine────────────────────*/ +aChar: parse arg x; L=length(x) /*process markers.*/ +if L==1 then return x /*1 char, as is. */ +if L==2 & datatype(x,'X') then return x2c(x) /*2 chars, hex. */ +if L==3 & datatype(x,'W') then return d2c(x) /*3 chars, decimal*/ +say oops 'illegal character or character code for' arg(2) "marker: " x +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CBLF subroutine─────────────────────*/ +CBLF: prompt='Please enter a' cell# "to place your next marker ["hm'] (or Quit):' + do forever; say $ prompt; parse pull x 1 ux 1 ox; upper ux + if datatype(ox,'W') then ox=ox/1 /*maybe normalize cell#: +0007. */ + select + when abbrev('QUIT',ux,1) then call tell 'quitting.' + when x='' then iterate /*Nada? Try again.*/ + when words(x)\==1 then say oops "too many" cell# 'specified:' x + when \datatype(x,'N') then say oops cell# "isn't numeric: " x + when \datatype(x,'W') then say oops cell# "isn't an integer: " x + when x=0 then say oops cell# "can't be zero: " x + when x<0 then say oops cell# "can't be negative: " x + when x>NN then say oops cell# "can't exceed " NN + when @.ox\=='' then say oops cell# "is already occupied: " x + otherwise leave /*do forever*/ + end /*select*/ + end /*forever*/ +@.ox=hm /*place a marker for the human.*/ +call showGrid /*and show the tic-tac-toe grid.*/ +return +/*──────────────────────────────────Hal subroutine──────────────────────*/ +Hal: select /*Hal will try various moves. */ + when win(cm,N-1) then call Hmove ,ec /* winning move? */ + when win(hm,N-1) then call Hmove ,ec /* blocking move? */ + when @.middle=='' then call Hmove middle /* center move. */ + when @.N.N=='' then call Hmove ,N N /*bR corner move. */ + when @.N.1=='' then call Hmove ,N 1 /*bL corner move. */ + when @.1.N=='' then call Hmove ,1 N /*tR corner move. */ + when @.1.1=='' then call Hmove ,1 1 /*tL corner move. */ + otherwise call Hmove ,ac /*some blank cell.*/ + end /*select*/ +return +/*──────────────────────────────────HMOVE subroutine────────────────────*/ +Hmove: parse arg Hplace,dr dc; if Hplace=='' then Hplace = (dr-1)*N + dc +@.Hplace=cm /*put marker for Hal the computer*/ +say; say $ 'computer places a marker ['cm"] at cell number " Hplace +call showGrid +return +/*──────────────────────────────────SHOWGRID subroutine─────────────────*/ +showGrid: _=0; open=0; cW=5; cH=3 /*cell width, cell height.*/ +do r=1 for N; do c=1 for N; _=_+1; @.r.c=@._; open=open|@._==''; end; end +say; z=0 /* [↑] create grid coörds.*/ + do j=1 for N /* [↓] show grids&markers.*/ + do t=1 for cH; _=; __= /*mk is a marker in a cell*/ + do k=1 for N; if t==2 then z=z+1; mk=; c#= + if t==2 then do; mk=@.z; c#=z; end /*c# is cell#*/ + _= _||jam||center(mk,cW); __= __||jam||center(c#,cW) + end /*k*/ + say pad substr(_,2) pad translate(substr(__,2), sing,dbl) + end /*t*/ + if j==N then leave; _= + do b=1 for N; _=_||junc||copies(bar,cW); end /*b*/ + say pad substr(_,2) pad translate(substr(_,2),sing,dbl) + end /*j*/ +say +if win(hm) then call tell 'You ('hm") won!" +if win(cm) then call tell 'The computer ('cm") won." +if \open then call tell 'This tic-tac-toe is a draw.' +return +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: do 4; say; end; say center(' 'arg(1)" ",sw,'─'); do 5; say; end +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────WIN subroutine──────────────────────*/ +win: parse arg wm,w; if w=='' then w=N /*see if there are W # of markers*/ +ac=; do r=1 for N; _=0; ec= /*see if any rows are a winner.*/ + do c=1 for N; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c; end + if ec\=='' then @c=ec; if _==N | (_>=w & ec\=='') then return 1 + end /*r*/ /*if w=N-1, checking for near win*/ + do c=1 for N; _=0; ec= /*see if any cols are a winner.*/ + do r=1 for N; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c; end + if ec\=='' then @c=ec; if _==N | (_>=w & ec\=='') then return 1 + end /*r*/ /*EC is a r,c version of cell #*/ +_=0; ec= /*see if winning descending diag.*/ + do d=1 for N; _=_+ (@.d.d==wm); if @.d.d=='' then ec=d d; end +if _==N | (_>=w & ec\=='') then return 1 +_=0; ec=; r=0 /*see if winning ascending diag.*/ + do c=N for N by -1; r=r+1; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c + end /*r*/ +if _==N | (_>=w & ec\=='') then return 1 +return 0 diff --git a/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb b/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb new file mode 100644 index 0000000000..cf0c48c982 --- /dev/null +++ b/Task/Tic-tac-toe/Ruby/tic-tac-toe.rb @@ -0,0 +1,143 @@ +module TicTacToe + + class Game + def initialize(player1Class, player2Class) + @board = Array.new(10) + @free_positions = (1..9).to_a + @players = [player1Class.new(self), player2Class.new(self)] + @turn = rand(2) + puts "#{@players[@turn]} goes first." + @players[@turn].marker = "X" + @players[nextTurn].marker = "O" + @winning_rows = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] + end + attr_reader :free_positions, :winning_rows, :board + + def play + loop do + player = @players[@turn] + idx = player.select + puts "#{player} selects #{player.marker} position #{idx}" + @board[idx] = player.marker + @free_positions.delete(idx) + + # check for a winner + @winning_rows.each do |row| + if row.all? {|idx| @board[idx] == player.marker} + puts "#{player} wins!" + print + return + end + end + + # no winner, is board full? + if @free_positions.empty? + puts "It's a draw." + print + return + end + + nextTurn! + end + end + + def nextTurn + (@turn + 1) % 2 + end + + def nextTurn! + @turn = nextTurn + end + + def opponent + @players[nextTurn] + end + + def print + puts [1,2,3].map {|i| @board[i].nil? ? i : @board[i]}.join("|") + puts "-+-+-" + puts [4,5,6].map {|i| @board[i].nil? ? i : @board[i]}.join("|") + puts "-+-+-" + puts [7,8,9].map {|i| @board[i].nil? ? i : @board[i]}.join("|") + end + end + + class Player + def initialize(game) + @game = game + @marker = nil + end + attr_accessor :marker + end + + class HumanPlayer < Player + def initialize(game) + super(game) + end + + def select + @game.print + loop do + print "Select your #{marker} position: " + selection = $stdin.gets.to_i + if not @game.free_positions.include?(selection) + puts "Position #{selection} is not available. Try again." + next + end + return selection + end + end + + def to_s + "Human" + end + end + + class ComputerPlayer < Player + def initialize(game) + super(game) + end + + def group_row(row, opponent) + markers = {self.marker => [], opponent.marker => [], nil => []} . + merge(row.group_by {|idx| @game.board[idx]}) + #p [row, markers].inspect + markers + end + + def select + index = nil + opponent = @game.opponent + + # look for winning rows + @game.winning_rows.each do |row| + markers = group_row(row, opponent) + if markers[self.marker].length == 2 and markers[nil].length == 1 + return markers[nil].first + end + end + + # look for opponent's winning rows to block + @game.winning_rows.each do |row| + markers = group_row(row, opponent) + if markers[opponent.marker].length == 2 and markers[nil].length == 1 + return markers[nil].first + end + end + + # need some logic here to get the computer to pick a smarter position + + # simply pick a position in order of preference + [5].concat([1,3,7,9].shuffle).concat([2,4,6,8].shuffle).each do |pos| + return pos if @game.free_positions.include?(pos) + end + end + + def to_s + "Computer" + end + end +end + +TicTacToe::Game.new(TicTacToe::ComputerPlayer, TicTacToe::ComputerPlayer).play +TicTacToe::Game.new(TicTacToe::HumanPlayer, TicTacToe::ComputerPlayer).play diff --git a/Task/Tic-tac-toe/Run-BASIC/tic-tac-toe.run b/Task/Tic-tac-toe/Run-BASIC/tic-tac-toe.run new file mode 100644 index 0000000000..36c12ff445 --- /dev/null +++ b/Task/Tic-tac-toe/Run-BASIC/tic-tac-toe.run @@ -0,0 +1,102 @@ +' --------------------------- +' TIC TAC TOE +' --------------------------- +winBox$ = "123 456 789 159 147 258 369 357" +boxPos$ = "123 231 456 564 789 897 159 591 357 753 132 465 798 174 285 396 159 471 582 693 147 258 369 195 375" +ai$ = "519628374" +ox$ = "OX" +[newGame] +for i = 1 to 9 + box$(i) = "" +next i +goto [shoTic] + +[loop] +for j = 1 to 2 + tic$ = mid$(ox$,j,1) + for i = 1 to 25 + b$ = word$(boxPos$,i," ") + b1 = val(mid$(b$,1,1)) + b2 = val(mid$(b$,2,1)) + b3 = val(mid$(b$,3,1)) + if box$(b1) = tic$ AND box$(b2) = tic$ AND box$(b3) = "" then + box$(b3) = "O" + goto [shoTic] + end if + next i +next j +if box$(1) = "O" AND box$(5) = "X" and box$(9) = "X" then + if box$(3) = "" then + box$(3) = "O" + goto [shoTic] + end if + if box$(7) = "" then + box$(7) = "O" + goto [shoTic] + end if +end if +for i = 1 to 9 + b1 = val(mid$(ai$,i,1)) + if box$(b1) = "" then + box$(b1) = "O" + exit for + end if +next i + +[shoTic] +cls +' ---------------------------------------- +' show tic tac toe screen +' ---------------------------------------- +html "" +for i = 1 to 9 + html "" +next i +html "

" + if box$(i) <> "" then + html box$(i) + else + button #box, " ";box$(i);" ", [doTic] + #box setkey(str$(i)) + end if + if i mod 3 = 0 then html "

" +gosub [checkWin] +wait + +[doTic] +box$(val(EventKey$)) = "X" +turn = 1 +gosub [checkWin] +goto [loop] + +' --- check for a winner ---------- +[checkWin] +for i = 1 to 8 + b$ = word$(winBox$,i," ") + b1 = val(mid$(b$,1,1)) + b2 = val(mid$(b$,2,1)) + b3 = val(mid$(b$,3,1)) + if box$(b1) = "O" and box$(b2) = "O" and box$(b3) = "O" then + print "You Loose!" + goto [playAgain] + end if + if box$(b1) = "X" and box$(b2) = "X" and box$(b3) = "X" then + print "You Win!" + goto [playAgain] + end if +next i + +moveCount = 0 +for i = 1 to 9 + if box$(i) <> "" then moveCount = moveCount + 1 +next i +if moveCount = 9 then + print "Draw!" + goto [playAgain] +end if +RETURN + +[playAgain] +input "Play again (y/n)";p$ +if upper$(p$) = "Y" then goto [newGame] +end diff --git a/Task/Tic-tac-toe/Scala/tic-tac-toe.scala b/Task/Tic-tac-toe/Scala/tic-tac-toe.scala new file mode 100644 index 0000000000..a05aea7754 --- /dev/null +++ b/Task/Tic-tac-toe/Scala/tic-tac-toe.scala @@ -0,0 +1,82 @@ +package object tictactoe { + val Human = 'X' + val Computer = 'O' + val BaseBoard = ('1' to '9').toList + val WinnerLines = List((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)) + val randomGen = new util.Random(System.currentTimeMillis) +} + +package tictactoe { + +class Board(aBoard : List[Char] = BaseBoard) { + + def availableMoves = aBoard.filter(c => c != Human && c != Computer) + + def availableMovesIdxs = for ((c,i) <- aBoard.zipWithIndex if c != Human && c != Computer) yield i + + def computerPlays = new Board(aBoard.updated(availableMovesIdxs(randomGen.nextInt(availableMovesIdxs.length)), Computer)) + + def humanPlays(move : Char) = new Board(aBoard.updated(aBoard.indexOf(move), Human)) + + def isDraw = aBoard.forall(c => c == Human || c == Computer) + + def isWinner(winner : Char) = + WinnerLines.exists{case (i,j,k) => aBoard(i) == winner && aBoard(j) == winner && aBoard(k) == winner} + + def isOver = isWinner(Computer) || isWinner(Human) || isDraw + + def print { + aBoard.grouped(3).foreach(row => println(row(0) + " " + row(1) + " " + row(2))) + } + + def printOverMessage { + if (isWinner(Human)) println("You win.") + else if (isWinner(Computer)) println("Computer wins.") + else if (isDraw) println("It's a draw.") + else println("Not over yet, or something went wrong.") + } + +} + + +object TicTacToe extends Application { + + def play(board : Board, turn : Char) { + + // Reads a char from input until it is one of + // the available moves in the current board + def readValidMove() : Char = { + print("Choose a move: ") + val validMoves = board.availableMoves + val move = readChar + if (validMoves.contains(move)) { + move + } else { + println("Invalid move. Choose another one in " + validMoves) + readValidMove() + } + } + + + board.print + + if (board.isOver) { + board.printOverMessage + return + } + + if (turn == Human) { // Human plays + val nextBoard = board.humanPlays(readValidMove) + play(nextBoard, Computer) + } else { // Computer plays + println("Computer plays: ") + val nextBoard = board.computerPlays + play(nextBoard, Human) + } + } + + play(new Board(),Human) + +} + +} diff --git a/Task/Tic-tac-toe/Tcl/tic-tac-toe.tcl b/Task/Tic-tac-toe/Tcl/tic-tac-toe.tcl new file mode 100644 index 0000000000..9db34ff375 --- /dev/null +++ b/Task/Tic-tac-toe/Tcl/tic-tac-toe.tcl @@ -0,0 +1,121 @@ +package require Tcl 8.6 + +# This code splits the players from the core game engine +oo::class create TicTacToe { + variable board player letter who + constructor {player1class player2class} { + set board {1 2 3 4 5 6 7 8 9} + set player(0) [$player1class new [self] [set letter(0) "X"]] + set player(1) [$player2class new [self] [set letter(1) "O"]] + set who 0 + } + + method PrintBoard {} { + lassign $board a1 b1 c1 a2 b2 c2 a3 b3 c3 + puts [format " %s | %s | %s" $a1 $b1 $c1] + puts "---+---+---" + puts [format " %s | %s | %s" $a2 $b2 $c2] + puts "---+---+---" + puts [format " %s | %s | %s" $a3 $b3 $c3] + } + + method WinForSomeone {} { + foreach w { + {0 1 2} {3 4 5} {6 7 8} {0 3 6} {1 4 7} {2 5 8} {0 4 8} {2 4 6} + } { + set b [lindex $board [lindex $w 0]] + if {$b ni "X O"} continue + foreach i $w {if {[lindex $board $i] ne $b} break} + if {[lindex $board $i] eq $b} { + foreach p $w {lappend w1 [expr {$p+1}]} + return [list $b $w1] + } + } + return "" + } + + method status {} { + return $board + } + + method IsDraw {} { + foreach b $board {if {[string is digit $b]} {return false}} + return true + } + + method legalMoves {} { + foreach b $board {if {[string is digit $b]} {lappend legal $b}} + return $legal + } + + method DoATurn {} { + set legal [my legalMoves] + my PrintBoard + while 1 { + set move [$player($who) turn] + if {$move in $legal} break + puts "Illegal move!" + } + lset board [expr {$move - 1}] $letter($who) + $player($who) describeMove $move + set who [expr {1 - $who}] + return [my WinForSomeone] + } + + method game {} { + puts " Tic-tac-toe game player. + Input the index of where you wish to place your mark at your turn.\n" + while {![my IsDraw]} { + set winner [my DoATurn] + if {$winner eq ""} continue + lassign $winner winLetter winSites + my PrintBoard + puts "\n$winLetter wins across \[[join $winSites {, }]\]" + return $winLetter + } + puts "\nA draw" + } +} + +# Stupid robotic player +oo::class create RandomRoboPlayer { + variable g + constructor {game letter} { + set g $game + } + method turn {} { + set legal [$g legalMoves] + return [lindex $legal [expr {int(rand()*[llength $legal])}]] + } + method describeMove {move} { + puts "I go at $move" + } +} + +# Interactive human player delegate +oo::class create HumanPlayer { + variable g char + constructor {game letter} { + set g $game + set char $letter + } + method turn {} { + set legal [$g legalMoves] + puts ">>> Put your $char in any of these positions: [join $legal {}]" + while 1 { + puts -nonewline ">>> " + flush stdout + gets stdin number + if {$number in $legal} break + puts ">>> Whoops I don't understand the input!" + } + return $number + } + method describeMove {move} { + puts "You went at $move" + } +} + +# Assemble the pieces +set ttt [TicTacToe new HumanPlayer RandomRoboPlayer] +$ttt game diff --git a/Task/Tic-tac-toe/XPL0/tic-tac-toe.xpl0 b/Task/Tic-tac-toe/XPL0/tic-tac-toe.xpl0 new file mode 100644 index 0000000000..572e0053cc --- /dev/null +++ b/Task/Tic-tac-toe/XPL0/tic-tac-toe.xpl0 @@ -0,0 +1,145 @@ +\The computer marks its moves with an "O" and the player uses an "X". The +\ numeric keypad is used to make the player's move. +\ +\ 7 | 8 | 9 +\ ---+---+--- +\ 4 | 5 | 6 +\ ---+---+--- +\ 1 | 2 | 3 +\ +\The player always goes first, but the 0 key is used to skip a move. Thus +\ it can be used to let the computer play first. Esc terminates program. + +inc c:\cxpl\codes; \intrinsic routine declarations +def X0=16, Y0=10; \coordinates of character in upper-left square +int I0, + PMove, \player's move (^0..^9) + Key; \keystroke +int X, O; \bit arrays for player and computer + \ bit 0 corresponds to playing square 1, etc. + + +proc HLine(X, Y); \Draw a horizontal line +int X, Y; +int I; +[Cursor(X, Y); +for I:= 0 to 10 do ChOut(0, ^Ä); +]; \HLine + + +proc VLine(X, Y); \Draw a vertical line over the above horizontal line +int X, Y; +int I; +[for I:= 0 to 4 do + [Cursor(X, Y+I); + ChOut(0, if I&1 then ^Å else ^³); + ]; +]; \VLine + + +func Won(p); \Return 'true' if player P has won +int P; +int T, I; +[T:= [$007, $038, $1C0, $049, $092, $124, $111, $054]; +for I:= 0 to 7 do \check if player matches a bit pattern for 3 in a row + if (P & T(I)) = T(I) then return true; +return false; +]; \Won + + +func Cats; \Return 'true' if no more moves available (Cat's game) +[if (X ! O) = $1FF then \all bit positions played + [Cursor(17, 20); + Text(0, "A draw!"); + return true; + ]; +return false; +]; \Cats + + +proc DoMove(P, M, Ch); \Make move in player's bit array and display it +int P, \address of player's bit array + M, \index 0..8 where bit is placed + Ch; +int I, X, Y; +[P(0):= P(0) ! 1< V0 then \save best value + [V0:= V; I0:= I]; + P(0):= P(0) & ~(1<=^1 & PMove<=^9 & \check for legal move + ((X!O) & 1<<(PMove-^1)) = 0 then quit; + ChOut(0, 7\Bel\); \beep the dude + ]; + if PMove # ^0 then + [DoMove(addr X, PMove-^1, ^X); + if Won(X) then + [Cursor(17, 20); + Text(0, "X wins!"); + quit; + ]; + ]; + if Cats then quit; + + I0:= Try(addr O) >>8; \GET COMPUTER'S MOVE (O) + DoMove(addr O, I0, ^O); \do best move + if Won(O) then + [Cursor(17, 20); + Text(0, "O wins!"); + quit; + ]; + if Cats then quit; + ]; +]; \PlayGame + + +int CpuReg; +[SetVid(1); \set 40x25 text mode +CpuReg:= GetReg; \turn off annoying flashing cursor +CpuReg(0):= $0100; \ with BIOS interrupt 10h, function 01h +CpuReg(2):= $2000; \set cursor type to disappear +SoftInt($10); +loop [PlayGame; + Key:= ChIn(1); \keep playing games until Esc key is hit + if Key = $1B\Esc\ then + [SetVid(3); exit]; \clear screen & restore normal text mode + ]; +] diff --git a/Task/Time-a-function/0DESCRIPTION b/Task/Time-a-function/0DESCRIPTION new file mode 100644 index 0000000000..6873b99e15 --- /dev/null +++ b/Task/Time-a-function/0DESCRIPTION @@ -0,0 +1,5 @@ +Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. + +Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in [[system time]] between start and finish, which could include time used by other processes on the computer. + +This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]]. diff --git a/Task/Time-a-function/1META.yaml b/Task/Time-a-function/1META.yaml new file mode 100644 index 0000000000..f6d82c59ad --- /dev/null +++ b/Task/Time-a-function/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming environment operations diff --git a/Task/Time-a-function/ACL2/time-a-function.acl2 b/Task/Time-a-function/ACL2/time-a-function.acl2 new file mode 100644 index 0000000000..11553366de --- /dev/null +++ b/Task/Time-a-function/ACL2/time-a-function.acl2 @@ -0,0 +1 @@ +(time$ (nthcdr 9999999 (take 10000000 nil))) diff --git a/Task/Time-a-function/Ada/time-a-function.ada b/Task/Time-a-function/Ada/time-a-function.ada new file mode 100644 index 0000000000..bd6d1e3dce --- /dev/null +++ b/Task/Time-a-function/Ada/time-a-function.ada @@ -0,0 +1,31 @@ +with Ada.Calendar; use Ada.Calendar; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Query_Performance is + type Proc_Access is access procedure(X : in out Integer); + function Time_It(Action : Proc_Access; Arg : Integer) return Duration is + Start_Time : Time := Clock; + Finis_Time : Time; + Func_Arg : Integer := Arg; + begin + Action(Func_Arg); + Finis_Time := Clock; + return Finis_Time - Start_Time; + end Time_It; + procedure Identity(X : in out Integer) is + begin + X := X; + end Identity; + procedure Sum (Num : in out Integer) is + begin + for I in 1..1000 loop + Num := Num + I; + end loop; + end Sum; + Id_Access : Proc_Access := Identity'access; + Sum_Access : Proc_Access := Sum'access; + +begin + Put_Line("Identity(4) takes" & Duration'Image(Time_It(Id_Access, 4)) & " seconds."); + Put_Line("Sum(4) takes:" & Duration'Image(Time_It(Sum_Access, 4)) & " seconds."); +end Query_Performance; diff --git a/Task/Time-a-function/Aime/time-a-function.aime b/Task/Time-a-function/Aime/time-a-function.aime new file mode 100644 index 0000000000..a46694a14b --- /dev/null +++ b/Task/Time-a-function/Aime/time-a-function.aime @@ -0,0 +1,50 @@ +integer +identity(integer x) +{ + return x; +} + + +integer +sum(integer c) +{ + integer s; + + s = 0; + while (c) { + s += c; + c -= 1; + } + + return s; +} + + +real +time_f(integer (*fp) (integer), integer fa) +{ + date f, s; + time t; + + d_now(s); + + fp(fa); + + d_now(f); + + t_ddiff(t, f, s); + + return t_microsecond(t) / 1000000r; +} + + +integer +main(void) +{ + o_real(6, time_f(identity, 1)); + o_text(" seconds\n"); + o_real(6, time_f(sum, 1000000)); + o_text(" seconds\n"); + + return 0; +} diff --git a/Task/Time-a-function/AutoHotkey/time-a-function-1.ahk b/Task/Time-a-function/AutoHotkey/time-a-function-1.ahk new file mode 100644 index 0000000000..aa80650fc1 --- /dev/null +++ b/Task/Time-a-function/AutoHotkey/time-a-function-1.ahk @@ -0,0 +1,15 @@ +MsgBox % time("fx") +Return + +fx() +{ + Sleep, 1000 +} + +time(function, parameter=0) +{ + SetBatchLines -1 ; don't sleep for other green threads + StartTime := A_TickCount + %function%(parameter) + Return ElapsedTime := A_TickCount - StartTime . " milliseconds" +} diff --git a/Task/Time-a-function/AutoHotkey/time-a-function-2.ahk b/Task/Time-a-function/AutoHotkey/time-a-function-2.ahk new file mode 100644 index 0000000000..df60d5d15f --- /dev/null +++ b/Task/Time-a-function/AutoHotkey/time-a-function-2.ahk @@ -0,0 +1,14 @@ +MsgBox % time("fx") + +time(function, parameter=0){ + SetBatchLines -1 + DllCall("QueryPerformanceCounter", "Int64*", CounterBefore) + DllCall("QueryPerformanceFrequency", "Int64*", Freq) + %function%(parameter) + DllCall("QueryPerformanceCounter", "Int64*", CounterAfter) + return (CounterAfter-CounterBefore)/Freq * 1000 " milliseconds" +} + +fx(){ + Sleep 1000 +} diff --git a/Task/Time-a-function/BASIC/time-a-function.basic b/Task/Time-a-function/BASIC/time-a-function.basic new file mode 100644 index 0000000000..ad2c0b5ff6 --- /dev/null +++ b/Task/Time-a-function/BASIC/time-a-function.basic @@ -0,0 +1,9 @@ +DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE + +timestart = TIMER +SLEEP 1 'code or function to execute goes here +timedone = TIMER + +'midnight check: +IF timedone < timestart THEN timedone = timedone + 86400 +timeelapsed = timedone - timestart diff --git a/Task/Time-a-function/BBC-BASIC/time-a-function.bbc b/Task/Time-a-function/BBC-BASIC/time-a-function.bbc new file mode 100644 index 0000000000..8a282e4f26 --- /dev/null +++ b/Task/Time-a-function/BBC-BASIC/time-a-function.bbc @@ -0,0 +1,3 @@ +start%=TIME:REM centi-second timer +REM perform processing +lapsed%=TIME-start% diff --git a/Task/Time-a-function/C++/time-a-function.cpp b/Task/Time-a-function/C++/time-a-function.cpp new file mode 100644 index 0000000000..ee0ca61727 --- /dev/null +++ b/Task/Time-a-function/C++/time-a-function.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +int identity(int x) { return x; } +int sum(int num) { + for (int i = 0; i < 1000000; i++) + num += i; + return num; +} + +double time_it(int (*action)(int), int arg) { + clock_t start_time = clock(); + action(arg); + clock_t finis_time = clock(); + return ((double) (finis_time - start_time)) / CLOCKS_PER_SEC; +} + +int main() { + cout << "Identity(4) takes " << time_it(identity, 4) << " seconds." << endl; + cout << "Sum(4) takes " << time_it(sum, 4) << " seconds." << endl; + return 0; +} diff --git a/Task/Time-a-function/C/time-a-function.c b/Task/Time-a-function/C/time-a-function.c new file mode 100644 index 0000000000..4ade5d8478 --- /dev/null +++ b/Task/Time-a-function/C/time-a-function.c @@ -0,0 +1,34 @@ +#include +#include + +int identity(int x) { return x; } + +int sum(int s) +{ + int i; + for(i=0; i < 1000000; i++) s += i; + return s; +} + +#define CLOCKTYPE CLOCK_MONOTONIC +/* this one should be appropriate to avoid errors on multiprocessors systems */ + +double time_it(int (*action)(int), int arg) +{ + struct timespec tsi, tsf; + + clock_gettime(CLOCKTYPE, &tsi); + action(arg); + clock_gettime(CLOCKTYPE, &tsf); + + double elaps_s = difftime(tsf.tv_sec, tsi.tv_sec); + long elaps_ns = tsf.tv_nsec - tsi.tv_nsec; + return elaps_s + ((double)elaps_ns) / 1.0e9; +} + +int main() +{ + printf("identity (4) takes %lf s\n", time_it(identity, 4)); + printf("sum (4) takes %lf s\n", time_it(sum, 4)); + return 0; +} diff --git a/Task/Time-a-function/Clojure/time-a-function.clj b/Task/Time-a-function/Clojure/time-a-function.clj new file mode 100644 index 0000000000..a2fe7c5c6b --- /dev/null +++ b/Task/Time-a-function/Clojure/time-a-function.clj @@ -0,0 +1,7 @@ + (defn fib [] + (map first + (iterate + (fn [[a b]] [b (+ a b)]) + [0 1]))) + + (time (take 100 (fib))) diff --git a/Task/Time-a-function/Common-Lisp/time-a-function-1.lisp b/Task/Time-a-function/Common-Lisp/time-a-function-1.lisp new file mode 100644 index 0000000000..b3d2bfc3c4 --- /dev/null +++ b/Task/Time-a-function/Common-Lisp/time-a-function-1.lisp @@ -0,0 +1,8 @@ +CL-USER> (time (reduce #'+ (make-list 100000 :initial-element 1))) +Evaluation took: + 0.151 seconds of real time + 0.019035 seconds of user run time + 0.01807 seconds of system run time + 0 calls to %EVAL + 0 page faults and + 2,400,256 bytes consed. diff --git a/Task/Time-a-function/Common-Lisp/time-a-function-2.lisp b/Task/Time-a-function/Common-Lisp/time-a-function-2.lisp new file mode 100644 index 0000000000..44d0305773 --- /dev/null +++ b/Task/Time-a-function/Common-Lisp/time-a-function-2.lisp @@ -0,0 +1,10 @@ +(defun timings (function) + (let ((real-base (get-internal-real-time)) + (run-base (get-internal-run-time))) + (funcall function) + (values (/ (- (get-internal-real-time) real-base) internal-time-units-per-second) + (/ (- (get-internal-run-time) run-base) internal-time-units-per-second)))) + +CL-USER> (timings (lambda () (reduce #'+ (make-list 100000 :initial-element 1)))) +17/500 +7/250 diff --git a/Task/Time-a-function/D/time-a-function-1.d b/Task/Time-a-function/D/time-a-function-1.d new file mode 100644 index 0000000000..192efabce0 --- /dev/null +++ b/Task/Time-a-function/D/time-a-function-1.d @@ -0,0 +1,24 @@ +import std.stdio, std.datetime; + +int identity(int x) { + return x; +} + +int sum(int num) { + foreach (i; 0 .. 100_000_000) + num += i; + return num; +} + +double timeIt(int function(int) func, int arg) { + StopWatch sw; + sw.start(); + func(arg); + sw.stop(); + return sw.peek().usecs / 1_000_000.0; +} + +void main() { + writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4)); + writefln("sum(4) takes %f seconds.", timeIt(&sum, 4)); +} diff --git a/Task/Time-a-function/D/time-a-function-2.d b/Task/Time-a-function/D/time-a-function-2.d new file mode 100644 index 0000000000..8e6e465fd1 --- /dev/null +++ b/Task/Time-a-function/D/time-a-function-2.d @@ -0,0 +1,27 @@ +import tango.io.Stdout; +import tango.time.Clock; + +int identity (int x) +{ + return x; +} + +int sum (int num) +{ + for (int i = 0; i < 1000000; i++) + num += i; + return num; +} + +double timeIt(int function(int) func, int arg) +{ + long before = Clock.now.ticks; + func(arg); + return (Clock.now.ticks - before) / cast(double)TimeSpan.TicksPerSecond; +} + +void main () +{ + Stdout.format("Identity(4) takes {:f6} seconds",timeIt(&identity,4)).newline; + Stdout.format("Sum(4) takes {:f6} seconds",timeIt(&sum,4)).newline; +} diff --git a/Task/Time-a-function/E/time-a-function.e b/Task/Time-a-function/E/time-a-function.e new file mode 100644 index 0000000000..ecd8cdc993 --- /dev/null +++ b/Task/Time-a-function/E/time-a-function.e @@ -0,0 +1,17 @@ +def countTo(x) { + println("Counting...") + for _ in 1..x {} + println("Done!") +} + +def MX := +def threadMX := MX.getThreadMXBean() +require(threadMX.isCurrentThreadCpuTimeSupported()) +threadMX.setThreadCpuTimeEnabled(true) + +for count in [10000, 100000] { + def start := threadMX.getCurrentThreadCpuTime() + countTo(count) + def finish := threadMX.getCurrentThreadCpuTime() + println(`Counting to $count takes ${(finish-start)//1000000}ms`) +} diff --git a/Task/Time-a-function/Erlang/time-a-function-1.erl b/Task/Time-a-function/Erlang/time-a-function-1.erl new file mode 100644 index 0000000000..5b18240357 --- /dev/null +++ b/Task/Time-a-function/Erlang/time-a-function-1.erl @@ -0,0 +1,5 @@ +5> {Time,Result} = timer:tc(fun () -> lists:foreach(fun(X) -> X*X end, lists:seq(1,100000)) end). +{226391,ok} +6> Time/1000000. % Time is in microseconds. +0.226391 +7> % Time is in microseconds. diff --git a/Task/Time-a-function/Erlang/time-a-function-2.erl b/Task/Time-a-function/Erlang/time-a-function-2.erl new file mode 100644 index 0000000000..31f568ebde --- /dev/null +++ b/Task/Time-a-function/Erlang/time-a-function-2.erl @@ -0,0 +1,2 @@ +9> timer:tc(fun (X) -> lists:foreach(fun(Y) -> Y*Y end, lists:seq(1,X)) end, [1000000]). +{2293844,ok} diff --git a/Task/Time-a-function/Erlang/time-a-function-3.erl b/Task/Time-a-function/Erlang/time-a-function-3.erl new file mode 100644 index 0000000000..7bf470247a --- /dev/null +++ b/Task/Time-a-function/Erlang/time-a-function-3.erl @@ -0,0 +1,4 @@ +8> timer:tc(lists,seq,[1,1000000]). +{62370, + [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22, + 23,24,25,26,27|...]} diff --git a/Task/Time-a-function/Euphoria/time-a-function.euphoria b/Task/Time-a-function/Euphoria/time-a-function.euphoria new file mode 100644 index 0000000000..ebc1359f67 --- /dev/null +++ b/Task/Time-a-function/Euphoria/time-a-function.euphoria @@ -0,0 +1,5 @@ +atom t +t = time() +some_procedure() +t = time() - t +printf(1,"Elapsed %f seconds.\n",t) diff --git a/Task/Time-a-function/Factor/time-a-function.factor b/Task/Time-a-function/Factor/time-a-function.factor new file mode 100644 index 0000000000..1a8917caf0 --- /dev/null +++ b/Task/Time-a-function/Factor/time-a-function.factor @@ -0,0 +1 @@ +[ 10000 iota sum drop ] time diff --git a/Task/Time-a-function/Forth/time-a-function.fth b/Task/Time-a-function/Forth/time-a-function.fth new file mode 100644 index 0000000000..9c8c097264 --- /dev/null +++ b/Task/Time-a-function/Forth/time-a-function.fth @@ -0,0 +1,6 @@ +: time: ( "word" -- ) + utime 2>R ' EXECUTE + utime 2R> D- + <# # # # # # # [CHAR] . HOLD #S #> TYPE ." seconds" ; + +1000 time: MS \ 1.000081 seconds ok diff --git a/Task/Time-a-function/Fortran/time-a-function.f b/Task/Time-a-function/Fortran/time-a-function.f new file mode 100644 index 0000000000..2e98c06cf3 --- /dev/null +++ b/Task/Time-a-function/Fortran/time-a-function.f @@ -0,0 +1,17 @@ +c The subroutine to analyze + subroutine do_something() +c For testing we just do nothing for 3 seconds + call sleep(3) + return + end + +c Main Program + program timing + integer(kind=8) start,finish,rate,max + call system_clock(start,rate,max) +c Here comes the function we want to time + call do_something() + call system_clock(finish,rate,max) + write(6,*) 'Elapsed Time in seconds:',(finish-start)/rate + return + end diff --git a/Task/Time-a-function/GAP/time-a-function.gap b/Task/Time-a-function/GAP/time-a-function.gap new file mode 100644 index 0000000000..25723b14e2 --- /dev/null +++ b/Task/Time-a-function/GAP/time-a-function.gap @@ -0,0 +1,2 @@ +# Return the time passed in last function +time; diff --git a/Task/Time-a-function/Go/time-a-function-1.go b/Task/Time-a-function/Go/time-a-function-1.go new file mode 100644 index 0000000000..455170a55c --- /dev/null +++ b/Task/Time-a-function/Go/time-a-function-1.go @@ -0,0 +1,9 @@ +package empty + +func Empty() {} + +func Count() { + // count to a million + for i := 0; i < 1e6; i++ { + } +} diff --git a/Task/Time-a-function/Go/time-a-function-2.go b/Task/Time-a-function/Go/time-a-function-2.go new file mode 100644 index 0000000000..d29e545ccf --- /dev/null +++ b/Task/Time-a-function/Go/time-a-function-2.go @@ -0,0 +1,15 @@ +package empty + +import "testing" + +func BenchmarkEmpty(b *testing.B) { + for i := 0; i < b.N; i++ { + Empty() + } +} + +func BenchmarkCount(b *testing.B) { + for i := 0; i < b.N; i++ { + Count() + } +} diff --git a/Task/Time-a-function/Go/time-a-function-3.go b/Task/Time-a-function/Go/time-a-function-3.go new file mode 100644 index 0000000000..465bffd2f5 --- /dev/null +++ b/Task/Time-a-function/Go/time-a-function-3.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "time" +) + +func from(t0 time.Time) { + fmt.Println(time.Now().Sub(t0)) +} + +func empty() { + defer from(time.Now()) +} + +func count() { + defer from(time.Now()) + for i := 0; i < 1e6; i++ { + } +} + +func main() { + empty() + count() +} diff --git a/Task/Time-a-function/Groovy/time-a-function-1.groovy b/Task/Time-a-function/Groovy/time-a-function-1.groovy new file mode 100644 index 0000000000..483dd006c7 --- /dev/null +++ b/Task/Time-a-function/Groovy/time-a-function-1.groovy @@ -0,0 +1,12 @@ +import java.lang.management.ManagementFactory +import java.lang.management.ThreadMXBean + +def threadMX = ManagementFactory.threadMXBean +assert threadMX.currentThreadCpuTimeSupported +threadMX.threadCpuTimeEnabled = true + +def clockCpuTime = { Closure c -> + def start = threadMX.currentThreadCpuTime + c.call() + (threadMX.currentThreadCpuTime - start)/1000000 +} diff --git a/Task/Time-a-function/Groovy/time-a-function-2.groovy b/Task/Time-a-function/Groovy/time-a-function-2.groovy new file mode 100644 index 0000000000..266961777f --- /dev/null +++ b/Task/Time-a-function/Groovy/time-a-function-2.groovy @@ -0,0 +1,5 @@ +def clockRealTime = { Closure c -> + def start = System.currentTimeMillis() + c.call() + System.currentTimeMillis() - start +} diff --git a/Task/Time-a-function/Groovy/time-a-function-3.groovy b/Task/Time-a-function/Groovy/time-a-function-3.groovy new file mode 100644 index 0000000000..93d2f47e8f --- /dev/null +++ b/Task/Time-a-function/Groovy/time-a-function-3.groovy @@ -0,0 +1,11 @@ +def countTo = { Long n -> + long i = 0; while(i < n) { i += 1L } +} + +["CPU time":clockCpuTime, "wall clock time":clockRealTime].each { measurementType, timer -> + println '\n' + [100000000L, 1000000000L].each { testSize -> + def measuredTime = timer(countTo.curry(testSize)) + println "Counting to ${testSize} takes ${measuredTime}ms of ${measurementType}" + } +} diff --git a/Task/Time-a-function/Haskell/time-a-function.hs b/Task/Time-a-function/Haskell/time-a-function.hs new file mode 100644 index 0000000000..1faed29c2a --- /dev/null +++ b/Task/Time-a-function/Haskell/time-a-function.hs @@ -0,0 +1,13 @@ +import System.CPUTime + +-- We assume the function we are timing is an IO monad computation +timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c +timeIt action arg = + do startTime <- getCPUTime + action arg + finishTime <- getCPUTime + return $ fromIntegral (finishTime - startTime) / 1000000000000 + +-- Version for use with evaluating regular non-monadic functions +timeIt' :: (Fractional c) => (a -> b) -> a -> IO c +timeIt' f = timeIt (\x -> f x `seq` return ()) diff --git a/Task/Time-a-function/HicEst/time-a-function.hicest b/Task/Time-a-function/HicEst/time-a-function.hicest new file mode 100644 index 0000000000..445d6e9648 --- /dev/null +++ b/Task/Time-a-function/HicEst/time-a-function.hicest @@ -0,0 +1,5 @@ +t_start = TIME() ! returns seconds since midnight +SYSTEM(WAIT = 1234) ! wait 1234 milliseconds +t_end = TIME() + +WRITE(StatusBar) t_end - t_start, " seconds" diff --git a/Task/Time-a-function/Icon/time-a-function-1.icon b/Task/Time-a-function/Icon/time-a-function-1.icon new file mode 100644 index 0000000000..db52f46da6 --- /dev/null +++ b/Task/Time-a-function/Icon/time-a-function-1.icon @@ -0,0 +1,35 @@ +procedure timef(f) #: time a function f +local gcol,alloc,used,size,runtime,header,x,i + +title := ["","total","static","string","block"] # headings +collect() # start with collected memory (before baseline) +every put(gcol := [], -&collections) # baseline collections count +every put(alloc := [], -&allocated) # . total allocated space by region +every put(used := [], -&storage) # . currently used space by region - no total +every put(size := [], -®ions) # . current size of regions - no total + +write("Performance and Timing measurement for ",image(f),":") +runtime := &time # base time +f() +write("Execution time=",&time-runtime," ms.") + +every (i := 0, x := &collections) do gcol[i +:= 1] +:= x +every (i := 0, x := &allocated ) do alloc[i +:= 1] +:= x +every (i := 0, x := &storage ) do used[i +:= 1] +:= x +every (i := 0, x := ®ions ) do size[i +:= 1] +:= x + +push(gcol,"garbage collections:") +push(alloc,"memory allocated:") +push(used,"N/A","currently used:") +push(size,"N/A","current size:") + +write("Memory Region and Garbage Collection Summary (delta):") +every (i := 0) <:= *!(title|gcol|alloc|used|size) +every x := (title|gcol|alloc|used|size) do { + f := left + every writes(f(!x,i + 3)) do f := right + write() + } +write("Note: static region values should be zero and may not be meaningful.") +return +end diff --git a/Task/Time-a-function/Icon/time-a-function-2.icon b/Task/Time-a-function/Icon/time-a-function-2.icon new file mode 100644 index 0000000000..4ca00edcae --- /dev/null +++ b/Task/Time-a-function/Icon/time-a-function-2.icon @@ -0,0 +1,6 @@ +procedure main() +timef(perfectnumbers) +end + +procedure perfectnumbers() +... diff --git a/Task/Time-a-function/Ioke/time-a-function.ioke b/Task/Time-a-function/Ioke/time-a-function.ioke new file mode 100644 index 0000000000..4ebcbd5900 --- /dev/null +++ b/Task/Time-a-function/Ioke/time-a-function.ioke @@ -0,0 +1,5 @@ +use("benchmark") + +func = method((1..50000) reduce(+)) + +Benchmark report(1, 1, func) diff --git a/Task/Time-a-function/J/time-a-function.j b/Task/Time-a-function/J/time-a-function.j new file mode 100644 index 0000000000..11c732ef6f --- /dev/null +++ b/Task/Time-a-function/J/time-a-function.j @@ -0,0 +1,2 @@ + (6!:2,7!:2) '|: 50 50 50 $ i. 50^3' +0.00387912 1.57414e6 diff --git a/Task/Time-a-function/Java/time-a-function-1.java b/Task/Time-a-function/Java/time-a-function-1.java new file mode 100644 index 0000000000..ee4cdb1f24 --- /dev/null +++ b/Task/Time-a-function/Java/time-a-function-1.java @@ -0,0 +1,27 @@ +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadMXBean; + +public class TimeIt { + public static void main(String[] args) { + final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean(); + assert threadMX.isCurrentThreadCpuTimeSupported(); + threadMX.setThreadCpuTimeEnabled(true); + + long start, end; + start = threadMX.getCurrentThreadCpuTime(); + countTo(100000000); + end = threadMX.getCurrentThreadCpuTime(); + System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms"); + start = threadMX.getCurrentThreadCpuTime(); + countTo(1000000000L); + end = threadMX.getCurrentThreadCpuTime(); + System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms"); + + } + + public static void countTo(long x){ + System.out.println("Counting..."); + for(long i=0;i sub { fac1(50) }, + 'fac2' => sub { fac2(50) }, +}); +Benchmark::cmpthese($result); diff --git a/Task/Time-a-function/Perl/time-a-function-2.pl b/Task/Time-a-function/Perl/time-a-function-2.pl new file mode 100644 index 0000000000..fef93a9bce --- /dev/null +++ b/Task/Time-a-function/Perl/time-a-function-2.pl @@ -0,0 +1,26 @@ +sub cpu_time { + my ($user,$system,$cuser,$csystem) = times; + $user + $system +} + +sub time_it { + my $action = shift; + my $startTime = cpu_time(); + $action->(@_); + my $finishTime = cpu_time(); + $finishTime - $startTime +} + +printf "Identity(4) takes %f seconds.\n", time_it(sub {@_}, 4); +# outputs "Identity(4) takes 0.000000 seconds." + +sub sum { + my $x = shift; + foreach (0 .. 999999) { + $x += $_; + } + $x +} + +printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4); +# outputs "Sum(4) takes 0.280000 seconds." diff --git a/Task/Time-a-function/PicoLisp/time-a-function.l b/Task/Time-a-function/PicoLisp/time-a-function.l new file mode 100644 index 0000000000..efb442f170 --- /dev/null +++ b/Task/Time-a-function/PicoLisp/time-a-function.l @@ -0,0 +1,3 @@ +: (bench (do 1000000 (* 3 4))) +0.080 sec +-> 12 diff --git a/Task/Time-a-function/PureBasic/time-a-function-1.purebasic b/Task/Time-a-function/PureBasic/time-a-function-1.purebasic new file mode 100644 index 0000000000..84d656177e --- /dev/null +++ b/Task/Time-a-function/PureBasic/time-a-function-1.purebasic @@ -0,0 +1,22 @@ +Procedure Foo(Limit) + Protected i, palindromic, String$ + For i=0 To Limit + String$=Str(i) + If String$=ReverseString(String$) + palindromic+1 + EndIf + Next + ProcedureReturn palindromic +EndProcedure + +If OpenConsole() + Define Start, Stop, cnt + PrintN("Starting timing of a calculation,") + PrintN("for this we test how many of 0-1000000 are palindromic.") + Start=ElapsedMilliseconds() + cnt=Foo(1000000) + Stop=ElapsedMilliseconds() + PrintN("The function need "+Str(stop-Start)+" msec,") + PrintN("and "+Str(cnt)+" are palindromic.") + Print("Press ENTER to exit."): Input() +EndIf diff --git a/Task/Time-a-function/PureBasic/time-a-function-2.purebasic b/Task/Time-a-function/PureBasic/time-a-function-2.purebasic new file mode 100644 index 0000000000..f6c124c5ce --- /dev/null +++ b/Task/Time-a-function/PureBasic/time-a-function-2.purebasic @@ -0,0 +1,14 @@ +If OpenConsole() + Define Timed.f, cnt + PrintN("Starting timing of a calculation,") + PrintN("for this we test how many of 0-1000000 are palindromic.") + ; Dependent on Droopy-library + If MeasureHiResIntervalStart() + ; Same Foo() as above... + cnt=Foo(1000000) + Timed=MeasureHiResIntervalStop() + EndIf + PrintN("The function need "+StrF(Timed*1000,3)+" msec,") + PrintN("and "+Str(cnt)+" are palindromic.") + Print("Press ENTER to exit."): Input() +EndIf diff --git a/Task/Time-a-function/PureBasic/time-a-function-3.purebasic b/Task/Time-a-function/PureBasic/time-a-function-3.purebasic new file mode 100644 index 0000000000..eb4b961263 --- /dev/null +++ b/Task/Time-a-function/PureBasic/time-a-function-3.purebasic @@ -0,0 +1,30 @@ +Procedure.f ticksHQ(reportIfPresent = #False) + Static maxfreq.q + Protected T.q + If reportIfPresent Or maxfreq = 0 + QueryPerformanceFrequency_(@maxfreq) + If maxfreq + ProcedureReturn 1.0 + Else + ProcedureReturn 0 + EndIf + EndIf + QueryPerformanceCounter_(@T) + ProcedureReturn T / maxfreq ;Result is in milliseconds +EndProcedure + +If OpenConsole() + Define timed.f, cnt + PrintN("Starting timing of a calculation,") + PrintN("for this we test how many of 0-1000000 are palindromic.") + ; Dependent on Windows API + If ticksHQ(#True) + timed = ticksHQ() ;start time + ; Same Foo() as above... + cnt = Foo(1000000) + timed = ticksHQ() - timed ;difference + EndIf + PrintN("The function need " + StrF(timed * 1000, 3) + " msec,") + PrintN("and " + Str(cnt) + " are palindromic.") + Print("Press ENTER to exit."): Input() +EndIf diff --git a/Task/Time-a-function/Python/time-a-function.py b/Task/Time-a-function/Python/time-a-function.py new file mode 100644 index 0000000000..aab867e1ef --- /dev/null +++ b/Task/Time-a-function/Python/time-a-function.py @@ -0,0 +1,18 @@ +import sys, timeit +def usec(function, arguments): + modname, funcname = __name__, function.__name__ + timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(), + setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars()) + try: + t, N = 0, 1 + while t < 0.2: + t = min(timer.repeat(repeat=3, number=N)) + N *= 10 + microseconds = round(10000000 * t / N, 1) # per loop + return microseconds + except: + timer.print_exc(file=sys.stderr) + raise + + def nothing(): pass + def identity(x): return x diff --git a/Task/Time-a-function/R/time-a-function-1.r b/Task/Time-a-function/R/time-a-function-1.r new file mode 100644 index 0000000000..7cda92ed3f --- /dev/null +++ b/Task/Time-a-function/R/time-a-function-1.r @@ -0,0 +1,13 @@ +# A task +foo <- function() +{ + for(i in 1:10) + { + mat <- matrix(rnorm(1e6), nrow=1e3) + mat^-0.5 + } +} +# Time the task +timer <- system.time(foo()) +# Extract the processing time +timer["user.self"] diff --git a/Task/Time-a-function/R/time-a-function-2.r b/Task/Time-a-function/R/time-a-function-2.r new file mode 100644 index 0000000000..b3436af0b8 --- /dev/null +++ b/Task/Time-a-function/R/time-a-function-2.r @@ -0,0 +1,4 @@ +Rprof() +foo() +Rprof(NULL) +summaryRprof() diff --git a/Task/Time-a-function/REXX/time-a-function-1.rexx b/Task/Time-a-function/REXX/time-a-function-1.rexx new file mode 100644 index 0000000000..60171daeeb --- /dev/null +++ b/Task/Time-a-function/REXX/time-a-function-1.rexx @@ -0,0 +1,31 @@ +/*REXX program to show the elapsed time for a function (or subroutine). */ +arg times . /*get the arg from command line. */ +if times=='' then times=100000 /*any specified? No, use default*/ + +call time 'R' /*only 1st character is examined.*/ +call time 'reset' /*this verbose version also works*/ +call time 'rompishness' /*and yet another example. */ + +junk = silly(times) /*invoke the SILLY function. */ + /* CALL SILLY TIMES also works.*/ + + /*The E is for elapsed time.*/ + /* │ */ + /* ┌────────┘ */ + /* │ */ + /* ↓ */ +say 'function SILLY took' format(time("E"),,2) 'seconds for' times "iterations." + /* ↑ */ + /* │ */ + /* ┌────────────────┘ */ + /* │ */ + /* The above 2 for the FORMAT function displays the time */ + /* with 2 decimal digits (past the decimal point). Using */ + /* a 0 (zero) would round the time to whole seconds. */ +exit +/*──────────────────────────────────SILLY subroutine────────────────────*/ +silly: procedure /*chew up some CPU time doing some silly stuff.*/ + do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ... */ + a.j=random() date() time() digits() fuzz() form() xrange() queued() + end /*j*/ +return j-1 diff --git a/Task/Time-a-function/REXX/time-a-function-2.rexx b/Task/Time-a-function/REXX/time-a-function-2.rexx new file mode 100644 index 0000000000..e857af69b7 --- /dev/null +++ b/Task/Time-a-function/REXX/time-a-function-2.rexx @@ -0,0 +1,26 @@ +/*REXX program shows the CPU time used for a REXX pgm since it started. */ +arg times . /*get the arg from command line. */ +if times=='' then times=100000 /*any specified? No, use default*/ +junk = silly(times) /*invoke the SILLY function. */ + /* CALL SILLY TIMES also works.*/ + + /*The J is for time used by */ + /* │ the REXX program */ + /* ┌────────┘ since it started, */ + /* │ this is a Regina extension. */ + /* ↓ */ +say 'function SILLY took' format(time("J"),,2) 'seconds for' times "iterations." + /* ↑ */ + /* │ */ + /* ┌────────────────┘ */ + /* │ */ + /* The above 2 for the FORMAT function displays the time */ + /* with 2 decimal digits (past the decimal point). Using */ + /* a 0 (zero) would round the time to whole seconds. */ +exit +/*──────────────────────────────────SILLY subroutine────────────────────*/ +silly: procedure /*chew up some CPU time doing some silly stuff.*/ + do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ... */ + a.j=random() date() time() digits() fuzz() form() xrange() queued() + end /*j*/ +return j-1 diff --git a/Task/Time-a-function/Racket/time-a-function.rkt b/Task/Time-a-function/Racket/time-a-function.rkt new file mode 100644 index 0000000000..ab83d01d8f --- /dev/null +++ b/Task/Time-a-function/Racket/time-a-function.rkt @@ -0,0 +1,7 @@ +#lang racket +(define (fact n) + (if (zero? n) + 1 + (* n (fact (sub1 n))))) + +(time (fact 5000)) diff --git a/Task/Time-a-function/Retro/time-a-function.retro b/Task/Time-a-function/Retro/time-a-function.retro new file mode 100644 index 0000000000..bbd8f3c932 --- /dev/null +++ b/Task/Time-a-function/Retro/time-a-function.retro @@ -0,0 +1,4 @@ +: .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ; + +: test 20000 [ putn space ] iterd ; +&test .runtime diff --git a/Task/Time-a-function/Ruby/time-a-function-1.rb b/Task/Time-a-function/Ruby/time-a-function-1.rb new file mode 100644 index 0000000000..711d4274b8 --- /dev/null +++ b/Task/Time-a-function/Ruby/time-a-function-1.rb @@ -0,0 +1,6 @@ +require 'benchmark' + +Benchmark.bm(8) do |x| + x.report("nothing:") { } + x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} } +end diff --git a/Task/Time-a-function/Ruby/time-a-function-2.rb b/Task/Time-a-function/Ruby/time-a-function-2.rb new file mode 100644 index 0000000000..40d70f5680 --- /dev/null +++ b/Task/Time-a-function/Ruby/time-a-function-2.rb @@ -0,0 +1 @@ +Benchmark.measure { whatever }.total diff --git a/Task/Time-a-function/Scala/time-a-function-1.scala b/Task/Time-a-function/Scala/time-a-function-1.scala new file mode 100644 index 0000000000..b15c17f468 --- /dev/null +++ b/Task/Time-a-function/Scala/time-a-function-1.scala @@ -0,0 +1,5 @@ +def time(f: => Unit)={ + val s = System.currentTimeMillis + f + System.currentTimeMillis - s +} diff --git a/Task/Time-a-function/Scala/time-a-function-2.scala b/Task/Time-a-function/Scala/time-a-function-2.scala new file mode 100644 index 0000000000..a867c4d045 --- /dev/null +++ b/Task/Time-a-function/Scala/time-a-function-2.scala @@ -0,0 +1,3 @@ +println(time { + for(i <- 1 to 10000000) {} +}) diff --git a/Task/Time-a-function/Scala/time-a-function-3.scala b/Task/Time-a-function/Scala/time-a-function-3.scala new file mode 100644 index 0000000000..5cbbc57360 --- /dev/null +++ b/Task/Time-a-function/Scala/time-a-function-3.scala @@ -0,0 +1,3 @@ +def count(i:Int) = for(j <- 1 to i){} + +println(time (count(10000000))) diff --git a/Task/Time-a-function/Scheme/time-a-function.ss b/Task/Time-a-function/Scheme/time-a-function.ss new file mode 100644 index 0000000000..eebefa19eb --- /dev/null +++ b/Task/Time-a-function/Scheme/time-a-function.ss @@ -0,0 +1 @@ +(time (some-function)) diff --git a/Task/Time-a-function/Seed7/time-a-function.seed7 b/Task/Time-a-function/Seed7/time-a-function.seed7 new file mode 100644 index 0000000000..765c655dcf --- /dev/null +++ b/Task/Time-a-function/Seed7/time-a-function.seed7 @@ -0,0 +1,35 @@ +$ include "seed7_05.s7i"; + include "time.s7i"; + include "duration.s7i"; + +const func integer: identity (in integer: x) is + return x; + +const func integer: sum (in integer: num) is func + result + var integer: result is 0; + local + var integer: number is 0; + begin + result := num; + for number range 1 to 1000000 do + result +:= number; + end for; + end func; + +const func duration: timeIt (ref func integer: aFunction) is func + result + var duration: result is duration.value; + local + var time: before is time.value; + begin + before := time(NOW); + ignore(aFunction); + result := time(NOW) - before; + end func; + +const proc: main is func + begin + writeln("Identity(4) takes " <& timeIt(identity(4))); + writeln("Sum(4) takes " <& timeIt(sum(4))); + end func; diff --git a/Task/Time-a-function/Slate/time-a-function.slate b/Task/Time-a-function/Slate/time-a-function.slate new file mode 100644 index 0000000000..9334f247d2 --- /dev/null +++ b/Task/Time-a-function/Slate/time-a-function.slate @@ -0,0 +1 @@ +[inform: 2000 factorial] timeToRun. diff --git a/Task/Time-a-function/Smalltalk/time-a-function.st b/Task/Time-a-function/Smalltalk/time-a-function.st new file mode 100644 index 0000000000..378e45dbe0 --- /dev/null +++ b/Task/Time-a-function/Smalltalk/time-a-function.st @@ -0,0 +1,2 @@ +Time millisecondsToRun: [ + Transcript show: 2000 factorial ]. diff --git a/Task/Time-a-function/Standard-ML/time-a-function.ml b/Task/Time-a-function/Standard-ML/time-a-function.ml new file mode 100644 index 0000000000..22a2bab125 --- /dev/null +++ b/Task/Time-a-function/Standard-ML/time-a-function.ml @@ -0,0 +1,7 @@ +fun time_it (action, arg) = let + val timer = Timer.startCPUTimer () + val _ = action arg + val times = Timer.checkCPUTimer timer +in + Time.+ (#usr times, #sys times) +end diff --git a/Task/Time-a-function/TUSCRIPT/time-a-function.tuscript b/Task/Time-a-function/TUSCRIPT/time-a-function.tuscript new file mode 100644 index 0000000000..79a4b2d108 --- /dev/null +++ b/Task/Time-a-function/TUSCRIPT/time-a-function.tuscript @@ -0,0 +1,14 @@ +$$ MODE TUSCRIPT +SECTION test +LOOP n=1,999999 +rest=MOD (n,1000) +IF (rest==0) Print n +ENDLOOP +ENDSECTION +time_beg=TIME () +DO test +time_end=TIME () +interval=TIME_INTERVAL (seconds,time_beg,time_end) +PRINT "'test' start at ",time_beg +PRINT "'test' ends at ",time_end +PRINT "'test' takes ",interval," seconds" diff --git a/Task/Time-a-function/Tcl/time-a-function.tcl b/Task/Time-a-function/Tcl/time-a-function.tcl new file mode 100644 index 0000000000..f110aefbac --- /dev/null +++ b/Task/Time-a-function/Tcl/time-a-function.tcl @@ -0,0 +1,7 @@ +proc sum_n {n} { + for {set i 1; set sum 0.0} {$i <= $n} {incr i} {set sum [expr {$sum + $i}]} + return [expr {wide($sum)}] +} + +puts [time {sum_n 1e6} 100] +puts [time {} 100] diff --git a/Task/Time-a-function/TorqueScript/time-a-function-1.torquescript b/Task/Time-a-function/TorqueScript/time-a-function-1.torquescript new file mode 100644 index 0000000000..d254ff627d --- /dev/null +++ b/Task/Time-a-function/TorqueScript/time-a-function-1.torquescript @@ -0,0 +1,23 @@ +function benchmark(%times,%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o) +{ + if(!isFunction(%function)) + { + warn("BENCHMARKING RESULT FOR" SPC %function @ ":" NL "Function does not exist."); + return -1; + } + + %start = getRealTime(); + + for(%i=0; %i < %times; %i++) + { + call(%function,%a,%b,%c,%d,%e,%f,%g,%h,%i,%j,%k,%l,%m,%n,%o); + } + + %end = getRealTime(); + + %result = (%end-%start) / %times; + + warn("BENCHMARKING RESULT FOR" SPC %function @ ":" NL %result); + + return %result; +} diff --git a/Task/Time-a-function/TorqueScript/time-a-function-2.torquescript b/Task/Time-a-function/TorqueScript/time-a-function-2.torquescript new file mode 100644 index 0000000000..3a4fd6cd7a --- /dev/null +++ b/Task/Time-a-function/TorqueScript/time-a-function-2.torquescript @@ -0,0 +1,9 @@ +function exampleFunction(%var1,%var2) +{ + //put stuff here +} + +benchmark(500,"exampleFunction","blah","variables"); + +==> BENCHMARKING RESULT FOR exampleFunction: +==> 13.257 diff --git a/Task/Time-a-function/UNIX-Shell/time-a-function.sh b/Task/Time-a-function/UNIX-Shell/time-a-function.sh new file mode 100644 index 0000000000..b6d8802c6c --- /dev/null +++ b/Task/Time-a-function/UNIX-Shell/time-a-function.sh @@ -0,0 +1 @@ +$ time sleep 1 diff --git a/Task/Time-a-function/XPL0/time-a-function.xpl0 b/Task/Time-a-function/XPL0/time-a-function.xpl0 new file mode 100644 index 0000000000..3fbc97bdf0 --- /dev/null +++ b/Task/Time-a-function/XPL0/time-a-function.xpl0 @@ -0,0 +1,7 @@ +include c:\cxpl\codes; +int T0, T1, I; +[T0:= GetTime; +for I:= 1, 1_000_000 do []; +T1:= GetTime; +IntOut(0, T1-T0); Text(0, " microseconds^M^J"); +] diff --git a/Task/Tokenize-a-string/0DESCRIPTION b/Task/Tokenize-a-string/0DESCRIPTION new file mode 100644 index 0000000000..6af0b33a4f --- /dev/null +++ b/Task/Tokenize-a-string/0DESCRIPTION @@ -0,0 +1 @@ +Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. diff --git a/Task/Tokenize-a-string/1META.yaml b/Task/Tokenize-a-string/1META.yaml new file mode 100644 index 0000000000..ae625822b7 --- /dev/null +++ b/Task/Tokenize-a-string/1META.yaml @@ -0,0 +1,2 @@ +--- +note: String manipulation diff --git a/Task/Tokenize-a-string/ACL2/tokenize-a-string.acl2 b/Task/Tokenize-a-string/ACL2/tokenize-a-string.acl2 new file mode 100644 index 0000000000..bca88dcf63 --- /dev/null +++ b/Task/Tokenize-a-string/ACL2/tokenize-a-string.acl2 @@ -0,0 +1,29 @@ +(defun split-at (xs delim) + (if (or (endp xs) (eql (first xs) delim)) + (mv nil (rest xs)) + (mv-let (before after) + (split-at (rest xs) delim) + (mv (cons (first xs) before) after)))) + +(defun split (xs delim) + (if (endp xs) + nil + (mv-let (before after) + (split-at xs delim) + (cons before (split after delim))))) + +(defun css->strs (css) + (if (endp css) + nil + (cons (coerce (first css) 'string) + (css->strs (rest css))))) + +(defun split-str (str delim) + (css->strs (split (coerce str 'list) delim))) + +(defun print-with (strs delim) + (if (endp strs) + (cw "~%") + (progn$ (cw (first strs)) + (cw (coerce (list delim) 'string)) + (print-with (rest strs) delim)))) diff --git a/Task/Tokenize-a-string/ALGOL-68/tokenize-a-string.alg b/Task/Tokenize-a-string/ALGOL-68/tokenize-a-string.alg new file mode 100644 index 0000000000..6d7857b49d --- /dev/null +++ b/Task/Tokenize-a-string/ALGOL-68/tokenize-a-string.alg @@ -0,0 +1,49 @@ +main:( + + OP +:= = (REF FLEX[]STRING in out, STRING item)VOID:( + [LWB in out: UPB in out+1]STRING new; + new[LWB in out: UPB in out]:=in out; + new[UPB new]:=item; + in out := new + ); + + PROC string split = (REF STRING beetles, STRING substr)[]STRING:( + """ Split beetles where substr is found """; + FLEX[1:0]STRING out; + INT start := 1, pos; + WHILE string in string(substr, pos, beetles[start:]) DO + out +:= STRING(beetles[start:start+pos-2]); + start +:= pos + UPB substr - 1 + OD; + IF start > LWB beetles THEN + out +:= STRING(beetles[start:]) + FI; + out + ); + + PROC char split = (REF STRING beetles, STRING chars)[]STRING: ( + """ Split beetles where character is found in chars """; + FLEX[1:0]STRING out; + FILE beetlef; + associate(beetlef, beetles); # associate a FILE handle with a STRING # + make term(beetlef, chars); # make term: assign CSV string terminator # + + PROC raise logical file end = (REF FILE f)BOOL: except logical file end; + on logical file end(beetlef, raise logical file end); + + STRING solo; + DO + getf(beetlef, ($g$, solo)); + out+:=solo; + getf(beetlef, ($x$)) # skip CHAR separator # + OD; + except logical file end: + SKIP; + out + ); + + STRING beetles := "John Lennon, Paul McCartney, George Harrison, Ringo Starr"; + + printf(($g"."$, string split(beetles, ", "),$l$)); + printf(($g"."$, char split(beetles, ", "),$l$)) +) diff --git a/Task/Tokenize-a-string/AWK/tokenize-a-string-1.awk b/Task/Tokenize-a-string/AWK/tokenize-a-string-1.awk new file mode 100644 index 0000000000..d1087ef8f4 --- /dev/null +++ b/Task/Tokenize-a-string/AWK/tokenize-a-string-1.awk @@ -0,0 +1,8 @@ +BEGIN { + s = "Hello,How,Are,You,Today" + split(s, arr, ",") + for(i=1; i < length(arr); i++) { + printf arr[i] "." + } + print +} diff --git a/Task/Tokenize-a-string/AWK/tokenize-a-string-2.awk b/Task/Tokenize-a-string/AWK/tokenize-a-string-2.awk new file mode 100644 index 0000000000..55fffcc740 --- /dev/null +++ b/Task/Tokenize-a-string/AWK/tokenize-a-string-2.awk @@ -0,0 +1,5 @@ +BEGIN { FS = "," } +{ + for(i=1; i <= NF; i++) printf $i "."; + print "" +} diff --git a/Task/Tokenize-a-string/ActionScript/tokenize-a-string.as b/Task/Tokenize-a-string/ActionScript/tokenize-a-string.as new file mode 100644 index 0000000000..b6a1517a09 --- /dev/null +++ b/Task/Tokenize-a-string/ActionScript/tokenize-a-string.as @@ -0,0 +1,6 @@ +var hello:String = "Hello,How,Are,You,Today"; +var tokens:Array = hello.split(","); +trace(tokens.join(".")); + +// Or as a one-liner +trace("Hello,How,Are,You,Today".split(",").join(".")); diff --git a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada new file mode 100644 index 0000000000..f79a6de30c --- /dev/null +++ b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada @@ -0,0 +1,18 @@ +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Parse_Commas is + Source_String : String := "Hello,How,Are,You,Today"; + Index_List : array(Source_String'Range) of Natural; + Next_Index : Natural := Index_List'First; +begin + Index_List(Next_Index) := Source_String'First; + while Index_List(Next_Index) < Source_String'Last loop + Next_Index := Next_Index + 1; + Index_List(Next_Index) := 1 + Index(Source_String(Index_List(Next_Index - 1)..Source_String'Last), ","); + if Index_List(Next_Index) = 1 then + Index_List(Next_Index) := Source_String'Last + 2; + end if; + Put(Source_String(Index_List(Next_Index - 1)..Index_List(Next_Index)-2) & "."); + end loop; +end Parse_Commas; diff --git a/Task/Tokenize-a-string/AutoHotkey/tokenize-a-string.ahk b/Task/Tokenize-a-string/AutoHotkey/tokenize-a-string.ahk new file mode 100644 index 0000000000..67f4f48701 --- /dev/null +++ b/Task/Tokenize-a-string/AutoHotkey/tokenize-a-string.ahk @@ -0,0 +1,6 @@ +string := "Hello,How,Are,You,Today" +stringsplit, string, string, `, +loop, % string0 +{ +msgbox % string%A_Index% +} diff --git a/Task/Tokenize-a-string/BASIC/tokenize-a-string.basic b/Task/Tokenize-a-string/BASIC/tokenize-a-string.basic new file mode 100644 index 0000000000..f63022d900 --- /dev/null +++ b/Task/Tokenize-a-string/BASIC/tokenize-a-string.basic @@ -0,0 +1,45 @@ +DIM parseMe AS STRING +parseMe = "Hello,How,Are,You,Today" + +DIM tmpLng1 AS INTEGER, tmpLng2 AS INTEGER, parsedCount AS INTEGER +tmpLng2 = 1 +parsedCount = -1 + +'count number of tokens +DO + tmpLng1 = INSTR(tmpLng2, parseMe, ",") + IF tmpLng1 THEN + parsedCount = parsedCount + 1 + tmpLng2 = tmpLng1 + 1 + ELSE + IF tmpLng2 < (LEN(parseMe) + 1) THEN parsedCount = parsedCount + 1 + EXIT DO + END IF +LOOP + +IF parsedCount > -1 THEN + REDIM parsed(parsedCount) AS STRING + tmpLng2 = 1 + parsedCount = -1 + + 'parse + DO + tmpLng1 = INSTR(tmpLng2, parseMe, ",") + IF tmpLng1 THEN + parsedCount = parsedCount + 1 + parsed(parsedCount) = MID$(parseMe, tmpLng2, tmpLng1 - tmpLng2) + tmpLng2 = tmpLng1 + 1 + ELSE + IF tmpLng2 < (LEN(parseMe) + 1) THEN + parsedCount = parsedCount + 1 + parsed(parsedCount) = MID$(parseMe, tmpLng2) + END IF + EXIT DO + END IF + LOOP + + PRINT parsed(0); + FOR L0 = 1 TO parsedCount + PRINT "."; parsed(L0); + NEXT +END IF diff --git a/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc b/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc new file mode 100644 index 0000000000..ed538d7a3d --- /dev/null +++ b/Task/Tokenize-a-string/BBC-BASIC/tokenize-a-string.bbc @@ -0,0 +1,8 @@ + INSTALL @lib$+"STRINGLIB" + + text$ = "Hello,How,Are,You,Today" + n% = FN_split(text$, ",", array$()) + FOR i% = 0 TO n%-1 + PRINT array$(i%) "." ; + NEXT + PRINT diff --git a/Task/Tokenize-a-string/Batch-File/tokenize-a-string.bat b/Task/Tokenize-a-string/Batch-File/tokenize-a-string.bat new file mode 100644 index 0000000000..aceb49cd07 --- /dev/null +++ b/Task/Tokenize-a-string/Batch-File/tokenize-a-string.bat @@ -0,0 +1,12 @@ +@echo off +setlocal enabledelayedexpansion +call :tokenize %1 res +echo %res% +goto :eof + +:tokenize +set str=%~1 +:loop +for %%i in (%str%) do set %2=!%2!.%%i +set %2=!%2:~1! +goto :eof diff --git a/Task/Tokenize-a-string/Bracmat/tokenize-a-string-1.bracmat b/Task/Tokenize-a-string/Bracmat/tokenize-a-string-1.bracmat new file mode 100644 index 0000000000..0ca19ada0c --- /dev/null +++ b/Task/Tokenize-a-string/Bracmat/tokenize-a-string-1.bracmat @@ -0,0 +1,13 @@ +( "Hello,How,Are,You,Today":?String +& :?ReverseList +& whl + ' ( @(!String:?element "," ?String) + & !element !ReverseList:?ReverseList + ) +& !String:?List +& whl + ' ( !ReverseList:%?element ?ReverseList + & (!element.!List):?List + ) +& out$!List +) diff --git a/Task/Tokenize-a-string/Bracmat/tokenize-a-string-2.bracmat b/Task/Tokenize-a-string/Bracmat/tokenize-a-string-2.bracmat new file mode 100644 index 0000000000..a1b91648ad --- /dev/null +++ b/Task/Tokenize-a-string/Bracmat/tokenize-a-string-2.bracmat @@ -0,0 +1,13 @@ +( get$("Hello,How,Are,You,Today",MEM):?CommaseparatedList +& :?ReverseList +& whl + ' ( !CommaseparatedList:(?element,?CommaseparatedList) + & !element !ReverseList:?ReverseList + ) +& !CommaseparatedList:?List +& whl + ' ( !ReverseList:%?element ?ReverseList + & (!element.!List):?List + ) +& out$!List +) diff --git a/Task/Tokenize-a-string/C++/tokenize-a-string-1.cpp b/Task/Tokenize-a-string/C++/tokenize-a-string-1.cpp new file mode 100644 index 0000000000..770f97f788 --- /dev/null +++ b/Task/Tokenize-a-string/C++/tokenize-a-string-1.cpp @@ -0,0 +1,16 @@ +#include +#include +#include +#include +#include +#include +int main() +{ + std::string s = "Hello,How,Are,You,Today"; + std::vector v; + std::istringstream buf(s); + for(std::string token; getline(buf, token, ','); ) + v.push_back(token); + copy(v.begin(), v.end(), std::ostream_iterator(std::cout, ".")); + std::cout << '\n'; +} diff --git a/Task/Tokenize-a-string/C++/tokenize-a-string-2.cpp b/Task/Tokenize-a-string/C++/tokenize-a-string-2.cpp new file mode 100644 index 0000000000..f6761e9953 --- /dev/null +++ b/Task/Tokenize-a-string/C++/tokenize-a-string-2.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include +#include +struct comma_ws : std::ctype { + static const mask* make_table() { + static std::vector v(classic_table(), classic_table() + table_size); + v[','] |= space; // comma will be classified as whitespace + return &v[0]; + } + comma_ws(std::size_t refs = 0) : ctype(make_table(), false, refs) {} +}; +int main() +{ + std::string s = "Hello,How,Are,You,Today"; + std::istringstream buf(s); + buf.imbue(std::locale(buf.getloc(), new comma_ws)); + std::istream_iterator beg(buf), end; + std::vector v(beg, end); + copy(v.begin(), v.end(), std::ostream_iterator(std::cout, ".")); + std::cout << '\n'; +} diff --git a/Task/Tokenize-a-string/C++/tokenize-a-string-3.cpp b/Task/Tokenize-a-string/C++/tokenize-a-string-3.cpp new file mode 100644 index 0000000000..5d068852ce --- /dev/null +++ b/Task/Tokenize-a-string/C++/tokenize-a-string-3.cpp @@ -0,0 +1,14 @@ +#include +#include +#include +#include +#include +#include +int main() +{ + std::string s = "Hello,How,Are,You,Today"; + boost::tokenizer<> tok(s); + std::vector v(tok.begin(), tok.end()); + copy(v.begin(), v.end(), std::ostream_iterator(std::cout, ".")) + std::cout << '\n'; +} diff --git a/Task/Tokenize-a-string/C/tokenize-a-string-1.c b/Task/Tokenize-a-string/C/tokenize-a-string-1.c new file mode 100644 index 0000000000..bf0f056ab7 --- /dev/null +++ b/Task/Tokenize-a-string/C/tokenize-a-string-1.c @@ -0,0 +1,22 @@ +#include +#include +#include + +int main(void) +{ + char *a[5]; + const char *s="Hello,How,Are,You,Today"; + int n=0, nn; + + char *ds=strdup(s); + + a[n]=strtok(ds, ","); + while(a[n] && n<4) a[++n]=strtok(NULL, ","); + + for(nn=0; nn<=n; ++nn) printf("%s.", a[nn]); + putchar('\n'); + + free(ds); + + return 0; +} diff --git a/Task/Tokenize-a-string/C/tokenize-a-string-2.c b/Task/Tokenize-a-string/C/tokenize-a-string-2.c new file mode 100644 index 0000000000..310d2ed7ea --- /dev/null +++ b/Task/Tokenize-a-string/C/tokenize-a-string-2.c @@ -0,0 +1,26 @@ +#include + +typedef (void *callbackfunc)(const char *); + +void doprint(const char *s) { + printf("%s.", s); +} + +void tokenize(char *s, char delim, callbackfunc *cb) { + char *olds = s; + char olddelim = delim; + while(olddelim && *s) { + while(*s && (delim != *s)) s++; + *s ^= olddelim = *s; // olddelim = *s; *s = 0; + cb(olds); + *s++ ^= olddelim; // *s = olddelim; s++; + olds = s; + } +} + +int main(void) +{ + char array[] = "Hello,How,Are,You,Today"; + tokenize(array, ',', doprint); + return 0; +} diff --git a/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj b/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj new file mode 100644 index 0000000000..ae80e8bc9f --- /dev/null +++ b/Task/Tokenize-a-string/Clojure/tokenize-a-string.clj @@ -0,0 +1 @@ +(apply str (interpose "." (seq (.split #"," "Hello,How,Are,You,Today")))) diff --git a/Task/Tokenize-a-string/CoffeeScript/tokenize-a-string.coffeescript b/Task/Tokenize-a-string/CoffeeScript/tokenize-a-string.coffeescript new file mode 100644 index 0000000000..43b8c46d48 --- /dev/null +++ b/Task/Tokenize-a-string/CoffeeScript/tokenize-a-string.coffeescript @@ -0,0 +1,2 @@ +arr = "Hello,How,Are,You,Today".split "," +console.log arr.join "." diff --git a/Task/Tokenize-a-string/Common-Lisp/tokenize-a-string.lisp b/Task/Tokenize-a-string/Common-Lisp/tokenize-a-string.lisp new file mode 100644 index 0000000000..50e72441c2 --- /dev/null +++ b/Task/Tokenize-a-string/Common-Lisp/tokenize-a-string.lisp @@ -0,0 +1,8 @@ +(defun comma-split (string) + (loop for start = 0 then (1+ finish) + for finish = (position #\, string :start start) + collecting (subseq string start finish) + until (null finish))) + +(defun write-with-periods (strings) + (format t "~{~A~^.~}" strings)) diff --git a/Task/Tokenize-a-string/D/tokenize-a-string.d b/Task/Tokenize-a-string/D/tokenize-a-string.d new file mode 100644 index 0000000000..7b3889b289 --- /dev/null +++ b/Task/Tokenize-a-string/D/tokenize-a-string.d @@ -0,0 +1,5 @@ +import std.stdio, std.string; + +void main() { + "Hello,How,Are,You,Today".split(",").join(".").writeln(); +} diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi new file mode 100644 index 0000000000..a1a2a870ba --- /dev/null +++ b/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi @@ -0,0 +1,32 @@ +program TokenizeString; + +{$APPTYPE CONSOLE} + +uses + Classes; + +var + tmp: TStringList; + i: Integer; + +begin + + // Instantiate TStringList class + tmp := TStringList.Create; + try + { Use the TStringList's CommaText property to get/set + all the strings in a single comma-delimited string } + tmp.CommaText := 'Hello,How,Are,You,Today'; + + { Now loop through the TStringList and display each + token on the console } + for i := 0 to Pred(tmp.Count) do + Writeln(tmp[i]); + + finally + tmp.Free; + end; + + Readln; + +end. diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi new file mode 100644 index 0000000000..1a48798e80 --- /dev/null +++ b/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi @@ -0,0 +1,5 @@ +Hello +How +Are +You +Today diff --git a/Task/Tokenize-a-string/E/tokenize-a-string.e b/Task/Tokenize-a-string/E/tokenize-a-string.e new file mode 100644 index 0000000000..ea212463a3 --- /dev/null +++ b/Task/Tokenize-a-string/E/tokenize-a-string.e @@ -0,0 +1 @@ +".".rjoin("Hello,How,Are,You,Today".split(",")) diff --git a/Task/Tokenize-a-string/Erlang/tokenize-a-string.erl b/Task/Tokenize-a-string/Erlang/tokenize-a-string.erl new file mode 100644 index 0000000000..8bfdc1c3b5 --- /dev/null +++ b/Task/Tokenize-a-string/Erlang/tokenize-a-string.erl @@ -0,0 +1,7 @@ +-module(tok). +-export([start/0]). + +start() -> + Lst = string:tokens("Hello,How,Are,You,Today",","), + io:fwrite("~s~n", [string:join(Lst,".")]), + ok. diff --git a/Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria b/Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria new file mode 100644 index 0000000000..0720c0b255 --- /dev/null +++ b/Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria @@ -0,0 +1,22 @@ +function split(sequence s, integer c) + sequence out + integer first, delim + out = {} + first = 1 + while first<=length(s) do + delim = find_from(c,s,first) + if delim = 0 then + delim = length(s)+1 + end if + out = append(out,s[first..delim-1]) + first = delim + 1 + end while + return out +end function + +sequence s +s = split("Hello,How,Are,You,Today", ',') + +for i = 1 to length(s) do + puts(1, s[i] & ',') +end for diff --git a/Task/Tokenize-a-string/Factor/tokenize-a-string.factor b/Task/Tokenize-a-string/Factor/tokenize-a-string.factor new file mode 100644 index 0000000000..2cb615b8f8 --- /dev/null +++ b/Task/Tokenize-a-string/Factor/tokenize-a-string.factor @@ -0,0 +1 @@ +"Hello,How,Are,You,Today" "," split "." join print diff --git a/Task/Tokenize-a-string/Fantom/tokenize-a-string.fantom b/Task/Tokenize-a-string/Fantom/tokenize-a-string.fantom new file mode 100644 index 0000000000..5b90d9a19b --- /dev/null +++ b/Task/Tokenize-a-string/Fantom/tokenize-a-string.fantom @@ -0,0 +1,12 @@ +class Main +{ + public static Void main () + { + str := "Hello,How,Are,You,Today" + words := str.split(',') + words.each |Str word| + { + echo ("${word}. ") + } + } +} diff --git a/Task/Tokenize-a-string/Forth/tokenize-a-string.fth b/Task/Tokenize-a-string/Forth/tokenize-a-string.fth new file mode 100644 index 0000000000..5eea676406 --- /dev/null +++ b/Task/Tokenize-a-string/Forth/tokenize-a-string.fth @@ -0,0 +1,18 @@ +: split ( str len separator len -- tokens count ) + here >r 2swap + begin + 2dup 2, \ save this token ( addr len ) + 2over search \ find next separator + while + dup negate here 2 cells - +! \ adjust last token length + 2over nip /string \ start next search past separator + repeat + 2drop 2drop + r> here over - ( tokens length ) + dup negate allot \ reclaim dictionary + 2 cells / ; \ turn byte length into token count + +: .tokens ( tokens count -- ) + 1 ?do dup 2@ type ." ." cell+ cell+ loop 2@ type ; + +s" Hello,How,Are,You,Today" s" ," split .tokens \ Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/Fortran/tokenize-a-string.f b/Task/Tokenize-a-string/Fortran/tokenize-a-string.f new file mode 100644 index 0000000000..e7eeccc240 --- /dev/null +++ b/Task/Tokenize-a-string/Fortran/tokenize-a-string.f @@ -0,0 +1,23 @@ +PROGRAM Example + + CHARACTER(23) :: str = "Hello,How,Are,You,Today" + CHARACTER(5) :: word(5) + INTEGER :: pos1 = 1, pos2, n = 0, i + + DO + pos2 = INDEX(str(pos1:), ",") + IF (pos2 == 0) THEN + n = n + 1 + word(n) = str(pos1:) + EXIT + END IF + n = n + 1 + word(n) = str(pos1:pos1+pos2-2) + pos1 = pos2+pos1 + END DO + + DO i = 1, n + WRITE(*,"(2A)", ADVANCE="NO") TRIM(word(i)), "." + END DO + +END PROGRAM Example diff --git a/Task/Tokenize-a-string/GAP/tokenize-a-string.gap b/Task/Tokenize-a-string/GAP/tokenize-a-string.gap new file mode 100644 index 0000000000..db866482ee --- /dev/null +++ b/Task/Tokenize-a-string/GAP/tokenize-a-string.gap @@ -0,0 +1,5 @@ +SplitString("Hello,How,Are,You,Today", ","); +# [ "Hello", "How", "Are", "You", "Today" ] + +JoinStringsWithSeparator(last, "."); +# "Hello.How.Are.You.Today" diff --git a/Task/Tokenize-a-string/Go/tokenize-a-string.go b/Task/Tokenize-a-string/Go/tokenize-a-string.go new file mode 100644 index 0000000000..f7827660e6 --- /dev/null +++ b/Task/Tokenize-a-string/Go/tokenize-a-string.go @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "Hello,How,Are,You,Today" + fmt.Println(strings.Join(strings.Split(s, ","), ".")) +} diff --git a/Task/Tokenize-a-string/Groovy/tokenize-a-string.groovy b/Task/Tokenize-a-string/Groovy/tokenize-a-string.groovy new file mode 100644 index 0000000000..0fa5962fe0 --- /dev/null +++ b/Task/Tokenize-a-string/Groovy/tokenize-a-string.groovy @@ -0,0 +1 @@ +println 'Hello,How,Are,You,Today'.split(',').join('.') diff --git a/Task/Tokenize-a-string/Haskell/tokenize-a-string-1.hs b/Task/Tokenize-a-string/Haskell/tokenize-a-string-1.hs new file mode 100644 index 0000000000..19c33eab79 --- /dev/null +++ b/Task/Tokenize-a-string/Haskell/tokenize-a-string-1.hs @@ -0,0 +1,16 @@ +splitBy :: (a -> Bool) -> [a] -> [[a]] +splitBy _ [] = [] +splitBy f list = first : splitBy f (dropWhile f rest) where + (first, rest) = break f list + +splitRegex :: Regex -> String -> [String] + +joinWith :: [a] -> [[a]] -> [a] +joinWith d xs = concat $ List.intersperse d xs +-- "concat $ intersperse" can be replaced with "intercalate" from the Data.List in GHC 6.8 and later + +putStrLn $ joinWith "." $ splitBy (== ',') $ "Hello,How,Are,You,Today" + +-- using regular expression to split: +import Text.Regex +putStrLn $ joinWith "." $ splitRegex (mkRegex ",") $ "Hello,How,Are,You,Today" diff --git a/Task/Tokenize-a-string/Haskell/tokenize-a-string-2.hs b/Task/Tokenize-a-string/Haskell/tokenize-a-string-2.hs new file mode 100644 index 0000000000..0ef04fa56d --- /dev/null +++ b/Task/Tokenize-a-string/Haskell/tokenize-a-string-2.hs @@ -0,0 +1,6 @@ +*Main> mapM_ putStrLn $ takeWhile (not.null) $ unfoldr (Just . second(drop 1). break (==',')) "Hello,How,Are,You,Today" +Hello +How +Are +You +Today diff --git a/Task/Tokenize-a-string/HicEst/tokenize-a-string.hicest b/Task/Tokenize-a-string/HicEst/tokenize-a-string.hicest new file mode 100644 index 0000000000..b25e33d62d --- /dev/null +++ b/Task/Tokenize-a-string/HicEst/tokenize-a-string.hicest @@ -0,0 +1,13 @@ +CHARACTER string="Hello,How,Are,You,Today", list + +nWords = INDEX(string, ',', 256) + 1 +maxWordLength = LEN(string) - 2*nWords +ALLOCATE(list, nWords*maxWordLength) + +DO i = 1, nWords + EDIT(Text=string, SePaRators=',', item=i, WordEnd, CoPyto=CHAR(i, maxWordLength, list)) +ENDDO + +DO i = 1, nWords + WRITE(APPend) TRIM(CHAR(i, maxWordLength, list)), '.' +ENDDO diff --git a/Task/Tokenize-a-string/Icon/tokenize-a-string.icon b/Task/Tokenize-a-string/Icon/tokenize-a-string.icon new file mode 100644 index 0000000000..f516a574ec --- /dev/null +++ b/Task/Tokenize-a-string/Icon/tokenize-a-string.icon @@ -0,0 +1,6 @@ +procedure main() + A := [] + "Hello,How,Are,You,Today" ? while put(A, 1(tab(upto(',')|0),=",")) + every writes(!A,".") + write() +end diff --git a/Task/Tokenize-a-string/Io/tokenize-a-string.io b/Task/Tokenize-a-string/Io/tokenize-a-string.io new file mode 100644 index 0000000000..dcd4c4c38b --- /dev/null +++ b/Task/Tokenize-a-string/Io/tokenize-a-string.io @@ -0,0 +1 @@ +"Hello,How,Are,You,Today" split(",") join(".") println diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-1.j b/Task/Tokenize-a-string/J/tokenize-a-string-1.j new file mode 100644 index 0000000000..6188a42ba0 --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-1.j @@ -0,0 +1,10 @@ + s=: 'Hello,How,Are,You,Today' + ] t=: <;._1 ',',s ++-----+---+---+---+-----+ +|Hello|How|Are|You|Today| ++-----+---+---+---+-----+ + ; t,&.>'.' +Hello.How.Are.You.Today. + + '.' (I.','=s)}s NB. two steps combined +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-2.j b/Task/Tokenize-a-string/J/tokenize-a-string-2.j new file mode 100644 index 0000000000..cb7408b8fa --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-2.j @@ -0,0 +1,8 @@ + require 'strings' + ',' splitstring s ++-----+---+---+---+-----+ +|Hello|How|Are|You|Today| ++-----+---+---+---+-----+ + + '.' joinstring ',' splitstring s +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-3.j b/Task/Tokenize-a-string/J/tokenize-a-string-3.j new file mode 100644 index 0000000000..5f81190eda --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-3.j @@ -0,0 +1,2 @@ + '"'([ ,~ ,) '","' joinstring ',' splitstring s +"Hello","How","Are","You","Today" diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-4.j b/Task/Tokenize-a-string/J/tokenize-a-string-4.j new file mode 100644 index 0000000000..20351945f2 --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-4.j @@ -0,0 +1,2 @@ + rplc&',.' s +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-5.j b/Task/Tokenize-a-string/J/tokenize-a-string-5.j new file mode 100644 index 0000000000..0f15952148 --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-5.j @@ -0,0 +1 @@ + fn;._2 string,',' diff --git a/Task/Tokenize-a-string/J/tokenize-a-string-6.j b/Task/Tokenize-a-string/J/tokenize-a-string-6.j new file mode 100644 index 0000000000..93186570a5 --- /dev/null +++ b/Task/Tokenize-a-string/J/tokenize-a-string-6.j @@ -0,0 +1 @@ + fn ((;._2)(@(,&','))) string diff --git a/Task/Tokenize-a-string/Java/tokenize-a-string-1.java b/Task/Tokenize-a-string/Java/tokenize-a-string-1.java new file mode 100644 index 0000000000..5e9ab80338 --- /dev/null +++ b/Task/Tokenize-a-string/Java/tokenize-a-string-1.java @@ -0,0 +1,7 @@ +String toTokenize = "Hello,How,Are,You,Today"; + +String words[] = toTokenize.split(",");//splits on one comma, multiple commas yield multiple splits + //toTokenize.split(",+") if you want to ignore empty fields +for(int i=0; i (',' )* ) -> {} (%nl / !.) + field <- / + nonescaped <- { [^,"%nl]* } + escaped <- '"' {~ ([^"] / '""' -> '"')* ~} '"' +]] + +print(unpack(record:match"hello,how,are,you,today")) diff --git a/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua b/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua new file mode 100644 index 0000000000..483cbe8a58 --- /dev/null +++ b/Task/Tokenize-a-string/Lua/tokenize-a-string-2.lua @@ -0,0 +1,10 @@ +str = "Hello,How,Are,You,Today" + +tokens = {} +for w in string.gmatch( str, "(%a+)" ) do + tokens[#tokens+1] = w +end + +for i = 1, #tokens do + print( tokens[i] ) +end diff --git a/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua b/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua new file mode 100644 index 0000000000..f778a0a11e --- /dev/null +++ b/Task/Tokenize-a-string/Lua/tokenize-a-string-3.lua @@ -0,0 +1,11 @@ +str = "Hello|How|Are|You||Today" + +tokens = {} +for w in string.gmatch( str, "([^|]*)|?" ) do + tokens[#tokens+1] = w +end +table.remove(tokens)--pops off the last empty value, because without doing |? we lose the last element. + +for i = 1, #tokens do + print( tokens[i] ) +end diff --git a/Task/Tokenize-a-string/M4/tokenize-a-string.m4 b/Task/Tokenize-a-string/M4/tokenize-a-string.m4 new file mode 100644 index 0000000000..f4ef385379 --- /dev/null +++ b/Task/Tokenize-a-string/M4/tokenize-a-string.m4 @@ -0,0 +1,11 @@ +define(`s',`Hello,How,Are,You,Today') +define(`set',`define(`$1[$2]',`$3')') +define(`get',`defn($1[$2])') +define(`n',0) +define(`fill', + `set(a,n,$1)`'define(`n',incr(n))`'ifelse(eval($#>1),1,`fill(shift($@))')') +fill(s) +define(`j',0) +define(`show', + `ifelse(eval(j> tokenizeString('Hello,How,Are,You,Today',',') +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/MAXScript/tokenize-a-string.maxscript b/Task/Tokenize-a-string/MAXScript/tokenize-a-string.maxscript new file mode 100644 index 0000000000..d01e5c3ef8 --- /dev/null +++ b/Task/Tokenize-a-string/MAXScript/tokenize-a-string.maxscript @@ -0,0 +1,6 @@ +output = "" +for word in (filterString "Hello,How,Are,You,Today" ",") do +( + output += (word + ".") +) +format "%\n" output diff --git a/Task/Tokenize-a-string/MMIX/tokenize-a-string.mmix b/Task/Tokenize-a-string/MMIX/tokenize-a-string.mmix new file mode 100644 index 0000000000..3159b2ac7b --- /dev/null +++ b/Task/Tokenize-a-string/MMIX/tokenize-a-string.mmix @@ -0,0 +1,54 @@ +sep IS ',' +EOS IS 0 +NL IS 10 + +// main registers +p IS $255 +tp GREG +c GREG +t GREG + + LOC Data_Segment + GREG @ +Text BYTE "Hello,How,Are,You,Today",EOS +token BYTE 0 +eot IS @+255 + + LOC #100 % main () { +Main LDA p,Text % + LDA tp,token % initialize pointers +2H LDBU c,p % DO get char + BZ c,5F % break if char == EOS + CMP t,c,sep % if char != sep then + PBNZ t,3F % store char + SET t,NL % terminate token with NL,EOS + STBU t,tp + SET t,EOS + INCL tp,1 + STBU t,tp + JMP 4F % continue + +3H STBU c,tp % store char +4H INCL tp,1 % update pointers + INCL p,1 + JMP 2B % LOOP + +5H SET t,NL % terminate last token and buffer + STBU t,tp + SET t,EOS + INCL tp,1 + STBU t,tp +% next part is not really necessary +% program runs only once +% INCL tp,1 % terminate buffer +% STBU t,tp + + LDA tp,token % reset token pointer + % REPEAT +2H ADD p,tp,0 % start of token + TRAP 0,Fputs,StdOut % output token + ADD tp,tp,p + INCL tp,1 % step to next token + LDBU t,tp + PBNZ t,2B % UNTIL EOB(uffer) + TRAP 0,Halt,0 diff --git a/Task/Tokenize-a-string/MUMPS/tokenize-a-string.mumps b/Task/Tokenize-a-string/MUMPS/tokenize-a-string.mumps new file mode 100644 index 0000000000..84c28480d9 --- /dev/null +++ b/Task/Tokenize-a-string/MUMPS/tokenize-a-string.mumps @@ -0,0 +1,7 @@ +TOKENS + NEW I,J,INP + SET INP="Hello,how,are,you,today" + NEW I FOR I=1:1:$LENGTH(INP,",") SET INP(I)=$PIECE(INP,",",I) + NEW J FOR J=1:1:I WRITE INP(J) WRITE:J'=I "." + KILL I,J,INP // Kill is optional. "New" variables automatically are killed on "Quit" + QUIT diff --git a/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math b/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math new file mode 100644 index 0000000000..437d948d7f --- /dev/null +++ b/Task/Tokenize-a-string/Mathematica/tokenize-a-string.math @@ -0,0 +1 @@ +Row[Riffle[StringSplit["Hello,How,Are,You,Today", ","], "."]] diff --git a/Task/Tokenize-a-string/Mercury/tokenize-a-string.mercury b/Task/Tokenize-a-string/Mercury/tokenize-a-string.mercury new file mode 100644 index 0000000000..f983c131aa --- /dev/null +++ b/Task/Tokenize-a-string/Mercury/tokenize-a-string.mercury @@ -0,0 +1,13 @@ +:- module string_tokenize. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module list, string. + +main(!IO) :- + Tokens = string.split_at_char((','), "Hello,How,Are,You,Today"), + io.write_list(Tokens, ".", io.write_string, !IO), + io.nl(!IO). diff --git a/Task/Tokenize-a-string/Modula-3/tokenize-a-string.mod3 b/Task/Tokenize-a-string/Modula-3/tokenize-a-string.mod3 new file mode 100644 index 0000000000..9a11e11936 --- /dev/null +++ b/Task/Tokenize-a-string/Modula-3/tokenize-a-string.mod3 @@ -0,0 +1,18 @@ +MODULE Tokenize EXPORTS Main; + +IMPORT IO, TextConv; + +TYPE Texts = REF ARRAY OF TEXT; + +VAR tokens: Texts; + string := "Hello,How,Are,You,Today"; + sep := SET OF CHAR {','}; + +BEGIN + tokens := NEW(Texts, TextConv.ExplodedSize(string, sep)); + TextConv.Explode(string, tokens^, sep); + FOR i := FIRST(tokens^) TO LAST(tokens^) DO + IO.Put(tokens[i] & "."); + END; + IO.Put("\n"); +END Tokenize. diff --git a/Task/Tokenize-a-string/Nemerle/tokenize-a-string.nemerle b/Task/Tokenize-a-string/Nemerle/tokenize-a-string.nemerle new file mode 100644 index 0000000000..a2903bb6c9 --- /dev/null +++ b/Task/Tokenize-a-string/Nemerle/tokenize-a-string.nemerle @@ -0,0 +1,14 @@ +using System; +using System.Console; +using Nemerle.Utility.NString; + +module Tokenize +{ + Main() : void + { + def cswords = "Hello,How,Are,You,Today"; + WriteLine(Concat(".", $[s | s in cswords.Split(',')])); + // Split() produces an array while Concat() consumes a list + // a quick in place list comprehension takes care of that + } +} diff --git a/Task/Tokenize-a-string/NetRexx/tokenize-a-string.netrexx b/Task/Tokenize-a-string/NetRexx/tokenize-a-string.netrexx new file mode 100644 index 0000000000..ad2f83b1f9 --- /dev/null +++ b/Task/Tokenize-a-string/NetRexx/tokenize-a-string.netrexx @@ -0,0 +1,12 @@ +/*NetRexx program ***************************************************** +* 20.08.2012 Walter Pachl derived from REXX Version 3 +**********************************************************************/ + sss='Hello,How,Are,You,Today' + Say 'input string='sss + Say '' + Say 'Words in the string:' + ss =sss.translate(' ',',') + Loop i=1 To ss.words() + Say ss.word(i)'.' + End + Say 'End-of-list.' diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml new file mode 100644 index 0000000000..30642eda82 --- /dev/null +++ b/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml @@ -0,0 +1,7 @@ +let rec split_char sep str = + try + let i = String.index str sep in + String.sub str 0 i :: + split_char sep (String.sub str (i+1) (String.length str - i - 1)) + with Not_found -> + [str] diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml new file mode 100644 index 0000000000..129aaaa54b --- /dev/null +++ b/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml @@ -0,0 +1,18 @@ +(* [try .. with] structures break tail-recursion, + so we externalise it in a sub-function *) +let string_index str c = + try Some(String.index str c) + with Not_found -> None + +let split_char sep str = + let rec aux acc str = + match string_index str sep with + | Some i -> + let this = String.sub str 0 i + and next = String.sub str (i+1) (String.length str - i - 1) in + aux (this::acc) next + | None -> + List.rev(str::acc) + in + aux [] str +;; diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml new file mode 100644 index 0000000000..1ddf66f256 --- /dev/null +++ b/Task/Tokenize-a-string/OCaml/tokenize-a-string-3.ocaml @@ -0,0 +1,14 @@ +let split_char sep str = + let string_index_from i = + try Some (String.index_from str i sep) + with Not_found -> None + in + let rec aux i acc = match string_index_from i with + | Some i' -> + let w = String.sub str i (i' - i) in + aux (succ i') (w::acc) + | None -> + let w = String.sub str i (String.length str - i) in + List.rev (w::acc) + in + aux 0 [] diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml new file mode 100644 index 0000000000..7b58650f99 --- /dev/null +++ b/Task/Tokenize-a-string/OCaml/tokenize-a-string-4.ocaml @@ -0,0 +1,3 @@ +#load "str.cma";; +let split_str sep str = + Str.split (Str.regexp_string sep) str diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml new file mode 100644 index 0000000000..6689860ed7 --- /dev/null +++ b/Task/Tokenize-a-string/OCaml/tokenize-a-string-5.ocaml @@ -0,0 +1 @@ +String.concat sep strings diff --git a/Task/Tokenize-a-string/Objeck/tokenize-a-string.objeck b/Task/Tokenize-a-string/Objeck/tokenize-a-string.objeck new file mode 100644 index 0000000000..4dcd14c9bc --- /dev/null +++ b/Task/Tokenize-a-string/Objeck/tokenize-a-string.objeck @@ -0,0 +1,10 @@ +bundle Default { + class Parse { + function : Main(args : String[]) ~ Nil { + tokens := "Hello,How,Are,You,Today"->Split(","); + each(i : tokens) { + tokens[i]->PrintLine(); + }; + } + } +} diff --git a/Task/Tokenize-a-string/Objective-C/tokenize-a-string.m b/Task/Tokenize-a-string/Objective-C/tokenize-a-string.m new file mode 100644 index 0000000000..0e9f00f367 --- /dev/null +++ b/Task/Tokenize-a-string/Objective-C/tokenize-a-string.m @@ -0,0 +1,4 @@ +NSString *text = @"Hello,How,Are,You,Today"; +NSArray *tokens = [text componentsSeparatedByString:@","]; +NSString *result = [tokens componentsJoinedByString:@"."]; +NSLog(result); diff --git a/Task/Tokenize-a-string/OpenEdge-Progress/tokenize-a-string.openedge b/Task/Tokenize-a-string/OpenEdge-Progress/tokenize-a-string.openedge new file mode 100644 index 0000000000..c0a66593bf --- /dev/null +++ b/Task/Tokenize-a-string/OpenEdge-Progress/tokenize-a-string.openedge @@ -0,0 +1,24 @@ +FUNCTION tokenizeString RETURNS CHAR ( + i_c AS CHAR +): + + DEF VAR ii AS INT. + DEF VAR carray AS CHAR EXTENT. + DEF VAR cresult AS CHAR. + + EXTENT( carray ) = NUM-ENTRIES( i_c ). + + DO ii = 1 TO NUM-ENTRIES( i_c ): + carray[ ii ] = ENTRY( ii, i_c ). + END. + + DO ii = 1 TO EXTENT( carray ). + cresult = cresult + "." + carray[ ii ]. + END. + RETURN SUBSTRING( cresult, 2 ). + +END FUNCTION. /* tokenizeString */ + +MESSAGE + tokenizeString( "Hello,How,Are,You,Today" ) +VIEW-AS ALERT-BOX. diff --git a/Task/Tokenize-a-string/Oz/tokenize-a-string.oz b/Task/Tokenize-a-string/Oz/tokenize-a-string.oz new file mode 100644 index 0000000000..d4eefe8e07 --- /dev/null +++ b/Task/Tokenize-a-string/Oz/tokenize-a-string.oz @@ -0,0 +1,3 @@ +for T in {String.tokens "Hello,How,Are,You,Today" &,} do + {System.printInfo T#"."} +end diff --git a/Task/Tokenize-a-string/PHP/tokenize-a-string.php b/Task/Tokenize-a-string/PHP/tokenize-a-string.php new file mode 100644 index 0000000000..9cb483dbb1 --- /dev/null +++ b/Task/Tokenize-a-string/PHP/tokenize-a-string.php @@ -0,0 +1,4 @@ + diff --git a/Task/Tokenize-a-string/PL-I/tokenize-a-string.pli b/Task/Tokenize-a-string/PL-I/tokenize-a-string.pli new file mode 100644 index 0000000000..3b32c439fd --- /dev/null +++ b/Task/Tokenize-a-string/PL-I/tokenize-a-string.pli @@ -0,0 +1,21 @@ +declare s character (100) initial ('Hello,How,Are,You,Today'); +declare n fixed binary (31); + +n = tally(s, ',')+1; + +begin; + declare table(n) character (50) varying; + declare c character (1); + declare (i, k) fixed binary (31); + + table = ''; k = 1; + do i = 1 to length(s); + c = substr(s, i, 1); + if c = ',' then k = k + 1; + else table(k) = table(k) || c; + end; + + /* display the table */ + table = table || '.'; + put skip list (string(table)); +end; diff --git a/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal b/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal new file mode 100644 index 0000000000..12e4f35e85 --- /dev/null +++ b/Task/Tokenize-a-string/Pascal/tokenize-a-string.pascal @@ -0,0 +1,17 @@ +program TokenizeString; + +{$mode objfpc}{$H+} + +const + CHelloStr = 'Hello,How,Are,You,Today'; +var + I: Integer; + VResult: string = ''; +begin + for I := 1 to Length(CHelloStr) do + if CHelloStr[I] = ',' then + VResult += LineEnding + else + VResult += CHelloStr[I]; + WriteLn(VResult); +end. diff --git a/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 b/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 new file mode 100644 index 0000000000..92481405f3 --- /dev/null +++ b/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 @@ -0,0 +1 @@ +'Hello,How,Are,You,Today'.split(',').join('.').say; diff --git a/Task/Tokenize-a-string/Perl/tokenize-a-string.pl b/Task/Tokenize-a-string/Perl/tokenize-a-string.pl new file mode 100644 index 0000000000..8432201e19 --- /dev/null +++ b/Task/Tokenize-a-string/Perl/tokenize-a-string.pl @@ -0,0 +1 @@ +print join('.', split /,/, 'Hello,How,Are,You,Today'), "\n"; diff --git a/Task/Tokenize-a-string/PicoLisp/tokenize-a-string.l b/Task/Tokenize-a-string/PicoLisp/tokenize-a-string.l new file mode 100644 index 0000000000..ec7f37a818 --- /dev/null +++ b/Task/Tokenize-a-string/PicoLisp/tokenize-a-string.l @@ -0,0 +1,2 @@ +(mapcar pack + (split (chop "Hello,How,Are,You,Today") ",") ) diff --git a/Task/Tokenize-a-string/Pike/tokenize-a-string.pike b/Task/Tokenize-a-string/Pike/tokenize-a-string.pike new file mode 100644 index 0000000000..43bc508bd8 --- /dev/null +++ b/Task/Tokenize-a-string/Pike/tokenize-a-string.pike @@ -0,0 +1 @@ +("Hello,How,Are,You,Today" / ",") * "."; diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-1.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-1.pop11 new file mode 100644 index 0000000000..461519941c --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-1.pop11 @@ -0,0 +1,6 @@ +;;; Make a list of strings from a string using space as separator +lvars list; +sysparse_string('the cat sat on the mat') -> list; +;;; print the list of strings +list => +** [the cat sat on the mat] diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-2.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-2.pop11 new file mode 100644 index 0000000000..54a2cbe61c --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-2.pop11 @@ -0,0 +1,10 @@ +lvars list; +sysparse_string('one 1 two 2 three 3 four 4', true) -> list; +;;; print the list of strings and numbers +list => +** [one 1 two 2 three 3 four 4] +;;; check that first item is a string and second an integer +isstring(list(1))=> +** +isinteger(list(2))=> +** diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-3.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-3.pop11 new file mode 100644 index 0000000000..ffba01d141 --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-3.pop11 @@ -0,0 +1,15 @@ +;;; Make pop-11 print strings with quotes +true -> pop_pr_quotes; +;;; +;;; Create a string of tokens using comma as token separator +lvars str='Hello,How,Are,You,Today'; +;;; +;;; Make a list of strings by applying sys_parse_string +;;; to str, using the character `,` as separator (the default +;;; separator, if none is provided, is the space character). +lvars strings; +[% sys_parse_string(str, `,`) %] -> strings; +;;; +;;; print the list of strings +strings => +** ['Hello' 'How' 'Are' 'You' 'Today'] diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-4.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-4.pop11 new file mode 100644 index 0000000000..9e273be694 --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-4.pop11 @@ -0,0 +1,4 @@ +{% sys_parse_string(str, `,`) %} -> strings; +;;; print the vector +strings => +** {'Hello' 'How' 'Are' 'You' 'Today'} diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-5.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-5.pop11 new file mode 100644 index 0000000000..00c166ce9a --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-5.pop11 @@ -0,0 +1,6 @@ +lvars numbers; +{% sys_parse_string('100 101 102 103 99.9 99.999', strnumber) %} -> numbers; +;;; the result is a vector containing integers and floats, +;;; which can be printed thus: +numbers => +** {100 101 102 103 99.9 99.999} diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-6.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-6.pop11 new file mode 100644 index 0000000000..3131959e84 --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-6.pop11 @@ -0,0 +1,18 @@ +;;; Declare and initialize variables +lvars str='Hello,How,Are,You,Today'; +;;; Iterate over string +lvars ls = [], i, j = 1; +for i from 1 to length(str) do + ;;; If comma + if str(i) = `,` then + ;;; Prepend word (substring) to list + cons(substring(j, i - j, str), ls) -> ls; + i + 1 -> j; + endif; +endfor; +;;; Prepend final word (if needed) +if j <= length(str) then + cons(substring(j, length(str) - j + 1, str), ls) -> ls; +endif; +;;; Reverse the list +rev(ls) -> ls; diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-7.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-7.pop11 new file mode 100644 index 0000000000..46baa965f6 --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-7.pop11 @@ -0,0 +1,9 @@ +;;; Put list elements and lenght on the stack +destlist(ls); +;;; Build a vector from them +lvars ar = consvector(); +;;; Display in a loop, putting trailing period +for i from 1 to length(ar) do + printf(ar(i), '%s.'); +endfor; +printf('\n'); diff --git a/Task/Tokenize-a-string/Pop11/tokenize-a-string-8.pop11 b/Task/Tokenize-a-string/Pop11/tokenize-a-string-8.pop11 new file mode 100644 index 0000000000..2f3083f363 --- /dev/null +++ b/Task/Tokenize-a-string/Pop11/tokenize-a-string-8.pop11 @@ -0,0 +1,3 @@ +for i in ls do + printf(i, '%s.'); +endfor; diff --git a/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic b/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic new file mode 100644 index 0000000000..2f5dbd573f --- /dev/null +++ b/Task/Tokenize-a-string/PowerBASIC/tokenize-a-string.powerbasic @@ -0,0 +1,15 @@ +FUNCTION PBMAIN () AS LONG + DIM parseMe AS STRING + parseMe = "Hello,How,Are,You,Today" + + REDIM parsed(PARSECOUNT(parseMe) - 1) AS STRING + PARSE parseMe, parsed() 'comma is default delimiter + + DIM L0 AS LONG, outP AS STRING + outP = parsed(0) + FOR L0 = 1 TO UBOUND(parsed) 'could reuse parsecount instead of ubound + outP = outP & "." & parsed(L0) + NEXT + + MSGBOX outP +END FUNCTION diff --git a/Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh new file mode 100644 index 0000000000..fc961f3ef2 --- /dev/null +++ b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh @@ -0,0 +1,2 @@ +$words = "Hello,How,Are,You,Today".Split(',') +[string]::Join('.', $words) diff --git a/Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh new file mode 100644 index 0000000000..f0f6a98b08 --- /dev/null +++ b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh @@ -0,0 +1,2 @@ +$words = "Hello,How,Are,You,Today" -split ',' +$words -join '.' diff --git a/Task/Tokenize-a-string/Prolog/tokenize-a-string.pro b/Task/Tokenize-a-string/Prolog/tokenize-a-string.pro new file mode 100644 index 0000000000..20a2da0a36 --- /dev/null +++ b/Task/Tokenize-a-string/Prolog/tokenize-a-string.pro @@ -0,0 +1,9 @@ +splitup(Sep,[token(B)|BL]) --> splitup(Sep,B,BL). +splitup(Sep,[A|AL],B) --> [A], {\+ [A] = Sep }, splitup(Sep,AL,B). +splitup(Sep,[],[B|BL]) --> Sep, splitup(Sep,B,BL). +splitup(_Sep,[],[]) --> []. +start :- + phrase(splitup(",",Tokens),"Hello,How,Are,You,Today"), + phrase(splitup(".",Tokens),Backtogether), + string_to_list(ABack,Backtogether), + writeln(ABack). diff --git a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic new file mode 100644 index 0000000000..28e4e237da --- /dev/null +++ b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-1.purebasic @@ -0,0 +1,10 @@ +NewList MyStrings.s() + +For i=1 To 5 + AddElement(MyStrings()) + MyStrings()=StringField("Hello,How,Are,You,Today",i,",") +Next i + +ForEach MyStrings() + Print(MyStrings()+".") +Next diff --git a/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic new file mode 100644 index 0000000000..c68564a14c --- /dev/null +++ b/Task/Tokenize-a-string/PureBasic/tokenize-a-string-2.purebasic @@ -0,0 +1 @@ +Print(ReplaceString("Hello,How,Are,You,Today",",",".")) diff --git a/Task/Tokenize-a-string/Python/tokenize-a-string-1.py b/Task/Tokenize-a-string/Python/tokenize-a-string-1.py new file mode 100644 index 0000000000..f1475a2c31 --- /dev/null +++ b/Task/Tokenize-a-string/Python/tokenize-a-string-1.py @@ -0,0 +1,3 @@ +text = "Hello,How,Are,You,Today" +tokens = text.split(',') +print ('.'.join(tokens)) diff --git a/Task/Tokenize-a-string/Python/tokenize-a-string-2.py b/Task/Tokenize-a-string/Python/tokenize-a-string-2.py new file mode 100644 index 0000000000..4431d582c7 --- /dev/null +++ b/Task/Tokenize-a-string/Python/tokenize-a-string-2.py @@ -0,0 +1 @@ +print ('.'.join('Hello,How,Are,You,Today'.split(','))) diff --git a/Task/Tokenize-a-string/R/tokenize-a-string-1.r b/Task/Tokenize-a-string/R/tokenize-a-string-1.r new file mode 100644 index 0000000000..ebdb7f51d2 --- /dev/null +++ b/Task/Tokenize-a-string/R/tokenize-a-string-1.r @@ -0,0 +1,3 @@ +text <- "Hello,How,Are,You,Today" +junk <- strsplit(text, split=",") +print(paste(unlist(junk), collapse=".")) diff --git a/Task/Tokenize-a-string/R/tokenize-a-string-2.r b/Task/Tokenize-a-string/R/tokenize-a-string-2.r new file mode 100644 index 0000000000..0a89571945 --- /dev/null +++ b/Task/Tokenize-a-string/R/tokenize-a-string-2.r @@ -0,0 +1 @@ +paste(unlist(strsplit(text, split=",")), collapse=".") diff --git a/Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol b/Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol new file mode 100644 index 0000000000..d4ee77b866 --- /dev/null +++ b/Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol @@ -0,0 +1,4 @@ +print ["Original:" original: "Hello,How,Are,You,Today"] +tokens: parse original "," +dotted: "" repeat i tokens [append dotted rejoin [i "."]] +print ["Dotted: " dotted] diff --git a/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx new file mode 100644 index 0000000000..a9ecce8af8 --- /dev/null +++ b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx @@ -0,0 +1,17 @@ +/*REXX program to seperate a string of comma-delimited words, and echo. */ +sss = 'Hello,How,Are,You,Today' /*words seperated by commas (,). */ +say 'input string='sss /*display the original string. */ +new=sss /*make a copy of the string. */ + + do items=1 until new=='' /*keep going until SSS is empty. */ + parse var new a.items ',' new /*parse words delinated by comma.*/ + end /*items*/ + +say; say 'Words in the string:' /*display a header for the list. */ + + do k=1 for items /*now, display all the words. */ + say a.k'.' /*append a period to the word. */ + end /*k*/ + +say 'End-of-list.' /*display a trailer for the list.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Tokenize-a-string/REXX/tokenize-a-string-2.rexx b/Task/Tokenize-a-string/REXX/tokenize-a-string-2.rexx new file mode 100644 index 0000000000..e3549311d6 --- /dev/null +++ b/Task/Tokenize-a-string/REXX/tokenize-a-string-2.rexx @@ -0,0 +1,10 @@ +/*REXX program to separate a string of comma-delimited words and echo */ +sss='Hello,How,Are,You,Today' +say 'input string='sss +say '' +say 'Words in the string:' +ss =translate(sss,' ',',') +Do i=1 To words(ss) + say word(ss,i)'.' + End +say 'End-of-list.' diff --git a/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt b/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt new file mode 100644 index 0000000000..4cba4cd412 --- /dev/null +++ b/Task/Tokenize-a-string/Racket/tokenize-a-string.rkt @@ -0,0 +1,5 @@ +#lang racket + +(for ([s (regexp-split #rx"," "Hello,How,Are,You,Today")]) + (printf "~a." s)) +(newline) diff --git a/Task/Tokenize-a-string/Raven/tokenize-a-string.raven b/Task/Tokenize-a-string/Raven/tokenize-a-string.raven new file mode 100644 index 0000000000..4634105d3c --- /dev/null +++ b/Task/Tokenize-a-string/Raven/tokenize-a-string.raven @@ -0,0 +1 @@ +'Hello,How,Are,You,Today' ',' split '.' join print diff --git a/Task/Tokenize-a-string/Retro/tokenize-a-string-1.retro b/Task/Tokenize-a-string/Retro/tokenize-a-string-1.retro new file mode 100644 index 0000000000..1f2c1a5495 --- /dev/null +++ b/Task/Tokenize-a-string/Retro/tokenize-a-string-1.retro @@ -0,0 +1,13 @@ +{{ + : char ( -$ ) " " ; + : tokenize ( $-$$ ) + @char ^strings'splitAtChar withLength 1- over + 0 swap ! tempString ; + : action ( $- ) + keepString ^buffer'add ; +---reveal--- + : split ( $cb- ) + ^buffer'set !char + char ^strings'append + [ tokenize action dup 1 <> ] while drop + ^buffer'get drop ; +}} diff --git a/Task/Tokenize-a-string/Retro/tokenize-a-string-2.retro b/Task/Tokenize-a-string/Retro/tokenize-a-string-2.retro new file mode 100644 index 0000000000..d6e97e636b --- /dev/null +++ b/Task/Tokenize-a-string/Retro/tokenize-a-string-2.retro @@ -0,0 +1,2 @@ +create strings 100 allot +"Hello,How,Are,You,Today" ', strings split diff --git a/Task/Tokenize-a-string/Retro/tokenize-a-string-3.retro b/Task/Tokenize-a-string/Retro/tokenize-a-string-3.retro new file mode 100644 index 0000000000..9bde72cc77 --- /dev/null +++ b/Task/Tokenize-a-string/Retro/tokenize-a-string-3.retro @@ -0,0 +1 @@ +strings [ @ "%s." puts ] ^types'STRING each@ diff --git a/Task/Tokenize-a-string/Ruby/tokenize-a-string.rb b/Task/Tokenize-a-string/Ruby/tokenize-a-string.rb new file mode 100644 index 0000000000..565980a2d7 --- /dev/null +++ b/Task/Tokenize-a-string/Ruby/tokenize-a-string.rb @@ -0,0 +1 @@ +puts "Hello,How,Are,You,Today".split(',').join('.') diff --git a/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run b/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run new file mode 100644 index 0000000000..7c11088ae7 --- /dev/null +++ b/Task/Tokenize-a-string/Run-BASIC/tokenize-a-string.run @@ -0,0 +1,5 @@ +text$ = "Hello,How,Are,You,Today" +FOR i = 1 to 5 + textArray$(i) = word$(text$,i,",") + print textArray$(i);" "; +NEXT diff --git a/Task/Tokenize-a-string/SNOBOL4/tokenize-a-string.sno b/Task/Tokenize-a-string/SNOBOL4/tokenize-a-string.sno new file mode 100644 index 0000000000..959ee0403a --- /dev/null +++ b/Task/Tokenize-a-string/SNOBOL4/tokenize-a-string.sno @@ -0,0 +1,17 @@ + define('split(chs,str)i,j,t,w2') :(split_end) +split t = table() +sp1 str pos(0) (break(chs) | rem) $ t ++ span(chs) (break(chs) | '') . w2 = w2 :s(sp1) +* t = differ(str,'') str ;* Uncomment for CSnobol + split = array(i) +sp2 split = t :s(sp2)f(return) +split_end + + define('join(ch,a)i,') :(join_end) +join join = join a + join = join ?a ch :s(join)f(return) +join_end + +* # Test and display + output = join('.',split(',','Hello,How,Are,You,Today')) +end diff --git a/Task/Tokenize-a-string/Scala/tokenize-a-string.scala b/Task/Tokenize-a-string/Scala/tokenize-a-string.scala new file mode 100644 index 0000000000..6ca513c7b9 --- /dev/null +++ b/Task/Tokenize-a-string/Scala/tokenize-a-string.scala @@ -0,0 +1 @@ +println("Hello,How,Are,You,Today" split "," mkString ".") diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss new file mode 100644 index 0000000000..b7f86c3456 --- /dev/null +++ b/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss @@ -0,0 +1,8 @@ +(use-modules (ice-9 regex)) +(define s "Hello,How,Are,You,Today") +(define words (map match:substring (list-matches "[^,]+" s))) + +(do ((n 0 (+ n 1))) ((= n (length words))) + (display (list-ref words n)) + (if (< n (- (length words) 1)) + (display "."))) diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss new file mode 100644 index 0000000000..7ac82ff81b --- /dev/null +++ b/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss @@ -0,0 +1,3 @@ +(define s "Hello,How,Are,You,Today") +(define words (string-tokenize s (char-set-complement (char-set #\,)))) +(define t (string-join words ".")) diff --git a/Task/Tokenize-a-string/Seed7/tokenize-a-string.seed7 b/Task/Tokenize-a-string/Seed7/tokenize-a-string.seed7 new file mode 100644 index 0000000000..9bbcf24c06 --- /dev/null +++ b/Task/Tokenize-a-string/Seed7/tokenize-a-string.seed7 @@ -0,0 +1,3 @@ +var array string: tokens is 0 times ""; + +tokens := split("Hello,How,Are,You,Today", ","); diff --git a/Task/Tokenize-a-string/Slate/tokenize-a-string.slate b/Task/Tokenize-a-string/Slate/tokenize-a-string.slate new file mode 100644 index 0000000000..30f078d2a7 --- /dev/null +++ b/Task/Tokenize-a-string/Slate/tokenize-a-string.slate @@ -0,0 +1 @@ +('Hello,How,Are,You,Today' splitWith: $,) join &separator: '.'. diff --git a/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-1.st b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-1.st new file mode 100644 index 0000000000..e7315b7754 --- /dev/null +++ b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-1.st @@ -0,0 +1,3 @@ +|array | +array := 'Hello,How,Are,You,Today' subStrings: $,. +array fold: [:concatenation :string | concatenation, '.', string ] diff --git a/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-2.st b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-2.st new file mode 100644 index 0000000000..0ecb37b862 --- /dev/null +++ b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-2.st @@ -0,0 +1 @@ +('Hello,How,Are,You,Today' subStrings: $,) join: '.' diff --git a/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-3.st b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-3.st new file mode 100644 index 0000000000..92dae2d724 --- /dev/null +++ b/Task/Tokenize-a-string/Smalltalk/tokenize-a-string-3.st @@ -0,0 +1,3 @@ +|array | +array := 'Hello,How,Are,You,Today' subStrings: $,. +array inject: '' into: [:concatenation :string | concatenation, string, '.' ] diff --git a/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-1.ml b/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-1.ml new file mode 100644 index 0000000000..a23579b4a8 --- /dev/null +++ b/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-1.ml @@ -0,0 +1,2 @@ +val splitter = String.tokens (fn c => c = #","); +val main = (String.concatWith ".") o splitter; diff --git a/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-2.ml b/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-2.ml new file mode 100644 index 0000000000..8774eb97d5 --- /dev/null +++ b/Task/Tokenize-a-string/Standard-ML/tokenize-a-string-2.ml @@ -0,0 +1,2 @@ +- main "Hello,How,Are,You,Today" +val it = "Hello.How.Are.You.Today" : string diff --git a/Task/Tokenize-a-string/TUSCRIPT/tokenize-a-string.tuscript b/Task/Tokenize-a-string/TUSCRIPT/tokenize-a-string.tuscript new file mode 100644 index 0000000000..7ba04e629c --- /dev/null +++ b/Task/Tokenize-a-string/TUSCRIPT/tokenize-a-string.tuscript @@ -0,0 +1,4 @@ +$$ MODE TUSCRIPT +SET string="Hello,How,Are,You,Today" +SET string=SPLIT (string,":,:") +SET string=JOIN (string,".") diff --git a/Task/Tokenize-a-string/TXR/tokenize-a-string-1.txr b/Task/Tokenize-a-string/TXR/tokenize-a-string-1.txr new file mode 100644 index 0000000000..34a552e8d8 --- /dev/null +++ b/Task/Tokenize-a-string/TXR/tokenize-a-string-1.txr @@ -0,0 +1,5 @@ +@(next :list "Hello,How,Are,You,Today") +@(coll)@{token /[^,]+/}@(end) +@(output) +@(rep)@token.@(last)@token@(end) +@(end) diff --git a/Task/Tokenize-a-string/TXR/tokenize-a-string-2.txr b/Task/Tokenize-a-string/TXR/tokenize-a-string-2.txr new file mode 100644 index 0000000000..86211c314f --- /dev/null +++ b/Task/Tokenize-a-string/TXR/tokenize-a-string-2.txr @@ -0,0 +1,5 @@ +@(next :list "Hello,How,Are,You,Today") +@(coll)@(maybe)@token,@(or)@token@(end)@(end) +@(output) +@(rep)@token.@(last)@token@(end) +@(end) diff --git a/Task/Tokenize-a-string/TXR/tokenize-a-string-3.txr b/Task/Tokenize-a-string/TXR/tokenize-a-string-3.txr new file mode 100644 index 0000000000..fd859c6598 --- /dev/null +++ b/Task/Tokenize-a-string/TXR/tokenize-a-string-3.txr @@ -0,0 +1 @@ +@(bind result @(cat-str (split-str "Hello,How,Are,You,Today" ",") ".")) diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl new file mode 100644 index 0000000000..df0ca51b5f --- /dev/null +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl @@ -0,0 +1 @@ +split $string "," diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl new file mode 100644 index 0000000000..7a5e8feca2 --- /dev/null +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl @@ -0,0 +1 @@ +join $list "." diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl new file mode 100644 index 0000000000..8e516c254a --- /dev/null +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl @@ -0,0 +1 @@ +puts [join [split "Hello,How,Are,You,Today" ","] "."] diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl new file mode 100644 index 0000000000..44b4bd0ec8 --- /dev/null +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl @@ -0,0 +1 @@ +puts [join [set words [split "Hello,How,Are,You,Today" ","]] "."] diff --git a/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-1.sh b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-1.sh new file mode 100644 index 0000000000..23ed978550 --- /dev/null +++ b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-1.sh @@ -0,0 +1,5 @@ +string='Hello,How,Are,You,Today' + +(IFS=, + printf '%s.' $string + echo) diff --git a/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-2.sh b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-2.sh new file mode 100644 index 0000000000..0e8e095121 --- /dev/null +++ b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-2.sh @@ -0,0 +1,58 @@ +#! /bin/bash +stripchar-l () +#removes the specified character from the left side of the string +#USAGE: stripchar "stuff" "s" --> tuff +{ + string="$1"; + string=${string#"$2"}; + + echo "$string" +} + +join () +#join a string of characters on a specified delimiter +#USAGE: join "1;2;3;4" ";" "," --> 1,2,3,4 +{ + local result=""; + local list="$1"; + OLDIFS="$IFS"; + local IFS=${2-" "}; + local output_field_seperator=${3-" "}; + + for element in $list; + do + result="$result$output_field_seperator$element"; + done; + + result="`stripchar-l "$result" "$output_field_seperator"`"; + echo "$result"; + IFS="$OLDIFS" +} + +split () +{ +#split a string of characters on a specified delimiter +#USAGE: split "1;2;3;4" ";" --> 1 2 3 4 + local list="$1"; + local input_field_seperator=${2-" "}; + local output_field_seperator=" "; + + #defined in terms of join + join "$list" "$input_field_seperator" "$output_field_seperator" +} + +strtokenize () +{ +#splits up a string of characters into tokens, +#based on a user supplied delimiter +#USAGE:strtokenize "1;2;3;4" ";" ":" --> 1:2:3:4 + local list="$1"; + local input_delimiter=${2-" "}; + local output_delimiter=${3-" "}; + local contains_a_space=" "; #added to highlight the use + #of " " as an argument to join + + #splits it input then joins it with a user supplied delimiter + join "$( split "$list" "$input_delimiter" )" \ + "$contains_a_space" "$output_delimiter"; +} diff --git a/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-3.sh b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-3.sh new file mode 100644 index 0000000000..a420c75680 --- /dev/null +++ b/Task/Tokenize-a-string/UNIX-Shell/tokenize-a-string-3.sh @@ -0,0 +1,2 @@ + strtokenize "Hello,How,Are,You,Today" "," "." + Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/UnixPipes/tokenize-a-string.unixpipes b/Task/Tokenize-a-string/UnixPipes/tokenize-a-string.unixpipes new file mode 100644 index 0000000000..7c1d1e2e1d --- /dev/null +++ b/Task/Tokenize-a-string/UnixPipes/tokenize-a-string.unixpipes @@ -0,0 +1,5 @@ +token() { + (IFS=, read -r A B; echo "$A".; test -n "$B" && (echo "$B" | token)) +} + +echo "Hello,How,Are,You" | token diff --git a/Task/Tokenize-a-string/Ursala/tokenize-a-string.ursala b/Task/Tokenize-a-string/Ursala/tokenize-a-string.ursala new file mode 100644 index 0000000000..cb1601a145 --- /dev/null +++ b/Task/Tokenize-a-string/Ursala/tokenize-a-string.ursala @@ -0,0 +1,7 @@ +#import std + +token_list = sep`, 'Hello,How,Are,You,Today' + +#cast %s + +main = mat`. token_list diff --git a/Task/Tokenize-a-string/VBScript/tokenize-a-string.vbscript b/Task/Tokenize-a-string/VBScript/tokenize-a-string.vbscript new file mode 100644 index 0000000000..2e5b6a5fa3 --- /dev/null +++ b/Task/Tokenize-a-string/VBScript/tokenize-a-string.vbscript @@ -0,0 +1 @@ +WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".") diff --git a/Task/Tokenize-a-string/Vala/tokenize-a-string.vala b/Task/Tokenize-a-string/Vala/tokenize-a-string.vala new file mode 100644 index 0000000000..086c8b6483 --- /dev/null +++ b/Task/Tokenize-a-string/Vala/tokenize-a-string.vala @@ -0,0 +1,6 @@ +// declare test string +string s = "Hello,How,Are,You,Today"; +// create array of strings, could use var words instead if desired +string[] words = s.split(","); +// create string by joining array of strings with . +string joined = string.joinv(".", words); diff --git a/Task/Tokenize-a-string/Vedit-macro-language/tokenize-a-string.vedit b/Task/Tokenize-a-string/Vedit-macro-language/tokenize-a-string.vedit new file mode 100644 index 0000000000..40db5efe1f --- /dev/null +++ b/Task/Tokenize-a-string/Vedit-macro-language/tokenize-a-string.vedit @@ -0,0 +1,20 @@ +Buf_Switch(Buf_Free) +Ins_Text("Hello,How,Are,You,Today") + +// Split the text into text registers 10, 11, ... +BOF +#1 = 9 +Repeat(ALL) { + #1++ + #2 = Cur_Pos + Search(",", ADVANCE+ERRBREAK) + Reg_Copy_Block(#1, #2, Cur_Pos-1) +} +Reg_Copy_Block(#1, #2, EOB_Pos) + +// Display the list +for (#3 = 10; #3 <= #1; #3++) { + Reg_Type(#3) Message(".") +} + +Buf_Quit(OK) diff --git a/Task/Tokenize-a-string/Visual-Basic/tokenize-a-string.vb b/Task/Tokenize-a-string/Visual-Basic/tokenize-a-string.vb new file mode 100644 index 0000000000..e6220da699 --- /dev/null +++ b/Task/Tokenize-a-string/Visual-Basic/tokenize-a-string.vb @@ -0,0 +1,14 @@ +Sub Main() + Dim parseMe As String, parsed As Variant + parseMe = "Hello,How,Are,You,Today" + + parsed = Split(parseMe, ",") + + Dim L0 As Long, outP As String + outP = parsed(0) + For L0 = 1 To UBound(parsed) + outP = outP & "." & parsed(L0) + Next + + MsgBox outP +End Sub diff --git a/Task/Tokenize-a-string/XPL0/tokenize-a-string.xpl0 b/Task/Tokenize-a-string/XPL0/tokenize-a-string.xpl0 new file mode 100644 index 0000000000..70a17b89f0 --- /dev/null +++ b/Task/Tokenize-a-string/XPL0/tokenize-a-string.xpl0 @@ -0,0 +1,20 @@ +string 0; +include c:\cxpl\codes; +int I, J, K, Char; +char String, Array(5,6); \5 words and 5 maximum chars + terminating 0 + +[String:= "Hello,How,Are,You,Today"; +I:= 0; K:= 0; +repeat J:= 0; + loop [Char:= String(I); + I:= I+1; + if Char=^, or Char=0 then quit; + Array(K,J):= Char; + J:= J+1; + ]; + Array(K,J):= 0; \terminate word + K:= K+1; \next word in array +until K>=5; +for K:= 4 downto 0 do [Text(0, addr Array(K,0)); ChOut(0, ^.)]; +CrLf(0); +] diff --git a/Task/Top-rank-per-group/0DESCRIPTION b/Task/Top-rank-per-group/0DESCRIPTION new file mode 100644 index 0000000000..a21463aebe --- /dev/null +++ b/Task/Top-rank-per-group/0DESCRIPTION @@ -0,0 +1,17 @@ +Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter. + +Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: +
Employee Name,Employee ID,Salary,Department
+Tyler Bennett,E10297,32000,D101
+John Rappl,E21437,47000,D050
+George Woltman,E00127,53500,D101
+Adam Smith,E63535,18000,D202
+Claire Buckman,E39876,27800,D202
+David McClellan,E04242,41500,D101
+Rich Holcomb,E01234,49500,D202
+Nathan Adams,E41298,21900,D050
+Richard Potter,E43128,15900,D101
+David Motsinger,E27002,19250,D202
+Tim Sampair,E03033,27000,D101
+Kim Arlich,E10001,57000,D190
+Timothy Grove,E16398,29900,D190
diff --git a/Task/Top-rank-per-group/Ada/top-rank-per-group.ada b/Task/Top-rank-per-group/Ada/top-rank-per-group.ada new file mode 100644 index 0000000000..cefdf1a4f8 --- /dev/null +++ b/Task/Top-rank-per-group/Ada/top-rank-per-group.ada @@ -0,0 +1,71 @@ +with Ada.Containers.Vectors; +with Ada.Text_IO; + +procedure Top is + type Departments is (D050, D101, D190, D202); + type Employee_Data is record + Name : String (1 .. 15); + ID : String (1 .. 6); + Salary : Positive; + Department : Departments; + end record; + + package Employee_Vectors is new Ada.Containers.Vectors + (Element_Type => Employee_Data, Index_Type => Positive); + + function Compare_Salary (Left, Right : Employee_Data) return Boolean is + begin + return Left.Salary > Right.Salary; + end Compare_Salary; + package Salary_Sort is new Employee_Vectors.Generic_Sorting + ("<" => Compare_Salary); + + function Compare_Department (Left, Right : Employee_Data) return Boolean is + begin + return Left.Department < Right.Department; + end Compare_Department; + package Department_Sort is new Employee_Vectors.Generic_Sorting + ("<" => Compare_Department); + + Example_Data : Employee_Vectors.Vector; +begin + -- fill data + Example_Data.Append (("Tyler Bennett ", "E10297", 32000, D101)); + Example_Data.Append (("John Rappl ", "E21437", 47000, D050)); + Example_Data.Append (("George Woltman ", "E00127", 53500, D101)); + Example_Data.Append (("Adam Smith ", "E63535", 18000, D202)); + Example_Data.Append (("Claire Buckman ", "E39876", 27800, D202)); + Example_Data.Append (("David McClellan", "E04242", 41500, D101)); + Example_Data.Append (("Rich Holcomb ", "E01234", 49500, D202)); + Example_Data.Append (("Nathan Adams ", "E41298", 21900, D050)); + Example_Data.Append (("Richard Potter ", "E43128", 15900, D101)); + Example_Data.Append (("David Motsinger", "E27002", 19250, D202)); + Example_Data.Append (("Tim Sampair ", "E03033", 27000, D101)); + Example_Data.Append (("Kim Arlich ", "E10001", 57000, D190)); + Example_Data.Append (("Timothy Grove ", "E16398", 29900, D190)); + -- sort by salary + Salary_Sort.Sort (Example_Data); + -- output each department + for Department in Departments loop + declare + Position : Employee_Vectors.Cursor := Example_Data.First; + Employee : Employee_Data; + begin + Ada.Text_IO.Put_Line ("Department " & Departments'Image (Department)); + for I in 1 .. 3 loop + Employee := Employee_Vectors.Element (Position); + while Employee.Department /= Department loop + Position := Employee_Vectors.Next (Position); + Employee := Employee_Vectors.Element (Position); + end loop; + Ada.Text_IO.Put_Line (" " & Employee.Name & " | " & + Employee.ID & " | " & + Positive'Image (Employee.Salary)); + Position := Employee_Vectors.Next (Position); + end loop; + exception + when Constraint_Error => + null; + end; + end loop; +end Top; diff --git a/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk b/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk new file mode 100644 index 0000000000..c4f929020d --- /dev/null +++ b/Task/Top-rank-per-group/AutoHotkey/top-rank-per-group.ahk @@ -0,0 +1,59 @@ +Departments = D050, D101, D190, D202 +StringSplit, Department_, Departments, `,, %A_Space% + +; Employee Name, Employee ID, Salary, Department +Add_Employee("Tyler Bennett ", "E10297", 32000, "D101") +Add_Employee("John Rappl ", "E21437", 47000, "D050") +Add_Employee("George Woltman ", "E00127", 53500, "D101") +Add_Employee("Adam Smith ", "E63535", 18000, "D202") +Add_Employee("Claire Buckman ", "E39876", 27800, "D202") +Add_Employee("David McClellan", "E04242", 41500, "D101") +Add_Employee("Rich Holcomb ", "E01234", 49500, "D202") +Add_Employee("Nathan Adams ", "E41298", 21900, "D050") +Add_Employee("Richard Potter ", "E43128", 15900, "D101") +Add_Employee("David Motsinger", "E27002", 19250, "D202") +Add_Employee("Tim Sampair ", "E03033", 27000, "D101") +Add_Employee("Kim Arlich ", "E10001", 57000, "D190") +Add_Employee("Timothy Grove ", "E16398", 29900, "D190") + + +; display top 3 ranks for each department +Loop, %Department_0% ; all departments + MsgBox,, % "Department: " Department_%A_Index% + , % TopRank(3, Department_%A_Index%) + + +;--------------------------------------------------------------------------- +TopRank(N, Department) { ; find the top N salaries in each department +;--------------------------------------------------------------------------- + local Collection := Msg := "" + Loop, %m% ; all employees + If (Employee_%A_Index%_Dept = Department) + ; collect all the salaries being paid in this department + Collection .= (Collection ? "," : "") Employee_%A_Index%_Salary + Sort, Collection, ND,R + StringSplit, Collection, Collection, `, + Loop, % (N < Collection0) ? N : Collection0 { + Salary := Collection%A_Index% + Loop, %m% ; find the respective employee + If (Employee_%A_Index%_Salary = Salary) + ; and put out his/her details + Msg .= Employee_%A_Index%_Name "`t" + . Employee_%A_Index%_ID "`t" + . Employee_%A_Index%_Salary "`t" + . Employee_%A_Index%_Dept "`t`n" + } + Return, Msg +} + + +;--------------------------------------------------------------------------- +Add_Employee(Name, ID, Salary, Department) { +;--------------------------------------------------------------------------- + global + m++ + Employee_%m%_Name := Name + Employee_%m%_ID := ID + Employee_%m%_Salary := Salary + Employee_%m%_Dept := Department +} diff --git a/Task/Top-rank-per-group/C++/top-rank-per-group.cpp b/Task/Top-rank-per-group/C++/top-rank-per-group.cpp new file mode 100644 index 0000000000..2d49ff767b --- /dev/null +++ b/Task/Top-rank-per-group/C++/top-rank-per-group.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include + + +struct Employee +{ + std::string Name; + std::string ID; + unsigned long Salary; + std::string Department; + Employee(std::string _Name = "", std::string _ID = "", unsigned long _Salary = 0, std::string _Department = "") + : Name(_Name), ID(_ID), Salary(_Salary), Department(_Department) + { } + + void display(std::ostream& out) const + { + out << Name << "\t" << ID << "\t" << Salary << "\t" << Department << std::endl; + } +}; + +// We'll tell std::set to use this to sort our employees. +struct CompareEarners +{ + bool operator()(const Employee& e1, const Employee& e2) + { + return (e1.Salary > e2.Salary); + } +}; + +// A few typedefs to make the code easier to type, read and maintain. +typedef std::list EMPLOYEELIST; + +// Notice the CompareEarners; We're telling std::set to user our specified comparison mechanism +// to sort its contents. +typedef std::set DEPARTMENTPAYROLL; + +typedef std::map DEPARTMENTLIST; + +void initialize(EMPLOYEELIST& Employees) +{ + // Initialize our employee list data source. + Employees.push_back(Employee("Tyler Bennett", "E10297", 32000, "D101")); + Employees.push_back(Employee("John Rappl", "E21437", 47000, "D050")); + Employees.push_back(Employee("George Woltman", "E21437", 53500, "D101")); + Employees.push_back(Employee("Adam Smith", "E21437", 18000, "D202")); + Employees.push_back(Employee("Claire Buckman", "E39876", 27800, "D202")); + Employees.push_back(Employee("David McClellan", "E04242", 41500, "D101")); + Employees.push_back(Employee("Rich Holcomb", "E01234", 49500, "D202")); + Employees.push_back(Employee("Nathan Adams", "E41298", 21900, "D050")); + Employees.push_back(Employee("Richard Potter", "E43128", 15900, "D101")); + Employees.push_back(Employee("David Motsinger", "E27002", 19250, "D202")); + Employees.push_back(Employee("Tim Sampair", "E03033", 27000, "D101")); + Employees.push_back(Employee("Kim Arlich", "E10001", 57000, "D190")); + Employees.push_back(Employee("Timothy Grove", "E16398", 29900, "D190")); +} + +void group(EMPLOYEELIST& Employees, DEPARTMENTLIST& Departments) +{ + // Loop through all of our employees. + for( EMPLOYEELIST::iterator iEmployee = Employees.begin(); + Employees.end() != iEmployee; + ++iEmployee ) + { + DEPARTMENTPAYROLL& groupSet = Departments[iEmployee->Department]; + + // Add our employee to this group. + groupSet.insert(*iEmployee); + } +} + +void present(DEPARTMENTLIST& Departments, unsigned int N) +{ + // Loop through all of our departments + for( DEPARTMENTLIST::iterator iDepartment = Departments.begin(); + Departments.end() != iDepartment; + ++iDepartment ) + { + std::cout << "In department " << iDepartment->first << std::endl; + std::cout << "Name\t\tID\tSalary\tDepartment" << std::endl; + // Get the top three employees for each employee + unsigned int rank = 1; + for( DEPARTMENTPAYROLL::iterator iEmployee = iDepartment->second.begin(); + ( iDepartment->second.end() != iEmployee) && (rank <= N); + ++iEmployee, ++rank ) + { + iEmployee->display(std::cout); + } + std::cout << std::endl; + } +} + +int main(int argc, char* argv[]) +{ + // Our container for our list of employees. + EMPLOYEELIST Employees; + + // Fill our list of employees + initialize(Employees); + + // Our departments. + DEPARTMENTLIST Departments; + + // Sort our employees into their departments. + // This will also rank them. + group(Employees, Departments); + + // Display the top 3 earners in each department. + present(Departments, 3); + + return 0; +} diff --git a/Task/Top-rank-per-group/C/top-rank-per-group.c b/Task/Top-rank-per-group/C/top-rank-per-group.c new file mode 100644 index 0000000000..aec7a1c382 --- /dev/null +++ b/Task/Top-rank-per-group/C/top-rank-per-group.c @@ -0,0 +1,55 @@ +#include +#include +#include + +typedef struct { + const char *name, *id, *dept; + int sal; +} person; + +person ppl[] = { + {"Tyler Bennett", "E10297", "D101", 32000}, + {"John Rappl", "E21437", "D050", 47000}, + {"George Woltman", "E00127", "D101", 53500}, + {"Adam Smith", "E63535", "D202", 18000}, + {"Claire Buckman", "E39876", "D202", 27800}, + {"David McClellan", "E04242", "D101", 41500}, + {"Rich Holcomb", "E01234", "D202", 49500}, + {"Nathan Adams", "E41298", "D050", 21900}, + {"Richard Potter", "E43128", "D101", 15900}, + {"David Motsinger", "E27002", "D202", 19250}, + {"Tim Sampair", "E03033", "D101", 27000}, + {"Kim Arlich", "E10001", "D190", 57000}, + {"Timothy Grove", "E16398", "D190", 29900}, +}; + +int pcmp(const void *a, const void *b) +{ + const person *aa = a, *bb = b; + int x = strcmp(aa->dept, bb->dept); + if (x) return x; + return aa->sal > bb->sal ? -1 : aa->sal < bb->sal; +} + +#define N sizeof(ppl)/sizeof(person) +void top(int n) +{ + int i, rank; + qsort(ppl, N, sizeof(person), pcmp); + + for (i = rank = 0; i < N; i++) { + if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) { + rank = 0; + printf("\n"); + } + + if (rank++ < n) + printf("%s %d: %s\n", ppl[i].dept, ppl[i].sal, ppl[i].name); + } +} + +int main() +{ + top(2); + return 0; +} diff --git a/Task/Top-rank-per-group/Clojure/top-rank-per-group.clj b/Task/Top-rank-per-group/Clojure/top-rank-per-group.clj new file mode 100644 index 0000000000..08ca89a7a3 --- /dev/null +++ b/Task/Top-rank-per-group/Clojure/top-rank-per-group.clj @@ -0,0 +1,25 @@ +(use '[clojure.contrib.seq-utils :only (group-by)]) + +(defstruct employee :Name :ID :Salary :Department) + +(def data + (->> '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190)) + (map #(apply (partial struct employee) %)))) + + +(doseq [[dep emps] (group-by :Department data)] + (println "Department:" dep) + (doseq [e (take 3 (reverse (sort-by :Salary emps)))] + (println e))) diff --git a/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-1.lisp b/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-1.lisp new file mode 100644 index 0000000000..4c8c832416 --- /dev/null +++ b/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-1.lisp @@ -0,0 +1,34 @@ +(defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql)) + (let ((not-pred (complement predicate)) + (group-data (make-hash-table :test group-test))) + (labels ((value (datum) + (funcall value-key datum)) + (insert (x list) + (merge 'list (list x) list not-pred :key #'value)) + (entry (group) + "Return the entry for the group, creating it if + necessary. An entry is a list whose first element is + k, the number of items currently associated with the + group (out of n total), and whose second element is + the list of the k current top items for the group." + (multiple-value-bind (entry presentp) + (gethash group group-data) + (if presentp entry + (setf (gethash group group-data) + (list 0 '()))))) + (update-entry (entry datum) + "Update the entry using datum. If there are already n + items associated with the entry, then when datum's value + is greater than the current least item, data is merged into + the items, and the list (minus the first element) is + stored in entry. Otherwise, if there are fewer than n + items in the entry, datum is merged in, and the + entry's k is increased by 1." + (if (= n (first entry)) + (when (funcall predicate (value datum) (value (first (second entry)))) + (setf (second entry) + (cdr (insert datum (second entry))))) + (setf (first entry) (1+ (first entry)) + (second entry) (insert datum (second entry)))))) + (dolist (datum data group-data) + (update-entry (entry (funcall group-key datum)) datum))))) diff --git a/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-2.lisp b/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-2.lisp new file mode 100644 index 0000000000..c5d8b53262 --- /dev/null +++ b/Task/Top-rank-per-group/Common-Lisp/top-rank-per-group-2.lisp @@ -0,0 +1,28 @@ +> (defparameter *employee-data* + '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190)) + "A list of lists of each employee's name, id, salary, and +department.") +*EMPLOYEE-DATA* + +> (top-n-by-group 3 *employee-data* 'third 'fourth '>) +# + +> (describe *) + +# is a HASH-TABLE +D101 (3 (("Tyler Bennett" E10297 32000 D101) ("David McClellan" E04242 41500 D101) ("George Woltman" E00127 53500 D101))) +D050 (2 (("Nathan Adams" E41298 21900 D050) ("John Rappl" E21437 47000 D050))) +D202 (3 (("David Motsinger" E27002 19250 D202) ("Claire Buckman" E39876 27800 D202) ("Rich Holcomb" E01234 49500 D202))) +D190 (2 (("Timothy Grove" E16398 29900 D190) ("Kim Arlich" E10001 57000 D190))) diff --git a/Task/Top-rank-per-group/D/top-rank-per-group.d b/Task/Top-rank-per-group/D/top-rank-per-group.d new file mode 100644 index 0000000000..6051f6b4d4 --- /dev/null +++ b/Task/Top-rank-per-group/D/top-rank-per-group.d @@ -0,0 +1,35 @@ +import std.stdio, std.algorithm, std.conv, std.range; + +struct Employee { + string name, id; + uint salary; + string department; +} + +immutable Employee[] data = [ + {"Tyler Bennett", "E10297", 32_000, "D101"}, + {"John Rappl", "E21437", 47_000, "D050"}, + {"George Woltman", "E00127", 53_500, "D101"}, + {"Adam Smith", "E63535", 18_000, "D202"}, + {"Claire Buckman", "E39876", 27_800, "D202"}, + {"David McClellan", "E04242", 41_500, "D101"}, + {"Rich Holcomb", "E01234", 49_500, "D202"}, + {"Nathan Adams", "E41298", 21_900, "D050"}, + {"Richard Potter", "E43128", 15_900, "D101"}, + {"David Motsinger", "E27002", 19_250, "D202"}, + {"Tim Sampair", "E03033", 27_000, "D101"}, + {"Kim Arlich", "E10001", 57_000, "D190"}, + {"Timothy Grove", "E16398", 29_900, "D190"}]; + +void main(in string[] args) { + immutable n = (args.length == 2) ? to!int(args[1]) : 3; + + Employee[][string] departments; + foreach (immutable rec; data) + departments[rec.department] ~= rec; + + foreach (dep, recs; departments) { + recs.topN!q{a.salary > b.salary}(n); + writefln("Department %s\n %(%s\n %)\n", dep, recs.take(n)); + } +} diff --git a/Task/Top-rank-per-group/E/top-rank-per-group-1.e b/Task/Top-rank-per-group/E/top-rank-per-group-1.e new file mode 100644 index 0000000000..ba2eeb2231 --- /dev/null +++ b/Task/Top-rank-per-group/E/top-rank-per-group-1.e @@ -0,0 +1,39 @@ +/** Turn a list of arrays into a list of maps with the given keys. */ +def addKeys(keys, rows) { + def res := [].diverge() + for row in rows { res.push(__makeMap.fromColumns(keys, row)) } + return res.snapshot() +} + +def data := addKeys( + ["name", "id", "salary", "dept"], + [["Tyler Bennett", "E10297", 32000, "D101"], + ["John Rappl", "E21437", 47000, "D050"], + ["George Woltman", "E00127", 53500, "D101"], + ["Adam Smith", "E63535", 18000, "D202"], + ["Claire Buckman", "E39876", 27800, "D202"], + ["David McClellan", "E04242", 41500, "D101"], + ["Rich Holcomb", "E01234", 49500, "D202"], + ["Nathan Adams", "E41298", 21900, "D050"], + ["Richard Potter", "E43128", 15900, "D101"], + ["David Motsinger", "E27002", 19250, "D202"], + ["Tim Sampair", "E03033", 27000, "D101"], + ["Kim Arlich", "E10001", 57000, "D190"], + ["Timothy Grove", "E16398", 29900, "D190"]]) + +def topSalaries(n, out) { + var groups := [].asMap() + for row in data { + def [=> salary, => dept] | _ := row + def top := groups.fetch(dept, fn {[]}).with([-salary, row]).sort() + groups with= (dept, top.run(0, top.size().min(n))) + } + for dept => group in groups.sortKeys() { + out.println(`Department $dept`) + out.println(`---------------`) + for [_, row] in group { + out.println(`${row["id"]} $$${row["salary"]} ${row["name"]}`) + } + out.println() + } +} diff --git a/Task/Top-rank-per-group/E/top-rank-per-group-2.e b/Task/Top-rank-per-group/E/top-rank-per-group-2.e new file mode 100644 index 0000000000..5ed6e0c244 --- /dev/null +++ b/Task/Top-rank-per-group/E/top-rank-per-group-2.e @@ -0,0 +1,22 @@ +? topSalaries(3, stdout) +Department D050 +--------------- +E21437 $47000 John Rappl +E41298 $21900 Nathan Adams + +Department D101 +--------------- +E00127 $53500 George Woltman +E04242 $41500 David McClellan +E10297 $32000 Tyler Bennett + +Department D190 +--------------- +E10001 $57000 Kim Arlich +E16398 $29900 Timothy Grove + +Department D202 +--------------- +E01234 $49500 Rich Holcomb +E39876 $27800 Claire Buckman +E27002 $19250 David Motsinger diff --git a/Task/Top-rank-per-group/Factor/top-rank-per-group.factor b/Task/Top-rank-per-group/Factor/top-rank-per-group.factor new file mode 100644 index 0000000000..59f99980ac --- /dev/null +++ b/Task/Top-rank-per-group/Factor/top-rank-per-group.factor @@ -0,0 +1,42 @@ +USING: accessors assocs fry io kernel math.parser sequences +sorting ; +IN: top-rank + +TUPLE: employee name id salary department ; + +CONSTANT: employees { + T{ employee f "Tyler Bennett" "E10297" 32000 "D101" } + T{ employee f "John Rappl" "E21437" 47000 "D050" } + T{ employee f "George Woltman" "E00127" 53500 "D101" } + T{ employee f "Adam Smith" "E63535" 18000 "D202" } + T{ employee f "Claire Buckman" "E39876" 27800 "D202" } + T{ employee f "David McClellan" "E04242" 41500 "D101" } + T{ employee f "Rich Holcomb" "E01234" 49500 "D202" } + T{ employee f "Nathan Adams" "E41298" 21900 "D050" } + T{ employee f "Richard Potter" "E43128" 15900 "D101" } + T{ employee f "David Motsinger" "E27002" 19250 "D202" } + T{ employee f "Tim Sampair" "E03033" 27000 "D101" } + T{ employee f "Kim Arlich" "E10001" 57000 "D190" } + T{ employee f "Timothy Grove" "E16398" 29900 "D190" } + } + +: group-by ( seq quot -- hash ) + H{ } clone [ '[ dup @ _ push-at ] each ] keep ; inline + +: prepare-departments ( seq -- departments ) + [ department>> ] group-by + [ [ salary>> ] inv-sort-with ] assoc-map ; + +: first-n-each ( seq n quot -- ) + [ short head-slice ] dip each ; inline + +: main ( -- ) + employees prepare-departments [ + [ "Department " write write ":" print ] dip + 3 [ + [ id>> write " $" write ] + [ salary>> number>string write " " write ] + [ name>> print ] tri + ] first-n-each + nl + ] assoc-each ; diff --git a/Task/Top-rank-per-group/Go/top-rank-per-group.go b/Task/Top-rank-per-group/Go/top-rank-per-group.go new file mode 100644 index 0000000000..9f4657ea01 --- /dev/null +++ b/Task/Top-rank-per-group/Go/top-rank-per-group.go @@ -0,0 +1,122 @@ +package main + +import ( + "fmt" + "sort" +) + +// language-native data description +type employee struct { + name, id string + salary int + dept string +} + +var data = []employee{ + {"Tyler Bennett", "E10297", 32000, "D101"}, + {"John Rappl", "E21437", 47000, "D050"}, + {"George Woltman", "E00127", 53500, "D101"}, + {"Adam Smith", "E63535", 18000, "D202"}, + {"Claire Buckman", "E39876", 27800, "D202"}, + {"David McClellan", "E04242", 41500, "D101"}, + {"Rich Holcomb", "E01234", 49500, "D202"}, + {"Nathan Adams", "E41298", 21900, "D050"}, + {"Richard Potter", "E43128", 15900, "D101"}, + {"David Motsinger", "E27002", 19250, "D202"}, + {"Tim Sampair", "E03033", 27000, "D101"}, + {"Kim Arlich", "E10001", 57000, "D190"}, + {"Timothy Grove", "E16398", 29900, "D190"}, +} + +// n provided as first parameter of function topN +func main() { + topN(3, data).print() + +} + +// return type of function topN +type result struct { + n int + dlist [][][]int // dimensions are department,salary,index into data +} + +func (r result) print() { + fmt.Println("Top", r.n, "salaries per department") + printEs := func(es []int) { + for _, ei := range es { + fmt.Printf(" %s %16s %7d\n", + data[ei].id, data[ei].name, data[ei].salary) + } + } + for _, slist := range r.dlist { + fmt.Println(data[slist[0][0]].dept) + nRemaining := r.n + sLast := len(slist) - 1 + for si := 0; si < sLast; si++ { + printEs(slist[si]) + nRemaining -= len(slist[si]) + } + if len(slist[sLast]) > nRemaining { + fmt.Println(" * * * * * * * tie * * * * * * *") + } + printEs(slist[sLast]) + } +} + +func topN(n int, data []employee) *result { + // summarize: construct map with unique deptartment names, + // unique salaries under each of those, + // and then a list of employees under each of those, + // with employees identified by index into data. + salsum := make(map[string]map[int][]int) + for i, e := range data { + dsum, ok := salsum[e.dept] + if !ok { + dsum = make(map[int][]int) + salsum[e.dept] = dsum + } + dsum[e.salary] = append(dsum[e.salary], i) + } + + // begin constructing result array. + // top level is list of departments. + dlist := make([][][]int, len(salsum)) + + // sort departments for readability + deptSort := make([]string, len(salsum)) + i := 0 + for dept := range salsum { + deptSort[i] = dept + i++ + } + sort.Strings(deptSort) + + for di, dept := range deptSort { + dsum := salsum[dept] + // sort salaries for selection (and readability) + salSort := make([]int, len(dsum)) + i := 0 + for s := range dsum { + salSort[i] = s + i++ + } + sort.Ints(salSort) + nRemaining := n + // construct level 2, unique salaries + var slist [][]int + // iterate from end so as to select highest + for si := len(salSort) - 1; si >= 0; si-- { + ssum := dsum[salSort[si]] + // construct level 3, indexes into data + elist := make([]int, len(ssum)) + slist = append(slist, elist) + copy(elist, ssum) + nRemaining -= len(ssum) + if nRemaining <= 0 { + break + } + } + dlist[di] = slist + } + return &result{n, dlist} +} diff --git a/Task/Top-rank-per-group/Groovy/top-rank-per-group.groovy b/Task/Top-rank-per-group/Groovy/top-rank-per-group.groovy new file mode 100644 index 0000000000..a854f28d0f --- /dev/null +++ b/Task/Top-rank-per-group/Groovy/top-rank-per-group.groovy @@ -0,0 +1,28 @@ +def displayRank(employees, number) { + employees.groupBy { it.Department }.sort().each { department, staff -> + println "Department $department" + println " Name ID Salary" + staff.sort { e1, e2 -> e2.Salary <=> e1.Salary } + staff[0.. + println " ${e.Name.padRight(20)}${e.ID}${sprintf('%8d', e.Salary)}" + } + println() + } +} + +def employees = [ + [Name: 'Tyler Bennett', ID: 'E10297', Salary: 32000, Department: 'D101'], + [Name: 'John Rappl', ID: 'E21437', Salary: 47000, Department: 'D050'], + [Name: 'George Woltman', ID: 'E00127', Salary: 53500, Department: 'D101'], + [Name: 'Adam Smith', ID: 'E63535', Salary: 18000, Department: 'D202'], + [Name: 'Claire Buckman', ID: 'E39876', Salary: 27800, Department: 'D202'], + [Name: 'David McClellan', ID: 'E04242', Salary: 41500, Department: 'D101'], + [Name: 'Rich Holcomb', ID: 'E01234', Salary: 49500, Department: 'D202'], + [Name: 'Nathan Adams', ID: 'E41298', Salary: 21900, Department: 'D050'], + [Name: 'Richard Potter', ID: 'E43128', Salary: 15900, Department: 'D101'], + [Name: 'David Motsinger', ID: 'E27002', Salary: 19250, Department: 'D202'], + [Name: 'Tim Sampair', ID: 'E03033', Salary: 27000, Department: 'D101'], + [Name: 'Kim Arlich', ID: 'E10001', Salary: 57000, Department: 'D190'], + [Name: 'Timothy Grove', ID: 'E16398', Salary: 29900, Department: 'D190'] +] +displayRank(employees, 3) diff --git a/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs b/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs new file mode 100644 index 0000000000..685918d44b --- /dev/null +++ b/Task/Top-rank-per-group/Haskell/top-rank-per-group.hs @@ -0,0 +1,45 @@ +import Data.List +import Control.Monad +import Control.Arrow +import Text.Printf +import Data.Ord +import Data.Function + +groupingOn = ((==) `on`) +comparingDwn = flip . comparing + + +type ID = Int +type DEP = String +type NAME = String +type SALARY = Double +data Employee = Employee {nr :: ID, dep :: DEP, name :: NAME, sal :: SALARY} + +employees :: [Employee] +employees = map (\(i,d,n,s) -> Employee i d n s) + [(1001,"AB","Janssen A.H.",41000), (101,"KA","'t Woud B.",45000), + (1013,"AB","de Bont C.A.",65000), (1101,"CC","Modaal A.M.J.",30000), + (1203,"AB","Anders H.",50000), (100,"KA","Ezelbips P.J.",52000), + (1102,"CC","Zagt A.",33000), (1103,"CC","Ternood T.R.",21000), + (1104,"CC","Lageln M.",23000), (1105,"CC","Amperwat A.",19000), + (1106,"CC","Boon T.J.",25000), (1107,"CC","Beloop L.O.",31000), + (1009,"CD","Janszoon A.",38665), (1026,"CD","Janszen H.P.",41000), + (1011,"CC","de Goeij J.",39000), (106,"KA","Pragtweik J.M.V.",42300), + (111,"KA","Bakeuro S.",31000), (105,"KA","Clubdrager C.",39800), + (104,"KA","Karendijk F.",23000), (107,"KA","Centjes R.M.",34000), + (119,"KA","Tegenstroom H.L.",39000), (1111,"CD","Telmans R.M.",55500), + (1093,"AB","de Slegte S.",46987), (1199,"CC","Uitlaat G.A.S.",44500) + ] + +dorank :: Int -> + (Employee -> DEP) -> + (Employee -> SALARY) -> + [Employee]-> [[Employee]] +dorank n o1 o2 = map (take n. sortBy (comparingDwn o2)) + . groupBy (groupingOn o1) . sortBy (comparing o1) + +toprank :: IO () +toprank = do + printf "%-16s %3s %10s\n" "NAME" "DEP" "TIP" + putStrLn $ replicate 31 '=' + mapM_ (mapM_ (ap (ap (printf "%-16s %3s %10.2g\n" . name) dep) sal)) $ dorank 3 dep sal employees diff --git a/Task/Top-rank-per-group/HicEst/top-rank-per-group.hicest b/Task/Top-rank-per-group/HicEst/top-rank-per-group.hicest new file mode 100644 index 0000000000..b6a5cb7d78 --- /dev/null +++ b/Task/Top-rank-per-group/HicEst/top-rank-per-group.hicest @@ -0,0 +1,30 @@ +CHARACTER source="Test.txt", outP='Top_rank.txt', fmt='A20,A8,i6,2x,A10' +CHARACTER name*20, employee_ID*10, department*10, temp*10 +REAL :: idx(1), N_top_salaries=3 + +! Open the source with 4 "," separated columns, skip line 1: +OPEN(FIle=source, Format='SL=1;4,;', LENgth=L) +ALLOCATE(idx, L) + +! Sort salary column 3 descending, then department column 4, store in idx: +SORT(FIle=source, Column=3, Descending=1, Column=4, Index=idx) + +! Display a spreadsheet-like scrolling dialog of the presorted source: +DLG(Text=idx, Text=source, Format=fmt, Y) + +! Output the first N top salaries of each department_ +OPEN(FIle=outP) +DO i = 1, L + rank = rank + 1 + READ(FIle=source, Row=idx(i)) name, employee_ID, salary, department + IF(temp /= department) THEN + rank = 1 + WRITE(FIle=outP) + temp = department + ENDIF + IF(rank <= N_top_salaries) THEN + WRITE(FIle=outP, Format=fmt) name, employee_ID, salary, department + ENDIF +ENDDO + +END diff --git a/Task/Top-rank-per-group/Icon/top-rank-per-group.icon b/Task/Top-rank-per-group/Icon/top-rank-per-group.icon new file mode 100644 index 0000000000..e7d993c9a3 --- /dev/null +++ b/Task/Top-rank-per-group/Icon/top-rank-per-group.icon @@ -0,0 +1,44 @@ +record Employee(name,id,salary,dept) + +procedure getEmployees () + employees := [ + Employee("Tyler Bennett","E10297",32000,"D101"), + Employee("John Rappl","E21437",47000,"D050"), + Employee("George Woltman","E00127",53500,"D101"), + Employee("Adam Smith","E63535",18000,"D202"), + Employee("Claire Buckman","E39876",27800,"D202"), + Employee("David McClellan","E04242",41500,"D101"), + Employee("Rich Holcomb","E01234",49500,"D202"), + Employee("Nathan Adams","E41298",21900,"D050"), + Employee("Richard Potter","E43128",15900,"D101"), + Employee("David Motsinger","E27002",19250,"D202"), + Employee("Tim Sampair","E03033",27000,"D101"), + Employee("Kim Arlich","E10001",57000,"D190"), + Employee("Timothy Grove","E16398",29900,"D190") + ] + return employees +end + +procedure show_employee (employee) + every writes (!employee || " ") + write () +end + +procedure main (args) + N := integer(args[1]) # N set from command line + employees := getEmployees () + groups := set() + every employee := !employees do insert(groups, employee.dept) + + every group := !groups do { + write ("== Top " || N || " in group " || group) + employeesInGroup := [] + every employee := !employees do { + if employee.dept == group then put(employeesInGroup, employee) + } + # sort by third field and reverse, so highest salary comes first + employeesInGroup := reverse(sortf(employeesInGroup, 3)) + # show the first N records, up to the end of the list + every show_employee (!employeesInGroup[1:(1+min(N,*employeesInGroup))]) + } +end diff --git a/Task/Top-rank-per-group/J/top-rank-per-group-1.j b/Task/Top-rank-per-group/J/top-rank-per-group-1.j new file mode 100644 index 0000000000..7cd737e45a --- /dev/null +++ b/Task/Top-rank-per-group/J/top-rank-per-group-1.j @@ -0,0 +1,5 @@ +NB. Dynamically generate convenience functions +('`',,;:^:_1: N=:{.Employees) =:, (_&{"1)`'' ([^:(_ -: ])L:0)"0 _~ i.# E =: {: Employees + +NB. Show top six ranked employees in each dept +N , (<@:>"1@:|:@:((6 <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E diff --git a/Task/Top-rank-per-group/J/top-rank-per-group-2.j b/Task/Top-rank-per-group/J/top-rank-per-group-2.j new file mode 100644 index 0000000000..0c27b14d20 --- /dev/null +++ b/Task/Top-rank-per-group/J/top-rank-per-group-2.j @@ -0,0 +1 @@ +reportTopSalaries=: 3 :'N , (<@:>"1@:|:@:((y <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E' diff --git a/Task/Top-rank-per-group/JavaScript/top-rank-per-group.js b/Task/Top-rank-per-group/JavaScript/top-rank-per-group.js new file mode 100644 index 0000000000..43ff4ac148 --- /dev/null +++ b/Task/Top-rank-per-group/JavaScript/top-rank-per-group.js @@ -0,0 +1,58 @@ +var data = [ + {name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"}, + {name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"}, + {name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"}, + {name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"}, + {name: "Claire Buckman", id: "E39876", salary: 27800, dept: "D202"}, + {name: "David McClellan", id: "E04242", salary: 41500, dept: "D101"}, + {name: "Rich Holcomb", id: "E01234", salary: 49500, dept: "D202"}, + {name: "Nathan Adams", id: "E41298", salary: 21900, dept: "D050"}, + {name: "Richard Potter", id: "E43128", salary: 15900, dept: "D101"}, + {name: "David Motsinger", id: "E27002", salary: 19250, dept: "D202"}, + {name: "Tim Sampair", id: "E03033", salary: 27000, dept: "D101"}, + {name: "Kim Arlich", id: "E10001", salary: 57000, dept: "D190"}, + {name: "Timothy Grove", id: "E16398", salary: 29900, dept: "D190"}, +]; + +function top_rank(n) { + var by_dept = group_by_dept(data); + for (var dept in by_dept) { + output(dept); + for (var i = 0; i < n && i < by_dept[dept].length; i++) { + var emp = by_dept[dept][i]; + output(emp.name + ", id=" + emp.id + ", salary=" + emp.salary); + } + output(""); + } +} + +// group by dept, and sort by balary +function group_by_dept(data) { + var by_dept = {}; + for (var idx in data) { + var dept = data[idx].dept; + if ( ! has_property(by_dept, dept)) { + by_dept[dept] = new Array(); + } + by_dept[dept].push(data[idx]); + } + for (var dept in by_dept) { + // numeric sort + by_dept[dept].sort(function (a,b){return b.salary - a.salary}); + } + return by_dept; +} + +function has_property(obj, propname) { + return typeof(obj[propname]) != "undefined"; +} + +function output(str) { + try { + WScript.Echo(str); // WSH + } catch(err) { + print(str); // Rhino + } +} + +top_rank(3); diff --git a/Task/Top-rank-per-group/Lua/top-rank-per-group.lua b/Task/Top-rank-per-group/Lua/top-rank-per-group.lua new file mode 100644 index 0000000000..fed5a157d0 --- /dev/null +++ b/Task/Top-rank-per-group/Lua/top-rank-per-group.lua @@ -0,0 +1,36 @@ +N = 2 + +lst = { { "Tyler Bennett","E10297",32000,"D101" }, + { "John Rappl","E21437",47000,"D050" }, + { "George Woltman","E00127",53500,"D101" }, + { "Adam Smith","E63535",18000,"D202" }, + { "Claire Buckman","E39876",27800,"D202" }, + { "David McClellan","E04242",41500,"D101" }, + { "Rich Holcomb","E01234",49500,"D202" }, + { "Nathan Adams","E41298",21900,"D050" }, + { "Richard Potter","E43128",15900,"D101" }, + { "David Motsinger","E27002",19250,"D202" }, + { "Tim Sampair","E03033",27000,"D101" }, + { "Kim Arlich","E10001",57000,"D190" }, + { "Timothy Grove","E16398",29900,"D190" } + } + +dep = {} +for i = 1, #lst do + if dep[ lst[i][4] ] == nil then + dep[ lst[i][4] ] = {} + dep[ lst[i][4] ][1] = lst[i] + else + dep[ lst[i][4] ][#dep[lst[i][4]]+1] = lst[i] + end +end + +for i, _ in pairs( dep ) do + table.sort( dep[i], function (a,b) return a[3] > b[3] end ) + + print( "Department:", dep[i][1][4] ) + for l = 1, math.min( N, #dep[i] ) do + print( "", dep[i][l][1], dep[i][l][2], dep[i][l][3] ) + end + print "" +end diff --git a/Task/Top-rank-per-group/Mathematica/top-rank-per-group.math b/Task/Top-rank-per-group/Mathematica/top-rank-per-group.math new file mode 100644 index 0000000000..bbbbe3698b --- /dev/null +++ b/Task/Top-rank-per-group/Mathematica/top-rank-per-group.math @@ -0,0 +1,14 @@ +InitialList ={{"Tyler Bennett","E10297",32000,"D101"}, +{"John Rappl","E21437",47000,"D050"},{"George Woltman","E00127",53500,"D101"}, +{"Adam Smith","E63535",18000,"D202"},{"Claire Buckman","E39876",27800,"D202"}, +{"David McClellan","E04242",41500,"D101"},{"Rich Holcomb","E01234",49500,"D202"}, +{"Nathan Adams","E41298",21900,"D050"},{"Richard Potter","E43128",15900,"D101"}, +{"David Motsinger","E27002",19250,"D202"},{"Tim Sampair","E03033",27000,"D101"}, +{"Kim Arlich","E10001",57000,"D190"},{"Timothy Grove","E16398",29900,"D190"}}; + +TrimmedList=Map[ If[Length[#]>3,Take[#,3],#]& , + Map[Reverse[SortBy[#,#[[3]]&]]&,GatherBy[InitialList,Last]] +]; + +Scan[((Print["Department ",#[[1,4]],"\n","Employee","\t","Id","\t","Salary"]&[#])&[#]; +(Scan[Print[#[[1]],"\t",#[[2]],"\t",#[[3]]]&,#] )& [#])&,TrimmedList] diff --git a/Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml b/Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml new file mode 100644 index 0000000000..7d90fb99f3 --- /dev/null +++ b/Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml @@ -0,0 +1,50 @@ +open StdLabels + +let to_string (name,_,s,_) = (Printf.sprintf "%s (%d)" name s) + +let take n li = + let rec aux i acc = function + | _ when i >= n -> (List.rev acc) + | [] -> (List.rev acc) + | x::xs -> aux (succ i) (x::acc) xs + in + aux 0 [] li ;; + +let toprank data n = + let len = List.length data in + let h = Hashtbl.create len in + List.iter data ~f:(fun ((_,_,_,dep) as employee) -> + Hashtbl.add h dep employee); + let deps = + List.fold_left data ~init:[] ~f: + (fun ac (_,_,_,v) -> if List.mem v ac then ac else v::ac) in + let f dep = + Printf.printf "Department: %s\n " dep; + let l = Hashtbl.find_all h dep in + let l2 = List.sort (fun (_,_,v1,_) (_,_,v2,_) -> compare v2 v1) l in + let l3 = (take n l2) in + print_endline(String.concat ", " (List.map to_string l3)); + print_newline() + in + List.iter f deps; +;; + +let data = [ + "Tyler Bennett", "E10297", 32000, "D101"; + "John Rappl", "E21437", 47000, "D050"; + "George Woltman", "E00127", 53500, "D101"; + "Adam Smith", "E63535", 18000, "D202"; + "Claire Buckman", "E39876", 27800, "D202"; + "David McClellan", "E04242", 41500, "D101"; + "Rich Holcomb", "E01234", 49500, "D202"; + "Nathan Adams", "E41298", 21900, "D050"; + "Richard Potter", "E43128", 15900, "D101"; + "David Motsinger", "E27002", 19250, "D202"; + "Tim Sampair", "E03033", 27000, "D101"; + "Kim Arlich", "E10001", 57000, "D190"; + "Timothy Grove", "E16398", 29900, "D190"; +] + +let () = + toprank data 3; +;; diff --git a/Task/Top-rank-per-group/Oz/top-rank-per-group.oz b/Task/Top-rank-per-group/Oz/top-rank-per-group.oz new file mode 100644 index 0000000000..3049943efa --- /dev/null +++ b/Task/Top-rank-per-group/Oz/top-rank-per-group.oz @@ -0,0 +1,46 @@ +declare + %% Create a list of employee records. + Data = {Map + [['Tyler Bennett' e10297 32000 d101] + ['John Rappl' e21437 47000 d050] + ['George Woltman' e00127 53500 d101] + ['Adam Smith' e63535 18000 d202] + ['Claire Buckman' e39876 27800 d202] + ['David McClellan' e04242 41500 d101] + ['Rich Holcomb' e01234 49500 d202] + ['Nathan Adams' e41298 21900 d050] + ['Richard Potter' e43128 15900 d101] + ['David Motsinger' e27002 19250 d202] + ['Tim Sampair' e03033 27000 d101] + ['Kim Arlich' e10001 57000 d190] + ['Timothy Grove' e16398 29900 d190]] + + fun {$ [Name Id Salary Department]} + employee(name:Name id:Id salary:Salary department:Department) + end} + + fun {TopEarners Employees N} + {Record.map {GroupBy Employees department} + fun {$ Employees} + {List.take + {Sort Employees CompareSalary} + N} + end} + end + + fun {CompareSalary E1 E2} + E1.salary > E2.salary + end + + %% Groups the records Xs by the value of feature F and returns + %% the result as a record that maps values of F to list of records. + fun {GroupBy Xs F} + Groups = {Dictionary.new} + in + for X in Xs do + Groups.(X.F) := X|{CondSelect Groups X.F nil} + end + {Dictionary.toRecord unit Groups} + end +in + {Inspect {TopEarners Data 3}} diff --git a/Task/Top-rank-per-group/PARI-GP/top-rank-per-group.pari b/Task/Top-rank-per-group/PARI-GP/top-rank-per-group.pari new file mode 100644 index 0000000000..4d6657ce87 --- /dev/null +++ b/Task/Top-rank-per-group/PARI-GP/top-rank-per-group.pari @@ -0,0 +1,28 @@ +{V=[["Tyler Bennett","E10297",32000,"D101"], +["John Rappl","E21437",47000,"D050"], +["George Woltman","E00127",53500,"D101"], +["Adam Smith","E63535",18000,"D202"], +["Claire Buckman","E39876",27800,"D202"], +["David McClellan","E04242",41500,"D101"], +["Rich Holcomb","E01234",49500,"D202"], +["Nathan Adams","E41298",21900,"D050"], +["Richard Potter","E43128",15900,"D101"], +["David Motsinger","E27002",19250,"D202"], +["Tim Sampair","E03033",27000,"D101"], +["Kim Arlich","E10001",57000,"D190"], +["Timothy Grove","E16398",29900,"D190"]]}; + +top(n,V)={ + my(dept=vecsort(vector(#V,i,V[i][4]),,8),d,v); + for(i=1,#dept, + d=dept[i]; + print(d); + v=select(u->u[4]==d,V); + v=vecsort(v,3,4); \\ Sort by salary (#3) descending (flag 0x4) + for(j=1,min(n,#v), + print("\t",v[j][1],"\t",v[j][2],"\t",v[j][3]) + ) + ); +}; + +top(2,V) diff --git a/Task/Top-rank-per-group/PHP/top-rank-per-group.php b/Task/Top-rank-per-group/PHP/top-rank-per-group.php new file mode 100644 index 0000000000..9c6a36606f --- /dev/null +++ b/Task/Top-rank-per-group/PHP/top-rank-per-group.php @@ -0,0 +1,48 @@ +$data = Array( + Array("Tyler Bennett","E10297",32000,"D101"), + Array("John Rappl","E21437",47000,"D050"), + Array("George Woltman","E00127",53500,"D101"), + Array("Adam Smith","E63535",18000,"D202"), + Array("Claire Buckman","E39876",27800,"D202"), + Array("David McClellan","E04242",41500,"D101"), + Array("Rich Holcomb","E01234",49500,"D202"), + Array("Nathan Adams","E41298",21900,"D050"), + Array("Richard Potter","E43128",15900,"D101"), + Array("David Motsinger","E27002",19250,"D202"), + Array("Tim Sampair","E03033",27000,"D101"), + Array("Kim Arlich","E10001",57000,"D190"), + Array("Timothy Grove","E16398",29900,"D190") + ); +function top_sal($num){ + global $data; + $depts = Array(); + foreach($data as $key => $arr){ + if(!isset($depts[$arr[3]])) $depts[$arr[3]] = Array(); + $depts[$arr[3]][] = $key; + } + function topsalsort($a,$b){ + global $data; + if ($data[$a][2] == $data[$b][2]) { + return 0; + } + return ($data[$a][2] < $data[$b][2]) ? 1 : -1; + } + foreach ($depts as $key => $val){ + usort($depts[$key],"topsalsort"); + } + ksort($depts); + echo '
';
+	foreach ($depts as $key => $val){
+		echo $key . '
'; + echo 'Name ID Salary
'; + $count = 0; + foreach($val as $value){ + echo $data[$value][0] . ' ' . $data[$value][1] . ' ' . $data[$value][2] . '
'; + $count++; + if($count>=$num) break; + } + echo '
'; + } + echo '
'; +} +top_sal(3); diff --git a/Task/Top-rank-per-group/Pascal/top-rank-per-group.pascal b/Task/Top-rank-per-group/Pascal/top-rank-per-group.pascal new file mode 100644 index 0000000000..00bb7b613d --- /dev/null +++ b/Task/Top-rank-per-group/Pascal/top-rank-per-group.pascal @@ -0,0 +1,69 @@ +program TopRankPerGroup(output); + +uses + Classes, Math; + +type + TData = record + name: string; + ID: string; + salary: longint; + dept: string + end; + PTData = ^TData; + +const + data: array [1..13] of TData = + ( (name: 'Tyler Bennett'; ID: 'E10297'; salary: 32000; dept: 'D101'), + (name: 'John Rappl'; ID: 'E21437'; salary: 47000; dept: 'D050'), + (name: 'George Woltman'; ID: 'E00127'; salary: 53500; dept: 'D101'), + (name: 'Adam Smith'; ID: 'E63535'; salary: 18000; dept: 'D202'), + (name: 'Claire Buckman'; ID: 'E39876'; salary: 27800; dept: 'D202'), + (name: 'David McClellan'; ID: 'E04242'; salary: 41500; dept: 'D101'), + (name: 'Rich Holcomb'; ID: 'E01234'; salary: 49500; dept: 'D202'), + (name: 'Nathan Adams'; ID: 'E41298'; salary: 21900; dept: 'D050'), + (name: 'Richard Potter'; ID: 'E43128'; salary: 15900; dept: 'D101'), + (name: 'David Motsinger'; ID: 'E27002'; salary: 19250; dept: 'D202'), + (name: 'Tim Sampair'; ID: 'E03033'; salary: 27000; dept: 'D101'), + (name: 'Kim Arlich'; ID: 'E10001'; salary: 57000; dept: 'D190'), + (name: 'Timothy Grove'; ID: 'E16398'; salary: 29900; dept: 'D190') + ); + +function CompareSalary(Item1, Item2: PTData): longint; + begin + CompareSalary := Item2^.salary - Item1^.salary; + end; + +var + depts : TStringList; + deptList: Tlist; + number, i, j: integer; + +begin + write ('Enter the number of ranks: '); + readln (number); + depts := TStringList.Create; + depts.Sorted := true; + depts.Duplicates := dupIgnore; + for i := low(data) to high(data) do + depts.Add(data[i].dept); + + for i := 0 to depts.Count - 1 do + begin + writeln; + writeln('Department: ', depts.Strings[i]); + deptList := TList.Create; + for j := low(data) to high(data) do + if data[j].dept = depts.Strings[i] then + deptList.Add(@data[j]); + deptList.Sort(TListSortCompare(@CompareSalary)); + for j := 0 to min(deptList.count, number) - 1 do + begin + write (PTData(deptList.Items[j])^.name, ', '); + write ('ID: ', PTData(deptList.Items[j])^.ID, ', '); + write ('Salary: ', PTData(deptList.Items[j])^.Salary); + writeln; + end; + deptList.Destroy; + end; +end. diff --git a/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 new file mode 100644 index 0000000000..ff37df75a7 --- /dev/null +++ b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 @@ -0,0 +1,24 @@ +my @data = ( + [< E10297 32000 D101 Tyler_Bennett >], + [< E21437 47000 D050 John_Rappl >], + [< E00127 53500 D101 George_Woltman >], + [< E63535 18000 D202 Adam_Smith >], + [< E39876 27800 D202 Claire_Buckman >], + [< E04242 41500 D101 David_McClellan >], + [< E01234 49500 D202 Rich_Holcomb >], + [< E41298 21900 D050 Nathan_Adams >], + [< E43128 15900 D101 Richard_Potter >], + [< E27002 19250 D202 David_Motsinger >], + [< E03033 27000 D101 Tim_Sampair >], + [< E10001 57000 D190 Kim_Arlich >], + [< E16398 29900 D190 Timothy_Grove >], +).map: { item %( < id salary dept name > Z=> .list ) } + +sub MAIN($N as Int = 3) { + my $cont = 0; + for @data.classify({ . }).sort».value { + my @es = .sort({ -. }); + print "\n" if $cont++; + say .< dept id salary name >.Str if .so for @es[^$N]; + } +} diff --git a/Task/Top-rank-per-group/Perl/top-rank-per-group.pl b/Task/Top-rank-per-group/Perl/top-rank-per-group.pl new file mode 100644 index 0000000000..84b02a891c --- /dev/null +++ b/Task/Top-rank-per-group/Perl/top-rank-per-group.pl @@ -0,0 +1,48 @@ +sub zip { + my @a = @{shift()}; + my @b = @{shift()}; + my @l; + push @l, shift @a, shift @b while @a and @b; + return @l; +} + +sub uniq { + my %h; + grep {!$h{$_}++} @_; +} + +my @data = + map {{ zip [qw(name id salary dept)], [split ','] }} + split "\n", + <<'EOF'; +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190 +EOF + +@ARGV or die "Please provide a value for N.\n"; +my $N = shift; + +foreach my $d (sort uniq map {$_->{dept}} @data) { + print "$d\n"; + my @es = + sort {$b->{salary} <=> $a->{salary}} + grep {$_->{dept} eq $d} + @data; + foreach (1 .. $N) { + @es or last; + my $e = shift @es; + printf "%-15s | %-6s | %5d\n", @{$e}{qw(name id salary)}; + } + print "\n"; +} diff --git a/Task/Top-rank-per-group/PicoLisp/top-rank-per-group.l b/Task/Top-rank-per-group/PicoLisp/top-rank-per-group.l new file mode 100644 index 0000000000..18f0be059c --- /dev/null +++ b/Task/Top-rank-per-group/PicoLisp/top-rank-per-group.l @@ -0,0 +1,27 @@ +# Employee Name, ID, Salary, Department +(de *Employees + ("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190) ) + +(de topEmployees (N) + (let Fmt (4 -16 -7 7) + (for Dept (by cadddr group *Employees) + (prinl "Department " (cadddr (car Dept)) ":") + (tab Fmt NIL "Name" "ID" "Salary") + (for (I . D) (flip (by caddr sort Dept)) + (tab Fmt (pack I ". ") (car D) (cadr D) (caddr D)) + (T (= I N)) ) + (prinl) ) ) ) + +(topEmployees 3) diff --git a/Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh b/Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh new file mode 100644 index 0000000000..20ce76c160 --- /dev/null +++ b/Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh @@ -0,0 +1,32 @@ +function New-Employee ($Name, $ID, $Salary, $Department) { + New-Object PSObject ` + | Add-Member -PassThru NoteProperty EmployeeName $Name ` + | Add-Member -PassThru NoteProperty EmployeeID $ID ` + | Add-Member -PassThru NoteProperty Salary $Salary ` + | Add-Member -PassThru NoteProperty Department $Department +} + +$data = (New-Employee 'Tyler Bennett' E10297 32000 D101), + (New-Employee 'John Rappl' E21437 47000 D050), + (New-Employee 'George Woltman' E00127 53500 D101), + (New-Employee 'Adam Smith' E63535 18000 D202), + (New-Employee 'Claire Buckman' E39876 27800 D202), + (New-Employee 'David McClellan' E04242 41500 D101), + (New-Employee 'Rich Holcomb' E01234 49500 D202), + (New-Employee 'Nathan Adams' E41298 21900 D050), + (New-Employee 'Richard Potter' E43128 15900 D101), + (New-Employee 'David Motsinger' E27002 19250 D202), + (New-Employee 'Tim Sampair' E03033 27000 D101), + (New-Employee 'Kim Arlich' E10001 57000 D190), + (New-Employee 'Timothy Grove' E16398 29900 D190) + +function Get-TopRank ($n) { + $data ` + | Group-Object Department ` + | ForEach-Object { + $_.Group ` + | Sort-Object Salary -Descending ` + | Select-Object -First $n + } ` + | Format-Table -GroupBy Department +} diff --git a/Task/Top-rank-per-group/PureBasic/top-rank-per-group.purebasic b/Task/Top-rank-per-group/PureBasic/top-rank-per-group.purebasic new file mode 100644 index 0000000000..32593b8758 --- /dev/null +++ b/Task/Top-rank-per-group/PureBasic/top-rank-per-group.purebasic @@ -0,0 +1,58 @@ +Structure Employees + Name$ + ID$ + Salary.i + Department$ +EndStructure + +Procedure displayTopEarners(List MyEmployees.Employees(), n) + Protected filename$ = OpenFileRequester("Top rank per group", "DataFile.txt", "", 0) + If ReadFile(0, filename$) + Protected InData.Employees, txt.s, MaxNameLength + + While Eof(0) = 0 + AddElement(MyEmployees()) + txt = ReadString(0) + With MyEmployees() + \Name$ = StringField(txt, 1, ",") + \ID$ = StringField(txt, 2, ",") + \Salary = Val(StringField(txt, 3, ",")) + \Department$ = StringField(txt, 4, ",") + If Len(\Name$) > MaxNameLength: MaxNameLength = Len(\Name$): EndIf + EndWith + Wend + CloseFile(0) + Else + MessageRequester("Information", "Couldn't open the file!") + End + EndIf + + If OpenConsole() + Protected OldDepartment$, count + + SortStructuredList(MyEmployees(), #PB_Sort_Descending, OffsetOf(Employees\Salary), #PB_Sort_integer) + SortStructuredList(MyEmployees(), #PB_Sort_Ascending, OffsetOf(Employees\Department$), #PB_Sort_String) + ForEach MyEmployees() + With MyEmployees() + If \Department$ <> OldDepartment$ + If OldDepartment$ <> "" + PrintN(#CRLF$) + EndIf + OldDepartment$ = \Department$ + PrintN("Department " + \Department$ + #CRLF$ + "---------------") + PrintN(LSet("Name", MaxNameLength + 3) + LSet("ID", 7) + LSet("Salary", 7)) + count = 0 + EndIf + count + 1 + If count <= n + PrintN(LSet(\Name$, MaxNameLength + 1) + " " + RSet(\ID$, 7) + " $" + Str(\Salary)) + EndIf + EndWith + Next + PrintN(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + EndIf +EndProcedure + +NewList MyEmployees.Employees() + +displayTopEarners(MyEmployees(), 3) diff --git a/Task/Top-rank-per-group/Python/top-rank-per-group-1.py b/Task/Top-rank-per-group/Python/top-rank-per-group-1.py new file mode 100644 index 0000000000..78fa039d5f --- /dev/null +++ b/Task/Top-rank-per-group/Python/top-rank-per-group-1.py @@ -0,0 +1,30 @@ +from collections import defaultdict +from heapq import nlargest + +data = [('Employee Name', 'Employee ID', 'Salary', 'Department'), + ('Tyler Bennett', 'E10297', 32000, 'D101'), + ('John Rappl', 'E21437', 47000, 'D050'), + ('George Woltman', 'E00127', 53500, 'D101'), + ('Adam Smith', 'E63535', 18000, 'D202'), + ('Claire Buckman', 'E39876', 27800, 'D202'), + ('David McClellan', 'E04242', 41500, 'D101'), + ('Rich Holcomb', 'E01234', 49500, 'D202'), + ('Nathan Adams', 'E41298', 21900, 'D050'), + ('Richard Potter', 'E43128', 15900, 'D101'), + ('David Motsinger', 'E27002', 19250, 'D202'), + ('Tim Sampair', 'E03033', 27000, 'D101'), + ('Kim Arlich', 'E10001', 57000, 'D190'), + ('Timothy Grove', 'E16398', 29900, 'D190')] + +departments = defaultdict(list) +for rec in data[1:]: + departments[rec[-1]].append(rec) + +N = 3 +format = " %-15s " * len(data[0]) +for department, recs in sorted(departments.items()): + print ("Department %s" % department) + print (format % data[0]) + for rec in nlargest(N, recs, key=lambda rec: rec[-2]): + print (format % rec) + print('') diff --git a/Task/Top-rank-per-group/Python/top-rank-per-group-2.py b/Task/Top-rank-per-group/Python/top-rank-per-group-2.py new file mode 100644 index 0000000000..aaa48569ee --- /dev/null +++ b/Task/Top-rank-per-group/Python/top-rank-per-group-2.py @@ -0,0 +1,27 @@ +from collections import namedtuple +from itertools import groupby + +N = 2 + +db = '''Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190''' + +rows = db.split('\n') +DBRecord = namedtuple('DBRecord', rows[0].replace(' ', '_')) +records = [ DBRecord(*row.split(',')) for row in rows[1:] ] +records.sort(key = lambda record: (record.Department, -float(record.Salary))) +print '\n\n'.join('\n '.join([dpt] + [str(g) for g in grp][:N]) + for dpt, grp in groupby(records, + lambda record: record.Department)) diff --git a/Task/Top-rank-per-group/R/top-rank-per-group-1.r b/Task/Top-rank-per-group/R/top-rank-per-group-1.r new file mode 100644 index 0000000000..65b2896d76 --- /dev/null +++ b/Task/Top-rank-per-group/R/top-rank-per-group-1.r @@ -0,0 +1,15 @@ +dfr <- read.csv(tc <- textConnection( +"Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190")); close(tc) diff --git a/Task/Top-rank-per-group/R/top-rank-per-group-2.r b/Task/Top-rank-per-group/R/top-rank-per-group-2.r new file mode 100644 index 0000000000..f8aca8d9db --- /dev/null +++ b/Task/Top-rank-per-group/R/top-rank-per-group-2.r @@ -0,0 +1 @@ +with(dfr, tapply(Salary, Department, max)) diff --git a/Task/Top-rank-per-group/R/top-rank-per-group-3.r b/Task/Top-rank-per-group/R/top-rank-per-group-3.r new file mode 100644 index 0000000000..974510e740 --- /dev/null +++ b/Task/Top-rank-per-group/R/top-rank-per-group-3.r @@ -0,0 +1,13 @@ +get.top.N.salaries <- function(N) +{ + with(dfr, tapply(Salary, Department, + function(x) + { + sort(x); + lx <- length(x) + if(N >= lx) return(x) + x[-1:(N-lx)] + })) +} + +get.top.N.salaries(3) diff --git a/Task/Top-rank-per-group/R/top-rank-per-group-4.r b/Task/Top-rank-per-group/R/top-rank-per-group-4.r new file mode 100644 index 0000000000..7e2a003977 --- /dev/null +++ b/Task/Top-rank-per-group/R/top-rank-per-group-4.r @@ -0,0 +1,15 @@ +get.top.N.salaries2 <- function(N) +{ + #Sort data frame by Department, then by Salary + sorted <- dfr[with(dfr, order(Department, Salary, decreasing=TRUE)),] + #Split the dataframe up, by Department + bydept <- split(sorted, sorted$Department) + #Return the first N values (or all of them + lapply(bydept, + function(x) + { + n <- min(N, nrow(x)) + x[1:n,] + }) +} +get.top.N.salaries2(3) diff --git a/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx b/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx new file mode 100644 index 0000000000..8cb6c2a316 --- /dev/null +++ b/Task/Top-rank-per-group/REXX/top-rank-per-group.rexx @@ -0,0 +1,47 @@ +/*REXX program shows top N salaries in each department (internal table).*/ +parse arg topN . /*get number for top N salaries. */ +if topN=='' then topN=1 /*if none, then assume only 1. */ +say 'Finding top' topN 'salaries in each department.'; say +@.= + /*employee name, ID, salary, dept.*/ + @.1="Tyler Bennett,E10297,32000,D101" + @.2="John Rappl,E21437,47000,D050" + @.3="George Woltman,E00127,53500,D101" + @.4="Adam Smith,E63535,18000,D202" + @.5="Claire Buckman,E39876,27800,D202" + @.6="David McClellan,E04242,41500,D101" + @.7="Rich Holcomb,E01234,49500,D202" + @.8="Nathan Adams,E41298,21900,D050" + @.9="Richard Potter,E43128,15900,D101" +@.10="David Motsinger,E27002,19250,D202" +@.11="Tim Sampair,E03033,27000,D101" +@.12="Kim Arlich,E10001,57000,D190" +@.13="Timothy Grove,E16398,29900,D190" +depts= + do j=1 until @.j=='' /*build database elements. */ + parse var @.j name.j ',' id.j "," sal.j ',' dept.j + if wordpos(dept.j,depts)==0 then depts=depts dept.j + end /*j*/ +employees=j-1 +#d=words(depts) +say employees 'employees,' #d "departments:" depts; say + + do dep=1 for #d /*process each department. */ + Xdept=word(depts,dep) /*current dept. being processed. */ + + do topN /*process the top N salaries. */ + highsal=0 /*highest salary (so far). */ + h=0 /*point to the highest paid emp. */ + do e=1 for employees /*process each employee in Dept. */ + if dept.e\==Xdept | sal.e "" : n = n + 1 : wend ' get count of employees +dim depSal$(n) +for i = 1 to n + depSal$(i) = word$(perSal$,i,chr$(13)) +next i +sw = 1 +while sw = 1 + sw = 0 + for i = 1 to n -1 + if word$(depSal$(i),4,",")+word$(depSal$(i),3,",") > word$(depSal$(i+1),4,",")+word$(depSal$(i+1),3,",") then + temp$ = depSal$(i) + depSal$(i) = depSal$(i+1) + depSal$(i+1) = temp$ + sw = 1 + end if + next i +wend +print "Employee Name";chr$(9);"ID";chr$(9);"Salary" +for i = 1 to n + if dep$ <> word$(depSal$(i),4,",") then + dep$ = word$(depSal$(i),4,",") + print : print"Department:";dep$ + end if +print word$(depSal$(i),1,",");chr$(9);word$(depSal$(i),2,",");chr$(9);word$(depSal$(i),3,",") +next i diff --git a/Task/Top-rank-per-group/SMEQL/top-rank-per-group-1.smeql b/Task/Top-rank-per-group/SMEQL/top-rank-per-group-1.smeql new file mode 100644 index 0000000000..89410efc31 --- /dev/null +++ b/Task/Top-rank-per-group/SMEQL/top-rank-per-group-1.smeql @@ -0,0 +1,6 @@ +table: Employees +---------------- +empID +dept +empName +salary diff --git a/Task/Top-rank-per-group/SMEQL/top-rank-per-group-2.smeql b/Task/Top-rank-per-group/SMEQL/top-rank-per-group-2.smeql new file mode 100644 index 0000000000..cee5175246 --- /dev/null +++ b/Task/Top-rank-per-group/SMEQL/top-rank-per-group-2.smeql @@ -0,0 +1,3 @@ +srt = orderBy(Employees, [dept, salary], order) +top = group(srt, [(dept) dept2, max(order) order]) +join(srt, top, a.dept=b.dept2 and b.order - a.order < 6) diff --git a/Task/Top-rank-per-group/Scala/top-rank-per-group.scala b/Task/Top-rank-per-group/Scala/top-rank-per-group.scala new file mode 100644 index 0000000000..2e7cce61ba --- /dev/null +++ b/Task/Top-rank-per-group/Scala/top-rank-per-group.scala @@ -0,0 +1,25 @@ +object TopRank extends Application { + import scala.io._ + val data = """Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190""" + + class Employee(val name:String, val id:String, val salary:Int, val department:String) { + override def toString = id +"\t"+salary+"\t"+name + } + Source.fromString(data).getLines().map(_.split(",")).map(x => new Employee(x(0), x(1), x(2).toInt, x(3) )).toList // read data into list of employees + .sortBy(x => (x.department, -x.salary)).groupBy(_.department).foreach{ group => // sort and group by + println("Department: "+group._1) + group._2.take(3).foreach{x => println("\t"+x) } + } +} diff --git a/Task/Top-rank-per-group/TUSCRIPT/top-rank-per-group.tuscript b/Task/Top-rank-per-group/TUSCRIPT/top-rank-per-group.tuscript new file mode 100644 index 0000000000..72dc6f831b --- /dev/null +++ b/Task/Top-rank-per-group/TUSCRIPT/top-rank-per-group.tuscript @@ -0,0 +1,47 @@ +$$ MODE TUSCRIPT +MODE DATA +$$ SET dates=* +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190 +$$ MODE TUSCRIPT +SET nix=SPLIT (dates,":,:",EmployeeName,Employee_ID,Salary,Department) +SET d=MIXED_SORT (department),d=REDUCE(d) +SET index=DIGIT_INDEX(salary), index=REVERSE(index) +SET employeeName=INDEX_SORT (employeeName,index) +SET employee_ID =INDEX_SORT (employee_ID,index) +SET Salary=INDEX_SORT (salary,index) +SET Department=INDEX_SORT (Department,index) +COMPILE +LOOP l=d +PRINT "Department ", l +SET rtable=QUOTES (l) +BUILD R_TABLE pos = rtable +SET id=FILTER_INDEX (department,pos,-) +RELEASE R_TABLE pos +SET en =SELECT (employeeName,#id) +SET ei =SELECT (employee_ID,#id) +SET sal =SELECT (salary,#id) +SET he =CENTER ("employeeName",-16) +SET hi =CENTER ("employee ID",-11) +SET hs =CENTER ("Salary",+10) +SET line=REPEAT ("-",37) +PRINT he,hi,hs +PRINT line + LOOP e=en,i=ei,s=sal + SET e=CENTER (e,-16), i=CENTER (i,-11), s=CENTER (s,+10) + PRINT e,i,s + ENDLOOP +PRINT " " +ENDLOOP +ENDCOMPILE diff --git a/Task/Top-rank-per-group/Tcl/top-rank-per-group.tcl b/Task/Top-rank-per-group/Tcl/top-rank-per-group.tcl new file mode 100644 index 0000000000..a840b497ea --- /dev/null +++ b/Task/Top-rank-per-group/Tcl/top-rank-per-group.tcl @@ -0,0 +1,34 @@ +package require Tcl 8.5 + +set text {Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190} + +set data [dict create] +foreach line [split $text \n] { + lassign [split $line ,] name id salary dept + dict lappend data $dept [list $name $id $salary] +} + +proc top_n_salaries {n data} { + incr n -1 + dict for {dept employees} $data { + puts "Department $dept" + foreach emp [lrange [lsort -integer -decreasing -index 2 $employees] 0 $n] { + puts [format " %-20s %-8s %8d" {*}$emp] + } + puts "" + } +} + +top_n_salaries 3 $data diff --git a/Task/Top-rank-per-group/Ursala/top-rank-per-group.ursala b/Task/Top-rank-per-group/Ursala/top-rank-per-group.ursala new file mode 100644 index 0000000000..70218f3055 --- /dev/null +++ b/Task/Top-rank-per-group/Ursala/top-rank-per-group.ursala @@ -0,0 +1,26 @@ +#import std +#import nat + +data = + +-[ +Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190]- + +top "n" = @tt sep`,*; mat0+ ^C(~&hz,mat`,*yS)*+ take/*"n"+ *zK2 (nleq+ %np~~)-3 to it and then computing its square and square root. diff --git a/Task/Topic-variable/J/topic-variable.j b/Task/Topic-variable/J/topic-variable.j new file mode 100644 index 0000000000..7852f46994 --- /dev/null +++ b/Task/Topic-variable/J/topic-variable.j @@ -0,0 +1,3 @@ + example=: *:, %: NB. *: is square, %: is square root + example 3 +9 1.73205 diff --git a/Task/Topic-variable/Perl-6/topic-variable.pl6 b/Task/Topic-variable/Perl-6/topic-variable.pl6 new file mode 100644 index 0000000000..be3ecc6f15 --- /dev/null +++ b/Task/Topic-variable/Perl-6/topic-variable.pl6 @@ -0,0 +1,3 @@ +given 3 { + .say for $_**2, .sqrt; +} diff --git a/Task/Topic-variable/Perl/topic-variable-1.pl b/Task/Topic-variable/Perl/topic-variable-1.pl new file mode 100644 index 0000000000..c377a70838 --- /dev/null +++ b/Task/Topic-variable/Perl/topic-variable-1.pl @@ -0,0 +1,2 @@ +my $_ = 3; +print for $_**2, "\n", sqrt; diff --git a/Task/Topic-variable/Perl/topic-variable-2.pl b/Task/Topic-variable/Perl/topic-variable-2.pl new file mode 100644 index 0000000000..bb1de1ff17 --- /dev/null +++ b/Task/Topic-variable/Perl/topic-variable-2.pl @@ -0,0 +1,17 @@ +for ($_ = 0; $_ <= 9; $_++) { + print "Outer"; + print "$_\n"; + # The inner loop will not nest properly unless + # it is preceded by a my statement + my $_; # This is required to nest the inner loop + for ($_ = 0; $_ <= 9; $_++) { + print "Inner"; + print "$_\n"; + } + # Alternatively we can use a local keyword in the + # inner loop declaration instead of a my statement + for (local $_ = 0; $_ <= 9; $_++) { + print "Alternative"; + print "$_\n"; + } +} diff --git a/Task/Topic-variable/UNIX-Shell/topic-variable.sh b/Task/Topic-variable/UNIX-Shell/topic-variable.sh new file mode 100644 index 0000000000..726e891eb3 --- /dev/null +++ b/Task/Topic-variable/UNIX-Shell/topic-variable.sh @@ -0,0 +1,2 @@ +multiply 3 4 # We assume this user defined function has been previously defined +echo $? # This will output 12, but $? will now be zero indicating a successful echo diff --git a/Task/Topological-sort/0DESCRIPTION b/Task/Topological-sort/0DESCRIPTION new file mode 100644 index 0000000000..cc231ad98e --- /dev/null +++ b/Task/Topological-sort/0DESCRIPTION @@ -0,0 +1,30 @@ +Given a mapping between items, and items they depend on, a [[wp:Topological sorting|topological sort]] orders items so that no item precedes an item it depends upon. + +The compiling of a library in the [[wp:VHDL|VHDL]] language has the constraint that a library must be compiled after any library it depends on. A tool exists that extracts library dependencies. The task is to '''write a function that will return a valid compile order of VHDL libraries from their dependencies.''' + +* Assume library names are single words. +* Items mentioned as only dependants, (sic), have no dependants of their own, but their order of compiling must be given. +* Any self dependencies should be ignored. +* Any un-orderable dependencies should be flagged. + +Use the following data as an example: +
+LIBRARY          LIBRARY DEPENDENCIES
+=======          ====================
+des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
+dw01             ieee dw01 dware gtech
+dw02             ieee dw02 dware
+dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
+dw04             dw04 ieee dw01 dware gtech
+dw05             dw05 ieee dware
+dw06             dw06 ieee dware
+dw07             ieee dware
+dware            ieee dware
+gtech            ieee gtech
+ramlib           std ieee
+std_cell_lib     ieee std_cell_lib
+synopsys         
+ +Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. + +C.f: [[Topological sort/Extracted top item]]. diff --git a/Task/Topological-sort/Ada/topological-sort-1.ada b/Task/Topological-sort/Ada/topological-sort-1.ada new file mode 100644 index 0000000000..80fa875fa3 --- /dev/null +++ b/Task/Topological-sort/Ada/topological-sort-1.ada @@ -0,0 +1,52 @@ +with Ada.Containers.Vectors; use Ada.Containers; + +package Digraphs is + + type Node_Idx_With_Null is new Natural; + subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last; + -- a Node_Index is a number from 1, 2, 3, ... and the representative of a node + + type Graph_Type is tagged private; + + -- make sure Node is in Graph (possibly without connections) + procedure Add_Node + (Graph: in out Graph_Type'Class; Node: Node_Index); + + -- insert an edge From->To into Graph; do nothing if already there + procedure Add_Connection + (Graph: in out Graph_Type'Class; From, To: Node_Index); + + -- get the largest Node_Index used in any Add_Node or Add_Connection op. + -- iterate over all nodes of Graph: "for I in 1 .. Graph.Node_Count loop ..." + function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null; + + -- remove an edge From->To from Fraph; do nothing if not there + -- Graph.Node_Count is not changed + procedure Del_Connection + (Graph: in out Graph_Type'Class; From, To: Node_Index); + + -- check if an edge From->to exists in Graph + function Connected + (Graph: Graph_Type; From, To: Node_Index) return Boolean; + + -- data structure to store a list of nodes + package Node_Vec is new Vectors(Positive, Node_Index); + + -- get a list of all nodes From->Somewhere in Graph + function All_Connections + (Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector; + + Graph_Is_Cyclic: exception; + + -- a depth-first search to find a topological sorting of the nodes + -- raises Graph_Is_Cyclic if no topological sorting is possible + function Top_Sort + (Graph: Graph_Type) return Node_Vec.Vector; + +private + + package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec."="); + + type Graph_Type is new Conn_Vec.Vector with null record; + +end Digraphs; diff --git a/Task/Topological-sort/Ada/topological-sort-2.ada b/Task/Topological-sort/Ada/topological-sort-2.ada new file mode 100644 index 0000000000..4bb55469e2 --- /dev/null +++ b/Task/Topological-sort/Ada/topological-sort-2.ada @@ -0,0 +1,106 @@ +package body Digraphs is + + function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null is + begin + return Node_Idx_With_Null(Graph.Length); + end Node_Count; + + procedure Add_Node(Graph: in out Graph_Type'Class; Node: Node_Index) is + begin + for I in Node_Index range Graph.Node_Count+1 .. Node loop + Graph.Append(Node_Vec.Empty_Vector); + end loop; + end Add_Node; + + procedure Add_Connection + (Graph: in out Graph_Type'Class; From, To: Node_Index) is + begin + Graph.Add_Node(Node_Index'Max(From, To)); + declare + Connection_List: Node_Vec.Vector := Graph.Element(From); + begin + for I in Connection_List.First_Index .. Connection_List.Last_Index loop + if Connection_List.Element(I) >= To then + if Connection_List.Element(I) = To then + return; -- if To is already there, don't add it a second time + else -- I is the first index with Element(I)>To, insert To here + Connection_List.Insert(Before => I, New_Item => To); + Graph.Replace_Element(From, Connection_List); + return; + end if; + end if; + end loop; + -- there was no I with no Element(I) > To, so insert To at the end + Connection_List.Append(To); + Graph.Replace_Element(From, Connection_List); + return; + end; + end Add_Connection; + + procedure Del_Connection + (Graph: in out Graph_Type'Class; From, To: Node_Index) is + Connection_List: Node_Vec.Vector := Graph.Element(From); + begin + for I in Connection_List.First_Index .. Connection_List.Last_Index loop + if Connection_List.Element(I) = To then + Connection_List.Delete(I); + Graph.Replace_Element(From, Connection_List); + return; -- we are done + end if; + end loop; + end Del_Connection; + + function Connected + (Graph: Graph_Type; From, To: Node_Index) return Boolean is + Connection_List: Node_Vec.Vector renames Graph.Element(From); + begin + for I in Connection_List.First_Index .. Connection_List.Last_Index loop + if Connection_List.Element(I) = To then + return True; + end if; + end loop; + return False; + end Connected; + + function All_Connections + (Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector is + begin + return Graph.Element(From); + end All_Connections; + + function Top_Sort + (Graph: Graph_Type) return Node_Vec.Vector is + + Result: Node_Vec.Vector; + Visited: array(1 .. Graph.Node_Count) of Boolean := (others => False); + Active: array(1 .. Graph.Node_Count) of Boolean := (others => False); + + procedure Visit(Node: Node_Index) is + begin + if not Visited(Node) then + Visited(Node) := True; + Active(Node) := True; + declare + Cons: Node_Vec.Vector := All_Connections(Graph, Node); + begin + for Idx in Cons.First_Index .. Cons.Last_Index loop + Visit(Cons.Element(Idx)); + end loop; + end; + Active(Node) := False; + Result.Append(Node); + else + if Active(Node) then + raise Constraint_Error with "Graph is Cyclic"; + end if; + end if; + end Visit; + + begin + for Some_Node in Visited'Range loop + Visit(Some_Node); + end loop; + return Result; + end Top_Sort; + +end Digraphs; diff --git a/Task/Topological-sort/Ada/topological-sort-3.ada b/Task/Topological-sort/Ada/topological-sort-3.ada new file mode 100644 index 0000000000..ed1952b9ac --- /dev/null +++ b/Task/Topological-sort/Ada/topological-sort-3.ada @@ -0,0 +1,42 @@ +private with Ada.Containers.Indefinite_Vectors; + +generic + type Index_Type_With_Null is new Natural; +package Set_Of_Names is + subtype Index_Type is Index_Type_With_Null + range 1 .. Index_Type_With_Null'Last; + -- manage a set of strings; + -- each string in the set is assigned a unique index of type Index_Type + + type Set is tagged private; + + -- inserts Name into Names; do nothing if already there; + procedure Add(Names: in out Set; Name: String); + + -- Same operation, additionally emiting Index=Names.Idx(Name) + procedure Add(Names: in out Set; Name: String; Index: out Index_Type); + + -- remove Name from Names; do nothing if not found + -- the removal may change the index of other strings in Names + procedure Sub(Names: in out Set; Name: String); + + -- returns the unique index of Name in Set; or 0 if Name is not there + function Idx(Names: Set; Name: String) return Index_Type_With_Null; + + -- returns the unique name of Index; + function Name(Names: Set; Index: Index_Type) return String; + + -- first index, last index and total number of names in set + -- to iterate over Names, use "for I in Names.Start .. Names.Stop loop ... + function Start(Names: Set) return Index_Type; + function Stop(Names: Set) return Index_Type_With_Null; + function Size(Names: Set) return Index_Type_With_Null; + +private + + package Vecs is new Ada.Containers.Indefinite_Vectors + (Index_Type => Index_Type, Element_Type => String); + + type Set is new Vecs.Vector with null record; + +end Set_Of_Names; diff --git a/Task/Topological-sort/Ada/topological-sort-4.ada b/Task/Topological-sort/Ada/topological-sort-4.ada new file mode 100644 index 0000000000..651146750c --- /dev/null +++ b/Task/Topological-sort/Ada/topological-sort-4.ada @@ -0,0 +1,68 @@ +package body Set_Of_Names is + + use type Ada.Containers.Count_Type, Vecs.Cursor; + + function Start(Names: Set) return Index_Type is + begin + if Names.Length = 0 then + return 1; + else + return Names.First_Index; + end if; + end Start; + + function Stop(Names: Set) return Index_Type_With_Null is + begin + if Names.Length=0 then + return 0; + else + return Names.Last_Index; + end if; + end Stop; + + function Size(Names: Set) return Index_Type_With_Null is + begin + return Index_Type_With_Null(Names.Length); + end Size; + + procedure Add(Names: in out Set; Name: String; Index: out Index_Type) is + I: Index_Type_With_Null := Names.Idx(Name); + begin + if I = 0 then -- Name is not yet in Set + Names.Append(Name); + Index := Names.Stop; + else + Index := I; + end if; + end Add; + + procedure Add(Names: in out Set; Name: String) is + I: Index_Type; + begin + Names.Add(Name, I); + end Add; + + procedure Sub(Names: in out Set; Name: String) is + I: Index_Type_With_Null := Names.Idx(Name); + begin + if I /= 0 then -- Name is in set + Names.Delete(I); + end if; + end Sub; + + function Idx(Names: Set; Name: String) return Index_Type_With_Null is + begin + for I in Names.First_Index .. Names.Last_Index loop + if Names.Element(I) = Name then + return I; + end if; + end loop; + return 0; + end Idx; + + function Name(Names: Set; Index: Index_Type) return String is + begin + return Names.Element(Index); + end Name; + +end Set_Of_Names; diff --git a/Task/Topological-sort/Ada/topological-sort-5.ada b/Task/Topological-sort/Ada/topological-sort-5.ada new file mode 100644 index 0000000000..449f63e0d0 --- /dev/null +++ b/Task/Topological-sort/Ada/topological-sort-5.ada @@ -0,0 +1,83 @@ +with Ada.Text_IO, Digraphs, Set_Of_Names, Ada.Command_Line; + +procedure Toposort is + + -- shortcuts for package names, intantiation of generic package + package TIO renames Ada.Text_IO; + package DG renames Digraphs; + package SN is new Set_Of_Names(DG.Node_Idx_With_Null); + + -- reat the graph from the file with the given Filename + procedure Read(Filename: String; G: out DG.Graph_Type; N: out SN.Set) is + + -- finds the first word in S(Start .. S'Last), delimited by spaces + procedure Find_Token(S: String; Start: Positive; + First: out Positive; Last: out Natural) is + + begin + First := Start; + while First <= S'Last and then S(First)= ' ' loop + First := First + 1; + end loop; + Last := First-1; + while Last < S'Last and then S(Last+1) /= ' ' loop + Last := Last + 1; + end loop; + end Find_Token; + + File: TIO.File_Type; + begin + TIO.Open(File, TIO.In_File, Filename); + TIO.Skip_Line(File, 2); + -- the first two lines contain header and "===...===" + while not TIO.End_Of_File(File) loop + declare + Line: String := TIO.Get_Line(File); + First: Positive; + Last: Natural; + To, From: DG.Node_Index; + begin + Find_Token(Line, Line'First, First, Last); + if Last >= First then + N.Add(Line(First .. Last), From); + G.Add_Node(From); + loop + Find_Token(Line, Last+1, First, Last); + exit when Last < First; + N.Add(Line(First .. Last), To); + G.Add_Connection(From, To); + end loop; + end if; + end; + end loop; + TIO.Close(File); + end Read; + + Graph: DG.Graph_Type; + Names: SN.Set; + +begin + Read(Ada.Command_Line.Argument(1), Graph, Names); + + -- eliminat self-cycles + for Start in 1 .. Graph.Node_Count loop + Graph.Del_Connection(Start, Start); + end loop; + + -- perform the topological sort and output the result + declare + Result: DG.Node_Vec.Vector; + begin + Result := Graph.Top_Sort; + for Index in Result.First_Index .. Result.Last_Index loop + TIO.Put(Names.Name(Result.Element(Index))); + if Index < Result.Last_Index then + TIO.Put(" -> "); + end if; + end loop; + TIO.New_Line; + exception + when DG.Graph_Is_Cyclic => + TIO.Put_Line("There is no topological sorting -- the Graph is cyclic!"); + end; +end Toposort; diff --git a/Task/Topological-sort/Bracmat/topological-sort.bracmat b/Task/Topological-sort/Bracmat/topological-sort.bracmat new file mode 100644 index 0000000000..8420164763 --- /dev/null +++ b/Task/Topological-sort/Bracmat/topological-sort.bracmat @@ -0,0 +1,49 @@ +( ("des_system_lib".std synopsys "std_cell_lib" "des_system_lib" dw02 dw01 ramlib ieee) + (dw01.ieee dw01 dware gtech) + (dw02.ieee dw02 dware) + (dw03.std synopsys dware dw03 dw02 dw01 ieee gtech) + (dw04.dw04 ieee dw01 dware gtech) + (dw05.dw05 ieee dware) + (dw06.dw06 ieee dware) + (dw07.ieee dware) + (dware.ieee dware) + (gtech.ieee gtech) + (ramlib.std ieee) + ("std_cell_lib".ieee "std_cell_lib") + (synopsys.) + (cycle-11.cycle-12) + (cycle-12.cycle-11) + (cycle-21.dw01 cycle-22 dw02 dw03) + (cycle-22.cycle-21 dw01 dw04) + : ?libdeps +& :?indeps +& ( toposort + = A Z res module dependants todo done + . !arg:(?todo.?done) + & ( areDone + = + . !arg: + | !arg + : ( %@ + : [%( !module+!done+!indeps:?+(? !sjt ?)+? + | ~(!libdeps:? (!sjt.?) ?) + & !sjt !indeps:?indeps + ) + ) + ?arg + & areDone$!arg + ) + & ( !todo + : ?A + (?module.?dependants&areDone$!dependants) + ( ?Z + & toposort$(!A !Z.!done !module):?res + ) + & !res + | (!todo.!done) + ) + ) +& toposort$(!libdeps.):(?cycles.?res) +& out$(" +compile order:" !indeps !res "\ncycles:" !cycles) +); diff --git a/Task/Topological-sort/C/topological-sort-1.c b/Task/Topological-sort/C/topological-sort-1.c new file mode 100644 index 0000000000..15516180a5 --- /dev/null +++ b/Task/Topological-sort/C/topological-sort-1.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include + +char input[] = + "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n" + "dw01 ieee dw01 dware gtech\n" + "dw02 ieee dw02 dware\n" + "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n" + "dw04 dw04 ieee dw01 dware gtech\n" + "dw05 dw05 ieee dware\n" + "dw06 dw06 ieee dware\n" + "dw07 ieee dware\n" + "dware ieee dware\n" + "gtech ieee gtech\n" + "ramlib std ieee\n" + "std_cell_lib ieee std_cell_lib\n" + "synopsys\n" + "cycle_11 cycle_12\n" + "cycle_12 cycle_11\n" + "cycle_21 dw01 cycle_22 dw02 dw03\n" + "cycle_22 cycle_21 dw01 dw04"; + +typedef struct item_t item_t, *item; +struct item_t { const char *name; int *deps, n_deps, idx, depth; }; + +int get_item(item *list, int *len, const char *name) +{ + int i; + item lst = *list; + + for (i = 0; i < *len; i++) + if (!strcmp(lst[i].name, name)) return i; + + lst = *list = realloc(lst, ++*len * sizeof(item_t)); + i = *len - 1; + memset(lst + i, 0, sizeof(item_t)); + lst[i].idx = i; + lst[i].name = name; + return i; +} + +void add_dep(item it, int i) +{ + if (it->idx == i) return; + it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int)); + it->deps[it->n_deps++] = i; +} + +int parse_input(item *ret) +{ + int n_items = 0; + int i, parent, idx; + item list = 0; + + char *s, *e, *word, *we; + for (s = input; ; s = 0) { + if (!(s = strtok_r(s, "\n", &e))) break; + + for (i = 0, word = s; ; i++, word = 0) { + if (!(word = strtok_r(word, " \t", &we))) break; + idx = get_item(&list, &n_items, word); + + if (!i) parent = idx; + else add_dep(list + parent, idx); + } + } + + *ret = list; + return n_items; +} + +/* recursively resolve compile order; negative means loop */ +int get_depth(item list, int idx, int bad) +{ + int max, i, t; + + if (!list[idx].deps) + return list[idx].depth = 1; + + if ((t = list[idx].depth) < 0) return t; + + list[idx].depth = bad; + for (max = i = 0; i < list[idx].n_deps; i++) { + if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) { + max = t; + break; + } + if (max < t + 1) max = t + 1; + } + return list[idx].depth = max; +} + +int main() +{ + int i, j, n, bad = -1, max, min; + item items; + n = parse_input(&items); + + for (i = 0; i < n; i++) + if (!items[i].depth && get_depth(items, i, bad) < 0) bad--; + + for (i = 0, max = min = 0; i < n; i++) { + if (items[i].depth > max) max = items[i].depth; + if (items[i].depth < min) min = items[i].depth; + } + + printf("Compile order:\n"); + for (i = min; i <= max; i++) { + if (!i) continue; + + if (i < 0) printf(" [unorderable]"); + else printf("%d:", i); + + for (j = 0; j < n || !putchar('\n'); j++) + if (items[j].depth == i) + printf(" %s", items[j].name); + } + + return 0; +} diff --git a/Task/Topological-sort/C/topological-sort-2.c b/Task/Topological-sort/C/topological-sort-2.c new file mode 100644 index 0000000000..1a790afb63 --- /dev/null +++ b/Task/Topological-sort/C/topological-sort-2.c @@ -0,0 +1,7 @@ +Compile order: + [unorderable] cycle_21 cycle_22 + [unorderable] cycle_11 cycle_12 +1: std synopsys ieee +2: std_cell_lib ramlib dware gtech +3: dw02 dw01 dw05 dw06 dw07 +4: des_system_lib dw03 dw04 diff --git a/Task/Topological-sort/Clojure/topological-sort-1.clj b/Task/Topological-sort/Clojure/topological-sort-1.clj new file mode 100644 index 0000000000..a893bef8d2 --- /dev/null +++ b/Task/Topological-sort/Clojure/topological-sort-1.clj @@ -0,0 +1,72 @@ +(use 'clojure.set) +(use 'clojure.contrib.seq-utils) + +(defn dep + "Constructs a single-key dependence, represented as a map from + item to a set of items, ensuring that item is not in the set." + [item items] + {item (difference (set items) (list item))}) + +(defn empty-dep + "Constructs a single-key dependence from item to an empty set." + [item] + (dep item '())) + +(defn pair-dep + "Invokes dep after destructuring item and items from the argument." + [[item items]] + (dep item items)) + +(defn default-deps + "Constructs a default dependence map taking every item + in the argument to an empty set" + [items] + (apply merge-with union (map empty-dep (flatten items)))) + +(defn declared-deps + "Constructs a dependence map from a list containaining + alternating items and list of their predecessor items." + [items] + (apply merge-with union (map pair-dep (partition 2 items)))) + +(defn deps + "Constructs a full dependence map containing both explicitly + represented dependences and default empty dependences for + items without explicit predecessors." + [items] + (merge (default-deps items) (declared-deps items))) + +(defn no-dep-items + "Returns all keys from the argument which have no (i.e. empty) dependences." + [deps] + (filter #(empty? (deps %)) (keys deps))) + +(defn remove-items + "Returns a dependence map with the specified items removed from keys + and from all dependence sets of remaining keys." + [deps items] + (let [items-to-remove (set items) + remaining-keys (difference (set (keys deps)) items-to-remove) + remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))] + (apply merge (map remaining-deps remaining-keys)))) + +(defn topo-sort-deps + "Given a dependence map, returns either a list of items in which each item + follows all of its predecessors, or a string showing the items among which + there is a cyclic dependence preventing a linear order." + [deps] + (loop [remaining-deps deps + result '()] + (if (empty? remaining-deps) + (reverse result) + (let [ready-items (no-dep-items remaining-deps)] + (if (empty? ready-items) + (str "ERROR: cycles remain among " (keys remaining-deps)) + (recur (remove-items remaining-deps ready-items) + (concat ready-items result))))))) + +(defn topo-sort + "Given a list of alternating items and predecessor lists, constructs a + full dependence map and then applies topo-sort-deps to that map." + [items] + (topo-sort-deps (deps items))) diff --git a/Task/Topological-sort/Clojure/topological-sort-2.clj b/Task/Topological-sort/Clojure/topological-sort-2.clj new file mode 100644 index 0000000000..996031f29e --- /dev/null +++ b/Task/Topological-sort/Clojure/topological-sort-2.clj @@ -0,0 +1,20 @@ +(def good-sample + '(:des_system_lib (:std :synopsys :std_cell_lib :des_system_lib :dw02 :dw01 :ramlib :ieee) + :dw01 (:ieee :dw01 :dware :gtech) + :dw02 (:ieee :dw02 :dware) + :dw03 (:std :synopsys :dware :dw03 :dw02 :dw01 :ieee :gtech) + :dw04 (:dw04 :ieee :dw01 :dware :gtech) + :dw05 (:dw05 :ieee :dware) + :dw06 (:dw06 :ieee :dware) + :dw07 (:ieee :dware) + :dware (:ieee :dware) + :gtech (:ieee :gtech) + :ramlib (:std :ieee) + :std_cell_lib (:ieee :std_cell_lib) + :synopsys ())) + +(def cyclic-dependence + '(:dw01 (:dw04))) + +(def bad-sample + (concat cyclic-dependence good-sample)) diff --git a/Task/Topological-sort/Clojure/topological-sort-3.clj b/Task/Topological-sort/Clojure/topological-sort-3.clj new file mode 100644 index 0000000000..b9ada35ee4 --- /dev/null +++ b/Task/Topological-sort/Clojure/topological-sort-3.clj @@ -0,0 +1,6 @@ +Clojure 1.1.0 +1:1 user=> # +1:2 topo=> (topo-sort good-sample) +(:std :synopsys :ieee :gtech :ramlib :dware :std_cell_lib :dw07 :dw06 :dw05 :dw01 :dw02 :des_system_lib :dw03 :dw04) +1:3 topo=> (topo-sort bad-sample) +"ERROR: cycles remain among (:dw01 :dw04 :dw03 :des_system_lib)" diff --git a/Task/Topological-sort/CoffeeScript/topological-sort.coffeescript b/Task/Topological-sort/CoffeeScript/topological-sort.coffeescript new file mode 100644 index 0000000000..c565329b2c --- /dev/null +++ b/Task/Topological-sort/CoffeeScript/topological-sort.coffeescript @@ -0,0 +1,95 @@ +toposort = (targets) -> + # targets is hash of sets, where keys are parent nodes and + # where values are sets that contain nodes that must precede the parent + + # Start by identifying obviously independent nodes + independents = [] + do -> + for k of targets + if targets[k].cnt == 0 + delete targets[k] + independents.push k + + # Note reverse dependencies for theoretical O(M+N) efficiency. + reverse_deps = [] + do -> + for k of targets + for child of targets[k].v + reverse_deps[child] ?= [] + reverse_deps[child].push k + + # Now be greedy--start with independent nodes, then start + # breaking dependencies, and keep going as long as we still + # have independent nodes left. + result = [] + while independents.length > 0 + k = independents.pop() + result.push k + for parent in reverse_deps[k] or [] + set_remove targets[parent], k + if targets[parent].cnt == 0 + independents.push parent + delete targets[parent] + + # Show unresolvable dependencies + for k of targets + console.log "WARNING: node #{k} is part of cyclical dependency" + result + +parse_deps = -> + # parse string data, remove self-deps, and fill in gaps + # + # e.g. this would transform {a: "a b c", d: "e"} to this: + # a: set(b, c) + # b: set() + # c: set() + # d: set(e) + # e: set() + targets = {} + deps = set() + for k, v of data + targets[k] = set() + children = v.split(' ') + for child in children + continue if child == '' + set_add targets[k], child unless child == k + set_add deps, child + + # make sure even leaf nodes are in targets + for dep of deps.v + if dep not of targets + targets[dep] = set() + targets + +set = -> + cnt: 0 + v: {} + +set_add = (s, e) -> + return if s.v[e] + s.cnt += 1 + s.v[e] = true + +set_remove = (s, e) -> + return if !s.v[e] + s.cnt -= 1 + delete s.v[e] + +data = + des_system_lib: "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee" + dw01: "ieee dw01 dware gtech" + dw02: "ieee dw02 dware" + dw03: "std synopsys dware dw03 dw02 dw01 ieee gtech" + dw04: "dw04 ieee dw01 dware gtech" + dw05: "dw05 ieee dware" + dw06: "dw06 ieee dware" + dw07: "ieee dware" + dware: "ieee dware" + gtech: "ieee gtech" + ramlib: "std ieee" + std_cell_lib: "ieee std_cell_lib" + synopsys: "" + + +targets = parse_deps() +console.log toposort targets diff --git a/Task/Topological-sort/Common-Lisp/topological-sort-1.lisp b/Task/Topological-sort/Common-Lisp/topological-sort-1.lisp new file mode 100644 index 0000000000..21404e3865 --- /dev/null +++ b/Task/Topological-sort/Common-Lisp/topological-sort-1.lisp @@ -0,0 +1,47 @@ +(defun topological-sort (graph &key (test 'eql)) + "Graph is an association list whose keys are objects and whose +values are lists of objects on which the corresponding key depends. +Test is used to compare elements, and should be a suitable test for +hash-tables. Topological-sort returns two values. The first is a +list of objects sorted toplogically. The second is a boolean +indicating whether all of the objects in the input graph are present +in the topological ordering (i.e., the first value)." + (let ((entries (make-hash-table :test test))) + (flet ((entry (vertex) + "Return the entry for vertex. Each entry is a cons whose + car is the number of outstanding dependencies of vertex + and whose cdr is a list of dependants of vertex." + (multiple-value-bind (entry presentp) (gethash vertex entries) + (if presentp entry + (setf (gethash vertex entries) (cons 0 '())))))) + ;; populate entries initially + (dolist (vertex graph) + (destructuring-bind (vertex &rest dependencies) vertex + (let ((ventry (entry vertex))) + (dolist (dependency dependencies) + (let ((dentry (entry dependency))) + (unless (funcall test dependency vertex) + (incf (car ventry)) + (push vertex (cdr dentry)))))))) + ;; L is the list of sorted elements, and S the set of vertices + ;; with no outstanding dependencies. + (let ((L '()) + (S (loop for entry being each hash-value of entries + using (hash-key vertex) + when (zerop (car entry)) collect vertex))) + ;; Until there are no vertices with no outstanding dependencies, + ;; process vertices from S, adding them to L. + (do* () ((endp S)) + (let* ((v (pop S)) (ventry (entry v))) + (remhash v entries) + (dolist (dependant (cdr ventry) (push v L)) + (when (zerop (decf (car (entry dependant)))) + (push dependant S))))) + ;; return (1) the list of sorted items, (2) whether all items + ;; were sorted, and (3) if there were unsorted vertices, the + ;; hash table mapping these vertices to their dependants + (let ((all-sorted-p (zerop (hash-table-count entries)))) + (values (nreverse L) + all-sorted-p + (unless all-sorted-p + entries))))))) diff --git a/Task/Topological-sort/Common-Lisp/topological-sort-2.lisp b/Task/Topological-sort/Common-Lisp/topological-sort-2.lisp new file mode 100644 index 0000000000..0caf454234 --- /dev/null +++ b/Task/Topological-sort/Common-Lisp/topological-sort-2.lisp @@ -0,0 +1,20 @@ +> (defparameter *dependency-graph* + '((des-system-lib std synopsys std-cell-lib des-system-lib dw02 dw01 ramlib ieee) + (dw01 ieee dw01 dware gtech) + (dw02 ieee dw02 dware) + (dw03 std synopsys dware dw03 dw02 dw01 ieee gtech) + (dw04 dw04 ieee dw01 dware gtech) + (dw05 dw05 ieee dware) + (dw06 dw06 ieee dware) + (dw07 ieee dware) + (dware ieee dware) + (gtech ieee gtech) + (ramlib std ieee) + (std-cell-lib ieee std-cell-lib) + (synopsys))) +*DEPENDENCY-GRAPH* + +> (topological-sort *dependency-graph*) +(IEEE DWARE DW02 DW05 DW06 DW07 GTECH DW01 DW04 STD-CELL-LIB SYNOPSYS STD DW03 RAMLIB DES-SYSTEM-LIB) +T +NIL diff --git a/Task/Topological-sort/Common-Lisp/topological-sort-3.lisp b/Task/Topological-sort/Common-Lisp/topological-sort-3.lisp new file mode 100644 index 0000000000..f57e89b787 --- /dev/null +++ b/Task/Topological-sort/Common-Lisp/topological-sort-3.lisp @@ -0,0 +1,28 @@ +> (defparameter *dependency-graph* + '((des-system-lib std synopsys std-cell-lib des-system-lib dw02 dw01 ramlib ieee) + (dw01 ieee dw01 dw04 dware gtech) + (dw02 ieee dw02 dware) + (dw03 std synopsys dware dw03 dw02 dw01 ieee gtech) + (dw04 dw04 ieee dw01 dware gtech) + (dw05 dw05 ieee dware) + (dw06 dw06 ieee dware) + (dw07 ieee dware) + (dware ieee dware) + (gtech ieee gtech) + (ramlib std ieee) + (std-cell-lib ieee std-cell-lib) + (synopsys))) +*DEPENDENCY-GRAPH* + +> (topological-sort *dependency-graph*) +(IEEE DWARE DW02 DW05 DW06 DW07 GTECH STD-CELL-LIB SYNOPSYS STD RAMLIB) +NIL +# + +> (describe (third /)) + +# is a HASH-TABLE +DW01 (1 DW04 DW03 DES-SYSTEM-LIB) +DW04 (1 DW01) +DW03 (1) +DES-SYSTEM-LIB (1) diff --git a/Task/Topological-sort/D/topological-sort.d b/Task/Topological-sort/D/topological-sort.d new file mode 100644 index 0000000000..c9f88e9bbf --- /dev/null +++ b/Task/Topological-sort/D/topological-sort.d @@ -0,0 +1,74 @@ +import std.stdio, std.string, std.algorithm, std.range; + +alias string[][string] TDependencies; + +final class ArgumentException : Exception { + this(string text) { + super(text); + } +} + +string[][] topoSort(TDependencies d) { + foreach (k, v; d) + d[k] = v.sort().uniq().filter!(s => s != k)().array(); + foreach (s; d.values.join().sort().uniq()) + if (s !in d) + d[s] = []; + + string[][] sorted; + while (true) { + string[] ordered; + + foreach (item, dep; d) + if (dep.empty) + ordered ~= item; + if (!ordered.empty) + sorted ~= ordered.sort().release(); + else + break; + + TDependencies dd; + foreach (item, dep; d) + if (!canFind(ordered, item)) + dd[item] = dep.filter!(s => !ordered.canFind(s))() + .array(); + d = dd; + } + + if (d.length > 0) + throw new ArgumentException(format( + "A cyclic dependency exists amongst:\n%s", d)); + + return sorted; +} + +void main() { + immutable data = +"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys"; + + TDependencies deps; + foreach (line; data.splitLines()) + deps[line.split()[0]] = line.split()[1 .. $]; + + auto depw = deps.dup; + foreach (idx, subOrder; topoSort(depw)) + writefln("#%d : %s", idx + 1, subOrder); + + writeln(); + depw = deps.dup; + depw["dw01"] ~= "dw04"; + foreach (subOrder; topoSort(depw)) // should throw + writeln(subOrder); +} diff --git a/Task/Topological-sort/E/topological-sort-1.e b/Task/Topological-sort/E/topological-sort-1.e new file mode 100644 index 0000000000..49db62efd4 --- /dev/null +++ b/Task/Topological-sort/E/topological-sort-1.e @@ -0,0 +1,49 @@ +def makeQueue := + +def topoSort(data :Map[any, Set[any]]) { + # Tables of nodes and edges + def forwardEdges := [].asMap().diverge() + def reverseCount := [].asMap().diverge() + + def init(node) { + reverseCount[node] := 0 + forwardEdges[node] := [].asSet().diverge() + } + for node => deps in data { + init(node) + for dep in deps { init(dep) } + } + + # 'data' holds the dependencies. Compute the other direction. + for node => deps in data { + for dep ? (dep != node) in deps { + forwardEdges[dep].addElement(node) + reverseCount[node] += 1 + } + } + + # Queue containing all elements that have no (initial or remaining) incoming edges + def ready := makeQueue() + for node => ==0 in reverseCount { + ready.enqueue(node) + } + + var result := [] + + while (ready.optDequeue() =~ node :notNull) { + result with= node + for next in forwardEdges[node] { + # Decrease count of incoming edges and enqueue if none + if ((reverseCount[next] -= 1).isZero()) { + ready.enqueue(next) + } + } + forwardEdges.removeKey(node) + } + + if (forwardEdges.size().aboveZero()) { + throw(`Topological sort failed: $forwardEdges remains`) + } + + return result +} diff --git a/Task/Topological-sort/E/topological-sort-2.e b/Task/Topological-sort/E/topological-sort-2.e new file mode 100644 index 0000000000..add42c8a68 --- /dev/null +++ b/Task/Topological-sort/E/topological-sort-2.e @@ -0,0 +1,21 @@ +pragma.enable("accumulator") + +def dataText := "\ +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys\ +" + +def data := accum [].asMap() for rx`(@item.{17})(@deps.*)` in dataText.split("\n") { _.with(item.trim(), deps.split(" ").asSet()) } + +println(topoSort(data)) diff --git a/Task/Topological-sort/Erlang/topological-sort-1.erl b/Task/Topological-sort/Erlang/topological-sort-1.erl new file mode 100644 index 0000000000..0a13f35879 --- /dev/null +++ b/Task/Topological-sort/Erlang/topological-sort-1.erl @@ -0,0 +1,71 @@ +-module(topological_sort). +-compile(export_all). + +-define(LIBRARIES, + [{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]}, + {dw01, [ieee, dw01, dware, gtech]}, + {dw02, [ieee, dw02, dware]}, + {dw03, [std, synopsys, dware, dw03, dw02, dw01, ieee, gtech]}, + {dw04, [dw04, ieee, dw01, dware, gtech]}, + {dw05, [dw05, ieee, dware]}, + {dw06, [dw06, ieee, dware]}, + {dw07, [ieee, dware]}, + {dware, [ieee, dware]}, + {gtech, [ieee, gtech]}, + {ramlib, [std, ieee]}, + {std_cell_lib, [ieee, std_cell_lib]}, + {synopsys, []}]). + +-define(BAD_LIBRARIES, + [{des_system_lib, [std, synopsys, std_cell_lib, des_system_lib, dw02, dw01, ramlib, ieee]}, + {dw01, [ieee, dw01, dw04, dware, gtech]}, + {dw02, [ieee, dw02, dware]}, + {dw03, [std, synopsys, dware, dw03, dw02, dw01, ieee, gtech]}, + {dw04, [dw04, ieee, dw01, dware, gtech]}, + {dw05, [dw05, ieee, dware]}, + {dw06, [dw06, ieee, dware]}, + {dw07, [ieee, dware]}, + {dware, [ieee, dware]}, + {gtech, [ieee, gtech]}, + {ramlib, [std, ieee]}, + {std_cell_lib, [ieee, std_cell_lib]}, + {synopsys, []}]). + +main() -> + top_sort(?LIBRARIES), + top_sort(?BAD_LIBRARIES). + +top_sort(Library) -> + G = digraph:new(), + lists:foreach(fun ({L,Deps}) -> + digraph:add_vertex(G,L), % noop if library already added + lists:foreach(fun (D) -> + add_dependency(G,L,D) + end, Deps) + end, Library), + T = digraph_utils:topsort(G), + case T of + false -> + io:format("Unsortable contains circular dependencies:~n",[]), + lists:foreach(fun (V) -> + case digraph:get_short_cycle(G,V) of + false -> + ok; + Vs -> + print_path(Vs) + end + end, digraph:vertices(G)); + _ -> + print_path(T) + end. + +print_path(L) -> + lists:foreach(fun (V) -> io:format("~s -> ",[V]) end, + lists:sublist(L,length(L)-1)), + io:format("~s~n",[lists:last(L)]). + +add_dependency(_G,_L,_L) -> + ok; +add_dependency(G,L,D) -> + digraph:add_vertex(G,D), % noop if dependency already added + digraph:add_edge(G,D,L). % Dependencies represented as an edge D -> L diff --git a/Task/Topological-sort/Erlang/topological-sort-2.erl b/Task/Topological-sort/Erlang/topological-sort-2.erl new file mode 100644 index 0000000000..461a5cb9f5 --- /dev/null +++ b/Task/Topological-sort/Erlang/topological-sort-2.erl @@ -0,0 +1,6 @@ +62> topological_sort:main(). +synopsys -> std -> ieee -> dware -> dw02 -> dw05 -> ramlib -> std_cell_lib -> dw06 -> dw07 -> gtech -> dw01 -> des_system_lib -> dw03 -> dw04 +Unsortable contains circular dependencies: +dw04 -> dw01 -> dw04 +dw01 -> dw04 -> dw01 +ok diff --git a/Task/Topological-sort/Fortran/topological-sort-1.f b/Task/Topological-sort/Fortran/topological-sort-1.f new file mode 100644 index 0000000000..3f3d609354 --- /dev/null +++ b/Task/Topological-sort/Fortran/topological-sort-1.f @@ -0,0 +1,24 @@ + SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO) + IMPLICIT NONE + INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR + DO 10 I=1,NL + IORD(I)=I + 10 IPOS(I)=I + K=1 + 20 J=K + K=NL+1 + DO 30 I=1,ND + IL=IDEP(I,1) + IR=IDEP(I,2) + IPL=IPOS(IL) + IPR=IPOS(IR) + IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30 + K=K-1 + IPOS(IORD(K))=IPL + IPOS(IL)=K + IORD(IPL)=IORD(K) + IORD(K)=IL + 30 CONTINUE + IF(K.GT.J) GO TO 20 + NO=J-1 + END diff --git a/Task/Topological-sort/Fortran/topological-sort-2.f b/Task/Topological-sort/Fortran/topological-sort-2.f new file mode 100644 index 0000000000..d9068a5d32 --- /dev/null +++ b/Task/Topological-sort/Fortran/topological-sort-2.f @@ -0,0 +1,38 @@ + PROGRAM EX_TSORT + IMPLICIT NONE + INTEGER NL,ND,NC,NO,IDEP,IORD,IPOS,ICODE,I,J,IL,IR + PARAMETER(NL=15,ND=44,NC=69) + CHARACTER*(20) LABEL + DIMENSION IDEP(ND,2),LABEL(NL),IORD(NL),IPOS(NL),ICODE(NC) + DATA LABEL/'DES_SYSTEM_LIB','DW01','DW02','DW03','DW04','DW05', + 1 'DW06','DW07','DWARE','GTECH','RAMLIB','STD_CELL_LIB','SYNOPSYS', + 2 'STD','IEEE'/ + DATA ICODE/1,14,13,12,1,3,2,11,15,0,2,15,2,9,10,0,3,15,3,9,0,4,14, + 213,9,4,3,2,15,10,0,5,5,15,2,9,10,0,6,6,15,9,0,7,7,15,9,0,8,15,9,0, + 39,15,9,0,10,15,10,0,11,14,15,0,12,15,12,0,0/ + +C DECODE DEPENDENCIES AND BUILD IDEP ARRAY + I=0 + J=0 + 10 I=I+1 + IL=ICODE(I) + IF(IL.EQ.0) GO TO 30 + 20 I=I+1 + IR=ICODE(I) + IF(IR.EQ.0) GO TO 10 + J=J+1 + IDEP(J,1)=IL + IDEP(J,2)=IR + GO TO 20 + 30 CONTINUE + +C SORT LIBRARIES ACCORDING TO DEPENDENCIES (TOPOLOGICAL SORT) + CALL TSORT(NL,ND,IDEP,IORD,IPOS,NO) + + PRINT*,'COMPILE ORDER' + DO 40 I=1,NO + 40 PRINT*,LABEL(IORD(I)) + PRINT*,'UNORDERED LIBRARIES' + DO 50 I=NO+1,NL + 50 PRINT*,LABEL(IORD(I)) + END diff --git a/Task/Topological-sort/Go/topological-sort.go b/Task/Topological-sort/Go/topological-sort.go new file mode 100644 index 0000000000..ffa9fa8b6b --- /dev/null +++ b/Task/Topological-sort/Go/topological-sort.go @@ -0,0 +1,107 @@ +package main + +import ( + "fmt" + "strings" +) + +var data = ` +LIBRARY LIBRARY DEPENDENCIES +======= ==================== +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys ` + +func main() { + // validate that data is positioned in string as expected + lines := strings.Split(data, "\n") + if lines[2][0] != '=' || strings.TrimSpace(lines[len(lines)-1]) == "" { + panic("data format") + } + // toss header lines + lines = lines[3:] + + // scan and interpret input, build directed graph + dg := make(map[string][]string) + for _, line := range lines { + def := strings.Fields(line) + if len(def) == 0 { + continue // handle blank lines + } + lib := def[0] // dependant (with an a) library + list := dg[lib] // handle additional dependencies + scan: + for _, pr := range def[1:] { // (pr for prerequisite) + if pr == lib { + continue // ignore self dependencies + } + for _, known := range list { + if known == pr { + continue scan // ignore duplicate dependencies + } + } + // build: this curious looking assignment establishess a node + // for the prerequisite library if it doesn't already exist. + dg[pr] = dg[pr] + // build: add edge (dependency) + list = append(list, pr) + } + // build: add or update node for dependant library + dg[lib] = list + } + + // topological sort on dg + for len(dg) > 0 { + // collect libs with no dependencies + var zero []string + for lib, deps := range dg { + if len(deps) == 0 { + zero = append(zero, lib) + delete(dg, lib) // remove node (lib) from dg + } + } + // cycle detection + if len(zero) == 0 { + fmt.Println("libraries with un-orderable dependencies:") + // collect un-orderable dependencies + cycle := make(map[string]bool) + for _, deps := range dg { + for _, dep := range deps { + cycle[dep] = true + } + } + // print libs with un-orderable dependencies + for lib, deps := range dg { + if cycle[lib] { + fmt.Println(lib, deps) + } + } + return + } + // output a set that can be processed concurrently + fmt.Println(zero) + + // remove edges (dependencies) from dg + for _, remove := range zero { + for lib, deps := range dg { + for i, dep := range deps { + if dep == remove { + copy(deps[i:], deps[i+1:]) + dg[lib] = deps[:len(deps)-1] + break + } + } + } + } + } +} diff --git a/Task/Topological-sort/Haskell/topological-sort-1.hs b/Task/Topological-sort/Haskell/topological-sort-1.hs new file mode 100644 index 0000000000..ccc045cca4 --- /dev/null +++ b/Task/Topological-sort/Haskell/topological-sort-1.hs @@ -0,0 +1,39 @@ +import Data.List +import Data.Maybe +import Control.Arrow +import System.Random +import Control.Monad + +combs 0 _ = [[]] +combs _ [] = [] +combs k (x:xs) = map (x:) (combs (k-1) xs) ++ combs k xs + +depLibs :: [(String, String)] +depLibs = [("des_system_lib","std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee"), + ("dw01","ieee dw01 dware gtech"), + ("dw02","ieee dw02 dware"), + ("dw03","std synopsys dware dw03 dw02 dw01 ieee gtech"), + ("dw04","dw04 ieee dw01 dware gtech"), + ("dw05","dw05 ieee dware"), + ("dw06","dw06 ieee dware"), + ("dw07","ieee dware"), + ("dware","ieee dware"), + ("gtech","ieee gtech"), + ("ramlib","std ieee"), + ("std_cell_lib","ieee std_cell_lib"), + ("synopsys",[])] + + +toposort xs + | (not.null) cycleDetect = error $ "Dependency cycle detected for libs " ++ show cycleDetect + | otherwise = foldl makePrecede [] dB + + where dB = map ((\(x,y) -> (x,y \\ x)). (return *** words)) xs + + makePrecede ts ([x],xs) = nub $ case elemIndex x ts of + Just i -> uncurry(++) $ first(++xs) $ splitAt i ts + _ -> ts ++ xs ++ [x] + + cycleDetect = filter ((>1).length) + $ map (\[(a,as), (b,bs)] -> (a `intersect` bs) ++ (b `intersect`as)) + $ combs 2 dB diff --git a/Task/Topological-sort/Haskell/topological-sort-2.hs b/Task/Topological-sort/Haskell/topological-sort-2.hs new file mode 100644 index 0000000000..ab6f151b78 --- /dev/null +++ b/Task/Topological-sort/Haskell/topological-sort-2.hs @@ -0,0 +1,5 @@ +*Main> toposort depLibs +["std","synopsys","ieee","std_cell_lib","dware","dw02","gtech","dw01","ramlib","des_system_lib","dw03","dw04","dw05","dw06","dw07"] + +*Main> toposort $ (\(xs,(k,ks):ys) -> xs++ (k,ks++" dw04"):ys) $ splitAt 1 depLibs +*** Exception: Dependency cycle detected for libs [["dw01","dw04"]] diff --git a/Task/Topological-sort/Haskell/topological-sort-3.hs b/Task/Topological-sort/Haskell/topological-sort-3.hs new file mode 100644 index 0000000000..8c69d56362 --- /dev/null +++ b/Task/Topological-sort/Haskell/topological-sort-3.hs @@ -0,0 +1,115 @@ +record graph(nodes,arcs) +global ex_name, in_name + +procedure main() + show(tsort(getgraph())) +end + +procedure tsort(g) + t := "" + while (n := g.nodes -- pnodes(g)) ~== "" do { + t ||:= "("||n||")" + g := delete(g,n) + } + if g.nodes == '' then return t + write("graph contains the cycle:") + write("\t",genpath(fn := !g.nodes,fn,g)) +end + +## pnodes(g) -- return the predecessor nodes of g +# (those that have an arc from them) +procedure pnodes(g) + static labels, fromnodes + initial { + labels := &ucase + fromnodes := 'ACEGIKMOQSUWY' + } + return cset(select(g.arcs,labels, fromnodes)) +end + +## select(s,image,object) - efficient node selection +procedure select(s,image,object) + slen := *s + ilen := *image + return if slen <= ilen then map(object[1+:slen/2],image[1+:slen],s) + else map(object,image,s[1+:ilen]) || select(s[1+ilen:0],image,object) +end + +## delete(g,x) -- deletes all nodes in x from graph g +# note that arcs must be deleted as well +procedure delete(g,x) + t := "" + g.arcs ? while arc := move(2) do if not upto(x,arc) then t ||:= arc + return graph(g.nodes--x,t) +end + + +## getgraph() -- read and construct a graph +# graph is described via sets of arcs, as in: +# +# from to1 to2 to3 +# +# external names are converted to single character names for efficiency +# self-referential arcs are ignored +procedure getgraph() + static labels + initial labels := &cset + ex_name := table() + in_name := table() + count := 0 + arcstr := "" + nodes := '' + every line := !&input do { + nextWord := create genWords(line) + if nfrom := @nextWord then { + /in_name[nfrom] := &cset[count +:= 1] + /ex_name[in_name[nfrom]] := nfrom + nodes ++:= in_name[nfrom] + while nto := @nextWord do { + if nfrom ~== nto then { + /in_name[nto] := &cset[count +:= 1] + /ex_name[in_name[nto]] := nto + nodes ++:= in_name[nto] + arcstr ||:= in_name[nfrom] || in_name[nto] + } + } + } + } + return graph(nodes,arcstr) +end + +# generate all 'words' in string +procedure genWords(s) + static wchars + initial wchars := &cset -- ' \t' + s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1 +end + +## show(t) - return the external names (in order) for the nodes in t +# Each output line contains names that are independent of each other +procedure show(t) + line := "" + every n := !t do + case n of { + "(" : line ||:= "\n\t(" + ")" : line[-1] := ")" + default : line ||:= ex_name[n] || " " + } + write(line) +end + +## genpath(f,t,g) -- generate paths from f to t in g +procedure genpath(f,t,g, seen) + /seen := '' + seen ++:= f + sn := nnodes(f,g) + if t ** sn == t then return ex_name[f] || " -> " || ex_name[t] + suspend ex_name[f] || " -> " || genpath(!(sn --seen),t,g,seen) +end + +## nnodes(f,g) -- compute all nodes that could follow f in g +procedure nnodes(f,g) + t := '' + g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2] + return t +end diff --git a/Task/Topological-sort/Haskell/topological-sort-4.hs b/Task/Topological-sort/Haskell/topological-sort-4.hs new file mode 100644 index 0000000000..45d898d5c6 --- /dev/null +++ b/Task/Topological-sort/Haskell/topological-sort-4.hs @@ -0,0 +1,87 @@ +record graph(nodes,arcs) + +procedure main() + show(tsort(getgraph())) +end + +procedure tsort(g) + t := [] + while *(n := g.nodes -- pnodes(g)) > 0 do { + every put(p := [], !n) + put(t, p) + g := delete(g,n) + } + if *g.nodes = 0 then return t + write("graph contains the cycle:") + write("\t",genpath(fn := !g.nodes,fn,g)) +end + +procedure pnodes(g) + cp := create !g.arcs + every insert(p := set(), |1(@cp,@cp)) + return p +end + +procedure delete(g,x) + arcs := [] + cp := create !g.arcs + while (f := @cp, t := @cp) do { + if !x == (f|t) then next + every put(arcs,f|t) + } + return graph(g.nodes--x, arcs) +end + +procedure getgraph() + arcs := [] + nodes := set() + every line := !&input do { + nextWord := create genWords(line) + if nfrom := @nextWord then { + insert(nodes, nfrom) + while nto := @nextWord do { + if nfrom ~== nto then { + insert(nodes, nto) + every put(arcs, nfrom | nto) + } + } + } + } + return graph(nodes,arcs) +end + +procedure genWords(s) + static wchars + initial wchars := &cset -- ' \t' + s ? while tab(upto(wchars))\1 do suspend tab(many(wchars))\1 +end + +procedure show(t) + line := "" + every n := !t do + case type(n) of { + "list" : line ||:= "\n\t("||toString(n)||")" + default : line ||:= " "||n + } + write(line) +end + +procedure toString(n) + every (s := "") ||:= !n || " " + return s[1:-1] | s +end + +procedure genpath(f,t,g, seen) + /seen := set() + insert(seen, f) + sn := nnodes(f,g) + if member(sn, t) then return f || " -> " || t + suspend f || " -> " || genpath(!(sn--seen),t,g,seen) +end + +procedure nnodes(f,g) + t := set() + cp := create !g.arcs + while (af := @cp, at := @cp) do if af == f then insert(t, at) + return t +end diff --git a/Task/Topological-sort/J/topological-sort-1.j b/Task/Topological-sort/J/topological-sort-1.j new file mode 100644 index 0000000000..d9c289be3f --- /dev/null +++ b/Task/Topological-sort/J/topological-sort-1.j @@ -0,0 +1,8 @@ +dependencySort=: monad define + parsed=. <@;:;._2 y + names=. {.&>parsed + depends=. (> =@i.@#) names e.S:1 parsed + depends=. (+. +./ .*.~)^:_ depends + assert.-.1 e. (<0 1)|:depends + (-.&names ~.;parsed),names /: +/"1 depends +) diff --git a/Task/Topological-sort/J/topological-sort-2.j b/Task/Topological-sort/J/topological-sort-2.j new file mode 100644 index 0000000000..5071753fab --- /dev/null +++ b/Task/Topological-sort/J/topological-sort-2.j @@ -0,0 +1,8 @@ +depSort=: monad define + parsed=. <@;:;._2 y + names=. {.&>parsed + depends=. (-.L:0"_1 #,.i.@#) names i.L:1 parsed + depends=. (~.@,&.> ;@:{L:0 1~)^:_ depends + assert.-.1 e. (i.@# e.S:0"0 ])depends + (-.&names ~.;parsed),names /: #@> depends +) diff --git a/Task/Topological-sort/Java/topological-sort.java b/Task/Topological-sort/Java/topological-sort.java new file mode 100644 index 0000000000..6641d7f7c5 --- /dev/null +++ b/Task/Topological-sort/Java/topological-sort.java @@ -0,0 +1,26 @@ +import java.util.ArrayList; +import java.util.TreeMap; + +public class TopologicalSort { + public static void main(String[] args) throws Exception { + TreeMap> mp = new TreeMap>(); + String[] data, input = new String[] { + "des_system_lib: std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee", + "dw01: ieee dw01 dware gtech", "dw02: ieee dw02 dware", + "dw03: std synopsys dware dw03 dw02 dw01 ieee gtech", + "dw04: dw04 ieee dw01 dware gtech", "dw05: dw05 ieee dware", + "dw06: dw06 ieee dware", "dw07: ieee dware", + "dware: ieee dware", "gtech: ieee gtech", "ramlib: std ieee", + "std_cell_lib: ieee std_cell_lib", "synopsys:" }; + + for (String str : input) + mp.put((data = str.split(":"))[0], Utils.aList(// + data.length < 2 || data[1].trim().equals("")// + ? null : data[1].trim().split("\\s+"))); + + Utils.tSortFix(mp); + System.out.println(Utils.tSort(mp)); + mp.put("dw01", Utils.aList("dw04")); + System.out.println(Utils.tSort(mp)); + } +} diff --git a/Task/Topological-sort/Mathematica/topological-sort.math b/Task/Topological-sort/Mathematica/topological-sort.math new file mode 100644 index 0000000000..9971b8c9e0 --- /dev/null +++ b/Task/Topological-sort/Mathematica/topological-sort.math @@ -0,0 +1,19 @@ +TopologicalSort[ + Graph[Flatten[# /. {l_, ld_} :> + Map[# -> l &, + DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@ + {{"des_system_lib", {"std", "synopsys", "std_cell_lib", + "des_system_lib", "dw02", "dw01", "ramlib", "ieee"}}, + {"dw01", {"ieee", "dw01", "dware", "gtech"}}, + {"dw02", {"ieee", "dw02", "dware"}}, + {"dw03", {"std", "synopsys", "dware", "dw03", "dw02", "dw01", + "ieee", "gtech"}}, + {"dw04", {"dw04", "ieee", "dw01", "dware", "gtech"}}, + {"dw05", {"dw05", "ieee", "dware"}}, + {"dw06", {"dw06", "ieee", "dware"}}, + {"dw07", {"ieee", "dware"}}, + {"dware", {"ieee", "dware"}}, + {"gtech", {"ieee", "gtech"}}, + {"ramlib", {"std", "ieee"}}, + {"std_cell_lib", {"ieee", "std_cell_lib"}}, + {"synopsys", {}}} diff --git a/Task/Topological-sort/OCaml/topological-sort.ocaml b/Task/Topological-sort/OCaml/topological-sort.ocaml new file mode 100644 index 0000000000..32ebfacba8 --- /dev/null +++ b/Task/Topological-sort/OCaml/topological-sort.ocaml @@ -0,0 +1,54 @@ +let dep_libs = [ + ("des_system_lib", ["std"; "synopsys"; "std_cell_lib"; "des_system_lib"; "dw02"; "dw01"; "ramlib"; "ieee"]); + ("dw01", (*"dw04"::*)["ieee"; "dw01"; "dware"; "gtech"]); + ("dw02", ["ieee"; "dw02"; "dware"]); + ("dw03", ["std"; "synopsys"; "dware"; "dw03"; "dw02"; "dw01"; "ieee"; "gtech"]); + ("dw04", ["dw04"; "ieee"; "dw01"; "dware"; "gtech"]); + ("dw05", ["dw05"; "ieee"; "dware"]); + ("dw06", ["dw06"; "ieee"; "dware"]); + ("dw07", ["ieee"; "dware"]); + ("dware", ["ieee"; "dware"]); + ("gtech", ["ieee"; "gtech"]); + ("ramlib", ["std"; "ieee"]); + ("std_cell_lib", ["ieee"; "std_cell_lib"]); + ("synopsys", []); +] + +let dep_libs = + let f (lib, deps) = (* remove self dependency *) + (lib, + List.filter (fun d -> d <> lib) deps) in + List.map f dep_libs + +let rev_unique = + List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) [] + +let libs = (* list items, each being unique *) + rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs)) + +let get_deps lib = + try (List.assoc lib dep_libs) + with Not_found -> [] + +let res = + let rec aux acc later todo progress = + match todo, later with + | [], [] -> (List.rev acc) + | [], _ -> + if progress + then aux acc [] later false + else invalid_arg "un-orderable data" + | x::xs, _ -> + let deps = get_deps x in + let ok = List.for_all (fun dep -> List.mem dep acc) deps in + if ok + then aux (x::acc) later xs true + else aux acc (x::later) xs progress + in + let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in + aux starts [] todo false + +let () = + print_string "result: \n "; + print_endline (String.concat ", " res); +;; diff --git a/Task/Topological-sort/Object-Pascal/topological-sort.object b/Task/Topological-sort/Object-Pascal/topological-sort.object new file mode 100644 index 0000000000..62eecbd1a4 --- /dev/null +++ b/Task/Topological-sort/Object-Pascal/topological-sort.object @@ -0,0 +1,412 @@ +program topologicalsortrosetta; + +{* +Topological sorter to parse e.g. dependencies. +Written for FreePascal 2.4.x/2.5.1. Probably works in Delphi, but you'd have to +change some units. +*} +{$IFDEF FPC} +// FreePascal-specific setup +{$mode objfpc} +uses {$IFDEF UNIX} + cwstring, {* widestring support for unix *} {$IFDEF UseCThreads} + cthreads, {$ENDIF UseCThreads} {$ENDIF UNIX} + Classes, + SysUtils; +{$ENDIF} + +type + RNodeIndex = record + NodeName: WideString; //Name of the node + //Index: integer; //Index number used in DepGraph. For now, we can distill the index from the array index. If we want to use a TList or similar, we'd need an index property + Order: integer; //Order when sorted + end; + + RDepGraph = record + Node: integer; //Refers to Index in NodeIndex + DependsOn: integer; //The Node depends on this other Node. + end; + + { TTopologicalSort } + + TTopologicalSort = class(TObject) + private + Nodes: array of RNodeIndex; + DependencyGraph: array of RDepGraph; + FCanBeSorted: boolean; + function SearchNode(NodeName: WideString): integer; + function SearchIndex(NodeID: integer): WideString; + function DepFromNodeID(NodeID: integer): integer; + function DepFromDepID(DepID: integer): integer; + function DepFromNodeIDDepID(NodeID, DepID: integer): integer; + procedure DelDependency(const Index: integer); + public + constructor Create; + destructor Destroy; override; + procedure SortOrder(var Output: TStringList); + procedure AddNode(NodeName: WideString); + procedure AddDependency(NodeName, DependsOn: WideString); + procedure AddNodeDependencies(NodeAndDependencies: TStringList); + //Each string has node, and the nodes it depends on. This allows insertion of an entire dependency graph at once + //procedure DelNode(NodeName: Widestring); + procedure DelDependency(NodeName, DependsOn: WideString); + + property CanBeSorted: boolean read FCanBeSorted; + + end; + +const + INVALID = -1; + // index not found for index search functions, no sort order defined, or record invalid/deleted + + function TTopologicalSort.SearchNode(NodeName: WideString): integer; + var + Counter: integer; + begin + // Return -1 if node not found. If node found, return index in array + Result := INVALID; + for Counter := 0 to High(Nodes) do + begin + if Nodes[Counter].NodeName = NodeName then + begin + Result := Counter; + break; + end; + end; + end; + + function TTopologicalSort.SearchIndex(NodeID: integer): WideString; + //Look up name for the index + begin + if (NodeID > 0) and (NodeID <= High(Nodes)) then + begin + Result := Nodes[NodeID].NodeName; + end + else + begin + Result := 'ERROR'; //something's fishy, this shouldn't happen + end; + end; + + function TTopologicalSort.DepFromNodeID(NodeID: integer): integer; + // Look for Node index number in the dependency graph + // and return the first node found. If nothing found, return -1 + var + Counter: integer; + begin + Result := INVALID; + for Counter := 0 to High(DependencyGraph) do + begin + if DependencyGraph[Counter].Node = NodeID then + begin + Result := Counter; + break; + end; + end; + end; + + function TTopologicalSort.DepFromDepID(DepID: integer): integer; + // Look for dependency index number in the dependency graph + // and return the index for the first one found. If nothing found, return -1 + var + Counter: integer; + begin + Result := INVALID; + for Counter := 0 to High(DependencyGraph) do + begin + if DependencyGraph[Counter].DependsOn = DepID then + begin + Result := Counter; + break; + end; + end; + end; + + function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer; + // Shows index for the dependency from NodeID on DepID, or INVALID if not found + var + Counter: integer; + begin + Result := INVALID; + for Counter := 0 to High(DependencyGraph) do + begin + if DependencyGraph[Counter].Node = NodeID then + if DependencyGraph[Counter].DependsOn = DepID then + begin + Result := Counter; + break; + end; + end; + end; + + procedure TTopologicalSort.DelDependency(const Index: integer); + // Removes dependency from array. + // Is fastest when the dependency is near the top of the array + // as we're copying the remaining elements. + var + Counter: integer; + OriginalLength: integer; + begin + OriginalLength := Length(DependencyGraph); + if Index = OriginalLength - 1 then + begin + SetLength(DependencyGraph, OriginalLength - 1); + end; + if Index < OriginalLength - 1 then + begin + for Counter := Index to OriginalLength - 2 do + begin + DependencyGraph[Counter] := DependencyGraph[Counter + 1]; + end; + SetLength(DependencyGraph, OriginalLength - 1); + end; + if Index > OriginalLength - 1 then + begin + // This could happen when deleting on an empty array: + raise Exception.Create('Tried to delete index ' + IntToStr(Index) + + ' while the maximum index was ' + IntToStr(OriginalLength - 1)); + end; + end; + + constructor TTopologicalSort.Create; + begin + inherited Create; + end; + + destructor TTopologicalSort.Destroy; + begin + // Clear up data just to make sure: + Finalize(DependencyGraph); + Finalize(Nodes); + inherited; + end; + + procedure TTopologicalSort.SortOrder(var Output: TStringList); + var + Counter: integer; + NodeCounter: integer; + OutputSortOrder: integer; + DidSomething: boolean; //used to detect cycles (circular references) + Node: integer; + begin + OutputSortOrder := 0; + DidSomething := True; // prime the loop below + FCanBeSorted := True; //hope for the best. + while (DidSomething = True) do + begin + // 1. Find all nodes (now) without dependencies, output them first and remove the dependencies: + // 1.1 Nodes that are not present in the dependency graph at all: + for Counter := 0 to High(Nodes) do + begin + if DepFromNodeID(Counter) = INVALID then + begin + if DepFromDepID(Counter) = INVALID then + begin + // Node doesn't occur in either side of the dependency graph, so it has sort order 0: + DidSomething := True; + if (Nodes[Counter].Order = INVALID) or + (Nodes[Counter].Order > OutputSortOrder) then + begin + // Enter sort order if the node doesn't have a lower valid order already. + Nodes[Counter].Order := OutputSortOrder; + end; + end; //Invalid Dep + end; //Invalid Node + end; //Count + // Done with the first batch, so we can increase the sort order: + OutputSortOrder := OutputSortOrder + 1; + // 1.2 Nodes that are only present on the right hand side of the dep graph: + DidSomething := False; + // reverse order so we can delete dependencies without passing upper array + for Counter := High(DependencyGraph) downto 0 do + begin + Node := DependencyGraph[Counter].DependsOn; //the depended node + if (DepFromNodeID(Node) = INVALID) then + begin + DidSomething := True; + //Delete dependency so we don't hit it again: + DelDependency(Counter); + if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then + begin + // Enter sort order if the node doesn't have a lower valid order already. + Nodes[Node].Order := OutputSortOrder; + end; + end; + OutputSortOrder := OutputSortOrder + 1; //next iteration + end; + // 2. Go back to 1 until we can't do more work, and do some bookkeeping: + OutputSortOrder := OutputSortOrder + 1; + end; //outer loop for 1 to 2 + OutputSortOrder := OutputSortOrder - 1; //fix unused last loop. + + // 2. If we have dependencies left, we have a cycle; exit. + if (High(DependencyGraph) > 0) then + begin + FCanBeSorted := False; //indicate we have a cycle + Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:'); + for Counter := 0 to High(DependencyGraph) do + begin + Output.Add(SearchIndex(DependencyGraph[Counter].Node) + + ' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn)); + end; + end + else + begin + // No cycle: + // Now parse results, if we have them + for Counter := 0 to OutputSortOrder do + begin + for NodeCounter := 0 to High(Nodes) do + begin + if Nodes[NodeCounter].Order = Counter then + begin + Output.Add(Nodes[NodeCounter].NodeName); + end; + end; //output each result + end; //order iteration + end; //cycle detection + end; + + procedure TTopologicalSort.AddNode(NodeName: WideString); + var + NodesNewLength: integer; + begin + // Adds node; make sure we don't add duplicate entries + if SearchNode(NodeName) = INVALID then + begin + NodesNewLength := Length(Nodes) + 1; + SetLength(Nodes, NodesNewLength); + Nodes[NodesNewLength - 1].NodeName := NodeName; //Arrays are 0 based + //Nodes[NodesNewLength -1].Index := //If we change the object to a tlist or something, we already have an index property + Nodes[NodesNewLength - 1].Order := INVALID; //default value + end; + end; + + procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString); + begin + // Make sure both nodes in the dependency exist as a node + if SearchNode(NodeName) = INVALID then + begin + Self.AddNode(NodeName); + end; + if SearchNode(DependsOn) = INVALID then + begin + Self.AddNode(DependsOn); + end; + // Add the dependency, only if we don't depend on ourselves: + if NodeName <> DependsOn then + begin + SetLength(DependencyGraph, Length(DependencyGraph) + 1); + DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName); + DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn); + end; + end; + + procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList); + // Takes a stringlist containing a list of strings. Each string contains node names + // separated by spaces. The first node depends on the others. It is permissible to have + // only one node name, which doesn't depend on anything. + // This procedure will add the dependencies and the nodes in one go. + var + Deplist: TStringList; + StringCounter: integer; + NodeCounter: integer; + begin + if Assigned(NodeAndDependencies) then + begin + DepList := TStringList.Create; + try + for StringCounter := 0 to NodeAndDependencies.Count - 1 do + begin + // For each string in the argument: split into names, and process: + DepList.Delimiter := ' '; //use space to separate the entries + DepList.StrictDelimiter := False; //allows us to ignore double spaces in input. + DepList.DelimitedText := NodeAndDependencies[StringCounter]; + for NodeCounter := 0 to DepList.Count - 1 do + begin + if NodeCounter = 0 then + begin + // Add the first node, which might be the only one. + Self.AddNode(Deplist[0]); + end; + + if NodeCounter > 0 then + begin + // Only add dependency from the second item onwards + // The AddDependency code will automatically add Deplist[0] to the Nodes, if required + Self.AddDependency(DepList[0], DepList[NodeCounter]); + end; + end; + end; + finally + DepList.Free; + end; + end; + end; + + procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString); + // Delete the record. + var + NodeID: integer; + DependsID: integer; + Dependency: integer; + begin + NodeID := Self.SearchNode(NodeName); + DependsID := Self.SearchNode(DependsOn); + if (NodeID <> INVALID) and (DependsID <> INVALID) then + begin + // Look up dependency and delete it. + Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID); + if (Dependency <> INVALID) then + begin + Self.DelDependency(Dependency); + end; + end; + end; + + // Main program: +var + InputList: TStringList; //Lines of dependencies + TopSort: TTopologicalSort; //Topological sort object + OutputList: TStringList; //Sorted dependencies + Counter: integer; +begin + + //Actual sort + InputList := TStringList.Create; + // Add rosetta code sample input separated by at least one space in the lines + InputList.Add( + 'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'); + InputList.Add('dw01 ieee dw01 dware gtech'); + InputList.Add('dw02 ieee dw02 dware'); + InputList.Add('dw03 std synopsys dware dw03 dw02 dw01 ieee gtech'); + InputList.Add('dw04 dw04 ieee dw01 dware gtech'); + InputList.Add('dw05 dw05 ieee dware'); + InputList.Add('dw06 dw06 ieee dware'); + InputList.Add('dw07 ieee dware'); + InputList.Add('dware ieee dware'); + InputList.Add('gtech ieee gtech'); + InputList.Add('ramlib std ieee'); + InputList.Add('std_cell_lib ieee std_cell_lib'); + InputList.Add('synopsys'); + TopSort := TTopologicalSort.Create; + OutputList := TStringList.Create; + try + TopSort.AddNodeDependencies(InputList); //read in nodes + TopSort.SortOrder(OutputList); //perform the sort + for Counter := 0 to OutputList.Count - 1 do + begin + writeln(OutputList[Counter]); + end; + except + on E: Exception do + begin + Writeln(stderr, 'Error: ', DateTimeToStr(Now), + ': Error sorting. Technical details: ', + E.ClassName, '/', E.Message); + end; + end; //try + OutputList.Free; + TopSort.Free; + InputList.Free; +end. diff --git a/Task/Topological-sort/Oz/topological-sort.oz b/Task/Topological-sort/Oz/topological-sort.oz new file mode 100644 index 0000000000..359968c3e4 --- /dev/null +++ b/Task/Topological-sort/Oz/topological-sort.oz @@ -0,0 +1,86 @@ +declare + Deps = unit( + des_system_lib: [std synopsys std_cell_lib des_system_lib + dw02 dw01 ramlib ieee] + dw01: [ieee dw01 dware gtech] + dw02: [ieee dw02 dware] + dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech] + dw04: [dw04 ieee dw01 dware gtech] + dw05: [dw05 ieee dware] + dw06: [dw06 ieee dware] + dw07: [ieee dware] + dware: [ieee dware] + gtech: [ieee gtech] + ramlib: [std ieee] + std_cell_lib: [ieee std_cell_lib] + synopsys:nil + ) + + %% Describe possible solutions + proc {TopologicalOrder Solution} + FullDeps = {Complete Deps} + in + %% The solution is a record that maps library names + %% to finite domain variables. + %% The smaller the value, the earlier it must be compiled + Solution = {FD.record sol {Arity FullDeps} 1#{Width FullDeps}} + %% for every lib on the left side + {Record.forAllInd FullDeps + proc {$ LibName Dependants} + %% ... and every dependant on the right side + for Dependant in Dependants do + %% propagate compilation order + if Dependant \= LibName then + Solution.LibName >: Solution.Dependant + end + end + end + } + %% enumerate solutions + {FD.distribute naive Solution} + end + + %% adds empty list of dependencies for libs that only occur on the right side + fun {Complete Dep} + AllLibs = {Nub {Record.foldL Dep Append nil}} + in + {Adjoin + {List.toRecord unit {Map AllLibs fun {$ L} L#nil end}} + Dep} + end + + %% removes duplicates + fun {Nub Xs} + D = {Dictionary.new} + in + for X in Xs do D.X := unit end + {Dictionary.keys D} + end + + %% print grouped by parallelizable jobs + proc {PrintSolution Sol} + for I in 1..{Record.foldL Sol Value.max 1} do + for Lib in {Arity {Record.filter Sol fun {$ X} X == I end}} do + {System.printInfo Lib#" "} + end + {System.printInfo "\n"} + end + end + + fun {GetOrderedLibs Sol} + {Map + {Sort {Record.toListInd Sol} CompareSecond} + SelectFirst} + end + fun {CompareSecond A B} A.2 < B.2 end + fun {SelectFirst X} X.1 end +in + case {SearchOne TopologicalOrder} + of nil then {System.showInfo "Un-orderable."} + [] [Sol] then + {System.showInfo "A possible topological ordering: "} + {ForAll {GetOrderedLibs Sol} System.showInfo} + + {System.showInfo "\nBONUS - grouped by parallelizable compile jobs:"} + {PrintSolution Sol} + end diff --git a/Task/Topological-sort/Perl-6/topological-sort-1.pl6 b/Task/Topological-sort/Perl-6/topological-sort-1.pl6 new file mode 100644 index 0000000000..dad1462d24 --- /dev/null +++ b/Task/Topological-sort/Perl-6/topological-sort-1.pl6 @@ -0,0 +1,37 @@ +sub print_topo_sort ( %deps ) { + my %ba; + for %deps.kv -> $before, @afters { + for @afters -> $after { + %ba{$before}{$after} = 1 if $before ne $after; + %ba{$after} //= {}; + } + } + + while %ba.grep( not *.value )».key -> @afters { + say ~@afters.sort; + %ba.delete(@afters); + %ba.values».delete(@afters); + } + + say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---'; +} + +my %deps = + des_system_lib => < std synopsys std_cell_lib des_system_lib dw02 + dw01 ramlib ieee >, + dw01 => < ieee dw01 dware gtech >, + dw02 => < ieee dw02 dware >, + dw03 => < std synopsys dware dw03 dw02 dw01 ieee gtech >, + dw04 => < dw04 ieee dw01 dware gtech >, + dw05 => < dw05 ieee dware >, + dw06 => < dw06 ieee dware >, + dw07 => < ieee dware >, + dware => < ieee dware >, + gtech => < ieee gtech >, + ramlib => < std ieee >, + std_cell_lib => < ieee std_cell_lib >, + synopsys => < >; + +print_topo_sort(%deps); +%deps.push: 'dw04'; # Add unresolvable dependency +print_topo_sort(%deps); diff --git a/Task/Topological-sort/Perl-6/topological-sort-2.pl6 b/Task/Topological-sort/Perl-6/topological-sort-2.pl6 new file mode 100644 index 0000000000..a71acfeb24 --- /dev/null +++ b/Task/Topological-sort/Perl-6/topological-sort-2.pl6 @@ -0,0 +1,13 @@ +sub print_topo_sort ( %deps ) { + my %ba = %deps.kv».map: * => set; + %ba{.key}.=union(set .value) if .key ne .value + for %deps.map: { .key X=> .value } + + while %ba.grep((:!value))».key -> @afters { + say ~@afters.sort; + %ba.delete(@afters); + %ba{*}».=difference(@afters); + } + + say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---'; +} diff --git a/Task/Topological-sort/Perl/topological-sort.pl b/Task/Topological-sort/Perl/topological-sort.pl new file mode 100644 index 0000000000..7ed10fdaa6 --- /dev/null +++ b/Task/Topological-sort/Perl/topological-sort.pl @@ -0,0 +1,39 @@ +sub print_topo_sort { + my %deps = @_; + + my %ba; + while ( my ( $before, $afters_aref ) = each %deps ) { + for my $after ( @{ $afters_aref } ) { + $ba{$before}{$after} = 1 if $before ne $after; + $ba{$after} ||= {}; + } + } + + while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) { + print "@afters\n"; + delete @ba{@afters}; + delete @{$_}{@afters} for values %ba; + } + + print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n"; +} + +my %deps = ( + des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02 + dw01 ramlib ieee )], + dw01 => [qw( ieee dw01 dware gtech )], + dw02 => [qw( ieee dw02 dware )], + dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )], + dw04 => [qw( dw04 ieee dw01 dware gtech )], + dw05 => [qw( dw05 ieee dware )], + dw06 => [qw( dw06 ieee dware )], + dw07 => [qw( ieee dware )], + dware => [qw( ieee dware )], + gtech => [qw( ieee gtech )], + ramlib => [qw( std ieee )], + std_cell_lib => [qw( ieee std_cell_lib )], + synopsys => [qw( )], +); +print_topo_sort(%deps); +push @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency +print_topo_sort(%deps); diff --git a/Task/Topological-sort/PicoLisp/topological-sort.l b/Task/Topological-sort/PicoLisp/topological-sort.l new file mode 100644 index 0000000000..2530ec4627 --- /dev/null +++ b/Task/Topological-sort/PicoLisp/topological-sort.l @@ -0,0 +1,15 @@ +(de sortDependencies (Lst) + (setq Lst # Build a flat list + (uniq + (mapcan + '((L) + (put (car L) 'dep (cdr L)) # Store dependencies in 'dep' properties + (copy L) ) + (mapcar uniq Lst) ) ) ) # without self-dependencies + (make + (while Lst + (ifn (find '((This) (not (: dep))) Lst) # Found non-depending lib? + (quit "Can't resolve dependencies" Lst) + (del (link @) 'Lst) # Yes: Store in result + (for This Lst # and remove from 'dep's + (=: dep (delete @ (: dep))) ) ) ) ) ) diff --git a/Task/Topological-sort/PowerShell/topological-sort.psh b/Task/Topological-sort/PowerShell/topological-sort.psh new file mode 100644 index 0000000000..8aa0fd14b8 --- /dev/null +++ b/Task/Topological-sort/PowerShell/topological-sort.psh @@ -0,0 +1,99 @@ +#Input Data +$a=@" +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys +"@ +#Convert to Object[] +$c = switch ( $a.split([char] 10) ) { + $_ { + $b=$_.split(' ') + New-Object PSObject -Property @{ + Library = $b[0] + "Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) ) + } + } +} +#Add pure dependencies +$c | ForEach-Object { + $_."Library Dependencies" | Where-Object { + $d=$_ + $(:andl foreach($i in $c) { + if($d -match $i.Library) { + $false + break andl + } + }) -eq $null + } | ForEach-Object { + $c+=New-Object PSObject -Property @{ + Library=$_ + "Library Dependencies"=@() + } + } +} +#Associate with a dependency value +##Initial Dependency Value +$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{ + Name="Dep Value" + Expression={ + 1 + } +} +##Modify Dependency Value, perform check for incorrect dependency +##Dep Value is determined by a parent child relationship, if a library is a parent, all libraries dependant on it are children +for( $i=0; $i -lt $d.count; $i++ ) { + $errmsg="" + foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) { + #Foreach other Child Library where this is a dependency, increase the Dep Value of the Child + if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) { + if( $k -match $d[$i].Library ) { + foreach( $n in $d[$i]."Library Dependencies" ) { + if( $n -match $d[$j].Library ) { + $errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library + break + } + } + $true + break orl + } + } ) ) { + #If the child has already been processed, increase the Dep Value of its children + if( $j -lt $i ) { + foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) { + if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) { + if( $m -match $d[$j].Library ) { + $true + break orl2 + } + } ) ) { + $d[$l]."Dep Value"+=$d[$i]."Dep Value" + } + } + } + $d[$j]."Dep Value"+=$d[$i]."Dep Value" + } + if( $errmsg -ne "" ) { + $errmsg + $d=$null + break + } + } +} +#Sort and Display +if( $d ) { + $d | Sort "Dep Value",Library | ForEach-Object { + "{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "=======" + } { + "{0,-14} $($_."Library Dependencies")" -f $_.Library + } +} diff --git a/Task/Topological-sort/PureBasic/topological-sort.purebasic b/Task/Topological-sort/PureBasic/topological-sort.purebasic new file mode 100644 index 0000000000..088b31bee0 --- /dev/null +++ b/Task/Topological-sort/PureBasic/topological-sort.purebasic @@ -0,0 +1,119 @@ +#EndOfDataMarker$ = "::EndOfData::" +DataSection + ;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N] + Data.s "des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]" + Data.s "dw01: [ieee dw01 dware gtech]" + ;Data.s "dw01: [ieee dw01 dware gtech dw04]" ;comment the previous line and uncomment this one for cyclic dependency + Data.s "dw02: [ieee dw02 dware]" + Data.s "dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech]" + Data.s "dw04: [dw04 ieee dw01 dware gtech]" + Data.s "dw05: [dw05 ieee dware]" + Data.s "dw06: [dw06 ieee dware]" + Data.s "dw07: [ieee dware]" + Data.s "dware: [ieee dware]" + Data.s "gtech: [ieee gtech]" + Data.s "ramlib: [std ieee]" + Data.s "std_cell_lib: [ieee std_cell_lib]" + Data.s "synopsys: nil" + Data.s #EndOfDataMarker$ +EndDataSection + +Structure DAG_node + Value.s + forRemoval.i ;flag marks elements that should be removed the next time they are accessed + List dependencies.s() +EndStructure + +If Not OpenConsole() + MessageRequester("Error","Unable to open console") + End +EndIf + +;// initialize Directed Acyclic Graph // +Define i, itemData.s, firstBracketPos +NewList DAG.DAG_node() +Repeat + Read.s itemData + itemData = Trim(itemData) + If itemData <> #EndOfDataMarker$ + AddElement(DAG()) + ;add library + DAG()\Value = Trim(Left(itemData, FindString(itemData, ":", 1) - 1)) + ;parse library dependencies + firstBracketPos = FindString(itemData, "[", 1) + If firstBracketPos + itemData = Trim(Mid(itemData, firstBracketPos + 1, FindString(itemData, "]", 1) - firstBracketPos - 1)) + For i = (CountString(itemData, " ") + 1) To 1 Step -1 + AddElement(DAG()\dependencies()) + DAG()\dependencies() = StringField(itemData, i, " ") + Next + EndIf + EndIf +Until itemData = #EndOfDataMarker$ + +;// process DAG // +;create DAG entry for nodes listed in dependencies but without their own entry +NewMap libraries() +ForEach DAG() + ForEach DAG()\dependencies() + libraries(DAG()\dependencies()) = #True + If DAG()\dependencies() = DAG()\Value + DeleteElement(DAG()\dependencies()) ;remove self-dependencies + EndIf + Next +Next + +ForEach DAG() + If FindMapElement(libraries(),DAG()\Value) + DeleteMapElement(libraries(),DAG()\Value) + EndIf +Next + +ResetList(DAG()) +ForEach libraries() + AddElement(DAG()) + DAG()\Value = MapKey(libraries()) +Next +ClearMap(libraries()) + +;process DAG() repeatedly until no changes occur +NewList compileOrder.s() +Repeat + noChangesMade = #True + ForEach DAG() + If DAG()\forRemoval + DeleteElement(DAG()) + Else + ;remove dependencies that have been placed in the compileOrder + ForEach DAG()\dependencies() + If FindMapElement(libraries(),DAG()\dependencies()) + DeleteElement(DAG()\dependencies()) + EndIf + Next + ;add DAG() entry to compileOrder if it has no more dependencies + If ListSize(DAG()\dependencies()) = 0 + AddElement(compileOrder()) + compileOrder() = DAG()\Value + libraries(DAG()\Value) = #True ;mark the library for removal as a dependency + DAG()\forRemoval = #True + noChangesMade = #False + EndIf + EndIf + Next +Until noChangesMade + +If ListSize(DAG()) + PrintN("Cyclic dependencies detected in:" + #CRLF$) + ForEach DAG() + PrintN(" " + DAG()\Value) + Next +Else + PrintN("Compile order:" + #CRLF$) + ForEach compileOrder() + PrintN(" " + compileOrder()) + Next +EndIf + +Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") +Input() +CloseConsole() diff --git a/Task/Topological-sort/Python/topological-sort.py b/Task/Topological-sort/Python/topological-sort.py new file mode 100644 index 0000000000..44ce79ca69 --- /dev/null +++ b/Task/Topological-sort/Python/topological-sort.py @@ -0,0 +1,36 @@ +try: + from functools import reduce +except: + pass + +data = { + 'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()), + 'dw01': set('ieee dw01 dware gtech'.split()), + 'dw02': set('ieee dw02 dware'.split()), + 'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()), + 'dw04': set('dw04 ieee dw01 dware gtech'.split()), + 'dw05': set('dw05 ieee dware'.split()), + 'dw06': set('dw06 ieee dware'.split()), + 'dw07': set('ieee dware'.split()), + 'dware': set('ieee dware'.split()), + 'gtech': set('ieee gtech'.split()), + 'ramlib': set('std ieee'.split()), + 'std_cell_lib': set('ieee std_cell_lib'.split()), + 'synopsys': set(), + } + +def toposort2(data): + for k, v in data.items(): + v.discard(k) # Ignore self dependencies + extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys()) + data.update({item:set() for item in extra_items_in_deps}) + while True: + ordered = set(item for item,dep in data.items() if not dep) + if not ordered: + break + yield ' '.join(sorted(ordered)) + data = {item: (dep - ordered) for item,dep in data.items() + if item not in ordered} + assert not data, "A cyclic dependency exists amongst %r" % data + +print ('\n'.join( toposort2(data) )) diff --git a/Task/Topological-sort/R/topological-sort-1.r b/Task/Topological-sort/R/topological-sort-1.r new file mode 100644 index 0000000000..89d3396a91 --- /dev/null +++ b/Task/Topological-sort/R/topological-sort-1.r @@ -0,0 +1,14 @@ +deps <- list( +"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"), +"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"), +"dw02" = c("ieee", "dw02", "dware"), +"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"), +"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"), +"dw05" = c("dw05", "ieee", "dware"), +"dw06" = c("dw06", "ieee", "dware"), +"dw07" = c("ieee", "dware"), +"dware" = c("ieee", "dware"), +"gtech" = c("ieee", "gtech"), +"ramlib" = c("std", "ieee"), +"std_cell_lib" = c("ieee", "std_cell_lib"), +"synopsys" = c()) diff --git a/Task/Topological-sort/R/topological-sort-2.r b/Task/Topological-sort/R/topological-sort-2.r new file mode 100644 index 0000000000..1fbbd39607 --- /dev/null +++ b/Task/Topological-sort/R/topological-sort-2.r @@ -0,0 +1,31 @@ +tsort <- function(deps) { + nm <- names(deps) + libs <- union(as.vector(unlist(deps)), nm) + + s <- c() + # first libs that depend on nothing + for(x in libs) { + if(!(x %in% nm)) { + s <- c(s, x) + } + } + + k <- 1 + while(k > 0) { + k <- 0 + for(x in setdiff(nm, s)) { + r <- c(s, x) + if(length(setdiff(deps[[x]], r)) == 0) { + s <- r + k <- 1 + } + } + } + + if(length(s) < length(libs)) { + v <- setdiff(libs, s) + stop(sprintf("Unorderable items :\n%s", paste("", v, sep="", collapse="\n"))) + } + + s +} diff --git a/Task/Topological-sort/R/topological-sort-3.r b/Task/Topological-sort/R/topological-sort-3.r new file mode 100644 index 0000000000..6f15e80334 --- /dev/null +++ b/Task/Topological-sort/R/topological-sort-3.r @@ -0,0 +1,4 @@ +tsort(deps) +# [1] "std" "ieee" "dware" "gtech" "ramlib" +# [6] "std_cell_lib" "synopsys" "dw01" "dw02" "dw03" +#[11] "dw04" "dw05" "dw06" "dw07" "des_system_lib" diff --git a/Task/Topological-sort/R/topological-sort-4.r b/Task/Topological-sort/R/topological-sort-4.r new file mode 100644 index 0000000000..e3d757cb9a --- /dev/null +++ b/Task/Topological-sort/R/topological-sort-4.r @@ -0,0 +1,5 @@ +Unorderable items : +des_system_lib +dw01 +dw04 +dw03 diff --git a/Task/Topological-sort/Ruby/topological-sort.rb b/Task/Topological-sort/Ruby/topological-sort.rb new file mode 100644 index 0000000000..542eb9b5d9 --- /dev/null +++ b/Task/Topological-sort/Ruby/topological-sort.rb @@ -0,0 +1,39 @@ +require 'tsort' +class Hash + include TSort + alias tsort_each_node each_key + def tsort_each_child(node, &block) + fetch(node).each(&block) + end +end + +depends = {} +DATA.each do |line| + libs = line.split(' ') + key = libs.shift + depends[key] = libs + libs.each {|lib| depends[lib] ||= []} +end + +begin + p depends.tsort + depends["dw01"] << "dw04" + p depends.tsort +rescue TSort::Cyclic => e + puts "cycle detected: #{e}" +end + +__END__ +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys diff --git a/Task/Topological-sort/Tcl/topological-sort-1.tcl b/Task/Topological-sort/Tcl/topological-sort-1.tcl new file mode 100644 index 0000000000..04123ef803 --- /dev/null +++ b/Task/Topological-sort/Tcl/topological-sort-1.tcl @@ -0,0 +1,37 @@ +package require Tcl 8.5 +proc topsort {data} { + # Clean the data + dict for {node depends} $data { + if {[set i [lsearch -exact $depends $node]] >= 0} { + set depends [lreplace $depends $i $i] + dict set data $node $depends + } + foreach node $depends {dict lappend data $node} + } + # Do the sort + set sorted {} + while 1 { + # Find available nodes + set avail [dict keys [dict filter $data value {}]] + if {![llength $avail]} { + if {[dict size $data]} { + error "graph is cyclic, possibly involving nodes \"[dict keys $data]\"" + } + return $sorted + } + # Note that the lsort is only necessary for making the results more like other langs + lappend sorted {*}[lsort $avail] + # Remove from working copy of graph + dict for {node depends} $data { + foreach n $avail { + if {[set i [lsearch -exact $depends $n]] >= 0} { + set depends [lreplace $depends $i $i] + dict set data $node $depends + } + } + } + foreach node $avail { + dict unset data $node + } + } +} diff --git a/Task/Topological-sort/Tcl/topological-sort-2.tcl b/Task/Topological-sort/Tcl/topological-sort-2.tcl new file mode 100644 index 0000000000..a0a001a732 --- /dev/null +++ b/Task/Topological-sort/Tcl/topological-sort-2.tcl @@ -0,0 +1,20 @@ +set inputData { + des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee + dw01 ieee dw01 dware gtech + dw02 ieee dw02 dware + dw03 std synopsys dware dw03 dw02 dw01 ieee gtech + dw04 dw04 ieee dw01 dware gtech + dw05 dw05 ieee dware + dw06 dw06 ieee dware + dw07 ieee dware + dware ieee dware + gtech ieee gtech + ramlib std ieee + std_cell_lib ieee std_cell_lib + synopsys +} +foreach line [split $inputData \n] { + if {[string trim $line] eq ""} continue + dict set parsedData [lindex $line 0] [lrange $line 1 end] +} +puts [topsort $parsedData] diff --git a/Task/Topological-sort/UNIX-Shell/topological-sort.sh b/Task/Topological-sort/UNIX-Shell/topological-sort.sh new file mode 100644 index 0000000000..fa4235fc89 --- /dev/null +++ b/Task/Topological-sort/UNIX-Shell/topological-sort.sh @@ -0,0 +1,30 @@ +$ awk '{ for (i = 1; i <= NF; i++) print $i, $1 }' < des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +> dw01 ieee dw01 dware gtech +> dw02 ieee dw02 dware +> dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +> dw04 dw04 ieee dw01 dware gtech +> dw05 dw05 ieee dware +> dw06 dw06 ieee dware +> dw07 ieee dware +> dware ieee dware +> gtech ieee gtech +> ramlib std ieee +> std_cell_lib ieee std_cell_lib +> synopsys +> ! +ieee +dware +dw02 +dw05 +dw06 +dw07 +gtech +dw01 +dw04 +std_cell_lib +synopsys +std +dw03 +ramlib +des_system_lib diff --git a/Task/Topological-sort/Ursala/topological-sort-1.ursala b/Task/Topological-sort/Ursala/topological-sort-1.ursala new file mode 100644 index 0000000000..15584c3e5d --- /dev/null +++ b/Task/Topological-sort/Ursala/topological-sort-1.ursala @@ -0,0 +1 @@ +tsort = ~&nmnNCjA*imSLs2nSjiNCSPT; @NiX ^=lxPrnSPX ^(~&rlPlT,~&rnPrmPljA*D@r)^|/~& ~&m!=rnSPlX diff --git a/Task/Topological-sort/Ursala/topological-sort-2.ursala b/Task/Topological-sort/Ursala/topological-sort-2.ursala new file mode 100644 index 0000000000..d69796b1f9 --- /dev/null +++ b/Task/Topological-sort/Ursala/topological-sort-2.ursala @@ -0,0 +1,25 @@ +#import std + +dependence_table = -[ + +LIBRARY LIBRARY DEPENDENCIES +======= ==================== +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys ]- + +parse = ~&htA*FS+ sep` *tttt + +#show+ + +main = <.~&l,@r ~&i&& 'unorderable: '--> mat` ~~ tsort parse dependence_table diff --git a/Task/Topological-sort/VBScript/topological-sort-1.vbscript b/Task/Topological-sort/VBScript/topological-sort-1.vbscript new file mode 100644 index 0000000000..a90468a11e --- /dev/null +++ b/Task/Topological-sort/VBScript/topological-sort-1.vbscript @@ -0,0 +1,79 @@ +class topological + dim dictDependencies + dim dictReported + dim depth + + sub class_initialize + set dictDependencies = createobject("Scripting.Dictionary") + set dictReported = createobject("Scripting.Dictionary") + depth = 0 + end sub + + sub reset + dictReported.removeall + end sub + + property let dependencies( s ) + 'assuming token tab token-list newline + dim i, j ,k + dim aList + dim dep + dim a1 + aList = Split( s, vbNewLine ) + '~ remove empty lines at end + do while aList( UBound( aList ) ) = vbnullstring + redim preserve aList( UBound( aList ) - 1 ) + loop + + for i = lbound( aList ) to ubound( aList ) + aList( i ) = Split( aList( i ), vbTab, 2 ) + a1 = Split( aList( i )( 1 ), " " ) + k = 0 + for j = lbound( a1) to ubound(a1) + if a1(j) <> aList(i)(0) then + a1(k) = a1(j) + k = k + 1 + end if + next + redim preserve a1(k-1) + aList(i)(1) = a1 + next + for i = lbound( aList ) to ubound( aList ) + dep = aList(i)(0) + if not dictDependencies.Exists( dep ) then + dictDependencies.add dep, aList(i)(1) + end if + next + + end property + + sub resolve( s ) + dim i + dim deps + '~ wscript.echo string(depth,"!"),s + depth = depth + 1 + if dictDependencies.Exists(s) then + deps = dictDependencies(s) + for i = lbound(deps) to ubound(deps) + resolve deps(i) + next + end if + if not seen(s) then + wscript.echo s + see s + end if + depth = depth - 1 + end sub + + function seen( key ) + seen = dictReported.Exists( key ) + end function + + sub see( key ) + dictReported.add key, "" + end sub + + property get keys + keys = dictDependencies.keys + end property +end class diff --git a/Task/Topological-sort/VBScript/topological-sort-2.vbscript b/Task/Topological-sort/VBScript/topological-sort-2.vbscript new file mode 100644 index 0000000000..d288174421 --- /dev/null +++ b/Task/Topological-sort/VBScript/topological-sort-2.vbscript @@ -0,0 +1,23 @@ +dim toposort +set toposort = new topological +toposort.dependencies = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee" & vbNewLine & _ + "dw01 ieee dw01 dware gtech" & vbNewLine & _ + "dw02 ieee dw02 dware" & vbNewLine & _ + "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech" & vbNewLine & _ + "dw04 dw04 ieee dw01 dware gtech" & vbNewLine & _ + "dw05 dw05 ieee dware" & vbNewLine & _ + "dw06 dw06 ieee dware" & vbNewLine & _ + "dw07 ieee dware" & vbNewLine & _ + "dware ieee dware" & vbNewLine & _ + "gtech ieee gtech" & vbNewLine & _ + "ramlib std ieee" & vbNewLine & _ + "std_cell_lib ieee std_cell_lib" & vbNewLine & _ + "synopsys " + +dim k +for each k in toposort.keys + wscript.echo "----- " & k + toposort.resolve k + wscript.echo "-----" + toposort.reset +next diff --git a/Task/Topological-sort/Visual-Basic-.NET/topological-sort.visual b/Task/Topological-sort/Visual-Basic-.NET/topological-sort.visual new file mode 100644 index 0000000000..796384de5e --- /dev/null +++ b/Task/Topological-sort/Visual-Basic-.NET/topological-sort.visual @@ -0,0 +1,329 @@ +' Adapted from: +' http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html +' added/changed: +' - conversion to VB.Net (.Net 2 framework) +' - added Rosetta Code dependency format parsing +' - check & removal of self-dependencies before sorting +Module Program + Sub Main() + Dim Fields As New List(Of Field)() + ' You can also add Dependson using code like: + ' .DependsOn = New String() {"ieee", "dw01", "dware"} _ + + fields.Add(New Field() With { _ + .Name = "des_system_lib", _ + .DependsOn = Split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw01", _ + .DependsOn = Split("ieee dw01 dware gtech", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw02", _ + .DependsOn = Split("ieee dw02 dware", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw03", _ + .DependsOn = Split("std synopsys dware dw03 dw02 dw01 ieee gtech", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw04", _ + .DependsOn = Split("dw04 ieee dw01 dware gtech", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw05", _ + .DependsOn = Split("dw05 ieee dware", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw06", _ + .DependsOn = Split("dw06 ieee dware", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dw07", _ + .DependsOn = Split("ieee dware", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "dware", _ + .DependsOn = Split("ieee dware", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "gtech", _ + .DependsOn = Split("ieee gtech", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "ramlib", _ + .DependsOn = Split("std ieee", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "std_cell_lib", _ + .DependsOn = Split("ieee std_cell_lib", " ") _ + }) + fields.Add(New Field() With { _ + .Name = "synopsys" _ + }) + Console.WriteLine("Input:") + For Each ThisField As field In fields + Console.WriteLine(ThisField.Name) + If ThisField.DependsOn IsNot Nothing Then + For Each item As String In ThisField.DependsOn + Console.WriteLine(" -{0}", item) + Next + End If + Next + + Console.WriteLine(vbLf & "...Sorting..." & vbLf) + + Dim sortOrder As Integer() = getTopologicalSortOrder(fields) + + For i As Integer = 0 To sortOrder.Length - 1 + Dim field = fields(sortOrder(i)) + Console.WriteLine(field.Name) + ' Write up dependencies, too: + 'If field.DependsOn IsNot Nothing Then + ' For Each item As String In field.DependsOn + ' Console.WriteLine(" -{0}", item) + ' Next + 'End If + Next + Console.Write("Press any key to continue . . . ") + Console.ReadKey(True) + End Sub + + Private Sub CheckDependencies (ByRef Fields As List(Of Field)) + ' Make sure all objects we depend on are part of the field list + ' themselves, as there may be dependencies that are not specified as fields themselves. + ' Remove dependencies on fields themselves.Y + Dim AField As Field, ADependency As String + + For i As Integer = Fields.Count - 1 To 0 Step -1 + AField=fields(i) + If AField.DependsOn IsNot Nothing then + For j As Integer = 0 To Ubound(AField.DependsOn) + ADependency = Afield.DependsOn(j) + ' We ignore fields that depends on themselves: + If AField.Name <> ADependency then + If ListContainsVertex(fields, ADependency) = False Then + ' Add the dependent object to the field list, as it + ' needs to be there, without any dependencies + Fields.Add(New Field() With { _ + .Name = ADependency _ + }) + End If + End If + Next j + End If + Next i + End Sub + + Private Sub RemoveSelfDependencies (ByRef Fields As List(Of Field)) + ' Make sure our fields don't depend on themselves. + ' If they do, remove the dependency. + Dim InitialUbound as Integer + For Each AField As Field In Fields + If AField.DependsOn IsNot Nothing Then + InitialUbound = Ubound(AField.DependsOn) + For i As Integer = InitialUbound to 0 Step - 1 + If Afield.DependsOn(i) = Afield.Name Then + ' This field depends on itself, so remove + For j as Integer = i To UBound(AField.DependsOn)-1 + Afield.DependsOn(j)=Afield.DependsOn(j+1) + Next + ReDim Preserve Afield.DependsOn(UBound(Afield.DependsOn)-1) + End If + Next + End If + Next + End Sub + + Private Function ListContainsVertex(Fields As List(Of Field), VertexName As String) As Boolean + ' Check to see if the list of Fields already contains a vertext called VertexName + Dim Found As Boolean = False + For i As Integer = 0 To fields.Count - 1 + If Fields(i).Name = VertexName Then + Found = True + Exit For + End If + Next + Return Found + End Function + + Private Function getTopologicalSortOrder(ByRef Fields As List(Of Field)) As Integer() + ' Gets sort order. Will also add required dependencies to + ' Fields. + + ' Make sure we don't have dependencies on ourselves. + ' We'll just get rid of them. + RemoveSelfDependencies(Fields) + + 'First check depencies, add them to Fields if required: + CheckDependencies(Fields) + ' Now we have the correct Fields list, so we can proceed: + Dim g As New TopologicalSorter(fields.Count) + Dim _indexes As New Dictionary(Of String, Integer)(fields.count) + + 'add vertex names to our lookup dictionaey + For i As Integer = 0 To fields.Count - 1 + _indexes(fields(i).Name.ToLower()) = g.AddVertex(i) + Next + + 'add edges + For i As Integer = 0 To fields.Count - 1 + If fields(i).DependsOn IsNot Nothing Then + For j As Integer = 0 To fields(i).DependsOn.Length - 1 + g.AddEdge(i, _indexes(fields(i).DependsOn(j).ToLower())) + Next + End If + Next + + Dim result As Integer() = g.Sort() + Return result + End Function + + Private Class Field + Public Property Name() As String + Get + Return m_Name + End Get + Set + m_Name = Value + End Set + End Property + Private m_Name As String + Public Property DependsOn() As String() + Get + Return m_DependsOn + End Get + Set + m_DependsOn = Value + End Set + End Property + Private m_DependsOn As String() + End Class +End Module +Class TopologicalSorter + ''source adapted from: + ''http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html + ''which was adapted from: + ''http://www.java2s.com/Code/Java/Collections-Data-Structure/Topologicalsorting.htm + #Region "- Private Members -" + + Private ReadOnly _vertices As Integer() + ' list of vertices + Private ReadOnly _matrix As Integer(,) + ' adjacency matrix + Private _numVerts As Integer + ' current number of vertices + Private ReadOnly _sortedArray As Integer() + ' Sorted vertex labels + + #End Region + + #Region "- CTors -" + + Public Sub New(size As Integer) + _vertices = New Integer(size - 1) {} + _matrix = New Integer(size - 1, size - 1) {} + _numVerts = 0 + For i As Integer = 0 To size - 1 + For j As Integer = 0 To size - 1 + _matrix(i, j) = 0 + Next + Next + ' sorted vert labels + _sortedArray = New Integer(size - 1) {} + End Sub + + #End Region + + #Region "- Public Methods -" + + Public Function AddVertex(vertex As Integer) As Integer + _vertices(System.Threading.Interlocked.Increment(_numVerts)-1) = vertex + Return _numVerts - 1 + End Function + + Public Sub AddEdge(start As Integer, [end] As Integer) + _matrix(start, [end]) = 1 + End Sub + + Public Function Sort() As Integer() + ' Topological sort + While _numVerts > 0 + ' while vertices remain, + ' get a vertex with no successors, or -1 + Dim currentVertex As Integer = noSuccessors() + If currentVertex = -1 Then + ' must be a cycle + Throw New Exception("Graph has cycles") + End If + + ' insert vertex label in sorted array (start at end) + _sortedArray(_numVerts - 1) = _vertices(currentVertex) + + ' delete vertex + deleteVertex(currentVertex) + End While + + ' vertices all gone; return sortedArray + Return _sortedArray + End Function + + #End Region + + #Region "- Private Helper Methods -" + + ' returns vert with no successors (or -1 if no such verts) + Private Function noSuccessors() As Integer + For row As Integer = 0 To _numVerts - 1 + Dim isEdge As Boolean = False + ' edge from row to column in adjMat + For col As Integer = 0 To _numVerts - 1 + If _matrix(row, col) > 0 Then + ' if edge to another, + isEdge = True + ' this vertex has a successor try another + Exit For + End If + Next + If Not isEdge Then + ' if no edges, has no successors + Return row + End If + Next + Return -1 + ' no + End Function + + Private Sub deleteVertex(delVert As Integer) + ' if not last vertex, delete from vertexList + If delVert <> _numVerts - 1 Then + For j As Integer = delVert To _numVerts - 2 + _vertices(j) = _vertices(j + 1) + Next + + For row As Integer = delVert To _numVerts - 2 + moveRowUp(row, _numVerts) + Next + + For col As Integer = delVert To _numVerts - 2 + moveColLeft(col, _numVerts - 1) + Next + End If + _numVerts -= 1 + ' one less vertex + End Sub + + Private Sub moveRowUp(row As Integer, length As Integer) + For col As Integer = 0 To length - 1 + _matrix(row, col) = _matrix(row + 1, col) + Next + End Sub + + Private Sub moveColLeft(col As Integer, length As Integer) + For row As Integer = 0 To length - 1 + _matrix(row, col) = _matrix(row, col + 1) + Next + End Sub + + #End Region +End Class diff --git a/Task/Topswops/0DESCRIPTION b/Task/Topswops/0DESCRIPTION new file mode 100644 index 0000000000..b270c11e6a --- /dev/null +++ b/Task/Topswops/0DESCRIPTION @@ -0,0 +1,22 @@ +Topswops is a card game created by John Conway in the 1970's. + +Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. A round is composed of reversing the first m cards where m is the value of the topmost card. rounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. For our example the swaps produce: +
    [2, 4, 1, 3]    # Initial shuffle
+    [4, 2, 1, 3]
+    [3, 1, 2, 4]
+    [2, 1, 3, 4]
+    [1, 2, 3, 4]
+For a total of four swaps from the initial ordering to produce the terminating case where 1 is on top. + + +For a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards. + +;Task: +The task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive. + +;Note: +[[oeis:A000375|Topswops]] is also known as [http://www.haskell.org/haskellwiki/Shootout/Fannkuch Fannkuch] from the German Pfannkuchen meaning [http://youtu.be/3biN6nQYqZY pancake]. + +;Cf. +* [[Number reversal game]] +* [[Sorting algorithms/Pancake sort]] diff --git a/Task/Topswops/C/topswops-1.c b/Task/Topswops/C/topswops-1.c new file mode 100644 index 0000000000..9c13d3fba6 --- /dev/null +++ b/Task/Topswops/C/topswops-1.c @@ -0,0 +1,45 @@ +#include +#include + +typedef struct { char v[16]; } deck; +typedef unsigned int uint; + +uint n, d, best[16]; + +void tryswaps(deck *a, uint f, uint s) { +# define A a->v +# define B b.v + if (d > best[n]) best[n] = d; + while (1) { + if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) + && (d + best[s] >= best[n] || A[s] == -1)) + break; + + if (d + best[s] <= best[n]) return; + if (!--s) return; + } + + d++; + deck b = *a; + for (uint i = 1, k = 2; i <= s; k <<= 1, i++) { + if (A[i] != i && (A[i] != -1 || (f & k))) + continue; + + for (uint j = B[0] = i; j--;) B[i - j] = A[j]; + tryswaps(&b, f | k, s); + } + d--; +} + +int main(void) { + deck x; + memset(&x, -1, sizeof(x)); + x.v[0] = 0; + + for (n = 1; n < 13; n++) { + tryswaps(&x, 1, n - 1); + printf("%2d: %d\n", n, best[n]); + } + + return 0; +} diff --git a/Task/Topswops/C/topswops-2.c b/Task/Topswops/C/topswops-2.c new file mode 100644 index 0000000000..3559015d76 --- /dev/null +++ b/Task/Topswops/C/topswops-2.c @@ -0,0 +1,116 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define MAX_CPUS 8 // increase this if you got more CPUs/cores + +typedef struct { char v[16]; } deck; + +int n, best[16]; + +// Update a shared variable by spinlock. Since this program really only +// enters locks dozens of times, a pthread_mutex_lock() would work +// equally fine, but RC already has plenty of examples for that. +#define SWAP_OR_RETRY(var, old, new) \ + if (!__sync_bool_compare_and_swap(&(var), old, new)) { \ + volatile int spin = 64; \ + while (spin--); \ + continue; } + +void tryswaps(deck *a, int f, int s, int d) { +#define A a->v +#define B b->v + + while (best[n] < d) { + int t = best[n]; + SWAP_OR_RETRY(best[n], t, d); + } + +#define TEST(x) \ + case x: if ((A[15-x] == 15-x || (A[15-x] == -1 && !(f & 1<<(15-x)))) \ + && (A[15-x] == -1 || d + best[15-x] >= best[n])) \ + break; \ + if (d + best[15-x] <= best[n]) return; \ + s = 14 - x + + switch (15 - s) { + TEST(0); TEST(1); TEST(2); TEST(3); TEST(4); + TEST(5); TEST(6); TEST(7); TEST(8); TEST(9); + TEST(10); TEST(11); TEST(12); TEST(13); TEST(14); + return; + } +#undef TEST + + deck *b = a + 1; + *b = *a; + d++; + +#define FLIP(x) \ + if (A[x] == x || ((A[x] == -1) && !(f & (1<= n) return 0; + + SWAP_OR_RETRY(first_swap, at, at + 1); + + memset(job->x, -1, sizeof(deck)); + job->x[0].v[at] = 0; + job->x[0].v[0] = at; + tryswaps(job->x, 1 | (1 << at), n - 1, 1); + } +} + +int main(void) { + int n_cpus = num_cpus(); + + for (int i = 0; i < MAX_CPUS; i++) + jobs[i].id = i; + + pthread_t tid[MAX_CPUS]; + + for (n = 2; n <= 14; n++) { + int top = n_cpus; + if (top > n) top = n; + + first_swap = 1; + for (int i = 0; i < top; i++) + pthread_create(tid + i, 0, thread_start, jobs + i); + + for (int i = 0; i < top; i++) + pthread_join(tid[i], 0); + + printf("%2d: %2d\n", n, best[n]); + } + + return 0; +} diff --git a/Task/Topswops/D/topswops-1.d b/Task/Topswops/D/topswops-1.d new file mode 100644 index 0000000000..ea1155fc40 --- /dev/null +++ b/Task/Topswops/D/topswops-1.d @@ -0,0 +1,15 @@ +import std.stdio, std.algorithm, std.range, permutations2; + +int topswops(in int n) { + static int flip(int[] xa) pure nothrow { + if (!xa[0]) return 0; + xa[0 .. xa[0] + 1].reverse(); // Slow with DMD. + return 1 + flip(xa); + } + return n.iota.array.permutations.map!flip.reduce!max; +} + +void main() { + foreach (immutable i; 1 .. 11) + writeln(i, ": ", i.topswops); +} diff --git a/Task/Topswops/D/topswops-2.d b/Task/Topswops/D/topswops-2.d new file mode 100644 index 0000000000..846a6cd5c0 --- /dev/null +++ b/Task/Topswops/D/topswops-2.d @@ -0,0 +1,59 @@ +import std.stdio, std.typetuple; + +template Range(int start, int stop) { + static if (stop <= start) + alias TypeTuple!() Range; + else + alias TypeTuple!(Range!(start, stop - 1), stop - 1) Range; +} + +__gshared uint[32] best; + +uint topswops(size_t n)() nothrow { + static assert(n > 0 && n < best.length); + size_t d = 0; + + alias T = byte; + alias Deck = T[n]; + + void trySwaps(in ref Deck deck, in uint f) nothrow { + if (d > best[n]) + best[n] = d; + + foreach_reverse (immutable i; Range!(0, n)) { + if ((deck[i] == i || (deck[i] == -1 && !(f & (1U << i)))) + && (d + best[i] >= best[n] || deck[i] == -1)) + break; + if (d + best[i] <= best[n]) + return; + } + + Deck deck2 = void; + foreach (immutable i; Range!(0, n)) // Copy. + deck2[i] = deck[i]; + + d++; + foreach (immutable i; Range!(1, n)) { + enum uint k = 1U << i; + if (deck[i] != i && (deck[i] != -1 || (f & k))) + continue; + + deck2[0] = cast(T)i; + foreach_reverse (immutable j; Range!(0, i)) + deck2[i - j] = deck[j]; // Reverse copy. + trySwaps(deck2, f | k); + } + d--; + } + + best[n] = 0; + Deck deck0 = -1; + deck0[0] = 0; + trySwaps(deck0, 1); + return best[n]; +} + +void main() { + foreach (i; Range!(1, 14)) + writefln("%2d: %d", i, topswops!i()); +} diff --git a/Task/Topswops/Go/topswops.go b/Task/Topswops/Go/topswops.go new file mode 100644 index 0000000000..26f1b249e9 --- /dev/null +++ b/Task/Topswops/Go/topswops.go @@ -0,0 +1,55 @@ +// Adapted from http://www-cs-faculty.stanford.edu/~uno/programs/topswops.w +// at Donald Knuth's web site. Algorithm credited there to Pepperdine +// and referenced to Mathematical Gazette 73 (1989), 131-133. +package main + +import "fmt" + +const ( // array sizes + maxn = 10 // max number of cards + maxl = 50 // upper bound for number of steps +) + +func main() { + for i := 1; i <= maxn; i++ { + fmt.Printf("%d: %d\n", i, steps(i)) + } +} + +func steps(n int) int { + var a, b [maxl][maxn + 1]int + var x [maxl]int + a[0][0] = 1 + var m int + for l := 0; ; { + x[l]++ + k := int(x[l]) + if k >= n { + if l <= 0 { + break + } + l-- + continue + } + if a[l][k] == 0 { + if b[l][k+1] != 0 { + continue + } + } else if a[l][k] != k+1 { + continue + } + a[l+1] = a[l] + for j := 1; j <= k; j++ { + a[l+1][j] = a[l][k-j] + } + b[l+1] = b[l] + a[l+1][0] = k + 1 + b[l+1][k+1] = 1 + if l > m-1 { + m = l + 1 + } + l++ + x[l] = 0 + } + return m +} diff --git a/Task/Topswops/Haskell/topswops-1.hs b/Task/Topswops/Haskell/topswops-1.hs new file mode 100644 index 0000000000..b1a6e73a34 --- /dev/null +++ b/Task/Topswops/Haskell/topswops-1.hs @@ -0,0 +1,13 @@ +import Data.List (permutations) + +topswops :: Int -> Int +topswops n = maximum $ map tops $ permutations [1 .. n] + where + tops (1 : _) = 0 + tops xa@(x : _) = 1 + tops reordered + where + reordered = reverse (take x xa) ++ drop x xa + +main = mapM_ + (\x -> putStrLn $ show x ++ ":\t" ++ show (topswops x)) + [1 .. 10] diff --git a/Task/Topswops/Haskell/topswops-2.hs b/Task/Topswops/Haskell/topswops-2.hs new file mode 100644 index 0000000000..71b5b2ebc2 --- /dev/null +++ b/Task/Topswops/Haskell/topswops-2.hs @@ -0,0 +1,12 @@ +import Data.List +import Control.Arrow +import Control.Monad + +derangements [1] = [[1]] +derangements xs = filter (and . zipWith (/=) [1..] ). permutations $ xs +topswop = ((uncurry (++). first reverse).). splitAt +topswopIter = takeWhile((/=1).head). iterate (topswop =<< head) +swops = map (length. topswopIter). derangements + +topSwops :: [Int] -> [(Int, Int)] +topSwops = zip [1..]. map (maximum. swops). drop 1. inits diff --git a/Task/Topswops/J/topswops-1.j b/Task/Topswops/J/topswops-1.j new file mode 100644 index 0000000000..c07d31e669 --- /dev/null +++ b/Task/Topswops/J/topswops-1.j @@ -0,0 +1 @@ + swops =: ((|.@:{. , }.)~ {.)^:a: diff --git a/Task/Topswops/J/topswops-2.j b/Task/Topswops/J/topswops-2.j new file mode 100644 index 0000000000..276517471d --- /dev/null +++ b/Task/Topswops/J/topswops-2.j @@ -0,0 +1,6 @@ + swops 2 4 1 3 +2 4 1 3 +4 2 1 3 +3 1 2 4 +2 1 3 4 +1 2 3 4 diff --git a/Task/Topswops/J/topswops-3.j b/Task/Topswops/J/topswops-3.j new file mode 100644 index 0000000000..4a6fb23036 --- /dev/null +++ b/Task/Topswops/J/topswops-3.j @@ -0,0 +1,11 @@ + (,. _1 + ! >./@:(#@swops@A. >:)&i. ])&> 1+i.10 + 1 0 + 2 1 + 3 2 + 4 4 + 5 7 + 6 10 + 7 16 + 8 22 + 9 30 +10 38 diff --git a/Task/Topswops/Java/topswops.java b/Task/Topswops/Java/topswops.java new file mode 100644 index 0000000000..bf6054052f --- /dev/null +++ b/Task/Topswops/Java/topswops.java @@ -0,0 +1,47 @@ +public class Topswops { + static final int maxBest = 32; + static int[] best; + + static private void trySwaps(int[] deck, int f, int d, int n) { + if (d > best[n]) + best[n] = d; + + for (int i = n - 1; i >= 0; i--) { + if (deck[i] == -1 || deck[i] == i) + break; + if (d + best[i] <= best[n]) + return; + } + + int[] deck2 = deck.clone(); + for (int i = 1; i < n; i++) { + final int k = 1 << i; + if (deck2[i] == -1) { + if ((f & k) != 0) + continue; + } else if (deck2[i] != i) + continue; + + deck2[0] = i; + for (int j = i - 1; j >= 0; j--) + deck2[i - j] = deck[j]; // Reverse copy. + trySwaps(deck2, f | k, d + 1, n); + } + } + + static int topswops(int n) { + assert(n > 0 && n < maxBest); + best[n] = 0; + int[] deck0 = new int[n + 1]; + for (int i = 1; i < n; i++) + deck0[i] = -1; + trySwaps(deck0, 1, 0, n); + return best[n]; + } + + public static void main(String[] args) { + best = new int[maxBest]; + for (int i = 1; i < 11; i++) + System.out.println(i + ": " + topswops(i)); + } +} diff --git a/Task/Topswops/Julia/topswops.julia b/Task/Topswops/Julia/topswops.julia new file mode 100644 index 0000000000..defe36e3cd --- /dev/null +++ b/Task/Topswops/Julia/topswops.julia @@ -0,0 +1,16 @@ +function topswops(n) + first = [1:n]; swapsa = ref(Int) + for perm = 2:(factorial(n)/factorial(n-n)) + swaps = 0 + a = nthperm(first,perm) + if a == first + break + else + while a[1] != 1 + a[1:a[1]] = reverse(a[1:a[1]]); swaps+= 1 + end + push!(swapsa,swaps) + end + end + return max(swapsa) +end diff --git a/Task/Topswops/Mathematica/topswops.math b/Task/Topswops/Mathematica/topswops.math new file mode 100644 index 0000000000..1669272589 --- /dev/null +++ b/Task/Topswops/Mathematica/topswops.math @@ -0,0 +1,8 @@ +flip[a_] := + Block[{a1 = First@a}, + If[a1 == Length@a, Reverse[a], + Join[Reverse[a[[;; a1]]], a[[a1 + 1 ;;]]]]] + +swaps[a_] := Length@FixedPointList[flip, a] - 2 + +Print[#, ": ", Max[swaps /@ Permutations[Range@#]]] & /@ Range[10]; diff --git a/Task/Topswops/Perl-6/topswops.pl6 b/Task/Topswops/Perl-6/topswops.pl6 new file mode 100644 index 0000000000..e774edfbec --- /dev/null +++ b/Task/Topswops/Perl-6/topswops.pl6 @@ -0,0 +1,19 @@ +sub postfix:(@a) { + @a == 1 + ?? [@a] + !! do for @a -> $a { + [ $a, @$_ ] for @a.grep(* != $a)! + } +} + +sub swops(@a is copy) { + my $count = 0; + until @a[0] == 1 { + @a[ ^@a[0] ] .= reverse; + $count++; + } + return $count; +} +sub topswops($n) { [max] map &swops, (1 .. $n)! } + +say "$_ {topswops $_}" for 1 .. 10; diff --git a/Task/Topswops/Python/topswops-1.py b/Task/Topswops/Python/topswops-1.py new file mode 100644 index 0000000000..be9590ca3a --- /dev/null +++ b/Task/Topswops/Python/topswops-1.py @@ -0,0 +1,26 @@ +>>> from itertools import permutations +>>> def f1(p): + i, p0 = 0, p[0] + while p0: + i += 1 + p0 += 1 + p[:p0] = p[:p0][::-1] + p0 = p[0] + return i + +>>> def fannkuch(n): + return max(f1(list(p)) for p in permutations(range(n))) + +>>> for n in range(1, 11): print(n,fannkuch(n)) + +1 0 +2 1 +3 2 +4 4 +5 7 +6 10 +7 16 +8 22 +9 30 +10 38 +>>> diff --git a/Task/Topswops/Python/topswops-2.py b/Task/Topswops/Python/topswops-2.py new file mode 100644 index 0000000000..40c5958563 --- /dev/null +++ b/Task/Topswops/Python/topswops-2.py @@ -0,0 +1,46 @@ +try: + import psyco + psyco.full() +except ImportError: + pass + +best = [0] * 16 + +def try_swaps(deck, f, s, d, n): + if d > best[n]: + best[n] = d + + i = 0 + k = 1 << s + while s: + k >>= 1 + s -= 1 + if deck[s] == -1 or deck[s] == s: + break + i |= k + if (i & f) == i and d + best[s] <= best[n]: + return d + s += 1 + + deck2 = list(deck) + k = 1 + for i2 in xrange(1, s): + k <<= 1 + if deck2[i2] == -1: + if f & k: continue + elif deck2[i2] != i2: + continue + + deck[i2] = i2 + deck2[:i2 + 1] = reversed(deck[:i2 + 1]) + try_swaps(deck2, f | k, s, 1 + d, n) + +def topswops(n): + best[n] = 0 + deck0 = [-1] * 16 + deck0[0] = 0 + try_swaps(deck0, 1, n, 0, n) + return best[n] + +for i in xrange(1, 13): + print "%2d: %d" % (i, topswops(i)) diff --git a/Task/Topswops/REXX/topswops.rexx b/Task/Topswops/REXX/topswops.rexx new file mode 100644 index 0000000000..4a7b0f35e8 --- /dev/null +++ b/Task/Topswops/REXX/topswops.rexx @@ -0,0 +1,41 @@ +/*REXX pgm gens N decks of numbered cards and finds the maximum "swops".*/ +parse arg things .; if things=='' then things=10; thingsX= things>9 + + do n=1 for things; #=deckSets(n,n) /*create "decks".*/ + mx= n\==1 /*handle case of a one-card deck.*/ + do i=1 for # + mx=max(mx,swops(!.i)) + end /*i*/ + say '──────── maximum swops for a deck of' right(n,2) ' cards is' right(mx,4) + end /*n*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────DECKSETS subroutine─────────────────*/ +deckSets: procedure expose !. /*X things taken Y at a time.*/ +parse arg x,y,,$ @.; #=0; call .deckset 1 /*set $ & @. to null.*/ +return # /*return # permutations (decks).*/ +.deckset: procedure expose @. x y $ # !.; parse arg ? +if ?>y then do; _=@.1; do j=2 to y; _=_ @.j; end /*j*/; #=#+1; !.#=_ + end + else do + ?m=?-1 /*used in the FOR for faster DO.*/ + if ?==1 then qs=2 /*¬ use 1-swops that start with 1*/ + else do + qs=1 + if @.1==? then qs=2 /*skip 1-swops: 3 x 1 x */ + end + do q=qs to x /*build permutation recursively. */ + do k=1 for ?m; if @.k==q then iterate q; end /*k*/ + @.?=q; call .deckset(?+1) + end /*q*/ + end +return +/*──────────────────────────────────SWOPS subroutine────────────────────*/ +swops: parse arg z; do _=1; t=word(z,1) + if word(z,t)==1 then return _ + if thingsX then do h=10 to things + z=changestr(h,z,d2x(h)) + end /*h*/ + z=reverse(subword(z,1,t)) subword(z,t+1) + if thingsX then do d=10 to things + z=changestr(d2x(d),z,d) + end /*_*/ diff --git a/Task/Topswops/Tcl/topswops.tcl b/Task/Topswops/Tcl/topswops.tcl new file mode 100644 index 0000000000..e24b4cc150 --- /dev/null +++ b/Task/Topswops/Tcl/topswops.tcl @@ -0,0 +1,34 @@ +package require struct::list + +proc swap {listVar} { + upvar 1 $listVar list + set n [lindex $list 0] + for {set i 0; set j [expr {$n-1}]} {$i<$j} {incr i;incr j -1} { + set tmp [lindex $list $i] + lset list $i [lindex $list $j] + lset list $j $tmp + } +} + +proc swaps {list} { + for {set i 0} {[lindex $list 0] > 1} {incr i} { + swap list + } + return $i +} + +proc topswops list { + set n 0 + ::struct::list foreachperm p $list { + set n [expr {max($n,[swaps $p])}] + } + return $n +} + +proc topswopsTo n { + puts "n\ttopswops(n)" + for {set i 1} {$i <= $n} {incr i} { + puts $i\t[topswops [lappend list $i]] + } +} +topswopsTo 10 diff --git a/Task/Topswops/XPL0/topswops-1.xpl0 b/Task/Topswops/XPL0/topswops-1.xpl0 new file mode 100644 index 0000000000..c8d2ac1bca --- /dev/null +++ b/Task/Topswops/XPL0/topswops-1.xpl0 @@ -0,0 +1,37 @@ +code ChOut=8, CrLf=9, IntOut=11; +int N, Max, Card1(16), Card2(16); + +proc Topswop(D); \Conway's card swopping game +int D; \depth of recursion +int I, J, C, T; +[if D # N then \generate N! permutations of 1..N in Card1 + [for I:= 0 to N-1 do + [for J:= 0 to D-1 do \check if object (letter) already used + if Card1(J) = I+1 then J:=100; + if J < 100 then + [Card1(D):= I+1; \card number not used so append it + Topswop(D+1); \recurse next level deeper + ]; + ]; + ] +else [\determine number of topswops to get card 1 at beginning + for I:= 0 to N-1 do Card2(I):= Card1(I); \make working copy of deck + C:= 0; \initialize swop counter + while Card2(0) # 1 do + [I:= 0; J:= Card2(0)-1; + while I < J do + [T:= Card2(I); Card2(I):= Card2(J); Card2(J):= T; + I:= I+1; J:= J-1; + ]; + C:= C+1; + ]; + if C>Max then Max:= C; + ]; +]; + +[for N:= 1 to 10 do + [Max:= 0; + Topswop(0); + IntOut(0, N); ChOut(0, ^ ); IntOut(0, Max); CrLf(0); + ]; +] diff --git a/Task/Topswops/XPL0/topswops-2.xpl0 b/Task/Topswops/XPL0/topswops-2.xpl0 new file mode 100644 index 0000000000..6f2a0fd546 --- /dev/null +++ b/Task/Topswops/XPL0/topswops-2.xpl0 @@ -0,0 +1,36 @@ +code CrLf=9, IntOut=11, Text=12; +int N, D, Best(16); + +proc TrySwaps(A, F, S); +int A, F, S; +int B(16), I, J, K; +[if D > Best(N) then Best(N):= D; +loop [if A(S)=-1 ! A(S)=S then quit; + if D+Best(S) <= Best(N) then return; + if S = 0 then quit; + S:= S-1; + ]; +D:= D+1; +for I:= 0 to S do B(I):= A(I); +K:= 1; +for I:= 1 to S do + [K:= K<<1; + if B(I)=-1 & (F&K)=0 ! B(I)=I then + [J:= I; B(0):= J; + while J do [J:= J-1; B(I-J):= A(J)]; + TrySwaps(B, F!K, S); + ]; + ]; +D:= D-1; +]; + +int I, X(16); +[for I:= 0 to 16-1 do + [X(I):= -1; Best(I):= 0]; +X(0):= 0; +for N:= 1 to 13 do + [D:= 0; + TrySwaps(X, 1, N-1); + IntOut(0, N); Text(0, ": "); IntOut(0, Best(N)); CrLf(0); + ]; +] diff --git a/Task/Towers-of-Hanoi/0DESCRIPTION b/Task/Towers-of-Hanoi/0DESCRIPTION new file mode 100644 index 0000000000..dd0e7ca3e6 --- /dev/null +++ b/Task/Towers-of-Hanoi/0DESCRIPTION @@ -0,0 +1 @@ +In this task, the goal is to solve the [[wp:Towers_of_Hanoi|Towers of Hanoi]] problem with recursion. diff --git a/Task/Towers-of-Hanoi/1META.yaml b/Task/Towers-of-Hanoi/1META.yaml new file mode 100644 index 0000000000..4431bf6fc2 --- /dev/null +++ b/Task/Towers-of-Hanoi/1META.yaml @@ -0,0 +1,5 @@ +--- +category: +- Recursion +- Games +note: Classic CS problems and programs diff --git a/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi.alg b/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi.alg new file mode 100644 index 0000000000..60dbf97b08 --- /dev/null +++ b/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi.alg @@ -0,0 +1,11 @@ +PROC move = (INT n, from, to, via) VOID: + IF n > 0 THEN + move(n - 1, from, via, to); + printf(($"Move disk from pole "g" to pole "gl$, from, to)); + move(n - 1, via, to, from) + FI +; + +main: ( + move(4, 1,2,3) +) diff --git a/Task/Towers-of-Hanoi/AWK/towers-of-hanoi.awk b/Task/Towers-of-Hanoi/AWK/towers-of-hanoi.awk new file mode 100644 index 0000000000..ab933ca1cc --- /dev/null +++ b/Task/Towers-of-Hanoi/AWK/towers-of-hanoi.awk @@ -0,0 +1,2 @@ +$ awk 'func hanoi(n,f,t,v){if(n>0){hanoi(n-1,f,v,t);print(f,"->",t);hanoi(n-1,v,t,f)}} +BEGIN{hanoi(4,"left","middle","right")}' diff --git a/Task/Towers-of-Hanoi/ActionScript/towers-of-hanoi.as b/Task/Towers-of-Hanoi/ActionScript/towers-of-hanoi.as new file mode 100644 index 0000000000..1eebc8c1b8 --- /dev/null +++ b/Task/Towers-of-Hanoi/ActionScript/towers-of-hanoi.as @@ -0,0 +1,9 @@ +public function move(n:int, from:int, to:int, via:int):void +{ + if (n > 0) + { + move(n - 1, from, via, to); + trace("Move disk from pole " + from + " to pole " + to); + move(n - 1, via, to, from); + } +} diff --git a/Task/Towers-of-Hanoi/Ada/towers-of-hanoi.ada b/Task/Towers-of-Hanoi/Ada/towers-of-hanoi.ada new file mode 100644 index 0000000000..43b7d109c9 --- /dev/null +++ b/Task/Towers-of-Hanoi/Ada/towers-of-hanoi.ada @@ -0,0 +1,15 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Towers is + type Pegs is (Left, Center, Right); + procedure Hanoi (Ndisks : Natural; Start_Peg : Pegs := Left; End_Peg : Pegs := Right; Via_Peg : Pegs := Center) is + begin + if Ndisks > 0 then + Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg); + Put_Line("Move disk" & Natural'Image(Ndisks) & " from " & Pegs'Image(Start_Peg) & " to " & Pegs'Image(End_Peg)); + Hanoi(Ndisks - 1, Via_Peg, End_Peg, Start_Peg); + end if; + end Hanoi; +begin + Hanoi(4); +end Towers; diff --git a/Task/Towers-of-Hanoi/Agena/towers-of-hanoi.agena b/Task/Towers-of-Hanoi/Agena/towers-of-hanoi.agena new file mode 100644 index 0000000000..02c0757bea --- /dev/null +++ b/Task/Towers-of-Hanoi/Agena/towers-of-hanoi.agena @@ -0,0 +1,9 @@ +move := proc(n::number, src::number, dst::number, via::number) is + if n > 0 then + move(n - 1, src, via, dst) + print(src & ' to ' & dst) + move(n - 1, via, dst, src) + fi +end + +move(4, 1, 2, 3) diff --git a/Task/Towers-of-Hanoi/AmigaE/towers-of-hanoi.amiga b/Task/Towers-of-Hanoi/AmigaE/towers-of-hanoi.amiga new file mode 100644 index 0000000000..fde1dcfc92 --- /dev/null +++ b/Task/Towers-of-Hanoi/AmigaE/towers-of-hanoi.amiga @@ -0,0 +1,11 @@ +PROC move(n, from, to, via) + IF n > 0 + move(n-1, from, via, to) + WriteF('Move disk from pole \d to pole \d\n', from, to) + move(n-1, via, to, from) + ENDIF +ENDPROC + +PROC main() + move(4, 1,2,3) +ENDPROC diff --git a/Task/Towers-of-Hanoi/AppleScript/towers-of-hanoi.applescript b/Task/Towers-of-Hanoi/AppleScript/towers-of-hanoi.applescript new file mode 100644 index 0000000000..5697c8f5fd --- /dev/null +++ b/Task/Towers-of-Hanoi/AppleScript/towers-of-hanoi.applescript @@ -0,0 +1,12 @@ +global moves --this is so the handler 'hanoi' can see the 'moves' variable +set moves to "" +hanoi(4, "peg A", "peg C", "peg B") + +on hanoi(ndisks, fromPeg, toPeg, withPeg) + if ndisks is greater than 0 then + hanoi(ndisks - 1, fromPeg, withPeg, toPeg) + set moves to moves & "Move disk " & ndisks & " from " & fromPeg & " to " & toPeg & return + hanoi(ndisks - 1, withPeg, toPeg, fromPeg) + end if + return moves +end hanoi diff --git a/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk b/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk new file mode 100644 index 0000000000..50dd04054b --- /dev/null +++ b/Task/Towers-of-Hanoi/AutoHotkey/towers-of-hanoi.ahk @@ -0,0 +1,13 @@ +move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = remaining pole +{ + if (n = 1) + { + msgbox , Move disk from pole %from% to pole %to% + } + else + { + move(n-1, from, via, to) + move(1, from, to, via) + move(n-1, via, to, from) + } +} diff --git a/Task/Towers-of-Hanoi/AutoIt/towers-of-hanoi.autoit b/Task/Towers-of-Hanoi/AutoIt/towers-of-hanoi.autoit new file mode 100644 index 0000000000..f951137a90 --- /dev/null +++ b/Task/Towers-of-Hanoi/AutoIt/towers-of-hanoi.autoit @@ -0,0 +1,11 @@ +Func move($n, $from, $to, $via) + If ($n = 1) Then + ConsoleWrite(StringFormat("Move disk from pole "&$from&" To pole "&$to&"\n")) + Else + move($n - 1, $from, $via, $to) + move(1, $from, $to, $via) + move($n - 1, $via, $to, $from) + EndIf +EndFunc + +move(4, 1,2,3) diff --git a/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-1.basic b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-1.basic new file mode 100644 index 0000000000..d5ca295739 --- /dev/null +++ b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-1.basic @@ -0,0 +1,9 @@ +SUB move (n AS Integer, fromPeg AS Integer, toPeg AS Integer, viaPeg AS Integer) + IF n>0 THEN + move n-1, fromPeg, viaPeg, toPeg + PRINT "Move disk from "; fromPeg; " to "; toPeg + move n-1, viaPeg, toPeg, fromPeg + END IF +END SUB + +move 4,1,2,3 diff --git a/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-2.basic b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-2.basic new file mode 100644 index 0000000000..30bf2aaf7e --- /dev/null +++ b/Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-2.basic @@ -0,0 +1,26 @@ +10 DIM N(1024), F(1024), T(1024), V(1024): REM STACK PER PARAMETER +20 SP = 0: REM STACK POINTER +30 N(SP) = 4: REM START WITH 4 DISCS +40 F(SP) = 1: REM ON PEG 1 +50 T(SP) = 2: REM MOVE TO PEG 2 +60 V(SP) = 3: REM VIA PEG 3 +70 GOSUB 100 +80 END +90 REM MOVE SUBROUTINE +100 IF N(SP) = 0 THEN RETURN +110 OS = SP: REMEMBER STACK POINTER +120 SP = SP + 1: REM INCREMENT STACK POINTER +130 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS +140 F(SP) = F(OS) : REM FROM START PEG +150 T(SP) = V(OS) : REM TO VIA PEG +160 V(SP) = T(OS) : REM VIA TO PEG +170 GOSUB 100 +180 OS = SP - 1: REM OS WILL HAVE CHANGED +190 PRINT "MOVE DISC FROM"; F(OS); "TO"; T(OS) +200 N(SP) = N(OS) - 1: REM MOVE N-1 DISCS +210 F(SP) = V(OS) : REM FROM VIA PEG +220 T(SP) = T(OS) : REM TO DEST PEG +230 V(SP) = F(OS) : REM VIA FROM PEG +240 GOSUB 100 +250 SP = SP - 1 : REM RESTORE STACK POINTER FOR CALLER +260 RETURN diff --git a/Task/Towers-of-Hanoi/BASIC256/towers-of-hanoi.basic256 b/Task/Towers-of-Hanoi/BASIC256/towers-of-hanoi.basic256 new file mode 100644 index 0000000000..e3903deea2 --- /dev/null +++ b/Task/Towers-of-Hanoi/BASIC256/towers-of-hanoi.basic256 @@ -0,0 +1,11 @@ +call move(4,1,2,3) +print "Towers of Hanoi puzzle completed!" +end + +subroutine move (n, fromPeg, toPeg, viaPeg) + if n>0 then + call move(n-1, fromPeg, viaPeg, toPeg) + print "Move disk from "+fromPeg+" to "+toPeg + call move(n-1, viaPeg, toPeg, fromPeg) + end if +end subroutine diff --git a/Task/Towers-of-Hanoi/BBC-BASIC/towers-of-hanoi.bbc b/Task/Towers-of-Hanoi/BBC-BASIC/towers-of-hanoi.bbc new file mode 100644 index 0000000000..ed1c26fd17 --- /dev/null +++ b/Task/Towers-of-Hanoi/BBC-BASIC/towers-of-hanoi.bbc @@ -0,0 +1,36 @@ + DIM Disc$(13),Size%(3) + FOR disc% = 1 TO 13 + Disc$(disc%) = STRING$(disc%," ")+STR$disc%+STRING$(disc%," ") + IF disc%>=10 Disc$(disc%) = MID$(Disc$(disc%),2) + Disc$(disc%) = CHR$17+CHR$(128+disc%-(disc%>7))+Disc$(disc%)+CHR$17+CHR$128 + NEXT disc% + + MODE 3 + OFF + ndiscs% = 13 + FOR n% = ndiscs% TO 1 STEP -1 + PROCput(n%,1) + NEXT + INPUT TAB(0,0) "Press Enter to start" dummy$ + PRINT TAB(0,0) SPC(20); + PROChanoi(ndiscs%,1,2,3) + VDU 30 + END + + DEF PROChanoi(a%,b%,c%,d%) + IF a%=0 ENDPROC + PROChanoi(a%-1,b%,d%,c%) + PROCtake(a%,b%) + PROCput(a%,c%) + PROChanoi(a%-1,d%,c%,b%) + ENDPROC + + DEF PROCput(disc%,peg%) + PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))Disc$(disc%); + Size%(peg%) = Size%(peg%)+1 + ENDPROC + + DEF PROCtake(disc%,peg%) + Size%(peg%) = Size%(peg%)-1 + PRINTTAB(13+26*(peg%-1)-disc%,20-Size%(peg%))STRING$(2*disc%+1," "); + ENDPROC diff --git a/Task/Towers-of-Hanoi/Bracmat/towers-of-hanoi.bracmat b/Task/Towers-of-Hanoi/Bracmat/towers-of-hanoi.bracmat new file mode 100644 index 0000000000..6106e7b32c --- /dev/null +++ b/Task/Towers-of-Hanoi/Bracmat/towers-of-hanoi.bracmat @@ -0,0 +1,12 @@ +( ( move + = n from to via + . !arg:(?n,?from,?to,?via) + & ( !n:>0 + & move$(!n+-1,!from,!via,!to) + & out$("Move disk from pole " !from " to pole " !to) + & move$(!n+-1,!via,!to,!from) + | + ) + ) +& move$(4,1,2,3) +); diff --git a/Task/Towers-of-Hanoi/C++/towers-of-hanoi.cpp b/Task/Towers-of-Hanoi/C++/towers-of-hanoi.cpp new file mode 100644 index 0000000000..3143a48ac2 --- /dev/null +++ b/Task/Towers-of-Hanoi/C++/towers-of-hanoi.cpp @@ -0,0 +1,9 @@ +void move(int n, int from, int to, int via) { + if (n == 1) { + std::cout << "Move disk from pole " << from << " to pole " << to << std::endl; + } else { + move(n - 1, from, via, to); + move(1, from, to, via); + move(n - 1, via, to, from); + } +} diff --git a/Task/Towers-of-Hanoi/C/towers-of-hanoi-1.c b/Task/Towers-of-Hanoi/C/towers-of-hanoi-1.c new file mode 100644 index 0000000000..f2abd618b0 --- /dev/null +++ b/Task/Towers-of-Hanoi/C/towers-of-hanoi-1.c @@ -0,0 +1,15 @@ +#include + +void move(int n, int from, int to, int via) +{ + if (n > 0) { + move(n - 1, from, via, to); + printf("Move disk from pole %d to pole %d\n", from, to); + move(n - 1, via, to, from); + } +} +int main() +{ + move(4, 1,2,3); + return 0; +} diff --git a/Task/Towers-of-Hanoi/C/towers-of-hanoi-2.c b/Task/Towers-of-Hanoi/C/towers-of-hanoi-2.c new file mode 100644 index 0000000000..de0aee3c14 --- /dev/null +++ b/Task/Towers-of-Hanoi/C/towers-of-hanoi-2.c @@ -0,0 +1,60 @@ +#include +#include +#include + +typedef struct { int *x, n; } tower; +tower *new_tower(int cap) +{ + tower *t = calloc(1, sizeof(tower) + sizeof(int) * cap); + t->x = (int*)(t + 1); + return t; +} + +tower *t[3]; +int height; + +void text(int y, int i, int d, const char *s) +{ + printf("\033[%d;%dH", height - y + 1, (height + 1) * (2 * i + 1) - d); + while (d--) printf("%s", s); +} + +void add_disk(int i, int d) +{ + t[i]->x[t[i]->n++] = d; + text(t[i]->n, i, d, "=="); + + usleep(100000); + fflush(stdout); +} + +int remove_disk(int i) +{ + int d = t[i]->x[--t[i]->n]; + text(t[i]->n + 1, i, d, " "); + return d; +} + +void move(int n, int from, int to, int via) +{ + if (!n) return; + + move(n - 1, from, via, to); + add_disk(to, remove_disk(from)); + move(n - 1, via, to, from); +} + +int main(int c, char *v[]) +{ + puts("\033[H\033[J"); + + if (c <= 1 || (height = atoi(v[1])) <= 0) + height = 8; + for (c = 0; c < 3; c++) t[c] = new_tower(height); + for (c = height; c; c--) add_disk(0, c); + + move(height, 0, 2, 1); + + text(1, 0, 1, "\n"); + return 0; +} diff --git a/Task/Towers-of-Hanoi/Clojure/towers-of-hanoi.clj b/Task/Towers-of-Hanoi/Clojure/towers-of-hanoi.clj new file mode 100644 index 0000000000..93be6da2a5 --- /dev/null +++ b/Task/Towers-of-Hanoi/Clojure/towers-of-hanoi.clj @@ -0,0 +1,7 @@ +(defn towers-of-hanoi [n from to via] + (if (= n 1) + (println (format "Move from %s to %s" from to)) + (do + (towers-of-hanoi (dec n) from via to) + (println (format "Move from %s to %s" from to)) + (recur (dec n) via to from)))) diff --git a/Task/Towers-of-Hanoi/CoffeeScript/towers-of-hanoi.coffeescript b/Task/Towers-of-Hanoi/CoffeeScript/towers-of-hanoi.coffeescript new file mode 100644 index 0000000000..332b1ec156 --- /dev/null +++ b/Task/Towers-of-Hanoi/CoffeeScript/towers-of-hanoi.coffeescript @@ -0,0 +1,8 @@ +hanoi = (ndisks, start_peg=1, end_peg=3) -> + if ndisks + staging_peg = 1 + 2 + 3 - start_peg - end_peg + hanoi(ndisks-1, start_peg, staging_peg) + console.log "Move disk #{ndisks} from peg #{start_peg} to #{end_peg}" + hanoi(ndisks-1, staging_peg, end_peg) + +hanoi(4) diff --git a/Task/Towers-of-Hanoi/Common-Lisp/towers-of-hanoi.lisp b/Task/Towers-of-Hanoi/Common-Lisp/towers-of-hanoi.lisp new file mode 100644 index 0000000000..d64f8c2160 --- /dev/null +++ b/Task/Towers-of-Hanoi/Common-Lisp/towers-of-hanoi.lisp @@ -0,0 +1,7 @@ +(defun move (n from to via) + (cond ((= n 1) + (format t "Move from ~A to ~A.~%" from to)) + (t + (move (- n 1) from via to) + (format t "Move from ~A to ~A.~%" from to) + (move (- n 1) via to from)))) diff --git a/Task/Towers-of-Hanoi/D/towers-of-hanoi-1.d b/Task/Towers-of-Hanoi/D/towers-of-hanoi-1.d new file mode 100644 index 0000000000..456c821620 --- /dev/null +++ b/Task/Towers-of-Hanoi/D/towers-of-hanoi-1.d @@ -0,0 +1,13 @@ +import std.stdio; + +void hanoi(in int n, in char from, in char to, in char via) { + if (n > 0) { + hanoi(n - 1, from, via, to); + writefln("Move disk %d from %s to %s", n, from, to); + hanoi(n - 1, via, to, from); + } +} + +void main() { + hanoi(3, 'L', 'M', 'R'); +} diff --git a/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d b/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d new file mode 100644 index 0000000000..5d46e90c78 --- /dev/null +++ b/Task/Towers-of-Hanoi/D/towers-of-hanoi-2.d @@ -0,0 +1,43 @@ +import std.stdio, std.conv, std.typetuple; + +void main(in string[] args) { + // Code found and then improved by Glenn C. Rhoads, + // then some more by M. Kolar (2000). + + immutable size_t n = (args.length > 1) ? to!size_t(args[1]) : 3; + size_t[3] p = [(1 << n) - 1, 0, 0]; + + printf("\n|"); + foreach_reverse (size_t i; 1 .. n + 1) + printf(" %zd", i); + printf("\n|\n|\n"); + + foreach (size_t x; 1 .. (1 << n)) { + { + immutable size_t i1 = x & (x - 1); + immutable size_t fr = (i1 + i1 / 3) & 3; + immutable size_t i2 = (x | (x - 1)) + 1; + immutable size_t to = (i2 + i2 / 3) & 3; + + size_t j = 1; + for (int w = x; !(w & 1); w >>= 1, j <<= 1) {} + + // Now j is not the number of the disk to move, + // it contains the single bit to be moved: + p[fr] &= ~j; + p[to] |= j; + } + + foreach (immutable(size_t) k; TypeTuple!(0, 1, 2)) { + printf("\n|"); + size_t j = 1 << n; + foreach_reverse (size_t w; 1 .. n + 1) { + j >>= 1; + if (j & p[k]) + printf(" %zd", w); + } + } + + putchar('\n'); + } +} diff --git a/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-1.dart b/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-1.dart new file mode 100644 index 0000000000..82ec928612 --- /dev/null +++ b/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-1.dart @@ -0,0 +1,15 @@ +main() { + moveit(from,to) { + print("move ${from} ---> ${to}"); + } + + hanoi(height,toPole,fromPole,usePole) { + if (height>0) { + hanoi(height-1,usePole,fromPole,toPole); + moveit(fromPole,toPole); + hanoi(height-1,toPole,usePole,fromPole); + } + } + + hanoi(3,3,1,2); +} diff --git a/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-2.dart b/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-2.dart new file mode 100644 index 0000000000..4069ca7102 --- /dev/null +++ b/Task/Towers-of-Hanoi/Dart/towers-of-hanoi-2.dart @@ -0,0 +1,13 @@ +main() { + String say(String from, String to) => "$from ---> $to"; + + hanoi(int height, int toPole, int fromPole, int usePole) { + if (height > 0) { + hanoi(height - 1, usePole, fromPole, toPole); + print(say(fromPole.toString(), toPole.toString())); + hanoi(height - 1, toPole, usePole, fromPole); + } + } + + hanoi(3, 3, 1, 2); +} diff --git a/Task/Towers-of-Hanoi/E/towers-of-hanoi.e b/Task/Towers-of-Hanoi/E/towers-of-hanoi.e new file mode 100644 index 0000000000..c46da16615 --- /dev/null +++ b/Task/Towers-of-Hanoi/E/towers-of-hanoi.e @@ -0,0 +1,9 @@ +def move(out, n, fromPeg, toPeg, viaPeg) { + if (n.aboveZero()) { + move(out, n.previous(), fromPeg, viaPeg, toPeg) + out.println(`Move disk $n from $fromPeg to $toPeg.`) + move(out, n.previous(), viaPeg, toPeg, fromPeg) + } +} + +move(stdout, 4, def left {}, def right {}, def middle {}) diff --git a/Task/Towers-of-Hanoi/Emacs-Lisp/towers-of-hanoi.l b/Task/Towers-of-Hanoi/Emacs-Lisp/towers-of-hanoi.l new file mode 100644 index 0000000000..11185dd7f5 --- /dev/null +++ b/Task/Towers-of-Hanoi/Emacs-Lisp/towers-of-hanoi.l @@ -0,0 +1,8 @@ +(defun move (n from to via) + (cond ((= n 1) + (print (format "Move from %S to %S" from to))) + (t + (progn + (move (- n 1) from via to) + (print (format "Move from %S to %S" from to)) + (move (- n 1) via to from))))) diff --git a/Task/Towers-of-Hanoi/Erlang/towers-of-hanoi.erl b/Task/Towers-of-Hanoi/Erlang/towers-of-hanoi.erl new file mode 100644 index 0000000000..ff5a2a7755 --- /dev/null +++ b/Task/Towers-of-Hanoi/Erlang/towers-of-hanoi.erl @@ -0,0 +1,6 @@ +move(1, F, T, _V) -> + io:format("Move from ~p to ~p~n", [F, T]); +move(N, F, T, V) -> + move(N-1, F, V, T), + move(1 , F, T, V), + move(N-1, V, T, F). diff --git a/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria b/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria new file mode 100644 index 0000000000..86a4a5f965 --- /dev/null +++ b/Task/Towers-of-Hanoi/Euphoria/towers-of-hanoi.euphoria @@ -0,0 +1,9 @@ +procedure move(integer n, sequence From, sequence To, sequence Via) + if n>0 then + move(n-1, From, Via, To) + printf(1, "Move disk %d from the %s pole to the %s pole\n", {n, From, To}) + move(n-1, Via, To, From) + end if +end procedure + +move(3, "left", "right", "middle") diff --git a/Task/Towers-of-Hanoi/FALSE/towers-of-hanoi.false b/Task/Towers-of-Hanoi/FALSE/towers-of-hanoi.false new file mode 100644 index 0000000000..22e769f004 --- /dev/null +++ b/Task/Towers-of-Hanoi/FALSE/towers-of-hanoi.false @@ -0,0 +1,4 @@ +["Move disk from "$!\" to "$!\" +"]p: { to from } +[n;0>[n;1-n: @\ h;! @\ p;! \@ h;! \@ n;1+n:]?]h: { via to from } +4n:["right"]["middle"]["left"]h;!%%% diff --git a/Task/Towers-of-Hanoi/Factor/towers-of-hanoi.factor b/Task/Towers-of-Hanoi/Factor/towers-of-hanoi.factor new file mode 100644 index 0000000000..beaeb52a56 --- /dev/null +++ b/Task/Towers-of-Hanoi/Factor/towers-of-hanoi.factor @@ -0,0 +1,11 @@ +USING: formatting kernel locals math ; +IN: rosettacode.hanoi + +: move ( from to -- ) + "%d->%d\n" printf ; +:: hanoi ( n from to other -- ) + n 0 > [ + n 1 - from other to hanoi + from to move + n 1 - other to from hanoi + ] when ; diff --git a/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-1.fth b/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-1.fth new file mode 100644 index 0000000000..2b3df8c2bc --- /dev/null +++ b/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-1.fth @@ -0,0 +1,13 @@ +CREATE peg1 ," left " +CREATE peg2 ," middle " +CREATE peg3 ," right " + +: .$ COUNT TYPE ; +: MOVE-DISK + LOCALS| via to from n | + n 1 = + IF CR ." Move disk from " from .$ ." to " to .$ + ELSE n 1- from via to RECURSE + 1 from to via RECURSE + n 1- via to from RECURSE + THEN ; diff --git a/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-2.fth b/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-2.fth new file mode 100644 index 0000000000..672f87e458 --- /dev/null +++ b/Task/Towers-of-Hanoi/Forth/towers-of-hanoi-2.fth @@ -0,0 +1,14 @@ +: left ." left" ; +: right ." right" ; +: middle ." middle" ; + +: move-disk ( v t f n -- v t f ) + dup 0= if drop exit then + 1- >R + rot swap R@ ( t v f n-1 ) recurse + rot swap + 2dup cr ." Move disk from " execute ." to " execute + swap rot R> ( f t v n-1 ) recurse + swap rot ; +: hanoi ( n -- ) + 1 max >R ['] right ['] middle ['] left R> move-disk drop drop drop ; diff --git a/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi.f b/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi.f new file mode 100644 index 0000000000..36248ec865 --- /dev/null +++ b/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi.f @@ -0,0 +1,19 @@ +PROGRAM TOWER + + CALL Move(4, 1, 2, 3) + +CONTAINS + + RECURSIVE SUBROUTINE Move(ndisks, from, to, via) + INTEGER, INTENT (IN) :: ndisks, from, to, via + + IF (ndisks == 1) THEN + WRITE(*, "(A,I1,A,I1)") "Move disk from pole ", from, " to pole ", to + ELSE + CALL Move(ndisks-1, from, via, to) + CALL Move(1, from, to, via) + CALL Move(ndisks-1, via, to, from) + END IF + END SUBROUTINE Move + +END PROGRAM TOWER diff --git a/Task/Towers-of-Hanoi/GAP/towers-of-hanoi.gap b/Task/Towers-of-Hanoi/GAP/towers-of-hanoi.gap new file mode 100644 index 0000000000..5c429d01f5 --- /dev/null +++ b/Task/Towers-of-Hanoi/GAP/towers-of-hanoi.gap @@ -0,0 +1,30 @@ +Hanoi := function(n) + local move; + move := function(n, a, b, c) # from, through, to + if n = 1 then + Print(a, " -> ", c, "\n"); + else + move(n - 1, a, c, b); + move(1, a, b, c); + move(n - 1, b, a, c); + fi; + end; + move(n, "A", "B", "C"); +end; + +Hanoi(1); +# A -> C + +Hanoi(2); +# A -> B +# A -> C +# B -> C + +Hanoi(3); +# A -> C +# A -> B +# C -> B +# A -> C +# B -> A +# B -> C +# A -> C diff --git a/Task/Towers-of-Hanoi/Go/towers-of-hanoi-1.go b/Task/Towers-of-Hanoi/Go/towers-of-hanoi-1.go new file mode 100644 index 0000000000..6334b60327 --- /dev/null +++ b/Task/Towers-of-Hanoi/Go/towers-of-hanoi-1.go @@ -0,0 +1,42 @@ +package main + +import "fmt" + +// a towers of hanoi solver just has one method, play +type solver interface { + play(int) +} + +func main() { + var t solver // declare variable of solver type + t = new(towers) // type towers must satisfy solver interface + t.play(4) +} + +// towers is example of type satisfying solver interface +type towers struct { + // an empty struct. some other solver might fill this with some + // data representation, maybe for algorithm validation, or maybe for + // visualization. +} + +// play is sole method required to implement solver type +func (t *towers) play(n int) { + // drive recursive solution, per task description + t.moveN(n, 1, 2, 3) +} + +// recursive algorithm +func (t *towers) moveN(n, from, to, via int) { + if n > 0 { + t.moveN(n-1, from, via, to) + t.move1(from, to) + t.moveN(n-1, via, to, from) + } +} + +// example function prints actions to screen. +// enhance with validation or visualization as needed. +func (t *towers) move1(from, to int) { + fmt.Println("move disk from rod", from, "to rod", to) +} diff --git a/Task/Towers-of-Hanoi/Go/towers-of-hanoi-2.go b/Task/Towers-of-Hanoi/Go/towers-of-hanoi-2.go new file mode 100644 index 0000000000..86bc3863f7 --- /dev/null +++ b/Task/Towers-of-Hanoi/Go/towers-of-hanoi-2.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + move(3, "A", "B", "C") +} + +func move(n uint64, a, b, c string) { + if n > 0 { + move(n-1, a, c, b) + fmt.Println("Move disk from " + a + " to " + c) + move(n-1, b, a, c) + } +} diff --git a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy new file mode 100644 index 0000000000..09981cad2c --- /dev/null +++ b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-1.groovy @@ -0,0 +1,17 @@ +def tail = { list, n -> def m = list.size(); list[([m - n, 0].max()).. } +def check = { it -> } + +def moveRing = { from, to -> to << from.pop(); report(); check(to) } + +def moveStack +moveStack = { from, to, using = STACK.values().find { !(it.is(from) || it.is(to)) } -> + if (!from) return + def n = from.size() + moveStack(tail(from, n-1), using, to) + moveRing(from, to) + moveStack(tail(using, n-1), to, from) +} diff --git a/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy new file mode 100644 index 0000000000..ab463c0910 --- /dev/null +++ b/Task/Towers-of-Hanoi/Groovy/towers-of-hanoi-2.groovy @@ -0,0 +1,14 @@ +enum Ring { + S('°'), M('o'), L('O'), XL('()'); + private sym + private Ring(sym) { this.sym=sym } + String toString() { sym } +} + +report = { STACK.keySet().each { println "${it}: ${STACK[it]}" }; println() } +check = { to -> assert to == ([] + to).sort().reverse() } + +Ring.values().reverseEach { STACK.A << it } +report() +check(STACK.A) +moveStack(STACK.A, STACK.C) diff --git a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-1.hs b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-1.hs new file mode 100644 index 0000000000..da3c0fac8c --- /dev/null +++ b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-1.hs @@ -0,0 +1,3 @@ +hanoi :: Integer -> a -> a -> a -> [(a, a)] +hanoi 0 _ _ _ = [] +hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a diff --git a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-2.hs b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-2.hs new file mode 100644 index 0000000000..dab3dd1817 --- /dev/null +++ b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-2.hs @@ -0,0 +1,2 @@ +hanoiIO n = mapM_ f $ hanoi n 1 2 3 where + f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y diff --git a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-3.hs b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-3.hs new file mode 100644 index 0000000000..35d6443fba --- /dev/null +++ b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-3.hs @@ -0,0 +1,7 @@ +hanoiM :: Integer -> IO () +hanoiM n = hanoiM' n 1 2 3 where + hanoiM' 0 _ _ _ = return () + hanoiM' n a b c = do + hanoiM' (n-1) a c b + putStrLn $ "Move " ++ show a ++ " to " ++ show b + hanoiM' (n-1) c b a diff --git a/Task/Towers-of-Hanoi/Icon/towers-of-hanoi.icon b/Task/Towers-of-Hanoi/Icon/towers-of-hanoi.icon new file mode 100644 index 0000000000..67a54023f4 --- /dev/null +++ b/Task/Towers-of-Hanoi/Icon/towers-of-hanoi.icon @@ -0,0 +1,23 @@ +procedure main(arglist) +hanoi(arglist[1]) | stop("Usage: hanoi n\n\rWhere n is the number of disks to move.") +end + +#procedure hanoi(n:integer, needle1:1, needle2:2) # unicon shorthand for icon code 1,2,3 below + +procedure hanoi(n, needle1, needle2) #: solve towers of hanoi by moving n disks from needle 1 to needle2 via other +local other + +n := integer(0 < n) | runerr(n,101) # 1 ensure integer (this also ensures it's positive too) +/needle1 := 1 # 2 default +/needle2 := 2 # 3 default + +if n = 1 then + write("Move disk from ", needle1, " to ", needle2) +else { + other := 6 - needle1 - needle2 # clever but somewhat un-iconish way to find other + hanoi(n-1, needle1, other) + write("Move disk from ", needle1, " to ", needle2) + hanoi(n-1, other, needle2) +} +return +end diff --git a/Task/Towers-of-Hanoi/Inform-7/towers-of-hanoi.inf b/Task/Towers-of-Hanoi/Inform-7/towers-of-hanoi.inf new file mode 100644 index 0000000000..3e3513ca61 --- /dev/null +++ b/Task/Towers-of-Hanoi/Inform-7/towers-of-hanoi.inf @@ -0,0 +1,27 @@ +Hanoi is a room. + +A disk is a kind of supporter. + +A post is a kind of supporter. A post is always fixed in place. + +The left post, the middle post, and the right post are posts in Hanoi. + +A disk is a kind of supporter. +The red disk is a disk on the left post. +The orange disk is a disk on the red disk. +The yellow disk is a disk on the orange disk. +The green disk is a disk on the yellow disk. + +Definition: a disk is topmost if nothing is on it. + +When play begins: + move 4 disks from the left post to the right post via the middle post. + +To move (N - number) disk/disks from (FP - post) to (TP - post) via (VP - post): + if N > 0: + move N - 1 disks from FP to VP via TP; + say "Moving a disk from [FP] to [TP]..."; + let D be a random topmost disk enclosed by FP; + if a topmost disk (called TD) is enclosed by TP, now D is on TD; + otherwise now D is on TP; + move N - 1 disks from VP to TP via FP. diff --git a/Task/Towers-of-Hanoi/Io/towers-of-hanoi.io b/Task/Towers-of-Hanoi/Io/towers-of-hanoi.io new file mode 100644 index 0000000000..7dcfe4e9d8 --- /dev/null +++ b/Task/Towers-of-Hanoi/Io/towers-of-hanoi.io @@ -0,0 +1,9 @@ +hanoi := method(n, from, to, via, + if (n == 1) then ( + writeln("Move from ", from, " to ", to) + ) else ( + hanoi(n - 1, from, via, to ) + hanoi(1 , from, to , via ) + hanoi(n - 1, via , to , from) + ) +) diff --git a/Task/Towers-of-Hanoi/Ioke/towers-of-hanoi.ioke b/Task/Towers-of-Hanoi/Ioke/towers-of-hanoi.ioke new file mode 100644 index 0000000000..56bb943956 --- /dev/null +++ b/Task/Towers-of-Hanoi/Ioke/towers-of-hanoi.ioke @@ -0,0 +1,13 @@ + = method(n, f, u, t, + if(n < 2, + "#{f} --> #{t}" println, + + H(n - 1, f, t, u) + "#{f} --> #{t}" println + H(n - 1, u, f, t) + ) +) + +hanoi = method(n, + H(n, 1, 2, 3) +) diff --git a/Task/Towers-of-Hanoi/J/towers-of-hanoi-1.j b/Task/Towers-of-Hanoi/J/towers-of-hanoi-1.j new file mode 100644 index 0000000000..db31b094a7 --- /dev/null +++ b/Task/Towers-of-Hanoi/J/towers-of-hanoi-1.j @@ -0,0 +1 @@ +H =: i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * NB. tacit using anonymous recursion diff --git a/Task/Towers-of-Hanoi/J/towers-of-hanoi-2.j b/Task/Towers-of-Hanoi/J/towers-of-hanoi-2.j new file mode 100644 index 0000000000..6bcdcc74ff --- /dev/null +++ b/Task/Towers-of-Hanoi/J/towers-of-hanoi-2.j @@ -0,0 +1,8 @@ + H 3 +0 2 +0 1 +2 1 +0 2 +1 2 +1 0 +2 0 diff --git a/Task/Towers-of-Hanoi/J/towers-of-hanoi-3.j b/Task/Towers-of-Hanoi/J/towers-of-hanoi-3.j new file mode 100644 index 0000000000..51590fecfd --- /dev/null +++ b/Task/Towers-of-Hanoi/J/towers-of-hanoi-3.j @@ -0,0 +1,7 @@ +H1=: monad define NB. explicit equivalent of H + if. y do. + ({&0 2 1 , 0 2 , {&1 0 2) H1 y-1 + else. + i.0 2 + end. +) diff --git a/Task/Towers-of-Hanoi/J/towers-of-hanoi-4.j b/Task/Towers-of-Hanoi/J/towers-of-hanoi-4.j new file mode 100644 index 0000000000..ec7835c266 --- /dev/null +++ b/Task/Towers-of-Hanoi/J/towers-of-hanoi-4.j @@ -0,0 +1,5 @@ +hanoi=: monad define + moves=. H y + disks=. $~` ((],[,]) $:@<:) @.* y + ('move disk ';' from peg ';' to peg ');@,."1 ":&.>disks,.1+moves +) diff --git a/Task/Towers-of-Hanoi/J/towers-of-hanoi-5.j b/Task/Towers-of-Hanoi/J/towers-of-hanoi-5.j new file mode 100644 index 0000000000..6cadb7fee5 --- /dev/null +++ b/Task/Towers-of-Hanoi/J/towers-of-hanoi-5.j @@ -0,0 +1,8 @@ + hanoi 3 +move disk 1 from peg 1 to peg 3 +move disk 2 from peg 1 to peg 2 +move disk 1 from peg 3 to peg 2 +move disk 3 from peg 1 to peg 3 +move disk 1 from peg 2 to peg 1 +move disk 2 from peg 2 to peg 3 +move disk 1 from peg 1 to peg 3 diff --git a/Task/Towers-of-Hanoi/Java/towers-of-hanoi.java b/Task/Towers-of-Hanoi/Java/towers-of-hanoi.java new file mode 100644 index 0000000000..671c2bf3c6 --- /dev/null +++ b/Task/Towers-of-Hanoi/Java/towers-of-hanoi.java @@ -0,0 +1,9 @@ +public void move(int n, int from, int to, int via) { + if (n == 1) { + System.out.println("Move disk from pole " + from + " to pole " + to); + } else { + move(n - 1, from, via, to); + move(1, from, to, via); + move(n - 1, via, to, from); + } +} diff --git a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi.js b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi.js new file mode 100644 index 0000000000..e9a87f53fc --- /dev/null +++ b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi.js @@ -0,0 +1,8 @@ +function move(n, a, b, c) { + if (n > 0) { + move(n-1, a, c, b); + console.log("Move disk from " + a + " to " + c); + move(n-1, b, a, c); + } +} +move(4, "A", "B", "C"); diff --git a/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-1.joy b/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-1.joy new file mode 100644 index 0000000000..4bdb6f8dd4 --- /dev/null +++ b/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-1.joy @@ -0,0 +1,7 @@ +DEFINE hanoi == [[rolldown] infra] dip + [ [ [null] [pop pop] ] + [ [dup2 [[rotate] infra] dip pred] + [ [dup rest put] dip + [[swap] infra] dip pred ] + [] ] ] + condnestrec. diff --git a/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-2.joy b/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-2.joy new file mode 100644 index 0000000000..42acb96bde --- /dev/null +++ b/Task/Towers-of-Hanoi/Joy/towers-of-hanoi-2.joy @@ -0,0 +1 @@ +[source destination temp] 5 hanoi. diff --git a/Task/Towers-of-Hanoi/K/towers-of-hanoi-1.k b/Task/Towers-of-Hanoi/K/towers-of-hanoi-1.k new file mode 100644 index 0000000000..28eba8b5d9 --- /dev/null +++ b/Task/Towers-of-Hanoi/K/towers-of-hanoi-1.k @@ -0,0 +1,17 @@ + h:{[n;a;b;c]if[n>0;_f[n-1;a;c;b];`0:,//$($n,":",$a,"->",$b,"\n");_f[n-1;c;b;a]]} + h[4;1;2;3] +1:1->3 +2:1->2 +1:3->2 +3:1->3 +1:2->1 +2:2->3 +1:1->3 +4:1->2 +1:3->2 +2:3->1 +1:2->1 +3:3->2 +1:1->3 +2:1->2 +1:3->2 diff --git a/Task/Towers-of-Hanoi/K/towers-of-hanoi-2.k b/Task/Towers-of-Hanoi/K/towers-of-hanoi-2.k new file mode 100644 index 0000000000..db3b33d980 --- /dev/null +++ b/Task/Towers-of-Hanoi/K/towers-of-hanoi-2.k @@ -0,0 +1,5 @@ + s:();{[n;a;b;c]if[n>0;_f[n-1;a;c;b];s,:n;_f[n-1;c;b;a]]}[4;1;2;3];s +1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 + + 1_{*1+&|x}'a:(2_vs!_2^4) +1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 diff --git a/Task/Towers-of-Hanoi/Liberty-BASIC/towers-of-hanoi.liberty b/Task/Towers-of-Hanoi/Liberty-BASIC/towers-of-hanoi.liberty new file mode 100644 index 0000000000..95434f64e9 --- /dev/null +++ b/Task/Towers-of-Hanoi/Liberty-BASIC/towers-of-hanoi.liberty @@ -0,0 +1,19 @@ + source$ ="A" + via$ ="B" + target$ ="C" + + call hanoi 4, source$, target$, via$ ' ie call procedure to move legally 4 disks from peg A to peg C via peg B + + wait + + sub hanoi numDisks, source$, target$, via$ + if numDisks =0 then + exit sub + else + call hanoi numDisks -1, source$, via$, target$ + print " Move disk "; numDisks; " from peg "; source$; " to peg "; target$ + call hanoi numDisks -1, via$, target$, source$ + end if + end sub + + end diff --git a/Task/Towers-of-Hanoi/Logo/towers-of-hanoi.logo b/Task/Towers-of-Hanoi/Logo/towers-of-hanoi.logo new file mode 100644 index 0000000000..a89c2493c4 --- /dev/null +++ b/Task/Towers-of-Hanoi/Logo/towers-of-hanoi.logo @@ -0,0 +1,7 @@ +to move :n :from :to :via + if :n = 0 [stop] + move :n-1 :from :via :to + (print [Move disk from] :from [to] :to) + move :n-1 :via :to :from +end +move 4 "left "middle "right diff --git a/Task/Towers-of-Hanoi/Logtalk/towers-of-hanoi.logtalk b/Task/Towers-of-Hanoi/Logtalk/towers-of-hanoi.logtalk new file mode 100644 index 0000000000..f6fec6b1b2 --- /dev/null +++ b/Task/Towers-of-Hanoi/Logtalk/towers-of-hanoi.logtalk @@ -0,0 +1,29 @@ +:- object(hanoi). + + :- public(run/1). + :- mode(run(+integer), one). + :- info(run/1, [ + comment is 'Solves the towers of Hanoi problem for the specified number of disks.', + argnames is ['Disks']]). + + run(Disks) :- + move(Disks, left, middle, right). + + move(1, Left, _, Right):- + !, + report(Left, Right). + move(Disks, Left, Aux, Right):- + Disks2 is Disks - 1, + move(Disks2, Left, Right, Aux), + report(Left, Right), + move(Disks2, Aux, Left, Right). + + report(Pole1, Pole2):- + write('Move a disk from '), + writeq(Pole1), + write(' to '), + writeq(Pole2), + write('.'), + nl. + +:- end_object. diff --git a/Task/Towers-of-Hanoi/Lua/towers-of-hanoi.lua b/Task/Towers-of-Hanoi/Lua/towers-of-hanoi.lua new file mode 100644 index 0000000000..5d14e88524 --- /dev/null +++ b/Task/Towers-of-Hanoi/Lua/towers-of-hanoi.lua @@ -0,0 +1,9 @@ +function move(n, src, dst, via) + if n > 0 then + move(n - 1, src, via, dst) + print(src, 'to', dst) + move(n - 1, via, dst, src) + end +end + +move(4, 1, 2, 3) diff --git a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m new file mode 100644 index 0000000000..14a03bd3b8 --- /dev/null +++ b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-1.m @@ -0,0 +1,7 @@ +function towerOfHanoi(n,A,C,B) + if (n~=0) + towerOfHanoi(n-1,A,B,C); + disp(sprintf('Move plate %d from tower %d to tower %d',[n A C])); + towerOfHanoi(n-1,B,C,A); + end +end diff --git a/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m new file mode 100644 index 0000000000..f309d71f6f --- /dev/null +++ b/Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi-2.m @@ -0,0 +1,8 @@ +towerOfHanoi(3,1,3,2) +Move plate 1 from tower 1 to tower 3 +Move plate 2 from tower 1 to tower 2 +Move plate 1 from tower 3 to tower 2 +Move plate 3 from tower 1 to tower 3 +Move plate 1 from tower 2 to tower 1 +Move plate 2 from tower 2 to tower 3 +Move plate 1 from tower 1 to tower 3 diff --git a/Task/Towers-of-Hanoi/Mathematica/towers-of-hanoi.math b/Task/Towers-of-Hanoi/Mathematica/towers-of-hanoi.math new file mode 100644 index 0000000000..8366813aa7 --- /dev/null +++ b/Task/Towers-of-Hanoi/Mathematica/towers-of-hanoi.math @@ -0,0 +1,5 @@ +Hanoi[0, from_, to_, via_] := Null +Hanoi[n_Integer, from_, to_, via_] := + (Hanoi[n-1, from, via, to]; + Print["Move disk from pole ", from, " to ", to, "."]; + Hanoi[n-1, via, from, to]) diff --git a/Task/Towers-of-Hanoi/Modula-3/towers-of-hanoi.mod3 b/Task/Towers-of-Hanoi/Modula-3/towers-of-hanoi.mod3 new file mode 100644 index 0000000000..52e344b992 --- /dev/null +++ b/Task/Towers-of-Hanoi/Modula-3/towers-of-hanoi.mod3 @@ -0,0 +1,17 @@ +MODULE Hanoi EXPORTS Main; + +FROM IO IMPORT Put; +FROM Fmt IMPORT Int; + +PROCEDURE doHanoi(n, from, to, using: INTEGER) = + BEGIN + IF n > 0 THEN + doHanoi(n - 1, from, using, to); + Put("move " & Int(from) & " --> " & Int(to) & "\n"); + doHanoi(n - 1, using, to, from); + END; + END doHanoi; + +BEGIN + doHanoi(4, 1, 2, 3); +END Hanoi. diff --git a/Task/Towers-of-Hanoi/Nemerle/towers-of-hanoi.nemerle b/Task/Towers-of-Hanoi/Nemerle/towers-of-hanoi.nemerle new file mode 100644 index 0000000000..5b2db9c10a --- /dev/null +++ b/Task/Towers-of-Hanoi/Nemerle/towers-of-hanoi.nemerle @@ -0,0 +1,20 @@ +using System; +using System.Console; + +module Towers +{ + Hanoi(n : int, from = 1, to = 3, via = 2) : void + { + when (n > 0) + { + Hanoi(n - 1, from, via, to); + WriteLine("Move disk from peg {0} to peg {1}", from, to); + Hanoi(n - 1, via, to, from); + } + } + + Main() : void + { + Hanoi(4) + } +} diff --git a/Task/Towers-of-Hanoi/NetRexx/towers-of-hanoi.netrexx b/Task/Towers-of-Hanoi/NetRexx/towers-of-hanoi.netrexx new file mode 100644 index 0000000000..cbafbe98cf --- /dev/null +++ b/Task/Towers-of-Hanoi/NetRexx/towers-of-hanoi.netrexx @@ -0,0 +1,27 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg discs . + if discs = '', discs < 1 then discs = 4 + say 'Minimum moves to solution:' 2 ** discs - 1 + moves = move(discs) + say 'Solved in' moves 'moves.' + return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method move(discs = int 4, towerFrom = int 1, towerTo = int 2, towerVia = int 3, moves = int 0) public static + if discs == 1 then do + moves = moves + 1 + say 'Move disc from peg' towerFrom 'to peg' towerTo '- Move No:' Rexx(moves).right(5) + end + else do + moves = move(discs - 1, towerFrom, towerVia, towerTo, moves) + moves = move(1, towerFrom, towerTo, towerVia, moves) + moves = move(discs - 1, towerVia, towerTo, towerFrom, moves) + end + return moves diff --git a/Task/Towers-of-Hanoi/NewLISP/towers-of-hanoi.newlisp b/Task/Towers-of-Hanoi/NewLISP/towers-of-hanoi.newlisp new file mode 100644 index 0000000000..016a1258bf --- /dev/null +++ b/Task/Towers-of-Hanoi/NewLISP/towers-of-hanoi.newlisp @@ -0,0 +1,7 @@ +(define (move n from to via) + (if (> n 0) + (move (- n 1) from via to + (print "move disk from pole " from " to pole " to "\n") + (move (- n 1) via to from)))) + +(move 4 1 2 3) diff --git a/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod b/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod new file mode 100644 index 0000000000..d80d015f79 --- /dev/null +++ b/Task/Towers-of-Hanoi/Nimrod/towers-of-hanoi.nimrod @@ -0,0 +1,7 @@ +proc hanoi(disks: int, fromTower: string, toTower: string, viaTower: string) = + if disks != 0: + hanoi(disks - 1, fromTower, viaTower, toTower) + echo("Move disk ", disks, " from ", fromTower, " to ", toTower) + hanoi(disks - 1, viaTower, toTower, fromTower) + +hanoi(4, "1", "2", "3") diff --git a/Task/Towers-of-Hanoi/OCaml/towers-of-hanoi.ocaml b/Task/Towers-of-Hanoi/OCaml/towers-of-hanoi.ocaml new file mode 100644 index 0000000000..33d93590fd --- /dev/null +++ b/Task/Towers-of-Hanoi/OCaml/towers-of-hanoi.ocaml @@ -0,0 +1,9 @@ +let rec hanoi n a b c = + if n <> 0 then begin + hanoi (pred n) a c b; + Printf.printf "Move disk from pole %d to pole %d\n" a b; + hanoi (pred n) c b a + end + +let () = + hanoi 4 1 2 3 diff --git a/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-1.m b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-1.m new file mode 100644 index 0000000000..fe0df61b96 --- /dev/null +++ b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-1.m @@ -0,0 +1,12 @@ +#import + +@interface TowersOfHanoi: NSObject { + int pegFrom; + int pegTo; + int pegVia; + int numDisks; +} + +-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks; +-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks; +@end diff --git a/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-2.m b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-2.m new file mode 100644 index 0000000000..fff45dd661 --- /dev/null +++ b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-2.m @@ -0,0 +1,21 @@ +#import "TowersOfHanoi.h" +@implementation TowersOfHanoi + +-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks { + pegFrom = from; + pegTo = to; + pegVia = via; + numDisks = disks; +} + +-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks { + if (disks == 1) { + printf("Move disk from pole %i to pole %i\n", from, to); + } else { + [self movePegFrom: from andMovePegTo: via andMovePegVia: to andWithNumDisks: disks-1]; + [self movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: 1]; + [self movePegFrom: via andMovePegTo: to andMovePegVia: from andWithNumDisks: disks-1]; + } +} + +@end diff --git a/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m new file mode 100644 index 0000000000..8191089970 --- /dev/null +++ b/Task/Towers-of-Hanoi/Objective-C/towers-of-hanoi-3.m @@ -0,0 +1,19 @@ +#import +#import "TowersOfHanoi.h" + +int main( int argc, const char *argv[] ) { + TowersOfHanoi *tower = [[TowersOfHanoi alloc] init]; + + int from = 1; + int to = 3; + int via = 2; + int disks = 3; + + [tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks]; + + [tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks]; + + [tower release]; + + return 0; +} diff --git a/Task/Towers-of-Hanoi/Octave/towers-of-hanoi.octave b/Task/Towers-of-Hanoi/Octave/towers-of-hanoi.octave new file mode 100644 index 0000000000..4019f023c3 --- /dev/null +++ b/Task/Towers-of-Hanoi/Octave/towers-of-hanoi.octave @@ -0,0 +1,11 @@ +function hanoimove(ndisks, from, to, via) + if ( ndisks == 1 ) + printf("Move disk from pole %d to pole %d\n", from, to); + else + hanoimove(ndisks-1, from, via, to); + hanoimove(1, from, to, via); + hanoimove(ndisks-1, via, to, from); + endif +endfunction + +hanoimove(4, 1, 2, 3); diff --git a/Task/Towers-of-Hanoi/Oz/towers-of-hanoi.oz b/Task/Towers-of-Hanoi/Oz/towers-of-hanoi.oz new file mode 100644 index 0000000000..132c10a698 --- /dev/null +++ b/Task/Towers-of-Hanoi/Oz/towers-of-hanoi.oz @@ -0,0 +1,10 @@ +declare + proc {TowersOfHanoi N From To Via} + if N > 0 then + {TowersOfHanoi N-1 From Via To} + {System.showInfo "Move from "#From#" to "#To} + {TowersOfHanoi N-1 Via To From} + end + end +in + {TowersOfHanoi 4 left middle right} diff --git a/Task/Towers-of-Hanoi/PHP/towers-of-hanoi.php b/Task/Towers-of-Hanoi/PHP/towers-of-hanoi.php new file mode 100644 index 0000000000..3ee4782204 --- /dev/null +++ b/Task/Towers-of-Hanoi/PHP/towers-of-hanoi.php @@ -0,0 +1,9 @@ +function move($n,$from,$to,$via) { + if ($n === 1) { + print("Move disk from pole $from to pole $to"); + } else { + move($n-1,$from,$via,$to); + move(1,$from,$to,$via); + move($n-1,$via,$to,$from); + } +} diff --git a/Task/Towers-of-Hanoi/PL-I/towers-of-hanoi.pli b/Task/Towers-of-Hanoi/PL-I/towers-of-hanoi.pli new file mode 100644 index 0000000000..1de6d19116 --- /dev/null +++ b/Task/Towers-of-Hanoi/PL-I/towers-of-hanoi.pli @@ -0,0 +1,19 @@ +tower: proc options (main); + + call Move (4,1,2,3); + +Move: procedure (ndiscs, from, to, via) recursive; + declare (ndiscs, from, to, via) fixed binary; + + if ndiscs = 1 then + put skip edit ('Move disc from pole ', trim(from), ' to pole ', + trim(to) ) (a); + else + do; + call Move (ndiscs-1, from, via, to); + call Move (1, from, to, via); + call Move (ndiscs-1, via, to, from); + end; +end Move; + +end tower; diff --git a/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-1.pascal b/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-1.pascal new file mode 100644 index 0000000000..9447723e16 --- /dev/null +++ b/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-1.pascal @@ -0,0 +1,18 @@ +program Hanoi; +type + TPole = (tpLeft, tpCenter, tpRight); +const + strPole:array[TPole] of string[6]=('left','center','right'); + + procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole); + begin + if Ndisks >0 then begin + MoveStack(Ndisks - 1, Origin,Auxiliary, Destination ); + Writeln('Move disk ',Ndisks ,' from ',strPole[Origin],' to ',strPole[Destination]); + MoveStack(Ndisks - 1, Auxiliary, Destination, origin); + end; + end; + +begin + MoveStack(4,tpLeft,tpCenter,tpRight); +end. diff --git a/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-2.pascal b/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-2.pascal new file mode 100644 index 0000000000..b1265578f2 --- /dev/null +++ b/Task/Towers-of-Hanoi/Pascal/towers-of-hanoi-2.pascal @@ -0,0 +1,25 @@ +program Hanoi; +type + TPole = (tpLeft, tpCenter, tpRight); +const + strPole:array[TPole] of string[6]=('left','center','right'); + + procedure MoveOneDisk(const DiskNum:integer; const Origin,Destination:TPole); + begin + Writeln('Move disk ',DiskNum,' from ',strPole[Origin],' to ',strPole[Destination]); + end; + + procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole); + begin + if Ndisks =1 then + MoveOneDisk(1,origin,Destination) + else begin + MoveStack(Ndisks - 1, Origin,Auxiliary, Destination ); + MoveOneDisk(Ndisks,origin,Destination); + MoveStack(Ndisks - 1, Auxiliary, Destination, origin); + end; + end; + +begin + MoveStack(4,tpLeft,tpCenter,tpRight); +end. diff --git a/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 b/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 new file mode 100644 index 0000000000..e88e1702ec --- /dev/null +++ b/Task/Towers-of-Hanoi/Perl-6/towers-of-hanoi.pl6 @@ -0,0 +1,8 @@ +subset Peg of Int where * == 1|2|3; + +multi hanoi (0, Peg $a, Peg $b, Peg $c) { } +multi hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) { + hanoi $n - 1, $a, $c, $b; + say "Move $a to $b."; + hanoi $n - 1, $c, $b, $a; +} diff --git a/Task/Towers-of-Hanoi/Perl/towers-of-hanoi.pl b/Task/Towers-of-Hanoi/Perl/towers-of-hanoi.pl new file mode 100644 index 0000000000..db3fcf7108 --- /dev/null +++ b/Task/Towers-of-Hanoi/Perl/towers-of-hanoi.pl @@ -0,0 +1,11 @@ +sub hanoi { + my ($n, $from, $to, $via) = (@_, 1, 2, 3); + + if ($n == 1) { + print "Move disk from pole $from to pole $to.\n"; + } else { + hanoi($n - 1, $from, $via, $to); + hanoi(1, $from, $to, $via); + hanoi($n - 1, $via, $to, $from); + }; +}; diff --git a/Task/Towers-of-Hanoi/PicoLisp/towers-of-hanoi.l b/Task/Towers-of-Hanoi/PicoLisp/towers-of-hanoi.l new file mode 100644 index 0000000000..b2c08837d3 --- /dev/null +++ b/Task/Towers-of-Hanoi/PicoLisp/towers-of-hanoi.l @@ -0,0 +1,5 @@ +(de move (N A B C) # Use: (move 3 'left 'center 'right) + (unless (=0 N) + (move (dec N) A C B) + (println 'Move 'disk 'from A 'to B) + (move (dec N) C B A) ) ) diff --git a/Task/Towers-of-Hanoi/Pop11/towers-of-hanoi.pop11 b/Task/Towers-of-Hanoi/Pop11/towers-of-hanoi.pop11 new file mode 100644 index 0000000000..ef73230475 --- /dev/null +++ b/Task/Towers-of-Hanoi/Pop11/towers-of-hanoi.pop11 @@ -0,0 +1,9 @@ +define hanoi(n, src, dst, via); +if n > 0 then + hanoi(n - 1, src, via, dst); + 'Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.' => + hanoi(n - 1, via, dst, src); +endif; +enddefine; + +hanoi(4, "left", "middle", "right"); diff --git a/Task/Towers-of-Hanoi/PostScript/towers-of-hanoi.ps b/Task/Towers-of-Hanoi/PostScript/towers-of-hanoi.ps new file mode 100644 index 0000000000..59e7ae4dda --- /dev/null +++ b/Task/Towers-of-Hanoi/PostScript/towers-of-hanoi.ps @@ -0,0 +1,48 @@ +%!PS-Adobe-3.0 +%%BoundingBox: 0 0 300 300 + +/plate { + exch 100 mul 50 add exch th mul 10 add moveto + dup s mul neg 2 div 0 rmoveto + dup s mul 0 rlineto + 0 th rlineto + s neg mul 0 rlineto + closepath gsave .5 setgray fill grestore 0 setgray stroke +} def + +/drawtower { + 0 1 2 { /x exch def /y 0 def + tower x get { + dup 0 gt { x y plate /y y 1 add def } {pop} ifelse + } forall + } for showpage +} def + +/apop { [ exch aload pop /last exch def ] last } def +/apush{ [ 3 1 roll aload pop counttomark -1 roll ] } def + +/hanoi { + 0 dict begin /from /mid /to /h 5 -1 2 { -1 roll def } for + h 1 eq { + tower from get apop tower to get apush + tower to 3 -1 roll put + tower from 3 -1 roll put + drawtower + } { + /h h 1 sub def + from to mid h hanoi + from mid to 1 hanoi + mid from to h hanoi + } ifelse + end +} def + + +/n 12 def +/s 90 n div def +/th 180 n div def +/tower [ [n 1 add -1 2 { } for ] [] [] ] def + +drawtower 0 1 2 n hanoi + +%%EOF diff --git a/Task/Towers-of-Hanoi/Prolog/towers-of-hanoi.pro b/Task/Towers-of-Hanoi/Prolog/towers-of-hanoi.pro new file mode 100644 index 0000000000..9a0e9e0f18 --- /dev/null +++ b/Task/Towers-of-Hanoi/Prolog/towers-of-hanoi.pro @@ -0,0 +1,10 @@ +hanoi(N) :- move(N,left,center,right). + +move(0,_,_,_) :- !. +move(N,A,B,C) :- + M is N-1, + move(M,A,C,B), + inform(A,B), + move(M,C,B,A). + +inform(X,Y) :- write([move,a,disk,from,the,X,pole,to,Y,pole]), nl. diff --git a/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-1.purebasic b/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-1.purebasic new file mode 100644 index 0000000000..02ec8a1a68 --- /dev/null +++ b/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-1.purebasic @@ -0,0 +1,7 @@ +Procedure Hanoi(n, A.s, C.s, B.s) + If n + Hanoi(n-1, A, B, C) + PrintN("Move the plate from "+A+" to "+C) + Hanoi(n-1, B, C, A) + EndIf +EndProcedure diff --git a/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-2.purebasic b/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-2.purebasic new file mode 100644 index 0000000000..e39dd4b5d7 --- /dev/null +++ b/Task/Towers-of-Hanoi/PureBasic/towers-of-hanoi-2.purebasic @@ -0,0 +1,14 @@ +Procedure Hanoi(n, A.s, C.s, B.s) + If n + Hanoi(n-1, A, B, C) + PrintN("Move the plate from "+A+" to "+C) + Hanoi(n-1, B, C, A) + EndIf +EndProcedure + +If OpenConsole() + Define n=3 + PrintN("Moving "+Str(n)+" pegs."+#CRLF$) + Hanoi(n,"Left Peg","Middle Peg","Right Peg") + PrintN(#CRLF$+"Press ENTER to exit."): Input() +EndIf diff --git a/Task/Towers-of-Hanoi/Python/towers-of-hanoi.py b/Task/Towers-of-Hanoi/Python/towers-of-hanoi.py new file mode 100644 index 0000000000..66435f737a --- /dev/null +++ b/Task/Towers-of-Hanoi/Python/towers-of-hanoi.py @@ -0,0 +1,7 @@ +def hanoi(ndisks, startPeg=1, endPeg=3): + if ndisks: + hanoi(ndisks-1, startPeg, 6-startPeg-endPeg) + print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg) + hanoi(ndisks-1, 6-startPeg-endPeg, endPeg) + +hanoi(ndisks=4) diff --git a/Task/Towers-of-Hanoi/R/towers-of-hanoi.r b/Task/Towers-of-Hanoi/R/towers-of-hanoi.r new file mode 100644 index 0000000000..bf9a086ea0 --- /dev/null +++ b/Task/Towers-of-Hanoi/R/towers-of-hanoi.r @@ -0,0 +1,11 @@ +hanoimove <- function(ndisks, from, to, via) { + if ( ndisks == 1 ) + cat("move disk from", from, "to", to, "\n") + else { + hanoimove(ndisks-1, from, via, to) + hanoimove(1, from, to, via) + hanoimove(ndisks-1, via, to, from) + } +} + +hanoimove(4,1,2,3) diff --git a/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol b/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol new file mode 100644 index 0000000000..1af8131a8a --- /dev/null +++ b/Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol @@ -0,0 +1,23 @@ +REBOL [ + Title: "Towers of Hanoi" + Author: oofoe + Date: 2009-12-08 + URL: http://rosettacode.org/wiki/Towers_of_Hanoi +] + +hanoi: func [ + {Begin moving the golden disks from one pole to the next. + Note: when last disk moved, the world will end.} + disks [integer!] "Number of discs on starting pole." + /poles "Name poles." + from to via +][ + if disks = 0 [return] + if not poles [from: 'left to: 'middle via: 'right] + + hanoi/poles disks - 1 from via to + print [from "->" to] + hanoi/poles disks - 1 via to from +] + +hanoi 4 diff --git a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx new file mode 100644 index 0000000000..137c7f2cf8 --- /dev/null +++ b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx @@ -0,0 +1,21 @@ +/*REXX program to show the moves to solve the Tower of Hanoi (3 disks). */ +arg z . /*get possible specification of Z*/ +if z=='' then z=3 /*Not given? Use default 3 towers*/ +move=0 /*number of ring moves so far. */ +call mov 1,3,z /*move top ring, then recurse... */ +say +say 'The minimum number of moves to solve a' z "ring Tower of Hanoi is" 2**z-1 +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────MOV subroutine───────────────────────────*/ +mov: procedure expose move; arg #1, #2, #3 +if #3==1 then call dsk #1, #2 + else do + call mov #1, 6-#1-#2, #3-1 + call mov #1, #2, 1 + call mov 6-#1-#2, #2, #3-1 + end +return +/*─────────────────────────────DSK subroutine───────────────────────────*/ +dsk: move=move+1 +say 'step' right(move,length(moves))": move disk " arg(1) '──►' arg(2) +return diff --git a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx new file mode 100644 index 0000000000..c5fd6c97ab --- /dev/null +++ b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx @@ -0,0 +1,82 @@ +/*REXX program shows pictorial moves to solve Tower of Hanoi (3 disks). */ +arg z .; if z=='' then z=3 +sw=80; wp=sw%3-1; blanks=centre('',wp) +c.1=sw%3%2 +c.2=sw%2-1 +c.3=sw-1-c.1-1 +move=0; totmoves=2**z-1; movek=totmoves; lentot=length(totmoves) +@abc='abcdefghijklmnopqrstuvwxyz' +ebcdic= 'f0'x==0 +if ebcdic then do + bar='bf'x;ar='df'x;boxen='db9f9caf'x;tl='ac'x;tr='bf'x;bl='ab'x;br='bb'x;vert='fa'x;down='9a'x + end + else do + bar='c4'x;ar='10'x;boxen='b0b1b2db'x;tl='da'x;tr='bf'x;bl='c0'x;br='d9'x;vert='b3'x;down='19'x + end +verts=vert || vert +downs=down || down +Tcorners=tl || tr +Bcorners=bl || br +box=left(boxen,1); boxchars=boxen || @abc +bararrow=bar || bar || ar +$.=0; $.1=z; k=z; kk=k+k + + do j=1 for z + @.3.j=blanks; @.2.j=blanks + @.1.j=centre(copies(box,kk),wp) + if z<=length(boxchars) then @.1.j=, + translate(@.1.j,substr(boxchars,kk%2,1),box) + kk=kk-2 + end /*j*/ + +call showtowers; call mov 1,3,z +say +say "The minimum number of moves for a" z 'ring Tower of Hanoi is' totmoves +exit +/*─────────────────────────────MOV subroutine───────────────────────────*/ +mov: if arg(3)==1 then call rng arg(1) arg(2) + else do + call mov arg(1),6-arg(1)-arg(2),arg(3)-1 + call mov arg(1),arg(2),1 + call mov 6-arg(1)-arg(2),arg(2),arg(3)-1 + end +return +/*─────────────────────────────RNG subroutine───────────────────────────*/ +rng: parse arg from dest; move=move+1; pp= +if from==1 then do + pp=overlay(bl,pp,c.1) + pp=overlay(bar,pp,c.1+1,c.dest-c.1-1,bar) + pp=pp || tr + end +if from==3 then do + pp=overlay(br,pp,c.3) + pp=overlay(bar,pp,c.dest+1,c.3-c.dest-1,bar) + pp=overlay(tl,pp,c.dest) + end +if from==2 then do + lpost=min(2,dest) + hpost=max(2,dest) + if dest==1 then do + pp=overlay(tl,pp,c.1) + pp=overlay(bar,pp,c.1+1,c.2-c.1-1,bar) + pp=pp || br + end + if dest==3 then do + pp=overlay(bl,pp,c.2) + pp=overlay(bar,pp,c.2+1,c.3-c.2-1,bar) + pp=pp || tr + end + end +say translate(pp,verts,Bcorners||Tcorners||bar); say overlay(movek,pp,1) +say translate(pp,verts,Tcorners||Bcorners||bar) +say translate(pp,downs,Tcorners||Bcorners||bar) +movek=movek-1 +$.from=$.from-1; $.dest=$.dest+1; _f=$.from+1; _t=$.dest +@.dest._t=@.from._f; @.from._f=blanks +call showtowers +return +/*─────────────────────────────SHOWTOWERS subroutine────────────────────*/ +showtowers: do j=z to 1 by -1 + _p=@.1.j @.2.j @.3.j; if _p\='' then say _p + end /*j*/ +return diff --git a/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt b/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt new file mode 100644 index 0000000000..288fabfb27 --- /dev/null +++ b/Task/Towers-of-Hanoi/Racket/towers-of-hanoi.rkt @@ -0,0 +1,9 @@ +#lang racket + +(define (hanoi n a b c) + (when (> n 0) + (hanoi (- n 1) a c b) + (printf "Move ~a to ~a\n" a b) + (hanoi (- n 1) c b a))) + +(hanoi 4 'left 'middle 'right) diff --git a/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-1.rascal b/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-1.rascal new file mode 100644 index 0000000000..b0300a95e0 --- /dev/null +++ b/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-1.rascal @@ -0,0 +1,7 @@ +public void hanoi(ndisks, startPeg, endPeg){ + if(ndisks>0){ + hanoi(ndisks-1, startPeg, 6 - startPeg - endPeg); + println("Move disk from peg to peg "); + hanoi(ndisks-1, 6 - startPeg - endPeg, endPeg); + } +} diff --git a/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-2.rascal b/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-2.rascal new file mode 100644 index 0000000000..8b7d8d7c0d --- /dev/null +++ b/Task/Towers-of-Hanoi/Rascal/towers-of-hanoi-2.rascal @@ -0,0 +1,17 @@ +rascal>hanoi(4,1,3) +Move disk 1 from peg 1 to peg 2 +Move disk 2 from peg 1 to peg 3 +Move disk 1 from peg 2 to peg 3 +Move disk 3 from peg 1 to peg 2 +Move disk 1 from peg 3 to peg 1 +Move disk 2 from peg 3 to peg 2 +Move disk 1 from peg 1 to peg 2 +Move disk 4 from peg 1 to peg 3 +Move disk 1 from peg 2 to peg 3 +Move disk 2 from peg 2 to peg 1 +Move disk 1 from peg 3 to peg 1 +Move disk 3 from peg 2 to peg 3 +Move disk 1 from peg 1 to peg 2 +Move disk 2 from peg 1 to peg 3 +Move disk 1 from peg 2 to peg 3 +ok diff --git a/Task/Towers-of-Hanoi/Retro/towers-of-hanoi.retro b/Task/Towers-of-Hanoi/Retro/towers-of-hanoi.retro new file mode 100644 index 0000000000..b536660010 --- /dev/null +++ b/Task/Towers-of-Hanoi/Retro/towers-of-hanoi.retro @@ -0,0 +1,15 @@ +4 elements a b c n + +: vars !c !b !a !n ; +: hanoi ( num from to via -- ) + vars + @n 0 <> + [ + @n @a @b @c + @n 1- @a @c @b hanoi + vars + @b @a "\nMove a ring from %d to %d" puts + @n 1- @c @b @a hanoi + ] ifTrue ; + +4 1 3 2 hanoi diff --git a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb new file mode 100644 index 0000000000..9f3f00215a --- /dev/null +++ b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-1.rb @@ -0,0 +1,10 @@ +def move(num_disks, starting_stick, target_stick, using_stick) + if num_disks == 1 + target_stick << starting_stick.shift + status + else + move(num_disks-1, starting_stick, using_stick, target_stick) + move(1, starting_stick, target_stick, using_stick) + move(num_disks-1, using_stick, target_stick, starting_stick) + end +end diff --git a/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb new file mode 100644 index 0000000000..5bb8c7aad6 --- /dev/null +++ b/Task/Towers-of-Hanoi/Ruby/towers-of-hanoi-2.rb @@ -0,0 +1,28 @@ +require 'pp' +# solve(source, via, target) +# Example: +# solve([5, 4, 3, 2, 1], [], []) +# Note this will also solve randomly placed disks, +# "place all disk in target with legal moves only". +def solve(*towers) + # total number of disks + disks = towers.inject(0){|sum, tower| sum+tower.length} + x=0 # sequence number + pp towers # initial trace + # have we solved the puzzle yet? + while towers.last.length < disks do + x+=1 # assume the next step + from = (x&x-1)%3 + to = ((x|(x-1))+1)%3 + # can we actually take from tower? + if top = towers[from].last + bottom = towers[to].last + # is the move legal? + if !bottom || bottom > top + # ok, do it! + towers[to].push(towers[from].pop) + pp towers # trace + end + end + end +end diff --git a/Task/Towers-of-Hanoi/Run-BASIC/towers-of-hanoi.run b/Task/Towers-of-Hanoi/Run-BASIC/towers-of-hanoi.run new file mode 100644 index 0000000000..4b71a60c5e --- /dev/null +++ b/Task/Towers-of-Hanoi/Run-BASIC/towers-of-hanoi.run @@ -0,0 +1,8 @@ +a = move(4, "1", "2", "3") +function move(n, a$, b$, c$) +if n > 0 then + a = move(n-1, a$, c$, b$) + print "Move disk from " ; a$ ; " to " ; c$ + a = move(n-1, b$, a$, c$) +end if +end function diff --git a/Task/Towers-of-Hanoi/SNOBOL4/towers-of-hanoi.sno b/Task/Towers-of-Hanoi/SNOBOL4/towers-of-hanoi.sno new file mode 100644 index 0000000000..808b84a4e4 --- /dev/null +++ b/Task/Towers-of-Hanoi/SNOBOL4/towers-of-hanoi.sno @@ -0,0 +1,13 @@ +* # Note: count is global + + define('hanoi(n,src,trg,tmp)') :(hanoi_end) +hanoi hanoi = eq(n,0) 1 :s(return) + hanoi(n - 1, src, tmp, trg) + count = count + 1 + output = count ': Move disc from ' src ' to ' trg + hanoi(n - 1, tmp, trg, src) :(return) +hanoi_end + +* # Test with 4 discs + hanoi(4,'A','C','B') +end diff --git a/Task/Towers-of-Hanoi/Sather/towers-of-hanoi.sa b/Task/Towers-of-Hanoi/Sather/towers-of-hanoi.sa new file mode 100644 index 0000000000..f91433f326 --- /dev/null +++ b/Task/Towers-of-Hanoi/Sather/towers-of-hanoi.sa @@ -0,0 +1,16 @@ +class MAIN is + + move(ndisks, from, to, via:INT) is + if ndisks = 1 then + #OUT + "Move disk from pole " + from + " to pole " + to + "\n"; + else + move(ndisks-1, from, via, to); + move(1, from, to, via); + move(ndisks-1, via, to, from); + end; + end; + + main is + move(4, 1, 2, 3); + end; +end; diff --git a/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala new file mode 100644 index 0000000000..4906a7799a --- /dev/null +++ b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-1.scala @@ -0,0 +1,9 @@ +def move(n: int, from: int, to: int, via: int) = { + if (n == 1) { + Console.println("Move disk from pole " + from + " to pole " + to) + } else { + move(n - 1, from, via, to) + move(1, from, to, via) + move(n - 1, via, to, from) + } + } diff --git a/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-2.scala b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-2.scala new file mode 100644 index 0000000000..4249a759bb --- /dev/null +++ b/Task/Towers-of-Hanoi/Scala/towers-of-hanoi-2.scala @@ -0,0 +1,36 @@ +object TowersOfHanoi { + import scala.reflect.Manifest + + def simpleName(m:Manifest[_]):String = { + val name = m.toString + name.substring(name.lastIndexOf('$')+1) + } + + trait Nat + final class _0 extends Nat + final class Succ[Pre<:Nat] extends Nat + + type _1 = Succ[_0] + type _2 = Succ[_1] + type _3 = Succ[_2] + type _4 = Succ[_3] + + case class Move[N<:Nat,A,B,C]() + + implicit def move0[A,B,C](implicit a:Manifest[A],b:Manifest[B]):Move[_0,A,B,C] = { + System.out.println("Move from "+simpleName(a)+" to "+simpleName(b));null + } + + implicit def moveN[P<:Nat,A,B,C](implicit m1:Move[P,A,C,B],m2:Move[_0,A,B,C],m3:Move[P,C,B,A]) + :Move[Succ[P],A,B,C] = null + + def run[N<:Nat,A,B,C](implicit m:Move[N,A,B,C]) = null + + case class Left() + case class Center() + case class Right() + + def main(args:Array[String]){ + run[_2,Left,Right,Center] + } +} diff --git a/Task/Towers-of-Hanoi/Scheme/towers-of-hanoi.ss b/Task/Towers-of-Hanoi/Scheme/towers-of-hanoi.ss new file mode 100644 index 0000000000..f96b1f5fde --- /dev/null +++ b/Task/Towers-of-Hanoi/Scheme/towers-of-hanoi.ss @@ -0,0 +1,12 @@ +(define (hanoi n a b c) + (if (> n 0) + (begin + (hanoi (- n 1) a c b) + (display "Move disk from pole ") + (display a) + (display " to pole ") + (display b) + (newline) + (hanoi (- n 1) c b a)))) + +(hanoi 4 1 2 3) diff --git a/Task/Towers-of-Hanoi/Seed7/towers-of-hanoi.seed7 b/Task/Towers-of-Hanoi/Seed7/towers-of-hanoi.seed7 new file mode 100644 index 0000000000..d747c6434a --- /dev/null +++ b/Task/Towers-of-Hanoi/Seed7/towers-of-hanoi.seed7 @@ -0,0 +1,8 @@ +const proc: hanoi (in integer: disk, in string: source, in string: dest, in string: via) is func + begin + if disk > 0 then + hanoi(pred(disk), source, via, dest); + writeln("Move disk " <& disk <& " from " <& source <& " to " <& dest); + hanoi(pred(disk), via, dest, source); + end if; + end func; diff --git a/Task/Towers-of-Hanoi/TI-83-BASIC/towers-of-hanoi.ti-83 b/Task/Towers-of-Hanoi/TI-83-BASIC/towers-of-hanoi.ti-83 new file mode 100644 index 0000000000..81fe09c10b --- /dev/null +++ b/Task/Towers-of-Hanoi/TI-83-BASIC/towers-of-hanoi.ti-83 @@ -0,0 +1,81 @@ +PROGRAM:TOHSOLVE +0→A +1→B +0→C +0→D +0→M +1→R +While A<1 or A>7 +Input "No. of rings=?",A +End +randM(A+1,3)→[C] +[[1,2][1,3][2,3]]→[E] + +Fill(0,[C]) +For(I,1,A,1) +I?[C](I,1) +End +ClrHome +While [C](1,3)≠1 and [C](1,2)≠1 + +For(J,1,3) +For(I,1,A) +If [C](I,J)≠0:Then +Output(I+1,3J,[C](I,J)) +End +End +End +While C=0 +Output(1,3B," ") +1→I +[E](R,2)→J +While [C](I,J)=0 and I≤A +I+1→I +End +[C](I,J)→D +1→I +[E](R,1)→J +While [C](I,J)=0 and I≤A +I+1→I +End +If (D<[C](I,J) and D≠0) or [C](I,J)=0:Then +[E](R,2)→B +Else +[E](R,1)→B +End + +1→I +While [C](I,B)=0 and I≤A +I+1→I +End +If I≤A:Then +[C](I,B)→C +0→[C](I,B) +Output(I+1,3B," ") +End +Output(1,3B,"V") +End + +While C≠0 +Output(1,3B," ") +If B=[E](R,2):Then +[E](R,1)→B +Else +[E](R,2)→B +End + +1→I +While [C](I,B)=0 and I≤A +I+1→I +End +If [C](I,B)=0 or [C](I,B)>C:Then +C→[C](I-1,B) +0→C +M+1→M +End +End +Output(1,3B,"V") +R+1→R +If R=4:Then:1→R:End + +End diff --git a/Task/Towers-of-Hanoi/TSE-SAL/towers-of-hanoi.tse b/Task/Towers-of-Hanoi/TSE-SAL/towers-of-hanoi.tse new file mode 100644 index 0000000000..4f7f3125a2 --- /dev/null +++ b/Task/Towers-of-Hanoi/TSE-SAL/towers-of-hanoi.tse @@ -0,0 +1,25 @@ +// library: program: run: towersofhanoi: recursive: sub 1.0.0.0.0 (filenamemacro=runprrsu.s) [kn, ri, tu, 07-02-2012 19:54:23] +PROC PROCProgramRunTowersofhanoiRecursiveSub( INTEGER totalDiskI, STRING fromS, STRING toS, STRING viaS, INTEGER bufferI ) + IF ( totalDiskI == 0 ) + RETURN() + ENDIF + PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI - 1, fromS, viaS, toS, bufferI ) + AddLine( Format( "Move disk", " ", totalDiskI, " ", "from peg", " ", "'", fromS, "'", " ", "to peg", " ", "'", toS, "'" ), bufferI ) + PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI - 1, viaS, toS, fromS, bufferI ) +END + +// library: program: run: towersofhanoi: recursive 1.0.0.0.6 (filenamemacro=runprtre.s) [kn, ri, tu, 07-02-2012 19:40:45] +PROC PROCProgramRunTowersofhanoiRecursive( INTEGER totalDiskI, STRING fromS, STRING toS, STRING viaS ) + INTEGER bufferI = 0 + PushPosition() + bufferI = CreateTempBuffer() + PopPosition() + PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI, fromS, toS, viaS, bufferI ) + GotoBufferId( bufferI ) +END + +PROC Main() +STRING s1[255] = "4" +IF ( NOT ( Ask( "program: run: towersofhanoi: recursive: totalDiskI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF + PROCProgramRunTowersofhanoiRecursive( Val( s1 ), "source", "target", "via" ) +END diff --git a/Task/Towers-of-Hanoi/Tcl/towers-of-hanoi.tcl b/Task/Towers-of-Hanoi/Tcl/towers-of-hanoi.tcl new file mode 100644 index 0000000000..08131fcc52 --- /dev/null +++ b/Task/Towers-of-Hanoi/Tcl/towers-of-hanoi.tcl @@ -0,0 +1,15 @@ +interp alias {} hanoi {} do_hanoi 0 + +proc do_hanoi {count n {from A} {to C} {via B}} { + if {$n == 1} { + interp alias {} hanoi {} do_hanoi [incr count] + puts "$count: move from $from to $to" + } else { + incr n -1 + hanoi $n $from $via $to + hanoi 1 $from $to $via + hanoi $n $via $to $from + } +} + +hanoi 4 diff --git a/Task/Towers-of-Hanoi/Toka/towers-of-hanoi.toka b/Task/Towers-of-Hanoi/Toka/towers-of-hanoi.toka new file mode 100644 index 0000000000..704f7dc8fb --- /dev/null +++ b/Task/Towers-of-Hanoi/Toka/towers-of-hanoi.toka @@ -0,0 +1,13 @@ +value| sa sb sc n | +[ to sc to sb to sa to n ] is vars! +[ ( num from to via -- ) + vars! + n 0 <> + [ + n sa sb sc + n 1- sa sc sb recurse + vars! + ." Move a ring from " sa . ." to " sb . cr + n 1- sc sb sa recurse + ] ifTrue +] is hanoi diff --git a/Task/Towers-of-Hanoi/UNIX-Shell/towers-of-hanoi.sh b/Task/Towers-of-Hanoi/UNIX-Shell/towers-of-hanoi.sh new file mode 100644 index 0000000000..1cd5c59b87 --- /dev/null +++ b/Task/Towers-of-Hanoi/UNIX-Shell/towers-of-hanoi.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +move() +{ + local n="$1" + local from="$2" + local to="$3" + local via="$4" + + if [[ "$n" == "1" ]] + then + echo "Move disk from pole $from to pole $to" + else + move $(($n - 1)) $from $via $to + move 1 $from $to $via + move $(($n - 1)) $via $to $from + fi +} + +move $1 $2 $3 $4 diff --git a/Task/Towers-of-Hanoi/Ursala/towers-of-hanoi.ursala b/Task/Towers-of-Hanoi/Ursala/towers-of-hanoi.ursala new file mode 100644 index 0000000000..282c247349 --- /dev/null +++ b/Task/Towers-of-Hanoi/Ursala/towers-of-hanoi.ursala @@ -0,0 +1,7 @@ +#import nat + +move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC + +#show+ + +main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'> diff --git a/Task/Towers-of-Hanoi/Vedit-macro-language/towers-of-hanoi.vedit b/Task/Towers-of-Hanoi/Vedit-macro-language/towers-of-hanoi.vedit new file mode 100644 index 0000000000..ccc32be744 --- /dev/null +++ b/Task/Towers-of-Hanoi/Vedit-macro-language/towers-of-hanoi.vedit @@ -0,0 +1,25 @@ +#1=1; #2=2; #3=3; #4=4 // move 4 disks from 1 to 2 +Call("MOVE_DISKS") +Return + +// Move disks +// #1 = from, #2 = to, #3 = via, #4 = number of disks +// +:MOVE_DISKS: +if (#4 > 0) { + Num_Push(1,4) + #9=#2; #2=#3; #3=#9; #4-- // #1 to #3 via #2 + Call("MOVE_DISKS") + Num_Pop(1,4) + + Ins_Text("Move a disk from ") // move one disk + Num_Ins(#1, LEFT+NOCR) + Ins_Text(" to ") + Num_Ins(#2, LEFT) + + Num_Push(1,4) + #9=#1; #1=#3; #3 = #9; #4-- // #3 to #2 via #1 + Call("MOVE_DISKS") + Num_Pop(1,4) +} +Return diff --git a/Task/Towers-of-Hanoi/Visual-Basic-.NET/towers-of-hanoi.visual b/Task/Towers-of-Hanoi/Visual-Basic-.NET/towers-of-hanoi.visual new file mode 100644 index 0000000000..b14bfea200 --- /dev/null +++ b/Task/Towers-of-Hanoi/Visual-Basic-.NET/towers-of-hanoi.visual @@ -0,0 +1,13 @@ +Module TowersOfHanoi + Sub MoveTowerDisks(ByVal disks As Integer, ByVal fromTower As Integer, ByVal toTower As Integer, ByVal viaTower As Integer) + If disks > 0 Then + MoveTowerDisks(disks - 1, fromTower, viaTower, toTower) + System.Console.WriteLine("Move disk {0} from {1} to {2}", disks, fromTower, toTower) + MoveTowerDisks(disks - 1, viaTower, toTower, fromTower) + End If + End Sub + + Sub Main() + MoveTowerDisks(4, 1, 2, 3) + End Sub +End Module diff --git a/Task/Towers-of-Hanoi/XPL0/towers-of-hanoi.xpl0 b/Task/Towers-of-Hanoi/XPL0/towers-of-hanoi.xpl0 new file mode 100644 index 0000000000..9d4e52d07a --- /dev/null +++ b/Task/Towers-of-Hanoi/XPL0/towers-of-hanoi.xpl0 @@ -0,0 +1,13 @@ +code Text=12; + +proc MoveTower(Discs, From, To, Using); +int Discs, From, To, Using; +[if Discs > 0 then + [MoveTower(Discs-1, From, Using, To); + Text(0, "Move from "); Text(0, From); + Text(0, " peg to "); Text(0, To); Text(0, " peg.^M^J"); + MoveTower(Discs-1, Using, To, From); + ]; +]; + +MoveTower(3, "left", "right", "center") diff --git a/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-1.xquery b/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-1.xquery new file mode 100644 index 0000000000..7ee38176b7 --- /dev/null +++ b/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-1.xquery @@ -0,0 +1,17 @@ +declare function local:hanoi($disk as xs:integer, $from as xs:integer, + $to as xs:integer, $via as xs:integer) as element()* +{ + if($disk > 0) + then ( + local:hanoi($disk - 1, $from, $via, $to), + {$from}{$to}, + local:hanoi($disk - 1, $via, $to, $from) + ) + else () +}; + + +{ + local:hanoi(4, 1, 2, 3) +} + diff --git a/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-2.xquery b/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-2.xquery new file mode 100644 index 0000000000..ed67658791 --- /dev/null +++ b/Task/Towers-of-Hanoi/XQuery/towers-of-hanoi-2.xquery @@ -0,0 +1,63 @@ + + + + 1 + 3 + + + 1 + 2 + + + 3 + 2 + + + 1 + 3 + + + 2 + 1 + + + 2 + 3 + + + 1 + 3 + + + 1 + 2 + + + 3 + 2 + + + 3 + 1 + + + 2 + 1 + + + 3 + 2 + + + 1 + 3 + + + 1 + 2 + + + 3 + 2 + + diff --git a/Task/Towers-of-Hanoi/XSLT/towers-of-hanoi.xslt b/Task/Towers-of-Hanoi/XSLT/towers-of-hanoi.xslt new file mode 100644 index 0000000000..c8148090cf --- /dev/null +++ b/Task/Towers-of-Hanoi/XSLT/towers-of-hanoi.xslt @@ -0,0 +1,26 @@ + + +left +middle +right + + + + + + + + + Move disk from + + to + + + + + + + + + + diff --git a/Task/Trabb-Pardo-Knuth-algorithm/0DESCRIPTION b/Task/Trabb-Pardo-Knuth-algorithm/0DESCRIPTION new file mode 100644 index 0000000000..c5ba65c870 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/0DESCRIPTION @@ -0,0 +1,21 @@ +The TPK algorithm is an early example of programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf The Early Development of Programming Languages]. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. + +From the [[wp:Trabb Pardo–Knuth algorithm|wikipedia entry]]: + + '''ask''' for 11 numbers to be read into a sequence ''S'' + '''reverse''' sequence ''S'' + '''for each''' ''item'' '''in''' sequence ''S'' + ''result'' ''':=''' '''call''' a function to do an ''operation'' + '''if''' ''result'' overflows + '''alert''' user + '''else''' + '''print''' ''result'' + +The task is to implement the algorithm: +# Use the function f(x) = |x|^{0.5} + 5x^3 +# The overflow condition is an answer of greater than 400. +# The 'user alert' should not stop processing of other items of the sequence. +# Print a prompt before accepting '''eleven''', textual, numeric inputs. +# You may optionally print the item as well as its associated result, but the results must be in reverse order of input. +# The sequence S may be 'implied' and so not shown explicitly. +# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed). diff --git a/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-60/trabb-pardo-knuth-algorithm.alg b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-60/trabb-pardo-knuth-algorithm.alg new file mode 100644 index 0000000000..bba612ddd0 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-60/trabb-pardo-knuth-algorithm.alg @@ -0,0 +1,13 @@ +begin + integer i; real y; real array a[0:10]; + real procedure f(t); value t; real t; + f:=sqrt(abs(t))+5*t^3; + for i:=0 step 1 until 10 do inreal(0, a[i]); + for i:=10 step -1 until 0 do + begin + y:=f(a[i]); + if y > 400 then outstring(1, "TOO LARGE") + else outreal(1,y); + outchar(1, "\n", 1) + end +end diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Ada/trabb-pardo-knuth-algorithm.ada b/Task/Trabb-Pardo-Knuth-algorithm/Ada/trabb-pardo-knuth-algorithm.ada new file mode 100644 index 0000000000..173797ccf6 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Ada/trabb-pardo-knuth-algorithm.ada @@ -0,0 +1,36 @@ +with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; + +procedure Trabb_Pardo_Knuth is + + type Real is digits 6 range -400.0 .. 400.0; + + package TIO renames Ada.Text_IO; + package FIO is new TIO.Float_IO(Real); + package Math is new Ada.Numerics.Generic_Elementary_Functions(Real); + + function F(X: Real) return Real is + begin + return (Math.Sqrt(abs(X)) + 5.0 * X**3); + end F; + + Values: array(1 .. 11) of Real; + +begin + TIO.Put("Please enter 11 Numbers:"); + for I in Values'Range loop + FIO.Get(Values(I)); + end loop; + + for I in reverse Values'Range loop + TIO.Put("f("); + FIO.Put(Values(I), Fore => 2, Aft => 3, Exp => 0); + TIO.Put(")="); + begin + FIO.Put(F(Values(I)), Fore=> 4, Aft => 3, Exp => 0); + exception + when Constraint_Error => TIO.Put("-->too large<--"); + end; + TIO.New_Line; + end loop; + +end Trabb_Pardo_Knuth; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.autoit b/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.autoit new file mode 100644 index 0000000000..dfad5694f6 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.autoit @@ -0,0 +1,24 @@ +; Trabb Pardo–Knuth algorithm +; by James1337 (autoit.de) +; AutoIt Version: 3.3.8.1 + +Local $S, $i, $y + +Do + $S = InputBox("Trabb Pardo–Knuth algorithm", "Please enter 11 numbers:", "1 2 3 4 5 6 7 8 9 10 11") + If @error Then Exit + $S = StringSplit($S, " ") +Until ($S[0] = 11) + +For $i = 11 To 1 Step -1 + $y = f($S[$i]) + If ($y > 400) Then + ConsoleWrite("f(" & $S[$i] & ") = Overflow!" & @CRLF) + Else + ConsoleWrite("f(" & $S[$i] & ") = " & $y & @CRLF) + EndIf +Next + +Func f($x) + Return Sqrt(Abs($x)) + 5*$x^3 +EndFunc diff --git a/Task/Trabb-Pardo-Knuth-algorithm/BASIC256/trabb-pardo-knuth-algorithm.basic256 b/Task/Trabb-Pardo-Knuth-algorithm/BASIC256/trabb-pardo-knuth-algorithm.basic256 new file mode 100644 index 0000000000..b3cefe381c --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/BASIC256/trabb-pardo-knuth-algorithm.basic256 @@ -0,0 +1,20 @@ +dim s(11) +print 'enter 11 numbers' +for i = 0 to 10 + input i + ">" , s[i] +next i + +for i = 10 to 0 step -1 + print "f(" + s[i] + ")="; + x = f(s[i]) + if x > 400 then + print "--- too large ---" + else + print x + endif +next i +end + +function f(n) + return sqrt(abs(n))+5*n^3 +end function diff --git a/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp b/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp new file mode 100644 index 0000000000..b5c7ae65cb --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +int main( ) { + std::vector input( 11 ) , results( 11 ) ; + double number = 0.0 ; + std::cout << "Please enter 11 numbers!\n" ; + for ( int i = 0 ; i < input.size( ) ; i++ ) { + std::cin >> number ; + input[ i ] = number ; + } + std::transform( input.begin( ) , input.end( ) , results.begin( ) , + [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; + for ( int i = 10 ; i > -1 ; i-- ) { + std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; + if ( results[ i ] > 400 ) + std::cout << "too large!" ; + else + std::cout << results[ i ] << " !" ; + std::cout << std::endl ; + } + return 0 ; +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c new file mode 100644 index 0000000000..208e70edb5 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c @@ -0,0 +1,40 @@ +/* Abhishek Ghosh + 27th August, 2012 */ + +#include +#include + +int +main () +{ + double inputs[11], check = 400, result; + int i; + + printf ("\nPlease enter 11 numbers :"); + + for (i = 0; i < 11; i++) + { + scanf ("%lf", &inputs[i]); + } + + printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); + + for (i = 10; i >= 0; i--) + { + result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); + + printf ("\nf(%lf) = "); + + if (result > check) + { + printf ("Overflow!"); + } + + else + { + printf ("%lf", result); + } + } + + return 0; +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d b/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d new file mode 100644 index 0000000000..691cb480c8 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/D/trabb-pardo-knuth-algorithm.d @@ -0,0 +1,20 @@ +import std.stdio, std.math, std.range, std.conv, std.algorithm; + +double f(in double x) pure nothrow { + return x.abs().sqrt() + 5 * x ^^ 3; +} + +void main() { + double[] data; + while (true) { + write("Please enter eleven numbers on a line: "); + data = readln().split().map!(to!double)().array(); + if (data.length == 11) + break; + writeln("Those aren't eleven numbers."); + } + foreach (x; data.retro()) { + immutable y = f(x); + writefln("f(%0.3f) = %s", x, y > 400 ? "Too large" : text(y)); + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Ela/trabb-pardo-knuth-algorithm.ela b/Task/Trabb-Pardo-Knuth-algorithm/Ela/trabb-pardo-knuth-algorithm.ela new file mode 100644 index 0000000000..fd6005d602 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Ela/trabb-pardo-knuth-algorithm.ela @@ -0,0 +1,15 @@ +open random number list console format read + +run () = + writen "Please enter 11 numbers:" $ + xs () |> iter + where xs () = [0..10] |> map (\_ -> readStr <| readn ()) + f x = sqrt (toSingle x) + 5.0 * (x ** 3.0) + p x = x < 400.0 + iter [] = () + iter (x::xs) + | p res = printfn "f({0}) = {1}" x res $ iter xs + | else = printfn "f({0}) :: Overflow" x $ iter xs + where res = f x + +run () diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Go/trabb-pardo-knuth-algorithm.go b/Task/Trabb-Pardo-Knuth-algorithm/Go/trabb-pardo-knuth-algorithm.go new file mode 100644 index 0000000000..ba1977a161 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Go/trabb-pardo-knuth-algorithm.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "log" + "math" +) + +func main() { + // prompt + fmt.Print("Enter 11 numbers: ") + // accept sequence + var s [11]float64 + for i := 0; i < 11; { + if _, err := fmt.Scanf("%f", &s[i]); err == nil { + i++ + } + } + // reverse sequence + for i, item := range s[:5] { + s[i], s[10-i] = s[10-i], item + } + // iterate + for _, item := range s { + if result, overflow := f(item); overflow { + // send alerts to stderr + log.Printf("f(%g) overflow", item) + } else { + // send normal results to stdout + fmt.Printf("f(%g) = %g\n", item, result) + } + } +} + +func f(x float64) (float64, bool) { + result := math.Pow(math.Abs(x), .5) + 5*x*x*x + return result, result > 400 +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs new file mode 100644 index 0000000000..c2cc01d10b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Haskell/trabb-pardo-knuth-algorithm.hs @@ -0,0 +1,9 @@ +import Control.Monad (replicateM_) + +f x = (abs x) ** 0.5 + 5 * x ** 3 + +main = do + putStrLn "Enter 11 numbers for evaluation" + replicateM_ 11 $ getLine >>= (\x -> if x>400 + then putStrLn "OVERFLOW" + else print x).f.read diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Io/trabb-pardo-knuth-algorithm.io b/Task/Trabb-Pardo-Knuth-algorithm/Io/trabb-pardo-knuth-algorithm.io new file mode 100644 index 0000000000..e4d45d6d7b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Io/trabb-pardo-knuth-algorithm.io @@ -0,0 +1,23 @@ +// Initialize objects to be used +in_num := File standardInput() +nums := List clone +result := Number + +// Prompt the user and get numbers from standard input +"Please enter 11 numbers:" println +11 repeat(nums append(in_num readLine() asNumber())) + +// Reverse the numbers received +nums reverseInPlace + +// Apply the function and tell the user if the result is above +// our limit. Otherwise, tell them the result. +nums foreach(v, + // v needs parentheses around it for abs to properly convert v to its absolute value + result = (v) abs ** 0.5 + 5 * v ** 3 + if (result > 400, + "Overflow!" println + , + result println + ) +) diff --git a/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-1.j b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-1.j new file mode 100644 index 0000000000..ff40ab60df --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-1.j @@ -0,0 +1,6 @@ +tpk=: 3 :0 + smoutput 'Enter 11 numbers: ' + t1=: ((5 * ^&3) + (^&0.5@* *))"0 |. _999&".;._1 ' ' , 1!:1 [ 1 + smoutput 'Values of functions of reversed input: ' , ": t1 + ; <@(,&' ')@": ` ((<'user alert ')&[) @. (>&400)"0 t1 +) diff --git a/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-2.j b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-2.j new file mode 100644 index 0000000000..4f118d84f0 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-2.j @@ -0,0 +1,5 @@ + tpk '' +Enter 11 numbers: +1 2 3 4 5 6 7 8.8 _9 10.123 0 +Values of functions of reversed input: 0 5189.96 _3642 3410.33 1717.65 1082.45 627.236 322 136.732 41.4142 6 +0 user alert _3642 user alert user alert user alert user alert 322 136.732 41.4142 6 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-3.j b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-3.j new file mode 100644 index 0000000000..11c09df182 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-3.j @@ -0,0 +1,10 @@ +get11numbers=: 3 :0 + smoutput 'Enter 11 numbers: ' + _&". 1!:1]1 +) + +f_x=: %:@| + 5 * ^&3 + +overflow400=: 'user alert'"_`":@.(<:&400)"0 + +tpk=: overflow400@f_x@|.@get11numbers diff --git a/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-4.j b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-4.j new file mode 100644 index 0000000000..80adbe9ca5 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/J/trabb-pardo-knuth-algorithm-4.j @@ -0,0 +1,14 @@ + tpk'' +Enter 11 numbers: +1 2 3 4 5 6 7 8.8 _9 10.123 0 +0 +user alert +_3642 +user alert +user alert +user alert +user alert +322 +136.732 +41.4142 +6 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Java/trabb-pardo-knuth-algorithm.java b/Task/Trabb-Pardo-Knuth-algorithm/Java/trabb-pardo-knuth-algorithm.java new file mode 100644 index 0000000000..dbdae63a0c --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Java/trabb-pardo-knuth-algorithm.java @@ -0,0 +1,36 @@ +/** + * Alexander Alvonellos + */ +import java.util.*; +import java.io.*; + +public class TPKA { + public static void main(String... args) { + double[] input = new double[11]; + double userInput = 0.0; + Scanner in = new Scanner(System.in); + for(int i = 0; i < 11; i++) { + System.out.print("Please enter a number: "); + String s = in.nextLine(); + try { + userInput = Double.parseDouble(s); + } catch (NumberFormatException e) { + System.out.println("You entered invalid input, exiting"); + System.exit(1); + } + input[i] = userInput; + } + for(int j = 10; j >= 0; j--) { + double x = input[j]; double y = f(x); + if( y < 400.0) { + System.out.printf("f( %.2f ) = %.2f\n", x, y); + } else { + System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); + } + } + } + + private static double f(double x) { + return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/JavaScript/trabb-pardo-knuth-algorithm.js b/Task/Trabb-Pardo-Knuth-algorithm/JavaScript/trabb-pardo-knuth-algorithm.js new file mode 100644 index 0000000000..86af4987e1 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/JavaScript/trabb-pardo-knuth-algorithm.js @@ -0,0 +1,36 @@ +#!/usr/bin/env js + +function main() { + var nums = getNumbers(11); + nums.reverse(); + for (var i in nums) { + pardoKnuth(nums[i], fn, 400); + } +} + +function pardoKnuth(n, f, max) { + var res = f(n); + putstr('f(' + String(n) + ')'); + if (res > max) { + print(' is too large'); + } else { + print(' = ' + String(res)); + } +} + +function fn(x) { + return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3); +} + +function getNumbers(n) { + var nums = []; + print('Enter', n, 'numbers.'); + for (var i = 1; i <= n; i++) { + putstr(' ' + i + ': '); + var num = readline(); + nums.push(Number(num)); + } + return nums; +} + +main(); diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Julia/trabb-pardo-knuth-algorithm.julia b/Task/Trabb-Pardo-Knuth-algorithm/Julia/trabb-pardo-knuth-algorithm.julia new file mode 100644 index 0000000000..656f826eb0 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Julia/trabb-pardo-knuth-algorithm.julia @@ -0,0 +1,16 @@ +f(x) = abs(x)^.5 + 5x^3 +for i in map(parse_int,reverse(split(chomp(readline(STDIN)),' '))) + println("$i: ",f(i)>400?"TOO LARGE":f(i)) +end +1 2 3 4 5 6 7 8 9 10 11 +11: TOO LARGE +10: TOO LARGE +9: TOO LARGE +8: TOO LARGE +7: TOO LARGE +6: TOO LARGE +5: TOO LARGE +4: 322.0 +3: 136.73205080756887 +2: 41.41421356237309 +1: 6.0 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/OCaml/trabb-pardo-knuth-algorithm.ocaml b/Task/Trabb-Pardo-Knuth-algorithm/OCaml/trabb-pardo-knuth-algorithm.ocaml new file mode 100644 index 0000000000..78a893c31b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/OCaml/trabb-pardo-knuth-algorithm.ocaml @@ -0,0 +1,12 @@ +let f x = sqrt x +. 5.0 *. (x ** 3.0) +let p x = x < 400.0 + +let () = + print_endline "Please enter 11 Numbers:"; + let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in + List.iter (fun x -> + let res = f x in + if p res + then Printf.printf "f(%g) = %g\n%!" x res + else Printf.eprintf "f(%g) :: Overflow\n%!" x + ) (List.rev lst) diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m b/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m new file mode 100644 index 0000000000..0e121d9450 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Objective-C/trabb-pardo-knuth-algorithm.m @@ -0,0 +1,41 @@ +// +// TPKA.m +// RosettaCode +// +// Created by Alexander Alvonellos on 5/26/12. +// Trabb Pardo-Knuth algorithm +// + +#import +double f(double x); + +double f(double x) { + return pow(abs(x), 0.5) + 5*(pow(x, 3)); +} + +int main (int argc, const char * argv[]) +{ + @autoreleasepool { + NSMutableArray *input = [[NSMutableArray alloc] initWithCapacity:0]; + + printf("%s", "Instructions: please enter 11 numbers.\n"); + for(int i = 0; i < 11; i++) { + double userInput = 0.0; + printf("%s", "Please enter a number: "); + scanf("%lf", &userInput); + [input addObject: [NSNumber numberWithDouble: (double) userInput]]; + } + + for(int i = 10; i >= 0; i--) { + double x = [[input objectAtIndex: i] doubleValue]; + double y = f(x); + printf("f(%.2f) \t=\t", x); + if(y < 400.0) { + printf("%.2f\n", y); + } else { + printf("%s\n", "TOO LARGE"); + } + } + } + return 0; +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PARI-GP/trabb-pardo-knuth-algorithm.pari b/Task/Trabb-Pardo-Knuth-algorithm/PARI-GP/trabb-pardo-knuth-algorithm.pari new file mode 100644 index 0000000000..7e8f0fd83e --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PARI-GP/trabb-pardo-knuth-algorithm.pari @@ -0,0 +1,6 @@ +{ + print("11 numbers: "); + v=vector(11, n, eval(input())); + v=apply(x->x=sqrt(abs(x))+5*x^3;if(x>400,"overflow",x), v); + vector(11, i, v[12-i]) +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Perl-6/trabb-pardo-knuth-algorithm.pl6 b/Task/Trabb-Pardo-Knuth-algorithm/Perl-6/trabb-pardo-knuth-algorithm.pl6 new file mode 100644 index 0000000000..82c04c9c8a --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Perl-6/trabb-pardo-knuth-algorithm.pl6 @@ -0,0 +1,6 @@ +my @nums = prompt("Please type 11 space-separated numbers: ").words + until @nums == 11; +for @nums.reverse -> $n { + my $r = $n.abs.sqrt + 5 * $n ** 3; + say "$n\t{ $r > 400 ?? 'Urk!' !! $r }"; +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl b/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl new file mode 100644 index 0000000000..5204fc3c29 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Perl/trabb-pardo-knuth-algorithm.pl @@ -0,0 +1,14 @@ +#!/usr/bin/perl +use strict ; +use warnings ; + +my $number ; +my @sequence ; +print "Please enter 11 numbers!\n" ; +for my $i ( 0..10 ) { + $number = ; + chomp $number ; + push @sequence , $number ; +} +map { my $result = sqrt( abs ( $_ ) ) + 5 * $_** 3 ; print "f( $_ ) " ; $result > 400 ? print "too large!\n" : print ": $result\n" ; } + reverse @sequence ; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-1.l b/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-1.l new file mode 100644 index 0000000000..ecd822d000 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-1.l @@ -0,0 +1,10 @@ +(de f (X) + (+ (sqrt (abs X)) (* 5 X X X)) ) + +(trace 'f) + +(in NIL + (prin "Input 11 numbers: ") + (for X (reverse (make (do 11 (link (read))))) + (when (> (f X) 400) + (prinl "TOO LARGE") ) ) ) diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-2.l b/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-2.l new file mode 100644 index 0000000000..894e8d206f --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PicoLisp/trabb-pardo-knuth-algorithm-2.l @@ -0,0 +1,30 @@ +Input 11 numbers: 1 2 3 4 5 6 7 8 9 10 11 + f : 11 + f = 6658 +TOO LARGE + f : 10 + f = 5003 +TOO LARGE + f : 9 + f = 3648 +TOO LARGE + f : 8 + f = 2562 +TOO LARGE + f : 7 + f = 1717 +TOO LARGE + f : 6 + f = 1082 +TOO LARGE + f : 5 + f = 627 +TOO LARGE + f : 4 + f = 322 + f : 3 + f = 136 + f : 2 + f = 41 + f : 1 + f = 6 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic b/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic new file mode 100644 index 0000000000..d1eac8940d --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic @@ -0,0 +1,52 @@ +Procedure.d f(x.d) + ProcedureReturn Pow(Abs(x), 0.5) + 5 * x * x * x +EndProcedure + +Procedure split(i.s, delimeter.s, List o.d()) + Protected index = CountString(i, delimeter) + 1 ;add 1 because last entry will not have a delimeter + + While index > 0 + AddElement(o()) + o() = ValD(Trim(StringField(i, index, delimeter))) + index - 1 + Wend + + ProcedureReturn ListSize(o()) +EndProcedure + +Define i$, entriesAreValid = 0, result.d, output$ +NewList numbers.d() + +If OpenConsole() + Repeat + PrintN(#crlf$ + "Enter eleven numbers that are each separated by spaces or commas:") + + i$ = Input( + i$ = Trim(i$) + If split(i$, ",", numbers.d()) < 11 + ClearList(numbers()) + If split(i$, " ", numbers.d()) < 11 + PrintN("Not enough numbers were supplied.") + ClearList(numbers()) + Else + entriesAreValid = 1 + EndIf + Else + entriesAreValid = 1 + EndIf + Until entriesAreValid = 1 + + ForEach numbers() + output$ = "f(" + RTrim(RTrim(StrD(numbers(), 3), "0"), ".") + ") = " + result.d = f(numbers()) + If result > 400 + output$ + "Too Large" + Else + output$ + RTrim(RTrim(StrD(result, 3), "0"), ".") + EndIf + PrintN(output$) + Next + + Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-1.py b/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-1.py new file mode 100644 index 0000000000..9f897540d7 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-1.py @@ -0,0 +1,10 @@ +Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 +Type "copyright", "credits" or "license()" for more information. +>>> def f(x): return abs(x) ** 0.5 + 5 * x**3 + +>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!") + for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1]))) + +11 numbers: 1 2 3 4 5 6 7 8 9 10 11 +11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0 +>>> diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-2.py b/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-2.py new file mode 100644 index 0000000000..44abf5df6f --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Python/trabb-pardo-knuth-algorithm-2.py @@ -0,0 +1,17 @@ +def f(x): + return abs(x) ** 0.5 + 5 * x**3 + +def ask(): + return [float(y) + for y in input('\n11 numbers: ').strip().split()[:11]] + +if __name__ == '__main__': + s = ask() + s.reverse() + for x in s: + result = f(x) + if result > 400: + print(' %s:%s' % (x, "TOO LARGE!"), end='') + else: + print(' %s:%s' % (x, result), end='') + print('') diff --git a/Task/Trabb-Pardo-Knuth-algorithm/R/trabb-pardo-knuth-algorithm.r b/Task/Trabb-Pardo-Knuth-algorithm/R/trabb-pardo-knuth-algorithm.r new file mode 100644 index 0000000000..1cb3f61a92 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/R/trabb-pardo-knuth-algorithm.r @@ -0,0 +1,11 @@ +S <- scan(n=11) + +f <- function(x) sqrt(abs(x)) + 5*x^3 + +for (i in rev(S)) { + res <- f(i) + if (res > 400) + print("Too large!") + else + print(res) +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx new file mode 100644 index 0000000000..aff45b02fa --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx @@ -0,0 +1,49 @@ +/*REXX program to implement the Trabb-Pardo-Knuth algorthm for N nums.*/ +N=11 /*N is the number of numbers. */ +maxValue=400 /*the maximum value f(x) can have*/ +precDigs=200 /*compute with this many digits. */ +showDigs=20 /*...but only show this many digs*/ +numeric digits precDigs /*the number of digits precision.*/ +prompt='enter' N "nunbers for the Trabb-Pardo-Knuth algorthm: (or Quit)" +say ' _____ ' /*vinculum.*/ +say 'function: ƒ(x) ≡ √ │x│ + (5 * x^3)' +/*██████████████████████████████████████████████████████████████████████*/ + do ask=0; say; say prompt; say; parse pull yyyU . 1 yyy; say + upper yyyU; if abbrev('QUIT',yyyU,1) then exit + + do validate=0 + select + when yyy='' then say 'no numbers entered' + when words(yyy)N then say 'too many numbers entered' + otherwise leave validate + end /*select*/ + iterate ask + end /*validate*/ + do j=1 for N; _=word(yyy,j) + if \datatype(_,'N') then do + say _ "isn't numeric" + iterate ask + end + end /*j*/ + leave ask + end /*ask*/ +say 'numbers entered:' yyy; say +/*██████████████████████████████████████████████████████████████████████*/ + do i=N by -1 to 1; p=word(yyy,i)/1 /*process #s in reverse.*/ + g=f(p) + numeric digits showdigs; g=g/1 /*scale down the result.*/ + if g>maxValue then say 'f('p") is > " maxValue ' ['g"]" + else say 'f('p") = " g /*show the (good) result*/ + numeric digits precDigs /*re-instate big digits.*/ + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────F function──────────────────────────*/ +f: procedure; arg x; return sqrt(abs(x)) + 5 * x**3 +/*──────────────────────────────────SQRT function───────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric digits 11 + g=.sqrtGuess(); 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 +.sqrtGuess: 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/Trabb-Pardo-Knuth-algorithm/Ruby/trabb-pardo-knuth-algorithm.rb b/Task/Trabb-Pardo-Knuth-algorithm/Ruby/trabb-pardo-knuth-algorithm.rb new file mode 100644 index 0000000000..59d5240dfc --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Ruby/trabb-pardo-knuth-algorithm.rb @@ -0,0 +1,13 @@ +nums = []; + +puts "Please enter 11 numbers:" +11.times{nums << gets.chomp.to_f} + +nums.reverse.each do |n| + res = n.abs ** 0.5 + 5 * n ** 3 + if res > 400 + puts "Overflow!" + else + puts res + end +end diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Tcl/trabb-pardo-knuth-algorithm.tcl b/Task/Trabb-Pardo-Knuth-algorithm/Tcl/trabb-pardo-knuth-algorithm.tcl new file mode 100644 index 0000000000..42572e650f --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Tcl/trabb-pardo-knuth-algorithm.tcl @@ -0,0 +1,20 @@ +# Helper procedures +proc f {x} {expr {abs($x)**0.5 + 5*$x**3}} +proc overflow {y} {expr {$y > 400}} + +# Read in 11 numbers, with nice prompting +fconfigure stdout -buffering none +for {set n 1} {$n <= 11} {incr n} { + puts -nonewline "number ${n}: " + lappend S [scan [gets stdin] "%f"] +} + +# Process and print results in reverse order +foreach x [lreverse $S] { + set result [f $x] + if {[overflow $result]} { + puts "${x}: TOO LARGE!" + } else { + puts "${x}: $result" + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/XPL0/trabb-pardo-knuth-algorithm.xpl0 b/Task/Trabb-Pardo-Knuth-algorithm/XPL0/trabb-pardo-knuth-algorithm.xpl0 new file mode 100644 index 0000000000..b24e68fae9 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/XPL0/trabb-pardo-knuth-algorithm.xpl0 @@ -0,0 +1,18 @@ +include c:\cxpl\codes; + +func real F(X); +real X; +return sqrt(abs(X)) + 5.0*X*X*X; + +real Result, S(11); int I; +[Text(0, "Please enter 11 numbers: "); +for I:= 0 to 11-1 do S(I):= RlIn(0); + +for I:= 11-1 downto 0 do + [RlOut(0, S(I)); + Result:= F(S(I)); + if Result > 400.0 then + Text(0, " overflows") + else RlOut(0, Result); + CrLf(0)]; +] diff --git a/Task/Tree-traversal/0DESCRIPTION b/Task/Tree-traversal/0DESCRIPTION new file mode 100644 index 0000000000..bc2bd2b9a4 --- /dev/null +++ b/Task/Tree-traversal/0DESCRIPTION @@ -0,0 +1,18 @@ +Implement a binary tree where each node carries an integer, and implement preoder, inorder, postorder and level-order [[wp:Tree traversal|traversal]]. Use those traversals to output the following tree: + 1 + / \ + / \ + / \ + 2 3 + / \ / + 4 5 6 + / / \ + 7 8 9 + +The correct output should look like this: + preorder: 1 2 4 7 5 3 6 8 9 + inorder: 7 4 2 5 1 8 6 9 3 + postorder: 7 4 5 2 8 9 6 3 1 + level-order: 1 2 3 4 5 6 7 8 9 + +[[wp:Tree traversal|This article]] has more information on traversing trees. diff --git a/Task/Tree-traversal/1META.yaml b/Task/Tree-traversal/1META.yaml new file mode 100644 index 0000000000..15ab9f5af3 --- /dev/null +++ b/Task/Tree-traversal/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Recursion +note: Data Structures diff --git a/Task/Tree-traversal/ACL2/tree-traversal.acl2 b/Task/Tree-traversal/ACL2/tree-traversal.acl2 new file mode 100644 index 0000000000..1292966f5c --- /dev/null +++ b/Task/Tree-traversal/ACL2/tree-traversal.acl2 @@ -0,0 +1,47 @@ +(defun flatten-preorder (tree) + (if (endp tree) + nil + (append (list (first tree)) + (flatten-preorder (second tree)) + (flatten-preorder (third tree))))) + +(defun flatten-inorder (tree) + (if (endp tree) + nil + (append (flatten-inorder (second tree)) + (list (first tree)) + (flatten-inorder (third tree))))) + +(defun flatten-postorder (tree) + (if (endp tree) + nil + (append (flatten-postorder (second tree)) + (flatten-postorder (third tree)) + (list (first tree))))) + +(defun flatten-level-r1 (tree level levels) + (if (endp tree) + levels + (let ((curr (cdr (assoc level levels)))) + (flatten-level-r1 + (second tree) + (1+ level) + (flatten-level-r1 + (third tree) + (1+ level) + (put-assoc level + (append curr (list (first tree))) + levels)))))) + +(defun flatten-level-r2 (levels max-level) + (declare (xargs :measure (nfix (1+ max-level)))) + (if (zp (1+ max-level)) + nil + (append (flatten-level-r2 levels + (1- max-level)) + (reverse (cdr (assoc max-level levels)))))) + + +(defun flatten-level (tree) + (let ((levels (flatten-level-r1 tree 0 nil))) + (flatten-level-r2 levels (len levels)))) diff --git a/Task/Tree-traversal/ALGOL-68/tree-traversal.alg b/Task/Tree-traversal/ALGOL-68/tree-traversal.alg new file mode 100644 index 0000000000..780265e423 --- /dev/null +++ b/Task/Tree-traversal/ALGOL-68/tree-traversal.alg @@ -0,0 +1,124 @@ +MODE VALUE = INT; +PROC value repr = (VALUE value)STRING: whole(value, 0); + +MODE NODES = STRUCT ( VALUE value, REF NODES left, right); +MODE NODE = REF NODES; + +PROC tree = (VALUE value, NODE left, right)NODE: + HEAP NODES := (value, left, right); + +PROC preorder = (NODE node, PROC (VALUE)VOID action)VOID: + IF node ISNT NODE(NIL) THEN + action(value OF node); + preorder(left OF node, action); + preorder(right OF node, action) + FI; + +PROC inorder = (NODE node, PROC (VALUE)VOID action)VOID: + IF node ISNT NODE(NIL) THEN + inorder(left OF node, action); + action(value OF node); + inorder(right OF node, action) + FI; + +PROC postorder = (NODE node, PROC (VALUE)VOID action)VOID: + IF node ISNT NODE(NIL) THEN + postorder(left OF node, action); + postorder(right OF node, action); + action(value OF node) + FI; + +PROC destroy tree = (NODE node)VOID: + postorder(node, (VALUE skip)VOID: + # free(node) - PR garbage collect hint PR # + node := (SKIP, NIL, NIL) + ); + +# helper queue for level order # +MODE QNODES = STRUCT (REF QNODES next, NODE value); +MODE QNODE = REF QNODES; + + +MODE QUEUES = STRUCT (QNODE begin, end); +MODE QUEUE = REF QUEUES; + +PROC enqueue = (QUEUE queue, NODE node)VOID: +( + HEAP QNODES qnode := (NIL, node); + IF end OF queue ISNT QNODE(NIL) THEN + next OF end OF queue + ELSE + begin OF queue + FI := end OF queue := qnode +); + +PROC queue empty = (QUEUE queue)BOOL: + begin OF queue IS QNODE(NIL); + +PROC dequeue = (QUEUE queue)NODE: +( + NODE out := value OF begin OF queue; + QNODE second := next OF begin OF queue; +# free(begin OF queue); PR garbage collect hint PR # + QNODE(begin OF queue) := (NIL, NIL); + begin OF queue := second; + IF queue empty(queue) THEN + end OF queue := begin OF queue + FI; + out +); + +PROC level order = (NODE node, PROC (VALUE)VOID action)VOID: +( + HEAP QUEUES queue := (QNODE(NIL), QNODE(NIL)); + enqueue(queue, node); + WHILE NOT queue empty(queue) + DO + NODE next := dequeue(queue); + IF next ISNT NODE(NIL) THEN + action(value OF next); + enqueue(queue, left OF next); + enqueue(queue, right OF next) + FI + OD +); + +PROC print node = (VALUE value)VOID: + print((" ",value repr(value))); + +main: ( + NODE node := tree(1, + tree(2, + tree(4, + tree(7, NIL, NIL), + NIL), + tree(5, NIL, NIL)), + tree(3, + tree(6, + tree(8, NIL, NIL), + tree(9, NIL, NIL)), + NIL)); + + MODE TEST = STRUCT( + STRING name, + PROC(NODE,PROC(VALUE)VOID)VOID order + ); + + PROC test = (TEST test)VOID:( + STRING pad=" "*(12-UPB name OF test); + print((name OF test,pad,": ")); + (order OF test)(node, print node); + print(new line) + ); + + []TEST test list = ( + ("preorder",preorder), + ("inorder",inorder), + ("postorder",postorder), + ("level order",level order) + ); + + FOR i TO UPB test list DO test(test list[i]) OD; + + destroy tree(node) +) diff --git a/Task/Tree-traversal/ATS/tree-traversal.ats b/Task/Tree-traversal/ATS/tree-traversal.ats new file mode 100644 index 0000000000..3af92347be --- /dev/null +++ b/Task/Tree-traversal/ATS/tree-traversal.ats @@ -0,0 +1,62 @@ +staload "prelude/DATS/list.dats" + +datatype Tree (a:t@ype) = + | Empty (a) + | Node (a) of (a, Tree a, Tree a) + + +fun print_list +(list: List int): void = + case list of + | nil () => () + | x :: xs => (print! (x, " "); print_list xs) + +overload print with print_list + +#define ++ list_append +infixr 40 ++ + + +fun {a:t@ype} preorder +(tree: Tree a): List a = + case tree of + | Empty () => nil () + | Node (x, l, r) => '[x] ++ preorder l ++ preorder r + +fun {a:t@ype} inorder +(tree: Tree a): List a = + case tree of + | Empty () => nil () + | Node (x, l, r) => inorder l ++ '[x] ++ inorder r + +fun {a:t@ype} postorder +(tree: Tree a): List a = + case tree of + | Empty () => nil () + | Node (x, l, r) => postorder l ++ postorder r ++ '[x] + +fun {a:t@ype} levelorder +(tree: Tree a): List a = loop '[tree] +where { + fun loop (list: List (Tree a)): List a = + case list of + | nil () => nil () + | Empty () :: xs => loop xs + | Node (x, l, r) :: xs => x :: loop (xs ++ '[l, r]) +} + + +implement main () = let + val tree = + Node (1, Node (2, Node (4, Node (7, Empty (), Empty ()), + Empty ()), + Node (5, Empty (), Empty ())), + Node (3, Node (6, Node (8, Empty (), Empty ()), + Node (9, Empty (), Empty ())), + Empty ())) +in + print! ("preorder:\t", preorder tree, "\n"); + print! ("inorder:\t", inorder tree, "\n"); + print! ("postorder:\t", postorder tree, "\n"); + print! ("level-order:\t", levelorder tree, "\n"); +end diff --git a/Task/Tree-traversal/Ada/tree-traversal.ada b/Task/Tree-traversal/Ada/tree-traversal.ada new file mode 100644 index 0000000000..caad323193 --- /dev/null +++ b/Task/Tree-traversal/Ada/tree-traversal.ada @@ -0,0 +1,108 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Unchecked_Deallocation; +with Ada.Containers.Doubly_Linked_Lists; + +procedure Tree_Traversal is + type Node; + type Node_Access is access Node; + type Node is record + Left : Node_Access := null; + Right : Node_Access := null; + Data : Integer; + end record; + procedure Destroy_Tree(N : in out Node_Access) is + procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); + begin + if N.Left /= null then + Destroy_Tree(N.Left); + end if; + if N.Right /= null then + Destroy_Tree(N.Right); + end if; + Free(N); + end Destroy_Tree; + function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is + Temp : Node_Access := new Node; + begin + Temp.Data := Value; + Temp.Left := Left; + Temp.Right := Right; + return Temp; + end Tree; + procedure Preorder(N : Node_Access) is + begin + Put(Integer'Image(N.Data)); + if N.Left /= null then + Preorder(N.Left); + end if; + if N.Right /= null then + Preorder(N.Right); + end if; + end Preorder; + procedure Inorder(N : Node_Access) is + begin + if N.Left /= null then + Inorder(N.Left); + end if; + Put(Integer'Image(N.Data)); + if N.Right /= null then + Inorder(N.Right); + end if; + end Inorder; + procedure Postorder(N : Node_Access) is + begin + if N.Left /= null then + Postorder(N.Left); + end if; + if N.Right /= null then + Postorder(N.Right); + end if; + Put(Integer'Image(N.Data)); + end Postorder; + procedure Levelorder(N : Node_Access) is + package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); + use Queues; + Node_Queue : List; + Next : Node_Access; + begin + Node_Queue.Append(N); + while not Is_Empty(Node_Queue) loop + Next := First_Element(Node_Queue); + Delete_First(Node_Queue); + Put(Integer'Image(Next.Data)); + if Next.Left /= null then + Node_Queue.Append(Next.Left); + end if; + if Next.Right /= null then + Node_Queue.Append(Next.Right); + end if; + end loop; + end Levelorder; + N : Node_Access; +begin + N := Tree(1, + Tree(2, + Tree(4, + Tree(7, null, null), + null), + Tree(5, null, null)), + Tree(3, + Tree(6, + Tree(8, null, null), + Tree(9, null, null)), + null)); + + Put("preorder: "); + Preorder(N); + New_Line; + Put("inorder: "); + Inorder(N); + New_Line; + Put("postorder: "); + Postorder(N); + New_Line; + Put("level order: "); + Levelorder(N); + New_Line; + Destroy_Tree(N); +end Tree_traversal; diff --git a/Task/Tree-traversal/AutoHotkey/tree-traversal.ahk b/Task/Tree-traversal/AutoHotkey/tree-traversal.ahk new file mode 100644 index 0000000000..0b7d1286f6 --- /dev/null +++ b/Task/Tree-traversal/AutoHotkey/tree-traversal.ahk @@ -0,0 +1,53 @@ +AddNode(Tree,1,2,3,1) ; Build global Tree +AddNode(Tree,2,4,5,2) +AddNode(Tree,3,6,0,3) +AddNode(Tree,4,7,0,4) +AddNode(Tree,5,0,0,5) +AddNode(Tree,6,8,9,6) +AddNode(Tree,7,0,0,7) +AddNode(Tree,8,0,0,8) +AddNode(Tree,9,0,0,9) + +MsgBox % "Preorder: " PreOrder(Tree,1) ; 1 2 4 7 5 3 6 8 9 +MsgBox % "Inorder: " InOrder(Tree,1) ; 7 4 2 5 1 8 6 9 3 +MsgBox % "postorder: " PostOrder(Tree,1) ; 7 4 5 2 8 9 6 3 1 +MsgBox % "levelorder: " LevOrder(Tree,1) ; 1 2 3 4 5 6 7 8 9 + +AddNode(ByRef Tree,Node,Left,Right,Value) { + if !isobject(Tree) + Tree := object() + + Tree[Node, "L"] := Left + Tree[Node, "R"] := Right + Tree[Node, "V"] := Value +} + +PreOrder(Tree,Node) { +ptree := Tree[Node, "V"] " " + . ((L:=Tree[Node, "L"]) ? PreOrder(Tree,L) : "") + . ((R:=Tree[Node, "R"]) ? PreOrder(Tree,R) : "") +return ptree +} +InOrder(Tree,Node) { + Return itree := ((L:=Tree[Node, "L"]) ? InOrder(Tree,L) : "") + . Tree[Node, "V"] " " + . ((R:=Tree[Node, "R"]) ? InOrder(Tree,R) : "") +} +PostOrder(Tree,Node) { + Return ptree := ((L:=Tree[Node, "L"]) ? PostOrder(Tree,L) : "") + . ((R:=Tree[Node, "R"]) ? PostOrder(Tree,R) : "") + . Tree[Node, "V"] " " +} +LevOrder(Tree,Node,Lev=1) { + Static ; make node lists static + i%Lev% .= Tree[Node, "V"] " " ; build node lists in every level + If (L:=Tree[Node, "L"]) + LevOrder(Tree,L,Lev+1) + If (R:=Tree[Node, "R"]) + LevOrder(Tree,R,Lev+1) + If (Lev > 1) + Return + While i%Lev% ; concatenate node lists from all levels + t .= i%Lev%, Lev++ + Return t +} diff --git a/Task/Tree-traversal/Bracmat/tree-traversal.bracmat b/Task/Tree-traversal/Bracmat/tree-traversal.bracmat new file mode 100644 index 0000000000..cb5890b923 --- /dev/null +++ b/Task/Tree-traversal/Bracmat/tree-traversal.bracmat @@ -0,0 +1,41 @@ +( + ( tree + = 1 + . (2.(4.7.) (5.)) + (3.6.(8.) (9.)) + ) +& ( preorder + = K sub + . !arg:(?K.?sub) ?arg + & !K preorder$!sub preorder$!arg + | + ) +& out$("preorder: " preorder$!tree) +& ( inorder + = K lhs rhs + . !arg:(?K.?sub) ?arg + & ( !sub:%?lhs ?rhs + & inorder$!lhs !K inorder$!rhs inorder$!arg + | !K + ) + ) +& out$("inorder: " inorder$!tree) +& ( postorder + = K sub + . !arg:(?K.?sub) ?arg + & postorder$!sub !K postorder$!arg + | + ) +& out$("postorder: " postorder$!tree) +& ( levelorder + = todo tree sub + . !arg:(.)& + | !arg:(?tree.?todo) + & ( !tree:(?K.?sub) ?tree + & !K levelorder$(!tree.!todo !sub) + | levelorder$(!todo.) + ) + ) +& out$("level-order:" levelorder$(!tree.)) +& +) diff --git a/Task/Tree-traversal/C++/tree-traversal.cpp b/Task/Tree-traversal/C++/tree-traversal.cpp new file mode 100644 index 0000000000..30be104010 --- /dev/null +++ b/Task/Tree-traversal/C++/tree-traversal.cpp @@ -0,0 +1,94 @@ +#include +#include +#include + +template +class TreeNode { +public: + TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) + : mValue(n), + mLeft(left), + mRight(right) {} + + T getValue() const { + return mValue; + } + + TreeNode* left() const { + return mLeft.get(); + } + + TreeNode* right() const { + return mRight.get(); + } + + void preorderTraverse() const { + std::cout << " " << getValue(); + if(mLeft) { mLeft->preorderTraverse(); } + if(mRight) { mRight->preorderTraverse(); } + } + + void inorderTraverse() const { + if(mLeft) { mLeft->inorderTraverse(); } + std::cout << " " << getValue(); + if(mRight) { mRight->inorderTraverse(); } + } + + void postorderTraverse() const { + if(mLeft) { mLeft->postorderTraverse(); } + if(mRight) { mRight->postorderTraverse(); } + std::cout << " " << getValue(); + } + + void levelorderTraverse() const { + std::queue q; + q.push(this); + + while(!q.empty()) { + const TreeNode* n = q.front(); + q.pop(); + std::cout << " " << n->getValue(); + + if(n->left()) { q.push(n->left()); } + if(n->right()) { q.push(n->right()); } + } + } + +protected: + T mValue; + boost::scoped_ptr mLeft; + boost::scoped_ptr mRight; + +private: + TreeNode(); +}; + +int main() { + TreeNode root(1, + new TreeNode(2, + new TreeNode(4, + new TreeNode(7)), + new TreeNode(5)), + new TreeNode(3, + new TreeNode(6, + new TreeNode(8), + new TreeNode(9)))); + + std::cout << "preorder: "; + root.preorderTraverse(); + std::cout << std::endl; + + std::cout << "inorder: "; + root.inorderTraverse(); + std::cout << std::endl; + + std::cout << "postorder: "; + root.postorderTraverse(); + std::cout << std::endl; + + std::cout << "level-order:"; + root.levelorderTraverse(); + std::cout << std::endl; + + return 0; +} diff --git a/Task/Tree-traversal/C-sharp/tree-traversal.cs b/Task/Tree-traversal/C-sharp/tree-traversal.cs new file mode 100644 index 0000000000..55f87e5148 --- /dev/null +++ b/Task/Tree-traversal/C-sharp/tree-traversal.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +class Node +{ + int Value; + Node Left; + Node Right; + + Node(int value = default(int), Node left = default(Node), Node right = default(Node)) + { + Value = value; + Left = left; + Right = right; + } + + IEnumerable Preorder() + { + yield return Value; + if (Left != null) + foreach (var value in Left.Preorder()) + yield return value; + if (Right != null) + foreach (var value in Right.Preorder()) + yield return value; + } + + IEnumerable Inorder() + { + if (Left != null) + foreach (var value in Left.Inorder()) + yield return value; + yield return Value; + if (Right != null) + foreach (var value in Right.Inorder()) + yield return value; + } + + IEnumerable Postorder() + { + if (Left != null) + foreach (var value in Left.Postorder()) + yield return value; + if (Right != null) + foreach (var value in Right.Postorder()) + yield return value; + yield return Value; + } + + IEnumerable LevelOrder() + { + var queue = new Queue(); + queue.Enqueue(this); + while (queue.Any()) + { + var node = queue.Dequeue(); + yield return node.Value; + if (node.Left != null) + queue.Enqueue(node.Left); + if (node.Right != null) + queue.Enqueue(node.Right); + } + } + + static void Main() + { + var tree = new Node(1, new Node(2, new Node(4, new Node(7)), new Node(5)), new Node(3, new Node(6, new Node(8), new Node(9)))); + foreach (var traversal in new Func>[] { tree.Preorder, tree.Inorder, tree.Postorder, tree.LevelOrder }) + Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal())); + } +} diff --git a/Task/Tree-traversal/C/tree-traversal.c b/Task/Tree-traversal/C/tree-traversal.c new file mode 100644 index 0000000000..2364ce4a51 --- /dev/null +++ b/Task/Tree-traversal/C/tree-traversal.c @@ -0,0 +1,146 @@ +#include +#include + +typedef struct node_s +{ + int value; + struct node_s* left; + struct node_s* right; +} *node; + +node tree(int v, node l, node r) +{ + node n = malloc(sizeof(struct node_s)); + n->value = v; + n->left = l; + n->right = r; + return n; +} + +void destroy_tree(node n) +{ + if (n->left) + destroy_tree(n->left); + if (n->right) + destroy_tree(n->right); + free(n); +} + +void preorder(node n, void (*f)(int)) +{ + f(n->value); + if (n->left) + preorder(n->left, f); + if (n->right) + preorder(n->right, f); +} + +void inorder(node n, void (*f)(int)) +{ + if (n->left) + inorder(n->left, f); + f(n->value); + if (n->right) + inorder(n->right, f); +} + +void postorder(node n, void (*f)(int)) +{ + if (n->left) + postorder(n->left, f); + if (n->right) + postorder(n->right, f); + f(n->value); +} + +/* helper queue for levelorder */ +typedef struct qnode_s +{ + struct qnode_s* next; + node value; +} *qnode; + +typedef struct { qnode begin, end; } queue; + +void enqueue(queue* q, node n) +{ + qnode node = malloc(sizeof(struct qnode_s)); + node->value = n; + node->next = 0; + if (q->end) + q->end->next = node; + else + q->begin = node; + q->end = node; +} + +node dequeue(queue* q) +{ + node tmp = q->begin->value; + qnode second = q->begin->next; + free(q->begin); + q->begin = second; + if (!q->begin) + q->end = 0; + return tmp; +} + +int queue_empty(queue* q) +{ + return !q->begin; +} + +void levelorder(node n, void(*f)(int)) +{ + queue nodequeue = {}; + enqueue(&nodequeue, n); + while (!queue_empty(&nodequeue)) + { + node next = dequeue(&nodequeue); + f(next->value); + if (next->left) + enqueue(&nodequeue, next->left); + if (next->right) + enqueue(&nodequeue, next->right); + } +} + +void print(int n) +{ + printf("%d ", n); +} + +int main() +{ + node n = tree(1, + tree(2, + tree(4, + tree(7, 0, 0), + 0), + tree(5, 0, 0)), + tree(3, + tree(6, + tree(8, 0, 0), + tree(9, 0, 0)), + 0)); + + printf("preorder: "); + preorder(n, print); + printf("\n"); + + printf("inorder: "); + inorder(n, print); + printf("\n"); + + printf("postorder: "); + postorder(n, print); + printf("\n"); + + printf("level-order: "); + levelorder(n, print); + printf("\n"); + + destroy_tree(n); + + return 0; +} diff --git a/Task/Tree-traversal/Clojure/tree-traversal.clj b/Task/Tree-traversal/Clojure/tree-traversal.clj new file mode 100644 index 0000000000..ed9a4b1faa --- /dev/null +++ b/Task/Tree-traversal/Clojure/tree-traversal.clj @@ -0,0 +1,44 @@ +(defn walk [node f order] + (when node + (doseq [o order] + (if (= o :visit) + (f (:val node)) + (walk (node o) f order))))) + +(defn preorder [node f] + (walk node f [:visit :left :right])) + +(defn inorder [node f] + (walk node f [:left :visit :right])) + +(defn postorder [node f] + (walk node f [:left :right :visit])) + +(defn queue [& xs] + (when (seq xs) + (apply conj clojure.lang.PersistentQueue/EMPTY xs))) + +(defn level-order [root f] + (loop [q (queue root)] + (when-not (empty? q) + (if-let [node (first q)] + (do + (f (:val node)) + (recur (conj (pop q) (:left node) (:right node)))) + (recur (pop q)))))) + +(defn vec-to-tree [t] + (if (vector? t) + (let [[val left right] t] + {:val val + :left (vec-to-tree left) + :right (vec-to-tree right)}) + t)) + +(let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]]) + fs '[preorder inorder postorder level-order] + pr-node #(print (format "%2d" %))] + (doseq [f fs] + (print (format "%-12s" (str f ":"))) + ((resolve f) tree pr-node) + (println))) diff --git a/Task/Tree-traversal/CoffeeScript/tree-traversal-1.coffeescript b/Task/Tree-traversal/CoffeeScript/tree-traversal-1.coffeescript new file mode 100644 index 0000000000..7853b5156d --- /dev/null +++ b/Task/Tree-traversal/CoffeeScript/tree-traversal-1.coffeescript @@ -0,0 +1,46 @@ +# In this example, we don't encapsulate binary trees as objects; instead, we have a +# convention on how to store them as arrays, and we namespace the functions that +# operate on those data structures. +binary_tree = + preorder: (tree, visit) -> + return unless tree? + [node, left, right] = tree + visit node + binary_tree.preorder left, visit + binary_tree.preorder right, visit + + inorder: (tree, visit) -> + return unless tree? + [node, left, right] = tree + binary_tree.inorder left, visit + visit node + binary_tree.inorder right, visit + + postorder: (tree, visit) -> + return unless tree? + [node, left, right] = tree + binary_tree.postorder left, visit + binary_tree.postorder right, visit + visit node + + levelorder: (tree, visit) -> + q = [] + q.push tree + while q.length > 0 + t = q.shift() + continue unless t? + [node, left, right] = t + visit node + q.push left + q.push right + +do -> + tree = [1, [2, [4, [7]], [5]], [3, [6, [8],[9]]]] + test_walk = (walk_function_name) -> + output = [] + binary_tree[walk_function_name] tree, output.push.bind(output) + console.log walk_function_name, output.join ' ' + test_walk "preorder" + test_walk "inorder" + test_walk "postorder" + test_walk "levelorder" diff --git a/Task/Tree-traversal/CoffeeScript/tree-traversal-2.coffeescript b/Task/Tree-traversal/CoffeeScript/tree-traversal-2.coffeescript new file mode 100644 index 0000000000..f71056d2a0 --- /dev/null +++ b/Task/Tree-traversal/CoffeeScript/tree-traversal-2.coffeescript @@ -0,0 +1,5 @@ +> coffee tree_traversal.coffee +preorder 1 2 4 7 5 3 6 8 9 +inorder 7 4 2 5 1 8 6 9 3 +postorder 7 4 5 2 8 9 6 3 1 +levelorder 1 2 3 4 5 6 7 8 9 diff --git a/Task/Tree-traversal/Common-Lisp/tree-traversal.lisp b/Task/Tree-traversal/Common-Lisp/tree-traversal.lisp new file mode 100644 index 0000000000..36bc07c04b --- /dev/null +++ b/Task/Tree-traversal/Common-Lisp/tree-traversal.lisp @@ -0,0 +1,38 @@ +(defun preorder (node f) + (when node + (funcall f (first node)) + (preorder (second node) f) + (preorder (third node) f))) + +(defun inorder (node f) + (when node + (inorder (second node) f) + (funcall f (first node)) + (inorder (third node) f))) + +(defun postorder (node f) + (when node + (postorder (second node) f) + (postorder (third node) f) + (funcall f (first node)))) + +(defun level-order (node f) + (loop with level = (list node) + while level + do + (setf level (loop for node in level + when node + do (funcall f (first node)) + and collect (second node) + and collect (third node))))) + +(defparameter *tree* '(1 (2 (4 (7)) + (5)) + (3 (6 (8) + (9))))) + +(defun show (traversal-function) + (format t "~&~(~A~):~12,0T" traversal-function) + (funcall traversal-function *tree* (lambda (value) (format t " ~A" value)))) + +(map nil #'show '(preorder inorder postorder level-order)) diff --git a/Task/Tree-traversal/D/tree-traversal-1.d b/Task/Tree-traversal/D/tree-traversal-1.d new file mode 100644 index 0000000000..ce2bd1d627 --- /dev/null +++ b/Task/Tree-traversal/D/tree-traversal-1.d @@ -0,0 +1,84 @@ +import std.stdio; + +const class Node(T) { + T data; + Node left, right; + + this(in T data, in Node left=null, in Node right=null) + pure nothrow { + this.data = data; + this.left = left; + this.right = right; + } +} + +// static templated opCall can't be used in Node +auto node(T)(in T data, in Node!T left=null, in Node!T right=null) +pure nothrow { + return new Node!T(data, left, right); +} + +void show(T)(in T x) { + write(x, " "); +} + +enum Visit { pre, inv, post } + +// visitor can be any kind of callable or it uses a default visitor. +// TNode can be any kind of Node, with data, left and right fields, +// so this is more generic than a member function of Node. +void backtrackingOrder(Visit v, TNode, TyF=void*) + (in TNode node, TyF visitor=null) { + static if (is(TyF == void*)) + auto trueVisitor = &show!(typeof(node.data)); + else + auto trueVisitor = visitor; + if (node !is null) { + static if (v == Visit.pre) + trueVisitor(node.data); + backtrackingOrder!v(node.left, visitor); + static if (v == Visit.inv) + trueVisitor(node.data); + backtrackingOrder!v(node.right, visitor); + static if (v == Visit.post) + trueVisitor(node.data); + } +} + +void levelOrder(TNode, TyF=void*) + (TNode node, TyF visitor=null, + const(TNode)[] more=[]) { + static if (is(TyF == void*)) + auto trueVisitor = &show!(typeof(node.data)); + else + auto trueVisitor = visitor; + if (node !is null) { + more ~= [node.left, node.right]; + trueVisitor(node.data); + } + if (more.length) + levelOrder(more[0], trueVisitor, more[1 .. $]); +} + +void main() { + alias node N; + auto tree = N(1, + N(2, + N(4, + N(7)), + N(5)), + N(3, + N(6, + N(8), + N(9)))); + + write(" preOrder: "); + backtrackingOrder!(Visit.pre)(tree); + write("\n inorder: "); + backtrackingOrder!(Visit.inv)(tree); + write("\n postOrder: "); + backtrackingOrder!(Visit.post)(tree); + write("\nlevelorder: "); + levelOrder(tree); + writeln(); +} diff --git a/Task/Tree-traversal/D/tree-traversal-2.d b/Task/Tree-traversal/D/tree-traversal-2.d new file mode 100644 index 0000000000..706b2d3cda --- /dev/null +++ b/Task/Tree-traversal/D/tree-traversal-2.d @@ -0,0 +1,44 @@ +const struct Node(T) { + T v; + Node* l, r; +} + +T[] preOrder(T)(in Node!T* t) pure nothrow { + return t ? t.v ~ preOrder(t.l) ~ preOrder(t.r) : []; +} + +T[] inOrder(T)(in Node!T* t) pure nothrow { + return t ? inOrder(t.l) ~ t.v ~ inOrder(t.r) : []; +} + +T[] postOrder(T)(in Node!T* t) pure nothrow { + return t ? postOrder(t.l) ~ postOrder(t.r) ~ t.v : []; +} + +T[] levelOrder(T)(in Node!T* t) pure nothrow { + static T[] loop(in Node!T*[] a) pure nothrow { + if (!a.length) return []; + if (!a[0]) return loop(a[1 .. $]); + return a[0].v ~ loop(a[1 .. $] ~ [a[0].l, a[0].r]); + } + return loop([t]); +} + +void main() { + alias N = Node!int; + auto tree = new N(1, + new N(2, + new N(4, + new N(7)), + new N(5)), + new N(3, + new N(6, + new N(8), + new N(9)))); + + import std.stdio; + writeln(preOrder(tree)); + writeln(inOrder(tree)); + writeln(postOrder(tree)); + writeln(levelOrder(tree)); +} diff --git a/Task/Tree-traversal/E/tree-traversal.e b/Task/Tree-traversal/E/tree-traversal.e new file mode 100644 index 0000000000..fa31d9e8a5 --- /dev/null +++ b/Task/Tree-traversal/E/tree-traversal.e @@ -0,0 +1,47 @@ +def btree := [1, [2, [4, [7, null, null], + null], + [5, null, null]], + [3, [6, [8, null, null], + [9, null, null]], + null]] + +def backtrackingOrder(node, pre, mid, post) { + switch (node) { + match ==null {} + match [value, left, right] { + pre(value) + backtrackingOrder(left, pre, mid, post) + mid(value) + backtrackingOrder(right, pre, mid, post) + post(value) + } + } +} + +def levelOrder(root, func) { + var level := [root].diverge() + while (level.size() > 0) { + for node in level.removeRun(0) { + switch (node) { + match ==null {} + match [value, left, right] { + func(value) + level.push(left) + level.push(right) +} } } } } + +print("preorder: ") +backtrackingOrder(btree, fn v { print(" ", v) }, fn _ {}, fn _ {}) +println() + +print("inorder: ") +backtrackingOrder(btree, fn _ {}, fn v { print(" ", v) }, fn _ {}) +println() + +print("postorder: ") +backtrackingOrder(btree, fn _ {}, fn _ {}, fn v { print(" ", v) }) +println() + +print("level-order:") +levelOrder(btree, fn v { print(" ", v) }) +println() diff --git a/Task/Tree-traversal/Elisa/tree-traversal-1.elisa b/Task/Tree-traversal/Elisa/tree-traversal-1.elisa new file mode 100644 index 0000000000..05a6f02ec2 --- /dev/null +++ b/Task/Tree-traversal/Elisa/tree-traversal-1.elisa @@ -0,0 +1,36 @@ +component BinaryTreeTraversals (Tree, Element); +type Tree; +type Node = Tree; + Tree (LeftTree = Tree, Element, RightTree = Tree) -> Tree; + Leaf (Element) -> Node; + Node (Tree) -> Node; + Item (Node) -> Element; + + Preorder (Tree) -> multi (Node); + Inorder (Tree) -> multi (Node); + Postorder (Tree) -> multi (Node); + Level_order(Tree) -> multi (Node); +begin + Tree (Lefttree, Item, Righttree) = Tree: [ Lefttree; Item; Righttree ]; + Leaf (anItem) = Tree (null(Tree), anItem, null(Tree) ); + Node (aTree) = aTree; + Item (aNode) = aNode.Item; + + Preorder (=null(Tree)) = no(Tree); + Preorder (T) = ( T, Preorder (T.Lefttree), Preorder (T.Righttree)); + + Inorder (=null(Tree)) = no(Tree); + Inorder (T) = ( Inorder (T.Lefttree), T, Inorder (T.Righttree)); + + Postorder (=null(Tree)) = no(Tree); + Postorder (T) = ( Postorder (T.Lefttree), Postorder (T.Righttree), T); + + Level_order(T) = [ Queue = {T}; + node = Tree:items(Queue); + [ result(node); + add(Queue, node.Lefttree) when valid(node.Lefttree); + add(Queue, node.Righttree) when valid(node.Righttree); + ]; + no(Tree); + ]; +end component BinaryTreeTraversals; diff --git a/Task/Tree-traversal/Elisa/tree-traversal-2.elisa b/Task/Tree-traversal/Elisa/tree-traversal-2.elisa new file mode 100644 index 0000000000..f8ef1decee --- /dev/null +++ b/Task/Tree-traversal/Elisa/tree-traversal-2.elisa @@ -0,0 +1,19 @@ +use BinaryTreeTraversals (Tree, integer); + +BT = Tree( + Tree( + Tree(Leaf(7), 4, null(Tree)), 2 , Leaf(5)), 1, + Tree( + Tree(Leaf(8), 6, Leaf(9)), 3 ,null(Tree))); + +{Item(Preorder(BT))}? +{ 1, 2, 4, 7, 5, 3, 6, 8, 9} + +{Item(Inorder(BT))}? +{ 7, 4, 2, 5, 1, 8, 6, 9, 3} + +{Item(Postorder(BT))}? +{ 7, 4, 5, 2, 8, 9, 6, 3, 1} + +{Item(Level_order(BT))}? +{ 1, 2, 3, 4, 5, 6, 7, 8, 9} diff --git a/Task/Tree-traversal/Erlang/tree-traversal.erl b/Task/Tree-traversal/Erlang/tree-traversal.erl new file mode 100644 index 0000000000..dc17e95a98 --- /dev/null +++ b/Task/Tree-traversal/Erlang/tree-traversal.erl @@ -0,0 +1,42 @@ +-module(tree_traversal). +-export([main/0]). +-export([preorder/2, inorder/2, postorder/2, levelorder/2]). +-export([tnode/0, tnode/1, tnode/3]). + +-define(NEWLINE, io:format("~n")). + +tnode() -> {}. +tnode(V) -> {node, V, {}, {}}. +tnode(V,L,R) -> {node, V, L, R}. + +preorder(_,{}) -> ok; +preorder(F,{node,V,L,R}) -> + F(V), preorder(F,L), preorder(F,R). + +inorder(_,{}) -> ok; +inorder(F,{node,V,L,R}) -> + inorder(F,L), F(V), inorder(F,R). + +postorder(_,{}) -> ok; +postorder(F,{node,V,L,R}) -> + postorder(F,L), postorder(F,R), F(V). + +levelorder(_, []) -> []; +levelorder(F, [{}|T]) -> levelorder(F, T); +levelorder(F, [{node,V,L,R}|T]) -> + F(V), levelorder(F, T++[L,R]); +levelorder(F, X) -> levelorder(F, [X]). + +main() -> + Tree = tnode(1, + tnode(2, + tnode(4, tnode(7), tnode()), + tnode(5, tnode(), tnode())), + tnode(3, + tnode(6, tnode(8), tnode(9)), + tnode())), + F = fun(X) -> io:format("~p ",[X]) end, + preorder(F, Tree), ?NEWLINE, + inorder(F, Tree), ?NEWLINE, + postorder(F, Tree), ?NEWLINE, + levelorder(F, Tree), ?NEWLINE. diff --git a/Task/Tree-traversal/Euphoria/tree-traversal.euphoria b/Task/Tree-traversal/Euphoria/tree-traversal.euphoria new file mode 100644 index 0000000000..cf1c4e48ee --- /dev/null +++ b/Task/Tree-traversal/Euphoria/tree-traversal.euphoria @@ -0,0 +1,67 @@ +constant VALUE = 1, LEFT = 2, RIGHT = 3 + +constant tree = {1, + {2, + {4, + {7, 0, 0}, + 0}, + {5, 0, 0}}, + {3, + {6, + {8, 0, 0}, + {9, 0, 0}}, + 0}} + +procedure preorder(object tree) + if sequence(tree) then + printf(1,"%d ",{tree[VALUE]}) + preorder(tree[LEFT]) + preorder(tree[RIGHT]) + end if +end procedure + +procedure inorder(object tree) + if sequence(tree) then + inorder(tree[LEFT]) + printf(1,"%d ",{tree[VALUE]}) + inorder(tree[RIGHT]) + end if +end procedure + +procedure postorder(object tree) + if sequence(tree) then + postorder(tree[LEFT]) + postorder(tree[RIGHT]) + printf(1,"%d ",{tree[VALUE]}) + end if +end procedure + +procedure lo(object tree, sequence more) + if sequence(tree) then + more &= {tree[LEFT],tree[RIGHT]} + printf(1,"%d ",{tree[VALUE]}) + end if + if length(more) > 0 then + lo(more[1],more[2..$]) + end if +end procedure + +procedure level_order(object tree) + lo(tree,{}) +end procedure + +puts(1,"preorder: ") +preorder(tree) +puts(1,'\n') + +puts(1,"inorder: ") +inorder(tree) +puts(1,'\n') + +puts(1,"postorder: ") +postorder(tree) +puts(1,'\n') + +puts(1,"level-order: ") +level_order(tree) +puts(1,'\n') diff --git a/Task/Tree-traversal/Factor/tree-traversal.factor b/Task/Tree-traversal/Factor/tree-traversal.factor new file mode 100644 index 0000000000..bfded9c947 --- /dev/null +++ b/Task/Tree-traversal/Factor/tree-traversal.factor @@ -0,0 +1,72 @@ +USING: accessors combinators deques dlists fry io kernel +math.parser ; +IN: rosetta.tree-traversal + +TUPLE: node data left right ; + +CONSTANT: example-tree + T{ node f 1 + T{ node f 2 + T{ node f 4 + T{ node f 7 f f } + f + } + T{ node f 5 f f } + } + T{ node f 3 + T{ node f 6 + T{ node f 8 f f } + T{ node f 9 f f } + } + f + } + } + +: preorder ( node quot: ( data -- ) -- ) + [ [ data>> ] dip call ] + [ [ left>> ] dip over [ preorder ] [ 2drop ] if ] + [ [ right>> ] dip over [ preorder ] [ 2drop ] if ] + 2tri ; inline recursive + +: inorder ( node quot: ( data -- ) -- ) + [ [ left>> ] dip over [ inorder ] [ 2drop ] if ] + [ [ data>> ] dip call ] + [ [ right>> ] dip over [ inorder ] [ 2drop ] if ] + 2tri ; inline recursive + +: postorder ( node quot: ( data -- ) -- ) + [ [ left>> ] dip over [ postorder ] [ 2drop ] if ] + [ [ right>> ] dip over [ postorder ] [ 2drop ] if ] + [ [ data>> ] dip call ] + 2tri ; inline recursive + +: (levelorder) ( dlist quot: ( data -- ) -- ) + over deque-empty? [ 2drop ] [ + [ dup pop-front ] dip { + [ [ data>> ] dip call drop ] + [ drop left>> [ swap push-back ] [ drop ] if* ] + [ drop right>> [ swap push-back ] [ drop ] if* ] + [ nip (levelorder) ] + } 3cleave + ] if ; inline recursive + +: levelorder ( node quot: ( data -- ) -- ) + [ 1dlist ] dip (levelorder) ; inline + +: levelorder2 ( node quot: ( data -- ) -- ) + [ 1dlist ] dip + [ dup deque-empty? not ] swap '[ + dup pop-front + [ data>> @ ] + [ left>> [ over push-back ] when* ] + [ right>> [ over push-back ] when* ] tri + ] while drop ; inline + +: main ( -- ) + example-tree [ number>string write " " write ] { + [ "preorder: " write preorder nl ] + [ "inorder: " write inorder nl ] + [ "postorder: " write postorder nl ] + [ "levelorder: " write levelorder nl ] + [ "levelorder2: " write levelorder2 nl ] + } 2cleave ; diff --git a/Task/Tree-traversal/Fantom/tree-traversal.fantom b/Task/Tree-traversal/Fantom/tree-traversal.fantom new file mode 100644 index 0000000000..670b07c3af --- /dev/null +++ b/Task/Tree-traversal/Fantom/tree-traversal.fantom @@ -0,0 +1,69 @@ +class Tree +{ + readonly Int label + readonly Tree? left + readonly Tree? right + + new make (Int label, Tree? left := null, Tree? right := null) + { + this.label = label + this.left = left + this.right = right + } + + Void preorder(|Int->Void| func) + { + func(label) + left?.preorder(func) // ?. will not call method if 'left' is null + right?.preorder(func) + } + + Void postorder(|Int->Void| func) + { + left?.postorder(func) + right?.postorder(func) + func(label) + } + + Void inorder(|Int->Void| func) + { + left?.inorder(func) + func(label) + right?.inorder(func) + } + + Void levelorder(|Int->Void| func) + { + Tree[] nodes := [this] + while (nodes.size > 0) + { + Tree cur := nodes.removeAt(0) + func(cur.label) + if (cur.left != null) nodes.add (cur.left) + if (cur.right != null) nodes.add (cur.right) + } + } +} + +class Main +{ + public static Void main () + { + tree := Tree(1, + Tree(2, Tree(4, Tree(7)), Tree(5)), + Tree(3, Tree(6, Tree(8), Tree(9)))) + List result := [,] + collect := |Int a -> Void| { result.add(a) } + tree.preorder(collect) + echo ("preorder: " + result.join(" ")) + result = [,] + tree.inorder(collect) + echo ("inorder: " + result.join(" ")) + result = [,] + tree.postorder(collect) + echo ("postorder: " + result.join(" ")) + result = [,] + tree.levelorder(collect) + echo ("levelorder: " + result.join(" ")) + } +} diff --git a/Task/Tree-traversal/Forth/tree-traversal.fth b/Task/Tree-traversal/Forth/tree-traversal.fth new file mode 100644 index 0000000000..8c38631b4d --- /dev/null +++ b/Task/Tree-traversal/Forth/tree-traversal.fth @@ -0,0 +1,56 @@ +\ binary tree (dictionary) +: node ( l r data -- node ) here >r , , , r> ; +: leaf ( data -- node ) 0 0 rot node ; + +: >data ( node -- ) @ ; +: >right ( node -- ) cell+ @ ; +: >left ( node -- ) cell+ cell+ @ ; + +: preorder ( xt tree -- ) + dup 0= if 2drop exit then + 2dup >data swap execute + 2dup >left recurse + >right recurse ; + +: inorder ( xt tree -- ) + dup 0= if 2drop exit then + 2dup >left recurse + 2dup >data swap execute + >right recurse ; + +: postorder ( xt tree -- ) + dup 0= if 2drop exit then + 2dup >left recurse + 2dup >right recurse + >data swap execute ; + +: max-depth ( tree -- n ) + dup 0= if exit then + dup >left recurse + swap >right recurse max 1+ ; + +defer depthaction +: depthorder ( depth tree -- ) + dup 0= if 2drop exit then + over 0= + if >data depthaction drop + else over 1- over >left recurse + swap 1- swap >right recurse + then ; + +: levelorder ( xt tree -- ) + swap is depthaction + dup max-depth 0 ?do + i over depthorder + loop drop ; + +7 leaf 0 4 node + 5 leaf 2 node +8 leaf 9 leaf 6 node + 0 3 node 1 node value tree + +cr ' . tree preorder \ 1 2 4 7 5 3 6 8 9 +cr ' . tree inorder \ 7 4 2 5 1 8 6 9 3 +cr ' . tree postorder \ 7 4 5 2 8 9 6 3 1 +cr tree max-depth . \ 4 +cr ' . tree levelorder \ 1 2 3 4 5 6 7 8 9 diff --git a/Task/Tree-traversal/Go/tree-traversal-1.go b/Task/Tree-traversal/Go/tree-traversal-1.go new file mode 100644 index 0000000000..1ce6f97da5 --- /dev/null +++ b/Task/Tree-traversal/Go/tree-traversal-1.go @@ -0,0 +1,86 @@ +package main + +import "fmt" + +type node struct { + value int + left, right *node +} + +func (n *node) iterPreorder(visit func(int)) { + if n == nil { + return + } + visit(n.value) + n.left.iterPreorder(visit) + n.right.iterPreorder(visit) +} + +func (n *node) iterInorder(visit func(int)) { + if n == nil { + return + } + n.left.iterInorder(visit) + visit(n.value) + n.right.iterInorder(visit) +} + +func (n *node) iterPostorder(visit func(int)) { + if n == nil { + return + } + n.left.iterPostorder(visit) + n.right.iterPostorder(visit) + visit(n.value) +} + +func (n *node) iterLevelorder(visit func(int)) { + if n == nil { + return + } + for queue := []*node{n}; ; { + n = queue[0] + visit(n.value) + copy(queue, queue[1:]) + queue = queue[:len(queue)-1] + if n.left != nil { + queue = append(queue, n.left) + } + if n.right != nil { + queue = append(queue, n.right) + } + if len(queue) == 0 { + return + } + } +} + +func main() { + tree := &node{1, + &node{2, + &node{4, + &node{7, nil, nil}, + nil}, + &node{5, nil, nil}}, + &node{3, + &node{6, + &node{8, nil, nil}, + &node{9, nil, nil}}, + nil}} + fmt.Print("preorder: ") + tree.iterPreorder(visitor) + fmt.Println() + fmt.Print("inorder: ") + tree.iterInorder(visitor) + fmt.Println() + fmt.Print("postorder: ") + tree.iterPostorder(visitor) + fmt.Println() + fmt.Print("level-order: ") + tree.iterLevelorder(visitor) + fmt.Println() +} + +func visitor(value int) { + fmt.Print(value, " ") +} diff --git a/Task/Tree-traversal/Go/tree-traversal-2.go b/Task/Tree-traversal/Go/tree-traversal-2.go new file mode 100644 index 0000000000..0077bcf944 --- /dev/null +++ b/Task/Tree-traversal/Go/tree-traversal-2.go @@ -0,0 +1,71 @@ +package main + +import "fmt" + +// flat, level-order representation. +// for node at index k, left child has index 2k, right child has index 2k+1. +// a value of -1 means the node does not exist. +type tree []int + +func main() { + t := tree{1, 2, 3, 4, 5, 6, -1, 7, -1, -1, -1, 8, 9} + visitor := func(n int) { + fmt.Print(n, " ") + } + fmt.Print("preorder: ") + t.iterPreorder(visitor) + fmt.Print("\ninorder: ") + t.iterInorder(visitor) + fmt.Print("\npostorder: ") + t.iterPostorder(visitor) + fmt.Print("\nlevel-order: ") + t.iterLevelorder(visitor) + fmt.Println() +} + +func (t tree) iterPreorder(visit func(int)) { + var traverse func(int) + traverse = func(k int) { + if k >= len(t) || t[k] == -1 { + return + } + visit(t[k]) + traverse(2*k + 1) + traverse(2*k + 2) + } + traverse(0) +} + +func (t tree) iterInorder(visit func(int)) { + var traverse func(int) + traverse = func(k int) { + if k >= len(t) || t[k] == -1 { + return + } + traverse(2*k + 1) + visit(t[k]) + traverse(2*k + 2) + } + traverse(0) +} + +func (t tree) iterPostorder(visit func(int)) { + var traverse func(int) + traverse = func(k int) { + if k >= len(t) || t[k] == -1 { + return + } + traverse(2*k + 1) + traverse(2*k + 2) + visit(t[k]) + } + traverse(0) +} + +func (t tree) iterLevelorder(visit func(int)) { + for _, n := range t { + if n != -1 { + visit(n) + } + } +} diff --git a/Task/Tree-traversal/Groovy/tree-traversal-1.groovy b/Task/Tree-traversal/Groovy/tree-traversal-1.groovy new file mode 100644 index 0000000000..cfbb0bbed2 --- /dev/null +++ b/Task/Tree-traversal/Groovy/tree-traversal-1.groovy @@ -0,0 +1,35 @@ +def preorder; +preorder = { Node node -> + ([node] + node.children().collect { preorder(it) }).flatten() +} + +def postorder; +postorder = { Node node -> + (node.children().collect { postorder(it) } + [node]).flatten() +} + +def inorder; +inorder = { Node node -> + def kids = node.children() + if (kids.empty) [node] + else if (kids.size() == 1 && kids[0].'@right') [node] + inorder(kids[0]) + else inorder(kids[0]) + [node] + (kids.size()>1 ? inorder(kids[1]) : []) +} + +def levelorder = { Node node -> + def nodeList = [] + def level = [node] + while (!level.empty) { + nodeList += level + def nextLevel = level.collect { it.children() }.flatten() + level = nextLevel + } + nodeList +} + +class BinaryNodeBuilder extends NodeBuilder { + protected Object postNodeCompletion(Object parent, Object node) { + assert node.children().size() < 3 + node + } +} diff --git a/Task/Tree-traversal/Groovy/tree-traversal-2.groovy b/Task/Tree-traversal/Groovy/tree-traversal-2.groovy new file mode 100644 index 0000000000..e7db86ed77 --- /dev/null +++ b/Task/Tree-traversal/Groovy/tree-traversal-2.groovy @@ -0,0 +1,10 @@ +try { + new BinaryNodeBuilder().'1' { + a {} + b {} + c {} + } + println 'not limited to binary tree\r\n' +} catch (org.codehaus.groovy.transform.powerassert.PowerAssertionError e) { + println 'limited to binary tree\r\n' +} diff --git a/Task/Tree-traversal/Groovy/tree-traversal-3.groovy b/Task/Tree-traversal/Groovy/tree-traversal-3.groovy new file mode 100644 index 0000000000..13280f520e --- /dev/null +++ b/Task/Tree-traversal/Groovy/tree-traversal-3.groovy @@ -0,0 +1,17 @@ +// 1 +// / \ +// 2 3 +// / \ / +// 4 5 6 +// / / \ +// 7 8 9 +def tree1 = new BinaryNodeBuilder(). +'1' { + '2' { + '4' { '7' {} } + '5' {} + } + '3' { + '6' { '8' {}; '9' {} } + } +} diff --git a/Task/Tree-traversal/Groovy/tree-traversal-4.groovy b/Task/Tree-traversal/Groovy/tree-traversal-4.groovy new file mode 100644 index 0000000000..8484372a2e --- /dev/null +++ b/Task/Tree-traversal/Groovy/tree-traversal-4.groovy @@ -0,0 +1,17 @@ +// 1 +// / \ +// 2 3 +// / \ / +// 4 5 6 +// \ / \ +// 7 8 9 +def tree2 = new BinaryNodeBuilder(). +'1' { + '2' { + '4' { '7'(right:true) {} } + '5' {} + } + '3' { + '6' { '8' {}; '9' {} } + } +} diff --git a/Task/Tree-traversal/Groovy/tree-traversal-5.groovy b/Task/Tree-traversal/Groovy/tree-traversal-5.groovy new file mode 100644 index 0000000000..aed0eb018d --- /dev/null +++ b/Task/Tree-traversal/Groovy/tree-traversal-5.groovy @@ -0,0 +1,15 @@ +def test = { tree -> + println "preorder: ${preorder(tree).collect{it.name()}}" + println "preorder: ${tree.depthFirst().collect{it.name()}}" + + println "postorder: ${postorder(tree).collect{it.name()}}" + + println "inorder: ${inorder(tree).collect{it.name()}}" + + println "level-order: ${levelorder(tree).collect{it.name()}}" + println "level-order: ${tree.breadthFirst().collect{it.name()}}" + + println() +} +test(tree1) +test(tree2) diff --git a/Task/Tree-traversal/Haskell/tree-traversal.hs b/Task/Tree-traversal/Haskell/tree-traversal.hs new file mode 100644 index 0000000000..731787ea54 --- /dev/null +++ b/Task/Tree-traversal/Haskell/tree-traversal.hs @@ -0,0 +1,45 @@ +data Tree a = Empty + | Node { value :: a, + left :: Tree a, + right :: Tree a } + +preorder, inorder, postorder, levelorder :: Tree a -> [a] + +preorder Empty = [] +preorder (Node v l r) = [v] + ++ preorder l + ++ preorder r + +inorder Empty = [] +inorder (Node v l r) = inorder l + ++ [v] + ++ inorder r + +postorder Empty = [] +postorder (Node v l r) = postorder l + ++ postorder r + ++ [v] + +levelorder x = loop [x] + where loop [] = [] + loop (Empty : xs) = loop xs + loop (Node v l r : xs) = v : loop (xs ++ [l,r]) + +tree :: Tree Int +tree = Node 1 + (Node 2 + (Node 4 + (Node 7 Empty Empty) + Empty) + (Node 5 Empty Empty)) + (Node 3 + (Node 6 + (Node 8 Empty Empty) + (Node 9 Empty Empty)) + Empty) + +main :: IO () +main = do print $ preorder tree + print $ inorder tree + print $ postorder tree + print $ levelorder tree diff --git a/Task/Tree-traversal/Icon/tree-traversal.icon b/Task/Tree-traversal/Icon/tree-traversal.icon new file mode 100644 index 0000000000..b4bcfcb7a2 --- /dev/null +++ b/Task/Tree-traversal/Icon/tree-traversal.icon @@ -0,0 +1,32 @@ +procedure main() + bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] + showTree(bTree, preorder|inorder|postorder|levelorder) +end + +procedure showTree(tree, f) + writes(image(f),":\t") + every writes(" ",f(tree)[1]) + write() +end + +procedure preorder(L) + if \L then suspend L | preorder(L[2|3]) +end + +procedure inorder(L) + if \L then suspend inorder(L[2]) | L | inorder(L[3]) +end + +procedure postorder(L) + if \L then suspend postorder(L[2|3]) | L +end + +procedure levelorder(L) + if \L then { + queue := [L] + while nextnode := get(queue) do { + every put(queue, \nextnode[2|3]) + suspend nextnode + } + } +end diff --git a/Task/Tree-traversal/J/tree-traversal-1.j b/Task/Tree-traversal/J/tree-traversal-1.j new file mode 100644 index 0000000000..0607864765 --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-1.j @@ -0,0 +1,4 @@ +preorder=: ]S:0 +postorder=: ([:; postorder&.>@}.) , >@{. +levelorder=: ;@({::L:1 _~ [: (/: #@>) @(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}. diff --git a/Task/Tree-traversal/J/tree-traversal-2.j b/Task/Tree-traversal/J/tree-traversal-2.j new file mode 100644 index 0000000000..9843462465 --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-2.j @@ -0,0 +1,5 @@ +N2=: conjunction def '( + { + public Node left; + public Node right; + public T data; + public Node(T data) + { + this.data = data; + } + public Node getLeft() + { + return this.left; + } + public void setLeft(Node left) + { + this.left = left; + } + public Node getRight() + { + return this.right; + } + public void setRight(Node right) + { + this.right = right; + } + } + public static void preorder(Node n) + { + if (n != null) + { + System.out.print(n.data + " "); + preorder(n.getLeft()); + preorder(n.getRight()); + } + } + public static void inorder(Node n) + { + if (n != null) + { + inorder(n.getLeft()); + System.out.print(n.data + " "); + inorder(n.getRight()); + } + } + public static void postorder(Node n) + { + if (n != null) + { + postorder(n.getLeft()); + postorder(n.getRight()); + System.out.print(n.data + " "); + } + } + public static void levelorder(Node n) + { + Queue> nodequeue = new LinkedList>(); + if (n != null) + nodequeue.add(n); + while (!nodequeue.isEmpty()) + { + Node next = nodequeue.remove(); + System.out.print(next.data + " "); + if (next.getLeft() != null) + { + nodequeue.add(next.getLeft()); + } + if (next.getRight() != null) + { + nodequeue.add(next.getRight()); + } + } + } + public static void main(final String[] args) + { + Node one = new Node(1); + Node two = new Node(2); + Node three = new Node(3); + Node four = new Node(4); + Node five = new Node(5); + Node six = new Node(6); + Node seven = new Node(7); + Node eight = new Node(8); + Node nine = new Node(9); + one.setLeft(two); + one.setRight(three); + two.setLeft(four); + two.setRight(five); + three.setLeft(six); + four.setLeft(seven); + six.setLeft(eight); + six.setRight(nine); + preorder(one); + System.out.println(); + inorder(one); + System.out.println(); + postorder(one); + System.out.println(); + levelorder(one); + System.out.println(); + } +} diff --git a/Task/Tree-traversal/JavaScript/tree-traversal.js b/Task/Tree-traversal/JavaScript/tree-traversal.js new file mode 100644 index 0000000000..3346bf4fa5 --- /dev/null +++ b/Task/Tree-traversal/JavaScript/tree-traversal.js @@ -0,0 +1,40 @@ +function BinaryTree(value, left, right) { + this.value = value; + this.left = left; + this.right = right; +} +BinaryTree.prototype.preorder = function(f) {this.walk(f,['this','left','right'])} +BinaryTree.prototype.inorder = function(f) {this.walk(f,['left','this','right'])} +BinaryTree.prototype.postorder = function(f) {this.walk(f,['left','right','this'])} +BinaryTree.prototype.walk = function(func, order) { + for (var i in order) + switch (order[i]) { + case "this": func(this.value); break; + case "left": if (this.left) this.left.walk(func, order); break; + case "right": if (this.right) this.right.walk(func, order); break; + } +} +BinaryTree.prototype.levelorder = function(func) { + var queue = [this]; + while (queue.length != 0) { + var node = queue.shift(); + func(node.value); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } +} + +// convenience function for creating a binary tree +function createBinaryTreeFromArray(ary) { + var left = null, right = null; + if (ary[1]) left = createBinaryTreeFromArray(ary[1]); + if (ary[2]) right = createBinaryTreeFromArray(ary[2]); + return new BinaryTree(ary[0], left, right); +} + +var tree = createBinaryTreeFromArray([1, [2, [4, [7]], [5]], [3, [6, [8],[9]]]]); + +print("*** preorder ***"); tree.preorder(print); +print("*** inorder ***"); tree.inorder(print); +print("*** postorder ***"); tree.postorder(print); +print("*** levelorder ***"); tree.levelorder(print); diff --git a/Task/Tree-traversal/Logo/tree-traversal.logo b/Task/Tree-traversal/Logo/tree-traversal.logo new file mode 100644 index 0000000000..4d0407498b --- /dev/null +++ b/Task/Tree-traversal/Logo/tree-traversal.logo @@ -0,0 +1,57 @@ +; nodes are [data left right], use "first" to get data + +to node.left :node + if empty? butfirst :node [output []] + output first butfirst :node +end +to node.right :node + if empty? butfirst :node [output []] + if empty? butfirst butfirst :node [output []] + output first butfirst butfirst :node +end +to max :a :b + output ifelse :a > :b [:a] [:b] +end +to tree.depth :tree + if empty? :tree [output 0] + output 1 + max tree.depth node.left :tree tree.depth node.right :tree +end + +to pre.order :tree :action + if empty? :tree [stop] + invoke :action first :tree + pre.order node.left :tree :action + pre.order node.right :tree :action +end +to in.order :tree :action + if empty? :tree [stop] + in.order node.left :tree :action + invoke :action first :tree + in.order node.right :tree :action +end +to post.order :tree :action + if empty? :tree [stop] + post.order node.left :tree :action + post.order node.right :tree :action + invoke :action first :tree +end +to at.depth :n :tree :action + if empty? :tree [stop] + ifelse :n = 1 [invoke :action first :tree] [ + at.depth :n-1 node.left :tree :action + at.depth :n-1 node.right :tree :action + ] +end +to level.order :tree :action + for [i 1 [tree.depth :tree]] [at.depth :i :tree :action] +end + +make "tree [1 [2 [4 [7]] + [5]] + [3 [6 [8] + [9]]]] + + pre.order :tree [(type ? "| |)] (print) + in.order :tree [(type ? "| |)] (print) + post.order :tree [(type ? "| |)] (print) +level.order :tree [(type ? "| |)] (print) diff --git a/Task/Tree-traversal/Mathematica/tree-traversal-1.math b/Task/Tree-traversal/Mathematica/tree-traversal-1.math new file mode 100644 index 0000000000..b01d0943ba --- /dev/null +++ b/Task/Tree-traversal/Mathematica/tree-traversal-1.math @@ -0,0 +1,9 @@ +preorder[a_Integer] := a; +preorder[a_[b__]] := Flatten@{a, preorder /@ {b}}; +inorder[a_Integer] := a; +inorder[a_[b_, c_]] := Flatten@{inorder@b, a, inorder@c}; +inorder[a_[b_]] := Flatten@{inorder@b, a}; postorder[a_Integer] := a; +postorder[a_[b__]] := Flatten@{postorder /@ {b}, a}; +levelorder[a_] := + Flatten[Table[Level[a, {n}], {n, 0, Depth@a}]] /. {b_Integer[__] :> + b}; diff --git a/Task/Tree-traversal/Mathematica/tree-traversal-2.math b/Task/Tree-traversal/Mathematica/tree-traversal-2.math new file mode 100644 index 0000000000..5ac3edcc16 --- /dev/null +++ b/Task/Tree-traversal/Mathematica/tree-traversal-2.math @@ -0,0 +1,4 @@ +preorder[1[2[4[7], 5], 3[6[8, 9]]]] +inorder[1[2[4[7], 5], 3[6[8, 9]]]] +postorder[1[2[4[7], 5], 3[6[8, 9]]]] +levelorder[1[2[4[7], 5], 3[6[8, 9]]]] diff --git a/Task/Tree-traversal/OCaml/tree-traversal.ocaml b/Task/Tree-traversal/OCaml/tree-traversal.ocaml new file mode 100644 index 0000000000..93ba744942 --- /dev/null +++ b/Task/Tree-traversal/OCaml/tree-traversal.ocaml @@ -0,0 +1,50 @@ +type 'a tree = Empty + | Node of 'a * 'a tree * 'a tree + +let rec preorder f = function + Empty -> () + | Node (v,l,r) -> f v; + preorder f l; + preorder f r + +let rec inorder f = function + Empty -> () + | Node (v,l,r) -> inorder f l; + f v; + inorder f r + +let rec postorder f = function + Empty -> () + | Node (v,l,r) -> postorder f l; + postorder f r; + f v + +let levelorder f x = + let queue = Queue.create () in + Queue.add x queue; + while not (Queue.is_empty queue) do + match Queue.take queue with + Empty -> () + | Node (v,l,r) -> f v; + Queue.add l queue; + Queue.add r queue + done + +let tree = + Node (1, + Node (2, + Node (4, + Node (7, Empty, Empty), + Empty), + Node (5, Empty, Empty)), + Node (3, + Node (6, + Node (8, Empty, Empty), + Node (9, Empty, Empty)), + Empty)) + +let () = + preorder (Printf.printf "%d ") tree; print_newline (); + inorder (Printf.printf "%d ") tree; print_newline (); + postorder (Printf.printf "%d ") tree; print_newline (); + levelorder (Printf.printf "%d ") tree; print_newline () diff --git a/Task/Tree-traversal/Oz/tree-traversal.oz b/Task/Tree-traversal/Oz/tree-traversal.oz new file mode 100644 index 0000000000..eafb2539ff --- /dev/null +++ b/Task/Tree-traversal/Oz/tree-traversal.oz @@ -0,0 +1,58 @@ +declare + Tree = n(1 + n(2 + n(4 n(7 e e) e) + n(5 e e)) + n(3 + n(6 n(8 e e) n(9 e e)) + e)) + + fun {Concat Xs} + {FoldR Xs Append nil} + end + + fun {Preorder T} + case T of e then nil + [] n(V L R) then + {Concat [[V] + {Preorder L} + {Preorder R}]} + end + end + + fun {Inorder T} + case T of e then nil + [] n(V L R) then + {Concat [{Inorder L} + [V] + {Inorder R}]} + end + end + + fun {Postorder T} + case T of e then nil + [] n(V L R) then + {Concat [{Postorder L} + {Postorder R} + [V]]} + end + end + + local + fun {Collect Queue} + case Queue of nil then nil + [] e|Xr then {Collect Xr} + [] n(V L R)|Xr then + V|{Collect {Append Xr [L R]}} + end + end + in + fun {Levelorder T} + {Collect [T]} + end + end +in + {Show {Preorder Tree}} + {Show {Inorder Tree}} + {Show {Postorder Tree}} + {Show {Levelorder Tree}} diff --git a/Task/Tree-traversal/Perl-6/tree-traversal.pl6 b/Task/Tree-traversal/Perl-6/tree-traversal.pl6 new file mode 100644 index 0000000000..dad3253ac0 --- /dev/null +++ b/Task/Tree-traversal/Perl-6/tree-traversal.pl6 @@ -0,0 +1,58 @@ +class TreeNode { + has TreeNode $.parent; + has TreeNode $.left; + has TreeNode $.right; + has $.value; + + method pre-order { + gather { + take $.value; + take $.left.pre-order if $.left; + take $.right.pre-order if $.right + } + } + + method in-order { + gather { + take $.left.in-order if $.left; + take $.value; + take $.right.in-order if $.right; + } + } + + method post-order { + gather { + take $.left.post-order if $.left; + take $.right.post-order if $.right; + take $.value; + } + } + + method level-order { + my TreeNode @queue = (self); + gather while @queue.elems { + my $n = @queue.shift; + take $n.value; + @queue.push($n.left) if $n.left; + @queue.push($n.right) if $n.right; + } + } +} + +my TreeNode $root = TreeNode.new( value => 1, + left => TreeNode.new( value => 2, + left => TreeNode.new( value => 4, left => TreeNode.new(value => 7)), + right => TreeNode.new( value => 5) + ), + right => TreeNode.new( value => 3, + left => TreeNode.new( value => 6, + left => TreeNode.new(value => 8), + right => TreeNode.new(value => 9) + ) + ) + ); + +say "preorder: ",$root.pre-order.join(" "); +say "inorder: ",$root.in-order.join(" "); +say "postorder: ",$root.post-order.join(" "); +say "levelorder:",$root.level-order.join(" "); diff --git a/Task/Tree-traversal/Perl/tree-traversal.pl b/Task/Tree-traversal/Perl/tree-traversal.pl new file mode 100644 index 0000000000..42d8e02689 --- /dev/null +++ b/Task/Tree-traversal/Perl/tree-traversal.pl @@ -0,0 +1,36 @@ +sub preorder +{ + my $t = shift or return (); + return ($t->[0], preorder($t->[1]), preorder($t->[2])); +} + +sub inorder +{ + my $t = shift or return (); + return (inorder($t->[1]), $t->[0], inorder($t->[2])); +} + +sub postorder +{ + my $t = shift or return (); + return (postorder($t->[1]), postorder($t->[2]), $t->[0]); +} + +sub depth +{ + my @ret; + my @a = ($_[0]); + while (@a) { + my $v = shift @a or next; + push @ret, $v->[0]; + push @a, @{$v}[1,2]; + } + return @ret; +} + +my $x = [1,[2,[4,[7]],[5]],[3,[6,[8],[9]]]]; + +print "pre: @{[preorder($x)]}\n"; +print "in: @{[inorder($x)]}\n"; +print "post: @{[postorder($x)]}\n"; +print "depth: @{[depth($x)]}\n"; diff --git a/Task/Tree-traversal/PicoLisp/tree-traversal.l b/Task/Tree-traversal/PicoLisp/tree-traversal.l new file mode 100644 index 0000000000..db11d96ba6 --- /dev/null +++ b/Task/Tree-traversal/PicoLisp/tree-traversal.l @@ -0,0 +1,34 @@ +(de preorder (Node Fun) + (when Node + (Fun (car Node)) + (preorder (cadr Node) Fun) + (preorder (caddr Node) Fun) ) ) + +(de inorder (Node Fun) + (when Node + (inorder (cadr Node) Fun) + (Fun (car Node)) + (inorder (caddr Node) Fun) ) ) + +(de postorder (Node Fun) + (when Node + (postorder (cadr Node) Fun) + (postorder (caddr Node) Fun) + (Fun (car Node)) ) ) + +(de level-order (Node Fun) + (for (Q (circ Node) Q) + (let N (fifo 'Q) + (Fun (car N)) + (and (cadr N) (fifo 'Q @)) + (and (caddr N) (fifo 'Q @)) ) ) ) + +(setq *Tree + (1 + (2 (4 (7)) (5)) + (3 (6 (8) (9))) ) ) + +(for Order '(preorder inorder postorder level-order) + (prin (align -13 (pack Order ":"))) + (Order *Tree printsp) + (prinl) ) diff --git a/Task/Tree-traversal/Prolog/tree-traversal.pro b/Task/Tree-traversal/Prolog/tree-traversal.pro new file mode 100644 index 0000000000..1971066453 --- /dev/null +++ b/Task/Tree-traversal/Prolog/tree-traversal.pro @@ -0,0 +1,56 @@ +tree :- + Tree= [1, + [2, + [4, + [7, nil, nil], + nil], + [5, nil, nil]], + [3, + [6, + [8, nil, nil], + [9,nil, nil]], + nil]], + + write('preorder : '), preorder(Tree), nl, + write('inorder : '), inorder(Tree), nl, + write('postorder : '), postorder(Tree), nl, + write('level-order : '), level_order([Tree]). + +preorder(nil). +preorder([Node, FG, FD]) :- + format('~w ', [Node]), + preorder(FG), + preorder(FD). + + +inorder(nil). +inorder([Node, FG, FD]) :- + inorder(FG), + format('~w ', [Node]), + inorder(FD). + +postorder(nil). +postorder([Node, FG, FD]) :- + postorder(FG), + postorder(FD), + format('~w ', [Node]). + + +level_order([]). + +level_order(A) :- + level_order_(A, U-U, S), + level_order(S). + +level_order_([], S-[],S). + +level_order_([[Node, FG, FD] | T], CS, FS) :- + format('~w ', [Node]), + append_dl(CS, [FG, FD|U]-U, CS1), + level_order_(T, CS1, FS). + +level_order_([nil | T], CS, FS) :- + level_order_(T, CS, FS). + + +append_dl(X-Y, Y-Z, X-Z). diff --git a/Task/Tree-traversal/PureBasic/tree-traversal.purebasic b/Task/Tree-traversal/PureBasic/tree-traversal.purebasic new file mode 100644 index 0000000000..355986e47f --- /dev/null +++ b/Task/Tree-traversal/PureBasic/tree-traversal.purebasic @@ -0,0 +1,135 @@ +Structure node + value.i + *left.node + *right.node +EndStructure + +Structure queue + List q.i() +EndStructure + +DataSection + tree: + Data.s "1(2(4(7),5),3(6(8,9)))" +EndDataSection + +;Convenient routine to interpret string data to construct a tree of integers. +Procedure createTree(*n.node, *tPtr.Character) + Protected num.s, *l.node, *ntPtr.Character + + Repeat + Select *tPtr\c + Case '0' To '9' + num + Chr(*tPtr\c) + Case '(' + *n\value = Val(num): num = "" + *ntPtr = *tPtr + 1 + If *ntPtr\c = ',' + ProcedureReturn *tPtr + Else + *l = AllocateMemory(SizeOf(node)) + *n\left = *l: *tPtr = createTree(*l, *ntPtr) + EndIf + Case ')', ',', #Null + If num: *n\value = Val(num): EndIf + ProcedureReturn *tPtr + EndSelect + + If *tPtr\c = ',' + *l = AllocateMemory(SizeOf(node)): + *n\right = *l: *tPtr = createTree(*l, *tPtr + 1) + EndIf + *tPtr + 1 + ForEver +EndProcedure + +Procedure enqueue(List q.i(), element) + LastElement(q()) + AddElement(q()) + q() = element +EndProcedure + +Procedure dequeue(List q.i()) + Protected element + If FirstElement(q()) + element = q() + DeleteElement(q()) + EndIf + ProcedureReturn element +EndProcedure + +Procedure onVisit(*n.node) + Print(Str(*n\value) + " ") +EndProcedure + +Procedure preorder(*n.node) ;recursive + onVisit(*n) + If *n\left + preorder(*n\left) + EndIf + If *n\right + preorder(*n\right) + EndIf +EndProcedure + +Procedure inorder(*n.node) ;recursive + If *n\left + inorder(*n\left) + EndIf + onVisit(*n) + If *n\right + inorder(*n\right) + EndIf +EndProcedure + +Procedure postorder(*n.node) ;recursive + If *n\left + postorder(*n\left) + EndIf + If *n\right + postorder(*n\right) + EndIf + onVisit(*n) +EndProcedure + +Procedure levelorder(*n.node) + Dim q.queue(1) + Protected readQueue = 1, writeQueue, *currNode.node + + enqueue(q(writeQueue)\q(),*n) ;start queue off with root + Repeat + readQueue ! 1: writeQueue ! 1 + While ListSize(q(readQueue)\q()) + *currNode = dequeue(q(readQueue)\q()) + If *currNode\left + enqueue(q(writeQueue)\q(),*currNode\left) + EndIf + If *currNode\right + enqueue(q(writeQueue)\q(),*currNode\right) + EndIf + onVisit(*currNode) + Wend + Until ListSize(q(writeQueue)\q()) = 0 +EndProcedure + +If OpenConsole() + Define root.node + createTree(root,?tree) + + Print("preorder: ") + preorder(root) + PrintN("") + Print("inorder: ") + inorder(root) + PrintN("") + Print("postorder: ") + postorder(root) + PrintN("") + Print("levelorder: ") + levelorder(root) + PrintN("") + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Tree-traversal/Python/tree-traversal.py b/Task/Tree-traversal/Python/tree-traversal.py new file mode 100644 index 0000000000..fa128e73ab --- /dev/null +++ b/Task/Tree-traversal/Python/tree-traversal.py @@ -0,0 +1,55 @@ +from collections import namedtuple +from sys import stdout + +Node = namedtuple('Node', 'data, left, right') +tree = Node(1, + Node(2, + Node(4, + Node(7, None, None), + None), + Node(5, None, None)), + Node(3, + Node(6, + Node(8, None, None), + Node(9, None, None)), + None)) + +def printwithspace(i): + stdout.write("%i " % i) + +def preorder(node, visitor = printwithspace): + if node is not None: + visitor(node.data) + preorder(node.left, visitor) + preorder(node.right, visitor) + +def inorder(node, visitor = printwithspace): + if node is not None: + inorder(node.left, visitor) + visitor(node.data) + inorder(node.right, visitor) + +def postorder(node, visitor = printwithspace): + if node is not None: + postorder(node.left, visitor) + postorder(node.right, visitor) + visitor(node.data) + +def levelorder(node, more=None, visitor = printwithspace): + if node is not None: + if more is None: + more = [] + more += [node.left, node.right] + visitor(node.data) + if more: + levelorder(more[0], more[1:], visitor) + +stdout.write(' preorder: ') +preorder(tree) +stdout.write('\n inorder: ') +inorder(tree) +stdout.write('\n postorder: ') +postorder(tree) +stdout.write('\nlevelorder: ') +levelorder(tree) +stdout.write('\n') diff --git a/Task/Tree-traversal/Qi/tree-traversal.qi b/Task/Tree-traversal/Qi/tree-traversal.qi new file mode 100644 index 0000000000..9b03f38634 --- /dev/null +++ b/Task/Tree-traversal/Qi/tree-traversal.qi @@ -0,0 +1,44 @@ +(set *tree* [1 [2 [4 [7]] + [5]] + [3 [6 [8] + [9]]]]) + +(define inorder + [] -> [] + [V] -> [V] + [V L] -> (append (inorder L) + [V]) + [V L R] -> (append (inorder L) + [V] + (inorder R))) + +(define postorder + [] -> [] + [V] -> [V] + [V L] -> (append (postorder L) + [V]) + [V L R] -> (append (postorder L) + (postorder R) + [V])) + +(define preorder + [] -> [] + [V] -> [V] + [V L] -> (append [V] + (preorder L)) + [V L R] -> (append [V] + (preorder L) + (preorder R))) + +(define levelorder-0 + [] -> [] + [[] | Q] -> (levelorder-0 Q) + [[V | LR] | Q] -> [V | (levelorder-0 (append Q LR))]) + +(define levelorder + Node -> (levelorder-0 [Node])) + +(preorder (value *tree*)) +(postorder (value *tree*)) +(inorder (value *tree*)) +(levelorder (value *tree*)) diff --git a/Task/Tree-traversal/REXX/tree-traversal.rexx b/Task/Tree-traversal/REXX/tree-traversal.rexx new file mode 100644 index 0000000000..3cffa82d08 --- /dev/null +++ b/Task/Tree-traversal/REXX/tree-traversal.rexx @@ -0,0 +1,317 @@ +/* REXX *************************************************************** +* Tree traversal += 1 += / \ += / \ += / \ += 2 3 += / \ / += 4 5 6 += / / \ += 7 8 9 += += The correct output should look like this: += preorder: 1 2 4 7 5 3 6 8 9 += inorder: 7 4 2 5 1 8 6 9 3 += postorder: 7 4 5 2 8 9 6 3 1 += level-order: 1 2 3 4 5 6 7 8 9 +* 17.06.2012 Walter Pachl not thorouggly tested +**********************************************************************/ +debug=0 +wl_soll=1 2 4 7 5 3 6 8 9 +il_soll=7 4 2 5 1 8 6 9 3 +pl_soll=7 4 5 2 8 9 6 3 1 +ll_soll=1 2 3 4 5 6 7 8 9 + +Call mktree +wl.=''; wl='' /* preorder */ +ll.=''; ll='' /* level-order */ + il='' /* inorder */ + pl='' /* postorder */ + +/********************************************************************** +* First walk the tree and construct preorder and level-order lists +**********************************************************************/ +done.=0 +lvl=1 +z=root +Call note z +Do Until z=0 + z=go_next(z) + Call note z + End +Call show 'preorder: ',wl,wl_soll +Do lvl=1 To 4 + ll=ll ll.lvl + End +Call show 'level-order:',ll,ll_soll + +/********************************************************************** +* Next construct postorder list +**********************************************************************/ +done.=0 +ridone.=0 +z=lbot(root) +Call notep z +Do Until z=0 + br=brother(z) + If br>0 &, + done.br=0 Then Do + ridone.br=1 + z=lbot(br) + Call notep z + End + Else + z=father(z) + Call notep z + End +Call show 'postorder: ',pl,pl_soll + +/********************************************************************** +* Finally construct inorder list +**********************************************************************/ +done.=0 +ridone.=0 +z=lbot(root) +Call notei z +Do Until z=0 + z=father(z) + Call notei z + ri=node.z.0rite + If ridone.z=0 Then Do + ridone.z=1 + If ri>0 Then Do + z=lbot(ri) + Call notei z + End + End + End + +/********************************************************************** +* And now show the results and check them for correctness +**********************************************************************/ +Call show 'inorder: ',il,il_soll + +Exit + +show: Parse Arg Which,have,soll +/********************************************************************** +* Show our result and show it it's correct +**********************************************************************/ +have=space(have) +If have=soll Then + tag='' +Else + tag='*wrong*' +Say which have tag +If tag<>'' Then + Say '------------>'soll 'is the expected result' +Return + +brother: Procedure Expose node. +/********************************************************************** +* Return the right node of this node's father or 0 +**********************************************************************/ + Parse arg no + nof=node.no.0father + brot1=node.nof.0rite + Return brot1 + +notei: Procedure Expose debug il done. +/********************************************************************** +* append the given node to il +**********************************************************************/ + Parse Arg nd + If nd<>0 &, + done.nd=0 Then + il=il nd + If debug Then + Say 'notei' nd + done.nd=1 + Return + +notep: Procedure Expose debug pl done. +/********************************************************************** +* append the given node to pl +**********************************************************************/ + Parse Arg nd + If nd<>0 &, + done.nd=0 Then Do + pl=pl nd + If debug Then + Say 'notep' nd + End + done.nd=1 + Return + +father: Procedure Expose node. +/********************************************************************** +* Return the father of the argument +* or 0 if the root is given as argument +**********************************************************************/ + Parse Arg nd + Return node.nd.0father + +lbot: Procedure Expose node. +/********************************************************************** +* From node z: Walk down on the left side until you reach the bottom +* and return the bottom node +* If z has no left son (at the bottom of the tree) returm itself +**********************************************************************/ + Parse Arg z + Do i=1 To 100 + If node.z.0left<>0 Then + z=node.z.0left + Else + Leave + End + Return z + +note: +/********************************************************************** +* add the node to the preorder list unless it's already there +* add the node to the level list +**********************************************************************/ + If z<>0 &, /* it's a node */ + done.z=0 Then Do /* not yet done */ + wl=wl z /* add it to the preorder list*/ + ll.lvl=ll.lvl z /* add it to the level list */ + done.z=1 /* remember it's done */ + End + Return + +go_next: Procedure Expose node. lvl +/********************************************************************** +* find the next node to visit in the treewalk +**********************************************************************/ + next=0 + Parse arg z + If node.z.0left<>0 Then Do /* there is a left son */ + If node.z.0left.done=0 Then Do /* we have not visited it */ + next=node.z.0left /* so we go there */ + node.z.0left.done=1 /* note we were here */ + lvl=lvl+1 /* increase the level */ + End + End + If next=0 Then Do /* not moved yet */ + If node.z.0rite<>0 Then Do /* there is a right son */ + If node.z.0rite.done=0 Then Do /* we have not visited it */ + next=node.z.0rite /* so we go there */ + node.z.0rite.done=1 /* note we were here */ + lvl=lvl+1 /* increase the level */ + End + End + End + If next=0 Then Do /* not moved yet */ + next=node.z.0father /* go to the father */ + lvl=lvl-1 /* decrease the level */ + End + Return next /* that's the next node */ + /* or zero if we are done */ + +mknode: Procedure Expose node. +/********************************************************************** +* create a new node +**********************************************************************/ + Parse Arg name + z=node.0+1 + node.z.0name=name + node.z.0father=0 + node.z.0left =0 + node.z.0rite =0 + node.0=z + Return z /* number of the node just created */ + +attleft: Procedure Expose node. +/********************************************************************** +* make son the left son of father +**********************************************************************/ + Parse Arg son,father + node.son.0father=father + z=node.father.0left + If z<>0 Then Do + node.z.0father=son + node.son.0left=z + End + node.father.0left=son + Return + +attrite: Procedure Expose node. +/********************************************************************** +* make son the right son of father +**********************************************************************/ + Parse Arg son,father + node.son.0father=father + z=node.father.0rite + If z<>0 Then Do + node.z.0father=son + node.son.0rite=z + End + node.father.0rite=son + le=node.father.0left + If le>0 Then + node.le.0brother=node.father.0rite + Return + +mktree: Procedure Expose node. root +/********************************************************************** +* build the tree according to the task +**********************************************************************/ + node.=0 + a=mknode('A'); root=a + b=mknode('B'); Call attleft b,a + c=mknode('C'); Call attrite c,a + d=mknode('D'); Call attleft d,b + e=mknode('E'); Call attrite e,b + f=mknode('F'); Call attleft f,c + g=mknode('G'); Call attleft g,d + h=mknode('H'); Call attleft h,f + i=mknode('I'); Call attrite i,f + Call show_tree 1 + Return + +show_tree: Procedure Expose node. +/********************************************************************** +* Show the tree +* f +* l1 1 r1 +* l r l r +* l r l r l r l r +* 12345678901234567890 +**********************************************************************/ + Parse Arg f + l.='' + l.1=overlay(f ,l.1, 9) + + l1=node.f.0left ;l.2=overlay(l1 ,l.2, 5) +/*b1=node.f.0brother ;l.2=overlay(b1 ,l.2, 9) */ + r1=node.f.0rite ;l.2=overlay(r1 ,l.2,13) + + l1g=node.l1.0left ;l.3=overlay(l1g ,l.3, 3) +/*b1g=node.l1.0brother ;l.3=overlay(b1g ,l.3, 5) */ + r1g=node.l1.0rite ;l.3=overlay(r1g ,l.3, 7) + + l2g=node.r1.0left ;l.3=overlay(l2g ,l.3,11) +/*b2g=node.r1.0brother ;l.3=overlay(b2g ,l.3,13) */ + r2g=node.r1.0rite ;l.3=overlay(r2g ,l.3,15) + + l1ls=node.l1g.0left ;l.4=overlay(l1ls,l.4, 2) +/*b1ls=node.l1g.0brother ;l.4=overlay(b1ls,l.4, 3) */ + r1ls=node.l1g.0rite ;l.4=overlay(r1ls,l.4, 4) + + l1rs=node.r1g.0left ;l.4=overlay(l1rs,l.4, 6) +/*b1rs=node.r1g.0brother ;l.4=overlay(b1rs,l.4, 7) */ + r1rs=node.r1g.0rite ;l.4=overlay(r1rs,l.4, 8) + + l2ls=node.l2g.0left ;l.4=overlay(l2ls,l.4,10) +/*b2ls=node.l2g.0brother ;l.4=overlay(b2ls,l.4,11) */ + r2ls=node.l2g.0rite ;l.4=overlay(r2ls,l.4,12) + + l2rs=node.r2g.0left ;l.4=overlay(l2rs,l.4,14) +/*b2rs=node.r2g.0brother ;l.4=overlay(b2rs,l.4,15) */ + r2rs=node.r2g.0rite ;l.4=overlay(r2rs,l.4,16) + Do i=1 To 4 + Say translate(l.i,' ','0') + Say '' + End + Return diff --git a/Task/Tree-traversal/Ruby/tree-traversal.rb b/Task/Tree-traversal/Ruby/tree-traversal.rb new file mode 100644 index 0000000000..3eb4e752f1 --- /dev/null +++ b/Task/Tree-traversal/Ruby/tree-traversal.rb @@ -0,0 +1,45 @@ +class BinaryTreeNode + def initialize(value, left=nil, right=nil) + @value, @left, @right = value, left, right + end + attr_reader :value, :left, :right + + def self.from_array(nested_list) + value, left, right = nested_list + if value + self.new(value, self.from_array(left), self.from_array(right)) + end + end + + def walk_nodes(order, &block) + order.each do |node| + case node + when :left then left && left.walk_nodes(order, &block) + when :self then yield self + when :right then right && right.walk_nodes(order, &block) + end + end + end + + def each_preorder(&b) ; walk_nodes([:self, :left, :right], &b) ; end + def each_inorder(&b) ; walk_nodes([:left, :self, :right], &b) ; end + def each_postorder(&b) ; walk_nodes([:left, :right, :self], &b) ; end + + def each_levelorder + queue = [self] + until queue.empty? + node = queue.shift + yield node + queue << node.left if node.left + queue << node.right if node.right + end + end +end + +root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]] + +%w{each_preorder each_inorder each_postorder each_levelorder}.each {|mthd| + printf "%-11s ", mthd[5..-1] + ':' + root.send(mthd) {|node| print "#{node.value} "} + puts +} diff --git a/Task/Tree-traversal/Scala/tree-traversal.scala b/Task/Tree-traversal/Scala/tree-traversal.scala new file mode 100644 index 0000000000..62ecce00f7 --- /dev/null +++ b/Task/Tree-traversal/Scala/tree-traversal.scala @@ -0,0 +1,55 @@ +case class IntNode(var value: Int, var left: Option[IntNode] = None, var right: Option[IntNode] = None) { + + def preorder[T](f: IntNode => Any): Unit = { + f(this) + left.map(_.preorder(f)) + right.map(_.preorder(f)) + } + + def postorder[T](f: IntNode => Any): Unit = { + left.map(_.postorder(f)) + right.map(_.postorder(f)) + f(this) + } + + def inorder[T](f: IntNode => Any): Unit = { + left.map(_.inorder(f)) + f(this) + right.map(_.inorder(f)) + } + + def levelorder[T](f: IntNode => Any): Unit = { + + def loVisit(ls: List[IntNode]): Unit = ls match { + case Nil => None + case h :: rest => f(h); loVisit(rest ++ h.left ++ h.right) + } + + loVisit(List(this)) + } +} + +object TreeTraversal extends App { + implicit def intNode2SomeIntNode(n: IntNode) = Some[IntNode](n) + + val tree = IntNode(1, + IntNode(2, + IntNode(4, + IntNode(7)), + IntNode(5)), + IntNode(3, + IntNode(6, + IntNode(8), + IntNode(9)))) + + List( + "preorder" -> tree.preorder _, + "inorder" -> tree.inorder _, + "postorder" -> tree.postorder _, + "levelorder" -> tree.levelorder _) foreach { + case (name, func) => + var s = new StringBuilder("%10s: ".format(name)) + func(n => s ++= n.value.toString + " ") + println(s) + } +} diff --git a/Task/Tree-traversal/Tcl/tree-traversal-1.tcl b/Task/Tree-traversal/Tcl/tree-traversal-1.tcl new file mode 100644 index 0000000000..25a25163b6 --- /dev/null +++ b/Task/Tree-traversal/Tcl/tree-traversal-1.tcl @@ -0,0 +1,50 @@ +oo::class create tree { + # Basic tree data structure stuff... + variable val l r + constructor {value {left {}} {right {}}} { + set val $value + set l $left + set r $right + } + method value {} {return $val} + method left {} {return $l} + method right {} {return $r} + destructor { + if {$l ne ""} {$l destroy} + if {$r ne ""} {$r destroy} + } + + # Traversal methods + method preorder {varName script {level 0}} { + upvar [incr level] $varName var + set var $val + uplevel $level $script + if {$l ne ""} {$l preorder $varName $script $level} + if {$r ne ""} {$r preorder $varName $script $level} + } + method inorder {varName script {level 0}} { + upvar [incr level] $varName var + if {$l ne ""} {$l inorder $varName $script $level} + set var $val + uplevel $level $script + if {$r ne ""} {$r inorder $varName $script $level} + } + method postorder {varName script {level 0}} { + upvar [incr level] $varName var + if {$l ne ""} {$l postorder $varName $script $level} + if {$r ne ""} {$r postorder $varName $script $level} + set var $val + uplevel $level $script + } + method levelorder {varName script} { + upvar 1 $varName var + set nodes [list [self]]; # A queue of nodes to process + while {[llength $nodes] > 0} { + set nodes [lassign $nodes n] + set var [$n value] + uplevel 1 $script + if {[$n left] ne ""} {lappend nodes [$n left]} + if {[$n right] ne ""} {lappend nodes [$n right]} + } + } +} diff --git a/Task/Tree-traversal/Tcl/tree-traversal-2.tcl b/Task/Tree-traversal/Tcl/tree-traversal-2.tcl new file mode 100644 index 0000000000..c2806dc7b6 --- /dev/null +++ b/Task/Tree-traversal/Tcl/tree-traversal-2.tcl @@ -0,0 +1,22 @@ +# Helpers to make construction and listing of a whole tree simpler +proc Tree nested { + lassign $nested v l r + if {$l ne ""} {set l [Tree $l]} + if {$r ne ""} {set r [Tree $r]} + tree new $v $l $r +} +proc Listify {tree order} { + set list {} + $tree $order v { + lappend list $v + } + return $list +} + +# Make a tree, print it a few ways, and destroy the tree +set t [Tree {1 {2 {4 7} 5} {3 {6 8 9}}}] +puts "preorder: [Listify $t preorder]" +puts "inorder: [Listify $t inorder]" +puts "postorder: [Listify $t postorder]" +puts "level-order: [Listify $t levelorder]" +$t destroy diff --git a/Task/Tree-traversal/UNIX-Shell/tree-traversal-1.sh b/Task/Tree-traversal/UNIX-Shell/tree-traversal-1.sh new file mode 100644 index 0000000000..74dacaeb2f --- /dev/null +++ b/Task/Tree-traversal/UNIX-Shell/tree-traversal-1.sh @@ -0,0 +1,84 @@ +left=() +right=() +value=() + +# node node#, left#, right#, value +# +# if value is empty, use node# + +node() { + nx=${1:-'Missing node index'} + leftx=${2} + rightx=${3} + val=${4:-$1} + value[$nx]="$val" + left[$nx]="$leftx" + right[$nx]="$rightx" +} + +# define the tree + +node 1 2 3 +node 2 4 5 +node 3 6 +node 4 7 +node 5 +node 6 8 9 +node 7 +node 8 +node 9 + +# walk NODE# ORDER + +walk() { + local nx=${1-"Missing index"} + shift + for branch in "$@" ; do + case "$branch" in + left) if [[ "${left[$nx]}" ]]; then walk ${left[$nx]} $@ ; fi ;; + right) if [[ "${right[$nx]}" ]]; then walk ${right[$nx]} $@ ; fi ;; + self) printf "%d " "${value[$nx]}" ;; + esac + done +} + +apush() { + local var="$1" + eval "$var=( \"\${$var[@]}\" \"$2\" )" +} + +showname() { + printf "%-12s " "$1:" +} + +showdata() { + showname "$1" + shift + walk "$@" + echo '' +} + +preorder() { showdata $FUNCNAME $1 self left right ; } +inorder() { showdata $FUNCNAME $1 left self right ; } +postorder() { showdata $FUNCNAME $1 left right self ; } +levelorder() { + showname 'level-order' + queue=( $1 ) + x=0 + while [[ $x < ${#queue[*]} ]]; do + value="${queue[$x]}" + printf "%d " "$value" + for more in "${left[$value]}" "${right[$value]}" ; do + if [[ -n "$more" ]]; then + apush queue "$more" + fi + done + : $((x++)) + done + echo '' +} + +preorder 1 +inorder 1 +postorder 1 +levelorder 1 diff --git a/Task/Tree-traversal/UNIX-Shell/tree-traversal-2.sh b/Task/Tree-traversal/UNIX-Shell/tree-traversal-2.sh new file mode 100644 index 0000000000..86de5178ae --- /dev/null +++ b/Task/Tree-traversal/UNIX-Shell/tree-traversal-2.sh @@ -0,0 +1,4 @@ +preorder: 1 2 4 7 5 3 6 8 9 +inorder: 7 4 2 5 1 8 6 9 3 +postorder: 7 4 5 2 8 9 6 3 1 +level-order: 1 2 3 4 5 6 7 8 9 diff --git a/Task/Tree-traversal/Ursala/tree-traversal.ursala b/Task/Tree-traversal/Ursala/tree-traversal.ursala new file mode 100644 index 0000000000..44303e87e7 --- /dev/null +++ b/Task/Tree-traversal/Ursala/tree-traversal.ursala @@ -0,0 +1,14 @@ +tree = + +1^:< + 2^: <4^: <7^: <>, 0>, 5^: <>>, + 3^: <6^: <8^: <>, 9^: <>>, 0>> + +pre = ~&dvLPCo +post = ~&vLPdNCTo +in = ~&vvhPdvtL2CTiQo +lev = ~&iNCaadSPfavSLiF3RTaq + +#cast %nLL + +main = <.pre,in,post,lev> tree diff --git a/Task/Trigonometric-functions/0DESCRIPTION b/Task/Trigonometric-functions/0DESCRIPTION new file mode 100644 index 0000000000..54d552749d --- /dev/null +++ b/Task/Trigonometric-functions/0DESCRIPTION @@ -0,0 +1,2 @@ +{{omit from|GAP}} +If your language has a library or built-in functions for trigonometry, show examples of sine, cosine, tangent, and their inverses using the same angle in radians and degrees. For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions, use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any [[wp:List of trigonometric identities|known approximation or identity]]. diff --git a/Task/Trigonometric-functions/1META.yaml b/Task/Trigonometric-functions/1META.yaml new file mode 100644 index 0000000000..8644b2ad9b --- /dev/null +++ b/Task/Trigonometric-functions/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Arithmetic operations diff --git a/Task/Trigonometric-functions/ACL2/trigonometric-functions.acl2 b/Task/Trigonometric-functions/ACL2/trigonometric-functions.acl2 new file mode 100644 index 0000000000..e4a414a18f --- /dev/null +++ b/Task/Trigonometric-functions/ACL2/trigonometric-functions.acl2 @@ -0,0 +1,79 @@ +(defun fac (n) + (if (zp n) + 1 + (* n (fac (1- n))))) + +(defconst *pi-approx* + (/ 3141592653589793238462643383279 + (expt 10 30))) + +(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system) + +(defun dgt-to-str (d) + (case d + (1 "1") (2 "2") (3 "3") (4 "4") (5 "5") + (6 "6") (7 "7") (8 "8") (9 "9") (0 "0"))) + +(defmacro cat (&rest args) + `(concatenate 'string ,@args)) + +(defun num-to-str-r (n) + (if (zp n) + "" + (cat (num-to-str-r (floor n 10)) + (dgt-to-str (mod n 10))))) + +(defun num-to-str (n) + (cond ((= n 0) "0") + ((< n 0) (cat "-" (num-to-str-r (- n)))) + (t (num-to-str-r n)))) + +(defun pad-with-zeros (places str lngth) + (declare (xargs :measure (nfix (- places lngth)))) + (if (zp (- places lngth)) + str + (pad-with-zeros places (cat "0" str) (1+ lngth)))) + +(defun as-decimal-str (r places) + (let ((before (floor r 1)) + (after (floor (* (expt 10 places) (mod r 1)) 1))) + (cat (num-to-str before) + "." + (let ((afterstr (num-to-str after))) + (pad-with-zeros places afterstr + (length afterstr)))))) + +(defun taylor-sine (theta terms term) + (declare (xargs :measure (nfix (- terms term)))) + (if (zp (- terms term)) + 0 + (+ (/ (*(expt -1 term) (expt theta (1+ (* 2 term)))) + (fac (1+ (* 2 term)))) + (taylor-sine theta terms (1+ term))))) + +(defun sine (theta) + (taylor-sine (mod theta (* 2 *pi-approx*)) + 20 0)) ; About 30 places of accuracy + +(defun cosine (theta) + (sine (+ theta (/ *pi-approx* 2)))) + +(defun tangent (theta) + (/ (sine theta) (cosine theta))) + +(defun rad->deg (rad) + (* 180 (/ rad *pi-approx*))) + +(defun deg->rad (deg) + (* *pi-approx* (/ deg 180))) + +(defun trig-demo () + (progn$ (cw "sine of pi / 4 radians: ") + (cw (as-decimal-str (sine (/ *pi-approx* 4)) 20)) + (cw "~%sine of 45 degrees: ") + (cw (as-decimal-str (sine (deg->rad 45)) 20)) + (cw "~%cosine of pi / 4 radians: ") + (cw (as-decimal-str (cosine (/ *pi-approx* 4)) 20)) + (cw "~%tangent of pi / 4 radians: ") + (cw (as-decimal-str (tangent (/ *pi-approx* 4)) 20)) + (cw "~%"))) diff --git a/Task/Trigonometric-functions/ALGOL-68/trigonometric-functions.alg b/Task/Trigonometric-functions/ALGOL-68/trigonometric-functions.alg new file mode 100644 index 0000000000..5d1ac0864e --- /dev/null +++ b/Task/Trigonometric-functions/ALGOL-68/trigonometric-functions.alg @@ -0,0 +1,22 @@ +main:( + REAL pi = 4 * arc tan(1); + # Pi / 4 is 45 degrees. All answers should be the same. # + REAL radians = pi / 4; + REAL degrees = 45.0; + REAL temp; + # sine # + print((sin(radians), " ", sin(degrees * pi / 180), new line)); + # cosine # + print((cos(radians), " ", cos(degrees * pi / 180), new line)); + # tangent # + print((tan(radians), " ", tan(degrees * pi / 180), new line)); + # arcsine # + temp := arc sin(sin(radians)); + print((temp, " ", temp * 180 / pi, new line)); + # arccosine # + temp := arc cos(cos(radians)); + print((temp, " ", temp * 180 / pi, new line)); + # arctangent # + temp := arc tan(tan(radians)); + print((temp, " ", temp * 180 / pi, new line)) +) diff --git a/Task/Trigonometric-functions/AWK/trigonometric-functions.awk b/Task/Trigonometric-functions/AWK/trigonometric-functions.awk new file mode 100644 index 0000000000..93b6ad8af3 --- /dev/null +++ b/Task/Trigonometric-functions/AWK/trigonometric-functions.awk @@ -0,0 +1,40 @@ +# tan(x) = tangent of x +function tan(x) { + return sin(x) / cos(x) +} + +# asin(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2] +function asin(y) { + return atan2(y, sqrt(1 - y * y)) +} + +# acos(x) = arccosine of x, domain [-1, 1], range [0, pi] +function acos(x) { + return atan2(sqrt(1 - x * x), x) +} + +# atan(y) = arctangent of y, range (-pi/2, pi/2) +function atan(y) { + return atan2(y, 1) +} + +BEGIN { + pi = atan2(0, -1) + degrees = pi / 180 + + print "Using radians:" + print " sin(-pi / 6) =", sin(-pi / 6) + print " cos(3 * pi / 4) =", cos(3 * pi / 4) + print " tan(pi / 3) =", tan(pi / 3) + print " asin(-1 / 2) =", asin(-1 / 2) + print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) + print " atan(sqrt(3)) =", atan(sqrt(3)) + + print "Using degrees:" + print " sin(-30) =", sin(-30 * degrees) + print " cos(135) =", cos(135 * degrees) + print " tan(60) =", tan(60 * degrees) + print " asin(-1 / 2) =", asin(-1 / 2) / degrees + print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) / degrees + print " atan(sqrt(3)) =", atan(sqrt(3)) / degrees +} diff --git a/Task/Trigonometric-functions/ActionScript/trigonometric-functions.as b/Task/Trigonometric-functions/ActionScript/trigonometric-functions.as new file mode 100644 index 0000000000..c0b5497fd6 --- /dev/null +++ b/Task/Trigonometric-functions/ActionScript/trigonometric-functions.as @@ -0,0 +1,16 @@ +trace("Radians:"); +trace("sin(Pi/4) = ", Math.sin(Math.PI/4)); +trace("cos(Pi/4) = ", Math.cos(Math.PI/4)); +trace("tan(Pi/4) = ", Math.tan(Math.PI/4)); +trace("arcsin(0.5) = ", Math.asin(0.5)); +trace("arccos(0.5) = ", Math.acos(0.5)); +trace("arctan(0.5) = ", Math.atan(0.5)); +trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)); +trace("\nDegrees") +trace("sin(45) = ", Math.sin(45 * Math.PI/180)); +trace("cos(45) = ", Math.cos(45 * Math.PI/180)); +trace("tan(45) = ", Math.tan(45 * Math.PI/180)); +trace("arcsin(0.5) = ", Math.asin(0.5)*180/Math.PI); +trace("arccos(0.5) = ", Math.acos(0.5)*180/Math.PI); +trace("arctan(0.5) = ", Math.atan(0.5)*180/Math.PI); +trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)*180/Math.PI); diff --git a/Task/Trigonometric-functions/Ada/trigonometric-functions.ada b/Task/Trigonometric-functions/Ada/trigonometric-functions.ada new file mode 100644 index 0000000000..b9094746c9 --- /dev/null +++ b/Task/Trigonometric-functions/Ada/trigonometric-functions.ada @@ -0,0 +1,35 @@ +with Ada.Numerics.Elementary_Functions; +use Ada.Numerics.Elementary_Functions; +with Ada.Float_Text_Io; use Ada.Float_Text_Io; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Trig is + Degrees_Cycle : constant Float := 360.0; + Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi; + Angle_Degrees : constant Float := 45.0; + Angle_Radians : constant Float := Ada.Numerics.Pi / 4.0; + procedure Put (V1, V2 : Float) is + begin + Put (V1, Aft => 5, Exp => 0); + Put (" "); + Put (V2, Aft => 5, Exp => 0); + New_Line; + end Put; +begin + Put (Sin (Angle_Degrees, Degrees_Cycle), + Sin (Angle_Radians, Radians_Cycle)); + Put (Cos (Angle_Degrees, Degrees_Cycle), + Cos (Angle_Radians, Radians_Cycle)); + Put (Tan (Angle_Degrees, Degrees_Cycle), + Tan (Angle_Radians, Radians_Cycle)); + Put (Cot (Angle_Degrees, Degrees_Cycle), + Cot (Angle_Radians, Radians_Cycle)); + Put (ArcSin (Sin (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), + ArcSin (Sin (Angle_Radians, Radians_Cycle), Radians_Cycle)); + Put (Arccos (Cos (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), + Arccos (Cos (Angle_Radians, Radians_Cycle), Radians_Cycle)); + Put (Arctan (Y => Tan (Angle_Degrees, Degrees_Cycle)), + Arctan (Y => Tan (Angle_Radians, Radians_Cycle))); + Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), + Arccot (X => Cot (Angle_Degrees, Degrees_Cycle))); +end Trig; diff --git a/Task/Trigonometric-functions/AutoHotkey/trigonometric-functions.ahk b/Task/Trigonometric-functions/AutoHotkey/trigonometric-functions.ahk new file mode 100644 index 0000000000..416d9c41d8 --- /dev/null +++ b/Task/Trigonometric-functions/AutoHotkey/trigonometric-functions.ahk @@ -0,0 +1,28 @@ +pi := 4 * atan(1) + radians := pi / 4 + degrees := 45.0 + result .= "`n" . sin(radians) . " " . sin(degrees * pi / 180) + result .= "`n" . cos(radians) . " " . cos(degrees * pi / 180) + result .= "`n" . tan(radians) . " " . tan(degrees * pi / 180) + + temp := asin(sin(radians)) + result .= "`n" . temp . " " . temp * 180 / pi + + temp := acos(cos(radians)) + result .= "`n" . temp . " " . temp * 180 / pi + + temp := atan(tan(radians)) + result .= "`n" . temp . " " . temp * 180 / pi + +msgbox % result +/* output +--------------------------- +trig.ahk +--------------------------- +0.707107 0.707107 +0.707107 0.707107 +1.000000 1.000000 +0.785398 45.000000 +0.785398 45.000000 +0.785398 45.000000 +*/ diff --git a/Task/Trigonometric-functions/BASIC/trigonometric-functions.basic b/Task/Trigonometric-functions/BASIC/trigonometric-functions.basic new file mode 100644 index 0000000000..81a2f0dfae --- /dev/null +++ b/Task/Trigonometric-functions/BASIC/trigonometric-functions.basic @@ -0,0 +1,15 @@ +pi = 3.141592653589793# +radians = pi / 4 'a.k.a. 45 degrees +degrees = 45 * pi / 180 'convert 45 degrees to radians once +PRINT SIN(radians) + " " + SIN(degrees) 'sine +PRINT COS(radians) + " " + COS(degrees) 'cosine +PRINT TAN(radians) + " " + TAN (degrees) 'tangent +'arcsin +thesin = SIN(radians) +arcsin = ATN(thesin / SQR(1 - thesin ^ 2)) +PRINT arcsin + " " + arcsin * 180 / pi +'arccos +thecos = COS(radians) +arccos = 2 * ATN(SQR(1 - thecos ^ 2) / (1 + thecos)) +PRINT arccos + " " + arccos * 180 / pi +PRINT ATN(TAN(radians)) + " " + ATN(TAN(radians)) * 180 / pi 'arctan diff --git a/Task/Trigonometric-functions/BBC-BASIC/trigonometric-functions.bbc b/Task/Trigonometric-functions/BBC-BASIC/trigonometric-functions.bbc new file mode 100644 index 0000000000..d035fddfe2 --- /dev/null +++ b/Task/Trigonometric-functions/BBC-BASIC/trigonometric-functions.bbc @@ -0,0 +1,14 @@ + @% = &90F : REM set column width + + angle_radians = PI/5 + angle_degrees = 36 + + PRINT SIN(angle_radians), SIN(RAD(angle_degrees)) + PRINT COS(angle_radians), COS(RAD(angle_degrees)) + PRINT TAN(angle_radians), TAN(RAD(angle_degrees)) + + number = 0.6 + + PRINT ASN(number), DEG(ASN(number)) + PRINT ACS(number), DEG(ACS(number)) + PRINT ATN(number), DEG(ATN(number)) diff --git a/Task/Trigonometric-functions/C++/trigonometric-functions.cpp b/Task/Trigonometric-functions/C++/trigonometric-functions.cpp new file mode 100644 index 0000000000..80e622ecf0 --- /dev/null +++ b/Task/Trigonometric-functions/C++/trigonometric-functions.cpp @@ -0,0 +1,31 @@ +#include +#include + +#ifdef M_PI // defined by all POSIX systems and some non-POSIX ones +double const pi = M_PI; +#else +double const pi = 4*std::atan(1); +#endif + +double const degree = pi/180; + +int main() +{ + std::cout << "=== radians ===\n"; + std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n"; + std::cout << "cos(pi/3) = " << std::cos(pi/3) << "\n"; + std::cout << "tan(pi/3) = " << std::tan(pi/3) << "\n"; + std::cout << "arcsin(1/2) = " << std::asin(0.5) << "\n"; + std::cout << "arccos(1/2) = " << std::acos(0.5) << "\n"; + std::cout << "arctan(1/2) = " << std::atan(0.5) << "\n"; + + std::cout << "\n=== degrees ===\n"; + std::cout << "sin(60°) = " << std::sin(60*degree) << "\n"; + std::cout << "cos(60°) = " << std::cos(60*degree) << "\n"; + std::cout << "tan(60°) = " << std::tan(60*degree) << "\n"; + std::cout << "arcsin(1/2) = " << std::asin(0.5)/degree << "°\n"; + std::cout << "arccos(1/2) = " << std::acos(0.5)/degree << "°\n"; + std::cout << "arctan(1/2) = " << std::atan(0.5)/degree << "°\n"; + + return 0; +} diff --git a/Task/Trigonometric-functions/C/trigonometric-functions.c b/Task/Trigonometric-functions/C/trigonometric-functions.c new file mode 100644 index 0000000000..c1146c688a --- /dev/null +++ b/Task/Trigonometric-functions/C/trigonometric-functions.c @@ -0,0 +1,27 @@ +#include +#include + +int main() { + double pi = 4 * atan(1); + /*Pi / 4 is 45 degrees. All answers should be the same.*/ + double radians = pi / 4; + double degrees = 45.0; + double temp; + /*sine*/ + printf("%f %f\n", sin(radians), sin(degrees * pi / 180)); + /*cosine*/ + printf("%f %f\n", cos(radians), cos(degrees * pi / 180)); + /*tangent*/ + printf("%f %f\n", tan(radians), tan(degrees * pi / 180)); + /*arcsine*/ + temp = asin(sin(radians)); + printf("%f %f\n", temp, temp * 180 / pi); + /*arccosine*/ + temp = acos(cos(radians)); + printf("%f %f\n", temp, temp * 180 / pi); + /*arctangent*/ + temp = atan(tan(radians)); + printf("%f %f\n", temp, temp * 180 / pi); + + return 0; +} diff --git a/Task/Trigonometric-functions/Clojure/trigonometric-functions.clj b/Task/Trigonometric-functions/Clojure/trigonometric-functions.clj new file mode 100644 index 0000000000..b1f98ad076 --- /dev/null +++ b/Task/Trigonometric-functions/Clojure/trigonometric-functions.clj @@ -0,0 +1,16 @@ +(ns user + (:require [clojure.contrib.generic.math-functions :as generic])) + +;(def pi Math/PI) +(def pi (* 4 (atan 1))) +(def dtor (/ pi 180)) +(def rtod (/ 180 pi)) +(def radians (/ pi 4)) +(def degrees 45) + +(println (str (sin radians) " " (sin (* degrees dtor)))) +(println (str (cos radians) " " (cos (* degrees dtor)))) +(println (str (tan radians) " " (tan (* degrees dtor)))) +(println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod))) +(println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod))) +(println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod))) diff --git a/Task/Trigonometric-functions/Common-Lisp/trigonometric-functions.lisp b/Task/Trigonometric-functions/Common-Lisp/trigonometric-functions.lisp new file mode 100644 index 0000000000..f1f467e783 --- /dev/null +++ b/Task/Trigonometric-functions/Common-Lisp/trigonometric-functions.lisp @@ -0,0 +1,16 @@ +(defun deg->rad (x) (* x (/ pi 180))) +(defun rad->deg (x) (* x (/ 180 pi))) + +(mapc (lambda (x) (format t "~s => ~s~%" x (eval x))) + '((sin (/ pi 4)) + (sin (deg->rad 45)) + (cos (/ pi 6)) + (cos (deg->rad 30)) + (tan (/ pi 3)) + (tan (deg->rad 60)) + (asin 1) + (rad->deg (asin 1)) + (acos 1/2) + (rad->deg (acos 1/2)) + (atan 15) + (rad->deg (atan 15)))) diff --git a/Task/Trigonometric-functions/D/trigonometric-functions.d b/Task/Trigonometric-functions/D/trigonometric-functions.d new file mode 100644 index 0000000000..a4edec07e4 --- /dev/null +++ b/Task/Trigonometric-functions/D/trigonometric-functions.d @@ -0,0 +1,21 @@ +import std.stdio, std.math; + +void main() { + enum real degrees = 45.0; + enum real t0 = degrees * PI / 180.0; + writeln("Reference: 0.7071067811865475244008"); + writefln("Sine: %.20f %.20f", sin(PI_4), sin(t0)); + writefln("Cosine: %.20f %.20f", cos(PI_4), cos(t0)); + writefln("Tangent: %.20f %.20f", tan(PI_4), tan(t0)); + + writeln(); + writeln("Reference: 0.7853981633974483096156"); + immutable real t1 = asin(sin(PI_4)); + writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0 / PI); + + immutable real t2 = acos(cos(PI_4)); + writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0 / PI); + + immutable real t3 = atan(tan(PI_4)); + writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0 / PI); +} diff --git a/Task/Trigonometric-functions/E/trigonometric-functions.e b/Task/Trigonometric-functions/E/trigonometric-functions.e new file mode 100644 index 0000000000..1599457016 --- /dev/null +++ b/Task/Trigonometric-functions/E/trigonometric-functions.e @@ -0,0 +1,16 @@ +def pi := (-1.0).acos() + +def radians := pi / 4.0 +def degrees := 45.0 + +def d2r := (pi/180).multiply +def r2d := (180/pi).multiply + +println(`$\ +${radians.sin()} ${d2r(degrees).sin()} +${radians.cos()} ${d2r(degrees).cos()} +${radians.tan()} ${d2r(degrees).tan()} +${def asin := radians.sin().asin()} ${r2d(asin)} +${def acos := radians.cos().acos()} ${r2d(acos)} +${def atan := radians.tan().atan()} ${r2d(atan)} +`) diff --git a/Task/Trigonometric-functions/Erlang/trigonometric-functions-1.erl b/Task/Trigonometric-functions/Erlang/trigonometric-functions-1.erl new file mode 100644 index 0000000000..26cae82a17 --- /dev/null +++ b/Task/Trigonometric-functions/Erlang/trigonometric-functions-1.erl @@ -0,0 +1,4 @@ +Deg=45. +Rad=math:pi()/4. + +math:sin(Deg * math:pi() / 180)==math:sin(Rad). diff --git a/Task/Trigonometric-functions/Erlang/trigonometric-functions-2.erl b/Task/Trigonometric-functions/Erlang/trigonometric-functions-2.erl new file mode 100644 index 0000000000..0af1109094 --- /dev/null +++ b/Task/Trigonometric-functions/Erlang/trigonometric-functions-2.erl @@ -0,0 +1 @@ +math:cos(Deg * math:pi() / 180)==math:cos(Rad). diff --git a/Task/Trigonometric-functions/Erlang/trigonometric-functions-3.erl b/Task/Trigonometric-functions/Erlang/trigonometric-functions-3.erl new file mode 100644 index 0000000000..0b39096cb6 --- /dev/null +++ b/Task/Trigonometric-functions/Erlang/trigonometric-functions-3.erl @@ -0,0 +1 @@ +math:tan(Deg * math:pi() / 180)==math:tan(Rad). diff --git a/Task/Trigonometric-functions/Erlang/trigonometric-functions-4.erl b/Task/Trigonometric-functions/Erlang/trigonometric-functions-4.erl new file mode 100644 index 0000000000..1554552bd3 --- /dev/null +++ b/Task/Trigonometric-functions/Erlang/trigonometric-functions-4.erl @@ -0,0 +1,2 @@ +Temp = math:acos(math:cos(Rad)). +Temp * 180 / math:pi()==Deg. diff --git a/Task/Trigonometric-functions/Erlang/trigonometric-functions-5.erl b/Task/Trigonometric-functions/Erlang/trigonometric-functions-5.erl new file mode 100644 index 0000000000..edfca4e55f --- /dev/null +++ b/Task/Trigonometric-functions/Erlang/trigonometric-functions-5.erl @@ -0,0 +1,2 @@ +Temp = math:atan(math:tan(Rad)). +Temp * 180 / math:pi()==Deg. diff --git a/Task/Trigonometric-functions/Fantom/trigonometric-functions.fantom b/Task/Trigonometric-functions/Fantom/trigonometric-functions.fantom new file mode 100644 index 0000000000..8f82e35054 --- /dev/null +++ b/Task/Trigonometric-functions/Fantom/trigonometric-functions.fantom @@ -0,0 +1,20 @@ +class Main +{ + public static Void main () + { + Float r := Float.pi / 4 + echo (r.sin) + echo (r.cos) + echo (r.tan) + echo (r.asin) + echo (r.acos) + echo (r.atan) + // and from degrees + echo (45.0f.toRadians.sin) + echo (45.0f.toRadians.cos) + echo (45.0f.toRadians.tan) + echo (45.0f.toRadians.asin) + echo (45.0f.toRadians.acos) + echo (45.0f.toRadians.atan) + } +} diff --git a/Task/Trigonometric-functions/Forth/trigonometric-functions.fth b/Task/Trigonometric-functions/Forth/trigonometric-functions.fth new file mode 100644 index 0000000000..1258bf80bb --- /dev/null +++ b/Task/Trigonometric-functions/Forth/trigonometric-functions.fth @@ -0,0 +1,8 @@ +45e pi f* 180e f/ \ radians + +cr fdup fsin f. \ also available: fsincos ( r -- sin cos ) +cr fdup fcos f. +cr fdup ftan f. +cr fdup fasin f. +cr fdup facos f. +cr fatan f. \ also available: fatan2 ( r1 r2 -- atan[r1/r2] ) diff --git a/Task/Trigonometric-functions/Fortran/trigonometric-functions-1.f b/Task/Trigonometric-functions/Fortran/trigonometric-functions-1.f new file mode 100644 index 0000000000..d90995f082 --- /dev/null +++ b/Task/Trigonometric-functions/Fortran/trigonometric-functions-1.f @@ -0,0 +1,18 @@ +PROGRAM Trig + + REAL pi, dtor, rtod, radians, degrees + + pi = 4.0 * ATAN(1.0) + dtor = pi / 180.0 + rtod = 180.0 / pi + radians = pi / 4.0 + degrees = 45.0 + + WRITE(*,*) SIN(radians), SIN(degrees*dtor) + WRITE(*,*) COS(radians), COS(degrees*dtor) + WRITE(*,*) TAN(radians), TAN(degrees*dtor) + WRITE(*,*) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod + WRITE(*,*) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod + WRITE(*,*) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod + +END PROGRAM Trig diff --git a/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f b/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f new file mode 100644 index 0000000000..fbcdf9e10a --- /dev/null +++ b/Task/Trigonometric-functions/Fortran/trigonometric-functions-2.f @@ -0,0 +1,4 @@ +ATAN2(y,x) ! Arctangent(y/x), ''-pi < result <= +pi'' +SINH(x) ! Hyperbolic sine +COSH(x) ! Hyperbolic cosine +TANH(x) ! Hyperbolic tangent diff --git a/Task/Trigonometric-functions/Go/trigonometric-functions.go b/Task/Trigonometric-functions/Go/trigonometric-functions.go new file mode 100644 index 0000000000..046b356923 --- /dev/null +++ b/Task/Trigonometric-functions/Go/trigonometric-functions.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "math" +) + +const d = 30. +const r = d * math.Pi / 180 + +var s = .5 +var c = math.Sqrt(3) / 2 +var t = 1 / math.Sqrt(3) + +func main() { + fmt.Printf("sin(%9.6f deg) = %f\n", d, math.Sin(d*math.Pi/180)) + fmt.Printf("sin(%9.6f rad) = %f\n", r, math.Sin(r)) + fmt.Printf("cos(%9.6f deg) = %f\n", d, math.Cos(d*math.Pi/180)) + fmt.Printf("cos(%9.6f rad) = %f\n", r, math.Cos(r)) + fmt.Printf("tan(%9.6f deg) = %f\n", d, math.Tan(d*math.Pi/180)) + fmt.Printf("tan(%9.6f rad) = %f\n", r, math.Tan(r)) + fmt.Printf("asin(%f) = %9.6f deg\n", s, math.Asin(s)*180/math.Pi) + fmt.Printf("asin(%f) = %9.6f rad\n", s, math.Asin(s)) + fmt.Printf("acos(%f) = %9.6f deg\n", c, math.Acos(c)*180/math.Pi) + fmt.Printf("acos(%f) = %9.6f rad\n", c, math.Acos(c)) + fmt.Printf("atan(%f) = %9.6f deg\n", t, math.Atan(t)*180/math.Pi) + fmt.Printf("atan(%f) = %9.6f rad\n", t, math.Atan(t)) +} diff --git a/Task/Trigonometric-functions/Groovy/trigonometric-functions.groovy b/Task/Trigonometric-functions/Groovy/trigonometric-functions.groovy new file mode 100644 index 0000000000..4c2b4daae4 --- /dev/null +++ b/Task/Trigonometric-functions/Groovy/trigonometric-functions.groovy @@ -0,0 +1,12 @@ +def radians = Math.PI/4 +def degrees = 45 + +def d2r = { it*Math.PI/180 } +def r2d = { it*180/Math.PI } + +println "sin(\u03C0/4) = ${Math.sin(radians)} == sin(45\u00B0) = ${Math.sin(d2r(degrees))}" +println "cos(\u03C0/4) = ${Math.cos(radians)} == cos(45\u00B0) = ${Math.cos(d2r(degrees))}" +println "tan(\u03C0/4) = ${Math.tan(radians)} == tan(45\u00B0) = ${Math.tan(d2r(degrees))}" +println "asin(\u221A2/2) = ${Math.asin(2**(-0.5))} == asin(\u221A2/2)\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\u00B0" +println "acos(\u221A2/2) = ${Math.acos(2**(-0.5))} == acos(\u221A2/2)\u00B0 = ${r2d(Math.acos(2**(-0.5)))}\u00B0" +println "atan(1) = ${Math.atan(1)} == atan(1)\u00B0 = ${r2d(Math.atan(1))}\u00B0" diff --git a/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs b/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs new file mode 100644 index 0000000000..536ca9dbcf --- /dev/null +++ b/Task/Trigonometric-functions/Haskell/trigonometric-functions.hs @@ -0,0 +1,10 @@ +fromDegrees deg = deg * pi / 180 +toDegrees rad = rad * 180 / pi + +example = [ + sin (pi / 6), sin (fromDegrees 30), + cos (pi / 6), cos (fromDegrees 30), + tan (pi / 6), tan (fromDegrees 30), + asin 0.5, toDegrees (asin 0.5), + acos 0.5, toDegrees (acos 0.5), + atan 0.5, toDegrees (atan 0.5)] diff --git a/Task/Trigonometric-functions/HicEst/trigonometric-functions-1.hicest b/Task/Trigonometric-functions/HicEst/trigonometric-functions-1.hicest new file mode 100644 index 0000000000..7774fa1a95 --- /dev/null +++ b/Task/Trigonometric-functions/HicEst/trigonometric-functions-1.hicest @@ -0,0 +1,12 @@ +pi = 4.0 * ATAN(1.0) +dtor = pi / 180.0 +rtod = 180.0 / pi +radians = pi / 4.0 +degrees = 45.0 + +WRITE(ClipBoard) SIN(radians), SIN(degrees*dtor) +WRITE(ClipBoard) COS(radians), COS(degrees*dtor) +WRITE(ClipBoard) TAN(radians), TAN(degrees*dtor) +WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod +WRITE(ClipBoard) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod +WRITE(ClipBoard) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod diff --git a/Task/Trigonometric-functions/HicEst/trigonometric-functions-2.hicest b/Task/Trigonometric-functions/HicEst/trigonometric-functions-2.hicest new file mode 100644 index 0000000000..3aa426bffe --- /dev/null +++ b/Task/Trigonometric-functions/HicEst/trigonometric-functions-2.hicest @@ -0,0 +1,6 @@ +0.7071067812 0.7071067812 +0.7071067812 0.7071067812 +1 1 +0.7853981634 45 +0.7853981634 45 +0.7853981634 45 diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-1.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-1.idl new file mode 100644 index 0000000000..12565533e9 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-1.idl @@ -0,0 +1,2 @@ +deg = 35 ; arbitrary number of degrees +rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-2.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-2.idl new file mode 100644 index 0000000000..28aae66bf8 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-2.idl @@ -0,0 +1,9 @@ +; the trig functions receive and emit radians: +print, rad, sin(rad), asin(sin(rad)) +print, cos(rad), acos(cos(rad)) +print, tan(rad), atan(tan(rad)) ; etc + +; prints the following: +; 0.610865 0.573576 0.610865 +; 0.819152 0.610865 +; 0.700208 0.610865 diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-3.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-3.idl new file mode 100644 index 0000000000..7c9dc33083 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-3.idl @@ -0,0 +1,5 @@ +; the hyperbolic versions exist and behave as expected: +print, sinh(rad) ; etc + +; outputs +; 0.649572 diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-4.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-4.idl new file mode 100644 index 0000000000..bc5c485ee8 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-4.idl @@ -0,0 +1,8 @@ +;If the input is an array, the output has the same dimensions etc as the input: +x = !dpi/[[2,3],[4,5],[6,7]] ; !dpi is a read-only sysvar = 3.1415... +print,sin(x) + +;outputs: +; 1.0000000 0.86602540 +; 0.70710678 0.58778525 +; 0.50000000 0.43388374 diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-5.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-5.idl new file mode 100644 index 0000000000..c03cbd9f91 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-5.idl @@ -0,0 +1,6 @@ +; the trig functions behave as expected for complex arguments: +x = complex(1,2) +print,sin(x) + +; outputs +; ( 3.16578, 1.95960) diff --git a/Task/Trigonometric-functions/IDL/trigonometric-functions-6.idl b/Task/Trigonometric-functions/IDL/trigonometric-functions-6.idl new file mode 100644 index 0000000000..65f2c44435 --- /dev/null +++ b/Task/Trigonometric-functions/IDL/trigonometric-functions-6.idl @@ -0,0 +1,8 @@ +invocable all +procedure main() + +d := 30 # degrees +r := dtor(d) # convert to radians + +every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") +end diff --git a/Task/Trigonometric-functions/J/trigonometric-functions-1.j b/Task/Trigonometric-functions/J/trigonometric-functions-1.j new file mode 100644 index 0000000000..1f128a4518 --- /dev/null +++ b/Task/Trigonometric-functions/J/trigonometric-functions-1.j @@ -0,0 +1 @@ + >,:(1&o. ; 2&o. ; 3&o.) (4%~o. 1), 180%~o. 45 diff --git a/Task/Trigonometric-functions/J/trigonometric-functions-2.j b/Task/Trigonometric-functions/J/trigonometric-functions-2.j new file mode 100644 index 0000000000..2d42bfe3be --- /dev/null +++ b/Task/Trigonometric-functions/J/trigonometric-functions-2.j @@ -0,0 +1 @@ + >,:([ , 180p_1&*)&.> (_1&o. ; _2&o. ; _3&o.) 0.5 diff --git a/Task/Trigonometric-functions/Java/trigonometric-functions.java b/Task/Trigonometric-functions/Java/trigonometric-functions.java new file mode 100644 index 0000000000..629593079b --- /dev/null +++ b/Task/Trigonometric-functions/Java/trigonometric-functions.java @@ -0,0 +1,22 @@ +public class Trig { + public static void main(String[] args) { + //Pi / 4 is 45 degrees. All answers should be the same. + double radians = Math.PI / 4; + double degrees = 45.0; + //sine + System.out.println(Math.sin(radians) + " " + Math.sin(Math.toRadians(degrees))); + //cosine + System.out.println(Math.cos(radians) + " " + Math.cos(Math.toRadians(degrees))); + //tangent + System.out.println(Math.tan(radians) + " " + Math.tan(Math.toRadians(degrees))); + //arcsine + double arcsin = Math.asin(Math.sin(radians)); + System.out.println(arcsin + " " + Math.toDegrees(arcsin)); + //arccosine + double arccos = Math.acos(Math.cos(radians)); + System.out.println(arccos + " " + Math.toDegrees(arccos)); + //arctangent + double arctan = Math.atan(Math.tan(radians)); + System.out.println(arctan + " " + Math.toDegrees(arctan)); + } +} diff --git a/Task/Trigonometric-functions/JavaScript/trigonometric-functions.js b/Task/Trigonometric-functions/JavaScript/trigonometric-functions.js new file mode 100644 index 0000000000..b69028266e --- /dev/null +++ b/Task/Trigonometric-functions/JavaScript/trigonometric-functions.js @@ -0,0 +1,22 @@ +var + radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same. + degrees = 45.0, + sine = Math.sin(radians), + cosine = Math.cos(radians), + tangent = Math.tan(radians), + arcsin = Math.asin(sine), + arccos = Math.acos(cosine), + arctan = Math.atan(tangent); + +// sine +window.alert(sine + " " + Math.sin(degrees * Math.PI / 180)); +// cosine +window.alert(cosine + " " + Math.cos(degrees * Math.PI / 180)); +// tangent +window.alert(tangent + " " + Math.tan(degrees * Math.PI / 180)); +// arcsine +window.alert(arcsin + " " + (arcsin * 180 / Math.PI)); +// arccosine +window.alert(arccos + " " + (arccos * 180 / Math.PI)); +// arctangent +window.alert(arctan + " " + (arctan * 180 / Math.PI)); diff --git a/Task/Trigonometric-functions/Liberty-BASIC/trigonometric-functions.liberty b/Task/Trigonometric-functions/Liberty-BASIC/trigonometric-functions.liberty new file mode 100644 index 0000000000..19bbe5f6e2 --- /dev/null +++ b/Task/Trigonometric-functions/Liberty-BASIC/trigonometric-functions.liberty @@ -0,0 +1,14 @@ +pi = ACS(-1) +radians = pi / 4.0 +rtod = 180 / pi +degrees = radians * rtod +dtor = pi / 180 + +'LB works in radians, so degrees require conversion +print "Sin: ";SIN(radians);" "; SIN(degrees*dtor) +print "Cos: ";COS(radians);" "; COS(degrees*dtor) +print "Tan: ";TAN(radians);" ";TAN(degrees*dtor) +print "- Inverse functions:" +print "Asn: ";ASN(SIN(radians));" Rad, "; ASN(SIN(degrees*dtor))*rtod;" Deg" +print "Acs: ";ACS(COS(radians));" Rad, "; ACS(COS(degrees*dtor))*rtod;" Deg" +print "Atn: ";ATN(TAN(radians));" Rad, "; ATN(TAN(degrees*dtor))*rtod;" Deg" diff --git a/Task/Trigonometric-functions/Logo/trigonometric-functions-1.logo b/Task/Trigonometric-functions/Logo/trigonometric-functions-1.logo new file mode 100644 index 0000000000..e22cc87ca0 --- /dev/null +++ b/Task/Trigonometric-functions/Logo/trigonometric-functions-1.logo @@ -0,0 +1,7 @@ +print sin 45 +print cos 45 +print arctan 1 +make "pi (radarctan 0 1) * 2 ; based on quadrant if uses two parameters +print radsin :pi / 4 +print radcos :pi / 4 +print 4 * radarctan 1 diff --git a/Task/Trigonometric-functions/Logo/trigonometric-functions-2.logo b/Task/Trigonometric-functions/Logo/trigonometric-functions-2.logo new file mode 100644 index 0000000000..96d2f03a26 --- /dev/null +++ b/Task/Trigonometric-functions/Logo/trigonometric-functions-2.logo @@ -0,0 +1,6 @@ +print sin 45 +print cos 45 +print arctan 1 +print radsin pi / 4 +print radcos pi / 4 +print 4 * radarctan 1 diff --git a/Task/Trigonometric-functions/Lua/trigonometric-functions.lua b/Task/Trigonometric-functions/Lua/trigonometric-functions.lua new file mode 100644 index 0000000000..f23beb8d66 --- /dev/null +++ b/Task/Trigonometric-functions/Lua/trigonometric-functions.lua @@ -0,0 +1 @@ +print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4)) diff --git a/Task/Trigonometric-functions/MATLAB/trigonometric-functions-1.m b/Task/Trigonometric-functions/MATLAB/trigonometric-functions-1.m new file mode 100644 index 0000000000..f367984a3e --- /dev/null +++ b/Task/Trigonometric-functions/MATLAB/trigonometric-functions-1.m @@ -0,0 +1,13 @@ +function trigExample(angleDegrees) + + angleRadians = angleDegrees * (pi/180); + + disp(sprintf('sin(%f)= %f\nasin(%f)= %f',[angleRadians sin(angleRadians) sin(angleRadians) asin(sin(angleRadians))])); + disp(sprintf('sind(%f)= %f\narcsind(%f)= %f',[angleDegrees sind(angleDegrees) sind(angleDegrees) asind(sind(angleDegrees))])); + disp('-----------------------'); + disp(sprintf('cos(%f)= %f\nacos(%f)= %f',[angleRadians cos(angleRadians) cos(angleRadians) acos(cos(angleRadians))])); + disp(sprintf('cosd(%f)= %f\narccosd(%f)= %f',[angleDegrees cosd(angleDegrees) cosd(angleDegrees) acosd(cosd(angleDegrees))])); + disp('-----------------------'); + disp(sprintf('tan(%f)= %f\natan(%f)= %f',[angleRadians tan(angleRadians) tan(angleRadians) atan(tan(angleRadians))])); + disp(sprintf('tand(%f)= %f\narctand(%f)= %f',[angleDegrees tand(angleDegrees) tand(angleDegrees) atand(tand(angleDegrees))])); +end diff --git a/Task/Trigonometric-functions/MATLAB/trigonometric-functions-2.m b/Task/Trigonometric-functions/MATLAB/trigonometric-functions-2.m new file mode 100644 index 0000000000..bab84bf6a4 --- /dev/null +++ b/Task/Trigonometric-functions/MATLAB/trigonometric-functions-2.m @@ -0,0 +1,15 @@ +>> trigExample(78) +sin(1.361357)= 0.978148 +asin(0.978148)= 1.361357 +sind(78.000000)= 0.978148 +arcsind(0.978148)= 78.000000 +----------------------- +cos(1.361357)= 0.207912 +acos(0.207912)= 1.361357 +cosd(78.000000)= 0.207912 +arccosd(0.207912)= 78.000000 +----------------------- +tan(1.361357)= 4.704630 +atan(4.704630)= 1.361357 +tand(78.000000)= 4.704630 +arctand(4.704630)= 78.000000 diff --git a/Task/Trigonometric-functions/MAXScript/trigonometric-functions.maxscript b/Task/Trigonometric-functions/MAXScript/trigonometric-functions.maxscript new file mode 100644 index 0000000000..f5e356d58b --- /dev/null +++ b/Task/Trigonometric-functions/MAXScript/trigonometric-functions.maxscript @@ -0,0 +1,21 @@ +local radians = pi / 4 +local degrees = 45.0 + +--sine +print (sin (radToDeg radians)) +print (sin degrees) +--cosine +print (cos (radToDeg radians)) +print (cos degrees) +--tangent +print (tan (radToDeg radians)) +print (tan degrees) +--arcsine +print (asin (sin (radToDeg radians))) +print (asin (sin degrees)) +--arccosine +print (acos (cos (radToDeg radians))) +print (acos (cos degrees)) +--arctangent +print (atan (tan (radToDeg radians))) +print (atan (tan degrees)) diff --git a/Task/Trigonometric-functions/Mathematica/trigonometric-functions.math b/Task/Trigonometric-functions/Mathematica/trigonometric-functions.math new file mode 100644 index 0000000000..29b96e729e --- /dev/null +++ b/Task/Trigonometric-functions/Mathematica/trigonometric-functions.math @@ -0,0 +1,9 @@ +Sin[1] +Cos[1] +Tan[1] +ArcSin[1] +ArcCos[1] +ArcTan[1] +Sin[90 Degree] +Cos[90 Degree] +Tan[90 Degree] diff --git a/Task/Trigonometric-functions/Maxima/trigonometric-functions.maxima b/Task/Trigonometric-functions/Maxima/trigonometric-functions.maxima new file mode 100644 index 0000000000..f79635fb16 --- /dev/null +++ b/Task/Trigonometric-functions/Maxima/trigonometric-functions.maxima @@ -0,0 +1,10 @@ +a: %pi / 3; +[sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)]; + +b: 1 / 2; +[asin(b), acos(b), atan(b), asec(1 / b), acsc(1 / b), acot(b)]; + +/* Hyperbolic functions are also available */ +a: 1 / 2; +[sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer; +[asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(1 / a)], numer; diff --git a/Task/Trigonometric-functions/Metafont/trigonometric-functions.metafont b/Task/Trigonometric-functions/Metafont/trigonometric-functions.metafont new file mode 100644 index 0000000000..30d604a8e5 --- /dev/null +++ b/Task/Trigonometric-functions/Metafont/trigonometric-functions.metafont @@ -0,0 +1,46 @@ +Pi := 3.14159; +vardef torad expr x = Pi*x/180 enddef; % conversions +vardef todeg expr x = 180x/Pi enddef; +vardef sin expr x = sind(todeg(x)) enddef; % radians version of sind +vardef cos expr x = cosd(todeg(x)) enddef; % and cosd + +vardef sign expr x = if x>=0: 1 else: -1 fi enddef; % commodity + +vardef tand expr x = % tan with arg in degree + if cosd(x) = 0: + infinity * sign(sind(x)) + else: sind(x)/cosd(x) fi enddef; +vardef tan expr x = tand(todeg(x)) enddef; % arg in rad + +% INVERSE + +% the arc having x as tanget is that between x-axis and a line +% from the center to the point (1, x); MF angle says this +vardef atand expr x = angle(1,x) enddef; +vardef atan expr x = torad(atand(x)) enddef; % rad version + +% known formula to express asin and acos in function of +% atan; a+-+b stays for sqrt(a^2 - b^2) (defined in plain MF) +vardef asin expr x = 2atan(x/(1+(1+-+x))) enddef; +vardef acos expr x = 2atan((1+-+x)/(1+x)) enddef; + +vardef asind expr x = todeg(asin(x)) enddef; % degree versions +vardef acosd expr x = todeg(acos(x)) enddef; + +% commodity +def outcompare(expr a, b) = message decimal a & " = " & decimal b enddef; + +% output tests +outcompare(torad(60), Pi/3); +outcompare(todeg(Pi/6), 30); + +outcompare(Pi/3, asin(sind(60))); +outcompare(30, acosd(cos(Pi/6))); +outcompare(45, atand(tand(45))); +outcompare(Pi/4, atan(tand(45))); + +outcompare(sin(Pi/3), sind(60)); +outcompare(cos(Pi/4), cosd(45)); +outcompare(tan(Pi/3), tand(60)); + +end diff --git a/Task/Trigonometric-functions/NetRexx/trigonometric-functions.netrexx b/Task/Trigonometric-functions/NetRexx/trigonometric-functions.netrexx new file mode 100644 index 0000000000..db166e16bf --- /dev/null +++ b/Task/Trigonometric-functions/NetRexx/trigonometric-functions.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary utf8 + +numeric digits 30 + +parse 'Radians Degrees angle' RADIANS DEGREES ANGLE .; +parse 'sine cosine tangent arcsine arccosine arctangent' SINE COSINE TANGENT ARCSINE ARCCOSINE ARCTANGENT . + +trigVals = '' +trigVals[RADIANS, ANGLE ] = (Rexx Math.PI) / 4 -- Pi/4 == 45 degrees +trigVals[DEGREES, ANGLE ] = 45.0 +trigVals[RADIANS, SINE ] = (Rexx Math.sin(trigVals[RADIANS, ANGLE])) +trigVals[DEGREES, SINE ] = (Rexx Math.sin(Math.toRadians(trigVals[DEGREES, ANGLE]))) +trigVals[RADIANS, COSINE ] = (Rexx Math.cos(trigVals[RADIANS, ANGLE])) +trigVals[DEGREES, COSINE ] = (Rexx Math.cos(Math.toRadians(trigVals[DEGREES, ANGLE]))) +trigVals[RADIANS, TANGENT ] = (Rexx Math.tan(trigVals[RADIANS, ANGLE])) +trigVals[DEGREES, TANGENT ] = (Rexx Math.tan(Math.toRadians(trigVals[DEGREES, ANGLE]))) +trigVals[RADIANS, ARCSINE ] = (Rexx Math.asin(trigVals[RADIANS, SINE])) +trigVals[DEGREES, ARCSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, SINE]))) +trigVals[RADIANS, ARCCOSINE ] = (Rexx Math.acos(trigVals[RADIANS, COSINE])) +trigVals[DEGREES, ARCCOSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, COSINE]))) +trigVals[RADIANS, ARCTANGENT] = (Rexx Math.atan(trigVals[RADIANS, TANGENT])) +trigVals[DEGREES, ARCTANGENT] = (Rexx Math.toDegrees(Math.atan(trigVals[DEGREES, TANGENT]))) + +say ' '.right(12)'|' RADIANS.right(17) '|' DEGREES.right(17) '|' +say ANGLE.right(12)'|' trigVals[RADIANS, ANGLE ].format(4, 12) '|' trigVals[DEGREES, ANGLE ].format(4, 12) '|' +say SINE.right(12)'|' trigVals[RADIANS, SINE ].format(4, 12) '|' trigVals[DEGREES, SINE ].format(4, 12) '|' +say COSINE.right(12)'|' trigVals[RADIANS, COSINE ].format(4, 12) '|' trigVals[DEGREES, COSINE ].format(4, 12) '|' +say TANGENT.right(12)'|' trigVals[RADIANS, TANGENT ].format(4, 12) '|' trigVals[DEGREES, TANGENT ].format(4, 12) '|' +say ARCSINE.right(12)'|' trigVals[RADIANS, ARCSINE ].format(4, 12) '|' trigVals[DEGREES, ARCSINE ].format(4, 12) '|' +say ARCCOSINE.right(12)'|' trigVals[RADIANS, ARCCOSINE ].format(4, 12) '|' trigVals[DEGREES, ARCCOSINE ].format(4, 12) '|' +say ARCTANGENT.right(12)'|' trigVals[RADIANS, ARCTANGENT].format(4, 12) '|' trigVals[DEGREES, ARCTANGENT].format(4, 12) '|' +say + +return diff --git a/Task/Trigonometric-functions/OCaml/trigonometric-functions.ocaml b/Task/Trigonometric-functions/OCaml/trigonometric-functions.ocaml new file mode 100644 index 0000000000..d8e5fe160b --- /dev/null +++ b/Task/Trigonometric-functions/OCaml/trigonometric-functions.ocaml @@ -0,0 +1,14 @@ +let pi = 4. *. atan 1. + +let radians = pi /. 4. +let degrees = 45.;; + +Printf.printf "%f %f\n" (sin radians) (sin (degrees *. pi /. 180.));; +Printf.printf "%f %f\n" (cos radians) (cos (degrees *. pi /. 180.));; +Printf.printf "%f %f\n" (tan radians) (tan (degrees *. pi /. 180.));; +let arcsin = asin (sin radians);; +Printf.printf "%f %f\n" arcsin (arcsin *. 180. /. pi);; +let arccos = acos (cos radians);; +Printf.printf "%f %f\n" arccos (arccos *. 180. /. pi);; +let arctan = atan (tan radians);; +Printf.printf "%f %f\n" arctan (arctan *. 180. /. pi);; diff --git a/Task/Trigonometric-functions/Octave/trigonometric-functions.octave b/Task/Trigonometric-functions/Octave/trigonometric-functions.octave new file mode 100644 index 0000000000..79de3e9f10 --- /dev/null +++ b/Task/Trigonometric-functions/Octave/trigonometric-functions.octave @@ -0,0 +1,21 @@ +function d = degree(rad) + d = 180*rad/pi; +endfunction + +r = pi/3; +rd = degree(r); + +funcs = { "sin", "cos", "tan", "sec", "cot", "csc" }; +ifuncs = { "asin", "acos", "atan", "asec", "acot", "acsc" }; + +for i = 1 : numel(funcs) + v = arrayfun(funcs{i}, r); + vd = arrayfun(strcat(funcs{i}, "d"), rd); + iv = arrayfun(ifuncs{i}, v); + ivd = arrayfun(strcat(ifuncs{i}, "d"), vd); + printf("%s(%f) = %s(%f) = %f (%f)\n", + funcs{i}, r, strcat(funcs{i}, "d"), rd, v, vd); + printf("%s(%f) = %f\n%s(%f) = %f\n", + ifuncs{i}, v, iv, + strcat(ifuncs{i}, "d"), vd, ivd); +endfor diff --git a/Task/Trigonometric-functions/Oz/trigonometric-functions.oz b/Task/Trigonometric-functions/Oz/trigonometric-functions.oz new file mode 100644 index 0000000000..5d7d2f0628 --- /dev/null +++ b/Task/Trigonometric-functions/Oz/trigonometric-functions.oz @@ -0,0 +1,21 @@ +declare + PI = 3.14159265 + + fun {FromDegrees Deg} + Deg * PI / 180. + end + + fun {ToDegrees Rad} + Rad * 180. / PI + end + + Radians = PI / 4. + Degrees = 45. +in + for F in [Sin Cos Tan] do + {System.showInfo {F Radians}#" "#{F {FromDegrees Degrees}}} + end + + for I#F in [Asin#Sin Acos#Cos Atan#Tan] do + {System.showInfo {I {F Radians}}#" "#{ToDegrees {I {F Radians}}}} + end diff --git a/Task/Trigonometric-functions/PARI-GP/trigonometric-functions.pari b/Task/Trigonometric-functions/PARI-GP/trigonometric-functions.pari new file mode 100644 index 0000000000..1872d298fb --- /dev/null +++ b/Task/Trigonometric-functions/PARI-GP/trigonometric-functions.pari @@ -0,0 +1,6 @@ +cos(Pi/2) +sin(Pi/2) +tan(Pi/2) +acos(1) +asin(1) +atan(1) diff --git a/Task/Trigonometric-functions/PHP/trigonometric-functions.php b/Task/Trigonometric-functions/PHP/trigonometric-functions.php new file mode 100644 index 0000000000..00a542d92a --- /dev/null +++ b/Task/Trigonometric-functions/PHP/trigonometric-functions.php @@ -0,0 +1,8 @@ +$radians = M_PI / 4; +$degrees = 45 * M_PI / 180; +echo sin($radians) . " " . sin($degrees); +echo cos($radians) . " " . cos($degrees); +echo tan($radians) . " " . tan($degrees); +echo asin(sin($radians)) . " " . asin(sin($radians)) * 180 / M_PI; +echo acos(cos($radians)) . " " . acos(cos($radians)) * 180 / M_PI; +echo atan(tan($radians)) . " " . atan(tan($radians)) * 180 / M_PI; diff --git a/Task/Trigonometric-functions/PL-I/trigonometric-functions.pli b/Task/Trigonometric-functions/PL-I/trigonometric-functions.pli new file mode 100644 index 0000000000..5f599a968c --- /dev/null +++ b/Task/Trigonometric-functions/PL-I/trigonometric-functions.pli @@ -0,0 +1,18 @@ +declare (x, xd, y, v) float; + +x = 0.5; xd = 45; + +/* angle in radians: */ +v = sin(x); y = asin(v); put skip list (y); +v = cos(x); y = acos(v); put skip list (y); +v = tan(x); y = atan(v); put skip list (y); + +/* angle in degrees: */ +v = sind(xd); put skip list (v); +v = cosd(xd); put skip list (v); +v = tand(xd); y = atand(v); put skip list (y); + +/* hyperbolic functions: */ +v = sinh(x); put skip list (v); +v = cosh(x); put skip list (v); +v = tanh(x); y = atanh(v); put skip list (y); diff --git a/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-1.sql b/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-1.sql new file mode 100644 index 0000000000..6dc3ae9e0c --- /dev/null +++ b/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-1.sql @@ -0,0 +1,12 @@ +DECLARE + pi NUMBER := 4 * atan(1); + radians NUMBER := pi / 4; + degrees NUMBER := 45.0; +BEGIN + DBMS_OUTPUT.put_line(SIN(radians) || ' ' || SIN(degrees * pi/180) ); + DBMS_OUTPUT.put_line(COS(radians) || ' ' || COS(degrees * pi/180) ); + DBMS_OUTPUT.put_line(TAN(radians) || ' ' || TAN(degrees * pi/180) ); + DBMS_OUTPUT.put_line(ASIN(SIN(radians)) || ' ' || ASIN(SIN(degrees * pi/180)) * 180/pi); + DBMS_OUTPUT.put_line(ACOS(COS(radians)) || ' ' || ACOS(COS(degrees * pi/180)) * 180/pi); + DBMS_OUTPUT.put_line(ATAN(TAN(radians)) || ' ' || ATAN(TAN(degrees * pi/180)) * 180/pi); +end; diff --git a/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-2.sql b/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-2.sql new file mode 100644 index 0000000000..4cda61629d --- /dev/null +++ b/Task/Trigonometric-functions/PL-SQL/trigonometric-functions-2.sql @@ -0,0 +1,4 @@ +ATAN2(n1,n2) --Arctangent(y/x), -pi < result <= +pi +SINH(n) --Hyperbolic sine +COSH(n) --Hyperbolic cosine +TANH(n) --Hyperbolic tangent diff --git a/Task/Trigonometric-functions/Pascal/trigonometric-functions.pascal b/Task/Trigonometric-functions/Pascal/trigonometric-functions.pascal new file mode 100644 index 0000000000..d0034af28e --- /dev/null +++ b/Task/Trigonometric-functions/Pascal/trigonometric-functions.pascal @@ -0,0 +1,21 @@ +Program TrigonometricFuntions(output); + +uses + math; + +var + radians, degree: double; + +begin + radians := pi / 4.0; + degree := 45; + // Pascal works in radians. Necessary degree-radian conversions are shown. + writeln (sin(radians),' ', sin(degree/180*pi)); + writeln (cos(radians),' ', cos(degree/180*pi)); + writeln (tan(radians),' ', tan(degree/180*pi)); + writeln (); + writeln (arcsin(sin(radians)),' Rad., or ', arcsin(sin(degree/180*pi))/pi*180,' Deg.'); + writeln (arccos(cos(radians)),' Rad., or ', arccos(cos(degree/180*pi))/pi*180,' Deg.'); + writeln (arctan(tan(radians)),' Rad., or ', arctan(tan(degree/180*pi))/pi*180,' Deg.'); + // ( radians ) / pi * 180 = deg. +end. diff --git a/Task/Trigonometric-functions/Perl-6/trigonometric-functions.pl6 b/Task/Trigonometric-functions/Perl-6/trigonometric-functions.pl6 new file mode 100644 index 0000000000..6a27e394ad --- /dev/null +++ b/Task/Trigonometric-functions/Perl-6/trigonometric-functions.pl6 @@ -0,0 +1,7 @@ +say sin(pi/3), ' ', sin 60, 'd'; # 'g' (gradians) and 1 (circles) +say cos(pi/4), ' ', cos 45, 'd'; # are also recognized. +say tan(pi/6), ' ', tan 30, 'd'; + +say asin(sqrt(3)/2), ' ', asin sqrt(3)/2, 'd'; +say acos(1/sqrt 2), ' ', acos 1/sqrt(2), 'd'; +say atan(1/sqrt 3), ' ', atan 1/sqrt(3), 'd'; diff --git a/Task/Trigonometric-functions/Perl/trigonometric-functions.pl b/Task/Trigonometric-functions/Perl/trigonometric-functions.pl new file mode 100644 index 0000000000..e1d297e801 --- /dev/null +++ b/Task/Trigonometric-functions/Perl/trigonometric-functions.pl @@ -0,0 +1,17 @@ +use Math::Trig; + +my $angle_degrees = 45; +my $angle_radians = pi / 4; + +print sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), "\n"; +print cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), "\n"; +print tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), "\n"; +print cot($angle_radians), ' ', cot(deg2rad($angle_degrees)), "\n"; +my $asin = asin(sin($angle_radians)); +print $asin, ' ', rad2deg($asin), "\n"; +my $acos = acos(cos($angle_radians)); +print $acos, ' ', rad2deg($acos), "\n"; +my $atan = atan(tan($angle_radians)); +print $atan, ' ', rad2deg($atan), "\n"; +my $acot = acot(cot($angle_radians)); +print $acot, ' ', rad2deg($acot), "\n"; diff --git a/Task/Trigonometric-functions/PicoLisp/trigonometric-functions.l b/Task/Trigonometric-functions/PicoLisp/trigonometric-functions.l new file mode 100644 index 0000000000..2e9ba9115a --- /dev/null +++ b/Task/Trigonometric-functions/PicoLisp/trigonometric-functions.l @@ -0,0 +1,20 @@ +(load "@lib/math.l") + +(de dtor (Deg) + (*/ Deg pi 180.0) ) + +(de rtod (Rad) + (*/ Rad 180.0 pi) ) + +(prinl + (format (sin (/ pi 4)) *Scl) " " (format (sin (dtor 45.0)) *Scl) ) +(prinl + (format (cos (/ pi 4)) *Scl) " " (format (cos (dtor 45.0)) *Scl) ) +(prinl + (format (tan (/ pi 4)) *Scl) " " (format (tan (dtor 45.0)) *Scl) ) +(prinl + (format (asin (sin (/ pi 4))) *Scl) " " (format (rtod (asin (sin (dtor 45.0)))) *Scl) ) +(prinl + (format (acos (cos (/ pi 4))) *Scl) " " (format (rtod (acos (cos (dtor 45.0)))) *Scl) ) +(prinl + (format (atan (tan (/ pi 4))) *Scl) " " (format (rtod (atan (tan (dtor 45.0)))) *Scl) ) diff --git a/Task/Trigonometric-functions/Pop11/trigonometric-functions.pop11 b/Task/Trigonometric-functions/Pop11/trigonometric-functions.pop11 new file mode 100644 index 0000000000..81a11d61c5 --- /dev/null +++ b/Task/Trigonometric-functions/Pop11/trigonometric-functions.pop11 @@ -0,0 +1,15 @@ +sin(30) => +cos(45) => +tan(45) => +arcsin(0.7) => +arccos(0.7) => +arctan(0.7) => +;;; switch to radians +true -> popradians; + +sin(pi*30/180) => +cos(pi*45/180) => +tan(pi*45/180) => +arcsin(0.7) => +arccos(0.7) => +arctan(0.7) => diff --git a/Task/Trigonometric-functions/PostScript/trigonometric-functions.ps b/Task/Trigonometric-functions/PostScript/trigonometric-functions.ps new file mode 100644 index 0000000000..40144ab9b2 --- /dev/null +++ b/Task/Trigonometric-functions/PostScript/trigonometric-functions.ps @@ -0,0 +1,11 @@ +90 sin = + +60 cos = + +%tan of 45 degrees + +45 sin 45 cos div = + +%inverse tan ( arc tan of sqrt 3) + +3 sqrt 1 atan = diff --git a/Task/Trigonometric-functions/PowerShell/trigonometric-functions.psh b/Task/Trigonometric-functions/PowerShell/trigonometric-functions.psh new file mode 100644 index 0000000000..09b882ef31 --- /dev/null +++ b/Task/Trigonometric-functions/PowerShell/trigonometric-functions.psh @@ -0,0 +1,12 @@ +$rad = [Math]::PI / 4 +$deg = 45 +'{0,10} {1,10}' -f 'Radians','Degrees' +'{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI / 180) +'{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI / 180) +'{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI / 180) +$temp = [Math]::Asin([Math]::Sin($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) +$temp = [Math]::Acos([Math]::Cos($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) +$temp = [Math]::Atan([Math]::Tan($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) diff --git a/Task/Trigonometric-functions/PureBasic/trigonometric-functions.purebasic b/Task/Trigonometric-functions/PureBasic/trigonometric-functions.purebasic new file mode 100644 index 0000000000..a2dcba9112 --- /dev/null +++ b/Task/Trigonometric-functions/PureBasic/trigonometric-functions.purebasic @@ -0,0 +1,24 @@ +OpenConsole() + +Macro DegToRad(deg) + deg*#PI/180 +EndMacro +Macro RadToDeg(rad) + rad*180/#PI +EndMacro + +degree = 45 +radians.f = #PI/4 + +PrintN(StrF(Sin(DegToRad(degree)))+" "+StrF(Sin(radians))) +PrintN(StrF(Cos(DegToRad(degree)))+" "+StrF(Cos(radians))) +PrintN(StrF(Tan(DegToRad(degree)))+" "+StrF(Tan(radians))) + +arcsin.f = ASin(Sin(radians)) +PrintN(StrF(arcsin)+" "+Str(RadToDeg(arcsin))) +arccos.f = ACos(Cos(radians)) +PrintN(StrF(arccos)+" "+Str(RadToDeg(arccos))) +arctan.f = ATan(Tan(radians)) +PrintN(StrF(arctan)+" "+Str(RadToDeg(arctan))) + +Input() diff --git a/Task/Trigonometric-functions/Python/trigonometric-functions.py b/Task/Trigonometric-functions/Python/trigonometric-functions.py new file mode 100644 index 0000000000..e6a18e3e69 --- /dev/null +++ b/Task/Trigonometric-functions/Python/trigonometric-functions.py @@ -0,0 +1,20 @@ +Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 +Type "copyright", "credits" or "license()" for more information. +>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi +>>> rad, deg = pi/4, 45.0 +>>> print("Sine:", sin(rad), sin(radians(deg))) +Sine: 0.7071067811865475 0.7071067811865475 +>>> print("Cosine:", cos(rad), cos(radians(deg))) +Cosine: 0.7071067811865476 0.7071067811865476 +>>> print("Tangent:", tan(rad), tan(radians(deg))) +Tangent: 0.9999999999999999 0.9999999999999999 +>>> arcsine = asin(sin(rad)) +>>> print("Arcsine:", arcsine, degrees(arcsine)) +Arcsine: 0.7853981633974482 44.99999999999999 +>>> arccosine = acos(cos(rad)) +>>> print("Arccosine:", arccosine, degrees(arccosine)) +Arccosine: 0.7853981633974483 45.0 +>>> arctangent = atan(tan(rad)) +>>> print("Arctangent:", arctangent, degrees(arctangent)) +Arctangent: 0.7853981633974483 45.0 +>>> diff --git a/Task/Trigonometric-functions/R/trigonometric-functions.r b/Task/Trigonometric-functions/R/trigonometric-functions.r new file mode 100644 index 0000000000..4e5ffed723 --- /dev/null +++ b/Task/Trigonometric-functions/R/trigonometric-functions.r @@ -0,0 +1,23 @@ +deg <- function(radians) 180*radians/pi +rad <- function(degrees) degrees*pi/180 +sind <- function(ang) sin(rad(ang)) +cosd <- function(ang) cos(rad(ang)) +tand <- function(ang) tan(rad(ang)) +asind <- function(v) deg(asin(v)) +acosd <- function(v) deg(acos(v)) +atand <- function(v) deg(atan(v)) + +r <- pi/3 +rd <- deg(r) + +print( c( sin(r), sind(rd)) ) +print( c( cos(r), cosd(rd)) ) +print( c( tan(r), tand(rd)) ) + +S <- sin(pi/4) +C <- cos(pi/3) +T <- tan(pi/4) + +print( c( asin(S), asind(S) ) ) +print( c( acos(C), acosd(C) ) ) +print( c( atan(T), atand(T) ) ) diff --git a/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol b/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol new file mode 100644 index 0000000000..5206a15cd2 --- /dev/null +++ b/Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol @@ -0,0 +1,29 @@ +REBOL [ + Title: "Trigonometric Functions" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/Trigonometric_Functions +] + +radians: pi / 4 degrees: 45.0 + +; Unlike most languages, REBOL's trig functions work in degrees unless +; you specify differently. + +print [sine/radians radians sine degrees] +print [cosine/radians radians cosine degrees] +print [tangent/radians radians tangent degrees] + +d2r: func [ + "Convert degrees to radians." + d [number!] "Degrees" +][d * pi / 180] + +arcsin: arcsine sine degrees +print [d2r arcsin arcsin] + +arccos: arccosine cosine degrees +print [d2r arccos arccos] + +arctan: arctangent tangent degrees +print [d2r arctan arctan] diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx new file mode 100644 index 0000000000..fd11c97b29 --- /dev/null +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx @@ -0,0 +1,9 @@ + ┌──────────────────────────────────────────────────────────────────────────┐ + │ One common method that ensures enough accuracy in REXX is specifying │ + │ more precision (via NUMERIC DIGITS nnn) than is needed, and then │ + │ displaying the number of digits that are desired, or the number(s) │ + │ could be re-normalized using the FORMAT bif. │ + │ │ + │ The technique used (below) is to set the numeric digits ten higher │ + │ than the desired digits, as specified by the SHOWDIGS variable. │ + └──────────────────────────────────────────────────────────────────────────┘ diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx new file mode 100644 index 0000000000..51f55126eb --- /dev/null +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx @@ -0,0 +1,109 @@ +/*REXX program demonstrates some common trig functions (30 digits shown)*/ +showdigs=30 /*show only 30 digits of number. */ +numeric digits showdigs+10 /*DIGITS default is 9, but use */ + /*extra digs to prevent rounding.*/ +say 'Using' showdigs 'decimal digits precision.'; say + + do j=-180 to +180 by 15 /*let's just do a half-Monty. */ + stuff = right(j,4) 'degrees, rads='show( d2r(j)), + ' sin='show(sinD(j)), + ' cos='show(cosD(J)) + /*don't let TAN go postal.*/ + if abs(j)\==90 then stuff=stuff ' tan='show(tanD(j)) + say stuff + end /*j*/ + +say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */ + say right(k,4) 'radians, degs='show( r2d(k)), + ' Acos='show(Acos(k)), + ' Asin='show(Asin(k)), + ' Atan='show(Atan(k)) + end /*k*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────subroutines─────────────────────────*/ +Asin: procedure; arg x; if x<-1 | x>1 then call AsinErr; s=x*x + if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z + do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end + return z + +Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x) + return Asin(x/sqrt(1+x**2)) + +cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) + if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 + if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 + return .sinCos(1,1,-1) + +sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) + if abs(x)=pi() then return 0; return .sinCos(x,x,1) + +.sinCos: parse arg z 1 p,_,i; x=x*x + do k=2 by 2; _=-_*x/(k*(k+i));z=z+_;if z=p then leave;p=z;end; return z + +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric digits 11 + g=.sqrtGuess(); 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 +.sqrtGuess: if x<0 then call sqrtErr; 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 + +e: return, +2.7182818284590452353602874713526624977572470936999595749669676277240766303535 + /*Note: the "real: E subroutine returns E's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ + /*If more than 1 million digits are required, be patient. */ + +exp: procedure; arg x; ix=x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x=x-ix + z=1; _=1; w=z; do j=1; _=_*x/j; z=(z+_)/1; if z==w then leave; w=z; end + if z\==0 then z=z*e()**ix; return z + +pi: return, /*a bit of overkill, but hey !! */ +3.1415926535897932384626433832795028841971693993751058209749445923078164062862 + /*Note: the real PI subroutine returns PI's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ + /*John Machin's formula is used for calculating more digits. */ + /*If more than 1 million digits are required, be patient. */ + +Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) +AcosD: return r2d(Acos(arg(1))) +AsinD: return r2d(Asin(arg(1))) +cosD: return cos(d2r(arg(1))) +sinD: return sin(d2r(arg(1))) +tan: procedure; arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ +tanD: return tan(d2r(arg(1))) +d2d: return arg(1)//360 /*normalize degrees►1 unit circle*/ +d2r: return r2r(arg(1)*pi()/180) /*convert degrees ──► radians. */ +r2d: return d2d((arg(1)*180/pi())) /*convert radians ──► degrees. */ +r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ +show: return left(left('',arg(1)>=0)format(arg(1),,showdigs)/1,showdigs) +tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 +tanErr: call tellErr 'tan('||x") causes division by zero, X="||x +AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x +AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x +sqrtErr: call tellErr "sqrt(x), X can't be negative, X="||x + /* ┌───────────────────────────────────────────────────────────────┐ + │ Not included here are: (among others): │ + │ some of the usual higher-math functions normally associated │ + │ with trig functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, │ + │ LOG (LN), LOG2, LOG10, ATAN2, │ + │ all of the hyperbolic trig functions and their inverses, │ + │ (too many to name here). │ + │ Angle conversions/normalizations: degrees/radians/grads/mils │ + │ [a circle = 2 pi radians, 360 degrees, 400 grads, 6400 mils].│ + │ Some of the other trig functions (hypens added intentially): │ + │ CHORD │ + │ COT (co-tangent) │ + │ CSC (co-secant) │ + │ CVC (co-versed cosine) │ + │ CVS (co-versed sine) │ + │ CXS (co-exsecant) │ + │ HAC (haver-cosine) │ + │ HAV (haver-sine │ + │ SEC (secant) │ + │ VCS (versed cosine or vercosine) │ + │ VSN (versed sine or versine) │ + │ XCS (exsecant) │ + │ COS/SIN/TAN cardinal (damped COS/SIN/TAN function) │ + │ COS/SIN integral │ + │ and all pertinent of the above's inverses (AVSN, ACVS...) │ + └───────────────────────────────────────────────────────────────┘ */ diff --git a/Task/Trigonometric-functions/RapidQ/trigonometric-functions.rapidq b/Task/Trigonometric-functions/RapidQ/trigonometric-functions.rapidq new file mode 100644 index 0000000000..5f256a3971 --- /dev/null +++ b/Task/Trigonometric-functions/RapidQ/trigonometric-functions.rapidq @@ -0,0 +1,33 @@ +$APPTYPE CONSOLE +$TYPECHECK ON + +SUB pause(prompt$) + PRINT prompt$ + DO + SLEEP .1 + LOOP UNTIL LEN(INKEY$) > 0 +END SUB + +'MAIN +DEFDBL pi , radians , degrees , deg2rad +pi = 4 * ATAN(1) +deg2rad = pi / 180 +radians = pi / 4 +degrees = 45 * deg2rad + +PRINT format$("%.6n" , SIN(radians)) + " " + format$("%.6n" , SIN(degrees)) +PRINT format$("%.6n" , COS(radians)) + " " + format$("%.6n" , COS(degrees)) +PRINT format$("%.6n" , TAN(radians)) + " " + format$("%.6n" , TAN(degrees)) + +DEFDBL temp = SIN(radians) +PRINT format$("%.6n" , ASIN(temp)) + " " + format$("%.6n" , ASIN(temp) / deg2rad) + +temp = COS(radians) +PRINT format$("%.6n" , ACOS(temp)) + " " + format$("%.6n" , ACOS(temp) / deg2rad) + +temp = TAN(radians) +PRINT format$("%.6n" , ATAN(temp)) + " " + format$("%.6n" , ATAN(temp) / deg2rad) + +pause("Press any key to continue.") + +END 'MAIN diff --git a/Task/Trigonometric-functions/Ruby/trigonometric-functions-1.rb b/Task/Trigonometric-functions/Ruby/trigonometric-functions-1.rb new file mode 100644 index 0000000000..52f36df3cd --- /dev/null +++ b/Task/Trigonometric-functions/Ruby/trigonometric-functions-1.rb @@ -0,0 +1,26 @@ +radians = Math::PI / 4 +degrees = 45.0 + +def deg2rad(d) + d * Math::PI / 180 +end + +def rad2deg(r) + r * 180 / Math::PI +end + +#sine +puts "#{Math.sin(radians)} #{Math.sin(deg2rad(degrees))}" +#cosine +puts "#{Math.cos(radians)} #{Math.cos(deg2rad(degrees))}" +#tangent +puts "#{Math.tan(radians)} #{Math.tan(deg2rad(degrees))}" +#arcsine +arcsin = Math.asin(Math.sin(radians)) +puts "#{arcsin} #{rad2deg(arcsin)}" +#arccosine +arccos = Math.acos(Math.cos(radians)) +puts "#{arccos} #{rad2deg(arccos)}" +#arctangent +arctan = Math.atan(Math.tan(radians)) +puts "#{arctan} #{rad2deg(arctan)}" diff --git a/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb b/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb new file mode 100644 index 0000000000..83845f17f8 --- /dev/null +++ b/Task/Trigonometric-functions/Ruby/trigonometric-functions-2.rb @@ -0,0 +1,63 @@ +require 'bigdecimal' # BigDecimal +require 'bigdecimal/math' # BigMath + +include BigMath # Allow sin(x, prec) instead of BigMath.sin(x, prec). + +# Tangent of _x_. +def tan(x, prec) + sin(x, prec) / cos(x, prec) +end + +# Arcsine of _y_, domain [-1, 1], range [-pi/2, pi/2]. +def asin(y, prec) + # Handle angles with no tangent. + return -PI / 2 if y == -1 + return PI / 2 if y == 1 + + # Tangent of angle is y / x, where x^2 + y^2 = 1. + atan(y / sqrt(1 - y * y, prec), prec) +end + +# Arccosine of _x_, domain [-1, 1], range [0, pi]. +def acos(x, prec) + # Handle angle with no tangent. + return PI / 2 if x == 0 + + # Tangent of angle is y / x, where x^2 + y^2 = 1. + a = atan(sqrt(1 - x * x, prec) / x, prec) + if a < 0 + a + PI(prec) + else + a + end +end + + +prec = 52 +pi = PI(prec) +degrees = pi / 180 # one degree in radians + +b1 = BigDecimal.new "1" +b2 = BigDecimal.new "2" +b3 = BigDecimal.new "3" + +f = proc { |big| big.round(50).to_s('F') } +print("Using radians:", + "\n sin(-pi / 6) = ", f[ sin(-pi / 6, prec) ], + "\n cos(3 * pi / 4) = ", f[ cos(3 * pi / 4, prec) ], + "\n tan(pi / 3) = ", f[ tan(pi / 3, prec) ], + "\n asin(-1 / 2) = ", f[ asin(-b1 / 2, prec) ], + "\n acos(-sqrt(2) / 2) = ", f[ acos(-sqrt(b2, prec) / 2, prec) ], + "\n atan(sqrt(3)) = ", f[ atan(sqrt(b3, prec), prec) ], + "\n") +print("Using degrees:", + "\n sin(-30) = ", f[ sin(-30 * degrees, prec) ], + "\n cos(135) = ", f[ cos(135 * degrees, prec) ], + "\n tan(60) = ", f[ tan(60 * degrees, prec) ], + "\n asin(-1 / 2) = ", + f[ asin(-b1 / 2, prec) / degrees ], + "\n acos(-sqrt(2) / 2) = ", + f[ acos(-sqrt(b2, prec) / 2, prec) / degrees ], + "\n atan(sqrt(3)) = ", + f[ atan(sqrt(b3, prec), prec) / degrees ], + "\n") diff --git a/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run b/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run new file mode 100644 index 0000000000..f573d3991b --- /dev/null +++ b/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run @@ -0,0 +1,13 @@ +deg = 45.0 +' Run BASIC works in radians. Convert deg and rad as shown. +d2r = ACS(-1)/180 +rad = deg*d2r +r2d = 180/ACS(-1) + +print "Sine: ";SIN(rad);" ";SIN(deg*d2r) +print "Cosine: ";COS(rad);" ";COS(deg*d2r) +print "Tangent: ";TAN(rad);" ";TAN(deg*d2r) +print +print "Arcsine: ";ASN(SIN(rad));" radians, (or ";ASN(SIN(deg*d2r))*r2d;" degrees)" +print "Arccosine: ";ACS(COS(rad));" radians, (or ";ACS(COS(deg*d2r))*r2d;" degrees)" +print "Arctangent: ";ATN(TAN(rad));" radians, (or ";ATN(TAN(deg*d2r))*r2d;" degrees)" diff --git a/Task/Trigonometric-functions/SAS/trigonometric-functions.sas b/Task/Trigonometric-functions/SAS/trigonometric-functions.sas new file mode 100644 index 0000000000..926083e432 --- /dev/null +++ b/Task/Trigonometric-functions/SAS/trigonometric-functions.sas @@ -0,0 +1,31 @@ +data _null_; +pi = 4*atan(1); +deg = 30; +rad = pi/6; +k = pi/180; +x = 0.2; + +a = sin(rad); +b = sin(deg*k); +put a b; + +a = cos(rad); +b = cos(deg*k); +put a b; + +a = tan(rad); +b = tan(deg*k); +put a b; + +a=arsin(x); +b=arsin(x)/k; +put a b; + +a=arcos(x); +b=arcos(x)/k; +put a b; + +a=atan(x); +b=atan(x)/k; +put a b; +run; diff --git a/Task/Trigonometric-functions/Scheme/trigonometric-functions.ss b/Task/Trigonometric-functions/Scheme/trigonometric-functions.ss new file mode 100644 index 0000000000..52fd0c6ace --- /dev/null +++ b/Task/Trigonometric-functions/Scheme/trigonometric-functions.ss @@ -0,0 +1,37 @@ +(define pi (* 4 (atan 1))) + +(define radians (/ pi 4)) +(define degrees 45) + +(display (sin radians)) +(display " ") +(display (sin (* degrees (/ pi 180)))) +(newline) + +(display (cos radians)) +(display " ") +(display (cos (* degrees (/ pi 180)))) +(newline) + +(display (tan radians)) +(display " ") +(display (tan (* degrees (/ pi 180)))) +(newline) + +(define arcsin (asin (sin radians))) +(display arcsin) +(display " ") +(display (* arcsin (/ 180 pi))) +(newline) + +(define arccos (acos (cos radians))) +(display arccos) +(display " ") +(display (* arccos (/ 180 pi))) +(newline) + +(define arctan (atan (tan radians))) +(display arctan) +(display " ") +(display (* arctan (/ 180 pi))) +(newline) diff --git a/Task/Trigonometric-functions/Seed7/trigonometric-functions.seed7 b/Task/Trigonometric-functions/Seed7/trigonometric-functions.seed7 new file mode 100644 index 0000000000..bc64186da2 --- /dev/null +++ b/Task/Trigonometric-functions/Seed7/trigonometric-functions.seed7 @@ -0,0 +1,17 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const proc: main is func + local + const float: radians is PI / 4.0; + const float: degrees is 45.0; + begin + writeln(" radians degrees"); + writeln("sine: " <& sin(radians) digits 5 <& sin(degrees * PI / 180.0) digits 5 lpad 9); + writeln("cosine: " <& cos(radians) digits 5 <& cos(degrees * PI / 180.0) digits 5 lpad 9); + writeln("tangent: " <& tan(radians) digits 5 <& tan(degrees * PI / 180.0) digits 5 lpad 9); + writeln("arcsine: " <& asin(0.70710677) digits 5 <& asin(0.70710677) * 180.0 / PI digits 5 lpad 9); + writeln("arccosine: " <& acos(0.70710677) digits 5 <& acos(0.70710677) * 180.0 / PI digits 5 lpad 9); + writeln("arctangent: " <& atan(1.0) digits 5 <& atan(1.0) * 180.0 / PI digits 5 lpad 9); + end func; diff --git a/Task/Trigonometric-functions/Tcl/trigonometric-functions.tcl b/Task/Trigonometric-functions/Tcl/trigonometric-functions.tcl new file mode 100644 index 0000000000..8d7423562b --- /dev/null +++ b/Task/Trigonometric-functions/Tcl/trigonometric-functions.tcl @@ -0,0 +1,18 @@ +package require Tcl 8.5 + +proc PI {} {expr {4*atan(1)}} +proc deg2rad d {expr {$d/180*[PI]}} +proc rad2deg r {expr {$r*180/[PI]}} + +namespace path ::tcl::mathfunc + +proc trig degrees { + set radians [deg2rad $degrees] + puts [sin $radians] + puts [cos $radians] + puts [tan $radians] + set arcsin [asin [sin $radians]]; puts "$arcsin [rad2deg $arcsin]" + set arccos [acos [cos $radians]]; puts "$arccos [rad2deg $arccos]" + set arctan [atan [tan $radians]]; puts "$arctan [rad2deg $arctan]" +} +trig 60.0 diff --git a/Task/Trigonometric-functions/XPL0/trigonometric-functions.xpl0 b/Task/Trigonometric-functions/XPL0/trigonometric-functions.xpl0 new file mode 100644 index 0000000000..8f96052412 --- /dev/null +++ b/Task/Trigonometric-functions/XPL0/trigonometric-functions.xpl0 @@ -0,0 +1,27 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +def Pi = 3.14159265358979323846; + +func real ATan(Y); \Arc tangent +real Y; +return ATan2(Y, 1.0); + +func real Deg(X); \Convert radians to degrees +real X; +return 57.2957795130823 * X; + +func real Rad(X); \Convert degrees to radians +real X; +return X / 57.2957795130823; + +real A, B, C; +[A:= Sin(Pi/6.0); +RlOut(0, A); ChOut(0, 9\tab\); RlOut(0, Sin(Rad(30.0))); CrLf(0); +B:= Cos(Pi/6.0); +RlOut(0, B); ChOut(0, 9\tab\); RlOut(0, Cos(Rad(30.0))); CrLf(0); +C:= Tan(Pi/4.0); +RlOut(0, C); ChOut(0, 9\tab\); RlOut(0, Tan(Rad(45.0))); CrLf(0); + +RlOut(0, ASin(A)); ChOut(0, 9\tab\); RlOut(0, Deg(ASin(A))); CrLf(0); +RlOut(0, ACos(B)); ChOut(0, 9\tab\); RlOut(0, Deg(ACos(B))); CrLf(0); +RlOut(0, ATan(C)); ChOut(0, 9\tab\); RlOut(0, Deg(ATan(C))); CrLf(0); +] diff --git a/Task/Truncatable-primes/0DESCRIPTION b/Task/Truncatable-primes/0DESCRIPTION new file mode 100644 index 0000000000..f9c2527e8a --- /dev/null +++ b/Task/Truncatable-primes/0DESCRIPTION @@ -0,0 +1,10 @@ +A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number; for example, the number 997 is called a ''left-truncatable prime'' as the numbers 997, 97, and 7 are all prime. The number 7393 is a ''right-truncatable prime'' as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime. No zeroes are allowed in truncatable primes. + +The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied). + +;C.f: +* [[Find largest left truncatable prime in a given base]] +* [[Sieve of Eratosthenes]] +* [http://mathworld.wolfram.com/TruncatablePrime.html Truncatable Prime] from Mathworld. + +[[:Category:Prime_Numbers]] diff --git a/Task/Truncatable-primes/1META.yaml b/Task/Truncatable-primes/1META.yaml new file mode 100644 index 0000000000..06b4f1f0c9 --- /dev/null +++ b/Task/Truncatable-primes/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Prime Numbers diff --git a/Task/Truncatable-primes/ALGOL-68/truncatable-primes.alg b/Task/Truncatable-primes/ALGOL-68/truncatable-primes.alg new file mode 100644 index 0000000000..c71b49e47a --- /dev/null +++ b/Task/Truncatable-primes/ALGOL-68/truncatable-primes.alg @@ -0,0 +1,56 @@ +#!/usr/local/bin/a68g --script # + +PROC is prime = (INT n)BOOL:( + []BOOL is short prime=(FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE); + IF n<=UPB is short prime THEN is short prime[n] # EXIT # ELSE + IF ( NOT ODD n | TRUE | n MOD 3 = 0 ) THEN FALSE # EXIT # ELSE + INT h := ENTIER sqrt(n)+3; + FOR a FROM 7 BY 6 WHILE a 0 loop + M := M * 10; + if N <= M then + return True; + end if; + end loop; + return False; + end Is_Left_Trucatable_Prime; + + function Is_Right_Trucatable_Prime (N : Positive) return Boolean is + M : Natural := N; + begin + while Contains (Primes, M) and M mod 10 > 0 loop + M := M / 10; + if M <= 1 then + return True; + end if; + end loop; + return False; + end Is_Right_Trucatable_Prime; + + Position : Cursor; +begin + for N in 2..1_000_000 loop + if Is_Prime (N) then + Insert (Primes, N); + end if; + end loop; + Position := Last (Primes); + while Has_Element (Position) loop + if Is_Left_Trucatable_Prime (Element (Position)) then + Put_Line ("Largest LTP from 1..1000000:" & Integer'Image (Element (Position))); + exit; + end if; + Previous (Position); + end loop; + Position := Last (Primes); + while Has_Element (Position) loop + if Is_Right_Trucatable_Prime (Element (Position)) then + Put_Line ("Largest RTP from 1..1000000:" & Integer'Image (Element (Position))); + exit; + end if; + Previous (Position); + end loop; +end Truncatable_Primes; diff --git a/Task/Truncatable-primes/C/truncatable-primes-1.c b/Task/Truncatable-primes/C/truncatable-primes-1.c new file mode 100644 index 0000000000..6df08587c7 --- /dev/null +++ b/Task/Truncatable-primes/C/truncatable-primes-1.c @@ -0,0 +1,63 @@ +#include +#include +#include + +#define MAX_PRIME 1000000 +char *primes; +int n_primes; + +/* Sieve. If we were to handle 10^9 range, use bit field. Regardless, + * if a large amount of prime numbers need to be tested, sieve is fast. + */ +void init_primes() +{ + int j; + primes = malloc(sizeof(char) * MAX_PRIME); + memset(primes, 1, MAX_PRIME); + primes[0] = primes[1] = 0; + int i = 2; + while (i * i < MAX_PRIME) { + for (j = i * 2; j < MAX_PRIME; j += i) + primes[j] = 0; + while (++i < MAX_PRIME && !primes[i]); + } +} + +int left_trunc(int n) +{ + int tens = 1; + while (tens < n) tens *= 10; + + while (n) { + if (!primes[n]) return 0; + tens /= 10; + if (n < tens) return 0; + n %= tens; + } + return 1; +} + +int right_trunc(int n) +{ + while (n) { + if (!primes[n]) return 0; + n /= 10; + } + return 1; +} + +int main() +{ + int n; + int max_left = 0, max_right = 0; + init_primes(); + + for (n = MAX_PRIME - 1; !max_left; n -= 2) + if (left_trunc(n)) max_left = n; + + for (n = MAX_PRIME - 1; !max_right; n -= 2) + if (right_trunc(n)) max_right = n; + + printf("Left: %d; right: %d\n", max_left, max_right); + return 0; +} diff --git a/Task/Truncatable-primes/C/truncatable-primes-2.c b/Task/Truncatable-primes/C/truncatable-primes-2.c new file mode 100644 index 0000000000..2c7fe6ce7a --- /dev/null +++ b/Task/Truncatable-primes/C/truncatable-primes-2.c @@ -0,0 +1 @@ +Left: 998443; right: 739399 diff --git a/Task/Truncatable-primes/C/truncatable-primes-3.c b/Task/Truncatable-primes/C/truncatable-primes-3.c new file mode 100644 index 0000000000..ee017c8492 --- /dev/null +++ b/Task/Truncatable-primes/C/truncatable-primes-3.c @@ -0,0 +1,47 @@ +#include + +#define MAXN 1000000 +int maxl, maxr; + +int is_prime(int n) +{ + int p; + if (n % 3 == 0) return 0; + + for (p = 6; p * p <= n; p += 6) + if (!(n % (p + 1) && n % (p + 5))) + return 0; + return 1; +} + +void left(int n, int tens) +{ + int i, nn; + + if (n > maxl) maxl = n; + if (n < MAXN / 10) + for (tens *= 10, i = 1; i < 10; i++) + if (is_prime(nn = i * tens + n)) + left(nn, tens); +} + +void right(int n) +{ + int i, nn; + static int d[] = {1,3,7,9}; + + if (n > maxr) maxr = n; + if (n < MAXN / 10) + for (i = 1; i < 4; i++) + if (is_prime(nn = n * 10 + d[i])) right(nn); +} + +int main(void) +{ + left(3, 1); left(7, 1); + right(3); right(5); right(7); + + printf("%d %d\n", maxl, maxr); + + return 0; +} diff --git a/Task/Truncatable-primes/Clojure/truncatable-primes.clj b/Task/Truncatable-primes/Clojure/truncatable-primes.clj new file mode 100644 index 0000000000..6c4de1eb5f --- /dev/null +++ b/Task/Truncatable-primes/Clojure/truncatable-primes.clj @@ -0,0 +1,41 @@ +(use '[clojure.contrib.lazy-seqs :only [primes]]) + +(def prime? + (let [mem (ref #{}) + primes (ref primes)] + (fn [n] + (dosync + (if (< n (first @primes)) + (@mem n) + (let [[mems ss] (split-with #(<= % n) @primes)] + (ref-set primes ss) + ((commute mem into mems) n))))))) + +(defn drop-lefts [n] + (let [dropl #(if (< % 10) 0 (Integer. (subs (str %) 1)))] + (->> (iterate dropl n) + (take-while pos? ,) + next))) + +(defn drop-rights [n] + (->> (iterate #(quot % 10) n) + next + (take-while pos? ,))) + +(defn truncatable-left? [n] + (every? prime? (drop-lefts n))) + +(defn truncatable-right? [n] + (every? prime? (drop-rights n))) + +user> (->> (for [p primes + :while (< p 1000000) + :when (not-any? #{\0} (str p)) + :let [l? (if (truncatable-left? p) p 0) + r? (if (truncatable-right? p) p 0)] + :when (or l? r?)] + [l? r?]) + ((juxt #(apply max-key first %) #(apply max-key second %)) ,) + ((juxt ffirst (comp second second)) ,) + (map vector ["left truncatable: " "right truncatable: "] ,)) +(["left truncatable: " 998443] ["right truncatable: " 739399]) diff --git a/Task/Truncatable-primes/CoffeeScript/truncatable-primes-1.coffeescript b/Task/Truncatable-primes/CoffeeScript/truncatable-primes-1.coffeescript new file mode 100644 index 0000000000..5e396558ae --- /dev/null +++ b/Task/Truncatable-primes/CoffeeScript/truncatable-primes-1.coffeescript @@ -0,0 +1,59 @@ +# You could have symmetric algorithms for max right and left +# truncatable numbers, but they lend themselves to slightly +# different optimizations. + +max_right_truncatable_number = (n, f) -> + # This algorithm only evaluates 37 numbers for primeness to + # get the max right truncatable prime < 1000000. Its + # optimization is that it prunes candidates for + # the first n-1 digits before having to iterate through + # the 10 possibilities for the last digit. + if n < 10 + candidate = n + while candidate > 0 + return candidate if f(candidate) + candidate -= 1 + else + left = Math.floor n / 10 + while left > 0 + left = max_right_truncatable_number left, f + right = 9 + while right > 0 + candidate = left * 10 + right + return candidate if candidate <= n and f(candidate) + right -= 1 + left -= 1 + throw Error "none found" + +max_left_truncatable_number = (max, f) -> + # This is a pretty straightforward countdown. The first + # optimization here would probably be to cache results of + # calling f on small numbers. + is_left_truncatable = (n) -> + candidate = 0 + power_of_ten = 1 + while n > 0 + r = n % 10 + return false if r == 0 + n = Math.floor n / 10 + candidate = r * power_of_ten + candidate + power_of_ten *= 10 + return false unless f(candidate) + true + do -> + n = max + while n > 0 + return n if is_left_truncatable n, f + n -= 1 + throw Error "none found" + +is_prime = (n) -> + return false if n == 1 + return true if n == 2 + for d in [2..n] + return false if n % d == 0 + return true if d * d >= n + + +console.log "right", max_right_truncatable_number(999999, is_prime) +console.log "left", max_left_truncatable_number(999999, is_prime) diff --git a/Task/Truncatable-primes/CoffeeScript/truncatable-primes-2.coffeescript b/Task/Truncatable-primes/CoffeeScript/truncatable-primes-2.coffeescript new file mode 100644 index 0000000000..a63cf6b05e --- /dev/null +++ b/Task/Truncatable-primes/CoffeeScript/truncatable-primes-2.coffeescript @@ -0,0 +1,3 @@ +> coffee truncatable_prime.coffee +right 739399 +left 998443 diff --git a/Task/Truncatable-primes/D/truncatable-primes.d b/Task/Truncatable-primes/D/truncatable-primes.d new file mode 100644 index 0000000000..62acff2e54 --- /dev/null +++ b/Task/Truncatable-primes/D/truncatable-primes.d @@ -0,0 +1,39 @@ +import std.stdio, std.math, std.string, std.conv; + +bool isPrime(int n) { + if (n <= 1) + return false; + foreach (i; 2 .. cast(int)sqrt(cast(real)n) + 1) + if (!(n % i)) + return false; + return true; +} + +bool isTruncatablePrime(bool left)(int n) { + string s = to!string(n); + if (indexOf(s, '0') != -1) + return false; + foreach (i; 0 .. s.length) + static if (left) { + if (!isPrime(to!int(s[i .. $]))) + return false; + } else { + if (!isPrime(to!int(s[0 .. i+1]))) + return false; + } + return true; +} + +void main() { + enum int n = 1_000_000; + foreach_reverse (i; 2 .. n) + if (isTruncatablePrime!true(i)) { + writeln("Largest left-truncatable prime in 2 .. ", n, ": ", i); + break; + } + foreach_reverse (i; 2 .. n) + if (isTruncatablePrime!false(i)) { + writeln("Largest right-truncatable prime in 2 .. ", n, ": ", i); + break; + } +} diff --git a/Task/Truncatable-primes/Fortran/truncatable-primes.f b/Task/Truncatable-primes/Fortran/truncatable-primes.f new file mode 100644 index 0000000000..06f8404da7 --- /dev/null +++ b/Task/Truncatable-primes/Fortran/truncatable-primes.f @@ -0,0 +1,88 @@ +module primes_mod + implicit none + + logical, allocatable :: primes(:) + +contains + +subroutine Genprimes(parr) + logical, intent(in out) :: parr(:) + integer :: i +! Prime sieve + parr = .true. + parr (1) = .false. + parr (4 : size(parr) : 2) = .false. + do i = 3, int (sqrt (real (size(parr)))), 2 + if (parr(i)) parr(i * i : size(parr) : i) = .false. + end do + +end subroutine + +function is_rtp(candidate) + logical :: is_rtp + integer, intent(in) :: candidate + integer :: n + + is_rtp = .true. + n = candidate / 10 + do while(n > 0) + if(.not. primes(n)) then + is_rtp = .false. + return + end if + n = n / 10 + end do + +end function + +function is_ltp(candidate) + logical :: is_ltp + integer, intent(in) :: candidate + integer :: i, n + character(10) :: nstr + + write(nstr, "(i10)") candidate + is_ltp = .true. + do i = len_trim(nstr)-1, 1, -1 + n = mod(candidate, 10**i) + if(.not. primes(n)) then + is_ltp = .false. + return + end if + end do +end function + +end module primes_mod + +program Truncatable_Primes + use primes_mod + implicit none + + integer, parameter :: limit = 999999 + integer :: i + character(10) :: nstr + +! Generate an array of prime flags up to limit of search + allocate(primes(limit)) + call Genprimes(primes) + +! Find left truncatable prime + do i = limit, 1, -1 + write(nstr, "(i10)") i + if(index(trim(nstr), "0") /= 0) cycle ! check for 0 in number + if(is_ltp(i)) then + write(*, "(a, i0)") "Largest left truncatable prime below 1000000 is ", i + exit + end if + end do + +! Find right truncatable prime + do i = limit, 1, -1 + write(nstr, "(i10)") i + if(index(trim(nstr), "0") /= 0) cycle ! check for 0 in number + if(is_rtp(i)) then + write(*, "(a, i0)") "Largest right truncatable prime below 1000000 is ", i + exit + end if + end do +end program diff --git a/Task/Truncatable-primes/Go/truncatable-primes.go b/Task/Truncatable-primes/Go/truncatable-primes.go new file mode 100644 index 0000000000..6657b3ba64 --- /dev/null +++ b/Task/Truncatable-primes/Go/truncatable-primes.go @@ -0,0 +1,55 @@ +package main + +import "fmt" + +func main() { + sieve(1e6) + if !search(6, 1e6, "left", func(n, pot int) int { return n % pot }) { + panic("997?") + } + if !search(6, 1e6, "right", func(n, _ int) int { return n / 10 }) { + panic("7393?") + } +} + +var c []bool + +func sieve(ss int) { + c = make([]bool, ss) + c[1] = true + for p := 2; ; { + p2 := p * p + if p2 >= ss { + break + } + for i := p2; i < ss; i += p { + c[i] = true + } + for { + p++ + if !c[p] { + break + } + } + } +} + +func search(digits, pot int, s string, truncFunc func(n, pot int) int) bool { + n := pot - 1 + pot /= 10 +smaller: + for ; n >= pot; n -= 2 { + for tn, tp := n, pot; tp > 0; tp /= 10 { + if tn < tp || c[tn] { + continue smaller + } + tn = truncFunc(tn, tp) + } + fmt.Println("max", s, "truncatable:", n) + return true + } + if digits > 1 { + return search(digits-1, pot, s, truncFunc) + } + return false +} diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-1.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-1.hs new file mode 100644 index 0000000000..60d190fb83 --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-1.hs @@ -0,0 +1,14 @@ +import Data.Numbers.Primes(primes, isPrime) +import Data.List +import Control.Arrow + +primes1e6 = reverse. filter (notElem '0'. show) $ takeWhile(<=1000000) primes + +rightT, leftT :: Int -> Bool +rightT = all isPrime. takeWhile(>0). drop 1. iterate (`div`10) +leftT x = all isPrime. takeWhile( main +Left truncatable 998443 +Right truncatable 739399 diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-3.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-3.hs new file mode 100644 index 0000000000..82c5c4b79c --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-3.hs @@ -0,0 +1,8 @@ +digits = [1..9] :: [Integer] +smallPrimes = filter isPrime digits +pow10 = iterate (*10) 1 +mul10 = (pow10!!). length. show +righT = (+) . (10 *) +lefT = liftM2 (.) (+) ((*) . mul10) + +primesTruncatable f = iterate (concatMap (filter isPrime.flip map digits. f)) smallPrimes diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-4.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-4.hs new file mode 100644 index 0000000000..13cf67273e --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-4.hs @@ -0,0 +1,5 @@ +*Main> maximum $ primesTruncatable righT !! 5 +739399 + +*Main> maximum $ primesTruncatable lefT !! 5 +998443 diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-5.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-5.hs new file mode 100644 index 0000000000..02a97cd656 --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-5.hs @@ -0,0 +1,33 @@ +procedure main(arglist) + N := 0 < integer(\arglist[1]) | 1000000 # primes to generator 1 to ... (1M or 1st arglist) + D := (0 < integer(\arglist[2]) | 10) / 2 # primes to display (10 or 2nd arglist) + P := sieve(N) # from sieve task (modified) + write("There are ",*P," prime numbers in the range 1 to ",N) + if *P <= 2*D then + every writes( "Primes: "|!sort(P)||" "|"\n" ) + else + every writes( "Primes: "|(L := sort(P))[1 to D]||" "|"... "|L[*L-D+1 to *L]||" "|"\n" ) + largesttruncateable(P) +end + +procedure largesttruncateable(P) #: find the largest left and right trucatable numbers in P +local ltp,rtp + + every x := sort(P)[*P to 1 by -1] do # largest to smallest + if not find('0',x) then { + /ltp := islefttrunc(P,x) + /rtp := isrighttrunc(P,x) + if \ltp & \rtp then break # until both found + } + write("Largest left truncatable prime = ", ltp) + write("Largest right truncatable prime = ", rtp) + return +end + +procedure isrighttrunc(P,x) #: return integer x if x and all right truncations of x are in P or fails +if x = 0 | (member(P,x) & isrighttrunc(P,x / 10)) then return x +end + +procedure islefttrunc(P,x) #: return integer x if x and all left truncations of x are in P or fails +if *x = 0 | ( (x := integer(x)) & member(P,x) & islefttrunc(P,x[2:0]) ) then return x +end diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-6.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-6.hs new file mode 100644 index 0000000000..ad4bb691ea --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-6.hs @@ -0,0 +1,3 @@ +selPrime=: #~ 1&p: +seed=: selPrime digits=: 1+i.9 +step=: selPrime@,@:(,&.":/&>)@{@; diff --git a/Task/Truncatable-primes/Haskell/truncatable-primes-7.hs b/Task/Truncatable-primes/Haskell/truncatable-primes-7.hs new file mode 100644 index 0000000000..25e564b9e1 --- /dev/null +++ b/Task/Truncatable-primes/Haskell/truncatable-primes-7.hs @@ -0,0 +1,4 @@ + >./ digits&step^:5 seed NB. left truncatable +998443 + >./ step&digits^:5 seed NB. right truncatable +739399 diff --git a/Task/Truncatable-primes/Java/truncatable-primes.java b/Task/Truncatable-primes/Java/truncatable-primes.java new file mode 100644 index 0000000000..cf63380dc4 --- /dev/null +++ b/Task/Truncatable-primes/Java/truncatable-primes.java @@ -0,0 +1,69 @@ +import java.util.BitSet; + +public class Main { + + public static void main(String[] args){ + + final int MAX = 1000000; + + //Sieve of Eratosthenes (using BitSet only for odd numbers) + BitSet primeList = new BitSet(MAX>>1); + primeList.set(0,primeList.size(),true); + + int sqroot = (int) Math.sqrt(MAX); + primeList.clear(0); + for(int num = 3; num <= sqroot; num+=2) + { + if( primeList.get(num >> 1) ) + { + int inc = num << 1; + for(int factor = num * num; factor < MAX; factor += inc) + { + //if( ((factor) & 1) == 1) + //{ + primeList.clear(factor >> 1); + //} + } + } + } + //Sieve ends... + + //Find Largest Truncatable Prime. (so we start from 1000000 - 1 + int rightTrunc = -1, leftTrunc = -1; + for(int prime = (MAX - 1) | 1; prime >= 3; prime -= 2) + { + if(primeList.get(prime>>1)) + { + //Already found Right Truncatable Prime? + if(rightTrunc == -1) + { + int right = prime; + while(right > 0 && primeList.get(right >> 1)) right /= 10; + if(right == 0) rightTrunc = prime; + } + + //Already found Left Truncatable Prime? + if(leftTrunc == -1 ) + { + //Left Truncation + String left = Integer.toString(prime); + if(!left.contains("0")) + { + while( left.length() > 0 ){ + int iLeft = Integer.parseInt(left); + if(!primeList.get( iLeft >> 1)) break; + left = left.substring(1); + } + if(left.length() == 0) leftTrunc = prime; + } + } + if(leftTrunc != -1 && rightTrunc != -1) //Found both? then Stop loop + { + break; + } + } + } + System.out.println("Left Truncatable : " + leftTrunc); + System.out.println("Right Truncatable : " + rightTrunc); + } +} diff --git a/Task/Truncatable-primes/Lua/truncatable-primes.lua b/Task/Truncatable-primes/Lua/truncatable-primes.lua new file mode 100644 index 0000000000..0c4cf1dc5d --- /dev/null +++ b/Task/Truncatable-primes/Lua/truncatable-primes.lua @@ -0,0 +1,47 @@ +max_number = 1000000 + +numbers = {} +for i = 2, max_number do + numbers[i] = i; +end + +for i = 2, max_number do + for j = i+1, max_number do + if numbers[j] ~= 0 and j % i == 0 then numbers[j] = 0 end + end +end + +max_prime_left, max_prime_right = 2, 2 +for i = 2, max_number do + if numbers[i] ~= 0 then + local is_prime = true + + local l = math.floor( i / 10 ) + while l > 1 do + if numbers[l] == 0 then + is_prime = false + break + end + l = math.floor( l / 10 ) + end + if is_prime then + max_prime_left = i + end + + is_prime = true + local n = 10; + while math.floor( i % 10 ) ~= 0 and n < max_number do + if numbers[ math.floor( i % 10 ) ] ~= 0 then + is_prime = false + break + end + n = n * 10 + end + if is_prime then + max_prime_right = i + end + end +end + +print( "max_prime_left = ", max_prime_left ) +print( "max_prime_right = ", max_prime_right ) diff --git a/Task/Truncatable-primes/MATLAB/truncatable-primes-1.m b/Task/Truncatable-primes/MATLAB/truncatable-primes-1.m new file mode 100644 index 0000000000..10c008b5dc --- /dev/null +++ b/Task/Truncatable-primes/MATLAB/truncatable-primes-1.m @@ -0,0 +1,61 @@ +function largestTruncatablePrimes(boundary) + + %Helper function for checking if a prime is left of right truncatable + function [leftTruncatable,rightTruncatable] = isTruncatable(prime,checkLeftTruncatable,checkRightTruncatable) + + numDigits = ceil(log10(prime)); %calculate the number of digits in the prime less one + powersOfTen = 10.^(0:numDigits); %cache the needed powers of ten + + leftTruncated = mod(prime,powersOfTen); %generate a list of numbers by repeatedly left truncating the prime + + %leading zeros will cause duplicate entries thus it is possible to + %detect leading zeros if we rotate the list to the left or right + %and check for any equivalences with the original list + hasLeadingZeros = any( circshift(leftTruncated,[0 1]) == leftTruncated ); + + if( hasLeadingZeros || not(checkLeftTruncatable) ) + leftTruncatable = false; + else + %check if all of the left truncated numbers are prime + leftTruncatable = all(isprime(leftTruncated(2:end))); + end + + if( checkRightTruncatable ) + rightTruncated = (prime - leftTruncated) ./ powersOfTen; %generate a list of right truncated numbers + rightTruncatable = all(isprime(rightTruncated(1:end-1))); %check if all the right truncated numbers are prime + else + rightTruncatable = false; + end + + end %isTruncatable() + + nums = primes(boundary); %generate all primes <= boundary + + %Flags that indicate if the largest left or right truncatable prime has not + %been found + leftTruncateNotFound = true; + rightTruncateNotFound = true; + + for prime = nums(end:-1:1) %Search through primes in reverse order + + %Get if the prime is left and/or right truncatable, ignoring + %checking for right truncatable if it has already been found + [leftTruncatable,rightTruncatable] = isTruncatable(prime,leftTruncateNotFound,rightTruncateNotFound); + + if( leftTruncateNotFound && leftTruncatable ) %print out largest left truncatable prime + display([num2str(prime) ' is the largest left truncatable prime <= ' num2str(boundary) '.']); + leftTruncateNotFound = false; + end + + if( rightTruncateNotFound && rightTruncatable ) %print out largest right truncatable prime + display([num2str(prime) ' is the largest right truncatable prime <= ' num2str(boundary) '.']); + rightTruncateNotFound = false; + end + + %Terminate loop when the largest left and right truncatable primes have + %been found + if( not(leftTruncateNotFound || rightTruncateNotFound) ) + break; + end + end +end diff --git a/Task/Truncatable-primes/MATLAB/truncatable-primes-2.m b/Task/Truncatable-primes/MATLAB/truncatable-primes-2.m new file mode 100644 index 0000000000..a08f60556a --- /dev/null +++ b/Task/Truncatable-primes/MATLAB/truncatable-primes-2.m @@ -0,0 +1,3 @@ +>> largestTruncatablePrimes(1e6) +998443 is the largest left truncatable prime <= 1000000. +739399 is the largest right truncatable prime <= 1000000. diff --git a/Task/Truncatable-primes/Mathematica/truncatable-primes.math b/Task/Truncatable-primes/Mathematica/truncatable-primes.math new file mode 100644 index 0000000000..9d3417bf6f --- /dev/null +++ b/Task/Truncatable-primes/Mathematica/truncatable-primes.math @@ -0,0 +1,6 @@ +LeftTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 && + And @@ PrimeQ /@ ToExpression /@ StringJoin /@ + Rest[Most[NestList[Rest, #, Length[#]] &[Characters[ToString[n]]]]] +RightTruncatablePrimeQ[n_] := Times @@ IntegerDigits[n] > 0 && + And @@ PrimeQ /@ ToExpression /@ StringJoin /@ + Rest[Most[NestList[Most, #, Length[#]] &[Characters[ToString[n]]]]] diff --git a/Task/Truncatable-primes/OpenEdge-Progress/truncatable-primes.openedge b/Task/Truncatable-primes/OpenEdge-Progress/truncatable-primes.openedge new file mode 100644 index 0000000000..c0ad3d6482 --- /dev/null +++ b/Task/Truncatable-primes/OpenEdge-Progress/truncatable-primes.openedge @@ -0,0 +1,81 @@ +FUNCTION isPrime RETURNS LOGICAL ( + i_i AS INT +): + + DEF VAR ii AS INT. + + DO ii = 2 TO SQRT( i_i ): + + IF i_i MODULO ii = 0 THEN + RETURN FALSE. + + END. + + RETURN TRUE AND i_i > 1. + +END FUNCTION. /* isPrime */ + +FUNCTION isLeftTruncatablePrime RETURNS LOGICAL ( + i_i AS INT +): + + DEF VAR ii AS INT. + DEF VAR cc AS CHAR. + DEF VAR lresult AS LOGICAL INITIAL TRUE. + + cc = STRING( i_i ). + + DO WHILE cc > "": + lresult = lresult AND isPrime( INTEGER( cc ) ). + cc = SUBSTRING( cc, 2 ). + END. + + RETURN lresult. + +END FUNCTION. /* isLeftTruncatablePrime */ + +FUNCTION isRightTruncatablePrime RETURNS LOGICAL ( + i_i AS INT +): + + DEF VAR ii AS INT. + DEF VAR cc AS CHAR. + DEF VAR lresult AS LOGICAL INITIAL TRUE. + + cc = STRING( i_i ). + + DO WHILE cc > "": + lresult = lresult AND isPrime( INTEGER( cc ) ). + cc = SUBSTRING( cc, 1, LENGTH( cc ) - 1 ). + END. + + RETURN lresult. + +END FUNCTION. /* isRightTruncatablePrime */ + +FUNCTION getHighestTruncatablePrimes RETURNS CHARACTER ( + i_imax AS INTEGER +): + + DEF VAR ii AS INT. + DEF VAR ileft AS INT. + DEF VAR iright AS INT. + + DO ii = i_imax TO 1 BY -1 WHILE ileft = 0 OR iright = 0: + + IF INDEX( STRING( ii ), "0" ) = 0 THEN DO: + IF ileft = 0 AND isLeftTruncatablePrime( ii ) THEN + ileft = ii. + IF iright = 0 AND isRightTruncatablePrime( ii ) THEN + iright = ii. + END. + + END. + + RETURN SUBSTITUTE("Left: &1~nRight: &2", ileft, iright ). + +END FUNCTION. /* getHighestTruncatablePrimes */ + +MESSAGE + getHighestTruncatablePrimes( 1000000 ) +VIEW-AS ALERT-BOX. diff --git a/Task/Truncatable-primes/PARI-GP/truncatable-primes.pari b/Task/Truncatable-primes/PARI-GP/truncatable-primes.pari new file mode 100644 index 0000000000..e01d3b531b --- /dev/null +++ b/Task/Truncatable-primes/PARI-GP/truncatable-primes.pari @@ -0,0 +1,30 @@ +left(n)={ + my(v=[2,3,5,7],u,t=1,out=0); + for(i=1,n, + t*=10; + u=[]; + for(j=1,#v, + forstep(a=t,t*9,t, + if(isprime(a+v[j]),u=concat(u,a+v[j])) + ) + ); + out=v[#v]; + v=vecsort(u) + ); + out +}; +right(n)={ + my(v=[2,3,5,7],u,out=0); + for(i=1,n, + u=[]; + for(j=1,#v, + forstep(a=1,9,[2,4], + if(isprime(10*v[j]+a),u=concat(u,10*v[j]+a)) + ) + ); + out=v[#v]; + v=u + ); + out +}; +[left(6),right(6)] diff --git a/Task/Truncatable-primes/PL-I/truncatable-primes.pli b/Task/Truncatable-primes/PL-I/truncatable-primes.pli new file mode 100644 index 0000000000..2fa2754163 --- /dev/null +++ b/Task/Truncatable-primes/PL-I/truncatable-primes.pli @@ -0,0 +1,67 @@ +tp: procedure options (main); + declare primes(1000000) bit (1); + declare max_primes fixed binary (31); + declare (i, k) fixed binary (31); + + max_primes = hbound(primes, 1); + call sieve; + + /* Now search for primes that are right-truncatable. */ + call right_truncatable; + + /* Now search for primes that are left-truncatable. */ + call left_truncatable; + +right_truncatable: procedure; + declare direction bit (1); + declare (i, k) fixed binary (31); + +test_truncatable: + do i = max_primes to 2 by -1; + if primes(i) then /* it's a prime */ + do; + k = i/10; + do while (k > 0); + if ^primes(k) then iterate test_truncatable; + k = k/10; + end; + put skip list (i || ' is right-truncatable'); + return; + end; + end; +end right_truncatable; + +left_truncatable: procedure; + declare direction bit (1); + declare (i, k, d, e) fixed binary (31); + +test_truncatable: + do i = max_primes to 2 by -1; + if primes(i) then /* it's a prime */ + do; + k = i; + do d = 100000 repeat d/10 until (d = 10); + e = k/d; + k = k - e*d; + if e = 0 then iterate test_truncatable; + if ^primes(k) then iterate test_truncatable; + end; + put skip list (i || ' is left-truncatable'); + return; + end; + end; +end left_truncatable; + +sieve: procedure; + declare (i, j) fixed binary (31); + + primes = '1'b; primes(1) = '0'b; + + do i = 2 to sqrt(max_primes); + do j = i+i to max_primes by i; + primes(j) = '0'b; + end; + end; +end sieve; + +end tp; diff --git a/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 b/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 new file mode 100644 index 0000000000..769d231664 --- /dev/null +++ b/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 @@ -0,0 +1,41 @@ +my @primes := 2, 3, 5, -> $p { ($p+2, $p+4 ... &prime)[*-1] } ... *; +my @isprime = False,False; # 0 and 1 are not primes by definition +sub prime($i) { @isprime[$i] //= ($i %% none @primes ...^ * > $_ given $i.sqrt.floor) } + +sub ltp { + for 9...1 -> $a { + for 9...1 -> $b { + for 9...1 -> $c { + for 9...1 -> $d { + for 9...1 -> $e { + for 9,7,3 -> $f { + my @x := [\+] $f, $e, $d, $c, $b, $a Z* (1,10,100 ... *); + return @x[*-1] if not grep {not prime $^n}, @x; + } + } + } + } + } + } +} + +sub infix:<*+> ($a,$b) { $a * 10 + $b } + +sub rtp { + for 7,5,3 { + for grep &prime, ($_ X*+ 9,7,3,1) { + for grep &prime, ($_ X*+ 9,7,3,1) { + for grep &prime, ($_ X*+ 9,7,3,1) { + for grep &prime, ($_ X*+ 9,7,3,1) { + for grep &prime, ($_ X*+ 9,7,3,1) { + return $_; + } + } + } + } + } + } +} + +say "Highest ltp: ", ltp; +say "Highest rtp: ", rtp; diff --git a/Task/Truncatable-primes/PicoLisp/truncatable-primes.l b/Task/Truncatable-primes/PicoLisp/truncatable-primes.l new file mode 100644 index 0000000000..0cdadf8399 --- /dev/null +++ b/Task/Truncatable-primes/PicoLisp/truncatable-primes.l @@ -0,0 +1,12 @@ +(load "@lib/rsa.l") # Use the 'prime?' function from RSA package + +(de truncatablePrime? (N Fun) + (for (L (chop N) L (Fun L)) + (T (= "0" (car L))) + (NIL (prime? (format L))) + T ) ) + +(let (Left 1000000 Right 1000000) + (until (truncatablePrime? (dec 'Left) cdr)) + (until (truncatablePrime? (dec 'Right) '((L) (cdr (rot L))))) + (cons Left Right) ) diff --git a/Task/Truncatable-primes/PowerShell/truncatable-primes.psh b/Task/Truncatable-primes/PowerShell/truncatable-primes.psh new file mode 100644 index 0000000000..099df45a29 --- /dev/null +++ b/Task/Truncatable-primes/PowerShell/truncatable-primes.psh @@ -0,0 +1,51 @@ +function IsPrime ( [int] $num ) +{ + $isprime = @{} + 2..[math]::sqrt($num) | Where-Object { + $isprime[$_] -eq $null } | ForEach-Object { + $_ + $isprime[$_] = $true + for ( $i=$_*$_ ; $i -le $num; $i += $_ ) + { $isprime[$i] = $false } + } + 2..$num | Where-Object { $isprime[$_] -eq $null } +} + +function Truncatable ( [int] $num ) +{ + $declen = [math]::abs($num).ToString().Length + $primes = @() + $ltprimes = @{} + $rtprimes = @{} + 1..$declen | ForEach-Object { $ltprimes[$_]=@{}; $rtprimes[$_]=@{} } + IsPrime $num | ForEach-Object { + $lastltprime = 2 + $lastrtprime = 2 + } { + $curprim = $_ + $curdeclen = $curprim.ToString().Length + $primes += $curprim + if( $curdeclen -eq 1 ) { + $ltprimes[1][$curprim] = $true + $rtprimes[1][$curprim] = $true + $lastltprime = $curprim + $lastrtprime = $curprim + } else { + $curmod = $curprim % [math]::pow(10,$curdeclen - 1) + $curdiv = [math]::floor($curprim / 10) + if( $ltprimes[$curdeclen - 1][[int]$curmod] ) { + $ltprimes[$curdeclen][$curprim] = $true + $lastltprime = $curprim + } + if( $rtprimes[$curdeclen - 1][[int]$curdiv] ) { + $rtprimes[$curdeclen][$curprim] = $true + $lastrtprime = $curprim + } + } + if( ( $ltprimes[$curdeclen - 2].Keys.count -gt 0 ) -and ( $ltprimes[$curdeclen - 1].Keys.count -gt 0 ) ) { $ltprimes[$curdeclen -2] = @{} } + if( ( $rtprimes[$curdeclen - 2].Keys.count -gt 0 ) -and ( $rtprimes[$curdeclen - 1].Keys.count -gt 0 ) ) { $rtprimes[$curdeclen -2] = @{} } + } { + "Largest Left Truncatable Prime: $lastltprime" + "Largest Right Truncatable Prime: $lastrtprime" + } +} diff --git a/Task/Truncatable-primes/PureBasic/truncatable-primes-1.purebasic b/Task/Truncatable-primes/PureBasic/truncatable-primes-1.purebasic new file mode 100644 index 0000000000..f4ef10b3c5 --- /dev/null +++ b/Task/Truncatable-primes/PureBasic/truncatable-primes-1.purebasic @@ -0,0 +1,68 @@ +#MaxLim = 999999 + +Procedure is_Prime(n) + If n<=1 : ProcedureReturn #False + ElseIf n<4 : ProcedureReturn #True + ElseIf n%2=0: ProcedureReturn #False + ElseIf n<9 : ProcedureReturn #True + ElseIf n%3=0: ProcedureReturn #False + Else + Protected r=Round(Sqr(n),#PB_Round_Down) + Protected f=5 + While f<=r + If n%f=0 Or n%(f+2)=0 + ProcedureReturn #False + EndIf + f+6 + Wend + EndIf + ProcedureReturn #True +EndProcedure + +Procedure TruncateLeft(n) + Protected s.s=Str(n), l=Len(s)-1 + If Not FindString(s,"0",1) + While l>0 + s=Right(s,l) + If Not is_Prime(Val(s)) + ProcedureReturn #False + EndIf + l-1 + Wend + ProcedureReturn #True + EndIf +EndProcedure + +Procedure TruncateRight(a) + Repeat + a/10 + If Not a + Break + ElseIf Not is_Prime(a) Or a%10=0 + ProcedureReturn #False + EndIf + ForEver + ProcedureReturn #True +EndProcedure + +i=#MaxLim +Repeat + If is_Prime(i) + If Not truncateleft And TruncateLeft(i) + truncateleft=i + EndIf + If Not truncateright And TruncateRight(i) + truncateright=i + EndIf + EndIf + If truncateleft And truncateright + Break + Else + i-2 + EndIf +Until i<=0 + +x.s="Largest TruncateLeft= "+Str(truncateleft) +y.s="Largest TruncateRight= "+Str(truncateright) + +MessageRequester("Truncatable primes",x+#CRLF$+y) diff --git a/Task/Truncatable-primes/PureBasic/truncatable-primes-2.purebasic b/Task/Truncatable-primes/PureBasic/truncatable-primes-2.purebasic new file mode 100644 index 0000000000..742cfc1653 --- /dev/null +++ b/Task/Truncatable-primes/PureBasic/truncatable-primes-2.purebasic @@ -0,0 +1,30 @@ +maxprime = 1000000 + +def primes(n): + multiples = set() + prime = [] + for i in range(2, n+1): + if i not in multiples: + prime.append(i) + multiples.update(set(range(i*i, n+1, i))) + return prime + +def truncatableprime(n): + 'Return a longest left and right truncatable primes below n' + primelist = [str(x) for x in primes(n)[::-1]] + primeset = set(primelist) + for n in primelist: + # n = 'abc'; [n[i:] for i in range(len(n))] -> ['abc', 'bc', 'c'] + alltruncs = set(n[i:] for i in range(len(n))) + if alltruncs.issubset(primeset): + truncateleft = int(n) + break + for n in primelist: + # n = 'abc'; [n[:i+1] for i in range(len(n))] -> ['a', 'ab', 'abc'] + alltruncs = set([n[:i+1] for i in range(len(n))]) + if alltruncs.issubset(primeset): + truncateright = int(n) + break + return truncateleft, truncateright + +print(truncatableprime(maxprime)) diff --git a/Task/Truncatable-primes/REXX/truncatable-primes.rexx b/Task/Truncatable-primes/REXX/truncatable-primes.rexx new file mode 100644 index 0000000000..868bb76263 --- /dev/null +++ b/Task/Truncatable-primes/REXX/truncatable-primes.rexx @@ -0,0 +1,40 @@ +/*REXX pgm finds largest left- and right-truncatable primes < 1 million.*/ +!.=0 /*placeholders for primes. */ +p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13; p.7=17 /*some low primes.*/ +!.2=1; !.3=1; !.4=1; !.7=1; !.11=1; !.13=1; !.17=1 /*low prime flags.*/ +n=7 /*number of primes so far. */ + do j=p.n+2 by 2 to 1000000 /*find all primes < 1,000,000. */ + if j//3 ==0 then iterate /*divisible by three? */ + if right(j,1)==5 then iterate /*right-most digit a five? */ + if j//7 ==0 then iterate /*divisible by seven? */ + if j//11 ==0 then iterate /*divisible by eleven? */ + /*the above 4 lines saves time. */ + do k=6 while p.k**2<=j /*divide by known odd primes. */ + if j//p.k==0 then iterate j /*Is divisible by X? Not prime.*/ + end /*k*/ + n=n+1 /*bump number of primes found. */ + p.n=j /*assign to sparse array. */ + !.j=1 /*indicate that J is a prime.*/ + end /*j*/ + +say 'The last prime is' p.n " (there are "n 'primes under one million).' +say copies('─',70) /*show a separator line. */ +lp=0; rp=0 + + do L=n by -1 until lp\==0; if pos(0,p.L)\==0 then iterate + do k=1 for length(p.L)-1; _=right(p.L,k) /*truncate a #.*/ + if \!._ then iterate L /*Truncated # ¬prime? Skip it.*/ + end /*k*/ + lp=p.L + end /*L*/ + + do R=n by -1 until rp\==0; if pos(0,p.R)\==0 then iterate + do k=1 for length(p.R)-1; _=left(p.R,k) /*truncate a #.*/ + if \!._ then iterate R /*Truncated # ¬prime? Skip it.*/ + end /*k*/ + rp=p.R + end /*R*/ + +say 'The largest left-truncatable prime under one million is ' lp +say 'The largest right-truncatable prime under one million is ' rp + /*stick a fork in it, we're done.*/ diff --git a/Task/Truncatable-primes/Ruby/truncatable-primes.rb b/Task/Truncatable-primes/Ruby/truncatable-primes.rb new file mode 100644 index 0000000000..ce18f3017e --- /dev/null +++ b/Task/Truncatable-primes/Ruby/truncatable-primes.rb @@ -0,0 +1,34 @@ +def left_truncatable?(n) + return truncatable?(n, $left_truncate) +end + +$left_truncate = proc do |n| + begin + n = Integer(String(n)[1..-1]) + rescue ArgumentError + n = 0 + end + n +end + +def right_truncatable?(n) + return truncatable?(n, $right_truncate) +end + +$right_truncate = proc {|n| n/10} + +def truncatable?(n, trunc_func) + return false if String(n).include? "0" + loop do + n = trunc_func.call(n) + return true if n == 0 + return false if not Prime.prime?(n) + end +end + +############# +require 'prime' +primes = Prime.each(1_000_000).to_a.reverse + +p primes.detect {|p| left_truncatable? p} +p primes.detect {|p| right_truncatable? p} diff --git a/Task/Truncatable-primes/Tcl/truncatable-primes.tcl b/Task/Truncatable-primes/Tcl/truncatable-primes.tcl new file mode 100644 index 0000000000..99a12cafcb --- /dev/null +++ b/Task/Truncatable-primes/Tcl/truncatable-primes.tcl @@ -0,0 +1,66 @@ +package require Tcl 8.5 + +# Optimized version of the Sieve-of-Eratosthenes task solution +proc sieve n { + set primes [list] + if {$n < 2} {return $primes} + set nums [dict create] + for {set i 2} {$i <= $n} {incr i} { + dict set nums $i "" + } + set next 2 + set limit [expr {sqrt($n)}] + while {$next <= $limit} { + for {set i $next} {$i <= $n} {incr i $next} {dict unset nums $i} + lappend primes $next + dict for {next -} $nums break + } + return [concat $primes [dict keys $nums]] +} + +proc isLeftTruncatable n { + global isPrime + while {[string length $n] > 0} { + if {![info exist isPrime($n)]} { + return false + } + set n [string range $n 1 end] + } + return true +} +proc isRightTruncatable n { + global isPrime + while {[string length $n] > 0} { + if {![info exist isPrime($n)]} { + return false + } + set n [string range $n 0 end-1] + } + return true +} + +# Demo code +set limit 1000000 +puts "calculating primes up to $limit" +set primes [sieve $limit] +puts "search space contains [llength $primes] members" +foreach p $primes { + set isPrime($p) "yes" +} +set primes [lreverse $primes] + +puts "searching for largest left-truncatable prime" +foreach p $primes { + if {[isLeftTruncatable $p]} { + puts FOUND:$p + break + } +} + +puts "searching for largest right-truncatable prime" +foreach p $primes { + if {[isRightTruncatable $p]} { + puts FOUND:$p + break + } +} diff --git a/Task/Truncatable-primes/XPL0/truncatable-primes.xpl0 b/Task/Truncatable-primes/XPL0/truncatable-primes.xpl0 new file mode 100644 index 0000000000..dbf4db54a9 --- /dev/null +++ b/Task/Truncatable-primes/XPL0/truncatable-primes.xpl0 @@ -0,0 +1,42 @@ +code CrLf=9, IntOut=11; + +func Prime(P); \Return true if P is a prime number +int P; \(1 is not prime, but 2 is, etc.) +int I; +[if P<=1 then return false; \negative numbers are not prime +for I:= 2 to sqrt(P) do + if rem(P/I) = 0 then return false; +return true; +]; + +func RightTrunc(N); \Return largest right-truncatable prime < one million +int N; +int M; +[for N:= 1_000_000-1 downto 2 do + [M:= N; + loop [if not Prime(M) then quit; + M:= M/10; + if rem(0) = 0 then quit; \no zeros allowed + if M=0 then return N; + ]; + ]; +]; + +func LeftTrunc(N); \Return largest left-truncatable prime < one million +int N; +int M, P; +[for N:= 1_000_000-1 downto 2 do + [M:= N; + P:=100_000; + loop [if not Prime(M) then quit; + M:= rem(M/P); + P:= P/10; + if M

3 then + raise Program_Error + with "usage: truncate_file []"; + end if; + + -- now do the real work + declare + File_Name: String := Arg(1); + Temp_Name: String := (if Args = 2 then Arg(1) & ".tmp" else Arg(3)); + -- an Ada 2012 conditional expression + File, Temp: Byte_IO.File_Type; + Count: Natural := Natural'Value(Arg(2)); + Value: Byte; + begin + -- open files + Byte_IO.Open (File => File, Mode => Byte_IO.In_File, Name => File_Name); + Byte_IO.Create(File => Temp, Mode => Byte_IO.Out_File, Name => Temp_Name); + + -- copy the required bytes (but at most as much as File has) from File to Temp + while (not Byte_IO.End_Of_File(File)) and Count > 0 loop + Byte_IO.Read (File, Value); + Byte_IO.Write(Temp, Value); + Count := Count - 1; + end loop; + + -- close files + Byte_IO.Close(Temp); + Byte_IO.Close(File); + + if Count = 0 then -- File was at least Count bytes long + -- remove File and rename Temp to File + Ada.Directories.Delete_File(Name => File_Name); + Ada.Directories.Rename(Old_Name => Temp_Name, New_Name => File_Name); + else -- File was too short + -- remove Temp and leave File as it is, output error + Ada.Directories.Delete_File(Name => Temp_Name); + raise Program_Error + with "Size of """ & File_Name & """ less than " & Arg(2); + end if; + end; +end Truncate_File; diff --git a/Task/Truncate-a-file/BASIC/truncate-a-file.basic b/Task/Truncate-a-file/BASIC/truncate-a-file.basic new file mode 100644 index 0000000000..b92f1867e8 --- /dev/null +++ b/Task/Truncate-a-file/BASIC/truncate-a-file.basic @@ -0,0 +1,20 @@ +SUB truncateFile (file AS STRING, length AS LONG) + IF LEN(DIR$(file)) THEN + DIM f AS LONG, c AS STRING + f = FREEFILE + OPEN file FOR BINARY AS f + IF length > LOF(f) THEN + CLOSE f + ERROR 62 'Input past end of file + ELSE + c = SPACE$(length) + GET #f, 1, c + CLOSE f + OPEN file FOR OUTPUT AS f + PRINT #f, c; + CLOSE f + END IF + ELSE + ERROR 53 + END IF +END SUB diff --git a/Task/Truncate-a-file/BBC-BASIC/truncate-a-file.bbc b/Task/Truncate-a-file/BBC-BASIC/truncate-a-file.bbc new file mode 100644 index 0000000000..3c937dd6bb --- /dev/null +++ b/Task/Truncate-a-file/BBC-BASIC/truncate-a-file.bbc @@ -0,0 +1,7 @@ + DEF PROCtruncate(file$, size%) + LOCAL file% + file% = OPENUP(file$) + IF file%=0 ERROR 100, "Could not open file" + EXT#file% = size% + CLOSE #file% + ENDPROC diff --git a/Task/Truncate-a-file/C-sharp/truncate-a-file.cs b/Task/Truncate-a-file/C-sharp/truncate-a-file.cs new file mode 100644 index 0000000000..cc06c224a4 --- /dev/null +++ b/Task/Truncate-a-file/C-sharp/truncate-a-file.cs @@ -0,0 +1,28 @@ +using System; +using System.IO; + +namespace TruncateFile +{ + internal class Program + { + private static void Main(string[] args) + { + TruncateFile(args[0], long.Parse(args[1])); + } + + private static void TruncateFile(string path, long length) + { + if (!File.Exists(path)) + throw new ArgumentException("No file found at specified path.", "path"); + + using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Write)) + { + if (fileStream.Length < length) + throw new ArgumentOutOfRangeException("length", + "The specified length is greater than that of the file."); + + fileStream.SetLength(length); + } + } + } +} diff --git a/Task/Truncate-a-file/C/truncate-a-file-1.c b/Task/Truncate-a-file/C/truncate-a-file-1.c new file mode 100644 index 0000000000..f30e2f727d --- /dev/null +++ b/Task/Truncate-a-file/C/truncate-a-file-1.c @@ -0,0 +1,81 @@ +#include +#include +#include + +/* Print "message: last Win32 error" to stderr. */ +void +oops(const wchar_t *message) +{ + wchar_t *buf; + DWORD error; + + buf = NULL; + error = GetLastError(); + FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error, 0, (wchar_t *)&buf, 0, NULL); + + if (buf) { + fwprintf(stderr, L"%ls: %ls", message, buf); + LocalFree(buf); + } else { + /* FormatMessageW failed. */ + fwprintf(stderr, L"%ls: unknown error 0x%x\n", + message, error); + } +} + +int +dotruncate(wchar_t *fn, LARGE_INTEGER fp) +{ + HANDLE fh; + + fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + if (fh == INVALID_HANDLE_VALUE) { + oops(fn); + return 1; + } + + if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || + SetEndOfFile(fh) == 0) { + oops(fn); + CloseHandle(fh); + return 1; + } + + CloseHandle(fh); + return 0; +} + +/* + * Truncate or extend a file to the given length. + */ +int +main() +{ + LARGE_INTEGER fp; + int argc; + wchar_t **argv, *fn, junk[2]; + + /* MinGW never provides wmain(argc, argv). */ + argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argv == NULL) { + oops(L"CommandLineToArgvW"); + return 1; + } + + if (argc != 3) { + fwprintf(stderr, L"usage: %ls filename length\n", argv[0]); + return 1; + } + + fn = argv[1]; + + /* fp = argv[2] converted to a LARGE_INTEGER. */ + if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) { + fwprintf(stderr, L"%ls: not a number\n", argv[2]); + return 1; + } + + return dotruncate(fn, fp); +} diff --git a/Task/Truncate-a-file/C/truncate-a-file-2.c b/Task/Truncate-a-file/C/truncate-a-file-2.c new file mode 100644 index 0000000000..790cee464e --- /dev/null +++ b/Task/Truncate-a-file/C/truncate-a-file-2.c @@ -0,0 +1,7 @@ +#include +#include + +... +truncate(filename, length); +ftruncate(fd, length); +... diff --git a/Task/Truncate-a-file/D/truncate-a-file.d b/Task/Truncate-a-file/D/truncate-a-file.d new file mode 100644 index 0000000000..576fc56213 --- /dev/null +++ b/Task/Truncate-a-file/D/truncate-a-file.d @@ -0,0 +1,22 @@ +import std.file, std.exception; + +void truncateFile(in string name, in size_t newSize) { + if (!exists(name) || !isFile(name)) + throw new Exception("File not found."); + + auto size = getSize(name); + if (size <= newSize) + throw new Exception( + "New size must be smaller than original size."); + + auto content = cast(ubyte[])read(name, newSize); + if (content.length != newSize) + throw new Exception("Reading file failed."); + + write(name, content); + enforce(getSize(name) == newSize); +} + +void main() { + truncateFile("truncate_test.txt", 0); +} diff --git a/Task/Truncate-a-file/Go/truncate-a-file.go b/Task/Truncate-a-file/Go/truncate-a-file.go new file mode 100644 index 0000000000..e072f407de --- /dev/null +++ b/Task/Truncate-a-file/Go/truncate-a-file.go @@ -0,0 +1,8 @@ +import ( + "fmt" + "os" +) + +if err := os.Truncate("filename", newSize); err != nil { + fmt.Println(err) +} diff --git a/Task/Truncate-a-file/Haskell/truncate-a-file.hs b/Task/Truncate-a-file/Haskell/truncate-a-file.hs new file mode 100644 index 0000000000..a8d8cdeda4 --- /dev/null +++ b/Task/Truncate-a-file/Haskell/truncate-a-file.hs @@ -0,0 +1,5 @@ +setFileSize :: FilePath -> FileOffset -> IO () +-- Truncates the file down to the specified length. +-- If the file was larger than the given length +-- before this operation was performed the extra is lost. +-- Note: calls truncate. diff --git a/Task/Truncate-a-file/Icon/truncate-a-file.icon b/Task/Truncate-a-file/Icon/truncate-a-file.icon new file mode 100644 index 0000000000..f75b692761 --- /dev/null +++ b/Task/Truncate-a-file/Icon/truncate-a-file.icon @@ -0,0 +1 @@ +truncate(f := open(filename, "bu"), newsizeinbytes) & close(f) diff --git a/Task/Truncate-a-file/J/truncate-a-file-1.j b/Task/Truncate-a-file/J/truncate-a-file-1.j new file mode 100644 index 0000000000..c6941c8b98 --- /dev/null +++ b/Task/Truncate-a-file/J/truncate-a-file-1.j @@ -0,0 +1,2 @@ +require 'files' NB. needed for versions prior to J7 +ftruncate=: ] fwrite~ ] fread@; 0 , [ diff --git a/Task/Truncate-a-file/J/truncate-a-file-2.j b/Task/Truncate-a-file/J/truncate-a-file-2.j new file mode 100644 index 0000000000..ca8bc36de9 --- /dev/null +++ b/Task/Truncate-a-file/J/truncate-a-file-2.j @@ -0,0 +1,5 @@ + (1000$ 'abcdefg') fwrite 'text.txt' NB. create test file + 567 ftruncate 'test.txt' NB. truncate test file +567 + fsize 'test.txt' NB. check new file size +567 diff --git a/Task/Truncate-a-file/Java/truncate-a-file.java b/Task/Truncate-a-file/Java/truncate-a-file.java new file mode 100644 index 0000000000..5283d28410 --- /dev/null +++ b/Task/Truncate-a-file/Java/truncate-a-file.java @@ -0,0 +1,17 @@ +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + +public class TruncFile { + public static void main(String[] args) throws IOException{ + if(args.length < 2){ + System.out.println("Usage: java TruncFile fileName newSize"); + return; + } + //turn on "append" so it doesn't clear the file + FileChannel outChan = new FileOutputStream(args[0], true).getChannel(); + long newSize = Long.parseLong(args[1]); + outChan.truncate(newSize); + outChan.close(); + } +} diff --git a/Task/Truncate-a-file/Liberty-BASIC/truncate-a-file.liberty b/Task/Truncate-a-file/Liberty-BASIC/truncate-a-file.liberty new file mode 100644 index 0000000000..ea5df89e38 --- /dev/null +++ b/Task/Truncate-a-file/Liberty-BASIC/truncate-a-file.liberty @@ -0,0 +1,30 @@ +dim info$( 50, 50) ' NB pre-dimension before calling file-exists + ' needed for file-exists function +open "test.dat" for output as #1 'create file + for i = 1 to 10000 + #1 chr$( int( 256 *rnd( 1))); + next +close #1 + +call truncateFile, "test.dat", 5000 + +wait + +sub truncateFile fn$, length + if fileExists( DefaultDir$, fn$) =0 then notice "No such file": exit sub + open fn$ for input as #i + file$ =input$( #i, lof( #i)) + if len( file$) filename; + BinaryWrite[temp, BinaryReadList[filename, "Byte", nbbytes]]; + Close[temp]; DeleteFile[filename]; RenameFile[temp, filename]; + ] diff --git a/Task/Truncate-a-file/OCaml/truncate-a-file-1.ocaml b/Task/Truncate-a-file/OCaml/truncate-a-file-1.ocaml new file mode 100644 index 0000000000..99564d9fe6 --- /dev/null +++ b/Task/Truncate-a-file/OCaml/truncate-a-file-1.ocaml @@ -0,0 +1,2 @@ +val truncate : string -> int -> unit +(** Truncates the named file to the given size. *) diff --git a/Task/Truncate-a-file/OCaml/truncate-a-file-2.ocaml b/Task/Truncate-a-file/OCaml/truncate-a-file-2.ocaml new file mode 100644 index 0000000000..c84c9ba5a9 --- /dev/null +++ b/Task/Truncate-a-file/OCaml/truncate-a-file-2.ocaml @@ -0,0 +1,2 @@ +val ftruncate : file_descr -> int -> unit +(** Truncates the file corresponding to the given descriptor to the given size. *) diff --git a/Task/Truncate-a-file/PL-I/truncate-a-file.pli b/Task/Truncate-a-file/PL-I/truncate-a-file.pli new file mode 100644 index 0000000000..4e9fc6c9e1 --- /dev/null +++ b/Task/Truncate-a-file/PL-I/truncate-a-file.pli @@ -0,0 +1,28 @@ +/* Parameters to be read in by the program are: */ +/* 1. the name of the file to be truncated, and */ +/* 2. the size of file after truncation. */ + +truncate_file: procedure options (main); /* 12 July 2012 */ + declare (i, n) fixed binary (31); + declare filename character(50) varying; + declare in file record input, out file record output; + + put ('What is the name of the file to be truncated?'); + get edit (filename) (L); + put ('What is the length of file to be retained?'); + get (n); + + begin; + declare c(n) character (1), ch character (1); + + open file (in) title ('/' || filename || ',type(fixed),recsize(1)' ) + input; + do i = 1 to n; read file (in) into (ch); c(i) = ch; end; + close file (in); + + open file (out) title ('/' || filename || ',append(n),type(fixed), + recsize(' || trim(n) || ')' ); + write file (out) from (c); + close file (out); + end; +end truncate_file; diff --git a/Task/Truncate-a-file/Pascal/truncate-a-file.pascal b/Task/Truncate-a-file/Pascal/truncate-a-file.pascal new file mode 100644 index 0000000000..5270b38898 --- /dev/null +++ b/Task/Truncate-a-file/Pascal/truncate-a-file.pascal @@ -0,0 +1,36 @@ +Program FileTruncate; + +uses + SysUtils; + +var + myfile: file of byte; + filename: string; + position: integer; + +begin + write('File for truncation: '); + readln(filename); + if not FileExists(filename) then + begin + writeln('Error: File does not exist.'); + exit; + end; + + write('Truncate position: '); + readln(position); + + Assign(myfile, filename); + Reset(myfile); + if FileSize(myfile) < position then + begin + writeln('Warning: The file "', filename, '" is too short. No need to truncate at position ', position); + Close(myfile); + exit; + end; + + Seek(myfile, position); + Truncate(myfile); + Close(myfile); + writeln('File "', filename, '" truncated at position ', position, '.'); +end. diff --git a/Task/Truncate-a-file/Perl-6/truncate-a-file.pl6 b/Task/Truncate-a-file/Perl-6/truncate-a-file.pl6 new file mode 100644 index 0000000000..73b80d6752 --- /dev/null +++ b/Task/Truncate-a-file/Perl-6/truncate-a-file.pl6 @@ -0,0 +1,12 @@ +use NativeCall; + +sub truncate(Str, Int --> int) is native {*} + +sub MAIN (Str $file, Int $to) { + given $file.IO { + .e or die "$file doesn't exist"; + .w or die "$file isn't writable"; + .s >= $to or die "$file is not big enough to truncate"; + } + truncate($file, $to) == 0 or die "Truncation was unsuccessful"; +} diff --git a/Task/Truncate-a-file/Perl/truncate-a-file.pl b/Task/Truncate-a-file/Perl/truncate-a-file.pl new file mode 100644 index 0000000000..2367dcda8a --- /dev/null +++ b/Task/Truncate-a-file/Perl/truncate-a-file.pl @@ -0,0 +1,7 @@ +# Open a file for writing, and truncate it to 1234 bytes. +open FOO, ">>file" or die; +truncate(FOO, 1234); +close FOO; + +# Truncate a file to 567 bytes. +truncate("file", 567); diff --git a/Task/Truncate-a-file/PicoLisp/truncate-a-file-1.l b/Task/Truncate-a-file/PicoLisp/truncate-a-file-1.l new file mode 100644 index 0000000000..f255b7e4e6 --- /dev/null +++ b/Task/Truncate-a-file/PicoLisp/truncate-a-file-1.l @@ -0,0 +1,2 @@ +(de truncate (File Len) + (native "@" "truncate" 'I File Len) ) diff --git a/Task/Truncate-a-file/PicoLisp/truncate-a-file-2.l b/Task/Truncate-a-file/PicoLisp/truncate-a-file-2.l new file mode 100644 index 0000000000..e30962b3fc --- /dev/null +++ b/Task/Truncate-a-file/PicoLisp/truncate-a-file-2.l @@ -0,0 +1,2 @@ +(de truncate (File Len) + (call "truncate" "-s" Len File) ) diff --git a/Task/Truncate-a-file/PowerBASIC/truncate-a-file.powerbasic b/Task/Truncate-a-file/PowerBASIC/truncate-a-file.powerbasic new file mode 100644 index 0000000000..069eab8e9f --- /dev/null +++ b/Task/Truncate-a-file/PowerBASIC/truncate-a-file.powerbasic @@ -0,0 +1,17 @@ +SUB truncateFile (file AS STRING, length AS DWORD) + IF LEN(DIR$(file)) THEN + DIM f AS LONG + f = FREEFILE + OPEN file FOR BINARY AS f + IF length > LOF(f) THEN + CLOSE f + ERROR 62 'Input past end + ELSE + SEEK f, length + 1 + SETEOF f + CLOSE f + END IF + ELSE + ERROR 53 'File not found + END IF +END SUB diff --git a/Task/Truncate-a-file/PureBasic/truncate-a-file.purebasic b/Task/Truncate-a-file/PureBasic/truncate-a-file.purebasic new file mode 100644 index 0000000000..5f5bc431ac --- /dev/null +++ b/Task/Truncate-a-file/PureBasic/truncate-a-file.purebasic @@ -0,0 +1,13 @@ +Procedure SetFileSize(File$, length.q) + Protected fh, pos, i + If FileSize(File$) < length + Debug "File to small, is a directory or does not exist." + ProcedureReturn #False + Else + fh = OpenFile(#PB_Any, File$) + FileSeek(fh, length) + TruncateFile(fh) + CloseFile(fh) + EndIf + ProcedureReturn #True +EndProcedure diff --git a/Task/Truncate-a-file/Python/truncate-a-file.py b/Task/Truncate-a-file/Python/truncate-a-file.py new file mode 100644 index 0000000000..ae0f3d50b8 --- /dev/null +++ b/Task/Truncate-a-file/Python/truncate-a-file.py @@ -0,0 +1,4 @@ +def truncate_file(fname, size): + "Open a file for writing, and truncate it to size bytes." + with open(fname, "ab") as f: + f.truncate(size) diff --git a/Task/Truncate-a-file/Ruby/truncate-a-file.rb b/Task/Truncate-a-file/Ruby/truncate-a-file.rb new file mode 100644 index 0000000000..9816e5ad89 --- /dev/null +++ b/Task/Truncate-a-file/Ruby/truncate-a-file.rb @@ -0,0 +1,5 @@ +# Open a file for writing, and truncate it to 1234 bytes. +File.open("file", "ab") { |f| f.truncate(1234) } + +# Truncate a file to 567 bytes. +File.truncate("file", 567) diff --git a/Task/Truncate-a-file/Tcl/truncate-a-file.tcl b/Task/Truncate-a-file/Tcl/truncate-a-file.tcl new file mode 100644 index 0000000000..572f481b2c --- /dev/null +++ b/Task/Truncate-a-file/Tcl/truncate-a-file.tcl @@ -0,0 +1,5 @@ +package require Tcl 8.5 + +set f [open "file" r+]; # Truncation is done on channels +chan truncate $f 1234; # Truncate at a particular length (in bytes) +close $f diff --git a/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-1.sh b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-1.sh new file mode 100644 index 0000000000..9564edd269 --- /dev/null +++ b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-1.sh @@ -0,0 +1,3 @@ +# Truncate a file named "myfile" to 1440 kilobytes. +ls myfile >/dev/null && + dd if=/dev/null of=myfile bs=1 seek=1440k diff --git a/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-2.sh b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-2.sh new file mode 100644 index 0000000000..04b9b96b82 --- /dev/null +++ b/Task/Truncate-a-file/UNIX-Shell/truncate-a-file-2.sh @@ -0,0 +1,2 @@ +# Truncate a file named "myfile" to 1440 kilobytes. +truncate -s 1440k myfile diff --git a/Task/Truncate-a-file/ZX-Spectrum-Basic/truncate-a-file.zx b/Task/Truncate-a-file/ZX-Spectrum-Basic/truncate-a-file.zx new file mode 100644 index 0000000000..f072002522 --- /dev/null +++ b/Task/Truncate-a-file/ZX-Spectrum-Basic/truncate-a-file.zx @@ -0,0 +1,8 @@ +10 CLEAR 29999 +20 INPUT "Which file do you want to truncate?";f$ +30 PRINT "Start tape to load file to truncate." +40 LOAD f$ CODE 30000 +50 "Input how many bytes do you want to keep?";n +60 PRINT "Please rewind the tape and press record." +70 SAVE f$ CODE 30000,n +80 STOP diff --git a/Task/Twelve-statements/0DESCRIPTION b/Task/Twelve-statements/0DESCRIPTION new file mode 100644 index 0000000000..18759e915f --- /dev/null +++ b/Task/Twelve-statements/0DESCRIPTION @@ -0,0 +1,20 @@ +This puzzle is borrowed from [http://math-frolic.blogspot.co.uk/2012/08/mind-wrenching.html here]. + +Given the following twelve statements, which of them are true? + +

1.  This is a numbered list of twelve statements.
+2.  Exactly 3 of the last 6 statements are true.
+3.  Exactly 2 of the even-numbered statements are true.
+4.  If statement 5 is true, then statements 6 and 7 are both true.
+5.  The 3 preceding statements are all false.
+6.  Exactly 4 of the odd-numbered statements are true.
+7.  Either statement 2 or 3 is true, but not both.
+8.  If statement 7 is true, then 5 and 6 are both true.
+9.  Exactly 3 of the first 6 statements are true.
+10.  The next two statements are both true.
+11.  Exactly 1 of statements 7, 8 and 9 are true.
+12.  Exactly 4 of the preceding statements are true.
+ +When you get tired of trying to figure it out in your head, write a program to solve it, and print the correct answer or answers. + +Extra credit: also print out a table of near misses, that is, solutions that are contradicted by only a single statement. diff --git a/Task/Twelve-statements/Ada/twelve-statements-1.ada b/Task/Twelve-statements/Ada/twelve-statements-1.ada new file mode 100644 index 0000000000..e4e421fe2b --- /dev/null +++ b/Task/Twelve-statements/Ada/twelve-statements-1.ada @@ -0,0 +1,79 @@ +with Ada.Text_IO, Logic; + +procedure Twelve_Statements is + + package L is new Logic(Number_Of_Statements => 12); use L; + + -- formally define the 12 statements as expression function predicates + function P01(T: Table) return Boolean is (T'Length = 12); -- list of 12 statements + function P02(T: Table) return Boolean is (Sum(T(7 .. 12)) = 3); -- three of last six + function P03(T: Table) return Boolean is (Sum(Half(T, Even)) = 2); -- two of the even + function P04(T: Table) return Boolean is (if T(5) then T(6) and T(7)); -- if 5 is true, then ... + function P05(T: Table) return Boolean is + ( (not T(2)) and (not T(3)) and (not T(4)) ); -- none of preceding three + function P06(T: Table) return Boolean is (Sum(Half(T, Odd)) = 4); -- four of the odd + function P07(T: Table) return Boolean is (T(2) xor T(3)); -- either 2 or 3, not both + function P08(T: Table) return Boolean is (if T(7) then T(5) and T(6)); -- if 7 is true, then ... + function P09(T: Table) return Boolean is (Sum(T(1 .. 6)) = 3); -- three of first six + function P10(T: Table) return Boolean is (T(11) and T(12)); -- next two + function P11(T: Table) return Boolean is (Sum(T(7..9)) = 1); -- one of 7, 8, 9 + function P12(T: Table) return Boolean is (Sum(T(1 .. 11)) = 4); -- four of the preding + + -- define a global list of statements + Statement_List: constant Statements := + (P01'Access, P02'Access, P03'Access, P04'Access, P05'Access, P06'Access, + P07'Access, P08'Access, P09'Access, P10'Access, P11'Access, P12'Access); + + -- try out all 2^12 possible choices for the table + procedure Try(T: Table; Fail: Natural; Idx: Indices'Base := Indices'First) is + + procedure Print_Table(T: Table) is + use Ada.Text_IO; + begin + Put(" "); + if Fail > 0 then + Put("(wrong at"); + for J in T'Range loop + if Statement_List(J)(T) /= T(J) then + Put(Integer'Image(J) & (if J < 10 then ") " else ") ")); + end if; + end loop; + end if; + if T = (1..12 => False) then + Put_Line("All false!"); + else + Put("True are"); + for J in T'Range loop + if T(J) then + Put(Integer'Image(J)); + end if; + end loop; + New_Line; + end if; + end Print_Table; + + Wrong_Entries: Natural := 0; + + begin + if Idx <= T'Last then + Try(T(T'First .. Idx-1) & False & T(Idx+1 .. T'Last), Fail, Idx+1); + Try(T(T'First .. Idx-1) & True & T(Idx+1 .. T'Last), Fail, Idx+1); + else -- now Index > T'Last and we have one of the 2^12 choices to test + for J in T'Range loop + if Statement_List(J)(T) /= T(J) then + Wrong_Entries := Wrong_Entries + 1; + end if; + end loop; + if Wrong_Entries = Fail then + Print_Table(T); + end if; + end if; + end Try; + +begin + Ada.Text_IO.Put_Line("Exact hits:"); + Try(T => (1..12 => False), Fail => 0); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line("Near Misses:"); + Try(T => (1..12 => False), Fail => 1); +end Twelve_Statements; diff --git a/Task/Twelve-statements/Ada/twelve-statements-2.ada b/Task/Twelve-statements/Ada/twelve-statements-2.ada new file mode 100644 index 0000000000..aec014e9d0 --- /dev/null +++ b/Task/Twelve-statements/Ada/twelve-statements-2.ada @@ -0,0 +1,16 @@ +generic + Number_Of_Statements: Positive; +package Logic is + + --types + subtype Indices is Natural range 1 .. Number_Of_Statements; + type Table is array(Indices range <>) of Boolean; + type Predicate is access function(T: Table) return Boolean; + type Statements is array(Indices) of Predicate; + type Even_Odd is (Even, Odd); + + -- convenience functions + function Sum(T: Table) return Natural; + function Half(T: Table; Which: Even_Odd) return Table; + +end Logic; diff --git a/Task/Twelve-statements/Ada/twelve-statements-3.ada b/Task/Twelve-statements/Ada/twelve-statements-3.ada new file mode 100644 index 0000000000..78d47402ec --- /dev/null +++ b/Task/Twelve-statements/Ada/twelve-statements-3.ada @@ -0,0 +1,27 @@ +package body Logic is + + function Sum(T: Table) return Natural is + Result: Natural := 0; + begin + for I in T'Range loop + if T(I) then + Result := Result + 1; + end if; + end loop; + return Result; + end Sum; + + function Half(T: Table; Which: Even_Odd) return Table is + Result: Table(T'Range); + Last: Natural := Result'First - 1; + begin + for I in T'Range loop + if I mod 2 = (if (Which=Odd) then 1 else 0) then + Last := Last+1; + Result(Last) := T(I); + end if; + end loop; + return Result(Result'First .. Last); + end Half; + +end Logic; diff --git a/Task/Twelve-statements/BBC-BASIC/twelve-statements.bbc b/Task/Twelve-statements/BBC-BASIC/twelve-statements.bbc new file mode 100644 index 0000000000..16b9d553f6 --- /dev/null +++ b/Task/Twelve-statements/BBC-BASIC/twelve-statements.bbc @@ -0,0 +1,43 @@ + nStatements% = 12 + DIM Pass%(nStatements%), T%(nStatements%) + + FOR try% = 0 TO 2^nStatements%-1 + + REM Postulate answer: + FOR stmt% = 1 TO 12 + T%(stmt%) = (try% AND 2^(stmt%-1)) <> 0 + NEXT + + REM Test consistency: + Pass%(1) = T%(1) = (nStatements% = 12) + Pass%(2) = T%(2) = ((T%(7)+T%(8)+T%(9)+T%(10)+T%(11)+T%(12)) = -3) + Pass%(3) = T%(3) = ((T%(2)+T%(4)+T%(6)+T%(8)+T%(10)+T%(12)) = -2) + Pass%(4) = T%(4) = ((NOT T%(5) OR (T%(6) AND T%(7)))) + Pass%(5) = T%(5) = (NOT T%(2) AND NOT T%(3) AND NOT T%(4)) + Pass%(6) = T%(6) = ((T%(1)+T%(3)+T%(5)+T%(7)+T%(9)+T%(11)) = -4) + Pass%(7) = T%(7) = ((T%(2) EOR T%(3))) + Pass%(8) = T%(8) = ((NOT T%(7) OR (T%(5) AND T%(6)))) + Pass%(9) = T%(9) = ((T%(1)+T%(2)+T%(3)+T%(4)+T%(5)+T%(6)) = -3) + Pass%(10) = T%(10) = (T%(11) AND T%(12)) + Pass%(11) = T%(11) = ((T%(7)+T%(8)+T%(9)) = -1) + Pass%(12) = T%(12) = ((T%(1)+T%(2)+T%(3)+T%(4)+T%(5)+T%(6) + \ + \ T%(7)+T%(8)+T%(9)+T%(10)+T%(11)) = -4) + + CASE SUM(Pass%()) OF + WHEN -11: + PRINT "Near miss with statements "; + FOR stmt% = 1 TO 12 + IF T%(stmt%) PRINT ; stmt% " "; + IF NOT Pass%(stmt%) miss% = stmt% + NEXT + PRINT "true (failed " ;miss% ")." + WHEN -12: + PRINT "Solution! with statements "; + FOR stmt% = 1 TO 12 + IF T%(stmt%) PRINT ; stmt% " "; + NEXT + PRINT "true." + ENDCASE + + NEXT try% + END diff --git a/Task/Twelve-statements/D/twelve-statements.d b/Task/Twelve-statements/D/twelve-statements.d new file mode 100644 index 0000000000..b36f315bb4 --- /dev/null +++ b/Task/Twelve-statements/D/twelve-statements.d @@ -0,0 +1,63 @@ +import std.stdio, std.typecons, std.algorithm,std.range,std.functional; + +immutable texts = [ + "this is a numbered list of twelve statements", + "exactly 3 of the last 6 statements are true", + "exactly 2 of the even-numbered statements are true", + "if statement 5 is true, then statements 6 and 7 are both true", + "the 3 preceding statements are all false", + "exactly 4 of the odd-numbered statements are true", + "either statement 2 or 3 is true, but not both", + "if statement 7 is true, then 5 and 6 are both true", + "exactly 3 of the first 6 statements are true", + "the next two statements are both true", + "exactly 1 of statements 7, 8 and 9 are true", + "exactly 4 of the preceding statements are true"]; + +alias curry!(reduce!q{a + b}, 0) sumi; + +immutable bool function(in bool[])[] funcs = [ + s => s.length == 12, + s => sumi(s[$-6 .. $]) == 3, + s => sumi(s[1 .. $].stride(2)) == 2, + s => s[4] ? (s[5] && s[6]) : true, + s => sumi(s[1 .. 4]) == 0, + s => sumi(s[0 .. $].stride(2)) == 4, + s => sumi(s[1 .. 3]) == 1, + s => s[6] ? (s[4] && s[5]) : true, + s => sumi(s[0 .. 6]) == 3, + s => s[10] && s[11], + s => sumi(s[6 .. 9]) == 1, + s => sumi(s[0 .. 11]) == 4]; + +void main() { + enum nStats = 12; + Tuple!(const bool[], const bool[])[] full, partial; + + foreach (n; 0 .. 2 ^^ nStats) { + const st = iota(nStats).map!(i => !!(n & (2 ^^ i)))().array(); + auto truths = funcs.map!(f => f(st))(); + const matches = zip(st, truths) + .map!(s_t => s_t[0] == s_t[1])() + .array(); + immutable mCount = matches.sumi(); + if (mCount == nStats) + full ~= tuple(st, matches); + else if (mCount == nStats - 1) + partial ~= tuple(st, matches); + } + + foreach (sols, isPartial; zip([full, partial], [false, true])) + foreach (stm; sols) { + if (isPartial) { + immutable pos = stm[1].countUntil(false); + writefln(`Missed by statement %d: "%s"`, + pos + 1, texts[pos]); + } else + writeln("Solution:"); + write(" "); + foreach (i, t; stm[0]) + writef("%d:%s ", i + 1, t ? "T" : "F"); + writeln(); + } +} diff --git a/Task/Twelve-statements/Go/twelve-statements.go b/Task/Twelve-statements/Go/twelve-statements.go new file mode 100644 index 0000000000..b8d83a5d51 --- /dev/null +++ b/Task/Twelve-statements/Go/twelve-statements.go @@ -0,0 +1,127 @@ +package main + +import "fmt" + +// its' not too much more work to check all the permutations concurrently +var solution = make(chan int) +var nearMiss = make(chan int) +var done = make(chan bool) + +func main() { + // iterate and use the bits as the permutation + for i := 0; i < 4096; i++ { + go checkPerm(i) + } + // collect the misses and list them after the complete solution(s) + var ms []int + for i := 0; i < 4096; { + select { + case <-done: + i++ + case s := <-solution: + print12("solution", s) + case m := <-nearMiss: + ms = append(ms, m) + } + } + for _, m := range ms { + print12("near miss", m) + } +} + +func print12(label string, bits int) { + fmt.Print(label, ":") + for i := 1; i <= 12; i++ { + if bits&1 == 1 { + fmt.Print(" ", i) + } + bits >>= 1 + } + fmt.Println() +} + +func checkPerm(tz int) { + // closure returns true if tz bit corresponding to + // 1-based statement number is 1. + ts := func(n uint) bool { + return tz>>(n-1)&1 == 1 + } + // variadic closure returns number of statements listed as arguments + // which have corresponding tz bit == 1. + ntrue := func(xs ...uint) int { + nt := 0 + for _, x := range xs { + if ts(x) { + nt++ + } + } + return nt + } + // a flag used on repeated calls to test. + // set to true when first contradiction is found. + // if another is found, this function (checkPerm) can "short circuit" + // and return immediately without checking additional statements. + var con bool + // closure called to test each statement + test := func(statement uint, b bool) { + switch { + case ts(statement) == b: + case con: + panic("bail") + default: + con = true + } + } + // short circuit mechanism + defer func() { + if x := recover(); x != nil { + if msg, ok := x.(string); !ok && msg != "bail" { + panic(x) + } + } + done <- true + }() + + // 1. This is a numbered list of twelve statements. + test(1, true) + + // 2. Exactly 3 of the last 6 statements are true. + test(2, ntrue(7, 8, 9, 10, 11, 12) == 3) + + // 3. Exactly 2 of the even-numbered statements are true. + test(3, ntrue(2, 4, 6, 8, 10, 12) == 2) + + // 4. If statement 5 is true, then statements 6 and 7 are both true. + test(4, !ts(5) || ts(6) && ts(7)) + + // 5. The 3 preceding statements are all false. + test(5, !ts(4) && !ts(3) && !ts(2)) + + // 6. Exactly 4 of the odd-numbered statements are true. + test(6, ntrue(1, 3, 5, 7, 9, 11) == 4) + + // 7. Either statement 2 or 3 is true, but not both. + test(7, ts(2) != ts(3)) + + // 8. If statement 7 is true, then 5 and 6 are both true. + test(8, !ts(7) || ts(5) && ts(6)) + + // 9. Exactly 3 of the first 6 statements are true. + test(9, ntrue(1, 2, 3, 4, 5, 6) == 3) + + // 10. The next two statements are both true. + test(10, ts(11) && ts(12)) + + // 11. Exactly 1 of statements 7, 8 and 9 are true. + test(11, ntrue(7, 8, 9) == 1) + + // 12. Exactly 4 of the preceding statements are true. + test(12, ntrue(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) == 4) + + // no short circuit? send permutation as either near miss or solution + if con { + nearMiss <- tz + } else { + solution <- tz + } +} diff --git a/Task/Twelve-statements/Groovy/twelve-statements.groovy b/Task/Twelve-statements/Groovy/twelve-statements.groovy new file mode 100644 index 0000000000..8108015712 --- /dev/null +++ b/Task/Twelve-statements/Groovy/twelve-statements.groovy @@ -0,0 +1,55 @@ +enum Rule { + r01( 1, { r()*.num == (1..12) }), + r02( 2, { r(7..12).count { it.truth } == 3 }), + r03( 3, { r(2..12, 2).count { it.truth } == 2 }), + r04( 4, { r(5).truth ? r(6).truth && r(7).truth : true }), + r05( 5, { r(2..4).count { it.truth } == 0 }), + r06( 6, { r(1..11, 2).count { it.truth } == 4 }), + r07( 7, { r(2).truth != r(3).truth }), + r08( 8, { r(7).truth ? r(5).truth && r(6).truth : true }), + r09( 9, { r(1..6).count { it.truth } == 3 }), + r10(10, { r(11).truth && r(12).truth }), + r11(11, { r(7..9).count { it.truth } == 1 }), + r12(12, { r(1..11).count { it.truth } == 4 }); + + final int num + final Closure statement + boolean truth + + static final List rules = [ null, r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12] + + private Rule(num, statement) { + this.num = num + this.statement = statement + } + + public static Rule r(int index) { rules[index] } + public static List r() { rules[1..12] } + public static List r(List indices) { rules[indices] } + public static List r(IntRange indices) { rules[indices] } + public static List r(IntRange indices, int step) { r(indices.step(step)) } + + public static void setAllTruth(int bits) { + (1..12).each { r(it).truth = !(bits & (1 << (12 - it))) } + } + + public static void evaluate() { + def nearMisses = [:] + (0..<(2**12)).each { i -> + setAllTruth(i) + def truthCandidates = r().findAll { it.truth } + def truthMatchCount = r().count { it.statement() == it.truth } + if (truthMatchCount == 12) { + println ">Solution< ${truthCandidates*.num}" + } else if (truthMatchCount == 11) { + def miss = (1..12).find { r(it).statement() != r(it).truth } + nearMisses << [(truthCandidates): miss] + } + } + nearMisses.each { truths, miss -> + printf ("Near Miss: %-21s (failed %2d)\n", "${truths*.num}", miss) + } + } +} + +Rule.evaluate() diff --git a/Task/Twelve-statements/Haskell/twelve-statements.hs b/Task/Twelve-statements/Haskell/twelve-statements.hs new file mode 100644 index 0000000000..ad9e1f4836 --- /dev/null +++ b/Task/Twelve-statements/Haskell/twelve-statements.hs @@ -0,0 +1,29 @@ +import Data.List (findIndices) + +tf = mapM (\_ -> [1,0]) + +wrongness b = findIndices id . zipWith (/=) b . map (fromEnum . ($ b)) + +statements = [ (==12) . length, + 3 ? [length statements-6..], + 2 ? [1,3..], + 4 ? [4..6], + 0 ? [1..3], + 4 ? [0,2..], + 1 ? [1,2], + 6 ? [4..6], + 3 ? [0..5], + 2 ? [10,11], + 1 ? [6,7,8], + 4 ? [0..10] + ] where + (s ? x) b = s == (sum . map (b!!) . takeWhile (< length b)) x + (a ? x) b = (b!!a == 0) || all ((==1).(b!!)) x + +testall s n = [(b, w) | b <- tf s, w <- [wrongness b s], length w == n] + +main = let t = testall statements in do + putStrLn "Answer" + mapM_ print $ t 0 + putStrLn "Near misses" + mapM_ print $ t 1 diff --git a/Task/Twelve-statements/J/twelve-statements-1.j b/Task/Twelve-statements/J/twelve-statements-1.j new file mode 100644 index 0000000000..c43b413570 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-1.j @@ -0,0 +1,6 @@ + apply +128!:2 + +NB. example + '*:' apply 1 2 3 +1 4 9 diff --git a/Task/Twelve-statements/J/twelve-statements-2.j b/Task/Twelve-statements/J/twelve-statements-2.j new file mode 100644 index 0000000000..155cc47c28 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-2.j @@ -0,0 +1,16 @@ +S=: <;._2 (0 :0) +12&=@# +3=+/@:{.~&_6 +2= +/@:{~&1 3 5 7 9 11 +4&{=*./@:{~&4 5 6 +0=+/@:{~&1 2 3 +4=+/@:{~&0 2 4 6 8 10 +1=+/@:{~&1 2 +6&{=*./@:{~&4 5 6 +3=+/@:{.~&6 +2=+/@:{~&10 11 +1=+/@:{~&6 7 8 +4=+/@:{.~&11 +) + +testall=: (];"1 0<@I.@:(]~:(apply&><))"1) #:@i.@(2&^)@# diff --git a/Task/Twelve-statements/J/twelve-statements-3.j b/Task/Twelve-statements/J/twelve-statements-3.j new file mode 100644 index 0000000000..f94bd4b865 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-3.j @@ -0,0 +1,4 @@ + (#~0=#@{::~&_1"1) testall S ++------------------------+ +¦1 0 1 1 0 1 1 0 0 0 1 0¦¦ ++------------------------+ diff --git a/Task/Twelve-statements/J/twelve-statements-4.j b/Task/Twelve-statements/J/twelve-statements-4.j new file mode 100644 index 0000000000..9a0cefa25e --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-4.j @@ -0,0 +1,34 @@ + (#~1=#@{::~&_1"1) testall S ++--------------------------+ +¦0 0 0 0 1 0 0 1 0 0 1 0¦0 ¦ ++-----------------------+--¦ +¦0 0 0 0 1 0 0 1 0 1 1 1¦0 ¦ ++-----------------------+--¦ +¦0 0 0 1 0 0 0 1 0 1 1 1¦0 ¦ ++-----------------------+--¦ +¦1 0 0 0 1 0 0 0 0 0 0 0¦7 ¦ ++-----------------------+--¦ +¦1 0 0 0 1 0 0 1 0 0 0 0¦10¦ ++-----------------------+--¦ +¦1 0 0 0 1 0 0 1 0 0 1 0¦11¦ ++-----------------------+--¦ +¦1 0 0 0 1 0 0 1 0 1 1 1¦11¦ ++-----------------------+--¦ +¦1 0 0 0 1 1 0 0 1 0 1 0¦7 ¦ ++-----------------------+--¦ +¦1 0 0 1 0 0 0 0 0 0 0 0¦7 ¦ ++-----------------------+--¦ +¦1 0 0 1 0 0 0 1 0 1 1 1¦11¦ ++-----------------------+--¦ +¦1 0 0 1 0 1 0 1 1 0 0 0¦5 ¦ ++-----------------------+--¦ +¦1 0 1 1 0 0 0 1 1 0 0 0¦6 ¦ ++-----------------------+--¦ +¦1 0 1 1 0 1 1 0 1 0 0 0¦8 ¦ ++-----------------------+--¦ +¦1 1 0 1 0 0 1 0 1 0 0 1¦11¦ ++-----------------------+--¦ +¦1 1 0 1 0 0 1 0 1 1 0 0¦9 ¦ ++-----------------------+--¦ +¦1 1 0 1 0 0 1 1 1 0 0 0¦7 ¦ ++--------------------------+ diff --git a/Task/Twelve-statements/J/twelve-statements-5.j b/Task/Twelve-statements/J/twelve-statements-5.j new file mode 100644 index 0000000000..3272f7a419 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-5.j @@ -0,0 +1,2 @@ + (-N)&{. #: S <:@]^:((]-.@-:(apply&><)"1) (-N)&{.@#:@])^:(_) 2^N=.#S +1 0 1 1 0 1 1 0 0 0 1 0 diff --git a/Task/Twelve-statements/Java/twelve-statements.java b/Task/Twelve-statements/Java/twelve-statements.java new file mode 100644 index 0000000000..219f08664c --- /dev/null +++ b/Task/Twelve-statements/Java/twelve-statements.java @@ -0,0 +1,113 @@ +public class LogicPuzzle +{ + boolean S[] = new boolean[13]; + int Count = 0; + + public boolean check2 () + { + int count = 0; + for (int k = 7; k <= 12; k++) + if (S[k]) count++; + return S[2] == (count == 3); + } + + public boolean check3 () + { + int count = 0; + for (int k = 2; k <= 12; k += 2) + if (S[k]) count++; + return S[3] == (count == 2); + } + + public boolean check4 () + { + return S[4] == ( !S[5] || S[6] && S[7]); + } + + public boolean check5 () + { + return S[5] == ( !S[2] && !S[3] && !S[4]); + } + + public boolean check6 () + { + int count = 0; + for (int k = 1; k <= 11; k += 2) + if (S[k]) count++; + return S[6] == (count == 4); + } + + public boolean check7 () + { + return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); + } + + public boolean check8 () + { + return S[8] == ( !S[7] || S[5] && S[6]); + } + + public boolean check9 () + { + int count = 0; + for (int k = 1; k <= 6; k++) + if (S[k]) count++; + return S[9] == (count == 3); + } + + public boolean check10 () + { + return S[10] == (S[11] && S[12]); + } + + public boolean check11 () + { + int count = 0; + for (int k = 7; k <= 9; k++) + if (S[k]) count++; + return S[11] == (count == 1); + } + + public boolean check12 () + { + int count = 0; + for (int k = 1; k <= 11; k++) + if (S[k]) count++; + return S[12] == (count == 4); + } + + public void check () + { + if (check2() && check3() && check4() && check5() && check6() + && check7() && check8() && check9() && check10() && check11() + && check12()) + { + for (int k = 1; k <= 12; k++) + if (S[k]) System.out.print(k + " "); + System.out.println(); + Count++; + } + } + + public void recurseAll (int k) + { + if (k == 13) + check(); + else + { + S[k] = false; + recurseAll(k + 1); + S[k] = true; + recurseAll(k + 1); + } + } + + public static void main (String args[]) + { + LogicPuzzle P = new LogicPuzzle(); + P.S[1] = true; + P.recurseAll(2); + System.out.println(); + System.out.println(P.Count + " Solutions found."); + } +} diff --git a/Task/Twelve-statements/Mathematica/twelve-statements.math b/Task/Twelve-statements/Mathematica/twelve-statements.math new file mode 100644 index 0000000000..ec617aa35c --- /dev/null +++ b/Task/Twelve-statements/Mathematica/twelve-statements.math @@ -0,0 +1,10 @@ +Print["Answer:\n", Column@Cases[#, {s_, 0} :> s], "\nNear misses:\n", + Column@Cases[#, {s_, 1} :> s]] &[{#, + Count[Boole /@ {Length@# == 12, Total@#[[7 ;;]] == 3, + Total@#[[2 ;; 12 ;; 2]] == 2, #[[5]] (#[[6]] + #[[7]] - 2) == + 0, Total@#[[2 ;; 4]] == 0, + Total@#[[1 ;; 11 ;; 2]] == 4, #[[2]] + #[[3]] == + 1, #[[7]] (#[[5]] + #[[6]] - 2) == 0, + Total@#[[;; 6]] == 3, #[[11]] + #[[12]] == 2, + Total@#[[7 ;; 9]] == 1, Total@#[[;; 11]] == 4} - #, + Except[0]]} & /@ Tuples[{1, 0}, 12]] diff --git a/Task/Twelve-statements/Perl-6/twelve-statements.pl6 b/Task/Twelve-statements/Perl-6/twelve-statements.pl6 new file mode 100644 index 0000000000..30fd0301fb --- /dev/null +++ b/Task/Twelve-statements/Perl-6/twelve-statements.pl6 @@ -0,0 +1,42 @@ +sub infix: ($protasis,$apodosis) { !$protasis or $apodosis } + +my @tests = { True }, # (there's no 0th statement) + { all(.[1..12]) === any(True, False) }, + { 3 == [+] .[7..12] }, + { 2 == [+] .[2,4...12] }, + { .[5] ? all .[6,7] }, + { none .[2,3,4] }, + { 4 == [+] .[1,3...11] }, + { one .[2,3] }, + { .[7] ? all .[5,6] }, + { 3 == [+] .[1..6] }, + { all .[11,12] }, + { one .[7,8,9] }, + { 4 == [+] .[1..11] }; + +my @good; +my @bad; +my @ugly; + +for reverse 0 ..^ 2**12 -> $i { + my @b = $i.fmt("%012b").comb; + my @assert = True, @b.map: { .so } + my @result = @tests.map: { .(@assert).so } + my @s = ( $_ if $_ and @assert[$_] for 1..12 ); + if @result eqv @assert { + push @good, "<{@s}> is consistent."; + } + else { + my @cons = gather for 1..12 { + if @assert[$_] !eqv @result[$_] { + take @result[$_] ?? $_ !! "¬$_"; + } + } + my $mess = "<{@s}> implies {@cons}."; + if @cons == 1 { push @bad, $mess } else { push @ugly, $mess } + } +} + +.say for @good; +say "\nNear misses:"; +.say for @bad; diff --git a/Task/Twelve-statements/Prolog/twelve-statements.pro b/Task/Twelve-statements/Prolog/twelve-statements.pro new file mode 100644 index 0000000000..e63a6140b3 --- /dev/null +++ b/Task/Twelve-statements/Prolog/twelve-statements.pro @@ -0,0 +1,51 @@ +puzzle :- + % 1. This is a numbered list of twelve statements. + L = [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12], + L ins 0..1, + element(1, L, 1), + + % 2. Exactly 3 of the last 6 statements are true. + A2 #<==> A7 + A8 + A9 + A10 + A11 + A12 #= 3, + + % 3. Exactly 2 of the even-numbered statements are true. + A3 #<==> A2 + A4 + A6 + A8 + A10 + A12 #= 2, + + % 4. If statement 5 is true, then statements 6 and 7 are both true. + A4 #<==> (A5 #==> (A6 #/\ A7)), + + % 5. The 3 preceding statements are all false. + A5 #<==> A2 + A3 + A4 #= 0, + + % 6. Exactly 4 of the odd-numbered statements are true. + A6 #==> A1 + A3 + A5 + A7 + A9 + A11 #= 4, + + % 7. Either statement 2 or 3 is true, but not both. + A7 #<==> A2 + A3 #= 1, + + % 8. If statement 7 is true, then 5 and 6 are both true. + A8 #<==> (A7 #==> A5 #/\ A6), + + + % 9. Exactly 3 of the first 6 statements are true. + A9 #<==> A1 + A2 + A3 + A4 + A5 + A6 #= 3, + + % 10. The next two statements are both true. + A10 #<==> A11 #/\ A12, + + % 11. Exactly 1 of statements 7, 8 and 9 are true. + A11 #<==> A7 + A8 + A9 #= 1, + + % 12. Exactly 4 of the preceding statements are true. + A12 #<==> A1 + A2 + A3 + A4 + A5 + A6 + A7 +A8 + A9 + A10 + A11 #= 4, + + label(L), + numlist(1, 12, NL), + write('Statements '), + maplist(my_write, NL, L), + writeln('are true'). + + +my_write(N, 1) :- + format('~w ', [N]). + +my_write(_N, 0). diff --git a/Task/Twelve-statements/Python/twelve-statements.py b/Task/Twelve-statements/Python/twelve-statements.py new file mode 100644 index 0000000000..5c777a8605 --- /dev/null +++ b/Task/Twelve-statements/Python/twelve-statements.py @@ -0,0 +1,40 @@ +from itertools import product +#from pprint import pprint as pp + +constraintinfo = ( + (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), + (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), + (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), + (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), + (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), + (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), + (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), + (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), + (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), + (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), + (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), + (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), +) + +def printer(st, matches): + if False in matches: + print('Missed by one statement: %i, %s' % docs[matches.index(False)]) + else: + print('Full match:') + print(' ' + ', '.join('%i:%s' % (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) + +funcs, docs = zip(*constraintinfo) + +full, partial = [], [] + +for st in product( *([(False, True)] * 12) ): + truths = [bool(func(st)) for func in funcs] + matches = [s == t for s,t in zip(st, truths)] + mcount = sum(matches) + if mcount == 12: + full.append((st, matches)) + elif mcount == 11: + partial.append((st, matches)) + +for stm in full + partial: + printer(*stm) diff --git a/Task/Twelve-statements/REXX/twelve-statements-1.rexx b/Task/Twelve-statements/REXX/twelve-statements-1.rexx new file mode 100644 index 0000000000..c0e4105266 --- /dev/null +++ b/Task/Twelve-statements/REXX/twelve-statements-1.rexx @@ -0,0 +1,37 @@ +/*REXX program to solve the "Twelve Statement Puzzle". */ +q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ +m=0 + do pass=1 for 2 /*find the maximum number trues. */ + /*statement 1 is TRUE by fiat. */ + do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) + + do b=1 for q /*define the various bits. */ + @.b=substr(n,b,1) /*define a particular @ bit. */ + end /*b*/ + + if @.1 then if yeses(1,1) \==1 then iterate + if @.2 then if yeses(7,12) \==3 then iterate + if @.3 then if yeses(2,12,2) \==2 then iterate + if @.4 then if yeses(5,5) then if yeses(6,7) \==2 then iterate + if @.5 then if yeses(2,4) \==0 then iterate + if @.6 then if yeses(1,12,2) \==4 then iterate + if @.7 then if yeses(2,3) \==1 then iterate + if @.8 then if yeses(7,7) then if yeses(5,6) \==2 then iterate + if @.9 then if yeses(1,6) \==3 then iterate + if @.10 then if yeses(11,12) \==2 then iterate + if @.11 then if yeses(7,9) \==1 then iterate + if @.12 then if yeses(1,11) \==4 then iterate + _=yeses(1,12) + if pass==1 then do; m=max(m,_); iterate; end + else if _\==m then iterate + + do j=1 for q; _=substr(n,j,1) + if _ then say @stmt right(j,2) " is " word('false true',1+_) + end /*tell*/ + end /*e*/ + end /*pass*/ +exit /*stick a fork in it, we're done.*/ +/*----------------------------------YESES subroutine--------------------*/ +yeses: parse arg L,H,B; #=0 + do i=L to H by word(B 1,1); #=#+@.i; end /*i*/ +return # diff --git a/Task/Twelve-statements/REXX/twelve-statements-2.rexx b/Task/Twelve-statements/REXX/twelve-statements-2.rexx new file mode 100644 index 0000000000..ca484e6a80 --- /dev/null +++ b/Task/Twelve-statements/REXX/twelve-statements-2.rexx @@ -0,0 +1,34 @@ +/*REXX program to solve the "Twelve Statement Puzzle". */ +q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ +m=0 + do pass=1 for 2 /*find the maximum number trues. */ + /*statement 1 is TRUE by fiat. */ + do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) + + do b=1 for q /*define the various bits. */ + @.b=substr(n,b,1) /*define a particular @ bit. */ + end /*b*/ + + if @.1 then if \ @.1 then iterate + if @.2 then if @.7+@.8+@.9+@.10+@.11+@.12 \==3 then iterate + if @.3 then if @.2+@.4+@.6+@.8+@.10+@.12 \==2 then iterate + if @.4 then if @.5 then if \(@.6 & @.7) then iterate + if @.5 then if @.2 | @.3 | @.4 then iterate + if @.6 then if @.1+@.3+@.5+@.7+@.9+@.11 \==4 then iterate + if @.7 then if \ (@.2 && @.3 ) then iterate + if @.8 then if @.7 then if \(@.5 & @.6) then iterate + if @.9 then if @.1+@.2+@.3+@.4+@.5+@.6 \==3 then iterate + if @.10 then if \ (@.11 & @.12) then iterate + if @.11 then if @.7+@.8+@.9 \==1 then iterate + _=@.1+@.2+@.3+@.4+@.5+@.6+@.7+@.8+@.9+@.10+@.11 + if @.12 then if _ \==4 then iterate + _=_+@.12 + if pass==1 then do; m=max(m,_); iterate; end + else if _\==m then iterate + + do j=1 for q + if @.j then say @stmt right(j,2) " is " word('false true',1+@.j) + end /*j*/ + end /*e*/ + end /*pass*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Twelve-statements/REXX/twelve-statements-3.rexx b/Task/Twelve-statements/REXX/twelve-statements-3.rexx new file mode 100644 index 0000000000..aded29d9cf --- /dev/null +++ b/Task/Twelve-statements/REXX/twelve-statements-3.rexx @@ -0,0 +1,30 @@ +/*REXX program to solve the "Twelve Statement Puzzle". */ +q=12; @stmt=right('statement',20) /*number of statements in puzzle.*/ +m=0 + do pass=1 for 2 /*find the maximum number trues. */ + /*statement 1 is TRUE by fiat. */ + do e=0 for 2**(q-1); n='1'right(x2b(d2x(e)), q-1, 0) + parse var n @1 2 @2 3 @3 4 @4 5 @5 6 @6 7 @7 8 @8 9 @9 10 @10 11 @11 12 @12 +/*¦¦¦ if @1 then if \ @1 then iterate ¦¦¦*/ + if @2 then if @7+@8+@9+@10+@11+@12 \==3 then iterate + if @3 then if @2+@4+@6+@8+@10+@12 \==2 then iterate + if @4 then if @5 then if \(@6 & @7) then iterate + if @5 then if @2 | @3 | @4 then iterate + if @6 then if @1+@3+@5+@7+@9+@11 \==4 then iterate + if @7 then if \ (@2 && @3 ) then iterate + if @8 then if @7 then if \(@5 & @6) then iterate + if @9 then if @1+@2+@3+@4+@5+@6 \==3 then iterate + if @10 then if \ (@11 & @12) then iterate + if @11 then if @7+@8+@9 \==1 then iterate + _=@1+@2+@3+@4+@5+@6+@7+@8+@9+@10+@11 /*shortcut*/ + if @12 then if _ \==4 then iterate + _=_+@12 + if pass==1 then do; m=max(m,_); iterate; end + else if _\==m then iterate + + do j=1 for q; _=substr(n,j,1) + if _ then say @stmt right(j,2) " is " word('false true',1+_) + end /*j*/ + end /*e*/ + end /*pass*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Twelve-statements/Ruby/twelve-statements.rb b/Task/Twelve-statements/Ruby/twelve-statements.rb new file mode 100644 index 0000000000..db17a0a0a4 --- /dev/null +++ b/Task/Twelve-statements/Ruby/twelve-statements.rb @@ -0,0 +1,30 @@ +constraints = [ + ->(st) { st.size == 12 }, + ->(st) { st[-6,6].count(true) == 3 }, + ->(st) { st.each_slice(2).map(&:last).count(true) == 2 }, + ->(st) { st[4] ? (st[5] & st[6]) : true }, + ->(st) { st[1..3].map(&:!).all? }, + ->(st) { st.each_slice(2).map(&:first).count(true) == 4 }, + ->(st) { st[1] ^ st[2] }, + ->(st) { st[6] ? (st[4] & st[5]) : true }, + ->(st) { st[0,6].count(true) == 3 }, + ->(st) { st[10] & st[11] }, + ->(st) { st[6..8].count(true) == 1 }, + ->(st) { st[0,11].count(true) == 4 }, +] + +Result = Struct.new(:truths, :consistency) + +results = [true, false].repeated_permutation(12).map do |truths| + Result.new(truths, constraints.zip(truths).map {|cn,truth| cn[truths] == truth }) +end + +puts "solution:", + results.find {|r| r.consistency.all? }.truths.inspect + +puts "near misses: " +near_misses = results.select {|r| r.consistency.count(false) == 1 } +near_misses.each do |r| + puts "missed by statement #{r.consistency.index(false) + 1}" + puts r.truths.inspect +end diff --git a/Task/Twelve-statements/Tcl/twelve-statements.tcl b/Task/Twelve-statements/Tcl/twelve-statements.tcl new file mode 100644 index 0000000000..8010ce83bd --- /dev/null +++ b/Task/Twelve-statements/Tcl/twelve-statements.tcl @@ -0,0 +1,73 @@ +package require Tcl 8.6 + +# Function to evaluate the truth of a statement +proc tcl::mathfunc::S {idx} { + upvar 1 state s + apply [lindex $s [expr {$idx - 1}]] $s +} +# Procedure to count the number of statements which are true +proc S+ args { + upvar 1 state state + tcl::mathop::+ {*}[lmap i $args {expr {S($i)}}] +} +# Turn a list of expressions into a list of lambda terms +proc lambdas items {lmap x $items {list state [list expr $x]}} + +# Find the truth assignment that produces consistency. And those that are +# near misses too. +proc findTruthMatch {statements} { + set n [llength $statements] + for {set i 0} {$i < 2**$n} {incr i} { + set state [split [format %0.*b $n $i] ""] + set truths [lmap f $statements {apply $f [lambdas $state]}] + set counteq [tcl::mathop::+ {*}[lmap s $state t $truths {expr { + $s == $t + }}]] + if {$counteq == $n} { + lappend exact $state + } elseif {$counteq == $n-1} { + set j 0 + foreach s $state t $truths { + incr j + if {$s != $t} { + lappend differ $state $j + break + } + } + } + } + return [list $exact $differ] +} + +# Rendering code +proc renderstate state { + return ([join [lmap s $state { + incr i + expr {$s ? "S($i)" : "\u00acS($i)"} + }] "\u22c0"]) +} + +# The statements, encoded as expressions +set statements { + {[llength $state] == 12} + {[S+ 7 8 9 10 11 12] == 3} + {[S+ 2 4 6 8 10 12] == 2} + {S(5) ? S(6) && S(7) : 1} + {[S+ 2 3 4] == 0} + {[S+ 1 3 5 7 9 11] == 4} + {S(2) != S(3)} + {S(7) ? S(5) && S(6) : 1} + {[S+ 1 2 3 4 5 6] == 3} + {S(11) && S(12)} + {[S+ 7 8 9] == 1} + {[S+ 1 2 3 4 5 6 7 8 9 10 11] == 4} +} +# Find the truth assignment(s) that give consistency +lassign [findTruthMatch [lambdas $statements]] exact differ +# Print the results +foreach state $exact { + puts "exact match\t[renderstate $state ]" +} +foreach {state j} $differ { + puts "almost found\t[renderstate $state] \u21d2 [expr {[lindex $state $j-1]?"\u00ac":{}}]S($j)" +} diff --git a/Task/URL-decoding/0DESCRIPTION b/Task/URL-decoding/0DESCRIPTION new file mode 100644 index 0000000000..1f5a9b3304 --- /dev/null +++ b/Task/URL-decoding/0DESCRIPTION @@ -0,0 +1,5 @@ +This task (the reverse of [[URL encoding]]) is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. + +'''Example''' + +The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". diff --git a/Task/URL-decoding/1META.yaml b/Task/URL-decoding/1META.yaml new file mode 100644 index 0000000000..12b5b405fb --- /dev/null +++ b/Task/URL-decoding/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- String manipulation diff --git a/Task/URL-decoding/AWK/url-decoding.awk b/Task/URL-decoding/AWK/url-decoding.awk new file mode 100644 index 0000000000..cc7efbb2ec --- /dev/null +++ b/Task/URL-decoding/AWK/url-decoding.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -f URL_DECODING.AWK +BEGIN { + str = "http%3A%2F%2Ffoo%20bar%2F" # "http://foo bar/" + printf("%s\n",str) + while (match(str,/%/)) { + L = substr(str,1,RSTART-1) # chars to left of "%" + M = substr(str,RSTART+1,2) # 2 chars to right of "%" + R = substr(str,RSTART+3) # chars to right of "%xx" + str = sprintf("%s%c%s",L,hex2dec(M),R) + } + printf("%s\n",str) + exit(0) +} +function hex2dec(s, num) { + num = index("0123456789ABCDEF",toupper(substr(s,length(s)))) - 1 + sub(/.$/,"",s) + return num + (length(s) ? 16*hex2dec(s) : 0) +} diff --git a/Task/URL-decoding/Ada/url-decoding.ada b/Task/URL-decoding/Ada/url-decoding.ada new file mode 100644 index 0000000000..b0c74d4009 --- /dev/null +++ b/Task/URL-decoding/Ada/url-decoding.ada @@ -0,0 +1,7 @@ +with AWS.URL; +with Ada.Text_IO; use Ada.Text_IO; +procedure Decode is + Encoded : constant String := "http%3A%2F%2Ffoo%20bar%2F"; +begin + Put_Line (AWS.URL.Decode (Encoded)); +end Decode; diff --git a/Task/URL-decoding/AutoHotkey/url-decoding.ahk b/Task/URL-decoding/AutoHotkey/url-decoding.ahk new file mode 100644 index 0000000000..8249129e62 --- /dev/null +++ b/Task/URL-decoding/AutoHotkey/url-decoding.ahk @@ -0,0 +1,13 @@ +encURL := "http%3A%2F%2Ffoo%20bar%2F" +SetFormat, Integer, hex +Loop Parse, encURL + If A_LoopField = `% + reading := 2, read := "" + else if reading + { + read .= A_LoopField, --reading + if not reading + out .= Chr("0x" . read) + } + else out .= A_LoopField +MsgBox % out ; http://foo bar/ diff --git a/Task/URL-decoding/BBC-BASIC/url-decoding.bbc b/Task/URL-decoding/BBC-BASIC/url-decoding.bbc new file mode 100644 index 0000000000..70b55a33f3 --- /dev/null +++ b/Task/URL-decoding/BBC-BASIC/url-decoding.bbc @@ -0,0 +1,22 @@ + PRINT FNurldecode("http%3A%2F%2Ffoo%20bar%2F") + END + + DEF FNurldecode(url$) + LOCAL i% + REPEAT + i% = INSTR(url$, "%", i%+1) + IF i% THEN + url$ = LEFT$(url$,i%-1) + \ + \ CHR$EVAL("&"+FNupper(MID$(url$,i%+1,2))) + \ + \ MID$(url$,i%+3) + ENDIF + UNTIL i% = 0 + = url$ + + DEF FNupper(A$) + LOCAL A%,C% + FOR A% = 1 TO LEN(A$) + C% = ASCMID$(A$,A%) + IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32) + NEXT + = A$ diff --git a/Task/URL-decoding/Bracmat/url-decoding.bracmat b/Task/URL-decoding/Bracmat/url-decoding.bracmat new file mode 100644 index 0000000000..7ed3e86a98 --- /dev/null +++ b/Task/URL-decoding/Bracmat/url-decoding.bracmat @@ -0,0 +1,11 @@ +( ( decode + = decoded hexcode notencoded + . :?decoded + & whl + ' ( @(!arg:?notencoded "%" (% %:?hexcode) ?arg) + & !decoded !notencoded chr$(x2d$!hexcode):?decoded + ) + & str$(!decoded !arg) + ) + & out$(decode$http%3A%2F%2Ffoo%20bar%2F) +); diff --git a/Task/URL-decoding/C++/url-decoding.cpp b/Task/URL-decoding/C++/url-decoding.cpp new file mode 100644 index 0000000000..f58679c631 --- /dev/null +++ b/Task/URL-decoding/C++/url-decoding.cpp @@ -0,0 +1,11 @@ +#include +#include "Poco/URI.h" +#include + +int main( ) { + std::string encoded( "http%3A%2F%2Ffoo%20bar%2F" ) ; + std::string decoded ; + Poco::URI::decode ( encoded , decoded ) ; + std::cout << encoded << " is decoded: " << decoded << " !" << std::endl ; + return 0 ; +} diff --git a/Task/URL-decoding/C-sharp/url-decoding.cs b/Task/URL-decoding/C-sharp/url-decoding.cs new file mode 100644 index 0000000000..d0fed253b1 --- /dev/null +++ b/Task/URL-decoding/C-sharp/url-decoding.cs @@ -0,0 +1,17 @@ +using System; + +namespace URLEncode +{ + internal class Program + { + private static void Main(string[] args) + { + Console.WriteLine(Decode("http%3A%2F%2Ffoo%20bar%2F")); + } + + private static string Decode(string uri) + { + return Uri.UnescapeDataString(uri); + } + } +} diff --git a/Task/URL-decoding/C/url-decoding.c b/Task/URL-decoding/C/url-decoding.c new file mode 100644 index 0000000000..4f79285e26 --- /dev/null +++ b/Task/URL-decoding/C/url-decoding.c @@ -0,0 +1,40 @@ +#include +#include + +inline int ishex(int x) +{ + return (x >= '0' && x <= '9') || + (x >= 'a' && x <= 'f') || + (x >= 'A' && x <= 'F'); +} + +int decode(const char *s, char *dec) +{ + char *o; + const char *end = s + strlen(s); + int c; + + for (o = dec; s <= end; o++) { + c = *s++; + if (c == '+') c = ' '; + else if (c == '%' && ( !ishex(*s++) || + !ishex(*s++) || + !sscanf(s - 2, "%2x", &c))) + return -1; + + if (dec) *o = c; + } + + return o - dec; +} + +int main() +{ + const char *url = "http%3A%2F%2ffoo+bar%2fabcd"; + char out[sizeof(url)]; + + printf("length: %d\n", decode(url, 0)); + puts(decode(url, out) < 0 ? "bad string" : out); + + return 0; +} diff --git a/Task/URL-decoding/Clojure/url-decoding.clj b/Task/URL-decoding/Clojure/url-decoding.clj new file mode 100644 index 0000000000..961641ac80 --- /dev/null +++ b/Task/URL-decoding/Clojure/url-decoding.clj @@ -0,0 +1 @@ +(java.net.URLDecoder/decode "http%3A%2F%2Ffoo%20bar%2F") diff --git a/Task/URL-decoding/CoffeeScript/url-decoding-1.coffeescript b/Task/URL-decoding/CoffeeScript/url-decoding-1.coffeescript new file mode 100644 index 0000000000..5b01609cae --- /dev/null +++ b/Task/URL-decoding/CoffeeScript/url-decoding-1.coffeescript @@ -0,0 +1 @@ +console.log decodeURIComponent "http%3A%2F%2Ffoo%20bar%2F?name=Foo%20Barson" diff --git a/Task/URL-decoding/CoffeeScript/url-decoding-2.coffeescript b/Task/URL-decoding/CoffeeScript/url-decoding-2.coffeescript new file mode 100644 index 0000000000..5c6c8a77b4 --- /dev/null +++ b/Task/URL-decoding/CoffeeScript/url-decoding-2.coffeescript @@ -0,0 +1,2 @@ +> coffee foo.coffee +http://foo bar/?name=Foo Barson diff --git a/Task/URL-decoding/D/url-decoding.d b/Task/URL-decoding/D/url-decoding.d new file mode 100644 index 0000000000..e1186efabb --- /dev/null +++ b/Task/URL-decoding/D/url-decoding.d @@ -0,0 +1,5 @@ +import std.stdio, std.uri; + +void main() { + writeln(decodeComponent("http%3A%2F%2Ffoo%20bar%2F")); +} diff --git a/Task/URL-decoding/Delphi/url-decoding.delphi b/Task/URL-decoding/Delphi/url-decoding.delphi new file mode 100644 index 0000000000..209d5aa3fa --- /dev/null +++ b/Task/URL-decoding/Delphi/url-decoding.delphi @@ -0,0 +1,9 @@ +program URLEncoding; + +{$APPTYPE CONSOLE} + +uses IdURI; + +begin + Writeln(TIdURI.URLDecode('http%3A%2F%2Ffoo%20bar%2F')); +end. diff --git a/Task/URL-decoding/Go/url-decoding.go b/Task/URL-decoding/Go/url-decoding.go new file mode 100644 index 0000000000..6a1bb18aa1 --- /dev/null +++ b/Task/URL-decoding/Go/url-decoding.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "net/url" +) + +const escaped = "http%3A%2F%2Ffoo%20bar%2F" + +func main() { + if u, err := url.QueryUnescape(escaped); err == nil { + fmt.Println(u) + } else { + fmt.Println(err) + } +} diff --git a/Task/URL-decoding/Groovy/url-decoding.groovy b/Task/URL-decoding/Groovy/url-decoding.groovy new file mode 100644 index 0000000000..7f3931715c --- /dev/null +++ b/Task/URL-decoding/Groovy/url-decoding.groovy @@ -0,0 +1 @@ +assert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http://foo bar/' diff --git a/Task/URL-decoding/Icon/url-decoding.icon b/Task/URL-decoding/Icon/url-decoding.icon new file mode 100644 index 0000000000..462f93d829 --- /dev/null +++ b/Task/URL-decoding/Icon/url-decoding.icon @@ -0,0 +1,22 @@ +link hexcvt + +procedure main() +ue := "http%3A%2F%2Ffoo%20bar%2F" +ud := decodeURL(ue) | stop("Improperly encoded string ",image(ue)) +write("encoded = ",image(ue)) +write("decoded = ",image(ue)) +end + +procedure decodeURL(s) #: decode URL/URI encoded data +static de +initial { # build lookup table for everything + de := table() + every de[hexstring(ord(c := !string(&ascii)),2)] := c + } + +c := "" +s ? until pos(0) do # decode every %xx or fail + c ||:= if ="%" then \de[move(2)] | fail + else move(1) +return c +end diff --git a/Task/URL-decoding/J/url-decoding-1.j b/Task/URL-decoding/J/url-decoding-1.j new file mode 100644 index 0000000000..598749f6c0 --- /dev/null +++ b/Task/URL-decoding/J/url-decoding-1.j @@ -0,0 +1,2 @@ +require'strings convert' +urldecode=: rplc&(;"_1&a."2(,:tolower)'%',.hfd i.#a.) diff --git a/Task/URL-decoding/J/url-decoding-2.j b/Task/URL-decoding/J/url-decoding-2.j new file mode 100644 index 0000000000..2b02df0798 --- /dev/null +++ b/Task/URL-decoding/J/url-decoding-2.j @@ -0,0 +1,2 @@ + urldecode 'http%3A%2F%2Ffoo%20bar%2F' +http://foo bar/ diff --git a/Task/URL-decoding/J/url-decoding-3.j b/Task/URL-decoding/J/url-decoding-3.j new file mode 100644 index 0000000000..e82a0b3acc --- /dev/null +++ b/Task/URL-decoding/J/url-decoding-3.j @@ -0,0 +1 @@ +urldecode=: rplc&(~.,/;"_1&a."2(,:tolower)'%',.hfd i.#a.) diff --git a/Task/URL-decoding/Java/url-decoding.java b/Task/URL-decoding/Java/url-decoding.java new file mode 100644 index 0000000000..8956899e6a --- /dev/null +++ b/Task/URL-decoding/Java/url-decoding.java @@ -0,0 +1,12 @@ +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; + +public class Main +{ + public static void main(String[] args) throws UnsupportedEncodingException + { + String encoded = "http%3A%2F%2Ffoo%20bar%2F"; + String normal = URLDecoder.decode(encoded, "utf-8"); + System.out.println(normal); + } +} diff --git a/Task/URL-decoding/JavaScript/url-decoding.js b/Task/URL-decoding/JavaScript/url-decoding.js new file mode 100644 index 0000000000..701a9dd5d6 --- /dev/null +++ b/Task/URL-decoding/JavaScript/url-decoding.js @@ -0,0 +1 @@ +decodeURIComponent("http%3A%2F%2Ffoo%20bar%2F") diff --git a/Task/URL-decoding/Liberty-BASIC/url-decoding.liberty b/Task/URL-decoding/Liberty-BASIC/url-decoding.liberty new file mode 100644 index 0000000000..f7b609990f --- /dev/null +++ b/Task/URL-decoding/Liberty-BASIC/url-decoding.liberty @@ -0,0 +1,25 @@ + dim lookUp$( 256) + + for i =0 to 256 + lookUp$( i) ="%" +dechex$( i) + next i + + url$ ="http%3A%2F%2Ffoo%20bar%2F" + + print "Supplied URL '"; url$; "'" + print "As string '"; url2string$( url$); "'" + + end + +function url2string$( i$) + for j =1 to len( i$) + c$ =mid$( i$, j, 1) + if c$ ="%" then + nc$ =chr$( hexdec( mid$( i$, j +1, 2))) + url2string$ =url2string$ +nc$ + j =j +2 + else + url2string$ =url2string$ +c$ + end if + next j +end function diff --git a/Task/URL-decoding/Mathematica/url-decoding-1.math b/Task/URL-decoding/Mathematica/url-decoding-1.math new file mode 100644 index 0000000000..f827114b60 --- /dev/null +++ b/Task/URL-decoding/Mathematica/url-decoding-1.math @@ -0,0 +1,4 @@ +URLDecoding[url_] := + StringReplace[url, "%" ~~ x_ ~~ y_ :> FromDigits[x ~~ y, 16]] //. + StringExpression[x___, Longest[n__Integer], y___] :> + StringExpression[x, FromCharacterCode[{n}, "UTF8"], y] diff --git a/Task/URL-decoding/Mathematica/url-decoding-2.math b/Task/URL-decoding/Mathematica/url-decoding-2.math new file mode 100644 index 0000000000..2968d6a009 --- /dev/null +++ b/Task/URL-decoding/Mathematica/url-decoding-2.math @@ -0,0 +1 @@ +URLDecoding["http%3A%2F%2Ffoo%20bar%2F"] diff --git a/Task/URL-decoding/NetRexx/url-decoding.netrexx b/Task/URL-decoding/NetRexx/url-decoding.netrexx new file mode 100644 index 0000000000..5b046fc94d --- /dev/null +++ b/Task/URL-decoding/NetRexx/url-decoding.netrexx @@ -0,0 +1,43 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols nobinary + +url = [ - + 'http%3A%2F%2Ffoo%20bar%2F', - + 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E', - + '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' - + ] + +loop u_ = 0 to url.length - 1 + say url[u_] + say DecodeURL(url[u_]) + say + end u_ + +return + +method DecodeURL(arg) public static + + Parse arg encoded + decoded = '' + PCT = '%' + + loop label e_ while encoded.length() > 0 + parse encoded head (PCT) +1 code +2 tail + decoded = decoded || head + select + when code.strip('T').length() = 2 & code.datatype('X') then do + code = code.x2c() + decoded = decoded || code + end + when code.strip('T').length() \= 0 then do + decoded = decoded || PCT + tail = code || tail + end + otherwise do + nop + end + end + encoded = tail + end e_ + + return decoded diff --git a/Task/URL-decoding/OCaml/url-decoding-1.ocaml b/Task/URL-decoding/OCaml/url-decoding-1.ocaml new file mode 100644 index 0000000000..70834aae9f --- /dev/null +++ b/Task/URL-decoding/OCaml/url-decoding-1.ocaml @@ -0,0 +1,6 @@ +$ ocaml +# #use "topfind";; +# #require "netstring";; + +# Netencoding.Url.decode "http%3A%2F%2Ffoo%20bar%2F" ;; +- : string = "http://foo bar/" diff --git a/Task/URL-decoding/OCaml/url-decoding-2.ocaml b/Task/URL-decoding/OCaml/url-decoding-2.ocaml new file mode 100644 index 0000000000..1a603c9602 --- /dev/null +++ b/Task/URL-decoding/OCaml/url-decoding-2.ocaml @@ -0,0 +1,48 @@ +/* Rexx */ + +Do + X = 0 + url. = '' + X = X + 1; url.0 = X; url.X = 'http%3A%2F%2Ffoo%20bar%2F' + X = X + 1; url.0 = X; url.X = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' + X = X + 1; url.0 = X; url.X = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' + + Do u_ = 1 to url.0 + Say url.u_ + Say DecodeURL(url.u_) + Say + End u_ + + Return +End +Exit + +DecodeURL: +Procedure +Do + Parse Arg encoded + decoded = '' + PCT = '%' + + Do label e_ while encoded~length() > 0 + Parse Var encoded head (PCT) +1 code +2 tail + decoded = decoded || head + Select + when code~strip('T')~length() = 2 & code~datatype('X') then Do + code = code~x2c() + decoded = decoded || code + End + when code~strip('T')~length() \= 0 then Do + decoded = decoded || PCT + tail = code || tail + End + otherwise Do + Nop + End + End + encoded = tail + End e_ + + Return decoded +End +Exit diff --git a/Task/URL-decoding/Objeck/url-decoding.objeck b/Task/URL-decoding/Objeck/url-decoding.objeck new file mode 100644 index 0000000000..fe7b427bf8 --- /dev/null +++ b/Task/URL-decoding/Objeck/url-decoding.objeck @@ -0,0 +1,5 @@ +class UrlDecode { + function : Main(args : String[]) ~ Nil { + Net.UrlUtility->Decode("http%3A%2F%2Ffoo%20bar%2F")->PrintLine(); + } +} diff --git a/Task/URL-decoding/Objective-C/url-decoding.m b/Task/URL-decoding/Objective-C/url-decoding.m new file mode 100644 index 0000000000..28c943904d --- /dev/null +++ b/Task/URL-decoding/Objective-C/url-decoding.m @@ -0,0 +1,3 @@ +NSString *encoded = @"http%3A%2F%2Ffoo%20bar%2F"; +NSString *normal = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; +NSLog(@"%@", normal); diff --git a/Task/URL-decoding/PHP/url-decoding.php b/Task/URL-decoding/PHP/url-decoding.php new file mode 100644 index 0000000000..d45841e425 --- /dev/null +++ b/Task/URL-decoding/PHP/url-decoding.php @@ -0,0 +1,5 @@ + diff --git a/Task/URL-decoding/Perl-6/url-decoding-1.pl6 b/Task/URL-decoding/Perl-6/url-decoding-1.pl6 new file mode 100644 index 0000000000..ddb7620bd6 --- /dev/null +++ b/Task/URL-decoding/Perl-6/url-decoding-1.pl6 @@ -0,0 +1,5 @@ +my $url = "http%3A%2F%2Ffoo%20bar%2F"; + +say $url.subst: :g, + /'%'(<:hexdigit>**2)/, + -> ($ord ) { chr(:16(~$ord)) } diff --git a/Task/URL-decoding/Perl-6/url-decoding-2.pl6 b/Task/URL-decoding/Perl-6/url-decoding-2.pl6 new file mode 100644 index 0000000000..b487d951e3 --- /dev/null +++ b/Task/URL-decoding/Perl-6/url-decoding-2.pl6 @@ -0,0 +1,2 @@ +$url ~~ s:g[ '%' (<:hexdigit> ** 2) ] = chr :16(~$0); +say $url; diff --git a/Task/URL-decoding/Perl/url-decoding-1.pl b/Task/URL-decoding/Perl/url-decoding-1.pl new file mode 100644 index 0000000000..4eb8b0c5ff --- /dev/null +++ b/Task/URL-decoding/Perl/url-decoding-1.pl @@ -0,0 +1,8 @@ +sub urldecode { + my $s = shift; + $s =~ tr/\+/ /; + $s =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/eg; + return $s; +} + +print urldecode('http%3A%2F%2Ffoo+bar%2F')."\n"; diff --git a/Task/URL-decoding/Perl/url-decoding-2.pl b/Task/URL-decoding/Perl/url-decoding-2.pl new file mode 100644 index 0000000000..989bd26df2 --- /dev/null +++ b/Task/URL-decoding/Perl/url-decoding-2.pl @@ -0,0 +1,7 @@ +#!/usr/bin/perl -w +use strict ; +use URI::Escape ; + +my $encoded = "http%3A%2F%2Ffoo%20bar%2F" ; +my $unencoded = uri_unescape( $encoded ) ; +print "The unencoded string is $unencoded !\n" ; diff --git a/Task/URL-decoding/PureBasic/url-decoding.purebasic b/Task/URL-decoding/PureBasic/url-decoding.purebasic new file mode 100644 index 0000000000..8379afd025 --- /dev/null +++ b/Task/URL-decoding/PureBasic/url-decoding.purebasic @@ -0,0 +1,3 @@ +URL$ = URLDecoder("http%3A%2F%2Ffoo%20bar%2F") + +Debug URL$ ; http://foo bar/ diff --git a/Task/URL-decoding/Python/url-decoding.py b/Task/URL-decoding/Python/url-decoding.py new file mode 100644 index 0000000000..2a2f82e3b1 --- /dev/null +++ b/Task/URL-decoding/Python/url-decoding.py @@ -0,0 +1,2 @@ +import urllib +print urllib.unquote("http%3A%2F%2Ffoo%20bar%2F") diff --git a/Task/URL-decoding/REXX/url-decoding-1.rexx b/Task/URL-decoding/REXX/url-decoding-1.rexx new file mode 100644 index 0000000000..9ddfb45761 --- /dev/null +++ b/Task/URL-decoding/REXX/url-decoding-1.rexx @@ -0,0 +1,48 @@ +/* Rexx */ + +Do + X = 0 + url. = '' + X = X + 1; url.0 = X; url.X = 'http%3A%2F%2Ffoo%20bar%2F' + X = X + 1; url.0 = X; url.X = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' + X = X + 1; url.0 = X; url.X = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' + + Do u_ = 1 to url.0 + Say url.u_ + Say DecodeURL(url.u_) + Say + End u_ + + Return +End +Exit + +DecodeURL: +Procedure +Do + Parse Arg encoded + decoded = '' + PCT = '%' + + Do while length(encoded) > 0 + Parse Var encoded head (PCT) +1 code +2 tail + decoded = decoded || head + Select + When length(strip(code, 'T')) = 2 & datatype(code, 'X') then Do + code = x2c(code) + decoded = decoded || code + End + When length(strip(code, 'T')) \= 0 then Do + decoded = decoded || PCT + tail = code || tail + End + Otherwise Do + Nop + End + End + encoded = tail + End + + Return decoded +End +Exit diff --git a/Task/URL-decoding/REXX/url-decoding-2.rexx b/Task/URL-decoding/REXX/url-decoding-2.rexx new file mode 100644 index 0000000000..9cf3204b6e --- /dev/null +++ b/Task/URL-decoding/REXX/url-decoding-2.rexx @@ -0,0 +1,32 @@ +/*REXX pgm convert an URL─encoded string ──► its original unencoded form*/ +url.1 = 'http%3A%2F%2Ffoo%20bar%2F' +url.2 = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' +url.3 = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' +URLs=3 + do j=1 for URLs + say url.j + say decodeURL(url.j) + say + end /*j*/ +exit +/*──────────────────────────────────DECODEURL subroutine────────────────*/ +decodeURL: procedure; parse arg encoded; decoded='' +encoded=translate(encoded,,'+') /*special case for encoded blank.*/ + + do while length(encoded)\==0 + parse var encoded head '%' +1 code +2 tail + decoded=decoded || head + + select + when length(strip(code,'T'))==2 &, + datatype(code,'X') then decoded=decoded || x2c(code) + when length(strip(code,'T'))\==0 then do + decoded=decoded'%' + tail=code || tail + end + otherwise nop + end /*select*/ + encoded=tail + end /*while*/ + +return decoded diff --git a/Task/URL-decoding/REXX/url-decoding-3.rexx b/Task/URL-decoding/REXX/url-decoding-3.rexx new file mode 100644 index 0000000000..be9b40dcc7 --- /dev/null +++ b/Task/URL-decoding/REXX/url-decoding-3.rexx @@ -0,0 +1,21 @@ +/*REXX pgm convert an URL─encoded string ──► its original unencoded form*/ +url.1 = 'http%3A%2F%2Ffoo%20bar%2F' +url.2 = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' +url.3 = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' +URLs=3 + do j=1 for URLs; say + say url.j + say URLdecode(url.j) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────URLDECODE subroutine────────────────*/ +URLdecode: procedure; parse arg yyy /*get encoded URL from arg list. */ +yyy=translate(yyy,,'+') /*special case for encoded blank.*/ +URL='' + do until yyy='' + parse var yyy plain '%' +1 code +2 yyy + URL=URL || plain + if datatype(code,'X') then URL=URL || x2c(code) + else URL=URL'%'code + end /*until*/ +return URL diff --git a/Task/URL-decoding/Racket/url-decoding.rkt b/Task/URL-decoding/Racket/url-decoding.rkt new file mode 100644 index 0000000000..19e7eb6a4b --- /dev/null +++ b/Task/URL-decoding/Racket/url-decoding.rkt @@ -0,0 +1,3 @@ +#lang racket +(require net/uri-codec) +(uri-decode "http%3A%2F%2Ffoo%20bar%2F") diff --git a/Task/URL-decoding/Retro/url-decoding.retro b/Task/URL-decoding/Retro/url-decoding.retro new file mode 100644 index 0000000000..c5c6acd3ee --- /dev/null +++ b/Task/URL-decoding/Retro/url-decoding.retro @@ -0,0 +1,16 @@ +create buffer 32000 allot + +{{ + create bit 5 allot + : extract ( $c-$a ) drop @+ bit ! @+ bit 1+ ! bit ; + : render ( $c-$n ) + dup '+ = [ drop 32 ] ifTrue + dup 13 = [ drop 32 ] ifTrue + dup 10 = [ drop 32 ] ifTrue + dup '% = [ extract hex toNumber decimal ] ifTrue ; + : ( $-$ ) repeat @+ 0; render ^buffer'add again ; +---reveal--- + : decode ( $- ) buffer ^buffer'set drop ; +}} + +"http%3A%2F%2Ffoo%20bar%2F" decode buffer puts diff --git a/Task/URL-decoding/Ruby/url-decoding-1.rb b/Task/URL-decoding/Ruby/url-decoding-1.rb new file mode 100644 index 0000000000..4582107167 --- /dev/null +++ b/Task/URL-decoding/Ruby/url-decoding-1.rb @@ -0,0 +1,3 @@ +require 'cgi' +puts CGI.unescape("http%3A%2F%2Ffoo%20bar%2F") +# => "http://foo bar/" diff --git a/Task/URL-decoding/Ruby/url-decoding-2.rb b/Task/URL-decoding/Ruby/url-decoding-2.rb new file mode 100644 index 0000000000..0997da9c6c --- /dev/null +++ b/Task/URL-decoding/Ruby/url-decoding-2.rb @@ -0,0 +1,3 @@ +require 'uri' +puts URI.decode_www_form_component("http%3A%2F%2Ffoo%20bar%2F") +# => "http://foo bar/" diff --git a/Task/URL-decoding/Scala/url-decoding.scala b/Task/URL-decoding/Scala/url-decoding.scala new file mode 100644 index 0000000000..18f7885ba9 --- /dev/null +++ b/Task/URL-decoding/Scala/url-decoding.scala @@ -0,0 +1,4 @@ +import java.net._ +val encoded="http%3A%2F%2Ffoo%20bar%2F" +val decoded=URLDecoder.decode(encoded, "UTF-8") +println(decoded) // -> http://foo bar/ diff --git a/Task/URL-decoding/Seed7/url-decoding.seed7 b/Task/URL-decoding/Seed7/url-decoding.seed7 new file mode 100644 index 0000000000..b38b8f6651 --- /dev/null +++ b/Task/URL-decoding/Seed7/url-decoding.seed7 @@ -0,0 +1,8 @@ +$ include "seed7_05.s7i"; + include "encoding.s7i"; + +const proc: main is func + begin + writeln(fromPercentEncoded("http%3A%2F%2Ffoo%20bar%2F")); + writeln(fromUrlEncoded("http%3A%2F%2Ffoo+bar%2F")); + end func; diff --git a/Task/URL-decoding/TUSCRIPT/url-decoding.tuscript b/Task/URL-decoding/TUSCRIPT/url-decoding.tuscript new file mode 100644 index 0000000000..5f844ebcae --- /dev/null +++ b/Task/URL-decoding/TUSCRIPT/url-decoding.tuscript @@ -0,0 +1,8 @@ +$$ MODE TUSCRIPT +url_encoded="http%3A%2F%2Ffoo%20bar%2F" +BUILD S_TABLE hex=":%><:><2<>2<%:" +hex=STRINGS (url_encoded,hex), hex=SPLIT(hex) +hex=DECODE (hex,hex) +url_decoded=SUBSTITUTE(url_encoded,":%><2<>2<%:",0,0,hex) +PRINT "encoded: ", url_encoded +PRINT "decoded: ", url_decoded diff --git a/Task/URL-decoding/Tcl/url-decoding-1.tcl b/Task/URL-decoding/Tcl/url-decoding-1.tcl new file mode 100644 index 0000000000..87c16ae2d4 --- /dev/null +++ b/Task/URL-decoding/Tcl/url-decoding-1.tcl @@ -0,0 +1,7 @@ +proc urlDecode {str} { + set specialMap {"[" "%5B" "]" "%5D"} + set seqRE {%([0-9a-fA-F]{2})} + set replacement {[format "%c" [scan "\1" "%2x"]]} + set modStr [regsub -all $seqRE [string map $specialMap $str] $replacement] + return [encoding convertfrom utf-8 [subst -nobackslash -novariable $modStr]] +} diff --git a/Task/URL-decoding/Tcl/url-decoding-2.tcl b/Task/URL-decoding/Tcl/url-decoding-2.tcl new file mode 100644 index 0000000000..6718838ac4 --- /dev/null +++ b/Task/URL-decoding/Tcl/url-decoding-2.tcl @@ -0,0 +1 @@ +puts [urlDecode "http%3A%2F%2Ffoo%20bar%2F"] diff --git a/Task/URL-decoding/UNIX-Shell/url-decoding.sh b/Task/URL-decoding/UNIX-Shell/url-decoding.sh new file mode 100644 index 0000000000..e409dcff2b --- /dev/null +++ b/Task/URL-decoding/UNIX-Shell/url-decoding.sh @@ -0,0 +1,64 @@ +function urldecode +{ + typeset encoded=$1 decoded= rest= c= c1= c2= + typeset rest2= bug='rest2=${rest}' + + if [[ -z ${BASH_VERSION:-} ]]; then + typeset -i16 hex=0; typeset -i8 oct=0 + + # bug /usr/bin/sh HP-UX 11.00 + typeset _encoded='xyz%26xyz' + rest="${_encoded#?}" + c="${_encoded%%${rest}}" + if (( ${#c} != 1 )); then + typeset qm='????????????????????????????????????????????????????????????????????????' + typeset bug='(( ${#rest} > 0 )) && typeset -L${#rest} rest2="${qm}" || rest2=${rest}' + fi + fi + + rest="${encoded#?}" + eval ${bug} + c="${encoded%%${rest2}}" + encoded="${rest}" + + while [[ -n ${c} ]]; do + if [[ ${c} = '%' ]]; then + rest="${encoded#?}" + eval ${bug} + c1="${encoded%%${rest2}}" + encoded="${rest}" + + rest="${encoded#?}" + eval ${bug} + c2="${encoded%%${rest2}}" + encoded="${rest}" + + if [[ -z ${c1} || -z ${c2} ]]; then + c="%${c1}${c2}" + echo "WARNING: invalid % encoding: ${c}" >&2 + elif [[ -n ${BASH_VERSION:-} ]]; then + c="\\x${c1}${c2}" + c=$(\echo -e "${c}") + else + hex="16#${c1}${c2}"; oct=hex + c="\\0${oct#8\#}" + c=$(print -- "${c}") + fi + elif [[ ${c} = '+' ]]; then + c=' ' + fi + + decoded="${decoded}${c}" + + rest="${encoded#?}" + eval ${bug} + c="${encoded%%${rest2}}" + encoded="${rest}" + done + + if [[ -n ${BASH_VERSION:-} ]]; then + \echo -E "${decoded}" + else + print -r -- "${decoded}" + fi +} diff --git a/Task/URL-decoding/XPL0/url-decoding.xpl0 b/Task/URL-decoding/XPL0/url-decoding.xpl0 new file mode 100644 index 0000000000..d430f4057a --- /dev/null +++ b/Task/URL-decoding/XPL0/url-decoding.xpl0 @@ -0,0 +1,23 @@ +code Text=12; +string 0; \use zero-terminated strings + +func Decode(S0); \Decode URL string and return its address +char S0; +char S1(80); \BEWARE: very temporary string space returned +int C, N, I, J; +[I:= 0; J:= 0; +repeat C:= S0(I); I:= I+1; \get char + if C=^% then \convert hex to char + [C:= S0(I); I:= I+1; + if C>=^a then C:= C & ~$20; \convert to uppercase + N:= C - (if C<=^9 then ^0 else ^A-10); + C:= S0(I); I:= I+1; + if C>=^a then C:= C & ~$20; + C:= N*16 + C - (if C<=^9 then ^0 else ^A-10); + ]; + S1(J):= C; J:= J+1; \put char in output string +until C=0; +return S1; +]; + +Text(0, Decode("http%3A%2F%2Ffoo%20bar%2f")) diff --git a/Task/URL-encoding/0DESCRIPTION b/Task/URL-encoding/0DESCRIPTION new file mode 100644 index 0000000000..aa3594a31f --- /dev/null +++ b/Task/URL-encoding/0DESCRIPTION @@ -0,0 +1,31 @@ +The task is to provide a function or mechanism to convert a provided string into URL encoding representation. + +In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. + +For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: + +*ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). +*ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) +*ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) +*ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) +*ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) +*Extended characters with character codes of 128 decimal (80 hex) and above. + +'''Example''' + +The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". + +'''Variations''' + +* Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". +* Some standards give different rules: RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says that "-._~" should not be encoded. HTML 5, section [http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#url-encoded-form-data 4.10.22.5 URL-encoded form data], says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. + +'''Options''' + +It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. + +'''See also''' + +[[URL decoding]] + +[[Category:String manipulation]] diff --git a/Task/URL-encoding/AWK/url-encoding.awk b/Task/URL-encoding/AWK/url-encoding.awk new file mode 100644 index 0000000000..948e492447 --- /dev/null +++ b/Task/URL-encoding/AWK/url-encoding.awk @@ -0,0 +1,24 @@ +BEGIN { + for (i = 0; i <= 255; i++) + ord[sprintf("%c", i)] = i +} + +# Encode string with application/x-www-form-urlencoded escapes. +function escape(str, c, len, res) { + len = length(str) + res = "" + for (i = 1; i <= len; i++) { + c = substr(str, i, 1); + if (c ~ /[0-9A-Za-z]/) + #if (c ~ /[-._*0-9A-Za-z]/) + res = res c + #else if (c == " ") + # res = res "+" + else + res = res "%" sprintf("%02X", ord[c]) + } + return res +} + +# Escape every line of input. +{ print escape($0) } diff --git a/Task/URL-encoding/Ada/url-encoding.ada b/Task/URL-encoding/Ada/url-encoding.ada new file mode 100644 index 0000000000..2bda15f99d --- /dev/null +++ b/Task/URL-encoding/Ada/url-encoding.ada @@ -0,0 +1,7 @@ +with AWS.URL; +with Ada.Text_IO; use Ada.Text_IO; +procedure Encode is + Normal : constant String := "http://foo bar/"; +begin + Put_Line (AWS.URL.Encode (Normal)); +end Encode; diff --git a/Task/URL-encoding/AutoHotkey/url-encoding.ahk b/Task/URL-encoding/AutoHotkey/url-encoding.ahk new file mode 100644 index 0000000000..513d8aca28 --- /dev/null +++ b/Task/URL-encoding/AutoHotkey/url-encoding.ahk @@ -0,0 +1,7 @@ +rawURL = http://foo bar/ +SetFormat, Integer, Hex +Loop Parse, rawURL + If A_LoopField is not alnum ; not a-zA-Z0-9 + encURL .= "%" . SubStr(Asc(A_LoopField), 3) + else encURL .= A_LoopField +MsgBox % encURL diff --git a/Task/URL-encoding/BBC-BASIC/url-encoding.bbc b/Task/URL-encoding/BBC-BASIC/url-encoding.bbc new file mode 100644 index 0000000000..014a04d53b --- /dev/null +++ b/Task/URL-encoding/BBC-BASIC/url-encoding.bbc @@ -0,0 +1,13 @@ + PRINT FNurlencode("http://foo bar/") + END + + DEF FNurlencode(url$) + LOCAL c%, i% + WHILE i% < LEN(url$) + i% += 1 + c% = ASCMID$(url$, i%) + IF c%<&30 OR c%>&7A OR c%>&39 AND c%<&41 OR c%>&5A AND c%<&61 THEN + url$ = LEFT$(url$,i%-1) + "%" + RIGHT$("0"+STR$~c%,2) + MID$(url$,i%+1) + ENDIF + ENDWHILE + = url$ diff --git a/Task/URL-encoding/Bracmat/url-encoding.bracmat b/Task/URL-encoding/Bracmat/url-encoding.bracmat new file mode 100644 index 0000000000..301a8b79fe --- /dev/null +++ b/Task/URL-encoding/Bracmat/url-encoding.bracmat @@ -0,0 +1,41 @@ +( ( encode + = encoded exceptions octet string + . !arg:(?exceptions.?string) + & :?encoded + & @( !string + : ? + ( %@?octet ? + & !encoded + ( !octet + : ( ~<0:~>9 + | ~Z + | ~z + ) + | @(!exceptions:? !octet ?) + & !octet + | "%" d2x$(asc$!octet) + ) + : ?encoded + & ~ + ) + ) + | str$!encoded + ) + & out$"without exceptions: +" + & out$(encode$(."http://foo bar/")) + & out$(encode$(."mailto:Ivan")) + & out$(encode$(."Aim ")) + & out$(encode$(."mailto:Irma")) + & out$(encode$(."User ")) + & out$(encode$(."http://foo.bar.com/~user-name/_subdir/*~.html")) + & out$" +with RFC 3986 rules: +" + & out$(encode$("-._~"."http://foo bar/")) + & out$(encode$("-._~"."mailto:Ivan")) + & out$(encode$("-._~"."Aim ")) + & out$(encode$("-._~"."mailto:Irma")) + & out$(encode$("-._~"."User ")) + & out$(encode$("-._~"."http://foo.bar.com/~user-name/_subdir/*~.html")) +); diff --git a/Task/URL-encoding/C++/url-encoding.cpp b/Task/URL-encoding/C++/url-encoding.cpp new file mode 100644 index 0000000000..9280a1d863 --- /dev/null +++ b/Task/URL-encoding/C++/url-encoding.cpp @@ -0,0 +1,9 @@ +#include +#include + +int main( ) { + QByteArray text ( "http://foo bar/" ) ; + QByteArray encoded( text.toPercentEncoding( ) ) ; + std::cout << encoded.data( ) << '\n' ; + return 0 ; +} diff --git a/Task/URL-encoding/C-sharp/url-encoding.cs b/Task/URL-encoding/C-sharp/url-encoding.cs new file mode 100644 index 0000000000..e69805bedd --- /dev/null +++ b/Task/URL-encoding/C-sharp/url-encoding.cs @@ -0,0 +1,17 @@ +using System; + +namespace URLEncode +{ + internal class Program + { + private static void Main(string[] args) + { + Console.WriteLine(Encode("http://foo bar/")); + } + + private static string Encode(string uri) + { + return Uri.EscapeDataString(uri); + } + } +} diff --git a/Task/URL-encoding/C/url-encoding.c b/Task/URL-encoding/C/url-encoding.c new file mode 100644 index 0000000000..ef9cc19e1b --- /dev/null +++ b/Task/URL-encoding/C/url-encoding.c @@ -0,0 +1,34 @@ +#include +#include + +char rfc3986[256] = {0}; +char html5[256] = {0}; + +/* caller responsible for memory */ +void encode(unsigned char *s, char *enc, char *tb) +{ + for (; *s; s++) { + if (tb[*s]) sprintf(enc, "%c", tb[*s]); + else sprintf(enc, "%%%02X", *s); + while (*++enc); + } +} + +int main() +{ + unsigned char url[] = "http://foo bar/"; + char enc[sizeof(url) * 3]; + + int i; + for (i = 0; i < 256; i++) { + rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_' + ? i : 0; + html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_' + ? i : (i == ' ') ? '+' : 0; + } + + encode(url, enc, rfc3986); + puts(enc); + + return 0; +} diff --git a/Task/URL-encoding/D/url-encoding.d b/Task/URL-encoding/D/url-encoding.d new file mode 100644 index 0000000000..854046f968 --- /dev/null +++ b/Task/URL-encoding/D/url-encoding.d @@ -0,0 +1,5 @@ +import std.stdio, std.uri; + +void main() { + writeln(encodeComponent("http://foo bar/")); +} diff --git a/Task/URL-encoding/Go/url-encoding.go b/Task/URL-encoding/Go/url-encoding.go new file mode 100644 index 0000000000..3c74fdf55b --- /dev/null +++ b/Task/URL-encoding/Go/url-encoding.go @@ -0,0 +1,10 @@ +package main + +import ( + "fmt" + "net/url" +) + +func main() { + fmt.Println(url.QueryEscape("http://foo bar/")) +} diff --git a/Task/URL-encoding/Icon/url-encoding.icon b/Task/URL-encoding/Icon/url-encoding.icon new file mode 100644 index 0000000000..082044511f --- /dev/null +++ b/Task/URL-encoding/Icon/url-encoding.icon @@ -0,0 +1,18 @@ +link hexcvt + +procedure main() +write("text = ",image(u := "http://foo bar/")) +write("encoded = ",image(ue := encodeURL(u))) +end + +procedure encodeURL(s) #: encode data for inclusion in a URL/URI +static en +initial { # build lookup table for everything + en := table() + every en[c := !string(~(&digits++&letters))] := "%"||hexstring(ord(c),2) + every /en[c := !string(&cset)] := c + } + +every (c := "") ||:= en[!s] # re-encode everything +return c +end diff --git a/Task/URL-encoding/J/url-encoding-1.j b/Task/URL-encoding/J/url-encoding-1.j new file mode 100644 index 0000000000..88c0c86f57 --- /dev/null +++ b/Task/URL-encoding/J/url-encoding-1.j @@ -0,0 +1,2 @@ +require'strings convert' +urlencode=: rplc&((#~2|_1 47 57 64 90 96 122 I.i.@#)a.;"_1'%',.hfd i.#a.) diff --git a/Task/URL-encoding/J/url-encoding-2.j b/Task/URL-encoding/J/url-encoding-2.j new file mode 100644 index 0000000000..2529d981e7 --- /dev/null +++ b/Task/URL-encoding/J/url-encoding-2.j @@ -0,0 +1,2 @@ + urlencode 'http://foo bar/' +http%3A%2F%2Ffoo%20bar%2F diff --git a/Task/URL-encoding/Java/url-encoding.java b/Task/URL-encoding/Java/url-encoding.java new file mode 100644 index 0000000000..62697479bf --- /dev/null +++ b/Task/URL-encoding/Java/url-encoding.java @@ -0,0 +1,12 @@ +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +public class Main +{ + public static void main(String[] args) throws UnsupportedEncodingException + { + String normal = "http://foo bar/"; + String encoded = URLEncoder.encode(normal, "utf-8"); + System.out.println(encoded); + } +} diff --git a/Task/URL-encoding/JavaScript/url-encoding.js b/Task/URL-encoding/JavaScript/url-encoding.js new file mode 100644 index 0000000000..6c3cd2ae0d --- /dev/null +++ b/Task/URL-encoding/JavaScript/url-encoding.js @@ -0,0 +1,2 @@ +var normal = 'http://foo/bar/'; +var encoded = encodeURIComponent(normal); diff --git a/Task/URL-encoding/Liberty-BASIC/url-encoding.liberty b/Task/URL-encoding/Liberty-BASIC/url-encoding.liberty new file mode 100644 index 0000000000..5efae4e712 --- /dev/null +++ b/Task/URL-encoding/Liberty-BASIC/url-encoding.liberty @@ -0,0 +1,23 @@ + dim lookUp$( 256) + + for i =0 to 256 + lookUp$( i) ="%" +dechex$( i) + next i + + string$ ="http://foo bar/" + + print "Supplied string '"; string$; "'" + print "As URL '"; url$( string$); "'" + + end + +function url$( i$) + for j =1 to len( i$) + c$ =mid$( i$, j, 1) + if instr( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", c$) then + url$ =url$ +c$ + else + url$ =url$ +lookUp$( asc( c$)) + end if + next j +end function diff --git a/Task/URL-encoding/Mathematica/url-encoding-1.math b/Task/URL-encoding/Mathematica/url-encoding-1.math new file mode 100644 index 0000000000..1dae8b5de1 --- /dev/null +++ b/Task/URL-encoding/Mathematica/url-encoding-1.math @@ -0,0 +1,7 @@ +URLEncoding[url_] := + StringReplace[url, + x : Except[ + Join[CharacterRange["0", "9"], CharacterRange["a", "z"], + CharacterRange["A", "Z"]]] :> + StringJoin[("%" ~~ #) & /@ + IntegerString[ToCharacterCode[x, "UTF8"], 16]]] diff --git a/Task/URL-encoding/Mathematica/url-encoding-2.math b/Task/URL-encoding/Mathematica/url-encoding-2.math new file mode 100644 index 0000000000..4575be7d78 --- /dev/null +++ b/Task/URL-encoding/Mathematica/url-encoding-2.math @@ -0,0 +1 @@ +URLEncoding["http://foo bar/"] diff --git a/Task/URL-encoding/NetRexx/url-encoding.netrexx b/Task/URL-encoding/NetRexx/url-encoding.netrexx new file mode 100644 index 0000000000..04edf6e16f --- /dev/null +++ b/Task/URL-encoding/NetRexx/url-encoding.netrexx @@ -0,0 +1,64 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +/* -------------------------------------------------------------------------- */ + testcase() + say + say 'RFC3986' + testcase('RFC3986') + say + say 'HTML5' + testcase('HTML5') + say + return + +/* -------------------------------------------------------------------------- */ +method encode(url, varn) public static + + variation = varn.upper + opts = '' + opts['RFC3986'] = '-._~' + opts['HTML5'] = '-._*' + + rp = '' + loop while url.length > 0 + parse url tc +1 url + select + when tc.datatype('A') then do + rp = rp || tc + end + when tc == ' ' then do + if variation = 'HTML5' then + rp = rp || '+' + else + rp = rp || '%' || tc.c2x + end + otherwise do + if opts[variation].pos(tc) > 0 then do + rp = rp || tc + end + else do + rp = rp || '%' || tc.c2x + end + end + end + end + + return rp + +/* -------------------------------------------------------------------------- */ +method testcase(variation = '') public static + + url = [ - + 'http://foo bar/' - + , 'mailto:"Ivan Aim" ' - + , 'mailto:"Irma User" ' - + , 'http://foo.bar.com/~user-name/_subdir/*~.html' - + ] + + loop i_ = 0 to url.length - 1 + say url[i_] + say encode(url[i_], variation) + end i_ + + return diff --git a/Task/URL-encoding/OCaml/url-encoding.ocaml b/Task/URL-encoding/OCaml/url-encoding.ocaml new file mode 100644 index 0000000000..fdf5fefea1 --- /dev/null +++ b/Task/URL-encoding/OCaml/url-encoding.ocaml @@ -0,0 +1,6 @@ +$ ocaml +# #use "topfind";; +# #require "netstring";; + +# Netencoding.Url.encode "http://foo bar/" ;; +- : string = "http%3A%2F%2Ffoo+bar%2F" diff --git a/Task/URL-encoding/Objeck/url-encoding.objeck b/Task/URL-encoding/Objeck/url-encoding.objeck new file mode 100644 index 0000000000..b813aaf0e9 --- /dev/null +++ b/Task/URL-encoding/Objeck/url-encoding.objeck @@ -0,0 +1,10 @@ +use FastCgi; + +bundle Default { + class UrlEncode { + function : Main(args : String[]) ~ Nil { + url := "http://foo bar/"; + UrlUtility->Encode(url)->PrintLine(); + } + } +} diff --git a/Task/URL-encoding/Objective-C/url-encoding.m b/Task/URL-encoding/Objective-C/url-encoding.m new file mode 100644 index 0000000000..459f2e89fa --- /dev/null +++ b/Task/URL-encoding/Objective-C/url-encoding.m @@ -0,0 +1,3 @@ +NSString *normal = @"http://foo bar/"; +NSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; +NSLog(@"%@", encoded); diff --git a/Task/URL-encoding/PHP/url-encoding.php b/Task/URL-encoding/PHP/url-encoding.php new file mode 100644 index 0000000000..59f4785c54 --- /dev/null +++ b/Task/URL-encoding/PHP/url-encoding.php @@ -0,0 +1,4 @@ + diff --git a/Task/URL-encoding/Perl-6/url-encoding.pl6 b/Task/URL-encoding/Perl-6/url-encoding.pl6 new file mode 100644 index 0000000000..ecd9faec47 --- /dev/null +++ b/Task/URL-encoding/Perl-6/url-encoding.pl6 @@ -0,0 +1,3 @@ +my $url = 'http://foo bar/'; + +say $url.subst(/<-[ A..Z a..z 0..9 ]>/, *.ord.fmt("%%%02X"), :g); diff --git a/Task/URL-encoding/Perl/url-encoding-1.pl b/Task/URL-encoding/Perl/url-encoding-1.pl new file mode 100644 index 0000000000..f6f530eee0 --- /dev/null +++ b/Task/URL-encoding/Perl/url-encoding-1.pl @@ -0,0 +1,8 @@ +sub urlencode { + my $s = shift; + $s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg; + $s =~ tr/ /+/; + return $s; +} + +print urlencode('http://foo bar/')."\n"; diff --git a/Task/URL-encoding/Perl/url-encoding-2.pl b/Task/URL-encoding/Perl/url-encoding-2.pl new file mode 100644 index 0000000000..d8f7362134 --- /dev/null +++ b/Task/URL-encoding/Perl/url-encoding-2.pl @@ -0,0 +1,4 @@ +use URI::Escape; + +my $s = 'http://foo/bar/'; +print uri_escape($s); diff --git a/Task/URL-encoding/Perl/url-encoding-3.pl b/Task/URL-encoding/Perl/url-encoding-3.pl new file mode 100644 index 0000000000..b50b6da37e --- /dev/null +++ b/Task/URL-encoding/Perl/url-encoding-3.pl @@ -0,0 +1,6 @@ +use 5.10.0; +use CGI; + +my $s = 'http://foo/bar/'; +say $s = CGI::escape($s); +say $s = CGI::unescape($s); diff --git a/Task/URL-encoding/PicoLisp/url-encoding.l b/Task/URL-encoding/PicoLisp/url-encoding.l new file mode 100644 index 0000000000..07f73efe36 --- /dev/null +++ b/Task/URL-encoding/PicoLisp/url-encoding.l @@ -0,0 +1,8 @@ +(de urlEncodeTooMuch (Str) + (pack + (mapcar + '((C) + (if (or (>= "9" C "0") (>= "Z" (uppc C) "A")) + C + (list '% (hex (char C))) ) ) + (chop Str) ) ) ) diff --git a/Task/URL-encoding/PureBasic/url-encoding.purebasic b/Task/URL-encoding/PureBasic/url-encoding.purebasic new file mode 100644 index 0000000000..57d7072c67 --- /dev/null +++ b/Task/URL-encoding/PureBasic/url-encoding.purebasic @@ -0,0 +1 @@ +URL$ = URLEncoder("http://foo bar/") diff --git a/Task/URL-encoding/Python/url-encoding.py b/Task/URL-encoding/Python/url-encoding.py new file mode 100644 index 0000000000..7d677e5492 --- /dev/null +++ b/Task/URL-encoding/Python/url-encoding.py @@ -0,0 +1,3 @@ +import urllib +s = 'http://foo/bar/' +s = urllib.quote(s) diff --git a/Task/URL-encoding/REALbasic/url-encoding-1.realbasic b/Task/URL-encoding/REALbasic/url-encoding-1.realbasic new file mode 100644 index 0000000000..8524c88a11 --- /dev/null +++ b/Task/URL-encoding/REALbasic/url-encoding-1.realbasic @@ -0,0 +1,3 @@ + Dim URL As String = "http://foo bar/" + URL = EncodeURLComponent(URL) + Print(URL) diff --git a/Task/URL-encoding/REALbasic/url-encoding-2.realbasic b/Task/URL-encoding/REALbasic/url-encoding-2.realbasic new file mode 100644 index 0000000000..3e95fe7632 --- /dev/null +++ b/Task/URL-encoding/REALbasic/url-encoding-2.realbasic @@ -0,0 +1,13 @@ +Function URLEncode(URL As String, Exceptions As String = "") As String + For i As Integer = 0 To 255 + If InStr(Exceptions, Chr(i)) > 0 Then Continue For i + Dim char As String = Chr(127) + Right("00" + Hex(i), 2) + URL = ReplaceAll(URL, Chr(i), char) + If i = 47 Then i = 57 + If i = 64 Then i = 90 + If i = 96 Then i = 122 + If i = 126 Then i = 128 + Next + URL = ReplaceAll(URL, Chr(127), "%") + Return URL +End Function diff --git a/Task/URL-encoding/REXX/url-encoding-1.rexx b/Task/URL-encoding/REXX/url-encoding-1.rexx new file mode 100644 index 0000000000..eded0fda62 --- /dev/null +++ b/Task/URL-encoding/REXX/url-encoding-1.rexx @@ -0,0 +1,72 @@ +/* Rexx */ +do + call testcase + say + say RFC3986 + call testcase RFC3986 + say + say HTML5 + call testcase HTML5 + say + return +end +exit + +/* -------------------------------------------------------------------------- */ +encode: +procedure +do + parse arg url, varn . + parse upper var varn variation + drop RFC3986 HTML5 + opts. = '' + opts.RFC3986 = '-._~' + opts.HTML5 = '-._*' + + rp = '' + do while length(url) > 0 + parse var url tc +1 url + select + when datatype(tc, 'A') then do + rp = rp || tc + end + when tc == ' ' then do + if variation = HTML5 then + rp = rp || '+' + else + rp = rp || '%' || c2x(tc) + end + otherwise do + if pos(tc, opts.variation) > 0 then do + rp = rp || tc + end + else do + rp = rp || '%' || c2x(tc) + end + end + end + end + + return rp +end +exit + +/* -------------------------------------------------------------------------- */ +testcase: +procedure +do + parse arg variation + X = 0 + url. = '' + X = X + 1; url.0 = X; url.X = 'http://foo bar/' + X = X + 1; url.0 = X; url.X = 'mailto:"Ivan Aim" ' + X = X + 1; url.0 = X; url.X = 'mailto:"Irma User" ' + X = X + 1; url.0 = X; url.X = 'http://foo.bar.com/~user-name/_subdir/*~.html' + + do i_ = 1 to url.0 + say url.i_ + say encode(url.i_, variation) + end i_ + + return +end diff --git a/Task/URL-encoding/REXX/url-encoding-2.rexx b/Task/URL-encoding/REXX/url-encoding-2.rexx new file mode 100644 index 0000000000..346437b324 --- /dev/null +++ b/Task/URL-encoding/REXX/url-encoding-2.rexx @@ -0,0 +1,31 @@ +/*REXX pgm encodes an URL text, blanks──►+, preserves -._* and -._~ */ +url.1= 'http://foo bar/' +url.2= 'mailto:"Ivan Aim" ' +url.3= 'mailto:"Irma User" ' +url.4= 'http://foo.bar.com/~user-name/_subdir/*~.html' +URLs=4 + do j=1 for URLs; say + say url.j + say URLencode(url.j) + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────URENCODE subroutine─────────────────*/ +URLencode: procedure; parse arg yyy; t1= '-._~' ; skip=0 + t2= '-._*' ; z='' + + do k=1 for length(yyy); _=substr(yyy,k,1) /*pickoff 1char*/ + if skip\==0 then do /*skip t1 | t2?*/ + skip=skip-1 /*skip a char. */ + iterate + end + select + when datatype(_,'A') then z=z || _ /*alphanumeric?*/ + when _==' ' then z=z'+' /*is a blank ? */ + when substr(yyy,k,4)==t1 |, /*t1 or t2 ? */ + substr(yyy,k,4)==t2 then do; skip=3 /*skip 3 chars.*/ + z=z || substr(yyy,k,4) + end + otherwise z=z'%'c2x(_) /*special char.*/ + end /*select*/ + end /*k*/ +return z diff --git a/Task/URL-encoding/Racket/url-encoding.rkt b/Task/URL-encoding/Racket/url-encoding.rkt new file mode 100644 index 0000000000..667f2d4521 --- /dev/null +++ b/Task/URL-encoding/Racket/url-encoding.rkt @@ -0,0 +1,3 @@ +#lang racket +(require net/uri-codec) +(uri-encode "http://foo bar/") diff --git a/Task/URL-encoding/Ruby/url-encoding-1.rb b/Task/URL-encoding/Ruby/url-encoding-1.rb new file mode 100644 index 0000000000..8ef42219e1 --- /dev/null +++ b/Task/URL-encoding/Ruby/url-encoding-1.rb @@ -0,0 +1,3 @@ +require 'cgi' +puts CGI.escape("http://foo bar/").gsub("+", "%20") +# => "http%3A%2F%2Ffoo%20bar%2F" diff --git a/Task/URL-encoding/Ruby/url-encoding-2.rb b/Task/URL-encoding/Ruby/url-encoding-2.rb new file mode 100644 index 0000000000..476193b9de --- /dev/null +++ b/Task/URL-encoding/Ruby/url-encoding-2.rb @@ -0,0 +1,3 @@ +require 'uri' +puts URI.encode_www_form_component("http://foo bar/").gsub("+", "%20") +# => "http%3A%2F%2Ffoo%20bar%2F" diff --git a/Task/URL-encoding/Run-BASIC/url-encoding.run b/Task/URL-encoding/Run-BASIC/url-encoding.run new file mode 100644 index 0000000000..99b5f59d8a --- /dev/null +++ b/Task/URL-encoding/Run-BASIC/url-encoding.run @@ -0,0 +1,9 @@ +urlIn$ = "http://foo bar/" + +for i = 1 to len(urlIn$) + a$ = mid$(urlIn$,i,1) + if (a$ >= "0" and a$ <= "9") _ + or (a$ >= "A" and a$ <= "Z") _ + or (a$ >= "a" and a$ <= "z") then url$ = url$ + a$ else url$ = url$ + "%"+dechex$(asc(a$)) +next i +print urlIn$;" -> ";url$ diff --git a/Task/URL-encoding/Seed7/url-encoding.seed7 b/Task/URL-encoding/Seed7/url-encoding.seed7 new file mode 100644 index 0000000000..31fa7ec7ae --- /dev/null +++ b/Task/URL-encoding/Seed7/url-encoding.seed7 @@ -0,0 +1,8 @@ +$ include "seed7_05.s7i"; + include "encoding.s7i"; + +const proc: main is func + begin + writeln(toPercentEncoded("http://foo bar/")); + writeln(toUrlEncoded("http://foo bar/")); + end func; diff --git a/Task/URL-encoding/TUSCRIPT/url-encoding.tuscript b/Task/URL-encoding/TUSCRIPT/url-encoding.tuscript new file mode 100644 index 0000000000..ac405a3a5e --- /dev/null +++ b/Task/URL-encoding/TUSCRIPT/url-encoding.tuscript @@ -0,0 +1,10 @@ +$$ MODE TUSCRIPT +text="http://foo bar/" +BUILD S_TABLE spez_char="::>/: 0 )) && typeset -L${#rest} rest2="${qm}" || rest2=${rest}' + fi + fi + + rest="${decoded#?}" + eval ${bug} + c="${decoded%%${rest2}}" + decoded="${rest}" + + while [[ -n ${c} ]]; do + case ${c} in + [-a-zA-z0-9.]) + ;; + ' ') + c='+' + ;; + *) + c=$(printf "%%%02X" "'$c") + ;; + esac + + encoded="${encoded}${c}" + + rest="${decoded#?}" + eval ${bug} + c="${decoded%%${rest2}}" + decoded="${rest}" + done + + if [[ -n ${BASH_VERSION:-} ]]; then + \echo -E "${encoded}" + else + print -r -- "${encoded}" + fi +} diff --git a/Task/URL-encoding/XPL0/url-encoding.xpl0 b/Task/URL-encoding/XPL0/url-encoding.xpl0 new file mode 100644 index 0000000000..f001100227 --- /dev/null +++ b/Task/URL-encoding/XPL0/url-encoding.xpl0 @@ -0,0 +1,21 @@ +code Text=12; +string 0; \use zero-terminated strings + +func Encode(S0); \Encode URL string and return its address +char S0; +char HD, S1(80); \BEWARE: very temporary string space returned +int C, I, J; +[HD:= "0123456789ABCDEF"; \hex digits +I:= 0; J:= 0; +repeat C:= S0(I); I:= I+1; + if C>=^0 & C<=^9 ! C>=^A & C<=^Z ! C>=^a & C<=^z ! C=0 + then [S1(J):= C; J:= J+1] \simply pass char to S1 + else [S1(J):= ^%; J:= J+1; \encode char into S1 + S1(J):= HD(C>>4); J:= J+1; + S1(J):= HD(C&$0F); J:= J+1; + ]; +until C=0; +return S1; +]; + +Text(0, Encode("http://foo bar/")) diff --git a/Task/Unbias-a-random-generator/0DESCRIPTION b/Task/Unbias-a-random-generator/0DESCRIPTION new file mode 100644 index 0000000000..09e443f42b --- /dev/null +++ b/Task/Unbias-a-random-generator/0DESCRIPTION @@ -0,0 +1,8 @@ +Given a weighted one bit generator of random numbers where the probability of a one occuring, P_1, is not the same as P_0, the probability of a zero occuring, the probability of the occurrence of a one followed by a zero is P_1 × P_0. This is the same as the probability of a zero followed by a one: P_0 × P_1. + +'''Task Details''' +* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. +* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. +* For N over its range, generate and show counts of the outputs of randN and unbiased(randN). + +The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. diff --git a/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.ada b/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.ada new file mode 100644 index 0000000000..0558de0003 --- /dev/null +++ b/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.ada @@ -0,0 +1,51 @@ +with Ada.Text_IO; with Ada.Numerics.Discrete_Random; + +procedure Bias_Unbias is + + Modulus: constant Integer := 60; -- lcm of {3,4,5,6} + type M is mod Modulus; + package Rand is new Ada.Numerics.Discrete_Random(M); + Gen: Rand.Generator; + + subtype Bit is Integer range 0 .. 1; + + function Biased_Bit(Bias_Base: Integer) return Bit is + begin + if (Integer(Rand.Random(Gen))* Bias_Base) / Modulus > 0 then + return 0; + else + return 1; + end if; + end Biased_Bit; + + function Unbiased_Bit(Bias_Base: Integer) return Bit is + A, B: Bit := 0; + begin + while A = B loop + A := Biased_Bit(Bias_Base); + B := Biased_Bit(Bias_Base); + end loop; + return A; + end Unbiased_Bit; + + package FIO is new Ada.Text_IO.Float_IO(Float); + + Counter_B, Counter_U: Natural; + Number_Of_Samples: constant Natural := 10_000; + +begin + Rand.Reset(Gen); + Ada.Text_IO.Put_Line(" I Biased% UnBiased%"); + for I in 3 .. 6 loop + Counter_B := 0; + Counter_U := 0; + for J in 1 .. Number_Of_Samples loop + Counter_B := Counter_B + Biased_Bit(I); + Counter_U := Counter_U + Unbiased_Bit(I); + end loop; + Ada.Text_IO.Put(Integer'Image(I)); + FIO.Put(100.0 * Float(Counter_B) / Float(Number_Of_Samples), 5, 2, 0); + FIO.Put(100.0 * Float(Counter_U) / Float(Number_Of_Samples), 5, 2, 0); + Ada.Text_IO.New_Line; + end loop; +end Bias_Unbias; diff --git a/Task/Unbias-a-random-generator/AutoHotkey/unbias-a-random-generator.ahk b/Task/Unbias-a-random-generator/AutoHotkey/unbias-a-random-generator.ahk new file mode 100644 index 0000000000..a7e533312c --- /dev/null +++ b/Task/Unbias-a-random-generator/AutoHotkey/unbias-a-random-generator.ahk @@ -0,0 +1,15 @@ +Biased(){ + Random, q, 0, 4 + return q=4 +} +Unbiased(){ + Loop + If ((a := Biased()) != biased()) + return a +} +Loop 1000 + t .= biased(), t2 .= unbiased() +StringReplace, junk, t2, 1, , UseErrorLevel +MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000 +StringReplace, junk, t, 1, , UseErrorLevel +MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000 diff --git a/Task/Unbias-a-random-generator/BBC-BASIC/unbias-a-random-generator.bbc b/Task/Unbias-a-random-generator/BBC-BASIC/unbias-a-random-generator.bbc new file mode 100644 index 0000000000..09fb816621 --- /dev/null +++ b/Task/Unbias-a-random-generator/BBC-BASIC/unbias-a-random-generator.bbc @@ -0,0 +1,20 @@ + FOR N% = 3 TO 6 + biased% = 0 + unbiased% = 0 + FOR I% = 1 TO 10000 + IF FNrandN(N%) biased% += 1 + IF FNunbiased(N%) unbiased% += 1 + NEXT + PRINT "N = ";N% " : biased = "; biased%/100 "%, unbiased = "; unbiased%/100 "%" + NEXT + END + + DEF FNunbiased(N%) + LOCAL A%,B% + REPEAT + A% = FNrandN(N%) + B% = FNrandN(N%) + UNTIL A%<>B% + = A% + + DEF FNrandN(N%) = -(RND(N%) = 1) diff --git a/Task/Unbias-a-random-generator/C-sharp/unbias-a-random-generator.cs b/Task/Unbias-a-random-generator/C-sharp/unbias-a-random-generator.cs new file mode 100644 index 0000000000..22906ba232 --- /dev/null +++ b/Task/Unbias-a-random-generator/C-sharp/unbias-a-random-generator.cs @@ -0,0 +1,59 @@ +using System; + +namespace Unbias +{ + internal class Program + { + private static void Main(string[] args) + { + // Demonstrate. + for (int n = 3; n <= 6; n++) + { + int biasedZero = 0, biasedOne = 0, unbiasedZero = 0, unbiasedOne = 0; + for (int i = 0; i < 100000; i++) + { + if (randN(n)) + biasedOne++; + else + biasedZero++; + if (Unbiased(n)) + unbiasedOne++; + else + unbiasedZero++; + } + + Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0\t# of 1\t% of 0\t% of 1", n); + Console.WriteLine("Biased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}", + biasedZero, biasedOne, + biasedZero/1000, biasedOne/1000); + Console.WriteLine("Unbiased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}", + unbiasedZero, unbiasedOne, + unbiasedZero/1000, unbiasedOne/1000); + } + } + + private static bool Unbiased(int n) + { + bool flip1, flip2; + + /* Flip twice, and check if the values are the same. + * If so, flip again. Otherwise, return the value of the first flip. */ + + do + { + flip1 = randN(n); + flip2 = randN(n); + } while (flip1 == flip2); + + return flip1; + } + + private static readonly Random random = new Random(); + + private static bool randN(int n) + { + // Has an 1/n chance of returning 1. Otherwise it returns 0. + return random.Next(0, n) == 0; + } + } +} diff --git a/Task/Unbias-a-random-generator/C/unbias-a-random-generator.c b/Task/Unbias-a-random-generator/C/unbias-a-random-generator.c new file mode 100644 index 0000000000..80af4123ee --- /dev/null +++ b/Task/Unbias-a-random-generator/C/unbias-a-random-generator.c @@ -0,0 +1,32 @@ +#include +#include + +int biased(int bias) +{ + /* balance out the bins, being pedantic */ + int r, rand_max = RAND_MAX - (RAND_MAX % bias); + while ((r = rand()) > rand_max); + return r < rand_max / bias; +} + +int unbiased(int bias) +{ + int a; + while ((a = biased(bias)) == biased(bias)); + return a; +} + +int main() +{ + int b, n = 10000, cb, cu, i; + for (b = 3; b <= 6; b++) { + for (i = cb = cu = 0; i < n; i++) { + cb += biased(b); + cu += unbiased(b); + } + printf("bias %d: %5.3f%% vs %5.3f%%\n", b, + 100. * cb / n, 100. * cu / n); + } + + return 0; +} diff --git a/Task/Unbias-a-random-generator/Clojure/unbias-a-random-generator.clj b/Task/Unbias-a-random-generator/Clojure/unbias-a-random-generator.clj new file mode 100644 index 0000000000..b40eadbd59 --- /dev/null +++ b/Task/Unbias-a-random-generator/Clojure/unbias-a-random-generator.clj @@ -0,0 +1,17 @@ +(defn biased [n] + (if (< (rand 2) (/ n)) 0 1)) + +(defn unbiased [n] + (loop [a 0 b 0] + (if (= a b) + (recur (biased n) (biased n)) + a))) + +(for [n (range 3 7)] + [n + (double (/ (apply + (take 50000 (repeatedly #(biased n)))) 50000)) + (double (/ (apply + (take 50000 (repeatedly #(unbiased n)))) 50000))]) +([3 0.83292 0.50422] + [4 0.87684 0.5023] + [5 0.90122 0.49728] + [6 0.91526 0.5]) diff --git a/Task/Unbias-a-random-generator/CoffeeScript/unbias-a-random-generator.coffeescript b/Task/Unbias-a-random-generator/CoffeeScript/unbias-a-random-generator.coffeescript new file mode 100644 index 0000000000..455e788481 --- /dev/null +++ b/Task/Unbias-a-random-generator/CoffeeScript/unbias-a-random-generator.coffeescript @@ -0,0 +1,29 @@ +biased_rand_function = (n) -> + # return a function that returns 0/1 with + # 1 appearing only 1/Nth of the time + cap = 1/n + -> + if Math.random() < cap + 1 + else + 0 + +unbiased_function = (f) -> + -> + while true + [n1, n2] = [f(), f()] + return n1 if n1 + n2 == 1 + +stats = (label, f) -> + cnt = 0 + sample_size = 10000000 + for i in [1...sample_size] + cnt += 1 if f() == 1 + console.log "ratio of 1s: #{cnt / sample_size} [#{label}]" + +for n in [3..6] + console.log "\n---------- n = #{n}" + f_biased = biased_rand_function(n) + f_unbiased = unbiased_function f_biased + stats "biased", f_biased + stats "unbiased", f_unbiased diff --git a/Task/Unbias-a-random-generator/Common-Lisp/unbias-a-random-generator.lisp b/Task/Unbias-a-random-generator/Common-Lisp/unbias-a-random-generator.lisp new file mode 100644 index 0000000000..b52b690c5c --- /dev/null +++ b/Task/Unbias-a-random-generator/Common-Lisp/unbias-a-random-generator.lisp @@ -0,0 +1,11 @@ +(defun biased (n) (if (zerop (random n)) 0 1)) + +(defun unbiased (n) + (loop with x do + (if (/= (setf x (biased n)) (biased n)) + (return x)))) + +(loop for n from 3 to 6 do + (let ((u (loop repeat 10000 collect (unbiased n))) + (b (loop repeat 10000 collect (biased n)))) + (format t "~a: unbiased ~d biased ~d~%" n (count 0 u) (count 0 b)))) diff --git a/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d new file mode 100644 index 0000000000..3e9e249c28 --- /dev/null +++ b/Task/Unbias-a-random-generator/D/unbias-a-random-generator.d @@ -0,0 +1,22 @@ +import std.stdio, std.random, std.algorithm, std.range; + +bool biased(in int n) /*nothrow*/ { + return uniform(0.0, 1.0) < (1.0 / n); +} + +int unbiased(in int bias) /*nothrow*/ { + int a; + while ((a = biased(bias)) == biased(bias)) {} + return a; +} + +void main() { + alias reduce!q{a + b} sum; /**/ + enum int M = 500_000; + foreach (n; 3 .. 7) { + immutable a1 = sum(0, iota(M).map!(_=> biased(n))()), + a2 = sum(0, iota(M).map!(_=> unbiased(n))()); + writefln("%d: %2.3f%% %2.3f%%", n, + 100.0 * a1 / M, 100.0 * a2 / M); + } +} diff --git a/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.euphoria b/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.euphoria new file mode 100644 index 0000000000..bac017f5a4 --- /dev/null +++ b/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.euphoria @@ -0,0 +1,25 @@ +function randN(integer N) + return rand(N) = 1 +end function + +function unbiased(integer N) + integer a + while 1 do + a = randN(N) + if a != randN(N) then + return a + end if + end while +end function + +constant n = 10000 +integer cb, cu +for b = 3 to 6 do + cb = 0 + cu = 0 + for i = 1 to n do + cb += randN(b) + cu += unbiased(b) + end for + printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n}) +end for diff --git a/Task/Unbias-a-random-generator/Fortran/unbias-a-random-generator.f b/Task/Unbias-a-random-generator/Fortran/unbias-a-random-generator.f new file mode 100644 index 0000000000..1f721a3675 --- /dev/null +++ b/Task/Unbias-a-random-generator/Fortran/unbias-a-random-generator.f @@ -0,0 +1,49 @@ +program Bias_Unbias + implicit none + + integer, parameter :: samples = 1000000 + integer :: i, j + integer :: c1, c2, rand + + do i = 3, 6 + c1 = 0 + c2 = 0 + do j = 1, samples + rand = bias(i) + if (rand == 1) c1 = c1 + 1 + rand = unbias(i) + if (rand == 1) c2 = c2 + 1 + end do + write(*, "(i2,a,f8.3,a,f8.3,a)") i, ":", real(c1) * 100.0 / real(samples), & + "%", real(c2) * 100.0 / real(samples), "%" + end do + +contains + +function bias(n) + integer :: bias + integer, intent(in) :: n + real :: r + + call random_number(r) + if (r > 1 / real(n)) then + bias = 0 + else + bias = 1 + end if +end function + +function unbias(n) + integer :: unbias + integer, intent(in) :: n + integer :: a, b + + do + a = bias(n) + b = bias(n) + if (a /= b) exit + end do + unbias = a +end function + +end program diff --git a/Task/Unbias-a-random-generator/GAP/unbias-a-random-generator.gap b/Task/Unbias-a-random-generator/GAP/unbias-a-random-generator.gap new file mode 100644 index 0000000000..3d00a90d6a --- /dev/null +++ b/Task/Unbias-a-random-generator/GAP/unbias-a-random-generator.gap @@ -0,0 +1,38 @@ +RandNGen := function(n) + local v, rand; + v := [1 .. n - 1]*0; + Add(v, 1); + rand := function() + return Random(v); + end; + return rand; +end; + +UnbiasedGen := function(rand) + local unbiased; + unbiased := function() + local a, b; + while true do + a := rand(); + b := rand(); + if a <> b then + break; + fi; + od; + return a; + end; + return unbiased; +end; + +range := [2 .. 6]; +v := List(range, RandNGen); +w := List(v, UnbiasedGen); +apply := gen -> Sum([1 .. 1000000], n -> gen()); + +# Some tests (2 is added as a witness, since in this case RandN is already unbiased) +PrintArray(TransposedMat([range, List(v, apply), List(w, apply)])); +# [ [ 2, 499991, 499041 ], +# [ 3, 333310, 500044 ], +# [ 4, 249851, 500663 ], +# [ 5, 200532, 500448 ], +# [ 6, 166746, 499859 ] ] diff --git a/Task/Unbias-a-random-generator/Go/unbias-a-random-generator.go b/Task/Unbias-a-random-generator/Go/unbias-a-random-generator.go new file mode 100644 index 0000000000..7279ce43d9 --- /dev/null +++ b/Task/Unbias-a-random-generator/Go/unbias-a-random-generator.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "math/rand" +) + +const samples = 1e6 + +func main() { + fmt.Println("Generator 1 count 0 count % 1 count") + for n := 3; n <= 6; n++ { + // function randN, per task description + randN := func() int { + if rand.Intn(n) == 0 { + return 1 + } + return 0 + } + var b [2]int + for x := 0; x < samples; x++ { + b[randN()]++ + } + fmt.Printf("randN(%d) %7d %7d %5.2f%%\n", + n, b[1], b[0], float64(b[1])*100/samples) + + // function unbiased, per task description + unbiased := func() (b int) { + for b = randN(); b == randN(); b = randN() { + } + return + } + var u [2]int + for x := 0; x < samples; x++ { + u[unbiased()]++ + } + fmt.Printf("unbiased %7d %7d %5.2f%%\n", + u[1], u[0], float64(u[1])*100/samples) + } +} diff --git a/Task/Unbias-a-random-generator/Haskell/unbias-a-random-generator.hs b/Task/Unbias-a-random-generator/Haskell/unbias-a-random-generator.hs new file mode 100644 index 0000000000..fc8717c819 --- /dev/null +++ b/Task/Unbias-a-random-generator/Haskell/unbias-a-random-generator.hs @@ -0,0 +1,29 @@ +import Control.Monad +import Random +import Data.IORef +import Text.Printf + +randN :: Integer -> IO Bool +randN n = randomRIO (1,n) >>= return . (== 1) + +unbiased :: Integer -> IO Bool +unbiased n = do + a <- randN n + b <- randN n + if a /= b then return a else unbiased n + +main :: IO () +main = forM_ [3..6] $ \n -> do + cb <- newIORef 0 + cu <- newIORef 0 + replicateM_ trials $ do + b <- randN n + u <- unbiased n + when b $ modifyIORef cb (+ 1) + when u $ modifyIORef cu (+ 1) + tb <- readIORef cb + tu <- readIORef cu + printf "%d: %5.2f%% %5.2f%%\n" n + (100 * fromIntegral tb / fromIntegral trials :: Double) + (100 * fromIntegral tu / fromIntegral trials :: Double) + where trials = 50000 diff --git a/Task/Unbias-a-random-generator/Icon/unbias-a-random-generator.icon b/Task/Unbias-a-random-generator/Icon/unbias-a-random-generator.icon new file mode 100644 index 0000000000..d47a7c98c1 --- /dev/null +++ b/Task/Unbias-a-random-generator/Icon/unbias-a-random-generator.icon @@ -0,0 +1,30 @@ +procedure main(A) + iters := \A[1] | 10000 + write("ratios of 0 to 1 from ",iters," trials:") + every n := 3 to 6 do { + results_randN := table(0) + results_unbiased := table(0) + every 1 to iters do { + results_randN[randN(n)] +:= 1 + results_unbiased[unbiased(n)] +:= 1 + } + showResults(n, "randN", results_randN) + showResults(n, "unbiased", results_unbiased) + } +end + +procedure showResults(n, s, t) + write(n," ",left(s,9),":",t[0],"/",t[1]," = ",t[0]/real(t[1])) +end + +procedure unbiased(n) + repeat { + n1 := randN(n) + n2 := randN(n) + if n1 ~= n2 then suspend n1 + } +end + +procedure randN(n) + repeat suspend if 1 = ?n then 1 else 0 +end diff --git a/Task/Unbias-a-random-generator/J/unbias-a-random-generator-1.j b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-1.j new file mode 100644 index 0000000000..22c78f46b6 --- /dev/null +++ b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-1.j @@ -0,0 +1,2 @@ +randN=: 0 = ? +unbiased=: i.@# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* randN@# ] diff --git a/Task/Unbias-a-random-generator/J/unbias-a-random-generator-2.j b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-2.j new file mode 100644 index 0000000000..3a865b681c --- /dev/null +++ b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-2.j @@ -0,0 +1,4 @@ + randN 10#6 +1 0 0 0 1 0 0 0 0 0 + unbiased 10#6 +1 0 0 1 0 0 1 0 1 1 diff --git a/Task/Unbias-a-random-generator/J/unbias-a-random-generator-3.j b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-3.j new file mode 100644 index 0000000000..3b3ed64414 --- /dev/null +++ b/Task/Unbias-a-random-generator/J/unbias-a-random-generator-3.j @@ -0,0 +1,16 @@ + +/randN 100#3 +30 + +/randN 100#4 +20 + +/randN 100#5 +18 + +/randN 100#6 +18 + +/unbiased 100#3 +49 + +/unbiased 100#4 +46 + +/unbiased 100#5 +49 + +/unbiased 100#6 +47 diff --git a/Task/Unbias-a-random-generator/Java/unbias-a-random-generator.java b/Task/Unbias-a-random-generator/Java/unbias-a-random-generator.java new file mode 100644 index 0000000000..1ca4ae393e --- /dev/null +++ b/Task/Unbias-a-random-generator/Java/unbias-a-random-generator.java @@ -0,0 +1,27 @@ +public class Bias { + public static boolean biased(int n) { + return Math.random() < 1.0 / n; + } + + public static boolean unbiased(int n) { + boolean a, b; + do { + a = biased(n); + b = biased(n); + } while (a == b); + return a; + } + + public static void main(String[] args) { + final int M = 50000; + for (int n = 3; n < 7; n++) { + int c1 = 0, c2 = 0; + for (int i = 0; i < M; i++) { + c1 += biased(n) ? 1 : 0; + c2 += unbiased(n) ? 1 : 0; + } + System.out.format("%d: %2.2f%% %2.2f%%\n", + n, 100.0*c1/M, 100.0*c2/M); + } + } +} diff --git a/Task/Unbias-a-random-generator/Liberty-BASIC/unbias-a-random-generator.liberty b/Task/Unbias-a-random-generator/Liberty-BASIC/unbias-a-random-generator.liberty new file mode 100644 index 0000000000..acddd13631 --- /dev/null +++ b/Task/Unbias-a-random-generator/Liberty-BASIC/unbias-a-random-generator.liberty @@ -0,0 +1,42 @@ +for N =3 to 6 ' bias as defined + tests =1E5 ' number of tests to do + + print " Biased bit-string, '1' chosen on average once out of "; N; " times . . . " + + countZeros =0: countOnes =0 + + for j =1 to tests + b =randN( N) + if b =1 then countOnes =countOnes +1 else countZeros =countZeros +1 + next j + + print " "; countZeros; " zeros & "; countOnes; " ones. Ratio ="; countOnes /tests + + print " Unbiased bit-string . . . " + + countZeros =0: countOnes =0 + + for j =1 to tests + b =unBiased( N) + if b =1 then countOnes =countOnes +1 else countZeros =countZeros +1 + next j + + print " "; countZeros; " zeros & "; countOnes; " ones. Ratio ="; countOnes /tests + print +next N + +print " DONE." + +end ' _____________________________________________________ + +function randN( n) + if rnd( 1) <( 1 /n) then randN =1 else randN =0 +end function + +function unBiased( n) + do + n1 =randN( n) + n2 =randN( n) + loop until n1 <>n2 + unBiased =n1 +end function diff --git a/Task/Unbias-a-random-generator/Lua/unbias-a-random-generator.lua b/Task/Unbias-a-random-generator/Lua/unbias-a-random-generator.lua new file mode 100644 index 0000000000..4060e9fc98 --- /dev/null +++ b/Task/Unbias-a-random-generator/Lua/unbias-a-random-generator.lua @@ -0,0 +1,42 @@ +local function randN(n) + return function() + if math.random() < 1/n then return 1 else return 0 end + end +end + +local function unbiased(n) + local biased = randN (n) + return function() + local a, b = biased(), biased() + while a==b do + a, b = biased(), biased() + end + return a + end +end + +local function demonstrate (samples) + for n = 3, 6 do + biased = randN(n) + unbias = unbiased(n) + local bcounts = {[0]=0,[1]=0} + local ucounts = {[0]=0,[1]=0} + for i=1, samples do + local bnum = biased() + local unum = unbias() + bcounts[bnum] = bcounts[bnum]+1 + ucounts[unum] = ucounts[unum]+1 + end + print(string.format("N = %d",n), + "# 0", "# 1", + "% 0", "% 1") + print("biased", bcounts[0], bcounts[1], + bcounts[0] / samples * 100, + bcounts[1] / samples * 100) + print("unbias", ucounts[0], ucounts[1], + ucounts[0] / samples * 100, + ucounts[1] / samples * 100) + end +end + +demonstrate(100000) diff --git a/Task/Unbias-a-random-generator/Mathematica/unbias-a-random-generator.math b/Task/Unbias-a-random-generator/Mathematica/unbias-a-random-generator.math new file mode 100644 index 0000000000..909c5a687b --- /dev/null +++ b/Task/Unbias-a-random-generator/Mathematica/unbias-a-random-generator.math @@ -0,0 +1,4 @@ +rand[bias_, n_] := 1 - Unitize@RandomInteger[bias - 1, n] + +unbiased[bias_, n_] := + DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]] diff --git a/Task/Unbias-a-random-generator/NetRexx/unbias-a-random-generator.netrexx b/Task/Unbias-a-random-generator/NetRexx/unbias-a-random-generator.netrexx new file mode 100644 index 0000000000..d474b71dc2 --- /dev/null +++ b/Task/Unbias-a-random-generator/NetRexx/unbias-a-random-generator.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +runSample(arg) +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method biased(n = int) public static returns boolean + return Math.random() < 1.0 / n + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method unbiased(n = int) public static returns boolean + a = boolean + b = boolean + loop until a \= b + a = biased(n) + b = biased(n) + end + return a + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method runSample(arg) private static + parse arg Mx . + if Mx.length <= 0 then Mx = 50000 + M = int Mx + loop n = int 3 to 6 + c1 = int 0 + c2 = int 0 + loop for M + if biased(n) then c1 = c1 + 1 + if unbiased(n) then c2 = c2 + 1 + end + say Rexx(n).right(3)':' Rexx(100.0 * c1 / M).format(6, 2)'%' Rexx(100.0 * c2 / M).format(6, 2)'%' + end n + return diff --git a/Task/Unbias-a-random-generator/OCaml/unbias-a-random-generator.ocaml b/Task/Unbias-a-random-generator/OCaml/unbias-a-random-generator.ocaml new file mode 100644 index 0000000000..f73fdeba8e --- /dev/null +++ b/Task/Unbias-a-random-generator/OCaml/unbias-a-random-generator.ocaml @@ -0,0 +1,20 @@ +let randN n = + if Random.int n = 0 then 1 else 0 + +let rec unbiased n = + let a = randN n in + if a <> randN n then a else unbiased n + +let () = + Random.self_init(); + let n = 50_000 in + for b = 3 to 6 do + let cb = ref 0 in + let cu = ref 0 in + for i = 1 to n do + cb := !cb + (randN b); + cu := !cu + (unbiased b); + done; + Printf.printf "%d: %5.2f%% %5.2f%%\n" + b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n) + done diff --git a/Task/Unbias-a-random-generator/PARI-GP/unbias-a-random-generator.pari b/Task/Unbias-a-random-generator/PARI-GP/unbias-a-random-generator.pari new file mode 100644 index 0000000000..960ee9c517 --- /dev/null +++ b/Task/Unbias-a-random-generator/PARI-GP/unbias-a-random-generator.pari @@ -0,0 +1,10 @@ +randN(N)=!random(N); +unbiased(N)={ + my(a,b); + while(1, + a=randN(N); + b=randN(N); + if(a!=b, return(a)) + ) +}; +for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n)))) diff --git a/Task/Unbias-a-random-generator/PL-I/unbias-a-random-generator.pli b/Task/Unbias-a-random-generator/PL-I/unbias-a-random-generator.pli new file mode 100644 index 0000000000..8ec6d8454a --- /dev/null +++ b/Task/Unbias-a-random-generator/PL-I/unbias-a-random-generator.pli @@ -0,0 +1,29 @@ +test: procedure options (main); /* 20 Nov. 2012 */ + +randN: procedure(N) returns (bit (1)); + declare N fixed (1); + declare random builtin; + declare r fixed (2) external initial (-1); + if r >= 0 then do; r = r-1; return ('0'b); end; + r = random()*2*N; + return ('1'b); +end randN; + +random: procedure returns (bit(1)); + declare (r1, r2) bit (1); + do until (r1 ^= r2); + r1 = randN(N); r2 = randN(N); + end; + return (r1); +end random; + + declare (biasedrn, unbiasedrn) (100) bit (1); + declare N fixed (1); + + put ('N Biased Unbiased (tally of 100 random numbers)'); + do N = 3 to 6; + biasedrn = randN(N); unbiasedrn = random; + put skip edit (N, sum(biasedrn), sum(unbiasedrn)) (F(1), 2 F(10)); + end; + +end test; diff --git a/Task/Unbias-a-random-generator/Perl-6/unbias-a-random-generator.pl6 b/Task/Unbias-a-random-generator/Perl-6/unbias-a-random-generator.pl6 new file mode 100644 index 0000000000..5dbb96b7f7 --- /dev/null +++ b/Task/Unbias-a-random-generator/Perl-6/unbias-a-random-generator.pl6 @@ -0,0 +1,20 @@ +sub randN ( $n where 3..6 ) { + return ( $n.rand / ($n - 1) ).Int; +} + +sub unbiased ( $n where 3..6 ) { + my $n1; + repeat { $n1 = randN($n) } until $n1 != randN($n); + return $n1; +} + +my $iterations = 1000; +for 3 .. 6 -> $n { + my ( @raw, @fixed ); + for ^$iterations { + @raw[ randN($n) ]++; + @fixed[ unbiased($n) ]++; + } + printf "N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\n", + $n, map { .perl, .[1] * 100 / $iterations }, $(@raw), $(@fixed); +} diff --git a/Task/Unbias-a-random-generator/Perl/unbias-a-random-generator.pl b/Task/Unbias-a-random-generator/Perl/unbias-a-random-generator.pl new file mode 100644 index 0000000000..0754b199db --- /dev/null +++ b/Task/Unbias-a-random-generator/Perl/unbias-a-random-generator.pl @@ -0,0 +1,21 @@ +sub randn { + my $n = shift; + return int(rand($n) / ($n - 1)); +} + +for my $n (3 .. 6) { + print "Bias $n: "; + my (@raw, @fixed); + for (1 .. 10000) { + my $x = randn($n); + $raw[$x]++; + $fixed[$x]++ if randn($n) != $x + } + print "@raw, "; + printf("%3g+-%.3g%%\tfixed: ", $raw[0]/100, + 100 * sqrt($raw[0] * $raw[1]) / ($raw[0] + $raw[1])**1.5); + print "@fixed, "; + printf("%3g+-%.3g%%\n", 100*$fixed[0]/($fixed[0] + $fixed[1]), + 100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5); + +} diff --git a/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-1.l b/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-1.l new file mode 100644 index 0000000000..227850abdc --- /dev/null +++ b/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-1.l @@ -0,0 +1,10 @@ +(de randN (N) + (if (= 1 (rand 1 N)) 1 0) ) + +(de unbiased (N) + (use (A B) + (while + (= + (setq A (randN N)) + (setq B (randN N)) ) ) + A ) ) diff --git a/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-2.l b/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-2.l new file mode 100644 index 0000000000..f447743788 --- /dev/null +++ b/Task/Unbias-a-random-generator/PicoLisp/unbias-a-random-generator-2.l @@ -0,0 +1,11 @@ +(for N (range 3 6) + (tab (2 1 7 2 7 2) + N ":" + (format + (let S 0 (do 10000 (inc 'S (randN N)))) + 2 ) + "%" + (format + (let S 0 (do 10000 (inc 'S (unbiased N)))) + 2 ) + "%" ) ) diff --git a/Task/Unbias-a-random-generator/PureBasic/unbias-a-random-generator.purebasic b/Task/Unbias-a-random-generator/PureBasic/unbias-a-random-generator.purebasic new file mode 100644 index 0000000000..604d25b5a4 --- /dev/null +++ b/Task/Unbias-a-random-generator/PureBasic/unbias-a-random-generator.purebasic @@ -0,0 +1,35 @@ +Procedure biased(n) + If Random(n) <> 1 + ProcedureReturn 0 + EndIf + ProcedureReturn 1 +EndProcedure + +Procedure unbiased(n) + Protected a, b + Repeat + a = biased(n) + b = biased(n) + Until a <> b + ProcedureReturn a +EndProcedure + +#count = 100000 + +Define n, m, output.s +For n = 3 To 6 + Dim b_count(1) + Dim u_count(1) + For m = 1 To #count + x = biased(n) + b_count(x) + 1 + x = unbiased(n) + u_count(x) + 1 + Next + output + "N = " + Str(n) + #LF$ + output + " biased =>" + #tab$ + "#0=" + Str(b_count(0)) + #tab$ + "#1=" +Str(b_count(1)) + output + #tab$ + " ratio=" + StrF(b_count(1) / #count * 100, 2) + "%" + #LF$ + output + " unbiased =>" + #tab$ + "#0=" + Str(u_count(0)) + #tab$ + "#1=" + Str(u_count(1)) + output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$ +Next +MessageRequester("Biased and Unbiased random number results", output) diff --git a/Task/Unbias-a-random-generator/Python/unbias-a-random-generator.py b/Task/Unbias-a-random-generator/Python/unbias-a-random-generator.py new file mode 100644 index 0000000000..4d57a0401a --- /dev/null +++ b/Task/Unbias-a-random-generator/Python/unbias-a-random-generator.py @@ -0,0 +1,28 @@ +from __future__ import print_function +import random + +def randN(N): + " 1,0 random generator factory with 1 appearing 1/N'th of the time" + return lambda: random.randrange(N) == 0 + +def unbiased(biased): + 'uses a biased() generator of 1 or 0, to create an unbiased one' + this, that = biased(), biased() + while this == that: # Loop until 10 or 01 + this, that = biased(), biased() + return this # return the first + +if __name__ == '__main__': + from collections import namedtuple + + Stats = namedtuple('Stats', 'count1 count0 percent') + + for N in range(3, 7): + biased = randN(N) + v = [biased() for x in range(1000000)] + v1, v0 = v.count(1), v.count(0) + print ( "Biased(%i) = %r" % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) ) + + v = [unbiased(biased) for x in range(1000000)] + v1, v0 = v.count(1), v.count(0) + print ( " Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) ) diff --git a/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx new file mode 100644 index 0000000000..9c2afe8aa4 --- /dev/null +++ b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx @@ -0,0 +1,22 @@ +/*REXX program to generated unbiased random numbers and show results. */ +parse arg samples seed . /*allow specification of options.*/ +if samples=='' | samples==',' then samples=1000 /*SAMPLES specified?*/ +if seed\=='' then call random ,,seed /*if specified, use it for RANDOM*/ +w=12 /*width of columnar output. */ +say centr('N') centr('random') centr('unbiased') centr('samples') + + do N=3 to 6; b=0; u=0 + do j=1 for samples + b=b + randN(N) + u=u + unbiased() + end /*j*/ + say center(N,w) center(b,w) center(u,w) center(samples,w) + end /*N*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────CENTR subroutine────────────────────*/ +centr: return center(arg(1),w,'─') +/*──────────────────────────────────RANDN subroutine────────────────────*/ +randN: return random(1,arg(1))==arg(1) +/*──────────────────────────────────UNBIASED subroutine─────────────────*/ +unbiased: do until x\==y; x=randN(N); y=randN(N); end /*until*/ +return x diff --git a/Task/Unbias-a-random-generator/Seed7/unbias-a-random-generator.seed7 b/Task/Unbias-a-random-generator/Seed7/unbias-a-random-generator.seed7 new file mode 100644 index 0000000000..6b5b7edc37 --- /dev/null +++ b/Task/Unbias-a-random-generator/Seed7/unbias-a-random-generator.seed7 @@ -0,0 +1,34 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const func integer: randN (in integer: n) is + return ord(rand(1, n) = 1); + +const func integer: unbiased (in integer: n) is func + result + var integer: unbiased is 0; + begin + repeat + unbiased := randN(n); + until unbiased <> randN(n); + end func; + +const proc: main is func + local + const integer: tests is 50000; + var integer: n is 0; + var integer: sumBiased is 0; + var integer: sumUnbiased is 0; + var integer: count is 0; + begin + for n range 3 to 6 do + sumBiased := 0; + sumUnbiased := 0; + for count range 1 to tests do + sumBiased +:= randN(n); + sumUnbiased +:= unbiased(n); + end for; + writeln(n <& ": " <& flt(100 * sumBiased) / flt(tests) digits 3 lpad 6 <& + " " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6); + end for; + end func; diff --git a/Task/Unbias-a-random-generator/Tcl/unbias-a-random-generator.tcl b/Task/Unbias-a-random-generator/Tcl/unbias-a-random-generator.tcl new file mode 100644 index 0000000000..f04db5ffab --- /dev/null +++ b/Task/Unbias-a-random-generator/Tcl/unbias-a-random-generator.tcl @@ -0,0 +1,23 @@ +# 1,0 random generator factory with 1 appearing 1/N'th of the time +proc randN n {expr {rand()*$n < 1}} + +# uses a biased generator of 1 or 0, to create an unbiased one +proc unbiased {biased} { + while 1 { + if {[set a [eval $biased]] != [eval $biased]} {return $a} + } +} + +for {set n 3} {$n <= 6} {incr n} { + set biased [list randN $n] + for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} { + incr c([eval $biased]) + } + puts [format " biased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \ + [expr {100.*$c(1)/$i}]] + for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} { + incr c([unbiased $biased]) + } + puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \ + [expr {100.*$c(1)/$i}]] +} diff --git a/Task/Undefined-values/0DESCRIPTION b/Task/Undefined-values/0DESCRIPTION new file mode 100644 index 0000000000..6bc365095f --- /dev/null +++ b/Task/Undefined-values/0DESCRIPTION @@ -0,0 +1 @@ +For languages which have an explicit notion of an undefined value, identify and exercise those language's mechanisms for identifying and manipulating a variable's value's status as being undefined diff --git a/Task/Undefined-values/1META.yaml b/Task/Undefined-values/1META.yaml new file mode 100644 index 0000000000..c78e2d9a80 --- /dev/null +++ b/Task/Undefined-values/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming language concepts diff --git a/Task/Undefined-values/ALGOL-68/undefined-values.alg b/Task/Undefined-values/ALGOL-68/undefined-values.alg new file mode 100644 index 0000000000..ab97fafd37 --- /dev/null +++ b/Task/Undefined-values/ALGOL-68/undefined-values.alg @@ -0,0 +1,16 @@ +MODE R = REF BOOL; +R r := NIL; + +MODE U = UNION(BOOL, VOID); +U u := EMPTY; + +IF r IS R(NIL) THEN + print(("r IS NIL", new line)) +ELSE + print(("r ISNT NIL", new line)) +FI; + +CASE u IN + (VOID):print(("u is EMPTY", new line)) + OUT print(("u isnt EMPTY", new line)) +ESAC diff --git a/Task/Undefined-values/ActionScript/undefined-values.as b/Task/Undefined-values/ActionScript/undefined-values.as new file mode 100644 index 0000000000..9e47dca6ea --- /dev/null +++ b/Task/Undefined-values/ActionScript/undefined-values.as @@ -0,0 +1,7 @@ +var foo; // untyped +var bar:*; // explicitly untyped + +trace(foo + ", " + bar); // outputs "undefined, undefined" + +if (foo == undefined) + trace("foo is undefined"); // outputs "foo is undefined" diff --git a/Task/Undefined-values/Ada/undefined-values.ada b/Task/Undefined-values/Ada/undefined-values.ada new file mode 100644 index 0000000000..11930c3ddf --- /dev/null +++ b/Task/Undefined-values/Ada/undefined-values.ada @@ -0,0 +1,23 @@ +pragma Initialize_Scalars; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Invalid_Value is + type Color is (Red, Green, Blue); + X : Float; + Y : Color; +begin + if not X'Valid then + Put_Line ("X is not valid"); + end if; + X := 1.0; + if X'Valid then + Put_Line ("X is" & Float'Image (X)); + end if; + if not Y'Valid then + Put_Line ("Y is not valid"); + end if; + Y := Green; + if Y'Valid then + Put_Line ("Y is " & Color'Image (Y)); + end if; +end Invalid_Value; diff --git a/Task/Undefined-values/BBC-BASIC/undefined-values-1.bbc b/Task/Undefined-values/BBC-BASIC/undefined-values-1.bbc new file mode 100644 index 0000000000..10d1f55561 --- /dev/null +++ b/Task/Undefined-values/BBC-BASIC/undefined-values-1.bbc @@ -0,0 +1,8 @@ + ok% = TRUE + ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE + IF ok% THEN + PRINT variable$ + ELSE + PRINT "Not defined" + ENDIF + RESTORE ERROR diff --git a/Task/Undefined-values/BBC-BASIC/undefined-values-2.bbc b/Task/Undefined-values/BBC-BASIC/undefined-values-2.bbc new file mode 100644 index 0000000000..8f2552c49a --- /dev/null +++ b/Task/Undefined-values/BBC-BASIC/undefined-values-2.bbc @@ -0,0 +1,11 @@ + PROCtest + END + + DEF PROCtest + LOCAL array() + IF !^array() < 2 PRINT "Array is undefined" + DIM array(1,2) + IF !^array() > 1 PRINT "Array is defined" + + !^array() = 0 : REM Set array to undefined state + ENDPROC diff --git a/Task/Undefined-values/C/undefined-values.c b/Task/Undefined-values/C/undefined-values.c new file mode 100644 index 0000000000..770242599f --- /dev/null +++ b/Task/Undefined-values/C/undefined-values.c @@ -0,0 +1,16 @@ +#include +#include + +int main() +{ + int junk, *junkp; + + /* Print an unitialized variable! */ + printf("junk: %d\n", junk); + + /* Follow a pointer to unitialized memory! */ + junkp = malloc(sizeof *junkp); + if (junkp) + printf("*junkp: %d\n", *junkp); + return 0; +} diff --git a/Task/Undefined-values/Common-Lisp/undefined-values-1.lisp b/Task/Undefined-values/Common-Lisp/undefined-values-1.lisp new file mode 100644 index 0000000000..9dc20c999f --- /dev/null +++ b/Task/Undefined-values/Common-Lisp/undefined-values-1.lisp @@ -0,0 +1,10 @@ + ;; assumption: none of these variables initially exist + + (defvar *x*) ;; variable exists now, but has no value + (defvar *y* 42) ;; variable exists now, and has a value + + (special-variable-p '*x*) -> T ;; Symbol *x* names a special variable + (boundp '*x*) -> NIL ;; *x* has no binding + (boundp '*y*) -> T + + (special-variable-p '*z*) -> NIL ;; *z* does not name a special variable diff --git a/Task/Undefined-values/Common-Lisp/undefined-values-2.lisp b/Task/Undefined-values/Common-Lisp/undefined-values-2.lisp new file mode 100644 index 0000000000..7868f1b208 --- /dev/null +++ b/Task/Undefined-values/Common-Lisp/undefined-values-2.lisp @@ -0,0 +1,3 @@ + (makunbound '*y*) ;; *y* no longer has a value; it is erroneous to evaluate *y* + + (setf *y* 43) ;; *y* is bound again. diff --git a/Task/Undefined-values/Common-Lisp/undefined-values-3.lisp b/Task/Undefined-values/Common-Lisp/undefined-values-3.lisp new file mode 100644 index 0000000000..a1e4db7f99 --- /dev/null +++ b/Task/Undefined-values/Common-Lisp/undefined-values-3.lisp @@ -0,0 +1,7 @@ + (defvar *dyn*) ;; special, no binding + + (let (*dyn* ;; locally scoped override, value is nil + lex) ;; lexical, value is nil + (list (boundp '*dyn*) *dyn* (boundp 'lex) lex)) -> (T NIL NIL NIL) + + (boundp '*global*) -> NIL diff --git a/Task/Undefined-values/D/undefined-values.d b/Task/Undefined-values/D/undefined-values.d new file mode 100644 index 0000000000..5962a71c52 --- /dev/null +++ b/Task/Undefined-values/D/undefined-values.d @@ -0,0 +1,19 @@ +void main() { + // Initialized: + int a = 5; + double b = 5.0; + char c = 'f'; + int[] d = [1, 2, 3]; + + // Default initialized: + int aa; // set to 0 + double bb; // set to double.init, that is a NaN + char cc; // set to 0xFF + int[] dd; // set to null + int[3] ee; // set to [0, 0, 0] + + // Undefined (contain garbage): + int aaa = void; + double[] bbb = void; + int[3] eee = void; +} diff --git a/Task/Undefined-values/Delphi/undefined-values.delphi b/Task/Undefined-values/Delphi/undefined-values.delphi new file mode 100644 index 0000000000..67cfd43f54 --- /dev/null +++ b/Task/Undefined-values/Delphi/undefined-values.delphi @@ -0,0 +1,13 @@ +var + P: PInteger; +begin + New(P); //Allocate some memory + try + If Assigned(P) Then //... + begin + P^ := 42; + end; + finally + Dispose(P); //Release memory allocated by New + end; +end; diff --git a/Task/Undefined-values/E/undefined-values.e b/Task/Undefined-values/E/undefined-values.e new file mode 100644 index 0000000000..47094bf6e9 --- /dev/null +++ b/Task/Undefined-values/E/undefined-values.e @@ -0,0 +1,3 @@ +if (foo == bar || (def baz := lookup(foo)) != null) { + ... +} diff --git a/Task/Undefined-values/GAP/undefined-values.gap b/Task/Undefined-values/GAP/undefined-values.gap new file mode 100644 index 0000000000..f5dccefcc5 --- /dev/null +++ b/Task/Undefined-values/GAP/undefined-values.gap @@ -0,0 +1,7 @@ +IsBound(a); +# true + +Unbind(a); + +IsBound(a); +# false diff --git a/Task/Undefined-values/Go/undefined-values.go b/Task/Undefined-values/Go/undefined-values.go new file mode 100644 index 0000000000..fa1e262bd2 --- /dev/null +++ b/Task/Undefined-values/Go/undefined-values.go @@ -0,0 +1,97 @@ +package main + +import "fmt" + +var ( + s []int + p *int + f func() + i interface{} + m map[int]int + c chan int +) + +func main() { + fmt.Println("Exercise nil objects:") + status() + + // initialize objects + s = make([]int, 1) + p = &s[0] // yes, reference element of slice just created + f = func() { fmt.Println("function call") } + i = user(0) // see user defined type just below + m = make(map[int]int) + c = make(chan int, 1) + + fmt.Println("\nExercise objects after initialization:") + status() +} + +type user int + +func (user) m() { + fmt.Println("method call") +} + +func status() { + trySlice() + tryPointer() + tryFunction() + tryInterface() + tryMap() + tryChannel() +} + +func reportPanic() { + if x := recover(); x != nil { + fmt.Println("panic:", x) + } +} + +func trySlice() { + defer reportPanic() + fmt.Println("s[0] =", s[0]) +} + +func tryPointer() { + defer reportPanic() + fmt.Println("*p =", *p) +} + +func tryFunction() { + defer reportPanic() + f() +} + +func tryInterface() { + defer reportPanic() + + // normally the nil identifier accesses a nil value for one of + // six predefined types. In a type switch however, nil can be used + // as a type. In this case, it matches the nil interface. + switch i.(type) { + case nil: + fmt.Println("i is nil interface") + case interface { + m() + }: + fmt.Println("i has method m") + } + + // assert type with method and then call method + i.(interface { + m() + }).m() +} + +func tryMap() { + defer reportPanic() + m[0] = 0 + fmt.Println("m[0] =", m[0]) +} + +func tryChannel() { + defer reportPanic() + close(c) + fmt.Println("channel closed") +} diff --git a/Task/Undefined-values/Haskell/undefined-values-1.hs b/Task/Undefined-values/Haskell/undefined-values-1.hs new file mode 100644 index 0000000000..0f6c83aae0 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-1.hs @@ -0,0 +1,3 @@ +main = print $ "Incoming error--" ++ undefined +-- When run in GHC: +-- "Incoming error--*** Exception: Prelude.undefined diff --git a/Task/Undefined-values/Haskell/undefined-values-2.hs b/Task/Undefined-values/Haskell/undefined-values-2.hs new file mode 100644 index 0000000000..17f26cbfc6 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-2.hs @@ -0,0 +1 @@ +main = print $ length [undefined, undefined, 1 `div` 0] diff --git a/Task/Undefined-values/Haskell/undefined-values-3.hs b/Task/Undefined-values/Haskell/undefined-values-3.hs new file mode 100644 index 0000000000..bb9557a682 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-3.hs @@ -0,0 +1 @@ +resurrect 0 = error "I'm out of orange smoke!" diff --git a/Task/Undefined-values/Haskell/undefined-values-4.hs b/Task/Undefined-values/Haskell/undefined-values-4.hs new file mode 100644 index 0000000000..4d332ce577 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-4.hs @@ -0,0 +1,2 @@ +undefined :: a +undefined = error "Prelude.undefined" diff --git a/Task/Undefined-values/Haskell/undefined-values-5.hs b/Task/Undefined-values/Haskell/undefined-values-5.hs new file mode 100644 index 0000000000..6e5dfaa9a0 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-5.hs @@ -0,0 +1,16 @@ +import Control.Exception (catch, evaluate, ErrorCall) +import System.IO.Unsafe (unsafePerformIO) +import Prelude hiding (catch) +import Control.DeepSeq (NFData, deepseq) + +scoopError :: (NFData a) => a -> Either String a +scoopError x = unsafePerformIO $ catch right left + where right = deepseq x $ return $ Right x + left e = return $ Left $ show (e :: ErrorCall) + +safeHead :: (NFData a) => [a] -> Either String a +safeHead = scoopError . head + +main = do + print $ safeHead ([] :: String) + print $ safeHead ["str"] diff --git a/Task/Undefined-values/Haskell/undefined-values-6.hs b/Task/Undefined-values/Haskell/undefined-values-6.hs new file mode 100644 index 0000000000..7a07a95073 --- /dev/null +++ b/Task/Undefined-values/Haskell/undefined-values-6.hs @@ -0,0 +1,15 @@ +global G1 + +procedure main(arglist) +local ML1 +static MS1 +undeftest() +end + +procedure undeftest(P1) +static S1 +local L1,L2 +every #write all local, parameter, static, and global variable names + write((localnames|paramnames|staticnames|globalnames)(¤t,0)) # ... visible in the current co-expression at this calling level (0) +return +end diff --git a/Task/Undefined-values/J/undefined-values-1.j b/Task/Undefined-values/J/undefined-values-1.j new file mode 100644 index 0000000000..4059d175d4 --- /dev/null +++ b/Task/Undefined-values/J/undefined-values-1.j @@ -0,0 +1,3 @@ + foo=: 3 + nc;:'foo bar' +0 _1 diff --git a/Task/Undefined-values/J/undefined-values-2.j b/Task/Undefined-values/J/undefined-values-2.j new file mode 100644 index 0000000000..d3ff87e3e2 --- /dev/null +++ b/Task/Undefined-values/J/undefined-values-2.j @@ -0,0 +1,7 @@ + erase;:'foo bar' +1 1 + nc;:'foo bar' +_1 _1 + bar=:99 + nc;:'foo bar' +_1 0 diff --git a/Task/Undefined-values/Java/undefined-values-1.java b/Task/Undefined-values/Java/undefined-values-1.java new file mode 100644 index 0000000000..a9088664f4 --- /dev/null +++ b/Task/Undefined-values/Java/undefined-values-1.java @@ -0,0 +1,3 @@ +String string = null; // the variable string is undefined +System.out.println(string); //prints "null" to std out +System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException diff --git a/Task/Undefined-values/Java/undefined-values-2.java b/Task/Undefined-values/Java/undefined-values-2.java new file mode 100644 index 0000000000..f90355ff4e --- /dev/null +++ b/Task/Undefined-values/Java/undefined-values-2.java @@ -0,0 +1,4 @@ +int i = null; // compilation error: incompatible types, required: int, found: +if (i == null) { // compilation error: incomparable types: int and + i = 1; +} diff --git a/Task/Undefined-values/Java/undefined-values-3.java b/Task/Undefined-values/Java/undefined-values-3.java new file mode 100644 index 0000000000..aeba2a46a1 --- /dev/null +++ b/Task/Undefined-values/Java/undefined-values-3.java @@ -0,0 +1,4 @@ +Integer i = null; // variable i is undefined +if (i == null) { + i = 1; +} diff --git a/Task/Undefined-values/JavaScript/undefined-values-1.js b/Task/Undefined-values/JavaScript/undefined-values-1.js new file mode 100644 index 0000000000..1b15176492 --- /dev/null +++ b/Task/Undefined-values/JavaScript/undefined-values-1.js @@ -0,0 +1,13 @@ +var a; + +typeof(a) === "undefined"; +typeof(b) === "undefined"; + +var obj = {}; // Empty object. +typeof(obj.c) === "undefined"; + +obj.c = 42; + +obj.c === 42; +delete obj.c; +typeof(obj.c) === "undefined"; diff --git a/Task/Undefined-values/JavaScript/undefined-values-2.js b/Task/Undefined-values/JavaScript/undefined-values-2.js new file mode 100644 index 0000000000..2e1917df80 --- /dev/null +++ b/Task/Undefined-values/JavaScript/undefined-values-2.js @@ -0,0 +1,3 @@ +var a; +a === void 0; // true +b === void 0; // throws a ReferenceError diff --git a/Task/Undefined-values/LOLCODE/undefined-values.lol b/Task/Undefined-values/LOLCODE/undefined-values.lol new file mode 100644 index 0000000000..e13d482730 --- /dev/null +++ b/Task/Undefined-values/LOLCODE/undefined-values.lol @@ -0,0 +1,18 @@ +HAI 1.3 + +I HAS A foo BTW, INISHULIZD TO NOOB +DIFFRINT foo AN FAIL, O RLY? + YA RLY, VISIBLE "FAIL != NOOB" +OIC + +I HAS A bar ITZ 42 +bar, O RLY? + YA RLY, VISIBLE "bar IZ DEFIND" +OIC + +bar R NOOB BTW, UNDEF bar +bar, O RLY? + YA RLY, VISIBLE "SHUD NEVAR C DIS" +OIC + +KTHXBYE diff --git a/Task/Undefined-values/Logo/undefined-values.logo b/Task/Undefined-values/Logo/undefined-values.logo new file mode 100644 index 0000000000..67b2603e7c --- /dev/null +++ b/Task/Undefined-values/Logo/undefined-values.logo @@ -0,0 +1,19 @@ +; procedures +to square :x + output :x * :x +end + +show defined? "x ; true +show procedure? "x ; true (also works for built-in primitives) +erase "x +show defined? "x ; false +show square 3 ; I don't know how to square + +; names + +make "n 23 + +show name? "n ; true +ern "n +show name? "n ; false +show :n ; n has no value diff --git a/Task/Undefined-values/Lua/undefined-values.lua b/Task/Undefined-values/Lua/undefined-values.lua new file mode 100644 index 0000000000..19a08e6516 --- /dev/null +++ b/Task/Undefined-values/Lua/undefined-values.lua @@ -0,0 +1,9 @@ +print( a ) + +local b +print( b ) + +if b == nil then + b = 5 +end +print( b ) diff --git a/Task/Undefined-values/MATLAB/undefined-values-1.m b/Task/Undefined-values/MATLAB/undefined-values-1.m new file mode 100644 index 0000000000..e81e0332fd --- /dev/null +++ b/Task/Undefined-values/MATLAB/undefined-values-1.m @@ -0,0 +1 @@ + global var; diff --git a/Task/Undefined-values/MATLAB/undefined-values-2.m b/Task/Undefined-values/MATLAB/undefined-values-2.m new file mode 100644 index 0000000000..08058c1c39 --- /dev/null +++ b/Task/Undefined-values/MATLAB/undefined-values-2.m @@ -0,0 +1 @@ + isempty(var) diff --git a/Task/Undefined-values/MATLAB/undefined-values-3.m b/Task/Undefined-values/MATLAB/undefined-values-3.m new file mode 100644 index 0000000000..b5a9ebcd04 --- /dev/null +++ b/Task/Undefined-values/MATLAB/undefined-values-3.m @@ -0,0 +1 @@ + var = [1, 2, NaN, 0/0, inf-inf, 5] diff --git a/Task/Undefined-values/MATLAB/undefined-values-4.m b/Task/Undefined-values/MATLAB/undefined-values-4.m new file mode 100644 index 0000000000..df2b66ccd0 --- /dev/null +++ b/Task/Undefined-values/MATLAB/undefined-values-4.m @@ -0,0 +1 @@ + isnan(var) diff --git a/Task/Undefined-values/MUMPS/undefined-values.mumps b/Task/Undefined-values/MUMPS/undefined-values.mumps new file mode 100644 index 0000000000..6f1e6e7862 --- /dev/null +++ b/Task/Undefined-values/MUMPS/undefined-values.mumps @@ -0,0 +1,2 @@ + IF $DATA(SOMEVAR)=0 DO UNDEF ; A result of 0 means the value is undefined + SET LOCAL=$GET(^PATIENT(RECORDNUM,0)) ;If there isn't a defined item at that location, a null string is returned diff --git a/Task/Undefined-values/Mathematica/undefined-values-1.math b/Task/Undefined-values/Mathematica/undefined-values-1.math new file mode 100644 index 0000000000..ac4481fb03 --- /dev/null +++ b/Task/Undefined-values/Mathematica/undefined-values-1.math @@ -0,0 +1,14 @@ +a +-> a + +a + a +-> 2 a + +ValueQ[a] +-> False + +a = 5 +-> 5 + +ValueQ[a] +-> True diff --git a/Task/Undefined-values/Mathematica/undefined-values-2.math b/Task/Undefined-values/Mathematica/undefined-values-2.math new file mode 100644 index 0000000000..d806bd0aa6 --- /dev/null +++ b/Task/Undefined-values/Mathematica/undefined-values-2.math @@ -0,0 +1,2 @@ +ConditionalExpression[a, False] +->Undefined diff --git a/Task/Undefined-values/Mathematica/undefined-values-3.math b/Task/Undefined-values/Mathematica/undefined-values-3.math new file mode 100644 index 0000000000..7966172b51 --- /dev/null +++ b/Task/Undefined-values/Mathematica/undefined-values-3.math @@ -0,0 +1,2 @@ +Sin[Undefined] +-> Undefined diff --git a/Task/Undefined-values/Mathematica/undefined-values-4.math b/Task/Undefined-values/Mathematica/undefined-values-4.math new file mode 100644 index 0000000000..4bee0eaa1c --- /dev/null +++ b/Task/Undefined-values/Mathematica/undefined-values-4.math @@ -0,0 +1,8 @@ +a = Undefined +-> Undefined + +a +-> Undefined + +ValueQ[a] +-> True diff --git a/Task/Undefined-values/OCaml/undefined-values.ocaml b/Task/Undefined-values/OCaml/undefined-values.ocaml new file mode 100644 index 0000000000..a88c57e3f6 --- /dev/null +++ b/Task/Undefined-values/OCaml/undefined-values.ocaml @@ -0,0 +1,13 @@ +(* There is no undefined value in OCaml, + but if you really need this you can use the built-in "option" type. + It is defined like this: type 'a option = None | Some of 'a *) + +let inc = function + Some n -> Some (n+1) +| None -> failwith "Undefined argument";; + +inc (Some 0);; +(* - : value = Some 1 *) + +inc None;; +(* Exception: Failure "Undefined argument". *) diff --git a/Task/Undefined-values/Oz/undefined-values.oz b/Task/Undefined-values/Oz/undefined-values.oz new file mode 100644 index 0000000000..39ee6d254f --- /dev/null +++ b/Task/Undefined-values/Oz/undefined-values.oz @@ -0,0 +1,12 @@ +declare X in + +thread + if {IsFree X} then {System.showInfo "X is unbound."} end + {Wait X} + {System.showInfo "Now X is determined."} +end + +{System.showInfo "Sleeping..."} +{Delay 1000} +{System.showInfo "Setting X."} +X = 42 diff --git a/Task/Undefined-values/PARI-GP/undefined-values-1.pari b/Task/Undefined-values/PARI-GP/undefined-values-1.pari new file mode 100644 index 0000000000..d04d108ff9 --- /dev/null +++ b/Task/Undefined-values/PARI-GP/undefined-values-1.pari @@ -0,0 +1 @@ +v == 'v diff --git a/Task/Undefined-values/PARI-GP/undefined-values-2.pari b/Task/Undefined-values/PARI-GP/undefined-values-2.pari new file mode 100644 index 0000000000..a8e258f390 --- /dev/null +++ b/Task/Undefined-values/PARI-GP/undefined-values-2.pari @@ -0,0 +1 @@ +is_entry("v") == NULL; diff --git a/Task/Undefined-values/PHP/undefined-values.php b/Task/Undefined-values/PHP/undefined-values.php new file mode 100644 index 0000000000..167f84bcc2 --- /dev/null +++ b/Task/Undefined-values/PHP/undefined-values.php @@ -0,0 +1,33 @@ + diff --git a/Task/Undefined-values/Perl-6/undefined-values-1.pl6 b/Task/Undefined-values/Perl-6/undefined-values-1.pl6 new file mode 100644 index 0000000000..278424fa3a --- /dev/null +++ b/Task/Undefined-values/Perl-6/undefined-values-1.pl6 @@ -0,0 +1 @@ +my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any() diff --git a/Task/Undefined-values/Perl-6/undefined-values-2.pl6 b/Task/Undefined-values/Perl-6/undefined-values-2.pl6 new file mode 100644 index 0000000000..48cf20800c --- /dev/null +++ b/Task/Undefined-values/Perl-6/undefined-values-2.pl6 @@ -0,0 +1 @@ +say Method ~~ Routine; # Bool::True diff --git a/Task/Undefined-values/Perl-6/undefined-values-3.pl6 b/Task/Undefined-values/Perl-6/undefined-values-3.pl6 new file mode 100644 index 0000000000..408c7b5620 --- /dev/null +++ b/Task/Undefined-values/Perl-6/undefined-values-3.pl6 @@ -0,0 +1,3 @@ +my $x; say $x.WHAT; # Any() +my Int $y; say $y.WHAT; # Int() +my Str $z; say $z.WHAT; # Str() diff --git a/Task/Undefined-values/Perl/undefined-values.pl b/Task/Undefined-values/Perl/undefined-values.pl new file mode 100644 index 0000000000..72cdf7eb6f --- /dev/null +++ b/Task/Undefined-values/Perl/undefined-values.pl @@ -0,0 +1,35 @@ +#!/usr/bin/perl -w +use strict; + +# Declare the variable. It is initialized to the value "undef" +our $var; + +# Check to see whether it is defined +print "var contains an undefined value at first check\n" unless defined $var; + +# Give it a value +$var = "Chocolate"; + +# Check to see whether it is defined after we gave it the +# value "Chocolate" +print "var contains an undefined value at second check\n" unless defined $var; + +# Give the variable the value "undef". +$var = undef; +# or, equivalently: +undef($var); + +# Check to see whether it is defined after we've explicitly +# given it an undefined value. +print "var contains an undefined value at third check\n" unless defined $var; + +# Give the variable a value of 42 +$var = 42; + +# Check to see whether the it is defined after we've given it +# the value 42. +print "var contains an undefined value at fourth check\n" unless defined $var; + +# Because most of the output is conditional, this serves as +# a clear indicator that the program has run to completion. +print "Done\n"; diff --git a/Task/Undefined-values/PicoLisp/undefined-values-1.l b/Task/Undefined-values/PicoLisp/undefined-values-1.l new file mode 100644 index 0000000000..ba288101d2 --- /dev/null +++ b/Task/Undefined-values/PicoLisp/undefined-values-1.l @@ -0,0 +1,4 @@ +: (myfoo 3 4) +!? (myfoo 3 4) +myfoo -- Undefined +? diff --git a/Task/Undefined-values/PicoLisp/undefined-values-2.l b/Task/Undefined-values/PicoLisp/undefined-values-2.l new file mode 100644 index 0000000000..f39d285234 --- /dev/null +++ b/Task/Undefined-values/PicoLisp/undefined-values-2.l @@ -0,0 +1,14 @@ +: MyVar +-> NIL + +: (default MyVar 7) +-> 7 + +: MyVar +-> 7 + +: (default MyVar 8) +-> 7 + +: MyVar +-> 7 diff --git a/Task/Undefined-values/Pike/undefined-values.pike b/Task/Undefined-values/Pike/undefined-values.pike new file mode 100644 index 0000000000..cc99a381f2 --- /dev/null +++ b/Task/Undefined-values/Pike/undefined-values.pike @@ -0,0 +1,11 @@ +> zero_type(UNDEFINED); +Result: 1 +> mapping bar = ([ "foo":"hello" ]); +> zero_type(bar->foo); +Result: 0 +> zero_type(bar->baz); +Result: 1 +> bar->baz=UNDEFINED; +Result: 0 +> zero_type(bar->baz); +Result: 0 diff --git a/Task/Undefined-values/PureBasic/undefined-values.purebasic b/Task/Undefined-values/PureBasic/undefined-values.purebasic new file mode 100644 index 0000000000..e3510c7431 --- /dev/null +++ b/Task/Undefined-values/PureBasic/undefined-values.purebasic @@ -0,0 +1,21 @@ +If OpenConsole() + + CompilerIf Defined(var, #PB_Variable) + PrintN("var is defined at first check") + CompilerElse + PrintN("var is undefined at first check") + Define var + CompilerEndIf + + CompilerIf Defined(var, #PB_Variable) + PrintN("var is defined at second check") + CompilerElse + PrintN("var is undefined at second check") + Define var + CompilerEndIf + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() + +EndIf diff --git a/Task/Undefined-values/Python/undefined-values.py b/Task/Undefined-values/Python/undefined-values.py new file mode 100644 index 0000000000..cf622bdeb0 --- /dev/null +++ b/Task/Undefined-values/Python/undefined-values.py @@ -0,0 +1,28 @@ +# Check to see whether a name is defined +try: name +except NameError: print "name is undefined at first check" + +# Create a name, giving it a string value +name = "Chocolate" + +# Check to see whether the name is defined now. +try: name +except NameError: print "name is undefined at second check" + +# Remove the definition of the name. +del name + +# Check to see whether it is defined after the explicit removal. +try: name +except NameError: print "name is undefined at third check" + +# Recreate the name, giving it a value of 42 +name = 42 + +# Check to see whether the name is defined now. +try: name +except NameError: print "name is undefined at fourth check" + +# Because most of the output is conditional, this serves as +# a clear indicator that the program has run to completion. +print "Done" diff --git a/Task/Undefined-values/R/undefined-values-1.r b/Task/Undefined-values/R/undefined-values-1.r new file mode 100644 index 0000000000..c673beee54 --- /dev/null +++ b/Task/Undefined-values/R/undefined-values-1.r @@ -0,0 +1 @@ +exists("x") diff --git a/Task/Undefined-values/R/undefined-values-2.r b/Task/Undefined-values/R/undefined-values-2.r new file mode 100644 index 0000000000..fbacf755d1 --- /dev/null +++ b/Task/Undefined-values/R/undefined-values-2.r @@ -0,0 +1 @@ +x <- NULL diff --git a/Task/Undefined-values/R/undefined-values-3.r b/Task/Undefined-values/R/undefined-values-3.r new file mode 100644 index 0000000000..019f1f7fee --- /dev/null +++ b/Task/Undefined-values/R/undefined-values-3.r @@ -0,0 +1,2 @@ +y <- c(1, 4, 9, NA, 25) +z <- c("foo", NA, "baz") diff --git a/Task/Undefined-values/R/undefined-values-4.r b/Task/Undefined-values/R/undefined-values-4.r new file mode 100644 index 0000000000..dd2eb34111 --- /dev/null +++ b/Task/Undefined-values/R/undefined-values-4.r @@ -0,0 +1,7 @@ +print_is_missing <- function(x) +{ + print(missing(x)) +} + +print_is_missing() # TRUE +print_is_missing(123) # FALSE diff --git a/Task/Undefined-values/REXX/undefined-values.rexx b/Task/Undefined-values/REXX/undefined-values.rexx new file mode 100644 index 0000000000..86254fc5e8 --- /dev/null +++ b/Task/Undefined-values/REXX/undefined-values.rexx @@ -0,0 +1,23 @@ +/*REXX program to test if a variable is defined. */ + +tlaloc = "rain god of the Aztecs." + + + /*check if the rain god is defined.*/ +y='tlaloc' +if symbol(y)=="VAR" then say y 'is defined.' + else say y "ain't defined." + + + /*check if the fire god is defined.*/ + +y='xiuhtecuhtli' +if symbol(y)=="VAR" then say y 'is defined.' + else say y "ain't defined." + + +drop tlaloc /*un-define the TLALOC variable. */ + /*check if the rain god is defined.*/ +y='tlaloc' +if symbol(y)=="VAR" then say y 'is defined.' + else say y "ain't defined." diff --git a/Task/Undefined-values/Ruby/undefined-values.rb b/Task/Undefined-values/Ruby/undefined-values.rb new file mode 100644 index 0000000000..4d55f35f76 --- /dev/null +++ b/Task/Undefined-values/Ruby/undefined-values.rb @@ -0,0 +1,15 @@ +# Check to see whether it is defined +puts "var is undefined at first check" unless defined? var + +# Give it a value +var = "Chocolate" + +# Check to see whether it is defined after we gave it the +# value "Chocolate" +puts "var is undefined at second check" unless defined? var + +# I don't know any way of undefining a variable in Ruby + +# Because most of the output is conditional, this serves as +# a clear indicator that the program has run to completion. +puts "Done" diff --git a/Task/Undefined-values/Smalltalk/undefined-values.st b/Task/Undefined-values/Smalltalk/undefined-values.st new file mode 100644 index 0000000000..13f00e0d9a --- /dev/null +++ b/Task/Undefined-values/Smalltalk/undefined-values.st @@ -0,0 +1,2 @@ +Smalltalk includesKey: #FooBar +myNamespace includesKey: #Baz diff --git a/Task/Undefined-values/Tcl/undefined-values.tcl b/Task/Undefined-values/Tcl/undefined-values.tcl new file mode 100644 index 0000000000..353b966a4b --- /dev/null +++ b/Task/Undefined-values/Tcl/undefined-values.tcl @@ -0,0 +1,24 @@ +# Variables are undefined by default and do not need explicit declaration + +# Check to see whether it is defined +if {![info exists var]} {puts "var is undefind at first check"} + +# Give it a value +set var "Screwy Squirrel" + +# Check to see whether it is defined +if {![info exists var]} {puts "var is undefind at second check"} + +# Remove its value +unset var + +# Check to see whether it is defined +if {![info exists var]} {puts "var is undefind at third check"} + +# Give it a value again +set var 12345 + +# Check to see whether it is defined +if {![info exists var]} {puts "var is undefind at fourth check"} + +puts "Done" diff --git a/Task/Undefined-values/UNIX-Shell/undefined-values.sh b/Task/Undefined-values/UNIX-Shell/undefined-values.sh new file mode 100644 index 0000000000..8081e83a29 --- /dev/null +++ b/Task/Undefined-values/UNIX-Shell/undefined-values.sh @@ -0,0 +1,3 @@ +VAR1="VAR1" +echo ${VAR1:-"Not set."} +echo ${VAR2:-"Not set."} diff --git a/Task/Unicode-strings/0DESCRIPTION b/Task/Unicode-strings/0DESCRIPTION new file mode 100644 index 0000000000..809a04f125 --- /dev/null +++ b/Task/Unicode-strings/0DESCRIPTION @@ -0,0 +1,13 @@ +As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics: + +* How easy is it to present Unicode strings in source code? Can Unicode literals be written directly, or be part of identifiers/keywords/etc? +* How well can the language communicate with the rest of the world? Is it good at input/output with Unicode? +* Is it convenient to manipulate Unicode strings in the language? +* How broad/deep does the language support Unicode? What encodings (e.g. UTF-8, UTF-16, etc) can be used? Normalization? + +'''Note''' This task is a bit unusual in that it encourages general discussion rather than clever coding. + +See also: + +* [[Unicode variable names]] +* [[Terminal control/Display an extended character]] diff --git a/Task/Unicode-strings/ALGOL-68/unicode-strings.alg b/Task/Unicode-strings/ALGOL-68/unicode-strings.alg new file mode 100644 index 0000000000..28f369813c --- /dev/null +++ b/Task/Unicode-strings/ALGOL-68/unicode-strings.alg @@ -0,0 +1,301 @@ +#!/usr/local/bin/a68g --script # +# -*- coding: utf-8 -*- # + +# UNICHAR/UNICODE must be printed using REPR to convert to UTF8 # + +MODE UNICHAR = STRUCT(BITS #31# bits); # assuming bits width >=31 # +MODE UNICODE = FLEX[0]UNICHAR; + +OP INITUNICHAR = (BITS bits)UNICHAR: (UNICHAR out; bits OF out := #ABS# bits; out); +OP INITUNICHAR = (CHAR char)UNICHAR: (UNICHAR out; bits OF out := BIN ABS char; out); +OP INITBITS = (UNICHAR unichar)BITS: #BIN# bits OF unichar; + +PROC raise value error = ([]UNION(FORMAT,BITS,STRING)argv )VOID: ( + putf(stand error, argv); stop +); + +MODE YIELDCHAR = PROC(CHAR)VOID; MODE GENCHAR = PROC(YIELDCHAR)VOID; +MODE YIELDUNICHAR = PROC(UNICHAR)VOID; MODE GENUNICHAR = PROC(YIELDUNICHAR)VOID; + +PRIO DOCONV = 1; + +# Convert a stream of UNICHAR into a stream of UTFCHAR # +OP DOCONV = (GENUNICHAR gen unichar, YIELDCHAR yield)VOID:( + BITS non ascii = NOT 2r1111111; +# FOR UNICHAR unichar IN # gen unichar( # ) DO ( # +## (UNICHAR unichar)VOID: ( + BITS bits := INITBITS unichar; + IF (bits AND non ascii) = 2r0 THEN # ascii # + yield(REPR ABS bits) + ELSE + FLEX[6]CHAR buf := "?"*6; # initialise work around # + INT bytes := 0; + BITS byte lead bits = 2r10000000; + FOR ofs FROM UPB buf BY -1 WHILE + bytes +:= 1; + buf[ofs]:= REPR ABS (byte lead bits OR bits AND 2r111111); + bits := bits SHR 6; + # WHILE # bits NE 2r0 DO + SKIP + OD; + BITS first byte lead bits = BIN (ABS(2r1 SHL bytes)-2) SHL (UPB buf - bytes + 1); + buf := buf[UPB buf-bytes+1:]; + buf[1] := REPR ABS(BIN ABS buf[1] OR first byte lead bits); + FOR i TO UPB buf DO yield(buf[i]) OD + FI +# OD # )) +); + +# Convert a STRING into a stream of UNICHAR # +OP DOCONV = (STRING string, YIELDUNICHAR yield)VOID: ( + PROC gen char = (YIELDCHAR yield)VOID: + FOR i FROM LWB string TO UPB string DO yield(string[i]) OD; + gen char DOCONV yield +); + +CO Prosser/Thompson UTF8 encoding scheme +Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6 + 7 U+007F 0xxxxxxx +11 U+07FF 110xxxxx 10xxxxxx +16 U+FFFF 1110xxxx 10xxxxxx 10xxxxxx +21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx +26 U+3FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx +31 U+7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx +END CO + +# Quickly calculate the length of the UTF8 encoded string # +PROC upb utf8 = (STRING utf8 string)INT:( + INT bytes to go := 0; + INT upb := 0; + FOR i FROM LWB utf8 string TO UPB utf8 string DO + CHAR byte := utf8 string[i]; + IF bytes to go = 0 THEN # start new utf char # + bytes to go := + IF ABS byte <= ABS 2r01111111 THEN 1 # 7 bits # + ELIF ABS byte <= ABS 2r11011111 THEN 2 # 11 bits # + ELIF ABS byte <= ABS 2r11101111 THEN 3 # 16 bits # + ELIF ABS byte <= ABS 2r11110111 THEN 4 # 21 bits # + ELIF ABS byte <= ABS 2r11111011 THEN 5 # 26 bits # + ELIF ABS byte <= ABS 2r11111101 THEN 6 # 31 bits # + ELSE raise value error(("Invalid UTF-8 bytes", BIN ABS byte)); ~ FI + FI; + bytes to go -:= 1; # skip over trailing bytes # + IF bytes to go = 0 THEN upb +:= 1 FI + OD; + upb +); + +# Convert a stream of CHAR into a stream of UNICHAR # +OP DOCONV = (GENCHAR gen char, YIELDUNICHAR yield)VOID: ( + INT bytes to go := 0; + INT lshift; + BITS mask, out; + + # FOR CHAR byte IN # gen char( # ) DO ( # + ## (CHAR byte)VOID: ( + INT bits := ABS byte; + IF bytes to go = 0 THEN # start new unichar # + bytes to go := + IF bits <= ABS 2r01111111 THEN 1 # 7 bits # + ELIF bits <= ABS 2r11011111 THEN 2 # 11 bits # + ELIF bits <= ABS 2r11101111 THEN 3 # 16 bits # + ELIF bits <= ABS 2r11110111 THEN 4 # 21 bits # + ELIF bits <= ABS 2r11111011 THEN 5 # 26 bits # + ELIF bits <= ABS 2r11111101 THEN 6 # 31 bits # + ELSE raise value error(("Invalid UTF-8 bytes", BIN bits)); ~ FI; + IF bytes to go = 1 THEN + lshift := 7; mask := 2r1111111 + ELSE + lshift := 7 - bytes to go; mask := BIN(ABS(2r1 SHL lshift)-1) + FI; + out := mask AND BIN bits; + + lshift := 6; mask := 2r111111 # subsequently pic 6 bits at a time # + ELSE + out := (out SHL lshift) OR ( mask AND BIN bits) + FI; + bytes to go -:= 1; + IF bytes to go = 0 THEN yield(INITUNICHAR out) FI + # OD # )) +); + +# Convert a string of UNICHAR into a stream of UTFCHAR # +OP DOCONV = (UNICODE unicode, YIELDCHAR yield)VOID:( + PROC gen unichar = (YIELDUNICHAR yield)VOID: + FOR i FROM LWB unicode TO UPB unicode DO yield(unicode[i]) OD; + gen unichar DOCONV yield +); + +# Some convenience/shorthand U operators # +# Convert a BITS into a UNICODE char # +OP U = (BITS bits)UNICHAR: + INITUNICHAR bits; + +# Convert a []BITS into a UNICODE char # +OP U = ([]BITS array bits)[]UNICHAR:( + [LWB array bits:UPB array bits]UNICHAR out; + FOR i FROM LWB array bits TO UPB array bits DO bits OF out[i]:=array bits[i] OD; + out +); + +# Convert a CHAR into a UNICODE char # +OP U = (CHAR char)UNICHAR: + INITUNICHAR char; + +# Convert a STRING into a UNICODE string # +OP U = (STRING utf8 string)UNICODE: ( + FLEX[upb utf8(utf8 string)]UNICHAR out; + INT i := 0; +# FOR UNICHAR char IN # utf8 string DOCONV ( +## (UNICHAR char)VOID: + out[i+:=1] := char +# OD #); + out +); + +# Convert a UNICODE string into a UTF8 STRING # +OP REPR = (UNICODE string)STRING: ( + STRING out; +# FOR CHAR char IN # string DOCONV ( +## (CHAR char)VOID: ( + out +:= char +# OD #)); + out +); + +# define the most useful OPerators on UNICODE CHARacter arrays # +# Note: LWB, UPB and slicing works as per normal # + +OP + = (UNICODE a,b)UNICODE: ( + [UPB a + UPB b]UNICHAR out; + out[:UPB a]:= a; out[UPB a+1:]:= b; + out +); + +OP + = (UNICODE a, UNICHAR b)UNICODE: a+UNICODE(b); +OP + = (UNICHAR a, UNICODE b)UNICODE: UNICODE(a)+b; +OP + = (UNICHAR a,b)UNICODE: UNICODE(a)+b; + +# Suffix a character to the end of a UNICODE string # +OP +:= = (REF UNICODE a, UNICODE b)VOID: a := a + b; +OP +:= = (REF UNICODE a, UNICHAR b)VOID: a := a + b; + +# Prefix a character to the beginning of a UNICODE string # +OP +=: = (UNICODE b, REF UNICODE a)VOID: a := b + a; +OP +=: = (UNICHAR b, REF UNICODE a)VOID: a := b + a; + +OP * = (UNICODE a, INT n)UNICODE: ( + UNICODE out := a; + FOR i FROM 2 TO n DO out +:= a OD; + out +); +OP * = (INT n, UNICODE a)UNICODE: a * n; + +OP * = (UNICHAR a, INT n)UNICODE: UNICODE(a)*n; +OP * = (INT n, UNICHAR a)UNICODE: n*UNICODE(a); + +OP *:= = (REF UNICODE a, INT b)VOID: a := a * b; + +# Wirthy Operators # +OP LT = (UNICHAR a,b)BOOL: ABS bits OF a LT ABS bits OF b, + LE = (UNICHAR a,b)BOOL: ABS bits OF a LE ABS bits OF b, + EQ = (UNICHAR a,b)BOOL: ABS bits OF a EQ ABS bits OF b, + NE = (UNICHAR a,b)BOOL: ABS bits OF a NE ABS bits OF b, + GE = (UNICHAR a,b)BOOL: ABS bits OF a GE ABS bits OF b, + GT = (UNICHAR a,b)BOOL: ABS bits OF a GT ABS bits OF b; + +# ASCII OPerators # +OP < = (UNICHAR a,b)BOOL: a LT b, + <= = (UNICHAR a,b)BOOL: a LE b, + = = (UNICHAR a,b)BOOL: a EQ b, + /= = (UNICHAR a,b)BOOL: a NE b, + >= = (UNICHAR a,b)BOOL: a GE b, + > = (UNICHAR a,b)BOOL: a GT b; + +# Non ASCII OPerators +OP ≤ = (UNICHAR a,b)BOOL: a LE b, + ≠ = (UNICHAR a,b)BOOL: a NE b, + ≥ = (UNICHAR a,b)BOOL: a GE b; +# + +# Compare two UNICODE strings for equality # +PROC unicode cmp = (UNICODE str a,str b)INT: ( + + IF LWB str a > LWB str b THEN exit lt ELIF LWB str a < LWB str b THEN exit gt FI; + + INT min upb = UPB(UPB str a < UPB str b | str a | str b ); + + FOR i FROM LWB str a TO min upb DO + UNICHAR a := str a[i], UNICHAR b := str b[i]; + IF a < b THEN exit lt ELIF a > b THEN exit gt FI + OD; + + IF UPB str a > UPB str b THEN exit gt ELIF UPB str a < UPB str b THEN exit lt FI; + + exit eq: 0 EXIT + exit lt: -1 EXIT + exit gt: 1 +); + +OP LT = (UNICODE a,b)BOOL: unicode cmp(a,b)< 0, + LE = (UNICODE a,b)BOOL: unicode cmp(a,b)<=0, + EQ = (UNICODE a,b)BOOL: unicode cmp(a,b) =0, + NE = (UNICODE a,b)BOOL: unicode cmp(a,b)/=0, + GE = (UNICODE a,b)BOOL: unicode cmp(a,b)>=0, + GT = (UNICODE a,b)BOOL: unicode cmp(a,b)> 0; + +# ASCII OPerators # +OP < = (UNICODE a,b)BOOL: a LT b, + <= = (UNICODE a,b)BOOL: a LE b, + = = (UNICODE a,b)BOOL: a EQ b, + /= = (UNICODE a,b)BOOL: a NE b, + >= = (UNICODE a,b)BOOL: a GE b, + > = (UNICODE a,b)BOOL: a GT b; + +# Non ASCII OPerators +OP ≤ = (UNICODE a,b)BOOL: a LE b, + ≠ = (UNICODE a,b)BOOL: a NE b, + ≥ = (UNICODE a,b)BOOL: a GE b; +# + +COMMENT - Todo: for all UNICODE and UNICHAR + Add NonASCII OPerators: ×, ×:=, + Add ASCII Operators: &, &:=, &=: + Add Wirthy OPerators: PLUSTO, PLUSAB, TIMESAB for UNICODE/UNICHAR, + Add UNICODE against UNICHAR comparison OPerators, + Add char_in_string and string_in_string PROCedures, + Add standard Unicode functions: + to_upper_case, to_lower_case, unicode_block, char_count, + get_directionality, get_numeric_value, get_type, is_defined, + is_digit, is_identifier_ignorable, is_iso_control, + is_letter, is_letter_or_digit, is_lower_case, is_mirrored, + is_space_char, is_supplementary_code_point, is_title_case, + is_unicode_identifier_part, is_unicode_identifier_start, + is_upper_case, is_valid_code_point, is_whitespace +END COMMENT + +test:( + + UNICHAR aircraft := U16r 2708; + printf(($"aircraft: "$, $"16r"16rdddd$, UNICODE(aircraft), $g$, " => ", REPR UNICODE(aircraft), $l$)); + + UNICODE chinese forty two = U16r 56db + U16r 5341 + U16r 4e8c; + printf(($"chinese forty two: "$, $g$, REPR chinese forty two, ", length string = ", UPB chinese forty two, $l$)); + + UNICODE poker = U "A123456789♥♦♣♠JQK"; + printf(($"poker: "$, $g$, REPR poker, ", length string = ", UPB poker, $l$)); + + UNICODE selectric := U"×÷≤≥≠¬∨∧⏨→↓↑□⌊⌈⎩⎧○⊥¢"; + printf(($"selectric: "$, $g$, REPR selectric, $l$)); + printf(($"selectric*4: "$, $g$, REPR(selectric*4), $l$)); + + print(( + "1 < 2 is ", U"1" < U"2", ", ", + "111 < 11 is ",U"111" < U"11", ", ", + "111 < 12 is ",U"111" < U"12", ", ", + "♥ < ♦ is ", U"♥" < U"♦", ", ", + "♥Q < ♥K is ",U"♥Q" < U"♥K", " & ", + "♥J < ♥K is ",U"♥J" < U"♥K", new line + )) + +) diff --git a/Task/Unicode-strings/BBC-BASIC/unicode-strings.bbc b/Task/Unicode-strings/BBC-BASIC/unicode-strings.bbc new file mode 100644 index 0000000000..c114c61fff --- /dev/null +++ b/Task/Unicode-strings/BBC-BASIC/unicode-strings.bbc @@ -0,0 +1,58 @@ + VDU 23,22,640;512;8,16,16,128+8 : REM Select UTF-8 mode + *FONT Times New Roman, 20 + + PRINT "Arabic:" + + arabic1$ = "هنا مثال يمكنك من الكتابة من اليمين" + arabic2$ = "الى اليسار باللغة العربية" + + VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing + PRINT FNarabic(arabic1$) ' FNarabic(arabic2$) + VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing + + PRINT '"Hebrew:" + + hebrew$ = "זוהי הדגמה של כתיבת טקסט בעברית מימין לשמאל" + + VDU 23,16,2;0;0;0;13 : REM Select right-to-left printing + PRINT hebrew$ + VDU 23,16,0;0;0;0;13 : REM Select left-to-right printing + + END + + REM!Eject + DEF FNarabic(A$) + LOCAL A%, B%, L%, O%, P%, U%, B$ + A$ += CHR$0 + FOR A% = !^A$ TO !^A$+LENA$-1 + IF ?A%<&80 OR ?A%>=&C0 THEN + L% = O% : O% = P% : P% = U% + U% = ((?A% AND &3F) << 6) + (A%?1 AND &3F) + IF ?A%<&80 U% = 0 + CASE TRUE OF + WHEN U%=&60C OR U%=&61F: U% = 0 + WHEN U%<&622: + WHEN U%<&626: U% = &01+2*(U%-&622) + WHEN U%<&628: U% = &09+4*(U%-&626) + WHEN U%<&62A: U% = &0F+4*(U%-&628) + WHEN U%<&62F: U% = &15+4*(U%-&62A) + WHEN U%<&633: U% = &29+2*(U%-&62F) + WHEN U%<&63B: U% = &31+4*(U%-&633) + WHEN U%<&641: + WHEN U%<&648: U% = &51+4*(U%-&641) + WHEN U%<&64B: U% = &6D+2*(U%-&648) + ENDCASE + IF P% IF P%<&80 THEN + B% = P% + IF O%=&5D IF P%<&5 B% += &74 + IF O%=&5D IF P%=&7 B% += &72 + IF O%=&5D IF P%=&D B% += &6E + IF B%>P% B$=LEFT$(B$,LENB$-3) : O% = L% + IF U% IF P%>7 IF P%<>&D IF P%<>&13 IF P%<>&29 IF P%<>&2B IF P%<>&2D IF P%<>&2F IF P%<>&6D IF P%<>&6F B% += 2 + IF O% IF O%>7 IF O%<>&D IF O%<>&13 IF O%<>&29 IF O%<>&2B IF O%<>&2D IF O%<>&2F IF O%<>&6D IF O%<>&6F B% += 1 + B$ = LEFT$(LEFT$(B$))+CHR$&EF+CHR$(&BA+(B%>>6))+CHR$(&80+(B%AND&3F)) + ENDIF + ENDIF + B$ += CHR$?A% + NEXT + = LEFT$(B$) diff --git a/Task/Unicode-strings/C/unicode-strings.c b/Task/Unicode-strings/C/unicode-strings.c new file mode 100644 index 0000000000..d24f9d6f47 --- /dev/null +++ b/Task/Unicode-strings/C/unicode-strings.c @@ -0,0 +1,30 @@ +#include +#include +#include + +/* wchar_t is the standard type for wide chars; what it is internally + * depends on the compiler. + */ +wchar_t poker[] = L"♥♦♣♠"; +wchar_t four_two[] = L"\x56db\x5341\x4e8c"; + +int main() { + /* Set the locale to alert C's multibyte output routines */ + if (!setlocale(LC_CTYPE, "")) { + fprintf(stderr, "Locale failure, check your env vars\n"); + return 1; + } + +#ifdef __STDC_ISO_10646__ + /* C99 compilers should understand these */ + printf("%lc\n", 0x2708); /* ✈ */ + printf("%ls\n", poker); /* ♥♦♣♠ */ + printf("%ls\n", four_two); /* 四十二 */ +#else + /* oh well */ + printf("airplane\n"); + printf("club diamond club spade\n"); + printf("for ty two\n"); +#endif + return 0; +} diff --git a/Task/Unicode-strings/Go/unicode-strings-1.go b/Task/Unicode-strings/Go/unicode-strings-1.go new file mode 100644 index 0000000000..9bab55ecd5 --- /dev/null +++ b/Task/Unicode-strings/Go/unicode-strings-1.go @@ -0,0 +1,5 @@ + var i int + var u rune + for i, u = range "voilà" { + fmt.Println(i, u) + } diff --git a/Task/Unicode-strings/Go/unicode-strings-2.go b/Task/Unicode-strings/Go/unicode-strings-2.go new file mode 100644 index 0000000000..b62d8a7557 --- /dev/null +++ b/Task/Unicode-strings/Go/unicode-strings-2.go @@ -0,0 +1,4 @@ + w := "voilà" + for i := 0; i < len(w); i++ { + fmt.Println(i, w[i]) + } diff --git a/Task/Unicode-strings/J/unicode-strings-1.j b/Task/Unicode-strings/J/unicode-strings-1.j new file mode 100644 index 0000000000..9a5e08e351 --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-1.j @@ -0,0 +1,2 @@ + '♥♦♣♠' +♥♦♣♠ diff --git a/Task/Unicode-strings/J/unicode-strings-2.j b/Task/Unicode-strings/J/unicode-strings-2.j new file mode 100644 index 0000000000..dcc5102b80 --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-2.j @@ -0,0 +1,2 @@ + #'♥♦♣♠' +12 diff --git a/Task/Unicode-strings/J/unicode-strings-3.j b/Task/Unicode-strings/J/unicode-strings-3.j new file mode 100644 index 0000000000..43f129ce0b --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-3.j @@ -0,0 +1,4 @@ + 7 u:'♥♦♣♠' +♥♦♣♠ + #7 u:'♥♦♣♠' +4 diff --git a/Task/Unicode-strings/J/unicode-strings-4.j b/Task/Unicode-strings/J/unicode-strings-4.j new file mode 100644 index 0000000000..274e31ebf0 --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-4.j @@ -0,0 +1,2 @@ + '♥♦♣♠' -: 7 u:'♥♦♣♠' +0 diff --git a/Task/Unicode-strings/J/unicode-strings-5.j b/Task/Unicode-strings/J/unicode-strings-5.j new file mode 100644 index 0000000000..00efc598ec --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-5.j @@ -0,0 +1,2 @@ + 'abcd'-:7 u:'abcd' +1 diff --git a/Task/Unicode-strings/J/unicode-strings-6.j b/Task/Unicode-strings/J/unicode-strings-6.j new file mode 100644 index 0000000000..d4a5c1aa18 --- /dev/null +++ b/Task/Unicode-strings/J/unicode-strings-6.j @@ -0,0 +1,4 @@ + '♥♦♣♠' -:&(7&u:) 7 u:'♥♦♣♠' +1 + '♥♦♣♠' -:&(8&u:) 7 u:'♥♦♣♠' +1 diff --git a/Task/Unicode-strings/Locomotive-Basic/unicode-strings.locomotive b/Task/Unicode-strings/Locomotive-Basic/unicode-strings.locomotive new file mode 100644 index 0000000000..ee321a293f --- /dev/null +++ b/Task/Unicode-strings/Locomotive-Basic/unicode-strings.locomotive @@ -0,0 +1,22 @@ +10 CLS:DEFINT a-z +20 ' define German umlauts as in Latin-1 +30 SYMBOL AFTER 196 +40 SYMBOL 196,&66,&18,&3C,&66,&7E,&66,&66,&0 +50 SYMBOL 214,&C6,&0,&7C,&C6,&C6,&C6,&7C,&0 +60 SYMBOL 220,&66,&0,&66,&66,&66,&66,&3C,&0 +70 SYMBOL 228,&6C,&0,&78,&C,&7C,&CC,&76,&0 +80 SYMBOL 246,&66,&0,&0,&3C,&66,&66,&3C,&0 +90 SYMBOL 252,&66,&0,&0,&66,&66,&66,&3E,&0 +100 SYMBOL 223,&38,&6C,&6C,&78,&6C,&78,&60,&0 +110 ' print string +120 READ h +130 IF h=0 THEN 180 +140 IF (h AND &X11100000)=&X11000000 THEN uc=(h AND &X11111)*2^6:GOTO 120 +150 IF (h AND &X11000000)=&X10000000 THEN uc=uc+(h AND &X111111):h=uc +160 PRINT CHR$(h); +170 GOTO 120 +180 PRINT +190 END +200 ' zero-terminated UTF-8 string +210 DATA &48,&C3,&A4,&6C,&6C,&C3,&B6,&20,&4C,&C3,&BC,&64,&77,&69,&67,&2E,&20,&C3,&84,&C3,&96,&C3,&9C +220 DATA &20,&C3,&A4,&C3,&B6,&C3,&BC,&20,&56,&69,&65,&6C,&65,&20,&47,&72,&C3,&BC,&C3,&9F,&65,&21,&00 diff --git a/Task/Unicode-strings/Perl-6/unicode-strings.pl6 b/Task/Unicode-strings/Perl-6/unicode-strings.pl6 new file mode 100644 index 0000000000..ba5df5c319 --- /dev/null +++ b/Task/Unicode-strings/Perl-6/unicode-strings.pl6 @@ -0,0 +1,2 @@ +sub prefix:<∛> ($𝕏) { $𝕏 ** (1/3) } +say ∛27; # prints 3 diff --git a/Task/Unicode-strings/Perl/unicode-strings-1.pl b/Task/Unicode-strings/Perl/unicode-strings-1.pl new file mode 100644 index 0000000000..cea7e418ef --- /dev/null +++ b/Task/Unicode-strings/Perl/unicode-strings-1.pl @@ -0,0 +1 @@ +use utf8; diff --git a/Task/Unicode-strings/Perl/unicode-strings-2.pl b/Task/Unicode-strings/Perl/unicode-strings-2.pl new file mode 100644 index 0000000000..5b9bafa4c5 --- /dev/null +++ b/Task/Unicode-strings/Perl/unicode-strings-2.pl @@ -0,0 +1,3 @@ +$四十二 = "voilà"; +print "$四十二"; # voilà +print uc($四十二); # VOILÀ diff --git a/Task/Unicode-strings/Perl/unicode-strings-3.pl b/Task/Unicode-strings/Perl/unicode-strings-3.pl new file mode 100644 index 0000000000..c87bf4c984 --- /dev/null +++ b/Task/Unicode-strings/Perl/unicode-strings-3.pl @@ -0,0 +1,4 @@ +use charnames qw(greek); +$x = "\N{sigma} \U\N{sigma}"; +$y = "\x{2708}"; +print scalar reverse("$x $y"); # ✈ Σ σ diff --git a/Task/Unicode-strings/Perl/unicode-strings-4.pl b/Task/Unicode-strings/Perl/unicode-strings-4.pl new file mode 100644 index 0000000000..40d8cafd96 --- /dev/null +++ b/Task/Unicode-strings/Perl/unicode-strings-4.pl @@ -0,0 +1 @@ +print "Say עִבְרִית" =~ /(\p{BidiClass:R})/g; # עברית diff --git a/Task/Unicode-strings/Perl/unicode-strings-5.pl b/Task/Unicode-strings/Perl/unicode-strings-5.pl new file mode 100644 index 0000000000..9e5c33a3e3 --- /dev/null +++ b/Task/Unicode-strings/Perl/unicode-strings-5.pl @@ -0,0 +1,2 @@ +open IN, "<:utf8", "file_utf"; +open OUT, ">:raw", "file_byte"; diff --git a/Task/Unicode-strings/PicoLisp/unicode-strings.l b/Task/Unicode-strings/PicoLisp/unicode-strings.l new file mode 100644 index 0000000000..01f2106b6e --- /dev/null +++ b/Task/Unicode-strings/PicoLisp/unicode-strings.l @@ -0,0 +1 @@ +(in '(iconv "-f" "ISO-8859-15" "file.txt") (line)) diff --git a/Task/Unicode-strings/Python/unicode-strings.py b/Task/Unicode-strings/Python/unicode-strings.py new file mode 100644 index 0000000000..fd8dfe804f --- /dev/null +++ b/Task/Unicode-strings/Python/unicode-strings.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python +# -*- coding: latin-1 -*- + +u = 'abcdé' +print(ord(u[-1])) diff --git a/Task/Unicode-strings/TXR/unicode-strings.txr b/Task/Unicode-strings/TXR/unicode-strings.txr new file mode 100644 index 0000000000..e021f713f3 --- /dev/null +++ b/Task/Unicode-strings/TXR/unicode-strings.txr @@ -0,0 +1,3 @@ +@{TITLE /[あ-ん一-耙]+/} (@ROMAJI/@ENGLISH) +@(freeform) +@(coll)@{STANZA /[^\n\x3000 ]+/}@(end)@/.*/ diff --git a/Task/Unicode-variable-names/0DESCRIPTION b/Task/Unicode-variable-names/0DESCRIPTION new file mode 100644 index 0000000000..ca392f6ba9 --- /dev/null +++ b/Task/Unicode-variable-names/0DESCRIPTION @@ -0,0 +1,9 @@ +{{omit from|BBC BASIC}} +# Describe, and give a pointer to documentation on your languages use of characters ''beyond'' those of the ASCII character set in the naming of variables. +# Show how to: +:* Set a variable with a name including the 'Δ', (delta ''character''), to 1 +:* Increment it +:* Print its value. + +;Cf.: +* [[Case-sensitivity of identifiers]] diff --git a/Task/Unicode-variable-names/1META.yaml b/Task/Unicode-variable-names/1META.yaml new file mode 100644 index 0000000000..cc284fe80a --- /dev/null +++ b/Task/Unicode-variable-names/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Unicode diff --git a/Task/Unicode-variable-names/ACL2/unicode-variable-names.acl2 b/Task/Unicode-variable-names/ACL2/unicode-variable-names.acl2 new file mode 100644 index 0000000000..6d12a28837 --- /dev/null +++ b/Task/Unicode-variable-names/ACL2/unicode-variable-names.acl2 @@ -0,0 +1,2 @@ +(let ((Δ 1)) + (1+ Δ)) diff --git a/Task/Unicode-variable-names/Ada/unicode-variable-names.ada b/Task/Unicode-variable-names/Ada/unicode-variable-names.ada new file mode 100644 index 0000000000..e98ea6c2a1 --- /dev/null +++ b/Task/Unicode-variable-names/Ada/unicode-variable-names.ada @@ -0,0 +1,8 @@ +with Ada.Text_IO; +procedure main is + Δ : Integer; +begin + Δ := 41; + Δ := Δ + 1; + Ada.Text_IO.Put_Line (Δ'Img); +end main; diff --git a/Task/Unicode-variable-names/AutoHotkey/unicode-variable-names.ahk b/Task/Unicode-variable-names/AutoHotkey/unicode-variable-names.ahk new file mode 100644 index 0000000000..6f5e34e3f2 --- /dev/null +++ b/Task/Unicode-variable-names/AutoHotkey/unicode-variable-names.ahk @@ -0,0 +1,3 @@ +Δ = 1 +Δ++ +MsgBox, % Δ diff --git a/Task/Unicode-variable-names/Common-Lisp/unicode-variable-names.lisp b/Task/Unicode-variable-names/Common-Lisp/unicode-variable-names.lisp new file mode 100644 index 0000000000..6f3d1ab21c --- /dev/null +++ b/Task/Unicode-variable-names/Common-Lisp/unicode-variable-names.lisp @@ -0,0 +1,2 @@ +(let ((Δ 1)) + (incf Δ)) diff --git a/Task/Unicode-variable-names/D/unicode-variable-names.d b/Task/Unicode-variable-names/D/unicode-variable-names.d new file mode 100644 index 0000000000..ca62d23749 --- /dev/null +++ b/Task/Unicode-variable-names/D/unicode-variable-names.d @@ -0,0 +1,7 @@ +import std.stdio; + +void main() { + auto Δ = 1; + Δ++; + writeln(Δ); +} diff --git a/Task/Unicode-variable-names/DWScript/unicode-variable-names.dwscript b/Task/Unicode-variable-names/DWScript/unicode-variable-names.dwscript new file mode 100644 index 0000000000..86f29662b5 --- /dev/null +++ b/Task/Unicode-variable-names/DWScript/unicode-variable-names.dwscript @@ -0,0 +1,5 @@ +var Δ : Integer; + +Δ := 1; +Inc(Δ); +PrintLn(Δ); diff --git a/Task/Unicode-variable-names/Delphi/unicode-variable-names.delphi b/Task/Unicode-variable-names/Delphi/unicode-variable-names.delphi new file mode 100644 index 0000000000..86b63a8b3a --- /dev/null +++ b/Task/Unicode-variable-names/Delphi/unicode-variable-names.delphi @@ -0,0 +1,17 @@ +(* Compiled with Delphi XE *) +program UnicodeVariableName; + +{$APPTYPE CONSOLE} + +uses + SysUtils; + +var + Δ: Integer; + +begin + Δ:= 1; + Inc(Δ); + Writeln(Δ); + Readln; +end. diff --git a/Task/Unicode-variable-names/Forth/unicode-variable-names.fth b/Task/Unicode-variable-names/Forth/unicode-variable-names.fth new file mode 100644 index 0000000000..b947eb1b5f --- /dev/null +++ b/Task/Unicode-variable-names/Forth/unicode-variable-names.fth @@ -0,0 +1,3 @@ +variable ∆ +5 ∆ ! +∆ @ . diff --git a/Task/Unicode-variable-names/Go/unicode-variable-names.go b/Task/Unicode-variable-names/Go/unicode-variable-names.go new file mode 100644 index 0000000000..bd883c0c79 --- /dev/null +++ b/Task/Unicode-variable-names/Go/unicode-variable-names.go @@ -0,0 +1,9 @@ +package main + +import "fmt" + +func main() { + Δ := 1 + Δ++ + fmt.Println(Δ) +} diff --git a/Task/Unicode-variable-names/Haskell/unicode-variable-names.hs b/Task/Unicode-variable-names/Haskell/unicode-variable-names.hs new file mode 100644 index 0000000000..8bcc9ee04e --- /dev/null +++ b/Task/Unicode-variable-names/Haskell/unicode-variable-names.hs @@ -0,0 +1,3 @@ +main = print ψ + where δΔ = 1 + ψ = δΔ + 1 diff --git a/Task/Unicode-variable-names/Java/unicode-variable-names.java b/Task/Unicode-variable-names/Java/unicode-variable-names.java new file mode 100644 index 0000000000..610dc90169 --- /dev/null +++ b/Task/Unicode-variable-names/Java/unicode-variable-names.java @@ -0,0 +1,5 @@ +int Δ = 1; +double π = 3.141592; +String 你好 = "hello"; +Δ++; +System.out.println(Δ); diff --git a/Task/Unicode-variable-names/LOLCODE/unicode-variable-names.lol b/Task/Unicode-variable-names/LOLCODE/unicode-variable-names.lol new file mode 100644 index 0000000000..c532a1d9df --- /dev/null +++ b/Task/Unicode-variable-names/LOLCODE/unicode-variable-names.lol @@ -0,0 +1,3 @@ +I HAS A SRS "Δ" ITZ 1 +SRS "Δ" R SUM OF SRS ":(394)" AN 1 +VISIBLE SRS ":[GREEK CAPITAL LETTER DELTA]" diff --git a/Task/Unicode-variable-names/Lua/unicode-variable-names.lua b/Task/Unicode-variable-names/Lua/unicode-variable-names.lua new file mode 100644 index 0000000000..a5b2309910 --- /dev/null +++ b/Task/Unicode-variable-names/Lua/unicode-variable-names.lua @@ -0,0 +1,9 @@ +local unicode = {} +unicode["Für"] = "for" +print(unicode["Für"]) + +unicode["garçon"] = "boy" +print(unicode["garçon"]) + +unicode["∆"]=1 +print(unicode["∆"]) diff --git a/Task/Unicode-variable-names/Mathematica/unicode-variable-names.math b/Task/Unicode-variable-names/Mathematica/unicode-variable-names.math new file mode 100644 index 0000000000..2b98881e49 --- /dev/null +++ b/Task/Unicode-variable-names/Mathematica/unicode-variable-names.math @@ -0,0 +1,3 @@ +Δ = 1; +Δ++; +Print[Δ] diff --git a/Task/Unicode-variable-names/NetRexx/unicode-variable-names.netrexx b/Task/Unicode-variable-names/NetRexx/unicode-variable-names.netrexx new file mode 100644 index 0000000000..0c2e4007b9 --- /dev/null +++ b/Task/Unicode-variable-names/NetRexx/unicode-variable-names.netrexx @@ -0,0 +1,33 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +upperΔ = 1 +Δupper = upperΔ +lowerδ = 2 +δlower = lowerδ + +say upperΔ '+' Δupper '= \-' +upperΔ = upperΔ + Δupper +say upperΔ + +say lowerδ '+' δlower '= \-' +lowerδ = lowerδ + δlower +say lowerδ +say + +-- Unicode works with the NetRexx built-in functions +Υππερ = '\u0391'.sequence('\u03a1') || '\u03a3'.sequence('\u03a9') -- ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ +Λοωερ = '\u03b1'.sequence('\u03c1') || '\u03c3'.sequence('\u03c9') -- αβγδεζηθικλμνξοπρστυφχψω +say Υππερ'.Lower =' Υππερ.lower() +say Λοωερ'.Upper =' Λοωερ.upper() +say + +-- Note: Even with unicode characters NetRexx variables are case-insensitive +numeric digits 12 +δ = 20.0 +π = Math.PI +θ = Π * Δ +σ = Θ ** 2 / (Π * 4) -- == Π * (Δ / 2) ** 2 +say 'Π =' π', diameter =' δ', circumference =' Θ', area =' Σ + +return diff --git a/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod b/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod new file mode 100644 index 0000000000..90f18dc334 --- /dev/null +++ b/Task/Unicode-variable-names/Nimrod/unicode-variable-names.nimrod @@ -0,0 +1,3 @@ +var Δ = 1 +Δ.inc() +echo(Δ) diff --git a/Task/Unicode-variable-names/PHP/unicode-variable-names.php b/Task/Unicode-variable-names/PHP/unicode-variable-names.php new file mode 100644 index 0000000000..eaf8beb48c --- /dev/null +++ b/Task/Unicode-variable-names/PHP/unicode-variable-names.php @@ -0,0 +1,4 @@ +($degrees) { $degrees * π / 180 }; + +for @ᐁ -> $ಠ_ಠ { say sin $ಠ_ಠ° }; diff --git a/Task/Unicode-variable-names/Perl/unicode-variable-names.pl b/Task/Unicode-variable-names/Perl/unicode-variable-names.pl new file mode 100644 index 0000000000..6f295938da --- /dev/null +++ b/Task/Unicode-variable-names/Perl/unicode-variable-names.pl @@ -0,0 +1,4 @@ +use utf8; +my $Δ = 1; +$Δ++; +print $Δ; diff --git a/Task/Unicode-variable-names/PicoLisp/unicode-variable-names.l b/Task/Unicode-variable-names/PicoLisp/unicode-variable-names.l new file mode 100644 index 0000000000..b655a9118d --- /dev/null +++ b/Task/Unicode-variable-names/PicoLisp/unicode-variable-names.l @@ -0,0 +1,8 @@ +: (setq Δ 1) +-> 1 +: Δ +-> 1 +: (inc 'Δ) +-> 2 +: Δ +-> 2 diff --git a/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium b/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium new file mode 100644 index 0000000000..20b99e6665 --- /dev/null +++ b/Task/Unicode-variable-names/Protium/unicode-variable-names-1.protium @@ -0,0 +1,3 @@ +<@ LETVARLIT>Δ|1 +<@ ACTICRVAR>Δ +<@ SAYVAR>Δ diff --git a/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium b/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium new file mode 100644 index 0000000000..504503f553 --- /dev/null +++ b/Task/Unicode-variable-names/Protium/unicode-variable-names-2.protium @@ -0,0 +1,3 @@ +<@ LETVARLIT>三角洲|1 +<@ ACTICRVAR>三角洲 +<@ SAYVAR>三角洲 diff --git a/Task/Unicode-variable-names/Python/unicode-variable-names.py b/Task/Unicode-variable-names/Python/unicode-variable-names.py new file mode 100644 index 0000000000..320a887172 --- /dev/null +++ b/Task/Unicode-variable-names/Python/unicode-variable-names.py @@ -0,0 +1,5 @@ +>>> Δx = 1 +>>> Δx += 1 +>>> print(Δx) +2 +>>> diff --git a/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt b/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt new file mode 100644 index 0000000000..81c49bd693 --- /dev/null +++ b/Task/Unicode-variable-names/Racket/unicode-variable-names.rkt @@ -0,0 +1,4 @@ +#lang racket +(define Δ 1) +(set! Δ (+ Δ 1)) +(displayln Δ) diff --git a/Task/Unicode-variable-names/Retro/unicode-variable-names.retro b/Task/Unicode-variable-names/Retro/unicode-variable-names.retro new file mode 100644 index 0000000000..ad25e77d45 --- /dev/null +++ b/Task/Unicode-variable-names/Retro/unicode-variable-names.retro @@ -0,0 +1,5 @@ +variable Δ +1 !Δ +@Δ putn +1 +Δ +@Δ putn diff --git a/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb b/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb new file mode 100644 index 0000000000..274d8a154e --- /dev/null +++ b/Task/Unicode-variable-names/Ruby/unicode-variable-names-1.rb @@ -0,0 +1,4 @@ +# -*- coding: big5 -*- +Δ = 1 +Δ += 1 +puts Δ diff --git a/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb b/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb new file mode 100644 index 0000000000..b7d1f69264 --- /dev/null +++ b/Task/Unicode-variable-names/Ruby/unicode-variable-names-2.rb @@ -0,0 +1,13 @@ +# -*- coding: euc-jp -*- + +class Numeric + def ≦(♯♭♪) + self <= ♯♭♪ + end +end + +∞ = Float::INFINITY +±5 = [-5, 5] +p [(±5.first.≦ ∞), + (±5.last.≦ ∞), + (∞.≦ ∞)] diff --git a/Task/Unicode-variable-names/Scala/unicode-variable-names.scala b/Task/Unicode-variable-names/Scala/unicode-variable-names.scala new file mode 100644 index 0000000000..7ee042cac4 --- /dev/null +++ b/Task/Unicode-variable-names/Scala/unicode-variable-names.scala @@ -0,0 +1,5 @@ +var Δ = 1 +val π = 3.141592 +val 你好 = "hello" +Δ += 1 +println(Δ) diff --git a/Task/Unicode-variable-names/Tcl/unicode-variable-names.tcl b/Task/Unicode-variable-names/Tcl/unicode-variable-names.tcl new file mode 100644 index 0000000000..88d2d55339 --- /dev/null +++ b/Task/Unicode-variable-names/Tcl/unicode-variable-names.tcl @@ -0,0 +1,3 @@ +set Δx 1 +incr Δx +puts [set Δx] diff --git a/Task/Universal-Turing-machine/0DESCRIPTION b/Task/Universal-Turing-machine/0DESCRIPTION new file mode 100644 index 0000000000..6cd990851d --- /dev/null +++ b/Task/Universal-Turing-machine/0DESCRIPTION @@ -0,0 +1,35 @@ +One of the foundational mathematical constructs behind computer science is the [[wp:Universal Turing machine|universal Turing Machine]]. Indeed one way to definitively prove that a language is Turing complete is to implement a universal Turing machine in it. + +'''The task''' + +For this task you would simulate such a machine capable of taking the definition of any other Turing machine and executing it. You will not, of course, have an infinite tape, but you should emulate this as much as is possible. The three permissible actions on the tape are "left", "right" and "stay". + +To test your universal Turing machine (and prove your programming language is Turing complete!), you should execute the following two Turing machines based on the following definitions. + +'''Simple incrementer''' +* '''States:''' q0, qf +* '''Initial state:''' q0 +* '''Terminating states:''' qf +* '''Permissible symbols:''' B, 1 +* '''Blank symbol:''' B +* '''Rules:''' +** (q0, 1, 1, right, q0) +** (q0, B, 1, stay, qf) + +The input for this machine should be a tape of 1 1 1 + +'''Three-state busy beaver''' +* '''States:''' a, b, c, halt +* '''Initial state:''' a +* '''Terminating states:''' halt +* '''Permissible symbols:''' 0, 1 +* '''Blank symbol:''' 0 +* '''Rules:''' +** (a, 0, 1, right, b) +** (a, 1, 1, left, c) +** (b, 0, 1, left, a) +** (b, 1, 1, right, b) +** (c, 0, 1, left, b) +** (c, 1, 1, stay, halt) + +The input for this machine should be an empty tape. diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.ada b/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.ada new file mode 100644 index 0000000000..d61152cc6d --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.ada @@ -0,0 +1,54 @@ +private with Ada.Containers.Doubly_Linked_Lists; + +generic + type State is (<>); -- State'First is starting state + type Symbol is (<>); -- Symbol'First is blank +package Turing is + + Start: constant State := State'First; + Halt: constant State := State'Last; + subtype Action_State is State range Start .. State'Pred(Halt); + + Blank: constant Symbol := Symbol'First; + + type Movement is (Left, Stay, Right); + + type Action is record + New_State: State; + Move_To: Movement; + New_Symbol: Symbol; + end record; + + type Rules_Type is array(Action_State, Symbol) of Action; + + type Tape_Type is limited private; + + type Symbol_Map is array(Symbol) of Character; + + function To_String(Tape: Tape_Type; Map: Symbol_Map) return String; + function Position_To_String(Tape: Tape_Type; Marker: Character := '^') + return String; + function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type; + + procedure Single_Step(Current: in out State; + Tape: in out Tape_Type; + Rules: Rules_Type); + + procedure Run(The_Tape: in out Tape_Type; + Rules: Rules_Type; + Max_Steps: Natural := Natural'Last; + Print: access procedure(Tape: Tape_Type; Current: State)); + -- runs from Start State until either Halt or # Steps exceeds Max_Steps + -- if # of steps exceeds Max_Steps, Constrained_Error is raised; + -- if Print is not null, Print is called at the beginning of each step + +private + package Symbol_Lists is new Ada.Containers.Doubly_Linked_Lists(Symbol); + subtype List is Symbol_Lists.List; + + type Tape_Type is record + Left: List; + Here: Symbol; + Right: List; + end record; +end Turing; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.ada b/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.ada new file mode 100644 index 0000000000..05e3b3cea5 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.ada @@ -0,0 +1,98 @@ +package body Turing is + + function List_To_String(L: List; Map: Symbol_Map) return String is + LL: List := L; + use type List; + begin + if L = Symbol_Lists.Empty_List then + return ""; + else + LL.Delete_First; + return Map(L.First_Element) & List_To_String(LL, Map); + end if; + end List_To_String; + + function To_String(Tape: Tape_Type; Map: Symbol_Map) return String is + + begin + return List_To_String(Tape.Left, Map) & Map(Tape.Here) & + List_To_String(Tape.Right, Map); + end To_String; + + function Position_To_String(Tape: Tape_Type; Marker: Character := '^') + return String is + Blank_Map: Symbol_Map := (others => ' '); + begin + return List_To_String(Tape.Left, Blank_Map) & Marker & + List_To_String(Tape.Right, Blank_Map); + end Position_To_String; + + function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type is + Char_Map: array(Character) of Symbol := (others => Blank); + Tape: Tape_Type; + begin + if Str = "" then + Tape.Here := Blank; + else + for S in Symbol loop + Char_Map(Map(S)) := S; + end loop; + Tape.Here := Char_Map(Str(Str'First)); + for I in Str'First+1 .. Str'Last loop + Tape.Right.Append(Char_Map(Str(I))); + end loop; + end if; + return Tape; + end To_Tape; + + procedure Single_Step(Current: in out State; + Tape: in out Tape_Type; + Rules: Rules_Type) is + Act: Action := Rules(Current, Tape.Here); + use type List; -- needed to compare Tape.Left/Right to the Empty_List + begin + Current := Act.New_State; -- 1. update State + Tape.Here := Act.New_Symbol; -- 2. write Symbol to Tape + case Act.Move_To is -- 3. move Tape to the Left/Right or Stay + when Left => + Tape.Right.Prepend(Tape.Here); + if Tape.Left /= Symbol_Lists.Empty_List then + Tape.Here := Tape.Left.Last_Element; + Tape.Left.Delete_Last; + else + Tape.Here := Blank; + end if; + when Stay => + null; -- Stay where you are! + when Right => + Tape.Left.Append(Tape.Here); + if Tape.Right /= Symbol_Lists.Empty_List then + Tape.Here := Tape.Right.First_Element; + Tape.Right.Delete_First; + else + Tape.Here := Blank; + end if; + end case; + end Single_Step; + + procedure Run(The_Tape: in out Tape_Type; + Rules: Rules_Type; + Max_Steps: Natural := Natural'Last; + Print: access procedure (Tape: Tape_Type; Current: State)) is + The_State: State := Start; + Steps: Natural := 0; + begin + Steps := 0; + while (Steps <= Max_Steps) and (The_State /= Halt) loop + if Print /= null then + Print(The_Tape, The_State); + end if; + Steps := Steps + 1; + Single_Step(The_State, The_Tape, Rules); + end loop; + if The_State /= Halt then + raise Constraint_Error; + end if; + end Run; + +end Turing; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.ada b/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.ada new file mode 100644 index 0000000000..a1b85343f7 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO, Turing; + +procedure Simple_Incrementer is + + type States is (Start, Stop); + type Symbols is (Blank, One); + + package UTM is new Turing(States, Symbols); + use UTM; + + Map: Symbol_Map := (One => '1', Blank => '_'); + + Rules: Rules_Type := + (Start => (One => (Start, Right, One), + Blank => (Stop, Stay, One))); + Tape: Tape_Type := To_Tape("111", Map); + + procedure Put_Tape(Tape: Tape_Type; Current: States) is + begin + Ada.Text_IO.Put_Line(To_String(Tape, Map) & " " & States'Image(Current)); + Ada.Text_IO.Put_Line(Position_To_String(Tape)); + end Put_Tape; + +begin + Run(Tape, Rules, 20, null); -- don't print the configuration during running + Put_Tape(Tape, Stop); -- print the final configuration +end Simple_Incrementer; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.ada b/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.ada new file mode 100644 index 0000000000..42ca413380 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.ada @@ -0,0 +1,31 @@ +with Ada.Text_IO, Turing; + +procedure Busy_Beaver_3 is + + type States is (A, B, C, Stop); + type Symbols is range 0 .. 1; + package UTM is new Turing(States, Symbols); use UTM; + + Map: Symbol_Map := (1 => '1', 0 => '0'); + + Rules: Rules_Type := + (A => (0 => (New_State => B, Move_To => Right, New_Symbol => 1), + 1 => (New_State => C, Move_To => Left, New_Symbol => 1)), + B => (0 => (New_State => A, Move_To => Left, New_Symbol => 1), + 1 => (New_State => B, Move_To => Right, New_Symbol => 1)), + C => (0 => (New_State => B, Move_To => Left, New_Symbol => 1), + 1 => (New_State => Stop, Move_To => Stay, New_Symbol => 1))); + + Tape: Tape_Type := To_Tape("", Map); + + procedure Put_Tape(Tape: Tape_Type; Current: States) is + begin + Ada.Text_IO.Put_Line(To_String(Tape, Map) & " " & + States'Image(Current)); + Ada.Text_IO.Put_Line(Position_To_String(Tape)); + end Put_Tape; + +begin + Run(Tape, Rules, 20, Put_Tape'Access); -- print configuration before each step + Put_Tape(Tape, Stop); -- and print the final configuration +end Busy_Beaver_3; diff --git a/Task/Universal-Turing-machine/D/universal-turing-machine.d b/Task/Universal-Turing-machine/D/universal-turing-machine.d new file mode 100644 index 0000000000..7cc82b8b05 --- /dev/null +++ b/Task/Universal-Turing-machine/D/universal-turing-machine.d @@ -0,0 +1,190 @@ +import std.stdio, std.algorithm, std.string, std.conv, std.array, + std.exception; + +struct UTM(bool doShow=true) { + alias Symbol = uint; + alias State = char; // Typedef? + enum Direction { right, left, stay } + + private TapeHead head; + private const TuringMachine tm; + + static struct Rule { + Symbol toWrite; + Direction direction; + State nextState; + } + + static struct TuringMachine { + Symbol[] symbols; + Symbol blank; + State initialState; + State[] haltStates, runningStates; + Rule[Symbol][State] rules; + Symbol[] input; + } + + static struct TapeHead { + immutable Symbol blank; + Symbol[] tape; + size_t position; + + this(in ref TuringMachine t) pure /*nothrow*/ { + this.blank = t.blank; + this.tape = t.input.dup; // Not nothrow. + if (this.tape.empty) + this.tape = [this.blank]; + this.position = 0; + } + + pure nothrow invariant() { + assert(this.position < this.tape.length); + } + + Symbol read() const pure nothrow { + return this.tape[this.position]; + } + + void show() const { + .write(this); + } + + void write(in Symbol symbol) { + static if (doShow) + show(); + this.tape[this.position] = symbol; + } + + void right() pure nothrow { + this.position++; + if (this.position == this.tape.length) + this.tape ~= this.blank; + } + + void left() pure nothrow { + if (this.position == 0) + this.tape = this.blank ~ this.tape; + else + this.position--; + } + + void move(in Direction dir) { + final switch (dir) { + case Direction.left: left(); break; + case Direction.right: right(); break; + case Direction.stay: /*Do nothing.*/ break; + } + } + + string toString() const { + return format("...%(%)...", this.tape) + ~ '\n' + ~ format("%" ~ text(this.position + 4) ~ "s", "^") + ~ '\n'; + } + } + + void show() const { + head.show(); + } + + this(const ref TuringMachine tm_) { + immutable errMsg = "Invalid input."; + enforce(!tm_.runningStates.empty, errMsg); + enforce(!tm_.haltStates.empty, errMsg); + enforce(!tm_.symbols.empty, errMsg); + enforce(tm_.rules.length, errMsg); + enforce(tm_.runningStates.canFind(tm_.initialState), errMsg); + enforce(tm_.symbols.canFind(tm_.blank), errMsg); + const allStates = tm_.runningStates ~ tm_.haltStates; + foreach (const s; tm_.rules.keys.to!(dchar[])().sort()) + enforce(tm_.runningStates.canFind(s), errMsg); + foreach (const aa; tm_.rules.byValue) + foreach (/*const*/ s, const rule; aa) { + enforce(tm_.symbols.canFind(s), errMsg); + enforce(tm_.symbols.canFind(rule.toWrite), errMsg); + enforce(allStates.canFind(rule.nextState), errMsg); + } + + this.tm = tm_; + this.head = TapeHead(this.tm); + + State state = this.tm.initialState; + while (true) { + if (tm.haltStates.canFind(state)) + break; + if (!tm.runningStates.canFind(state)) + throw new Exception("Unknown state."); + immutable symbol = this.head.read(); + immutable rule = this.tm.rules[state][symbol]; + this.head.write(rule.toWrite); + this.head.move(rule.direction); + state = rule.nextState; + } + static if (doShow) + show(); + } +} + +void main() { + with (UTM!()) { + alias R = Rule; + writeln("Incrementer:"); + TuringMachine tm1; + tm1.symbols = [0, 1]; + tm1.blank = 0; + tm1.initialState = 'A'; + tm1.haltStates = ['H']; + tm1.runningStates = ['A']; + with (Direction) + tm1.rules = ['A': [0: R(1, left, 'H'), + 1: R(1, right, 'A')]]; + tm1.input = [1, 1, 1]; + UTM!()(tm1); + + // http://en.wikipedia.org/wiki/Busy_beaver + writeln("\nBusy beaver machine (3-state, 2-symbol):"); + TuringMachine tm2; + tm2.symbols = [0, 1]; + tm2.blank = 0; + tm2.initialState = 'A'; + tm2.haltStates = ['H']; + tm2.runningStates = ['A', 'B', 'C']; + with (Direction) + tm2.rules = ['A': [0: R(1, right, 'B'), + 1: R(1, left, 'C')], + 'B': [0: R(1, left, 'A'), + 1: R(1, right, 'B')], + 'C': [0: R(1, left, 'B'), + 1: R(1, stay, 'H')]]; + UTM!()(tm2); + } + + with (UTM!false) { + writeln("\nSorting stress test (12212212121212):"); + alias R = Rule; + TuringMachine tm3; + tm3.symbols = [0, 1, 2, 3]; + tm3.blank = 0; + tm3.initialState = 'A'; + tm3.haltStates = ['H']; + tm3.runningStates = ['A', 'B', 'C', 'D', 'E']; + with (Direction) + tm3.rules = ['A': [1: R(1, right, 'A'), + 2: R(3, right, 'B'), + 0: R(0, left, 'E')], + 'B': [1: R(1, right, 'B'), + 2: R(2, right, 'B'), + 0: R(0, left, 'C')], + 'C': [1: R(2, left, 'D'), + 2: R(2, left, 'C'), + 3: R(2, left, 'E')], + 'D': [1: R(1, left, 'D'), + 2: R(2, left, 'D'), + 3: R(1, right, 'A')], + 'E': [1: R(1, left, 'E'), + 0: R(0, right, 'H')]]; + tm3.input = [1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2]; + UTM!false(tm3).show(); + } +} diff --git a/Task/Universal-Turing-machine/Erlang/universal-turing-machine.erl b/Task/Universal-Turing-machine/Erlang/universal-turing-machine.erl new file mode 100644 index 0000000000..daee682f0c --- /dev/null +++ b/Task/Universal-Turing-machine/Erlang/universal-turing-machine.erl @@ -0,0 +1,68 @@ +#!/usr/bin/env escript + +-module(turing). +-mode(compile). + +-export([main/1]). + +% Incrementer definition: +% States: a | halt +% Initial state: a +% Halting states: halt +% Symbols: b | '1' +% Blank symbol: b +incrementer_config() -> {a, [halt], b}. +incrementer(a, '1') -> {'1', right, a}; +incrementer(a, b) -> {'1', stay, halt}. + +% Busy beaver definition: +% States: a | b | c | halt +% Initial state: a +% Halting states: halt +% Symbols: '0' | '1' +% Blank symbol: '0' +busy_beaver_config() -> {a, [halt], '0'}. +busy_beaver(a, '0') -> {'1', right, b}; +busy_beaver(a, '1') -> {'1', left, c}; +busy_beaver(b, '0') -> {'1', left, a}; +busy_beaver(b, '1') -> {'1', right, b}; +busy_beaver(c, '0') -> {'1', left, b}; +busy_beaver(c, '1') -> {'1', stay, halt}. + +% Mainline code. +main([]) -> + io:format("==============================~n"), + io:format("Turing machine simulator test.~n"), + io:format("==============================~n"), + + Tape1 = turing(fun incrementer_config/0, fun incrementer/2, ['1','1','1']), + io:format("~w~n", [Tape1]), + + Tape2 = turing(fun busy_beaver_config/0, fun busy_beaver/2, []), + io:format("~w~n", [Tape2]). + +% Universal Turing machine simulator. +turing(Config, Rules, Input) -> + {Start, _, _} = Config(), + {Left, Right} = perform(Config, Rules, Start, {[], Input}), + lists:reverse(Left) ++ Right. + +perform(Config, Rules, State, Input = {LeftInput, RightInput}) -> + {_, Halts, Blank} = Config(), + case lists:member(State, Halts) of + true -> Input; + false -> + {NewRight, Symbol} = symbol(RightInput, Blank), + {NewSymbol, Action, NewState} = Rules(State, Symbol), + NewInput = action(Action, Blank, {LeftInput, [NewSymbol| NewRight]}), + perform(Config, Rules, NewState, NewInput) + end. + +symbol([], Blank) -> {[], Blank}; +symbol([S|R], _) -> {R, S}. + +action(left, Blank, {[], Right}) -> {[], [Blank|Right]}; +action(left, _, {[L|Ls], Right}) -> {Ls, [L|Right]}; +action(stay, _, Tape) -> Tape; +action(right, Blank, {Left, []}) -> {[Blank|Left], []}; +action(right, _, {Left, [R|Rs]}) -> {[R|Left], Rs}. diff --git a/Task/Universal-Turing-machine/Java/universal-turing-machine.java b/Task/Universal-Turing-machine/Java/universal-turing-machine.java new file mode 100644 index 0000000000..e8d6b08b29 --- /dev/null +++ b/Task/Universal-Turing-machine/Java/universal-turing-machine.java @@ -0,0 +1,238 @@ +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.ListIterator; +import java.util.List; +import java.util.Set; +import java.util.Map; + +public class UTM { + private List tape; + private String blankSymbol; + private ListIterator head; + private Map transitions = new HashMap(); + private Set terminalStates; + private String initialState; + + public UTM(Set transitions, Set terminalStates, String initialState, String blankSymbol) { + this.blankSymbol = blankSymbol; + for (Transition t : transitions) { + this.transitions.put(t.from, t); + } + this.terminalStates = terminalStates; + this.initialState = initialState; + } + + public static class StateTapeSymbolPair { + private String state; + private String tapeSymbol; + + public StateTapeSymbolPair(String state, String tapeSymbol) { + this.state = state; + this.tapeSymbol = tapeSymbol; + } + + // These methods can be auto-generated by Eclipse. + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((state == null) ? 0 : state.hashCode()); + result = prime + * result + + ((tapeSymbol == null) ? 0 : tapeSymbol + .hashCode()); + return result; + } + + // These methods can be auto-generated by Eclipse. + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StateTapeSymbolPair other = (StateTapeSymbolPair) obj; + if (state == null) { + if (other.state != null) + return false; + } else if (!state.equals(other.state)) + return false; + if (tapeSymbol == null) { + if (other.tapeSymbol != null) + return false; + } else if (!tapeSymbol.equals(other.tapeSymbol)) + return false; + return true; + } + + @Override + public String toString() { + return "(" + state + "," + tapeSymbol + ")"; + } + } + + public static class Transition { + private StateTapeSymbolPair from; + private StateTapeSymbolPair to; + private int direction; // -1 left, 0 neutral, 1 right. + + public Transition(StateTapeSymbolPair from, StateTapeSymbolPair to, int direction) { + this.from = from; + this.to = to; + this.direction = direction; + } + + @Override + public String toString() { + return from + "=>" + to + "/" + direction; + } + } + + public void initializeTape(List input) { // Arbitrary Strings as symbols. + tape = input; + } + + public void initializeTape(String input) { // Uses single characters as symbols. + tape = new LinkedList(); + for (int i = 0; i < input.length(); i++) { + tape.add(input.charAt(i) + ""); + } + } + + public List runTM() { // Returns null if not in terminal state. + if (tape.size() == 0) { + tape.add(blankSymbol); + } + + head = tape.listIterator(); + head.next(); + head.previous(); + + StateTapeSymbolPair tsp = new StateTapeSymbolPair(initialState, tape.get(0)); + + while (transitions.containsKey(tsp)) { // While a matching transition exists. + System.out.println(this + " --- " + transitions.get(tsp)); + Transition trans = transitions.get(tsp); + head.set(trans.to.tapeSymbol); // Write tape symbol. + tsp.state = trans.to.state; // Change state. + if (trans.direction == -1) { // Go left. + if (!head.hasPrevious()) { + head.add(blankSymbol); // Extend tape. + } + tsp.tapeSymbol = head.previous(); // Memorize tape symbol. + } else if (trans.direction == 1) { // Go right. + head.next(); + if (!head.hasNext()) { + head.add(blankSymbol); // Extend tape. + head.previous(); + } + tsp.tapeSymbol = head.next(); // Memorize tape symbol. + head.previous(); + } else { + tsp.tapeSymbol = trans.to.tapeSymbol; + } + } + + System.out.println(this + " --- " + tsp); + + if (terminalStates.contains(tsp.state)) { + return tape; + } else { + return null; + } + } + + @Override + public String toString() { + try { + int headPos = head.previousIndex(); + String s = "[ "; + + for (int i = 0; i <= headPos; i++) { + s += tape.get(i) + " "; + } + + s += "[H] "; + + for (int i = headPos + 1; i < tape.size(); i++) { + s += tape.get(i) + " "; + } + + return s + "]"; + } catch (Exception e) { + return ""; + } + } + + public static void main(String[] args) { + // Simple incrementer. + String init = "q0"; + String blank = "b"; + + Set term = new HashSet(); + term.add("qf"); + + Set trans = new HashSet(); + + trans.add(new Transition(new StateTapeSymbolPair("q0", "1"), new StateTapeSymbolPair("q0", "1"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("q0", "b"), new StateTapeSymbolPair("qf", "1"), 0)); + + UTM machine = new UTM(trans, term, init, blank); + machine.initializeTape("111"); + System.out.println("Output (si): " + machine.runTM() + "\n"); + + // Busy Beaver (overwrite variables from above). + init = "a"; + + term.clear(); + term.add("halt"); + + blank = "0"; + + trans.clear(); + + // Change state from "a" to "b" if "0" is read on tape, write "1" and go to the right. (-1 left, 0 nothing, 1 right.) + trans.add(new Transition(new StateTapeSymbolPair("a", "0"), new StateTapeSymbolPair("b", "1"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("a", "1"), new StateTapeSymbolPair("c", "1"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("b", "0"), new StateTapeSymbolPair("a", "1"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("b", "1"), new StateTapeSymbolPair("b", "1"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("c", "0"), new StateTapeSymbolPair("b", "1"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("c", "1"), new StateTapeSymbolPair("halt", "1"), 0)); + + machine = new UTM(trans, term, init, blank); + machine.initializeTape(""); + System.out.println("Output (bb): " + machine.runTM()); + + // Sorting test (overwrite variables from above). + init = "s0"; + blank = "*"; + + term = new HashSet(); + term.add("see"); + + trans = new HashSet(); + + trans.add(new Transition(new StateTapeSymbolPair("s0", "a"), new StateTapeSymbolPair("s0", "a"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("s0", "b"), new StateTapeSymbolPair("s1", "B"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("s0", "*"), new StateTapeSymbolPair("se", "*"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s1", "a"), new StateTapeSymbolPair("s1", "a"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("s1", "b"), new StateTapeSymbolPair("s1", "b"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("s1", "*"), new StateTapeSymbolPair("s2", "*"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s2", "a"), new StateTapeSymbolPair("s3", "b"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s2", "b"), new StateTapeSymbolPair("s2", "b"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s2", "B"), new StateTapeSymbolPair("se", "b"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s3", "a"), new StateTapeSymbolPair("s3", "a"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s3", "b"), new StateTapeSymbolPair("s3", "b"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("s3", "B"), new StateTapeSymbolPair("s0", "a"), 1)); + trans.add(new Transition(new StateTapeSymbolPair("se", "a"), new StateTapeSymbolPair("se", "a"), -1)); + trans.add(new Transition(new StateTapeSymbolPair("se", "*"), new StateTapeSymbolPair("see", "*"), 1)); + + machine = new UTM(trans, term, init, blank); + machine.initializeTape("babbababaa"); + System.out.println("Output (sort): " + machine.runTM() + "\n"); + } +} diff --git a/Task/Universal-Turing-machine/Mercury/universal-turing-machine-1.mercury b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-1.mercury new file mode 100644 index 0000000000..cdcac5f8f1 --- /dev/null +++ b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-1.mercury @@ -0,0 +1,58 @@ +:- module turing. + +:- interface. + +:- import_module list. +:- import_module set. + +:- type config(State, Symbol) + ---> config(initial_state :: State, + halting_states :: set(State), + blank :: Symbol ). + +:- type action ---> left ; stay ; right. + +:- func turing(config(State, Symbol), + pred(State, Symbol, Symbol, action, State), + list(Symbol)) = list(Symbol). +:- mode turing(in, + pred(in, in, out, out, out) is semidet, + in) = out is det. + +:- implementation. + +:- import_module pair. +:- import_module require. + +turing(Config@config(Start, _, _), Rules, Input) = Output :- + (Left-Right) = perform(Config, Rules, Start, ([]-Input)), + Output = append(reverse(Left), Right). + +:- func perform(config(State, Symbol), + pred(State, Symbol, Symbol, action, State), + State, pair(list(Symbol))) = pair(list(Symbol)). +:- mode perform(in, pred(in, in, out, out, out) is semidet, + in, in) = out is det. +perform(Config@config(_, Halts, Blank), Rules, State, + Input@(LeftInput-RightInput)) = Output :- + symbol(RightInput, Blank, RightNew, Symbol), + ( set.member(State, Halts) -> + Output = Input + ; Rules(State, Symbol, NewSymbol, Action, NewState) -> + NewLeft = pair(LeftInput, [NewSymbol|RightNew]), + NewRight = action(Action, Blank, NewLeft), + Output = perform(Config, Rules, NewState, NewRight) + ; + error("an impossible state has apparently become possible") ). + +:- pred symbol(list(Symbol), Symbol, list(Symbol), Symbol). +:- mode symbol(in, in, out, out) is det. +symbol([], Blank, [], Blank). +symbol([Sym|Rem], _, Rem, Sym). + +:- func action(action, State, pair(list(State))) = pair(list(State)). +action(left, Blank, ([]-Right)) = ([]-[Blank|Right]). +action(left, _, ([Left|Lefts]-Rights)) = (Lefts-[Left|Rights]). +action(stay, _, Tape) = Tape. +action(right, Blank, (Left-[])) = ([Blank|Left]-[]). +action(right, _, (Left-[Right|Rights])) = ([Right|Left]-Rights). diff --git a/Task/Universal-Turing-machine/Mercury/universal-turing-machine-2.mercury b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-2.mercury new file mode 100644 index 0000000000..7a829b685e --- /dev/null +++ b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-2.mercury @@ -0,0 +1,17 @@ +:- type incrementer_states ---> a ; halt. +:- type incrementer_symbols ---> b ; '1'. + +:- func incrementer_config = config(incrementer_states, incrementer_symbols). +incrementer_config = config(a, % the initial state + set([halt]), % the set of halting states + b). % the blank symbol + +:- pred incrementer(incrementer_states::in, + incrementer_symbols::in, + incrementer_symbols::out, + action::out, + incrementer_states::out) is semidet. +incrementer(a, '1', '1', right, a). +incrementer(a, b, '1', stay, halt). + +TapeOut = turing(incrementer_config, incrementer, [1, 1, 1]). diff --git a/Task/Universal-Turing-machine/Mercury/universal-turing-machine-3.mercury b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-3.mercury new file mode 100644 index 0000000000..13cd4abaca --- /dev/null +++ b/Task/Universal-Turing-machine/Mercury/universal-turing-machine-3.mercury @@ -0,0 +1,21 @@ +:- type busy_beaver_states ---> a ; b ; c ; halt. +:- type busy_beaver_symbols ---> '0' ; '1'. + +:- func busy_beaver_config = config(busy_beaver_states, busy_beaver_symbols). +busy_beaver_config = config(a, % initial state + set([halt]), % set of terminating states + '0'). % blank symbol + +:- pred busy_beaver(busy_beaver_states::in, + busy_beaver_symbols::in, + busy_beaver_symbols::out, + action::out, + busy_beaver_states::out) is semidet. +busy_beaver(a, '0', '1', right, b). +busy_beaver(a, '1', '1', left, c). +busy_beaver(b, '0', '1', left, a). +busy_beaver(b, '1', '1', right, b). +busy_beaver(c, '0', '1', left, b). +busy_beaver(c, '1', '1', stay, halt). + +TapeOut = turing(busy_beaver_config, busy_beaver, []). diff --git a/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 b/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 new file mode 100644 index 0000000000..34011fa031 --- /dev/null +++ b/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 @@ -0,0 +1,74 @@ +sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$pos is copy = 0) { + $pos += @tape if $pos < 0; + die "Bad initial position" unless $pos ~~ ^@tape; + + step: + print "$state\t"; + for ^@tape { + my $v = @tape[$_]; + print $_ == $pos ?? "[$v]" !! " $v "; + } + print "\n"; + + return if $state eq $halt; + for @rules -> @rule { + my ($s0, $v0, $v1, $dir, $s1) = @rule; + next unless $s0 eq $state and @tape[$pos] eq $v0; + + @tape[$pos] = $v1; + + given $dir { + when 'left' { + if $pos == 0 { unshift @tape, $blank } + else { $pos-- } + } + when 'right' { + push @tape, $blank if ++$pos >= @tape; + } + } + + $state = $s1; + goto step; + } + + die "No matching rules"; +} + +say "incr machine"; +run_utm :halt, + :state, + :tape[1,1,1], + :blank, + :rules[ [< q0 1 1 right q0 >], + [< q0 B 1 stay qf >] ]; + +say "\nbusy beaver"; +run_utm :halt, + :state
, + :blank<0>, + :rules[ [< a 0 1 right b >], + [< a 1 1 left c >], + [< b 0 1 left a >], + [< b 1 1 right b >], + [< c 0 1 left b >], + [< c 1 1 stay halt >] ]; + +say "\nsorting test"; +run_utm :halt, + :state, + :blank<0>, + :tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >], + :rules[ [< A 1 1 right A >], + [< A 2 3 right B >], + [< A 0 0 left E >], + [< B 1 1 right B >], + [< B 2 2 right B >], + [< B 0 0 left C >], + [< C 1 2 left D >], + [< C 2 2 left C >], + [< C 3 2 left E >], + [< D 1 1 left D >], + [< D 2 2 left D >], + [< D 3 1 right A >], + [< E 1 1 left E >], + [< E 0 0 right STOP >] ]; diff --git a/Task/Universal-Turing-machine/Perl/universal-turing-machine.pl b/Task/Universal-Turing-machine/Perl/universal-turing-machine.pl new file mode 100644 index 0000000000..67470a95e0 --- /dev/null +++ b/Task/Universal-Turing-machine/Perl/universal-turing-machine.pl @@ -0,0 +1,83 @@ +use strict; +use warnings; + +sub run_utm { + my %o = @_; + my $st = $o{state} // die "init head state undefined"; + my $blank = $o{blank} // die "blank symbol undefined"; + my @rules = @{$o{rules}} or die "rules undefined"; + my @tape = $o{tape} ? @{$o{tape}} : ($blank); + my $halt = $o{halt}; + + my $pos = $o{pos} // 0; + $pos += @tape if $pos < 0; + die "bad init position" if $pos >= @tape || $pos < 0; + +step: while (1) { + print "$st\t"; + for (0 .. $#tape) { + my $v = $tape[$_]; + print $_ == $pos ? "[$v]" : " $v "; + } + print "\n"; + + last if $st eq $halt; + for (@rules) { + my ($s0, $v0, $v1, $dir, $s1) = @$_; + next unless $s0 eq $st and $tape[$pos] eq $v0; + + $tape[$pos] = $v1; + + if ($dir eq 'left') { + if ($pos == 0) { unshift @tape, $blank} + else { $pos-- } + } elsif ($dir eq 'right') { + push @tape, $blank if ++$pos >= @tape + } + + $st = $s1; + next step; + } + + die "no matching rules"; + } +} + +print "incr machine\n"; +run_utm halt=>'qf', + state=>'q0', + tape=>[1,1,1], + blank=>'B', + rules=>[[qw/q0 1 1 right q0/], + [qw/q0 B 1 stay qf/]]; + +print "\nbusy beaver\n"; +run_utm halt=>'halt', + state=>'a', + blank=>'0', + rules=>[[qw/a 0 1 right b/], + [qw/a 1 1 left c/], + [qw/b 0 1 left a/], + [qw/b 1 1 right b/], + [qw/c 0 1 left b/], + [qw/c 1 1 stay halt/]]; + +print "\nsorting test\n"; +run_utm halt=>'STOP', + state=>'A', + blank=>'0', + tape=>[qw/2 2 2 1 2 2 1 2 1 2 1 2 1 2/], + rules=>[[qw/A 1 1 right A/], + [qw/A 2 3 right B/], + [qw/A 0 0 left E/], + [qw/B 1 1 right B/], + [qw/B 2 2 right B/], + [qw/B 0 0 left C/], + [qw/C 1 2 left D/], + [qw/C 2 2 left C/], + [qw/C 3 2 left E/], + [qw/D 1 1 left D/], + [qw/D 2 2 left D/], + [qw/D 3 1 right A/], + [qw/E 1 1 left E/], + [qw/E 0 0 right STOP/]]; diff --git a/Task/Universal-Turing-machine/Prolog/universal-turing-machine-1.pro b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-1.pro new file mode 100644 index 0000000000..c038ca5f5f --- /dev/null +++ b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-1.pro @@ -0,0 +1,31 @@ +turing(Config, Rules, TapeIn, TapeOut) :- + call(Config, IS, _, _, _, _), + perform(Config, Rules, IS, {[], TapeIn}, {Ls, Rs}), + reverse(Ls, Ls1), + append(Ls1, Rs, TapeOut). + +perform(Config, Rules, State, TapeIn, TapeOut) :- + call(Config, _, FS, RS, B, Symbols), + ( memberchk(State, FS) -> + TapeOut = TapeIn + ; memberchk(State, RS) -> + {LeftIn, RightIn} = TapeIn, + symbol(RightIn, Symbol, RightRem, B), + memberchk(Symbol, Symbols), + once(call(Rules, State, Symbol, NewSymbol, Action, NewState)), + memberchk(NewSymbol, Symbols), + action(Action, {LeftIn, [NewSymbol|RightRem]}, {LeftOut, RightOut}, B), + perform(Config, Rules, NewState, {LeftOut, RightOut}, TapeOut) ). + +symbol([], B, [], B). +symbol([Sym|Rs], Sym, Rs, _). + +action(left, {Lin, Rin}, {Lout, Rout}, B) :- left(Lin, Rin, Lout, Rout, B). +action(stay, Tape, Tape, _). +action(right, {Lin, Rin}, {Lout, Rout}, B) :- right(Lin, Rin, Lout, Rout, B). + +left([], Rs, [], [B|Rs], B). +left([L|Ls], Rs, Ls, [L|Rs], _). + +right(L, [], [B|L], [], B). +right(L, [S|Rs], [S|L], Rs, _). diff --git a/Task/Universal-Turing-machine/Prolog/universal-turing-machine-2.pro b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-2.pro new file mode 100644 index 0000000000..09a767eb7f --- /dev/null +++ b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-2.pro @@ -0,0 +1,10 @@ +incrementer_config(IS, FS, RS, B, S) :- + IS = q0, % initial state + FS = [qf], % halting states + RS = [IS], % running states + B = 0, % blank symbol + S = [B, 1]. % valid symbols +incrementer(q0, 1, 1, right, q0). +incrementer(q0, b, 1, stay, qf). + +turing(incrementer_config, incrementer, [1, 1, 1], TapeOut). diff --git a/Task/Universal-Turing-machine/Prolog/universal-turing-machine-3.pro b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-3.pro new file mode 100644 index 0000000000..16dfa61578 --- /dev/null +++ b/Task/Universal-Turing-machine/Prolog/universal-turing-machine-3.pro @@ -0,0 +1,14 @@ +busy_beaver_config(IS, FS, RS, B, S) :- + IS = 'A', % initial state + FS = ['HALT'], % halting states + RS = [IS, 'B', 'C'], % running states + B = 0, % blank symbol + S = [B, 1]. % valid symbols +busy_beaver('A', 0, 1, right, 'B'). +busy_beaver('A', 1, 1, left, 'C'). +busy_beaver('B', 0, 1, left, 'A'). +busy_beaver('B', 1, 1, right, 'B'). +busy_beaver('C', 0, 1, left, 'B'). +busy_beaver('C', 1, 1, stay, 'HALT'). + +turing(busy_beaver_config, busy_beaver, [], TapeOut). diff --git a/Task/Universal-Turing-machine/Ruby/universal-turing-machine-1.rb b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-1.rb new file mode 100644 index 0000000000..6c786d7a9f --- /dev/null +++ b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-1.rb @@ -0,0 +1,62 @@ +class Turing + class Tape + def initialize(symbols, blank, starting_tape) + @symbols = symbols + @blank = blank + @tape = starting_tape + @index = 0 + end + def read + retval = @tape[@index] + unless retval + retval = @tape[@index] = @blank + end + raise "invalid symbol '#{retval}' on tape" unless @tape.member?(retval) + return retval + end + def write(symbol) + @tape[@index] = symbol + end + def right + @index += 1 + end + def left + if @index == 0 + @tape.unshift @blank + else + @index -= 1 + end + end + def stay + # nop + end + def get_tape + return @tape + end + end + + def initialize(symbols, blank, + initial_state, halt_states, running_states, + rules, starting_tape = []) + @tape = Tape.new(symbols, blank, starting_tape) + @initial_state = initial_state + @halt_states = halt_states + @running_states = running_states + @rules = rules + @halted = false + end + def run + raise "machine already halted" if @halted + state = @initial_state + while (true) + break if @halt_states.member? state + raise "unknown state '#{state}'" unless @running_states.member? state + symbol = @tape.read + outsym, action, state = @rules[state][symbol] + @tape.write outsym + @tape.send action + end + @halted = true + return @tape.get_tape + end +end diff --git a/Task/Universal-Turing-machine/Ruby/universal-turing-machine-2.rb b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-2.rb new file mode 100644 index 0000000000..d49e9aceeb --- /dev/null +++ b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-2.rb @@ -0,0 +1,12 @@ +incrementer_rules = { + :q0 => { 1 => [1, :right, :q0], + :b => [1, :stay, :qf]} +} +t = Turing.new([:b, 1], # permitted symbols + :b, # blank symbol + :q0, # starting state + [:qf], # terminating states + [:q0], # running states + incrementer_rules, # operating rules + [1, 1, 1]) # starting tape +print t.run, "\n" diff --git a/Task/Universal-Turing-machine/Ruby/universal-turing-machine-3.rb b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-3.rb new file mode 100644 index 0000000000..39a2a828f2 --- /dev/null +++ b/Task/Universal-Turing-machine/Ruby/universal-turing-machine-3.rb @@ -0,0 +1,16 @@ +busy_beaver_rules = { + :a => { 0 => [1, :right, :b], + 1 => [1, :left, :c]}, + :b => { 0 => [1, :left, :a], + 1 => [1, :right, :b]}, + :c => { 0 => [1, :left, :b], + 1 => [1, :stay, :halt]} +} +t = Turing.new([0, 1], # permitted symbols + 0, # blank symbol + :a, # starting state + [:halt], # terminating states + [:a, :b, :c], # running states + busy_beaver_rules, # operating rules + []) # starting tape +print t.run, "\n" diff --git a/Task/Universal-Turing-machine/Tcl/universal-turing-machine-1.tcl b/Task/Universal-Turing-machine/Tcl/universal-turing-machine-1.tcl new file mode 100644 index 0000000000..ac47d33953 --- /dev/null +++ b/Task/Universal-Turing-machine/Tcl/universal-turing-machine-1.tcl @@ -0,0 +1,37 @@ +proc turing {states initial terminating symbols blank tape rules {doTrace 1}} { + set state $initial + set idx 0 + set tape [split $tape ""] + if {[llength $tape] == 0} { + set tape [list $blank] + } + foreach rule $rules { + lassign $rule state0 sym0 sym1 move state1 + set R($state0,$sym0) [list $sym1 $move $state1] + } + while {$state ni $terminating} { + set sym [lindex $tape $idx] + lassign $R($state,$sym) sym1 move state1 + if {$doTrace} { + ### Print the state, great for debugging + puts "[join $tape ""]\t$state->$state1" + puts "[string repeat { } $idx]^" + } + lset tape $idx $sym1 + switch $move { + left { + if {[incr idx -1] < 0} { + set idx 0 + set tape [concat [list $blank] $tape] + } + } + right { + if {[incr idx] == [llength $tape]} { + lappend tape $blank + } + } + } + set state $state1 + } + return [join $tape ""] +} diff --git a/Task/Universal-Turing-machine/Tcl/universal-turing-machine-2.tcl b/Task/Universal-Turing-machine/Tcl/universal-turing-machine-2.tcl new file mode 100644 index 0000000000..6f9394864f --- /dev/null +++ b/Task/Universal-Turing-machine/Tcl/universal-turing-machine-2.tcl @@ -0,0 +1,32 @@ +puts "Simple incrementer" +puts TAPE=[turing {q0 qf} q0 qf {1 B} B "111" { + {q0 1 1 right q0} + {q0 B 1 stay qf} +}] +puts "Three-state busy beaver" +puts TAPE=[turing {a b c halt} a halt {0 1} 0 "" { + {a 0 1 right b} + {a 1 1 left c} + {b 0 1 left a} + {b 1 1 right b} + {c 0 1 left b} + {c 1 1 stay halt} +}] +puts "Sorting stress test" +# We suppress the trace output for this so as to keep the output short +puts TAPE=[turing {A B C D E H} A H {0 1 2 3} 0 "12212212121212" { + {A 1 1 right A} + {A 2 3 right B} + {A 0 0 left E} + {B 1 1 right B} + {B 2 2 right B} + {B 0 0 left C} + {C 1 2 left D} + {C 2 2 left C} + {C 3 2 left E} + {D 1 1 left D} + {D 2 2 left D} + {D 3 1 right A} + {E 1 1 left E} + {E 0 0 right H} +} no] diff --git a/Task/Update-a-configuration-file/0DESCRIPTION b/Task/Update-a-configuration-file/0DESCRIPTION new file mode 100644 index 0000000000..e84f097502 --- /dev/null +++ b/Task/Update-a-configuration-file/0DESCRIPTION @@ -0,0 +1,52 @@ +We have a configuration file as follows: + + # This is a configuration file in standard configuration file format + # + # Lines begininning with a hash or a semicolon are ignored by the application + # program. Blank lines are also ignored by the application program. + + # The first word on each non comment line is the configuration option. + # Remaining words or numbers on the line are configuration parameter + # data fields. + + # Note that configuration option names are not case sensitive. However, + # configuration parameter data is case sensitive and the lettercase must + # be preserved. + + # This is a favourite fruit + FAVOURITEFRUIT banana + + # This is a boolean that should be set + NEEDSPEELING + + # This boolean is commented out + ; SEEDSREMOVED + + # How many bananas we have + NUMBEROFBANANAS 48 + +The task is to manipulate the configuration file as follows: + +* Disable the needspeeling option (using a semicolon prefix) +* Enable the seedsremoved option by removing the semicolon and any leading whitespace +* Change the numberofbananas parameter to 1024 +* Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 + +Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. + +Options should always be disabled by prefixing them with a semicolon. + +Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. + +If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. + +For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) + +The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). + +Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and paramters should consist only of a single +space, and any non ascii extended characters, tabs characters, or control codes +(other than end of line markers), should also be removed. + +'''See also:''' +* [[Read a configuration file]] diff --git a/Task/Update-a-configuration-file/1META.yaml b/Task/Update-a-configuration-file/1META.yaml new file mode 100644 index 0000000000..53d5156105 --- /dev/null +++ b/Task/Update-a-configuration-file/1META.yaml @@ -0,0 +1,2 @@ +--- +note: File handling diff --git a/Task/Update-a-configuration-file/AutoHotkey/update-a-configuration-file.ahk b/Task/Update-a-configuration-file/AutoHotkey/update-a-configuration-file.ahk new file mode 100644 index 0000000000..94e1025cde --- /dev/null +++ b/Task/Update-a-configuration-file/AutoHotkey/update-a-configuration-file.ahk @@ -0,0 +1,92 @@ +; Author: AlephX, Aug 17 2011 +data = %A_scriptdir%\rosettaconfig.txt +outdata = %A_scriptdir%\rosettaconfig.tmp +FileDelete, %outdata% + +NUMBEROFBANANAS := 1024 +numberofstrawberries := 560 +NEEDSPEELING = "0" +FAVOURITEFRUIT := "bananas" +SEEDSREMOVED = "1" +BOOL0 = "0" +BOOL1 = "1" +NUMBER1 := 1 +number0 := 0 +STRINGA := "string here" + +parameters = bool0|bool1|NUMBER1|number0|stringa|NEEDSPEELING|seedsremoved|numberofbananas|numberofstrawberries + +Loop, Read, %data%, %outdata% + { + if (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "") + { + Line := A_LoopReadLine + } + else + { + if instr(A_LoopReadLine, ";") == 1 + { + parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "") + + parametervalue = %parameter% + value := %parametervalue% + if value == 0 + Line := A_loopReadLine + else + Line := Parameter + } + else + { + parameter := RegExReplace(A_LoopReadLine, "^[ \s]+|[ \s]+$", "") + if instr(parameter, A_Space) + parameter := substr(parameter, 1, instr(parameter, A_Space)-1) + + if instr(parameters, parameter) > 0 + { + parametervalue = %parameter% + value := %parametervalue% + + if (value = chr(34) . "0" . chr(34)) + Line := "; " . Parameter + else + { + if (value = chr(34) . "1" . chr(34)) + Line := Parameter + else + Line = %parametervalue% %value% + } + } + else + Line := A_LoopReadLine + } + + } + StringReplace, parameters, parameters, %parametervalue%,, + StringReplace, parameters, parameters,||,| + + FileAppend, %Line%`n + } + +Loop, parse, parameters,| + { + if (A_Loopfield <> "") + { + StringUpper, parameter, A_LoopField + parametervalue = %parameter% + value := %parametervalue% + + if (value = chr(34) . "0" . chr(34)) + Line := "; " . parameter + else + { + if (value = chr(34) . "1" . chr(34)) + Line := parameter + else + Line = %parametervalue% %value% + } + + FileAppend, %Line%`n, %outdata% + } + } + +FileCopy, %A_scriptdir%\rosettaconfig.tmp, %A_scriptdir%\rosettaconfig.txt, 1 diff --git a/Task/Update-a-configuration-file/C/update-a-configuration-file.c b/Task/Update-a-configuration-file/C/update-a-configuration-file.c new file mode 100644 index 0000000000..43a1e5c574 --- /dev/null +++ b/Task/Update-a-configuration-file/C/update-a-configuration-file.c @@ -0,0 +1,67 @@ +#include +#include +#include + +#define strcomp(X, Y) strcasecmp(X, Y) + +struct option +{ const char *name, *value; + int flag; }; + +/* TODO: dynamically obtain these */ +struct option updlist[] = +{ { "NEEDSPEELING", NULL }, + { "SEEDSREMOVED", "" }, + { "NUMBEROFBANANAS", "1024" }, + { "NUMBEROFSTRAWBERRIES", "62000" }, + { NULL, NULL } }; + +int output_opt(FILE *to, struct option *opt) +{ if (opt->value == NULL) + return fprintf(to, "; %s\n", opt->name); + else if (opt->value[0] == 0) + return fprintf(to, "%s\n", opt->name); + else + return fprintf(to, "%s %s\n", opt->name, opt->value); } + +int update(FILE *from, FILE *to, struct option *updlist) +{ char line_buf[256], opt_name[128]; + int i; + for (;;) + { size_t len, space_span, span_to_hash; + if (fgets(line_buf, sizeof line_buf, from) == NULL) + break; + len = strlen(line_buf); + space_span = strspn(line_buf, "\t "); + span_to_hash = strcspn(line_buf, "#"); + if (space_span == span_to_hash) + goto line_out; + if (space_span == len) + goto line_out; + if ((sscanf(line_buf, "; %127s", opt_name) == 1) || + (sscanf(line_buf, "%127s", opt_name) == 1)) + { int flag = 0; + for (i = 0; updlist[i].name; i++) + { if (strcomp(updlist[i].name, opt_name) == 0) + { if (output_opt(to, &updlist[i]) < 0) + return -1; + updlist[i].flag = 1; + flag = 1; } } + if (flag == 0) + goto line_out; } + else + line_out: + if (fprintf(to, "%s", line_buf) < 0) + return -1; + continue; } + { for (i = 0; updlist[i].name; i++) + { if (!updlist[i].flag) + if (output_opt(to, &updlist[i]) < 0) + return -1; } } + return feof(from) ? 0 : -1; } + +int main(void) +{ if (update(stdin, stdout, updlist) < 0) + { fprintf(stderr, "failed\n"); + return (EXIT_FAILURE); } + return 0; } diff --git a/Task/Update-a-configuration-file/D/update-a-configuration-file.d b/Task/Update-a-configuration-file/D/update-a-configuration-file.d new file mode 100644 index 0000000000..b644f14a9f --- /dev/null +++ b/Task/Update-a-configuration-file/D/update-a-configuration-file.d @@ -0,0 +1,113 @@ +import std.stdio, std.file, std.string, std.regex, std.path, + std.typecons; + +final class Config { + enum EntryType { empty, enabled, disabled, comment, ignore } + + static protected struct Entry { + EntryType type; + string name, value; + } + protected Entry[] entries; + protected string path; + + this(in string path) { + if (!isValidPath(path) || (exists(path) && !isFile(path))) + throw new Exception("Invalid filename"); + + this.path = path; + if (!exists(path)) + return; + + auto r = regex(r"^(;*)\s*([A-Z0-9]+)\s*([A-Z0-9]*)", "i"); + auto f = File(path, "r"); + foreach (const buf; f.byLine()) { + auto line = buf.strip().idup; + if (!line.length) + entries ~= Entry(EntryType.empty); + else if (line[0] == '#') + entries ~= Entry(EntryType.comment, line); + else { + line = line.removechars("^a-zA-Z0-9\x20;"); + auto m = match(line, r); + if (!m.empty && m.front[2].length) { + EntryType t = EntryType.enabled; + if (m.front[1].length) + t = EntryType.disabled; + addOption(m.front[2], m.front[3], t); + } + } + } + } + + void enableOption(in string name) pure { + immutable i = getOptionIndex(name); + if (!i.isNull) + entries[i].type = EntryType.enabled; + } + + void disableOption(in string name) pure { + immutable i = getOptionIndex(name); + if (!i.isNull) + entries[i].type = EntryType.disabled; + } + + void setOption(in string name, in string value) pure { + immutable i = getOptionIndex(name); + if (!i.isNull) + entries[i].value = value; + } + + void addOption(in string name, in string val, + in EntryType t = EntryType.enabled) pure { + entries ~= Entry(t, name.toUpper(), val); + } + + void removeOption(in string name) pure { + immutable i = getOptionIndex(name); + if (!i.isNull) + entries[i].type = EntryType.ignore; + } + + Nullable!size_t getOptionIndex(in string name) const pure { + foreach (immutable i, const ref e; entries) { + if (e.type != EntryType.enabled && + e.type != EntryType.disabled) + continue; + if (e.name == name.toUpper()) + return typeof(return)(i); + } + return typeof(return).init; + } + + void store() { + auto f = File(path, "w+"); + foreach (immutable e; entries) { + final switch (e.type) { + case EntryType.empty: + f.writeln(); + break; + case EntryType.enabled: + f.writefln("%s %s", e.name, e.value); + break; + case EntryType.disabled: + f.writefln("; %s %s", e.name, e.value); + break; + case EntryType.comment: + f.writeln(e.name); + break; + case EntryType.ignore: + continue; + } + } + } +} + +void main() { + auto cfg = new Config("config.txt"); + cfg.enableOption("seedsremoved"); + cfg.disableOption("needspeeling"); + cfg.setOption("numberofbananas", "1024"); + cfg.addOption("numberofstrawberries", "62000"); + cfg.store(); +} diff --git a/Task/Update-a-configuration-file/Go/update-a-configuration-file.go b/Task/Update-a-configuration-file/Go/update-a-configuration-file.go new file mode 100644 index 0000000000..ea0086f8c6 --- /dev/null +++ b/Task/Update-a-configuration-file/Go/update-a-configuration-file.go @@ -0,0 +1,204 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "log" + "os" + "strings" + "unicode" +) + +// line represents a single line in the configuration file. +type line struct { + kind lineKind + option string + value string + disabled bool +} + +// lineKind represents the different kinds of configuration line. +type lineKind int + +const ( + _ lineKind = iota + ignore + parseError + comment + blank + value +) + +func (l line) String() string { + switch l.kind { + case ignore, parseError, comment, blank: + return l.value + case value: + s := l.option + if l.disabled { + s = "; " + s + } + if l.value != "" { + s += " " + l.value + } + return s + } + panic("unexpected line kind") +} + +func removeDross(s string) string { + return strings.Map(func(r rune) rune { + if r < 32 || r > 0x7f || unicode.IsControl(r) { + return -1 + } + return r + }, s) +} + +func parseLine(s string) line { + if s == "" { + return line{kind: blank} + } + if s[0] == '#' { + return line{kind: comment, value: s} + } + s = removeDross(s) + fields := strings.Fields(s) + if len(fields) == 0 { + return line{kind: blank} + } + // Strip leading semicolons (but record that we found them) + semi := false + for len(fields[0]) > 0 && fields[0][0] == ';' { + semi = true + fields[0] = fields[0][1:] + } + // Lose the first field if it was all semicolons + if fields[0] == "" { + fields = fields[1:] + } + switch len(fields) { + case 0: + // This can only happen if the line starts + // with a semicolon but has no other information + return line{kind: ignore} + case 1: + return line{ + kind: value, + option: strings.ToUpper(fields[0]), + disabled: semi, + } + case 2: + return line{ + kind: value, + option: strings.ToUpper(fields[0]), + value: fields[1], + disabled: semi, + } + } + return line{kind: parseError, value: s} +} + +// Config represents a "standard" configuration file. +type Config struct { + options map[string]int // index of each option in lines. + lines []line +} + +// index returns the index of the given option in +// c.lines, or -1 if not found. +func (c *Config) index(option string) int { + if i, ok := c.options[option]; ok { + return i + } + return -1 +} + +// addLine adds a line to the config, ignoring +// duplicate options and "ignore" lines. +func (c *Config) addLine(l line) { + switch l.kind { + case ignore: + return + case value: + if c.index(l.option) >= 0 { + return + } + c.options[l.option] = len(c.lines) + c.lines = append(c.lines, l) + default: + c.lines = append(c.lines, l) + } +} + +// ReadConfig reads a configuration file from path and returns it. +func ReadConfig(path string) (*Config, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + r := bufio.NewReader(f) + c := &Config{options: make(map[string]int)} + for { + s, err := r.ReadString('\n') + if s != "" { + if err == nil { + // strip newline unless we encountered an error without finding one. + s = s[:len(s)-1] + } + c.addLine(parseLine(s)) + } + if err == io.EOF { + break + } + if err != nil { + return nil, err + } + } + return c, nil +} + +// Set sets an option to a value, adding the option if necessary. If +// the option was previously disabled, it will be enabled. +func (c *Config) Set(option string, val string) { + if i := c.index(option); i >= 0 { + line := &c.lines[i] + line.disabled = false + line.value = val + return + } + c.addLine(line{ + kind: value, + option: option, + value: val, + }) +} + +// Enable sets the enabled status of an option. It is +// ignored if the option does not already exist. +func (c *Config) Enable(option string, enabled bool) { + if i := c.index(option); i >= 0 { + c.lines[i].disabled = !enabled + } +} + +// Write writes the configuration file to the writer. +func (c *Config) Write(w io.Writer) { + for _, line := range c.lines { + fmt.Println(line) + } +} + +func main() { + c, err := ReadConfig("/tmp/cfg") + if err != nil { + log.Fatalln(err) + } + c.Enable("NEEDSPEELING", false) + c.Set("SEEDSREMOVED", "") + c.Set("NUMBEROFBANANAS", "1024") + c.Set("NUMBEROFSTRAWBERRIES", "62000") + c.Write(os.Stdout) +} diff --git a/Task/Update-a-configuration-file/J/update-a-configuration-file-1.j b/Task/Update-a-configuration-file/J/update-a-configuration-file-1.j new file mode 100644 index 0000000000..cbfa96d74b --- /dev/null +++ b/Task/Update-a-configuration-file/J/update-a-configuration-file-1.j @@ -0,0 +1,36 @@ +require 'regex strings' + +normalize=:3 :0 + seen=. a: + eol=. {:;y + t=. '' + for_line.<;._2;y do. lin=. deb line=.>line + if. '#'={.line do. t=.t,line,eol + elseif. ''-:lin do. t =. t,eol + elseif. do. + line=. 1 u:([-.-.)&(32+i.95)&.(3&u:) line + base=. ('^ *;;* *';'') rxrplc line + nm=. ;name=. {.;:toupper base + if. -. name e. seen do. + seen=. seen, name + t=. t,eol,~dtb ('; '#~';'={.lin),(('^(?i) *',nm,'\b *');(nm,' ')) rxrplc base + end. + end. + end.t +) + +enable=:1 :0 + (; + push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n" + unless grep { /^;*[ \t]*NUMBEROFSTRAWBERRIES\b/; } @config; + + foreach my $line (@config) { + + if (substr($line, 0, 1) eq '#') { + push @out, $line; + next; + } + + next if $line =~ /^[;\t ]+$/; + + my ($option, $option_name); + + if ($line =~ /^([A-Z]+[0-9]*)/) { + $option_name = lc $1; + $option = eval "\\\$$option_name"; + my $value = eval "\${$option_name}"; + + if ($value) { + $$option = $value; + } + else { + $line = '; ' . $line; + $$option = undef; + } + } + elsif ($line =~ /^;+\s*([A-Z]+[0-9]*)/) { + $option_name = lc $1; + $option = eval "\\\$$option_name"; + my $value = eval "\${$option_name}"; + + if ($value) { + $line =~ s/^;+\s*//; + $$option = $value == 1 ? '' : $value; + } + else { + $$option = undef; + } + } + + if (defined $$option) { + push @out, "\U$option_name\E $$option\n" + unless grep { /^\U$option_name\E\b/; } @out; + } + else { + $line =~ s/\s*[^[:ascii:]]+\s*$//; + $line =~ s/[[:cntrl:]\s]+$//; + push(@out, "$line\n"); + } + } +} + +config(); + +my $file = join('', @out); +$file =~ s/\n{3,}/\n\n/g; + +print $file; + +__DATA__ +# This is a configuration file in standard configuration file format +# +# Lines begininning with a hash or a semicolon are ignored by the application +# program. Blank lines are also ignored by the application program. + +# The first word on each non comment line is the configuration option. +# Remaining words or numbers on the line are configuration parameter +# data fields. + +# Note that configuration option names are not case sensitive. However, +# configuration parameter data is case sensitive and the lettercase must +# be preserved. + +# This is a favourite fruit +FAVOURITEFRUIT banana + +# This is a boolean that should be set +NEEDSPEELING + +# This boolean is commented out +; SEEDSREMOVED + +# How many bananas we have +NUMBEROFBANANAS 48 diff --git a/Task/Update-a-configuration-file/PicoLisp/update-a-configuration-file.l b/Task/Update-a-configuration-file/PicoLisp/update-a-configuration-file.l new file mode 100644 index 0000000000..da72049ff4 --- /dev/null +++ b/Task/Update-a-configuration-file/PicoLisp/update-a-configuration-file.l @@ -0,0 +1,56 @@ +(let Data # Read all data + (in "config" + (make + (until (eof) + (link (trim (split (line) " "))) ) ) ) + (setq Data # Fix comments + (mapcar + '((L) + (while (head '(";" ";") (car L)) + (pop L) ) + (if (= '(";") (car L)) + L + (cons NIL L) ) ) + Data ) ) + (let (Need NIL Seed NIL NBan NIL NStr NIL Favo NIL) + (map + '((L) + (let D (mapcar uppc (cadar L)) + (cond + ((= '`(chop "NEEDSPEELING") D) + (if Need + (set L) + (on Need) + (unless (caar L) + (set (car L) '(";")) ) ) ) + ((= '`(chop "SEEDSREMOVED") D) + (if Seed + (set L) + (on Seed) + (when (caar L) + (set (car L)) ) ) ) + ((= '`(chop "NUMBEROFBANANAS") D) + (if NBan + (set L) + (on NBan) + (set (cddar L) 1024) ) ) + ((= '`(chop "NUMBEROFSTRAWBERRIES") D) + (if NStr + (set L) + (on NStr) ) ) + ((= '`(chop "FAVOURITEFRUIT") D) + (if Favo + (set L) + (on Favo) ) ) ) ) ) + Data ) + (unless Need + (conc Data (cons (list NIL "NEEDSPEELING"))) ) + (unless Seed + (conc Data (cons (list NIL "SEEDSREMOVED"))) ) + (unless NBan + (conc Data (cons (list NIL "NUMBEROFBANANAS" 1024))) ) + (unless NStr + (conc Data (cons (list NIL "NUMBEROFSTRAWBERRIES" 62000))) ) ) + (out "config" + (for L Data + (prinl (glue " " (if (car L) L (cdr L)))) ) ) ) diff --git a/Task/Update-a-configuration-file/Python/update-a-configuration-file.py b/Task/Update-a-configuration-file/Python/update-a-configuration-file.py new file mode 100644 index 0000000000..683598ebbc --- /dev/null +++ b/Task/Update-a-configuration-file/Python/update-a-configuration-file.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python + +#---------------------------------------------------------------------------- +# STANDARD MODULES +#---------------------------------------------------------------------------- +import re +import string + + +#---------------------------------------------------------------------------- +# GLOBAL: VARIABLES +#---------------------------------------------------------------------------- +DISABLED_PREFIX = ';' + + +#---------------------------------------------------------------------------- +# CLASS Option +#---------------------------------------------------------------------------- +class Option(object): + """An option, characterized by its name and its (optional) value. and by + its status, which can be enabled or disabled. + If its value is None, it is regarded to as a boolean option with a + value of true. + """ + + #------------------------------------------------------------------------ + def __init__(self, name, value=None, disabled=False, + disabled_prefix=DISABLED_PREFIX): + """Create an Option instance, setting its name to 'name' (always + converted to a string) and its value to 'value'. If 'disabled' is + True, the option is considered disabled, otherwise enabled. + The string 'disabled_prefix' is used as a prefix when generating the + string representation of the option. + """ + self.name = str(name) + self.value = value + self.disabled = bool(disabled) + self.disabled_prefix = disabled_prefix + + #------------------------------------------------------------------------ + def __str__(self): + """Return a string representation of the Option instance. + This always includes the option name, followed by a space and the + option value (if it is not None). If the option is disabled, the + whole string is preprendend by the string stored in the instance + attribute 'disabled_prefix' and a space. + """ + disabled = ('', '%s ' % self.disabled_prefix)[self.disabled] + value = (' %s' % self.value, '')[self.value is None] + return ''.join((disabled, self.name, value)) + + #------------------------------------------------------------------------ + def get(self): + """Return the option value. + If the stored value is None, the option is regarded to as a + boolean one and its enabled status is returned. Othrwise its value + is returned. + """ + enabled = not bool(self.disabled) + if self.value is None: + value = enabled + else: + value = enabled and self.value + return value + + +#---------------------------------------------------------------------------- +# CLASS Config +#---------------------------------------------------------------------------- +class Config(object): + """A set of configuration options and comment strings. + """ + # Regular expression matching a valid option line. + reOPTION = r'^\s*(?P%s*)\s*(?P\w+)(?:\s+(?P.+?))?\s*$' + + #------------------------------------------------------------------------ + def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX): + """Initialize a Config instance, optionally reading the contents of + the configuration file 'fname'. + The string 'disabled_prefix' is used as a prefix when generating the + string representation of the options. + """ + self.disabled_prefix = disabled_prefix + self.contents = [] # Sequence of strings and Option instances. + self.options = {} # Map an option name to an Option instance. + self.creOPTION = re.compile(self.reOPTION % self.disabled_prefix) + if fname: + self.parse_file(fname) + + #------------------------------------------------------------------------ + def __str__(self): + """Return a string representation of the Config instance. + This is just the concatenation of all the items stored in the + attribute 'contents'. + """ + return '\n'.join(map(str, self.contents)) + + #------------------------------------------------------------------------ + def parse_file(self, fname): + """Parse all the lines of file 'fname' by applying the method + 'parser_lines' on the file contents. + """ + with open(fname) as f: + self.parse_lines(f) + return self + + #------------------------------------------------------------------------ + def parse_lines(self, lines): + """Parse all the lines of iterable 'lines' by invoking the method + 'parse_line' for each line in 'lines'. + """ + for line in lines: + self.parse_line(line) + return self + + #------------------------------------------------------------------------ + def parse_line(self, line): + """Parse the line 'line', looking for options. + If an option line is found, spaces are stripped from the start and + the end of 'line' and any non-printable character is removed as well. + Only the first occurrence of an option is processed, all the other + occurrences are ignored. A valid option is added to the instance + attribute 'contents' (in order to preserve its position among the + other lines). It is also added to the mapping stored in the instance + attribute 'options'. + Any non-option string is added the the instance attribute 'contents', + except those lines starting with the string stored into the instance + attribute 'disabled_prefix' which are not followed by any option + name. + """ + s = ''.join(c for c in line.strip() if c in string.printable) + moOPTION = self.creOPTION.match(s) + if moOPTION: + name = moOPTION.group('name').upper() + if not name in self.options: + self.add_option(name, moOPTION.group('value'), + moOPTION.group('disabled')) + else: + if not s.startswith(self.disabled_prefix): + self.contents.append(line.rstrip()) + return self + + #------------------------------------------------------------------------ + def add_option(self, name, value=None, disabled=False): + """Create a new Option instance, named 'name' (always converted to + uppercase) with value 'value' and set its disabled status to + 'disabled'. + The Option instance is added to the instance attribute 'contents'. + It is also added to the mapping stored in the instance attribute + 'options'. + """ + name = name.upper() + opt = Option(name, value, disabled) + self.options[name] = opt + self.contents.append(opt) + return opt + + #------------------------------------------------------------------------ + def set_option(self, name, value=None, disabled=False): + """Look for an option named 'name' (always converted to + uppercase) among the options stored in the instance + attribute 'options'. + If it is not found, a new Option instance is created. + In any case its value is set to 'value' and its disabled + status to 'disabled'. + """ + name = name.upper() + opt = self.options.get(name) + if opt: + opt.value = value + opt.disabled = disabled + else: + opt = self.add_option(name, value, disabled) + return opt + + #------------------------------------------------------------------------ + def enable_option(self, name, value=None): + """Enable the option named 'name' (always converted to + uppercase) and set its value to 'value'. + If the option is not found, it is created and added to the + end of the instance attribute 'contents'. + """ + return self.set_option(name, value, False) + + #------------------------------------------------------------------------ + def disable_option(self, name, value=None): + """Disable the option named 'name' (always converted to + uppercase) and set its value to 'value'. + If the option is not found, it is created and added to the + end of the instance attribute 'contents'. + """ + return self.set_option(name, value, True) + + #------------------------------------------------------------------------ + def get_option(self, name): + """Return the value of the option named 'name' (always + converted to uppercase). + If the option is not found in the instance attribute + 'options', None is returned. If the stored value is None, + it is regarded to as a boolean option and its enable status + is returned. Otherwise its value is returned. + """ + opt = self.options.get(name.upper()) + value = opt.get() if opt else None + return value + + +#---------------------------------------------------------------------------- +# MAIN +#---------------------------------------------------------------------------- +if __name__ == '__main__': + import sys + cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None) + cfg.disable_option('needspeeling') + cfg.enable_option('seedsremoved') + cfg.enable_option('numberofbananas', 1024) + cfg.enable_option('numberofstrawberries', 62000) + print cfg diff --git a/Task/Update-a-configuration-file/Ruby/update-a-configuration-file.rb b/Task/Update-a-configuration-file/Ruby/update-a-configuration-file.rb new file mode 100644 index 0000000000..2bf1e62763 --- /dev/null +++ b/Task/Update-a-configuration-file/Ruby/update-a-configuration-file.rb @@ -0,0 +1,140 @@ +require 'stringio' + +class ConfigFile + + # create a ConfigFile object from a file + def self.file(filename) + fh = File.open(filename) + obj = self.new(fh) + obj.filename = filename + fh.close + obj + end + + # create a ConfigFile object from a string + def self.data(string) + fh = StringIO.new(string) + obj = self.new(fh) + fh.close + obj + end + + def initialize(filehandle) + @lines = filehandle.readlines + @filename = nil + tidy_file + end + attr :filename + + def save() + if @filename + File.open(@filename, "w") {|f| f.write(self)} + end + end + + def tidy_file() + @lines.map! do |line| + # remove leading whitespace + line.lstrip! + + if line.match(/^#/) + # Lines beginning with hash symbols should not be manipulated and left + # unchanged in the revised file. + line + else + # replace double semicolon prefixes with just a single semicolon + line.sub!(/^;+\s+/, "; ") + + if line.match(/^; \s*$/) + # Any lines beginning with a semicolon or groups of semicolons, but no + # following option should be removed + line = "" + else + # remove ... any trailing whitespace on the lines + line = line.rstrip + "\n" + + # Whitespace between the option and paramters should consist only of a + # single space + if m = line.match(/^(; )?([[:upper:]]+)\s+(.*)/) + line = (m[1].nil? ? "" : m[1]) + format_line(m[2], m[3]) + end + end + + line + end + end + end + + def format_line(option, value) + "%s%s\n" % [option.upcase.strip, value.nil? ? "" : " " + value.to_s.strip] + end + + # returns the index of the option, or nil if not found + def find_option(option) + @lines.find_index {|line| line.match(/^#{option.upcase.strip}\b/)} + end + + # uncomments a disabled option + def enable_option(option) + if idx = find_option("; " + option) + @lines[idx][/^; /] = "" + end + end + + # comment a line with a semi-colon + def disable_option(option) + if idx = find_option(option) + @lines[idx][/^/] = "; " + end + end + + # add an option, or change the value of an existing option. + # use nil for the value to set a boolean option + def set_value(option, value) + if idx = find_option(option) + @lines[idx] = format_line(option, value) + else + @lines << format_line(option, value) + end + end + + def to_s + @lines.join('') + end +end + + +config = ConfigFile.data(DATA.read) +config.disable_option('needspeeling') +config.enable_option('seedsremoved') +config.set_value('numberofbananas', 1024) +config.set_value('numberofstrawberries', 62000) +puts config + + +__END__ +# This is a configuration file in standard configuration file format +# +# Lines begininning with a hash or a semicolon are ignored by the application +# program. Blank lines are also ignored by the application program. + +# The first word on each non comment line is the configuration option. +# Remaining words or numbers on the line are configuration parameter +# data fields. + +# Note that configuration option names are not case sensitive. However, +# configuration parameter data is case sensitive and the lettercase must +# be preserved. + +# This is a favourite fruit +FAVOURITEFRUIT banana + +# This is a boolean that should be set + NEEDSPEELING + +# This boolean is commented out +;;; SEEDSREMOVED +;;; + +# How many bananas we have +NUMBEROFBANANAS 48 diff --git a/Task/Update-a-configuration-file/TXR/update-a-configuration-file.txr b/Task/Update-a-configuration-file/TXR/update-a-configuration-file.txr new file mode 100644 index 0000000000..ff30d70bbc --- /dev/null +++ b/Task/Update-a-configuration-file/TXR/update-a-configuration-file.txr @@ -0,0 +1,76 @@ +@(next :args) +@configfile +@(maybe) +@ (next configfile) +@ (collect :vars (config)) +@config +@ (end) +@(end) +@(collect) +@ (cases) +@option= +@ (output :into new_opt_line :filter :upcase) +; @option +@ (end) +@ (or) +@option=@val +@ (output :into new_opt_line :filter :upcase) +@option @val +@ (end) +@ (or) +@option +@ (output :into new_opt_line :filter :upcase) +@option +@ (end) +@ (end) +@ (next :var config) +@ (local new_config) +@ (bind new_config ()) +@ (collect :vars ((opt_there ""))) +@ (block) +@ (cases) +@ (cases) +@{line /[ \t]*/} +@ (or) +@{line /#.*/} +@ (end) +@ (output :append :into new_config) +@line +@ (end) +@ (accept) +@ (or) +@ (maybe) +; @opt_there +@ (or) +@opt_there @(skip) +@ (or) +@opt_there +@ (or) +@original_line +@ (end) +@ (end) +@ (cases) +@ (bind opt_there option :filter :upcase) +@ (output :append :into new_config) +@new_opt_line +@ (end) +@ (or) +@ (output :append :into new_config) +@original_line +@ (end) +@ (end) +@ (end) +@ (cases) +@ (bind opt_there option :filter :upcase) +@ (or) +@ (output :append :into new_config) +@new_opt_line +@ (end) +@ (end) +@ (set config new_config) +@(end) +@(output) +@ (repeat) +@config +@ (end) +@(end) diff --git a/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-1.tcl b/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-1.tcl new file mode 100644 index 0000000000..795f3bdc95 --- /dev/null +++ b/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-1.tcl @@ -0,0 +1,76 @@ +package require Tcl 8.6 +oo::class create Config { + variable filename contents + constructor fileName { + set filename $fileName + set contents {} + try { + set f [open $filename] + ### Sanitize during input + foreach line [split [read $f] \n] { + if {[string match "#*" $line]} { + lappend contents $line + continue + } + if {[regexp {^;\W*$} $line]} continue + set line [string trim [regsub -all {[^\u0020-\u007e]} $line {}]] + if {[regexp {^(\W*)(\w+)(.*)$} $line -> a b c]} { + set line "[regsub -all {^;+} $a {;}][string toupper $b]$c" + } + lappend contents $line + } + } finally { + if {[info exists f]} { + close $f + } + } + } + method save {} { + set f [open $filename w] + puts $f [join $contents \n] + close $f + } + + # Utility methods (not exposed API) + method Transform {pattern vars replacement} { + set matched 0 + set line -1 + set RE "(?i)^$pattern$" + foreach l $contents { + incr line + if {[uplevel 1 [list regexp $RE $l -> {*}$vars]]} { + if {$matched} { + set contents [lreplace $contents $line $line] + incr line -1 + } else { + lset contents $line [uplevel 1 [list subst $replacement]] + } + set matched 1 + } + } + return $matched + } + method Format {k v} { + set v " [string trimleft $v]" + return "[string toupper $k][string trimright $v]" + } + + # Public API for modifying options + method enable {option} { + if {![my Transform ";?\\s*($option)\\M\s*(.*)" {k v} \ + {[my Format $k $v]}]} { + lappend contents [my Format $option ""] + } + } + method disable {option} { + if {![my Transform ";?\\s*($option)\\M\s*(.*)" {k v} \ + {; [my Format $k $v]}]} { + lappend contents "; [my Format $option ""]" + } + } + method set {option {value ""}} { + if {![my Transform ";?\\s*($option)\\M.*" k {[my Format $k $value]}]} { + lappend contents [my Format $option $value] + } + } +} diff --git a/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-2.tcl b/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-2.tcl new file mode 100644 index 0000000000..276eb0b40f --- /dev/null +++ b/Task/Update-a-configuration-file/Tcl/update-a-configuration-file-2.tcl @@ -0,0 +1,6 @@ +set cfg [Config new "sample.cfg"] +$cfg disable needspeeling +$cfg enable seedsremoved +$cfg set numberofbananas 1024 +$cfg set numberofstrawberries 62000 +$cfg save diff --git a/Task/Use-another-language-to-call-a-function/0DESCRIPTION b/Task/Use-another-language-to-call-a-function/0DESCRIPTION new file mode 100644 index 0000000000..c0913a5f87 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/0DESCRIPTION @@ -0,0 +1,23 @@ +{{clarified-review}} +This task is inverse to the task [[Call foreign language function]]. Consider the following [[C]] program: +#include + +extern int Query (char * Data, size_t * Length); + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + if (0 == Query (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } +} +Write an implementation of Query in your language and make ''main'' calling it. The function Query takes the buffer a places the string ''Here am I'' into it. The buffer size in bytes is specified by the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1. diff --git a/Task/Use-another-language-to-call-a-function/1META.yaml b/Task/Use-another-language-to-call-a-function/1META.yaml new file mode 100644 index 0000000000..f6d82c59ad --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Programming environment operations diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada new file mode 100644 index 0000000000..b8e500de2a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada @@ -0,0 +1,8 @@ +with Interfaces.C; use Interfaces.C; +with Interfaces.C.Strings; use Interfaces.C.Strings; + +package Exported is + function Query (Data : chars_ptr; Size : access size_t) + return int; + pragma Export (C, Query, "Query"); +end Exported; diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada new file mode 100644 index 0000000000..6f6dda465e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada @@ -0,0 +1,14 @@ +package body Exported is + function Query (Data : chars_ptr; Size : access size_t) + return int is + Result : char_array := "Here am I"; + begin + if Size.all < Result'Length then + return 0; + else + Update (Data, 0, Result); + Size.all := Result'Length; + return 1; + end if; + end Query; +end Exported; diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada new file mode 100644 index 0000000000..1e55d5dd28 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada @@ -0,0 +1,4 @@ +gcc -c main.c +gnatmake -c exported.adb +gnatbind -n exported.ali +gnatlink exported.ali main.o -o main diff --git a/Task/Use-another-language-to-call-a-function/AutoHotkey/use-another-language-to-call-a-function.ahk b/Task/Use-another-language-to-call-a-function/AutoHotkey/use-another-language-to-call-a-function.ahk new file mode 100644 index 0000000000..0adecec887 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/AutoHotkey/use-another-language-to-call-a-function.ahk @@ -0,0 +1,21 @@ +; Example: The following is a working script that displays a summary of all top-level windows. + +; For performance and memory conservation, call RegisterCallback() only once for a given callback: +if not EnumAddress ; Fast-mode is okay because it will be called only from this thread: + EnumAddress := RegisterCallback("EnumWindowsProc", "Fast") + +DetectHiddenWindows On ; Due to fast-mode, this setting will go into effect for the callback too. + +; Pass control to EnumWindows(), which calls the callback repeatedly: +DllCall("EnumWindows", UInt, EnumAddress, UInt, 0) +MsgBox %Output% ; Display the information accumulated by the callback. + +EnumWindowsProc(hwnd, lParam) +{ + global Output + WinGetTitle, title, ahk_id %hwnd% + WinGetClass, class, ahk_id %hwnd% + if title + Output .= "HWND: " . hwnd . "`tTitle: " . title . "`tClass: " . class . "`n" + return true ; Tell EnumWindows() to continue until all windows have been enumerated. +} diff --git a/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-1.c b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-1.c new file mode 100644 index 0000000000..c89bfb8bd1 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-1.c @@ -0,0 +1,32 @@ +#if 0 +I rewrote the driver according to good sense, my style, +and discussion. + +This is file main.c on Autumn 2011 ubuntu linux release. +The emacs compile command output: + +-*- mode: compilation; default-directory: "/tmp/" -*- +Compilation started at Mon Mar 12 20:25:27 + +make -k CFLAGS=-Wall main.o +cc -Wall -c -o main.o main.c + +Compilation finished at Mon Mar 12 20:25:27 +#endif + +#include +#include + +extern int Query(char *Data, unsigned *Length); + +int main(int argc, char *argv[]) { + char Buffer[1024], *pc; + unsigned Size = sizeof(Buffer); + if (!Query(Buffer, &Size)) + fputs("failed to call Query", stdout); + else + for (pc = Buffer; Size--; ++pc) + putchar(*pc); + putchar('\n'); + return EXIT_SUCCESS; +} diff --git a/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-2.c b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-2.c new file mode 100644 index 0000000000..ffa1e81d34 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-2.c @@ -0,0 +1,21 @@ +#if 0 +This is file query.c + +-*- mode: compilation; default-directory: "/tmp/" -*- +Compilation started at Mon Mar 12 20:36:25 + +make -k CFLAGS=-Wall query.o +cc -Wall -c -o query.o query.c + +Compilation finished at Mon Mar 12 20:36:26 +#endif + +#include + +int Query(char *Data, unsigned *Length) { + const char *message = "Here am I"; + unsigned n = strlen(message); + if (n <= *Length) + return strncpy(Data, message, (size_t)n), *Length = n, 1; + return 0; +} diff --git a/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-3.c b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-3.c new file mode 100644 index 0000000000..b55f3da67c --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/C/use-another-language-to-call-a-function-3.c @@ -0,0 +1,3 @@ +$ gcc main.c query.o -o main && ./main +Here am I +$ diff --git a/Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.delphi b/Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.delphi new file mode 100644 index 0000000000..03b285b733 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.delphi @@ -0,0 +1,21 @@ +function Query(Buffer: PChar; var Size: Int64): LongBool; +const + Text = 'Hello World!'; +begin + If not Assigned(Buffer) Then + begin + Size := 0; + Result := False; + Exit; + end; + If Size < Length(Text) Then + begin + Size := 0; + Result := False; + Exit; + end; + + Size := Length(Text); + Move(Text[1], Buffer^, Size); + Result := True; +end; diff --git a/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-1.go b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-1.go new file mode 100644 index 0000000000..53799e57ff --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-1.go @@ -0,0 +1,10 @@ +#include +#include "_cgo_export.h" + +void Run() +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + if (0 == Query (Buffer, &Size)) + ... diff --git a/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-2.go b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-2.go new file mode 100644 index 0000000000..c1152b0e0c --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-2.go @@ -0,0 +1,27 @@ +package main + +// #include +// extern void Run(); +import "C" +import "unsafe" + +func main() { + C.Run() +} + +const msg = "Here am I" + +//export Query +func Query(cbuf *C.char, csiz *C.size_t) C.int { + if int(*csiz) <= len(msg) { + return 0 + } + pbuf := uintptr(unsafe.Pointer(cbuf)) + for i := 0; i < len(msg); i++ { + *((*byte)(unsafe.Pointer(pbuf))) = msg[i] + pbuf++ + } + *((*byte)(unsafe.Pointer(pbuf))) = 0 + *csiz = C.size_t(len(msg) + 1) + return 1 +} diff --git a/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-1.hs b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-1.hs new file mode 100644 index 0000000000..b1a26bfef2 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-1.hs @@ -0,0 +1,31 @@ +#ifdef __GLASGOW_HASKELL__ +#include "Called_stub.h" +extern void __stginit_Called(void); +#endif +#include +#include + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + hs_init(&argc, &argv); +#ifdef __GLASGOW_HASKELL__ + hs_add_root(__stginit_Called); +#endif + + if (0 == query_hs (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } + + hs_exit(); + return 0; +} diff --git a/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-2.hs b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-2.hs new file mode 100644 index 0000000000..94c96cb02a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-2.hs @@ -0,0 +1,26 @@ +{-# LANGUAGE ForeignFunctionInterface #-} + +module Called where + +import Foreign +import Foreign.C.String (CString, withCStringLen) +import Foreign.C.Types + +-- place a string into the buffer pointed to by ptrBuff (with size +-- pointed to by ptrSize). If successful, sets number of overwritten +-- bytes in ptrSize and returns 1, otherwise, it does nothing and +-- returns 0 +query_hs :: CString -> Ptr CSize -> IO CInt +query_hs ptrBuff ptrSize = withCStringLen "Here I am" + (\(str, len) -> do + buffSize <- peek ptrSize + if sizeOf str > (fromIntegral buffSize) + then do + poke ptrSize 0 + return 0 + else do + poke ptrSize (fromIntegral len) + copyArray ptrBuff str len + return 1) + +foreign export ccall query_hs :: CString -> Ptr CSize -> IO CInt diff --git a/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-3.hs b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-3.hs new file mode 100644 index 0000000000..bbd5d09716 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-3.hs @@ -0,0 +1 @@ +ghc -c -O Called.hs diff --git a/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-4.hs b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-4.hs new file mode 100644 index 0000000000..b3f10ed3a0 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haskell/use-another-language-to-call-a-function-4.hs @@ -0,0 +1 @@ +ghc -optc-O calling.c Called.o Called_stub.o -o calling diff --git a/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe b/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe new file mode 100644 index 0000000000..a135ea7374 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe @@ -0,0 +1 @@ +untyped __call__("functionName", args); diff --git a/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-1.j b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-1.j new file mode 100644 index 0000000000..3856cf474e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-1.j @@ -0,0 +1 @@ +query=:3 :'0&#^:(y < #)''Here am I''' diff --git a/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-2.j b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-2.j new file mode 100644 index 0000000000..ea376cc4c9 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-2.j @@ -0,0 +1,17 @@ +#include +#include +#include + +int Query(char*,unsigned*); + +int main(int argc,char*argv[]) { + char Buffer[1024], *pc; + unsigned Size = (unsigned)sizeof(Buffer); + if (!Query(Buffer,&Size)) + fputs("Failed to call Query",stdout); + else + for (pc = Buffer; Size--; ++pc) + putchar(*pc); + putchar('\n'); + return EXIT_SUCCESS; +} diff --git a/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-3.j b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-3.j new file mode 100644 index 0000000000..5758d13783 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-3.j @@ -0,0 +1,117 @@ +// J Front End Example +// define _WIN32 for Windows, __MACH__ for MAC, J64 for 64-bit +// JE is loaded from current working directory + +//make jfex && LD_LIBRARY_PATH=/usr/local/j64-701/bin ./jfex + +#ifdef _WIN32 +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#define GETPROCADDRESS(h,p) GetProcAddress(h,p) +#define JDLLNAME "\\j.dll" +#else +#define _stdcall +#include +#define GETPROCADDRESS(h,p) dlsym(h,p) +#ifdef __MACH__ +#define JDLLNAME "/libj.dylib" +#else +#define JDLLNAME "/libj.so" +#endif +#define _getcwd getcwd +#endif + +#include +#include +#include +#include +#include"jfex.h" +#include"jlib.h" + +static JDoType jdo; +static JFreeType jfree; +static JgaType jga; +static JGetLocaleType jgetlocale; + +static J jt; +static void* hjdll; + +static char **adadbreak; +static void sigint(int k){**adadbreak+=1;signal(SIGINT,sigint);} +static char input[1000]; + +// J calls for input (debug suspension and 1!:1[1) and we call for input +char* _stdcall Jinput(J jt,char* prompt) +{ + fputs(prompt,stdout); + if(fgets(input, sizeof(input), stdin)) + { + fputs("\n",stdout); + **adadbreak+=1; + } + return input; +} + +static char*buffer = NULL; /**************************************/ +static unsigned length = 0; /**************************************/ +static int Jouts = 0; /**************************************/ + +// J calls for output +#define LINEFEED 10 /**************************************/ +void _stdcall Joutput(J jt,int type, char* s) /********************/ +{ + size_t L; + if(MTYOEXIT==type) exit((int)(I)s); + L = strlen(s); + L -= (L && (LINEFEED==s[L-1])); /* CRLF not handled. */ + if (L && (!Jouts)) { + length = L; + strncpy(buffer,s,L); + Jouts = 1; + } +} + +int Query(char*Data,unsigned*Length) +{ + void* callbacks[] = {Joutput,NULL,Jinput,0,(void*)SMCON}; + char pathdll[1000]; + _getcwd(pathdll,sizeof(pathdll)); + strcat(pathdll,JDLLNAME); +#ifdef _WIN32 + hjdll=LoadLibraryA(pathdll); +#else + hjdll=dlopen(pathdll,RTLD_LAZY); + if (NULL == hjdll) + hjdll=dlopen(JDLLNAME+1,RTLD_LAZY); /* use LD_LIBRARY_PATH */ +#endif + if(NULL == hjdll) + { + fprintf(stderr,"Unix use: $ LD_LIBRARY_PATH=path/to/libj.so %s\n","programName");//*argv); + fputs("Load library failed: ",stderr); + fputs(pathdll,stderr); + fputs("\n",stderr); + return 0; // load library failed + } + jt=((JInitType)GETPROCADDRESS(hjdll,"JInit"))(); + if(!jt) return 0; // JE init failed + ((JSMType)GETPROCADDRESS(hjdll,"JSM"))(jt,callbacks); + jdo=(JDoType)GETPROCADDRESS(hjdll,"JDo"); + jfree=(JFreeType)GETPROCADDRESS(hjdll,"JFree"); + jga=(JgaType)GETPROCADDRESS(hjdll,"Jga"); + jgetlocale=(JGetLocaleType)GETPROCADDRESS(hjdll,"JGetLocale"); + adadbreak=(char**)jt; // first address in jt is address of breakdata + signal(SIGINT,sigint); + { + char input[999]; + //memset(input,0,sizeof input); + buffer = Data; + sprintf(input,"query %u [ 0!:110<'rc_embed.ijs'\n",*Length); /***deceptive input routine, a hard coded string*********/ + jdo(jt,input); + if (!Jouts) + return 0; + *Length = length; + } + jfree(jt); + return 1; +} diff --git a/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-4.j b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-4.j new file mode 100644 index 0000000000..2083e0e41a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-4.j @@ -0,0 +1,10 @@ +# jfe makefile info +# customize to create makefile suitable for your platform +# 32bit builds on 64bit systems require -m32 in CFLAGS and FLAGS +# Unix requires -ldl in FLAGS and Windows does not + +CPPFLAGS= -I/usr/local/j64-602/system/examples/jfe +CFLAGS= -O0 -g +LOADLIBES= -ldl + +main: main.o Query.o diff --git a/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-5.j b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-5.j new file mode 100644 index 0000000000..c74fe63c1a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/J/use-another-language-to-call-a-function-5.j @@ -0,0 +1,3 @@ +$ make main && LD_LIBRARY_PATH=~/Downloads/jgplsrc/j/bin ./main +Here am I +$ diff --git a/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-1.lisaac b/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-1.lisaac new file mode 100644 index 0000000000..ebabdde279 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-1.lisaac @@ -0,0 +1,32 @@ +Section Header + ++ name := QUERY; +- external := `#define main _query_main`; +- external := `#define query Query`; + +Section External + +- query(buffer : NATIVE_ARRAY[CHARACTER], size : NATIVE_ARRAY[INTEGER]) : INTEGER <- ( + + s : STRING_CONSTANT; + + len, result : INTEGER; + s := "Here am I"; + len := s.count; + (len > size.item(0)).if { + result := 0; + } else { + 1.to len do { i : INTEGER; + buffer.put (s @ i) to (i - 1); + }; + size.put len to 0; + result := 1; + }; + result +); + +Section Public + +- main <- ( + + buffer : NATIVE_ARRAY[CHARACTER]; + + size : NATIVE_ARRAY[INTEGER]; + query(buffer, size); // need this to pull the query() method +); diff --git a/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-2.lisaac b/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-2.lisaac new file mode 100644 index 0000000000..3ef411ff1a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lisaac/use-another-language-to-call-a-function-2.lisaac @@ -0,0 +1,15 @@ +TARGET=test_query + +all: $(TARGET) + +$(TARGET): main.o query.o + gcc -o $@ main.o query.o + +.c.o: + gcc -c $< + +query.c: query.li + -lisaac $< + +clean: + rm -f $(TARGET) *.o query.c diff --git a/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ocaml b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ocaml new file mode 100644 index 0000000000..f1a7db42ed --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ocaml @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +extern int Query (char * Data, size_t * Length) +{ + static value * closure_f = NULL; + if (closure_f == NULL) { + closure_f = caml_named_value("Query function cb"); + } + value ret = caml_callback(*closure_f, Val_unit); + *Length = Int_val(Field(ret, 1)); + strncpy(Data, String_val(Field(ret, 0)), *Length); + return 1; +} + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + unsigned Size = 0; + + caml_main(argv); /* added from the original main */ + + if (0 == Query (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + printf("size: %d\n", Size); + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } +} diff --git a/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ocaml b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ocaml new file mode 100644 index 0000000000..987116f69f --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ocaml @@ -0,0 +1,8 @@ +let caml_query () = + let s = "Here am I" in + (s, String.length s) +;; + +let () = + Callback.register "Query function cb" caml_query; +;; diff --git a/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-1.l b/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-1.l new file mode 100644 index 0000000000..cb3eb3fd0b --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-1.l @@ -0,0 +1,3 @@ +(let (Str "Here am I" Len (format (opt))) # Get length from command line + (unless (>= (size Str) Len) # Check buffer size + (prinl Str) ) ) # Return string if OK diff --git a/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-2.l b/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-2.l new file mode 100644 index 0000000000..b4d50f5f23 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/PicoLisp/use-another-language-to-call-a-function-2.l @@ -0,0 +1,11 @@ +int Query(char *Data, size_t *Length) { + FILE *fp; + char buf[64]; + + sprintf(buf, "/usr/bin/picolisp query.l %d -bye", *Length); + if (!(fp = popen(buf, "r"))) + return 0; + fgets(Data, *Length, fp); + *Length = strlen(Data); + return pclose(fp) >= 0 && *Length != 0; +} diff --git a/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-1.py b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-1.py new file mode 100644 index 0000000000..9a0dca7245 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-1.py @@ -0,0 +1,6 @@ +# store this in file rc_embed.py +# store this in file rc_embed.py +def query(buffer_length): + message = b'Here am I' + L = len(message) + return message[0:L*(L <= buffer_length)] diff --git a/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-2.py b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-2.py new file mode 100644 index 0000000000..8e9f7c5d38 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-2.py @@ -0,0 +1,22 @@ +#if 0 +//I rewrote the driver according to good sense, my style, +//and discussion --Kernigh 15:45, 12 February 2011 (UTC). +#endif + +#include +#include +#include + +extern int Query(char*,unsigned*); + +int main(int argc,char*argv[]) { + char Buffer[1024], *pc; + unsigned Size = sizeof(Buffer); + if (!Query(Buffer,&Size)) + fputs("Failed to call Query",stdout); + else + for (pc = Buffer; Size--; ++pc) + putchar(*pc); + putchar('\n'); + return EXIT_SUCCESS; +} diff --git a/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-3.py b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-3.py new file mode 100644 index 0000000000..41acc9aef7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-3.py @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +int Query(char*Data,unsigned*Length) { + char *module = "rc_embed", *function = "query"; + PyObject *pName, *pModule, *pFunc, *pResult, *pArgs, *pLength; + long result = 0; + if (!Py_IsInitialized()) + Py_Initialize(); + pName = PyUnicode_FromString(module); + pModule = PyImport_Import(pName); + Py_DECREF(pName); + if (NULL == pModule) { + PyErr_Print(); + fprintf(stderr,"Failed to load \"%s\"\n",module); + return 0; + } + pFunc = PyObject_GetAttrString(pModule,function); + if ((NULL == pFunc) || (!PyCallable_Check(pFunc))) { + if (PyErr_Occurred()) + PyErr_Print(); + fprintf(stderr,"Cannot find function \"%s\"\n",function); + if (NULL != pFunc) + Py_DECREF(pFunc); + Py_DECREF(pModule); + return 0; + } + pArgs = PyTuple_New(1); + pLength = PyLong_FromUnsignedLong((unsigned long)(*Length)); + if (NULL == pLength) { + Py_DECREF(pArgs); + Py_DECREF(pFunc); + Py_DECREF(pModule); + return 0; + } + PyTuple_SetItem(pArgs,0,pLength); + pResult = PyObject_CallObject(pFunc, pArgs); + if (NULL == pResult) + result = 0; + else if (!PyBytes_Check(pResult)) { + result = 0; + Py_DECREF(pResult); + } else { + if (! PyBytes_Size(pResult)) + result = 0; + else { + *Length = (unsigned)PyBytes_Size(pResult); + strncpy(Data,PyBytes_AsString(pResult),*Length); + Py_DECREF(pResult); + result = 1; + } + } + Py_DECREF(pArgs); + Py_DECREF(pFunc); + Py_DECREF(pModule); + Py_Finalize(); + return result; +} diff --git a/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-4.py b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-4.py new file mode 100644 index 0000000000..67476d393b --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Python/use-another-language-to-call-a-function-4.py @@ -0,0 +1,12 @@ +$ make main.o +cc -c -o main.o main.c +$ D=$( dirname $( which python3 ) ) +$ gcc $( $D/python3.2-config --cflags ) -c Query.c +In file included from /usr/include/python3.2mu/Python.h:8:0, + from Q.c:18: +/usr/include/python3.2mu/pyconfig.h:1173:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default] +/usr/include/features.h:214:0: note: this is the location of the previous definition +$ gcc -o main main.o Query.o $( $D/python3.2-config --ldflags ) +$ ./main +Here am I +$ diff --git a/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-1.tcl b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-1.tcl new file mode 100644 index 0000000000..f1e4be160f --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-1.tcl @@ -0,0 +1,22 @@ +int Query (char * Data, size_t * Length) { + Tcl_Obj *arguments[2]; + int code; + + arguments[0] = Tcl_NewStringObj("Query", -1); /* -1 for "use up to zero byte" */ + arguments[1] = Tcl_NewStringObj(Data, Length); + Tcl_IncrRefCount(arguments[0]); + Tcl_IncrRefCount(arguments[1]); + if (Tcl_EvalObjv(interp, 2, arguments, 0) != TCL_OK) { + /* Was an error or other exception; report here... */ + Tcl_DecrRefCount(arguments[0]); + Tcl_DecrRefCount(arguments[1]); + return 0; + } + Tcl_DecrRefCount(arguments[0]); + Tcl_DecrRefCount(arguments[1]); + if (Tcl_GetObjResult(NULL, Tcl_GetObjResult(interp), &code) != TCL_OK) { + /* Not an integer result */ + return 0; + } + return code; +} diff --git a/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-2.tcl b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-2.tcl new file mode 100644 index 0000000000..3e4f08b383 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-2.tcl @@ -0,0 +1,4 @@ +proc Query data { + puts "Query was $data" + return 1; +} diff --git a/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-3.tcl b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-3.tcl new file mode 100644 index 0000000000..096e8359d2 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-3.tcl @@ -0,0 +1,14 @@ +int Query (char * Data, size_t * Length) { + const char *str; + int len; + + if (Tcl_Eval(interp, "Query") != TCL_OK) { + return 0; + } + str = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &len); + if (len+1 > Length) { + return 0; + } + memcpy(Data, str, len+1); + return 1; +} diff --git a/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-4.tcl b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-4.tcl new file mode 100644 index 0000000000..96e59bffe6 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-4.tcl @@ -0,0 +1,3 @@ +proc Query {} { + return "Here am I" +} diff --git a/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-5.tcl b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-5.tcl new file mode 100644 index 0000000000..de7a1c4e0b --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Tcl/use-another-language-to-call-a-function-5.tcl @@ -0,0 +1,9 @@ +#include +Tcl_Interp *interp; + +int main(int argc, char **argv) { + Tcl_FindExecutable(argv[0]); /* Initializes library */ + interp = Tcl_CreateInterp(); /* Make an interpreter */ + + /* Rest of contents of main() from task header... */ +} diff --git a/Task/User-input-Graphical/0DESCRIPTION b/Task/User-input-Graphical/0DESCRIPTION new file mode 100644 index 0000000000..202df31b6f --- /dev/null +++ b/Task/User-input-Graphical/0DESCRIPTION @@ -0,0 +1,3 @@ +In this task, the goal is to input a string and the integer 75000, from [[graphical user interface]]. + +See also: [[User input/Text]] diff --git a/Task/User-input-Graphical/1META.yaml b/Task/User-input-Graphical/1META.yaml new file mode 100644 index 0000000000..66076e8d10 --- /dev/null +++ b/Task/User-input-Graphical/1META.yaml @@ -0,0 +1,7 @@ +--- +category: +- GUI +- Basic language learning +note: Text processing +requires: +- Graphics diff --git a/Task/User-input-Graphical/Ada/user-input-graphical.ada b/Task/User-input-Graphical/Ada/user-input-graphical.ada new file mode 100644 index 0000000000..2fe58a3723 --- /dev/null +++ b/Task/User-input-Graphical/Ada/user-input-graphical.ada @@ -0,0 +1,80 @@ +with Gtk.Button; use Gtk.Button; +with Gtk.GEntry; use Gtk.GEntry; +with Gtk.Label; use Gtk.Label; +with Gtk.Window; use Gtk.Window; +with Gtk.Widget; use Gtk.Widget; +with Gtk.Table; use Gtk.Table; + +with Gtk.Handlers; +with Gtk.Main; + +procedure Graphic_Input is + Window : Gtk_Window; + Grid : Gtk_Table; + Label : Gtk_Label; + Message : Gtk_Label; + Edit : Gtk_GEntry; + Button : Gtk_Button; + + package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); + package Return_Handlers is + new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean); + + function Delete_Event (Widget : access Gtk_Widget_Record'Class) + return Boolean is + begin + return False; + end Delete_Event; + + procedure Destroy (Widget : access Gtk_Widget_Record'Class) is + begin + Gtk.Main.Main_Quit; + end Destroy; + + procedure Clicked (Widget : access Gtk_Widget_Record'Class) is + begin + if Get_Text (Label) = "Enter integer:" then + Set_Text (Message, "Entered:" & Integer'Image (Integer'Value (Get_Text (Edit)))); + Set_Sensitive (Button, False); + else + Set_Text (Message, "Entered:" & Get_Text (Edit)); + Set_Text (Label, "Enter integer:"); + end if; + exception + when Constraint_Error => + Set_Text (Message, "Error integer input"); + end Clicked; + +begin + Gtk.Main.Init; + Gtk.Window.Gtk_New (Window); + Gtk_New (Grid, 2, 3, False); + Add (Window, Grid); + Gtk_New (Label, "Enter string:"); + Attach (Grid, Label, 0, 1, 0, 1); + Gtk_New (Edit); + Attach (Grid, Edit, 1, 2, 0, 1); + Gtk_New (Button, "OK"); + Attach (Grid, Button, 2, 3, 0, 1); + Gtk_New (Message); + Attach (Grid, Message, 0, 3, 1, 2); + Return_Handlers.Connect + ( Window, + "delete_event", + Return_Handlers.To_Marshaller (Delete_Event'Access) + ); + Handlers.Connect + ( Window, + "destroy", + Handlers.To_Marshaller (Destroy'Access) + ); + Handlers.Connect + ( Button, + "clicked", + Handlers.To_Marshaller (Clicked'Access) + ); + Show_All (Grid); + Show (Window); + + Gtk.Main.Main; +end Graphic_Input; diff --git a/Task/User-input-Graphical/AppleScript/user-input-graphical-1.applescript b/Task/User-input-Graphical/AppleScript/user-input-graphical-1.applescript new file mode 100644 index 0000000000..16330f1d44 --- /dev/null +++ b/Task/User-input-Graphical/AppleScript/user-input-graphical-1.applescript @@ -0,0 +1 @@ +set input to text returned of (display dialog "Enter text:" default answer "") diff --git a/Task/User-input-Graphical/AppleScript/user-input-graphical-2.applescript b/Task/User-input-Graphical/AppleScript/user-input-graphical-2.applescript new file mode 100644 index 0000000000..9a7035e815 --- /dev/null +++ b/Task/User-input-Graphical/AppleScript/user-input-graphical-2.applescript @@ -0,0 +1 @@ +set input to text returned of (display dialog "Enter a number:" default answer "") as integer diff --git a/Task/User-input-Graphical/AutoHotkey/user-input-graphical-1.ahk b/Task/User-input-Graphical/AutoHotkey/user-input-graphical-1.ahk new file mode 100644 index 0000000000..6c329b11aa --- /dev/null +++ b/Task/User-input-Graphical/AutoHotkey/user-input-graphical-1.ahk @@ -0,0 +1,3 @@ +InputBox, String, Input, Enter a string: +InputBox, Int, Input, Enter an int: +Msgbox, You entered "%String%" and "%Int%" diff --git a/Task/User-input-Graphical/AutoHotkey/user-input-graphical-2.ahk b/Task/User-input-Graphical/AutoHotkey/user-input-graphical-2.ahk new file mode 100644 index 0000000000..85e3467b83 --- /dev/null +++ b/Task/User-input-Graphical/AutoHotkey/user-input-graphical-2.ahk @@ -0,0 +1,13 @@ +Gui, Add, Text,, String: +Gui, Add, Text,, Int: +Gui, Add, Button, gGo, Go! +Gui, Add, Edit, vString ym +Gui, Add, Edit, VInt +Gui, Show, Center, Input +Return + +Go: +Gui, Submit, NoHide +Msgbox, You entered "%String%" and "%Int%" +ExitApp +Return diff --git a/Task/User-input-Graphical/BBC-BASIC/user-input-graphical.bbc b/Task/User-input-Graphical/BBC-BASIC/user-input-graphical.bbc new file mode 100644 index 0000000000..4a704adaaa --- /dev/null +++ b/Task/User-input-Graphical/BBC-BASIC/user-input-graphical.bbc @@ -0,0 +1,25 @@ + INSTALL @lib$+"WINLIB2" + INSTALL @lib$+"WINLIB5" + ES_NUMBER = 8192 + + form% = FN_newdialog("Rosetta Code", 100, 100, 100, 64, 8, 1000) + PROC_static(form%, "String:", 100, 8, 8, 30, 14, 0) + PROC_editbox(form%, "Example", 101, 40, 6, 52, 14, 0) + PROC_static(form%, "Number:", 102, 8, 26, 30, 14, 0) + PROC_editbox(form%, "75000", 103, 40, 24, 52, 14, ES_NUMBER) + PROC_pushbutton(form%, "Read", FN_setproc(PROCread), 30, 43, 40, 16, 0) + PROC_showdialog(form%) + + REPEAT + WAIT 1 + UNTIL !form% = 0 + QUIT + + DEF PROCread + LOCAL buffer%, number% + DIM buffer% LOCAL 255 + SYS "GetDlgItemText", !form%, 101, buffer%, 255 + SYS "GetDlgItemInt", !form%, 103, 0, 1 TO number% + PRINT "String = """ $$buffer% """" + PRINT "Number = " ; number% + ENDPROC diff --git a/Task/User-input-Graphical/C++/user-input-graphical-1.cpp b/Task/User-input-Graphical/C++/user-input-graphical-1.cpp new file mode 100644 index 0000000000..98c1dac2a9 --- /dev/null +++ b/Task/User-input-Graphical/C++/user-input-graphical-1.cpp @@ -0,0 +1,25 @@ +#ifndef TASK_H +#define TASK_H + +#include + +class QLabel ; +class QLineEdit ; +class QVBoxLayout ; +class QHBoxLayout ; + +class EntryWidget : public QWidget { + + Q_OBJECT +public : + EntryWidget( QWidget *parent = 0 ) ; +private : + QHBoxLayout *upperpart , *lowerpart ; + QVBoxLayout *entryLayout ; + QLineEdit *stringinput ; + QLineEdit *numberinput ; + QLabel *stringlabel ; + QLabel *numberlabel ; +} ; + +#endif diff --git a/Task/User-input-Graphical/C++/user-input-graphical-2.cpp b/Task/User-input-Graphical/C++/user-input-graphical-2.cpp new file mode 100644 index 0000000000..261438be49 --- /dev/null +++ b/Task/User-input-Graphical/C++/user-input-graphical-2.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include +#include "task.h" + +EntryWidget::EntryWidget ( QWidget *parent ) + : QWidget( parent ) { + entryLayout = new QVBoxLayout( this ) ; + stringlabel = new QLabel( "Enter a string!" ) ; + stringinput = new QLineEdit( "" ) ; + stringinput->setMaxLength( 20 ) ; + stringinput->setInputMask( QString( "AAAAAAAAAAAAAAAAAAA" ) ) ; + upperpart = new QHBoxLayout ; + upperpart->addWidget( stringlabel ) ; + upperpart->addWidget( stringinput ) ; + numberlabel = new QLabel( "Enter a number!" ) ; + numberinput = new QLineEdit( "0" ) ; + numberinput->setMaxLength( 5 ) ; + numberinput->setInputMask( QString( "99999" ) ) ; + lowerpart = new QHBoxLayout ; + lowerpart->addWidget( numberlabel ) ; + lowerpart->addWidget( numberinput ) ; + entryLayout->addLayout( upperpart ) ; + entryLayout->addLayout( lowerpart ) ; + setLayout( entryLayout ) ; +} diff --git a/Task/User-input-Graphical/C++/user-input-graphical-3.cpp b/Task/User-input-Graphical/C++/user-input-graphical-3.cpp new file mode 100644 index 0000000000..c4ab04716e --- /dev/null +++ b/Task/User-input-Graphical/C++/user-input-graphical-3.cpp @@ -0,0 +1,9 @@ +#include +#include "task.h" + +int main( int argc , char *argv[ ] ) { + QApplication app( argc , argv ) ; + EntryWidget theWidget ; + theWidget.show( ) ; + return app.exec( ) ; +} diff --git a/Task/User-input-Graphical/C/user-input-graphical.c b/Task/User-input-Graphical/C/user-input-graphical.c new file mode 100644 index 0000000000..4568539f91 --- /dev/null +++ b/Task/User-input-Graphical/C/user-input-graphical.c @@ -0,0 +1,74 @@ +#include + +void ok_hit(GtkButton *o, GtkWidget **w) +{ + GtkMessageDialog *msg; + + gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); + const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]); + + msg = (GtkMessageDialog *) + gtk_message_dialog_new(NULL, + GTK_DIALOG_MODAL, + (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, + GTK_BUTTONS_OK, + "You wrote '%s' and selected the number %d%s", + c, (gint)v, + (v==75000) ? "" : " which is wrong (75000 expected)!"); + gtk_widget_show_all(GTK_WIDGET(msg)); + (void)gtk_dialog_run(GTK_DIALOG(msg)); + gtk_widget_destroy(GTK_WIDGET(msg)); + if ( v==75000 ) gtk_main_quit(); +} + +int main(int argc, char **argv) +{ + GtkWindow *win; + GtkEntry *entry; + GtkSpinButton *spin; + GtkButton *okbutton; + GtkLabel *entry_l, *spin_l; + GtkHBox *hbox[2]; + GtkVBox *vbox; + GtkWidget *widgs[2]; + + gtk_init(&argc, &argv); + + win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(win, "Insert values"); + + entry_l = (GtkLabel *)gtk_label_new("Insert a string"); + spin_l = (GtkLabel *)gtk_label_new("Insert 75000"); + + entry = (GtkEntry *)gtk_entry_new(); + spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1); + + widgs[0] = GTK_WIDGET(entry); + widgs[1] = GTK_WIDGET(spin); + + okbutton = (GtkButton *)gtk_button_new_with_label("Ok"); + + hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); + hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1); + + vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1); + + gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); + gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); + gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); + gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin)); + + gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); + gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); + gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton)); + + gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox)); + + g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); + g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs); + + gtk_widget_show_all(GTK_WIDGET(win)); + gtk_main(); + + return 0; +} diff --git a/Task/User-input-Graphical/Clojure/user-input-graphical.clj b/Task/User-input-Graphical/Clojure/user-input-graphical.clj new file mode 100644 index 0000000000..36033c063f --- /dev/null +++ b/Task/User-input-Graphical/Clojure/user-input-graphical.clj @@ -0,0 +1,6 @@ +(import 'javax.swing.JOptionPane) +(let [number (-> "Enter an Integer" + JOptionPane/showInputDialog + Integer/parseInt) + string (JOptionPane/showInputDialog "Enter a String")] + [number string]) diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-1.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-1.lisp new file mode 100644 index 0000000000..9a19c835dc --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-1.lisp @@ -0,0 +1 @@ +(capi:prompt-for-string "Enter a string:") diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-2.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-2.lisp new file mode 100644 index 0000000000..8b784c931e --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-2.lisp @@ -0,0 +1,4 @@ +(do ((number 0) (okp t)) + ((or (not okp) (= 75000 number))) + (multiple-value-setq (number okp) + (capi:prompt-for-integer "Enter an integer:"))) diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-3.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-3.lisp new file mode 100644 index 0000000000..b2e0e6290c --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-3.lisp @@ -0,0 +1,2 @@ +(capi:prompt-for-integer "Enter an integer:" + :ok-check #'(lambda (n) (= n 75000))) diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-4.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-4.lisp new file mode 100644 index 0000000000..6240cedf0c --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-4.lisp @@ -0,0 +1,13 @@ +(capi:define-interface string/integer-prompt () () + (:panes + (string-pane + capi:text-input-pane + :title "Enter a string:") + (integer-pane + capi:text-input-pane + :title "Enter an integer:" + :change-callback :redisplay-interface)) + (:layouts + (main + capi:column-layout + '(string-pane integer-pane)))) diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-5.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-5.lisp new file mode 100644 index 0000000000..a47ad3802b --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-5.lisp @@ -0,0 +1,7 @@ +(defun string/integer-prompt-value (pane) + (with-slots (string-pane integer-pane) pane + (let* ((string (capi:text-input-pane-text string-pane)) + (integer-string (capi:text-input-pane-text integer-pane)) + (integer (when (every 'digit-char-p integer-string) + (parse-integer integer-string :junk-allowed t)))) + (values (cons string integer))))) diff --git a/Task/User-input-Graphical/Common-Lisp/user-input-graphical-6.lisp b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-6.lisp new file mode 100644 index 0000000000..938509cb59 --- /dev/null +++ b/Task/User-input-Graphical/Common-Lisp/user-input-graphical-6.lisp @@ -0,0 +1,6 @@ +(defun do-prompting () + (capi:popup-confirmer + (make-instance 'string/integer-prompt) + "Enter some values:" + :value-function 'string/integer-prompt-value + :ok-check #'(lambda (result) (eql (cdr result) 75000)))) diff --git a/Task/User-input-Graphical/Delphi/user-input-graphical.delphi b/Task/User-input-Graphical/Delphi/user-input-graphical.delphi new file mode 100644 index 0000000000..e9da90d3af --- /dev/null +++ b/Task/User-input-Graphical/Delphi/user-input-graphical.delphi @@ -0,0 +1,20 @@ +program UserInputGraphical; + +{$APPTYPE CONSOLE} + +uses SysUtils, Dialogs; + +var + s: string; + lStringValue: string; + lIntegerValue: Integer; +begin + lStringValue := InputBox('User input/Graphical', 'Enter a string', ''); + + repeat + s := InputBox('User input/Graphical', 'Enter the number 75000', '75000'); + lIntegerValue := StrToIntDef(s, 0); + if lIntegerValue <> 75000 then + ShowMessage('Invalid entry: ' + s); + until lIntegerValue = 75000; +end. diff --git a/Task/User-input-Graphical/Frink/user-input-graphical-1.frink b/Task/User-input-Graphical/Frink/user-input-graphical-1.frink new file mode 100644 index 0000000000..e806b8e16d --- /dev/null +++ b/Task/User-input-Graphical/Frink/user-input-graphical-1.frink @@ -0,0 +1,2 @@ +s = input["Enter a string: "] +i = parseInt[input["Enter an integer: "]] diff --git a/Task/User-input-Graphical/Frink/user-input-graphical-2.frink b/Task/User-input-Graphical/Frink/user-input-graphical-2.frink new file mode 100644 index 0000000000..620d40d83e --- /dev/null +++ b/Task/User-input-Graphical/Frink/user-input-graphical-2.frink @@ -0,0 +1,2 @@ +[s,i] = input["Dialog title", ["Enter a string", "Enter an integer"]] +i = parseInt[i] diff --git a/Task/User-input-Graphical/Haskell/user-input-graphical-1.hs b/Task/User-input-Graphical/Haskell/user-input-graphical-1.hs new file mode 100644 index 0000000000..dde1065dc3 --- /dev/null +++ b/Task/User-input-Graphical/Haskell/user-input-graphical-1.hs @@ -0,0 +1,61 @@ +import Graphics.UI.Gtk +import Control.Monad + +main = do + initGUI + + window <- windowNew + set window [windowTitle := "Graphical user input", containerBorderWidth := 10] + + vb <- vBoxNew False 0 + containerAdd window vb + + hb1 <- hBoxNew False 0 + boxPackStart vb hb1 PackNatural 0 + hb2 <- hBoxNew False 0 + boxPackStart vb hb2 PackNatural 0 + + lab1 <- labelNew (Just "Enter number 75000") + boxPackStart hb1 lab1 PackNatural 0 + nrfield <- entryNew + entrySetText nrfield "75000" + boxPackStart hb1 nrfield PackNatural 5 + + strfield <- entryNew + boxPackEnd hb2 strfield PackNatural 5 + lab2 <- labelNew (Just "Enter a text") + boxPackEnd hb2 lab2 PackNatural 0 + + accbox <- hBoxNew False 0 + boxPackStart vb accbox PackNatural 5 + im <- imageNewFromStock stockApply IconSizeButton + acceptButton <- buttonNewWithLabel "Accept" + buttonSetImage acceptButton im + boxPackStart accbox acceptButton PackRepel 0 + + txtstack <- statusbarNew + boxPackStart vb txtstack PackNatural 0 + id <- statusbarGetContextId txtstack "Line" + + widgetShowAll window + + onEntryActivate nrfield (showStat nrfield txtstack id) + onEntryActivate strfield (showStat strfield txtstack id) + + onPressed acceptButton $ do + g <- entryGetText nrfield + if g=="75000" then + widgetDestroy window + else do + msgid <- statusbarPush txtstack id "You didn't enter 75000. Try again" + return () + + onDestroy window mainQuit + mainGUI + +showStat :: Entry -> Statusbar -> ContextId -> IO () +showStat fld stk id = do + txt <- entryGetText fld + let mesg = "You entered \"" ++ txt ++ "\"" + msgid <- statusbarPush stk id mesg + return () diff --git a/Task/User-input-Graphical/Haskell/user-input-graphical-2.hs b/Task/User-input-Graphical/Haskell/user-input-graphical-2.hs new file mode 100644 index 0000000000..778419400f --- /dev/null +++ b/Task/User-input-Graphical/Haskell/user-input-graphical-2.hs @@ -0,0 +1 @@ +*Main> main diff --git a/Task/User-input-Graphical/HicEst/user-input-graphical.hicest b/Task/User-input-Graphical/HicEst/user-input-graphical.hicest new file mode 100644 index 0000000000..a2df6b5d62 --- /dev/null +++ b/Task/User-input-Graphical/HicEst/user-input-graphical.hicest @@ -0,0 +1,4 @@ +CHARACTER string*100 + +DLG(Edit=string, Edit=num_value, Button='&OK', TItle='Enter 75000 for num_value') +WRITE(Messagebox, Name) "You entered", string, num_value diff --git a/Task/User-input-Graphical/Icon/user-input-graphical.icon b/Task/User-input-Graphical/Icon/user-input-graphical.icon new file mode 100644 index 0000000000..12f164c926 --- /dev/null +++ b/Task/User-input-Graphical/Icon/user-input-graphical.icon @@ -0,0 +1,15 @@ +procedure main() +WOpen("size=800,800") | stop("Unable to open window") +WWrite("Enter a string:") +s := WRead() +WWrite("You entered ",image(s)) +WWrite("Enter the integer 75000:") +i := WRead() +if i := integer(i) then + WWrite("You entered: ",i) +else + WWrite(image(i)," isn't an integer") +WDone() +end + +link graphics diff --git a/Task/User-input-Graphical/J/user-input-graphical.j b/Task/User-input-Graphical/J/user-input-graphical.j new file mode 100644 index 0000000000..9b986bffca --- /dev/null +++ b/Task/User-input-Graphical/J/user-input-graphical.j @@ -0,0 +1,32 @@ +SIMPLEGUI=: noun define +pc simpleGui; +xywh 136 39 44 12;cc accept button;cn "Accept"; +xywh 0 14 60 11;cc IntegerLabel static ss_right;cn "Enter an integer"; +xywh 65 13 60 12;cc integer edit; +xywh 0 39 60 11;cc TextLabel static ss_right;cn "Enter text"; +xywh 64 38 60 12;cc text edit; +pas 6 6;pcenter; +rem form end; +) + +simpleGui_run=: verb define + wd SIMPLEGUI + wd 'set integer *', ": 75000 + wd 'pshow;' +) + +simpleGui_accept_button=: verb define + ttxt=. text + tint=. _". integer NB. invalid integers assigned value _ + if. tint ~: 75000 do. + wdinfo 'Integer entered was not 75000.' + else. + simpleGui_close '' + 'simpleGui_text simpleGui_integer'=: ttxt;tint + end. +) + +simpleGui_close=: wd bind 'pclose' +simpleGui_cancel=: simpleGui_close + +simpleGui_run'' diff --git a/Task/User-input-Graphical/Java/user-input-graphical.java b/Task/User-input-Graphical/Java/user-input-graphical.java new file mode 100644 index 0000000000..d09e16e77f --- /dev/null +++ b/Task/User-input-Graphical/Java/user-input-graphical.java @@ -0,0 +1,9 @@ +import javax.swing.*; + +public class GetInputSwing { + public static void main(String[] args) throws Exception { + int number = Integer.parseInt( + JOptionPane.showInputDialog ("Enter an Integer")); + String string = JOptionPane.showInputDialog ("Enter a String"); + } +} diff --git a/Task/User-input-Graphical/JavaScript/user-input-graphical.js b/Task/User-input-Graphical/JavaScript/user-input-graphical.js new file mode 100644 index 0000000000..e96db9fd45 --- /dev/null +++ b/Task/User-input-Graphical/JavaScript/user-input-graphical.js @@ -0,0 +1,5 @@ +var str = prompt("Enter a string"); +var value = 0; +while (value != 75000) { + value = parseInt( prompt("Enter the number 75000") ); +} diff --git a/Task/User-input-Graphical/Liberty-BASIC/user-input-graphical.liberty b/Task/User-input-Graphical/Liberty-BASIC/user-input-graphical.liberty new file mode 100644 index 0000000000..c16858640b --- /dev/null +++ b/Task/User-input-Graphical/Liberty-BASIC/user-input-graphical.liberty @@ -0,0 +1,48 @@ +' [RC] User input/graphical + + ' Typical LB graphical input/output example.This shows how LB takes user input. + ' You'd usually do more validating of input. + + + nomainwin ' No console window needed. + + textbox#w.tb1, 100, 20, 200, 30 + textbox#w.tb2, 100, 60, 200, 30 + textbox#w.tb3, 100,160, 200, 30 + + statictext #w.st1, "String =", 10, 30, 90, 30 + statictext #w.st2, "Integer =", 10, 70, 90, 30 + + button #w.b1, "Read and Show", [buttonClicked], LR, 180, 70 + + WindowWidth =360 + WindowHeight =240 + UpperLeftX = 40 + UpperLeftY = 40 + + open "User input of integer & string" for window as #w + + #w "trapclose [quit]" ' Clean exit routine. + #w.tb1 "!font courier 12" + #w.tb2 "!font courier 12" + #w.tb3 "!font courier 12 bold" + #w.st1 "!font courier 12" + #w.st2 "!font courier 12" + + #w.tb1 "Change this string." + #w.tb2 "Enter an integer here." + #w.tb3 "Display will be here." + + #w.tb1 "!selectall" + + wait + + [buttonClicked] ' Button-clicked routine collects data + #w.tb1 "!contents? in1$" + #w.tb2 "!contents? in2$" + #w.tb3 in1$; " "; int( val( in2$)) + wait + + [quit] + close #w + end diff --git a/Task/User-input-Graphical/Mathematica/user-input-graphical.math b/Task/User-input-Graphical/Mathematica/user-input-graphical.math new file mode 100644 index 0000000000..f9056719bf --- /dev/null +++ b/Task/User-input-Graphical/Mathematica/user-input-graphical.math @@ -0,0 +1,2 @@ +str = InputString["Input a string"]; nb = + InputString["Input a number"]; Print[str, " " , ToString@nb] diff --git a/Task/User-input-Graphical/NetRexx/user-input-graphical.netrexx b/Task/User-input-Graphical/NetRexx/user-input-graphical.netrexx new file mode 100644 index 0000000000..9416ce1492 --- /dev/null +++ b/Task/User-input-Graphical/NetRexx/user-input-graphical.netrexx @@ -0,0 +1,18 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary +import javax.swing.JOptionPane + +unumber = 0 +ustring = '' + +do + unumber = Integer.parseInt(JOptionPane.showInputDialog("Enter an Integer")) + ustring = JOptionPane.showInputDialog("Enter a String") +catch ex = Exception + ex.printStackTrace +end + +unumber = unumber * 1.0 -- just to prove unumber is really a number +say 'Number:' unumber.right(10)', String:' ustring + +return diff --git a/Task/User-input-Graphical/NewLISP/user-input-graphical.newlisp b/Task/User-input-Graphical/NewLISP/user-input-graphical.newlisp new file mode 100644 index 0000000000..4470d80b5b --- /dev/null +++ b/Task/User-input-Graphical/NewLISP/user-input-graphical.newlisp @@ -0,0 +1,45 @@ +; file: input-gui.lsp +; url: http://rosettacode.org/wiki/User_input/Graphical +; author: oofoe 2012-02-02 + +; Colours +(setq ok '(.8 1 .8) fail '(1 .5 .5)) + +; Load library and initialize GUI server: +(load (append (env "NEWLISPDIR") "/guiserver.lsp")) +(gs:init) + +; Validation Callback + +; There is a bug in the "gs:get-text" function that causes it to fail +; silently if the text field is empty. Therfore, I set the field +; background to red first and only clear it if the field returns +; correctly. +(define (validate) + (gs:set-color 'string fail) + (if (not (empty? (gs:get-text 'string))) + (gs:set-color 'string ok)) + + (gs:set-color 'number fail) + (if (= 75000 (int (gs:get-text 'number))) + (gs:set-color 'number ok)) + ) + +; Create main window frame and set layout. +(gs:frame 'main 100 100 256 128 "User Input/Graphical") +(gs:set-flow-layout 'main "left" 4 4) + +; Create and add widgets. +(gs:label 'instructions "Please enter a string and the number 75000:") +(gs:text-field 'string 'validate 32) +(gs:text-field 'number 'validate 8) +(gs:button 'check 'validate "validate...") +(gs:add-to 'main 'instructions 'string 'number 'check) + +; Show main window. +(gs:set-visible 'main true) + +; Start event loop. +(gs:listen) + +; No (exit) needed -- guiserver kills program on window close. diff --git a/Task/User-input-Graphical/Oz/user-input-graphical.oz b/Task/User-input-Graphical/Oz/user-input-graphical.oz new file mode 100644 index 0000000000..7389e9baae --- /dev/null +++ b/Task/User-input-Graphical/Oz/user-input-graphical.oz @@ -0,0 +1,37 @@ +functor +import + Application + QTk at 'x-oz://system/wp/QTk.ozf' + System +define + Number NumberWidget + Text + StatusLabel + WindowClosed + GUI = td(action:OnClose + return:WindowClosed + lr(label(text:"Enter some text:" width:20) + entry(return:Text glue:ew) + glue:ew) + lr(label(text:"Enter a number:" width:20) + numberentry(max:100000 return:Number handle:NumberWidget) + label(handle:StatusLabel width:20) + glue:ew + ) + button(text:"Ok" glue:ew + action:OnClose + ) + ) + proc {OnClose} + if {NumberWidget get($)} \= 75000 then + {StatusLabel set(text:"Invalid value")} + else + {Window close} + end + end + Window = {QTk.build GUI} + {Window show} + {Wait WindowClosed} + {System.showInfo "You entered; "#Text#", "#Number} + {Application.exit 0} +end diff --git a/Task/User-input-Graphical/Perl/user-input-graphical-1.pl b/Task/User-input-Graphical/Perl/user-input-graphical-1.pl new file mode 100644 index 0000000000..9d4100ae6b --- /dev/null +++ b/Task/User-input-Graphical/Perl/user-input-graphical-1.pl @@ -0,0 +1,41 @@ +use Wx; + +# --------------------------------------------------------------- + +package MyApp; +use base 'Wx::App'; +use Wx qw(wxHORIZONTAL wxVERTICAL wxALL wxALIGN_CENTER); +use Wx::Event 'EVT_BUTTON'; + +our ($frame, $text_input, $integer_input); + +sub OnInit + {$frame = new Wx::Frame + (undef, -1, 'Input window', [-1, -1], [250, 150]); + + my $panel = new Wx::Panel($frame, -1); + $text_input = new Wx::TextCtrl($panel, -1, ''); + $integer_input = new Wx::SpinCtrl + ($panel, -1, '', [-1, -1], [-1, -1], + 0, 0, 100_000); + + my $okay_button = new Wx::Button($panel, -1, 'OK'); + EVT_BUTTON($frame, $okay_button, \&OnQuit); + + my $sizer = new Wx::BoxSizer(wxVERTICAL); + $sizer->Add($_, 0, wxALL | wxALIGN_CENTER, 5) + foreach $text_input, $integer_input, $okay_button; + $panel->SetSizer($sizer); + + $frame->Show(1);} + +sub OnQuit + {print 'String: ', $text_input->GetValue, "\n"; + print 'Integer: ', $integer_input->GetValue, "\n"; + $frame->Close;} + +# --------------------------------------------------------------- + +package main; + +MyApp->new->MainLoop; diff --git a/Task/User-input-Graphical/Perl/user-input-graphical-2.pl b/Task/User-input-Graphical/Perl/user-input-graphical-2.pl new file mode 100644 index 0000000000..97052e3029 --- /dev/null +++ b/Task/User-input-Graphical/Perl/user-input-graphical-2.pl @@ -0,0 +1,16 @@ +use XUL::Gui; + +display Window + title => 'Input Window', + width => 250, + height => 150, + TextBox( id => 'txt' ), + TextBox( id => 'num', type => 'number' ), + Button( + label => 'OK', + oncommand => sub { + print "String: " . ID(txt)->value . "\n" + . "Number: " . ID(num)->value . "\n"; + quit; + }, + ); diff --git a/Task/User-input-Graphical/PicoLisp/user-input-graphical.l b/Task/User-input-Graphical/PicoLisp/user-input-graphical.l new file mode 100644 index 0000000000..2495ab1fe0 --- /dev/null +++ b/Task/User-input-Graphical/PicoLisp/user-input-graphical.l @@ -0,0 +1,10 @@ +(and + (call 'sh "-c" + (pack + "dialog \ + --inputbox 'Input a string' 8 60 \ + --inputbox 'Input a number' 8 20 \ + 2>" + (tmp "dlg") ) ) + (split (in (tmp "dlg") (line)) "^I") + (cons (pack (car @)) (format (cadr @))) ) diff --git a/Task/User-input-Graphical/PowerBASIC/user-input-graphical.powerbasic b/Task/User-input-Graphical/PowerBASIC/user-input-graphical.powerbasic new file mode 100644 index 0000000000..699d144f94 --- /dev/null +++ b/Task/User-input-Graphical/PowerBASIC/user-input-graphical.powerbasic @@ -0,0 +1,14 @@ +FUNCTION PBMAIN () AS LONG + result$ = INPUTBOX$("Enter a string.") + MSGBOX result$ + DO + 'This assumes that 75000 is the ONLY valid input. + result$ = INPUTBOX$("Enter the number 75000.") + IF VAL(result$) <> 75000 THEN + MSGBOX "You need to enter 75000!" + ELSE + MSGBOX "You entered the right number." + EXIT DO + END IF + LOOP +END FUNCTION diff --git a/Task/User-input-Graphical/PowerShell/user-input-graphical.psh b/Task/User-input-Graphical/PowerShell/user-input-graphical.psh new file mode 100644 index 0000000000..d575c87c1a --- /dev/null +++ b/Task/User-input-Graphical/PowerShell/user-input-graphical.psh @@ -0,0 +1,98 @@ +#region Define the Windows Form +[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") + +$Form1 = New-Object System.Windows.Forms.Form +$label1 = New-Object System.Windows.Forms.Label +$label2 = New-Object System.Windows.Forms.Label +$txtInputText = New-Object System.Windows.Forms.TextBox +$txtInputNumber = New-Object System.Windows.Forms.TextBox +$btnAccept = New-Object System.Windows.Forms.Button +$label3 = New-Object System.Windows.Forms.Label +$btnCancel = New-Object System.Windows.Forms.Button +$SuspendLayout +# +# label1 +# +$label1.AutoSize = $true +$label1.Location = New-Object System.Drawing.Point(23, 36) +$label1.Name = "label1" +$label1.Size = New-Object System.Drawing.Size(34, 13) +$label1.TabIndex = 0 +$label1.Text = "String" +# +# label2 +# +$label2.AutoSize = $true +$label2.Location = New-Object System.Drawing.Point(13, 62) +$label2.Name = "label2" +$label2.Size = New-Object System.Drawing.Size(44, 13) +$label2.TabIndex = 1 +$label2.Text = "Number" +# +# txtInputText +# +$txtInputText.Location = New-Object System.Drawing.Point(63, 33) +$txtInputText.Name = "txtInputText" +$txtInputText.Size = New-Object System.Drawing.Size(100, 20) +$txtInputText.TabIndex = 0 +# +# txtInputNumber +# +$txtInputNumber.Location = New-Object System.Drawing.Point(63, 59) +$txtInputNumber.Name = "txtInputNumber" +$txtInputNumber.Size = New-Object System.Drawing.Size(100, 20) +$txtInputNumber.TabIndex = 1 +$txtInputNumber.Text = "75000" +# +# btnAccept +# +$btnAccept.DialogResult = [System.Windows.Forms.DialogResult]::OK +$btnAccept.Location = New-Object System.Drawing.Point(16, 94) +$btnAccept.Name = "btnAccept" +$btnAccept.Size = New-Object System.Drawing.Size(75, 23) +$btnAccept.TabIndex = 2 +$btnAccept.Text = "Accept" +$btnAccept.UseVisualStyleBackColor = $true +$btnAccept.add_Click({$rc="Accept"; $Form1.Close()}) +# +# label3 +# +$label3.AutoSize = $true +$label3.Location = New-Object System.Drawing.Point(13, 9) +$label3.Name = "label3" +$label3.Size = New-Object System.Drawing.Size(173, 13) +$label3.TabIndex = 5 +$label3.Text = "Please input a string and a number:" +# +# btnCancel +# +$btnCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel +$btnCancel.Location = New-Object System.Drawing.Point(97, 94) +$btnCancel.Name = "btnCancel" +$btnCancel.Size = New-Object System.Drawing.Size(75, 23) +$btnCancel.TabIndex = 3 +$btnCancel.Text = "Cancel" +$btnCancel.UseVisualStyleBackColor = $true +# +# Form1 +# +$Form1.AcceptButton = $btnAccept +$Form1.CancelButton = $btnCancel +$Form1.ClientSize = New-Object System.Drawing.Size(196, 129) +$Form1.ControlBox = $false +$Form1.Controls.Add($btnCancel) +$Form1.Controls.Add($label3) +$Form1.Controls.Add($btnAccept) +$Form1.Controls.Add($txtInputNumber) +$Form1.Controls.Add($txtInputText) +$Form1.Controls.Add($label2) +$Form1.Controls.Add($label1) +$Form1.Name = "Form1" +$Form1.Text = "RosettaCode" + +#endregion Define the Windows Form + +### Show the input form +$f = $Form1.ShowDialog() +if ( $f -eq [System.Windows.Forms.DialogResult]::Cancel ) { "User selected Cancel" } +else { "User entered `"{0}`" for the text and {1} for the number" -f $txtInputText.Text, $txtInputNumber.Text } diff --git a/Task/User-input-Graphical/PureBasic/user-input-graphical.purebasic b/Task/User-input-Graphical/PureBasic/user-input-graphical.purebasic new file mode 100644 index 0000000000..381433c2e9 --- /dev/null +++ b/Task/User-input-Graphical/PureBasic/user-input-graphical.purebasic @@ -0,0 +1,2 @@ +string$=InputRequester("Some Title","Enter a string","") +variable=Val(InputRequester("Some other Title","Enter a Number","75000")) diff --git a/Task/User-input-Graphical/Python/user-input-graphical.py b/Task/User-input-Graphical/Python/user-input-graphical.py new file mode 100644 index 0000000000..2d173e4e97 --- /dev/null +++ b/Task/User-input-Graphical/Python/user-input-graphical.py @@ -0,0 +1,7 @@ +import Tkinter,tkSimpleDialog + +root = Tkinter.Tk() +root.withdraw() + +number = tkSimpleDialog.askinteger("Integer", "Enter a Number") +string = tkSimpleDialog.askstring("String", "Enter a String") diff --git a/Task/User-input-Graphical/R/user-input-graphical.r b/Task/User-input-Graphical/R/user-input-graphical.r new file mode 100644 index 0000000000..558f6e405d --- /dev/null +++ b/Task/User-input-Graphical/R/user-input-graphical.r @@ -0,0 +1,20 @@ +library(gWidgets) +options(guiToolkit="RGtk2") ## using gWidgtsRGtk2 + +w <- gwindow("Enter a string and a number") +lyt <- glayout(cont=w) +lyt[1,1] <- "Enter a string" +lyt[1,2] <- gedit("", cont=lyt) +lyt[2,1] <- "Enter 75000" +lyt[2,2] <- gedit("", cont=lyt) +lyt[3,2] <- gbutton("validate", cont=lyt, handler=function(h,...) { + txt <- svalue(lyt[1,2]) + x <- svalue(lyt[2,2]) + x <- gsub(",", "", x) + x <- as.integer(x) + + if(nchar(txt) > 0 && x == 75000) + gmessage("Congratulations, you followed directions", parent=w) + else + gmessage("You failed this simple task", parent=w) +}) diff --git a/Task/User-input-Graphical/REBOL/user-input-graphical.rebol b/Task/User-input-Graphical/REBOL/user-input-graphical.rebol new file mode 100644 index 0000000000..a313d37c2a --- /dev/null +++ b/Task/User-input-Graphical/REBOL/user-input-graphical.rebol @@ -0,0 +1,60 @@ +REBOL [ + Title: "Graphical User Input" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/User_Input_-_graphical +] + +; Simple GUI's can be defined with 'layout', a special purpose dialect +; for specifying interfaces. In this case, I describe a gradient +; background with an instruction label, followed by the input fields +; and a validation button. It's possible to check dynamically as the +; user types but I wanted to keep this example as clear as possible. + +view layout [ + +; You can define new widget styles. Here I create a padded label style +; (so that everything will line up) and a simple indicator light to +; show if there's a problem with an input field. + + style label vtext 60 "unlabeled" + style indicator box maroon 24x24 + + backdrop effect [gradient 0x1 black coal] + + vtext "Please enter a string, and the number 75000:" + +; By default, GUI widgets are arranged top down. The 'across' word +; starts stacking widgets from left to right. 'return' starts a new +; line -- just like on a typewriter! + + across + +; Notice I'm using my new label and indicator styles here. Widgets +; that I need to access later (the input field and the indicator) are +; assigned to variables. + + label "string:" s: field 240 si: indicator return + + label "number:" n: field 50 ni: indicator return + + pad 66 + button "validate" [ + +; The user may have entered bogus values, so I reset the indicators: + + si/color: ni/color: maroon + +; Now I check to see if the values are correct. For the string, I just +; care that there is one. For the integer, I make sure that it +; evaluates to an integer and that it's value is 75000. Because I've +; already set the indicator colour, I don't care the integer +; conversion raises an error or not, so I ignore it if anything goes +; wrong. + + if 0 < length? get-face s [si/color: green] + error? try [if 75000 = to-integer get-face n [ni/color: green]] + + show [si ni] ; Repainting multiple objects at once. + ] +] diff --git a/Task/User-input-Graphical/Rascal/user-input-graphical.rascal b/Task/User-input-Graphical/Rascal/user-input-graphical.rascal new file mode 100644 index 0000000000..653f69cab0 --- /dev/null +++ b/Task/User-input-Graphical/Rascal/user-input-graphical.rascal @@ -0,0 +1,14 @@ +import vis::Render; +import vis::Figure; + +public void UserInput2(){ + integer = ""; + string = ""; + row1 = [text("Enter a string "), + textfield("",void(str s){string = s;}), + text(str(){return " This input box will give a string by definition.\n You entered ";})]; + row2 = [text("Enter 75000"), + textfield("",void(str v){integer = v;}), + text(str(){return " ";})]; + render(grid([row1, row2])); +} diff --git a/Task/User-input-Graphical/Ruby/user-input-graphical-1.rb b/Task/User-input-Graphical/Ruby/user-input-graphical-1.rb new file mode 100644 index 0000000000..176496c9b3 --- /dev/null +++ b/Task/User-input-Graphical/Ruby/user-input-graphical-1.rb @@ -0,0 +1,39 @@ +require 'tk' + +def main + root = TkRoot.new + l1 = TkLabel.new(root, "text" => "input a string") + e1 = TkEntry.new(root) + l2 = TkLabel.new(root, "text" => "input the number 75000") + e2 = TkEntry.new(root) do + validate "focusout" + validatecommand lambda {e2.value.to_i == 75_000} + invalidcommand lambda {focus_number_entry(e2)} + end + ok = TkButton.new(root) do + text "OK" + command lambda {validate_input(e1, e2)} + end + Tk.grid(l1, e1) + Tk.grid(l2, e2) + Tk.grid("x",ok, "sticky" => "w") + Tk.mainloop +end + +def validate_input(text_entry, number_entry) + if number_entry.value.to_i != 75_000 + focus_number_entry(number_entry) + else + puts %Q{You entered: "#{text_entry.value}" and "#{number_entry.value}"} + root.destroy + end +end + +def focus_number_entry(widget) + widget \ + .configure("background" => "red", "foreground" => "white") \ + .selection_range(0, "end") \ + .focus +end + +main diff --git a/Task/User-input-Graphical/Ruby/user-input-graphical-2.rb b/Task/User-input-Graphical/Ruby/user-input-graphical-2.rb new file mode 100644 index 0000000000..a0225ff534 --- /dev/null +++ b/Task/User-input-Graphical/Ruby/user-input-graphical-2.rb @@ -0,0 +1,7 @@ +Shoes.app do + string = ask('Enter a string:') + begin + number = ask('Enter the number 75000:') + end while number.to_i != 75000 + para %Q{you entered the string "#{string}" and the number #{number}} +end diff --git a/Task/User-input-Graphical/TI-89-BASIC/user-input-graphical.ti-89 b/Task/User-input-Graphical/TI-89-BASIC/user-input-graphical.ti-89 new file mode 100644 index 0000000000..a13badbaff --- /dev/null +++ b/Task/User-input-Graphical/TI-89-BASIC/user-input-graphical.ti-89 @@ -0,0 +1,8 @@ +Prgm + Dialog + Title "Rosetta Code" + Request "A string", s + DropDown "An integer", {"75000"}, n + EndDlog + 74999 + n → n +EndPrgm diff --git a/Task/User-input-Graphical/Tcl/user-input-graphical-1.tcl b/Task/User-input-Graphical/Tcl/user-input-graphical-1.tcl new file mode 100644 index 0000000000..dee3cb580a --- /dev/null +++ b/Task/User-input-Graphical/Tcl/user-input-graphical-1.tcl @@ -0,0 +1,5 @@ +# create entry widget: +pack [entry .e1] + +# read its content: +set input [.e get] diff --git a/Task/User-input-Graphical/Tcl/user-input-graphical-2.tcl b/Task/User-input-Graphical/Tcl/user-input-graphical-2.tcl new file mode 100644 index 0000000000..7e86535054 --- /dev/null +++ b/Task/User-input-Graphical/Tcl/user-input-graphical-2.tcl @@ -0,0 +1,4 @@ +pack [entry .e1 -textvar input] + +# show the content at any time by +puts $input diff --git a/Task/User-input-Graphical/VBScript/user-input-graphical.vbscript b/Task/User-input-Graphical/VBScript/user-input-graphical.vbscript new file mode 100644 index 0000000000..a5d74cb086 --- /dev/null +++ b/Task/User-input-Graphical/VBScript/user-input-graphical.vbscript @@ -0,0 +1,2 @@ +strUserIn = InputBox("Enter Data") +Wscript.Echo strUserIn diff --git a/Task/User-input-Graphical/Vedit-macro-language/user-input-graphical.vedit b/Task/User-input-Graphical/Vedit-macro-language/user-input-graphical.vedit new file mode 100644 index 0000000000..1dde9ff86c --- /dev/null +++ b/Task/User-input-Graphical/Vedit-macro-language/user-input-graphical.vedit @@ -0,0 +1,3 @@ +Dialog_Input_1(1, "`User Input example`, + `??Enter a string `, + `??Enter a number `") diff --git a/Task/User-input-Text/0DESCRIPTION b/Task/User-input-Text/0DESCRIPTION new file mode 100644 index 0000000000..7c9ab2626f --- /dev/null +++ b/Task/User-input-Text/0DESCRIPTION @@ -0,0 +1,3 @@ +{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]][[Category:Keyboard Input]] In this task, the goal is to input a string and the integer 75000, from the text console. + +See also: [[User input/Graphical]] diff --git a/Task/User-input-Text/1META.yaml b/Task/User-input-Text/1META.yaml new file mode 100644 index 0000000000..88eb5468ca --- /dev/null +++ b/Task/User-input-Text/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Text processing diff --git a/Task/User-input-Text/ALGOL-68/user-input-text.alg b/Task/User-input-Text/ALGOL-68/user-input-text.alg new file mode 100644 index 0000000000..efe8ecd1c0 --- /dev/null +++ b/Task/User-input-Text/ALGOL-68/user-input-text.alg @@ -0,0 +1,5 @@ +print("Enter a string: "); +STRING s := read string; +print("Enter a number: "); +INT i := read int; +~ diff --git a/Task/User-input-Text/AWK/user-input-text.awk b/Task/User-input-Text/AWK/user-input-text.awk new file mode 100644 index 0000000000..500316c66e --- /dev/null +++ b/Task/User-input-Text/AWK/user-input-text.awk @@ -0,0 +1,5 @@ +~/src/opt/run $ awk 'BEGIN{printf "enter a string: "}{s=$0;i=$0+0;print "ok,"s"/"i}' +enter a string: hello world +ok,hello world/0 +75000 +ok,75000/75000 diff --git a/Task/User-input-Text/Ada/user-input-text-1.ada b/Task/User-input-Text/Ada/user-input-text-1.ada new file mode 100644 index 0000000000..fa98fc4e5f --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-1.ada @@ -0,0 +1,14 @@ +function Get_String return String is + Line : String (1 .. 1_000); + Last : Natural; +begin + Get_Line (Line, Last); + return Line (1 .. Last); +end Get_String; + +function Get_Integer return Integer is + S : constant String := Get_String; +begin + return Integer'Value (S); + -- may raise exception Constraint_Error if value entered is not a well-formed integer +end Get_Integer; diff --git a/Task/User-input-Text/Ada/user-input-text-2.ada b/Task/User-input-Text/Ada/user-input-text-2.ada new file mode 100644 index 0000000000..18a90e3a3e --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-2.ada @@ -0,0 +1,2 @@ +My_String : String := Get_String; +My_Integer : Integer := Get_Integer; diff --git a/Task/User-input-Text/AutoHotkey/user-input-text-1.ahk b/Task/User-input-Text/AutoHotkey/user-input-text-1.ahk new file mode 100644 index 0000000000..e017ece560 --- /dev/null +++ b/Task/User-input-Text/AutoHotkey/user-input-text-1.ahk @@ -0,0 +1,7 @@ +DllCall("AllocConsole") +FileAppend, please type something`n, CONOUT$ +FileReadLine, line, CONIN$, 1 +msgbox % line +FileAppend, please type '75000'`n, CONOUT$ +FileReadLine, line, CONIN$, 1 +msgbox % line diff --git a/Task/User-input-Text/AutoHotkey/user-input-text-2.ahk b/Task/User-input-Text/AutoHotkey/user-input-text-2.ahk new file mode 100644 index 0000000000..c6de426b84 --- /dev/null +++ b/Task/User-input-Text/AutoHotkey/user-input-text-2.ahk @@ -0,0 +1,23 @@ +TrayTip, Input:, Type a string: +Input(String) +TrayTip, Input:, Type an int: +Input(Int) +TrayTip, Done!, Input was recieved. +Msgbox, You entered "%String%" and "%Int%" +ExitApp +Return + +Input(ByRef Output) +{ + Loop + { + Input, Char, L1, {Enter}{Space} + If ErrorLevel contains Enter + Break + Else If ErrorLevel contains Space + Output .= " " + Else + Output .= Char + TrayTip, Input:, %Output% + } +} diff --git a/Task/User-input-Text/BASIC/user-input-text.basic b/Task/User-input-Text/BASIC/user-input-text.basic new file mode 100644 index 0000000000..672c8c2c7b --- /dev/null +++ b/Task/User-input-Text/BASIC/user-input-text.basic @@ -0,0 +1,2 @@ +INPUT "Enter a string"; s$ +INPUT "Enter a number: ", i% diff --git a/Task/User-input-Text/BBC-BASIC/user-input-text.bbc b/Task/User-input-Text/BBC-BASIC/user-input-text.bbc new file mode 100644 index 0000000000..050b3c7301 --- /dev/null +++ b/Task/User-input-Text/BBC-BASIC/user-input-text.bbc @@ -0,0 +1,5 @@ + INPUT LINE "Enter a string: " string$ + INPUT "Enter a number: " number + + PRINT "String = """ string$ """" + PRINT "Number = " ; number diff --git a/Task/User-input-Text/Batch-File/user-input-text.bat b/Task/User-input-Text/Batch-File/user-input-text.bat new file mode 100644 index 0000000000..1ba3ec4bcf --- /dev/null +++ b/Task/User-input-Text/Batch-File/user-input-text.bat @@ -0,0 +1,3 @@ +@echo off +set /p var= +echo %var% diff --git a/Task/User-input-Text/Befunge/user-input-text-1.bf b/Task/User-input-Text/Befunge/user-input-text-1.bf new file mode 100644 index 0000000000..c292bffdd2 --- /dev/null +++ b/Task/User-input-Text/Befunge/user-input-text-1.bf @@ -0,0 +1,3 @@ +<>:v:"Enter a string: " + ^,_ >~:1+v + ^ _@ diff --git a/Task/User-input-Text/Befunge/user-input-text-2.bf b/Task/User-input-Text/Befunge/user-input-text-2.bf new file mode 100644 index 0000000000..e5d38a455b --- /dev/null +++ b/Task/User-input-Text/Befunge/user-input-text-2.bf @@ -0,0 +1,2 @@ +<>:v:"Enter a number: " + ^,_ & @ diff --git a/Task/User-input-Text/C++/user-input-text-1.cpp b/Task/User-input-Text/C++/user-input-text-1.cpp new file mode 100644 index 0000000000..c8bcdafb0a --- /dev/null +++ b/Task/User-input-Text/C++/user-input-text-1.cpp @@ -0,0 +1,16 @@ +#include +#include +using namespace std; + +int main() +{ + // while probably all current implementations have int wide enough for 75000, the C++ standard + // only guarantees this for long int. + long int integer_input; + string string_input; + cout << "Enter an integer: "; + cin >> integer_input; + cout << "Enter a string: "; + cin >> string_input; + return 0; +} diff --git a/Task/User-input-Text/C++/user-input-text-2.cpp b/Task/User-input-Text/C++/user-input-text-2.cpp new file mode 100644 index 0000000000..2d3e05e509 --- /dev/null +++ b/Task/User-input-Text/C++/user-input-text-2.cpp @@ -0,0 +1 @@ + cin >> string_input; diff --git a/Task/User-input-Text/C++/user-input-text-3.cpp b/Task/User-input-Text/C++/user-input-text-3.cpp new file mode 100644 index 0000000000..6ea04b3221 --- /dev/null +++ b/Task/User-input-Text/C++/user-input-text-3.cpp @@ -0,0 +1 @@ + getline(cin, string_input); diff --git a/Task/User-input-Text/C/user-input-text.c b/Task/User-input-Text/C/user-input-text.c new file mode 100644 index 0000000000..770281896e --- /dev/null +++ b/Task/User-input-Text/C/user-input-text.c @@ -0,0 +1,11 @@ +#include +int main(int argc, char* argv[]) +{ + int input; + if((scanf("%d", &input))==1) + { + printf("Read in %d\n", input); + return 1; + } + return 0; +} diff --git a/Task/User-input-Text/Clojure/user-input-text.clj b/Task/User-input-Text/Clojure/user-input-text.clj new file mode 100644 index 0000000000..42d044b4d8 --- /dev/null +++ b/Task/User-input-Text/Clojure/user-input-text.clj @@ -0,0 +1,4 @@ +(import '(java.util Scanner)) +(def scan (Scanner. *in*)) +(def s (.nextLine scan)) +(def n (.nextInt scan)) diff --git a/Task/User-input-Text/Common-Lisp/user-input-text.lisp b/Task/User-input-Text/Common-Lisp/user-input-text.lisp new file mode 100644 index 0000000000..446ce1cb6a --- /dev/null +++ b/Task/User-input-Text/Common-Lisp/user-input-text.lisp @@ -0,0 +1,9 @@ +(format t "Enter some text: ") +(let ((s (read-line))) + (format t "You entered ~s~%" s)) + +(format t "Enter a number: ") +(let ((n (read))) + (if (numberp n) + (format t "You entered ~d.~%" n) + (format t "That was not a number."))) diff --git a/Task/User-input-Text/D/user-input-text.d b/Task/User-input-Text/D/user-input-text.d new file mode 100644 index 0000000000..ed4b5baf4c --- /dev/null +++ b/Task/User-input-Text/D/user-input-text.d @@ -0,0 +1,13 @@ +import std.stdio; + +void main() { + long number; + write("Enter an integer: "); + readf("%d", &number); + + char[] str; + write("Enter a string: "); + readf(" %s\n", &str); + + writeln("Read in '", number, "' and '", str, "'"); +} diff --git a/Task/User-input-Text/Delphi/user-input-text.delphi b/Task/User-input-Text/Delphi/user-input-text.delphi new file mode 100644 index 0000000000..28758c5f84 --- /dev/null +++ b/Task/User-input-Text/Delphi/user-input-text.delphi @@ -0,0 +1,22 @@ +program UserInputText; + +{$APPTYPE CONSOLE} + +uses SysUtils; + +var + s: string; + lStringValue: string; + lIntegerValue: Integer; +begin + WriteLn('Enter a string:'); + Readln(lStringValue); + + repeat + WriteLn('Enter the number 75000'); + Readln(s); + lIntegerValue := StrToIntDef(s, 0); + if lIntegerValue <> 75000 then + Writeln('Invalid entry: ' + s); + until lIntegerValue = 75000; +end. diff --git a/Task/User-input-Text/Erlang/user-input-text-1.erl b/Task/User-input-Text/Erlang/user-input-text-1.erl new file mode 100644 index 0000000000..73ebad9655 --- /dev/null +++ b/Task/User-input-Text/Erlang/user-input-text-1.erl @@ -0,0 +1,2 @@ +{ok, [String]} = io:fread("Enter a string: ","~s"). +{ok, [Number]} = io:fread("Enter a number: ","~d"). diff --git a/Task/User-input-Text/Erlang/user-input-text-2.erl b/Task/User-input-Text/Erlang/user-input-text-2.erl new file mode 100644 index 0000000000..b91a07bfd8 --- /dev/null +++ b/Task/User-input-Text/Erlang/user-input-text-2.erl @@ -0,0 +1 @@ + String = io:get_line("Enter a string: "). diff --git a/Task/User-input-Text/Euphoria/user-input-text.euphoria b/Task/User-input-Text/Euphoria/user-input-text.euphoria new file mode 100644 index 0000000000..4cd7988cd3 --- /dev/null +++ b/Task/User-input-Text/Euphoria/user-input-text.euphoria @@ -0,0 +1,9 @@ +include get.e + +sequence s +atom n + +s = prompt_string("Enter a string:") +puts(1, s & '\n') +n = prompt_number("Enter a number:",{}) +printf(1, "%d", n) diff --git a/Task/User-input-Text/FALSE/user-input-text.false b/Task/User-input-Text/FALSE/user-input-text.false new file mode 100644 index 0000000000..cff3156284 --- /dev/null +++ b/Task/User-input-Text/FALSE/user-input-text.false @@ -0,0 +1,3 @@ +[[^$' =~][,]#,]w: +[0[^'0-$$9>0@>|~][\10*+]#%]d: +w;! d;!. diff --git a/Task/User-input-Text/Factor/user-input-text.factor b/Task/User-input-Text/Factor/user-input-text.factor new file mode 100644 index 0000000000..af6ae3ba40 --- /dev/null +++ b/Task/User-input-Text/Factor/user-input-text.factor @@ -0,0 +1,4 @@ +"Enter a string: " write +readln +"Enter a number: " write +readln string>number diff --git a/Task/User-input-Text/Falcon/user-input-text.falcon b/Task/User-input-Text/Falcon/user-input-text.falcon new file mode 100644 index 0000000000..5e8981662a --- /dev/null +++ b/Task/User-input-Text/Falcon/user-input-text.falcon @@ -0,0 +1,4 @@ +printl("Enter a string:") +str = input() +printl("Enter a number:") +n = int(input()) diff --git a/Task/User-input-Text/Fantom/user-input-text.fantom b/Task/User-input-Text/Fantom/user-input-text.fantom new file mode 100644 index 0000000000..94479c548d --- /dev/null +++ b/Task/User-input-Text/Fantom/user-input-text.fantom @@ -0,0 +1,18 @@ +class Main +{ + public static Void main () + { + Env.cur.out.print ("Enter a string: ").flush + str := Env.cur.in.readLine + echo ("Entered :$str:") + Env.cur.out.print ("Enter 75000: ").flush + Int n + try n = Env.cur.in.readLine.toInt + catch (Err e) + { + echo ("You had to enter a number") + return + } + echo ("Entered :$n: which is " + ((n == 75000) ? "correct" : "wrong")) + } +} diff --git a/Task/User-input-Text/Forth/user-input-text-1.fth b/Task/User-input-Text/Forth/user-input-text-1.fth new file mode 100644 index 0000000000..f11013ff7c --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-1.fth @@ -0,0 +1,3 @@ +: INPUT$ ( n -- addr n ) + PAD SWAP ACCEPT + PAD SWAP ; diff --git a/Task/User-input-Text/Forth/user-input-text-2.fth b/Task/User-input-Text/Forth/user-input-text-2.fth new file mode 100644 index 0000000000..b3d8fb6597 --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-2.fth @@ -0,0 +1,4 @@ +: INPUT# ( -- u true | false ) + 0. 16 INPUT$ DUP >R + >NUMBER NIP NIP + R> <> DUP 0= IF NIP THEN ; diff --git a/Task/User-input-Text/Forth/user-input-text-3.fth b/Task/User-input-Text/Forth/user-input-text-3.fth new file mode 100644 index 0000000000..016c437a6b --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-3.fth @@ -0,0 +1,2 @@ +: INPUT# ( -- n true | d 1 | false ) + 16 INPUT$ SNUMBER? ; diff --git a/Task/User-input-Text/Forth/user-input-text-4.fth b/Task/User-input-Text/Forth/user-input-text-4.fth new file mode 100644 index 0000000000..01727602ef --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-4.fth @@ -0,0 +1,3 @@ +: INPUT# ( -- n true | false ) + 16 INPUT$ NUMBER? NIP + DUP 0= IF NIP THEN ; diff --git a/Task/User-input-Text/Forth/user-input-text-5.fth b/Task/User-input-Text/Forth/user-input-text-5.fth new file mode 100644 index 0000000000..480a3c7c7a --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-5.fth @@ -0,0 +1,8 @@ +: input# + begin + refill drop bl parse-word ( a n) + number error? ( n f) + while ( n) + drop ( --) + repeat ( n) +; diff --git a/Task/User-input-Text/Forth/user-input-text-6.fth b/Task/User-input-Text/Forth/user-input-text-6.fth new file mode 100644 index 0000000000..384ffe5c50 --- /dev/null +++ b/Task/User-input-Text/Forth/user-input-text-6.fth @@ -0,0 +1,6 @@ +: TEST + ." Enter your name: " 80 INPUT$ CR + ." Hello there, " TYPE CR + ." Enter a number: " INPUT# CR + IF ." Your number is " . + ELSE ." That's not a number!" THEN CR ; diff --git a/Task/User-input-Text/Fortran/user-input-text.f b/Task/User-input-Text/Fortran/user-input-text.f new file mode 100644 index 0000000000..bc10790ead --- /dev/null +++ b/Task/User-input-Text/Fortran/user-input-text.f @@ -0,0 +1,7 @@ +character(20) :: s +integer :: i + +print*, "Enter a string (max 20 characters)" +read*, s +print*, "Enter the integer 75000" +read*, i diff --git a/Task/User-input-Text/Frink/user-input-text.frink b/Task/User-input-Text/Frink/user-input-text.frink new file mode 100644 index 0000000000..e806b8e16d --- /dev/null +++ b/Task/User-input-Text/Frink/user-input-text.frink @@ -0,0 +1,2 @@ +s = input["Enter a string: "] +i = parseInt[input["Enter an integer: "]] diff --git a/Task/User-input-Text/Go/user-input-text-1.go b/Task/User-input-Text/Go/user-input-text-1.go new file mode 100644 index 0000000000..5dd687f4c6 --- /dev/null +++ b/Task/User-input-Text/Go/user-input-text-1.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + var s string + var i int + if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 { + fmt.Println("good") + } else { + fmt.Println("wrong") + } +} diff --git a/Task/User-input-Text/Go/user-input-text-2.go b/Task/User-input-Text/Go/user-input-text-2.go new file mode 100644 index 0000000000..74c650a592 --- /dev/null +++ b/Task/User-input-Text/Go/user-input-text-2.go @@ -0,0 +1,38 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" +) + +func main() { + in := bufio.NewReader(os.Stdin) + + fmt.Print("Enter string: ") + s, err := in.ReadString('\n') + if err != nil { + fmt.Println(err) + return + } + s = strings.TrimSpace(s) + + fmt.Print("Enter 75000: ") + s, err = in.ReadString('\n') + if err != nil { + fmt.Println(err) + return + } + n, err := strconv.Atoi(strings.TrimSpace(s)) + if err != nil { + fmt.Println(err) + return + } + if n != 75000 { + fmt.Println("fail: not 75000") + return + } + fmt.Println("Good") +} diff --git a/Task/User-input-Text/Groovy/user-input-text.groovy b/Task/User-input-Text/Groovy/user-input-text.groovy new file mode 100644 index 0000000000..753cfb11a2 --- /dev/null +++ b/Task/User-input-Text/Groovy/user-input-text.groovy @@ -0,0 +1,2 @@ +word = System.in.readLine() +num = System.in.readLine().toInteger() diff --git a/Task/User-input-Text/Haskell/user-input-text.hs b/Task/User-input-Text/Haskell/user-input-text.hs new file mode 100644 index 0000000000..defc979cb0 --- /dev/null +++ b/Task/User-input-Text/Haskell/user-input-text.hs @@ -0,0 +1,9 @@ +import System.IO (hFlush, stdout) +main = do + putStr "Enter a string: " + hFlush stdout + str <- getLine + putStr "Enter an integer: " + hFlush stdout + num <- readLn :: IO Int + putStrLn $ str ++ (show num) diff --git a/Task/User-input-Text/Icon/user-input-text.icon b/Task/User-input-Text/Icon/user-input-text.icon new file mode 100644 index 0000000000..64abfd0ae3 --- /dev/null +++ b/Task/User-input-Text/Icon/user-input-text.icon @@ -0,0 +1,10 @@ +procedure main () + writes ("Enter something: ") + s := read () + write ("You entered: " || s) + + writes ("Enter 75000: ") + if (i := integer (read ())) then + write (if (i = 75000) then "correct" else "incorrect") + else write ("you must enter a number") +end diff --git a/Task/User-input-Text/Io/user-input-text.io b/Task/User-input-Text/Io/user-input-text.io new file mode 100644 index 0000000000..a986684346 --- /dev/null +++ b/Task/User-input-Text/Io/user-input-text.io @@ -0,0 +1,2 @@ +string := File clone standardInput readLine("Enter a string: ") +integer := File clone standardInput readLine("Enter 75000: ") asNumber diff --git a/Task/User-input-Text/J/user-input-text-1.j b/Task/User-input-Text/J/user-input-text-1.j new file mode 100644 index 0000000000..efbcebc361 --- /dev/null +++ b/Task/User-input-Text/J/user-input-text-1.j @@ -0,0 +1,3 @@ + require 'misc' NB. load system script + prompt 'Enter string: ' + 0".prompt 'Enter an integer: ' diff --git a/Task/User-input-Text/J/user-input-text-2.j b/Task/User-input-Text/J/user-input-text-2.j new file mode 100644 index 0000000000..2c13ac6749 --- /dev/null +++ b/Task/User-input-Text/J/user-input-text-2.j @@ -0,0 +1,14 @@ + prompt 'Enter string: ' NB. output string to session +Enter string: Hello World +Hello World + 0".prompt 'Enter an integer: ' NB. output integer to session +Enter an integer: 75000 +75000 + mystring=: prompt 'Enter string: ' NB. store string as noun +Enter string: Hello Rosetta Code + myinteger=: 0".prompt 'Enter an integer: ' NB. store integer as noun +Enter an integer: 75000 + mystring;myinteger NB. show contents of nouns +┌──────────────────┬─────┐ +│Hello Rosetta Code│75000│ +└──────────────────┴─────┘ diff --git a/Task/User-input-Text/Java/user-input-text-1.java b/Task/User-input-Text/Java/user-input-text-1.java new file mode 100644 index 0000000000..482df3bdb0 --- /dev/null +++ b/Task/User-input-Text/Java/user-input-text-1.java @@ -0,0 +1,10 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class GetInput { + public static void main(String[] args) throws Exception { + BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in)); + int number = Integer.parseInt(sysin.readLine()); + String string = sysin.readLine(); + } +} diff --git a/Task/User-input-Text/Java/user-input-text-2.java b/Task/User-input-Text/Java/user-input-text-2.java new file mode 100644 index 0000000000..2dcebd306b --- /dev/null +++ b/Task/User-input-Text/Java/user-input-text-2.java @@ -0,0 +1,9 @@ +import java.util.Scanner; + +public class GetInput { + public static void main(String[] args) { + Scanner stdin = new Scanner(System.in); + String string = stdin.nextLine(); + int number = stdin.nextInt(); + } +} diff --git a/Task/User-input-Text/JavaScript/user-input-text-1.js b/Task/User-input-Text/JavaScript/user-input-text-1.js new file mode 100644 index 0000000000..f2acfd6fb5 --- /dev/null +++ b/Task/User-input-Text/JavaScript/user-input-text-1.js @@ -0,0 +1,8 @@ +WScript.Echo("Enter a string"); +var str = WScript.StdIn.ReadLine(); + +var val = 0; +while (val != 75000) { + WScript.Echo("Enter the integer 75000"); + val = parseInt( WScript.StdIn.ReadLine() ); +} diff --git a/Task/User-input-Text/JavaScript/user-input-text-2.js b/Task/User-input-Text/JavaScript/user-input-text-2.js new file mode 100644 index 0000000000..2e0ef7b962 --- /dev/null +++ b/Task/User-input-Text/JavaScript/user-input-text-2.js @@ -0,0 +1,8 @@ +print("Enter a string"); +var str = readline(); + +var val = 0; +while (val != 75000) { + print("Enter the integer 75000"); + val = parseInt( readline() ); +} diff --git a/Task/User-input-Text/Joy/user-input-text.joy b/Task/User-input-Text/Joy/user-input-text.joy new file mode 100644 index 0000000000..9c4a636149 --- /dev/null +++ b/Task/User-input-Text/Joy/user-input-text.joy @@ -0,0 +1,4 @@ +"Enter a string: " putchars +stdin fgets +"Enter a number: " putchars +stdin fgets 10 strtol. diff --git a/Task/User-input-Text/Kite/user-input-text.kite b/Task/User-input-Text/Kite/user-input-text.kite new file mode 100644 index 0000000000..2e6f5e54ae --- /dev/null +++ b/Task/User-input-Text/Kite/user-input-text.kite @@ -0,0 +1,2 @@ +System.file.stdout|write("Enter a String "); +string = System.file.stdin|readline(); diff --git a/Task/User-input-Text/Liberty-BASIC/user-input-text.liberty b/Task/User-input-Text/Liberty-BASIC/user-input-text.liberty new file mode 100644 index 0000000000..7e87d62e5b --- /dev/null +++ b/Task/User-input-Text/Liberty-BASIC/user-input-text.liberty @@ -0,0 +1,2 @@ +Input "Enter a string. ";string$ +Input "Enter the value 75000.";num diff --git a/Task/User-input-Text/Logo/user-input-text.logo b/Task/User-input-Text/Logo/user-input-text.logo new file mode 100644 index 0000000000..39015157fa --- /dev/null +++ b/Task/User-input-Text/Logo/user-input-text.logo @@ -0,0 +1,7 @@ +make "input readlist ; in: string 75000 +show map "number? :input ; [false true] + +make "input readword ; in: 75000 +show :input + 123 ; 75123 +make "input readword ; in: string 75000 +show :input ; string 75000 diff --git a/Task/User-input-Text/Lua/user-input-text.lua b/Task/User-input-Text/Lua/user-input-text.lua new file mode 100644 index 0000000000..6e6556e64d --- /dev/null +++ b/Task/User-input-Text/Lua/user-input-text.lua @@ -0,0 +1,4 @@ +print('Enter a string: ') +s = io.stdin:read() +print('Enter a number: ') +i = tonumber(io.stdin:read()) diff --git a/Task/User-input-Text/MATLAB/user-input-text.m b/Task/User-input-Text/MATLAB/user-input-text.m new file mode 100644 index 0000000000..8f538db305 --- /dev/null +++ b/Task/User-input-Text/MATLAB/user-input-text.m @@ -0,0 +1,20 @@ +>> input('Input string: ') +Input string: 'Hello' + +ans = + +Hello + +>> input('Input number: ') +Input number: 75000 + +ans = + + 75000 + +>> input('Input number, the number will be stored as a string: ','s') +Input number, the number will be stored as a string: 75000 + +ans = + +75000 diff --git a/Task/User-input-Text/MUMPS/user-input-text.mumps b/Task/User-input-Text/MUMPS/user-input-text.mumps new file mode 100644 index 0000000000..30f46af8a7 --- /dev/null +++ b/Task/User-input-Text/MUMPS/user-input-text.mumps @@ -0,0 +1,8 @@ +TXTINP + NEW S,N + WRITE "Enter a string: " + READ S,! + WRITE "Enter the number 75000: " + READ N,! + KILL S,N + QUIT diff --git a/Task/User-input-Text/Mathematica/user-input-text.math b/Task/User-input-Text/Mathematica/user-input-text.math new file mode 100644 index 0000000000..24fb8a3e89 --- /dev/null +++ b/Task/User-input-Text/Mathematica/user-input-text.math @@ -0,0 +1,2 @@ +mystring = InputString["give me a string please"]; +myinteger = Input["give me an integer please"]; diff --git a/Task/User-input-Text/Metafont/user-input-text.metafont b/Task/User-input-Text/Metafont/user-input-text.metafont new file mode 100644 index 0000000000..c1f9322c11 --- /dev/null +++ b/Task/User-input-Text/Metafont/user-input-text.metafont @@ -0,0 +1,12 @@ +string s; +message "write a string: "; +s := readstring; +message s; +message "write a number now: "; +b := scantokens readstring; +if b = 750: + message "You've got it!" +else: + message "Sorry..." +fi; +end diff --git a/Task/User-input-Text/Mirah/user-input-text.mirah b/Task/User-input-Text/Mirah/user-input-text.mirah new file mode 100644 index 0000000000..66fd111ed1 --- /dev/null +++ b/Task/User-input-Text/Mirah/user-input-text.mirah @@ -0,0 +1,3 @@ +s = System.console.readLine() + +puts s diff --git a/Task/User-input-Text/Modula-3/user-input-text.mod3 b/Task/User-input-Text/Modula-3/user-input-text.mod3 new file mode 100644 index 0000000000..32cbbe3c15 --- /dev/null +++ b/Task/User-input-Text/Modula-3/user-input-text.mod3 @@ -0,0 +1,14 @@ +MODULE Input EXPORTS Main; + +IMPORT IO, Fmt; + +VAR string: TEXT; + number: INTEGER; + +BEGIN + IO.Put("Enter a string: "); + string := IO.GetLine(); + IO.Put("Enter a number: "); + number := IO.GetInt(); + IO.Put("You entered: " & string & " and " & Fmt.Int(number) & "\n"); +END Input. diff --git a/Task/User-input-Text/Nemerle/user-input-text.nemerle b/Task/User-input-Text/Nemerle/user-input-text.nemerle new file mode 100644 index 0000000000..06456df85a --- /dev/null +++ b/Task/User-input-Text/Nemerle/user-input-text.nemerle @@ -0,0 +1,20 @@ +using System; +using System.Console; + +module Input +{ + Main() : void + { + Write("Enter a string:"); + _ = ReadLine() + + mutable entry = 0; + mutable numeric = false; + + do + { + Write("Enter 75000:"); + numeric = int.TryParse(ReadLine(), out entry); + } while ((!numeric) || (entry != 75000)) + } +} diff --git a/Task/User-input-Text/NetRexx/user-input-text.netrexx b/Task/User-input-Text/NetRexx/user-input-text.netrexx new file mode 100644 index 0000000000..300db74ca8 --- /dev/null +++ b/Task/User-input-Text/NetRexx/user-input-text.netrexx @@ -0,0 +1,17 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +checkVal = 75000 +say 'Input a string then the number' checkVal +parse ask inString +parse ask inNumber . + +say 'Input string:' inString +say 'Input number:' inNumber +if inNumber == checkVal then do + say 'Success! Input number is as requested' + end +else do + say 'Failure! Number' inNumber 'is not' checkVal + end +return diff --git a/Task/User-input-Text/OCaml/user-input-text.ocaml b/Task/User-input-Text/OCaml/user-input-text.ocaml new file mode 100644 index 0000000000..24d2477905 --- /dev/null +++ b/Task/User-input-Text/OCaml/user-input-text.ocaml @@ -0,0 +1,5 @@ +print_string "Enter a string: "; +let str = read_line () in + print_string "Enter an integer: "; + let num = read_int () in + Printf.printf "%s%d\n" str num diff --git a/Task/User-input-Text/Objeck/user-input-text.objeck b/Task/User-input-Text/Objeck/user-input-text.objeck new file mode 100644 index 0000000000..86c93d45cf --- /dev/null +++ b/Task/User-input-Text/Objeck/user-input-text.objeck @@ -0,0 +1,13 @@ +use IO; + +bundle Default { + class Hello { + function : Main(args : String[]) ~ Nil { + string := Console->GetInstance()->ReadString(); + string->PrintLine(); + + number := Console->GetInstance()->ReadString()->ToInt(); + number->PrintLine(); + } + } +} diff --git a/Task/User-input-Text/Octave/user-input-text.octave b/Task/User-input-Text/Octave/user-input-text.octave new file mode 100644 index 0000000000..6bc2fc6e08 --- /dev/null +++ b/Task/User-input-Text/Octave/user-input-text.octave @@ -0,0 +1,15 @@ +% read a string ("s") +s = input("Enter a string: ", "s"); + +% read a GNU Octave expression, which is evaluated; e.g. +% 5/7 gives 0.71429 +i = input("Enter an expression: "); + +% parse the input for an integer +printf("Enter an integer: "); +ri = scanf("%d"); + +% show the values +disp(s); +disp(i); +disp(ri); diff --git a/Task/User-input-Text/Oz/user-input-text.oz b/Task/User-input-Text/Oz/user-input-text.oz new file mode 100644 index 0000000000..c39b9d1e7a --- /dev/null +++ b/Task/User-input-Text/Oz/user-input-text.oz @@ -0,0 +1,14 @@ +declare + StdIn = {New class $ from Open.file Open.text end init(name:stdin)} + StringInput + Num = {NewCell 0} +in + {System.printInfo "Enter a string: "} + StringInput = {StdIn getS($)} + + for until:@Num == 75000 do + {System.printInfo "Enter 75000: "} + Line = {StdIn getS($)} + in + Num := try {String.toInt Line} catch _ then 0 end + end diff --git a/Task/User-input-Text/PARI-GP/user-input-text.pari b/Task/User-input-Text/PARI-GP/user-input-text.pari new file mode 100644 index 0000000000..9fac8cb5ca --- /dev/null +++ b/Task/User-input-Text/PARI-GP/user-input-text.pari @@ -0,0 +1,2 @@ +s=input(); +n=eval(input()); diff --git a/Task/User-input-Text/PHP/user-input-text.php b/Task/User-input-Text/PHP/user-input-text.php new file mode 100644 index 0000000000..bf9d951f9e --- /dev/null +++ b/Task/User-input-Text/PHP/user-input-text.php @@ -0,0 +1,4 @@ +#!/usr/bin/php +; # equivalent to readline(*STDIN) +my $integer = <>; diff --git a/Task/User-input-Text/PicoLisp/user-input-text.l b/Task/User-input-Text/PicoLisp/user-input-text.l new file mode 100644 index 0000000000..da29196600 --- /dev/null +++ b/Task/User-input-Text/PicoLisp/user-input-text.l @@ -0,0 +1,4 @@ +(in NIL # Guarantee reading from standard input + (let (Str (read) Num (read)) + (prinl "The string is: \"" Str "\"") + (prinl "The number is: " Num) ) ) diff --git a/Task/User-input-Text/Pike/user-input-text.pike b/Task/User-input-Text/Pike/user-input-text.pike new file mode 100644 index 0000000000..0407cbd10c --- /dev/null +++ b/Task/User-input-Text/Pike/user-input-text.pike @@ -0,0 +1,6 @@ +int main(){ + write("Enter a String: "); + string str = Stdio.stdin->gets(); + write("Enter 75000: "); + int num = Stdio.stdin->gets(); +} diff --git a/Task/User-input-Text/Pop11/user-input-text.pop11 b/Task/User-input-Text/Pop11/user-input-text.pop11 new file mode 100644 index 0000000000..2c43a2f4cc --- /dev/null +++ b/Task/User-input-Text/Pop11/user-input-text.pop11 @@ -0,0 +1,9 @@ +;;; Setup item reader +lvars itemrep = incharitem(charin); +lvars s, c, j = 0; +;;; read chars up to a newline and put them on the stack +while (charin() ->> c) /= `\n` do j + 1 -> j ; c endwhile; +;;; build the string +consstring(j) -> s; +;;; read the integer +lvars i = itemrep(); diff --git a/Task/User-input-Text/PostScript/user-input-text-1.ps b/Task/User-input-Text/PostScript/user-input-text-1.ps new file mode 100644 index 0000000000..4a13aed9f3 --- /dev/null +++ b/Task/User-input-Text/PostScript/user-input-text-1.ps @@ -0,0 +1,6 @@ +%open stdin for reading (and name the channel "kbd"): +/kbd (%stdin) (r) file def +%make ten-char buffer to read string into: +/buf (..........) def +%read string into buffer: +kbd buf readline diff --git a/Task/User-input-Text/PostScript/user-input-text-2.ps b/Task/User-input-Text/PostScript/user-input-text-2.ps new file mode 100644 index 0000000000..0b03c16c37 --- /dev/null +++ b/Task/User-input-Text/PostScript/user-input-text-2.ps @@ -0,0 +1,2 @@ +%if the read was successful, convert the string to integer: +{cvi} if diff --git a/Task/User-input-Text/PowerShell/user-input-text.psh b/Task/User-input-Text/PowerShell/user-input-text.psh new file mode 100644 index 0000000000..9d904a3244 --- /dev/null +++ b/Task/User-input-Text/PowerShell/user-input-text.psh @@ -0,0 +1,2 @@ +$string = Read-Host "Input a string" +[int]$number = Read-Host "Input a number" diff --git a/Task/User-input-Text/PureBasic/user-input-text.purebasic b/Task/User-input-Text/PureBasic/user-input-text.purebasic new file mode 100644 index 0000000000..c2a0895a0c --- /dev/null +++ b/Task/User-input-Text/PureBasic/user-input-text.purebasic @@ -0,0 +1,16 @@ +If OpenConsole() + ; Declare a string and a integer to be used + Define txt.s, num.i + + Print("Enter a string: ") + txt=Input() + + Repeat + Print("Enter the number 75000: ") + num=Val(Input()) ; Converts the Input to a Value with Val() + Until num=75000 + ; Check that the user really gives us 75000! + + Print("You made it!") + Delay(3000): CloseConsole() +EndIf diff --git a/Task/User-input-Text/Python/user-input-text-1.py b/Task/User-input-Text/Python/user-input-text-1.py new file mode 100644 index 0000000000..b98ba656be --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-1.py @@ -0,0 +1 @@ + string = raw_input("Input a string: ") diff --git a/Task/User-input-Text/Python/user-input-text-2.py b/Task/User-input-Text/Python/user-input-text-2.py new file mode 100644 index 0000000000..542936e49d --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-2.py @@ -0,0 +1 @@ + string = input("Input a string: ") diff --git a/Task/User-input-Text/Python/user-input-text-3.py b/Task/User-input-Text/Python/user-input-text-3.py new file mode 100644 index 0000000000..590e90ef8d --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-3.py @@ -0,0 +1 @@ + number = input("Input a number: ") # Deprecated, please don't use. diff --git a/Task/User-input-Text/Python/user-input-text-4.py b/Task/User-input-Text/Python/user-input-text-4.py new file mode 100644 index 0000000000..ef48fb0346 --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-4.py @@ -0,0 +1 @@ + number = eval(input("Input a number: ")) # Evil, please don't use. diff --git a/Task/User-input-Text/Python/user-input-text-5.py b/Task/User-input-Text/Python/user-input-text-5.py new file mode 100644 index 0000000000..cadf09dd76 --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-5.py @@ -0,0 +1 @@ + number = float(raw_input("Input a number: ")) diff --git a/Task/User-input-Text/Python/user-input-text-6.py b/Task/User-input-Text/Python/user-input-text-6.py new file mode 100644 index 0000000000..b10f9b5f9e --- /dev/null +++ b/Task/User-input-Text/Python/user-input-text-6.py @@ -0,0 +1 @@ + number = float(input("Input a number: ")) diff --git a/Task/User-input-Text/R/user-input-text.r b/Task/User-input-Text/R/user-input-text.r new file mode 100644 index 0000000000..2edd069307 --- /dev/null +++ b/Task/User-input-Text/R/user-input-text.r @@ -0,0 +1,2 @@ +stringval <- readline("String: ") +intval <- as.integer(readline("Integer: ")) diff --git a/Task/User-input-Text/REBOL/user-input-text.rebol b/Task/User-input-Text/REBOL/user-input-text.rebol new file mode 100644 index 0000000000..08f159e88b --- /dev/null +++ b/Task/User-input-Text/REBOL/user-input-text.rebol @@ -0,0 +1,29 @@ +REBOL [ + Title: "Textual User Input" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/User_Input_-_text +] + +s: n: "" + +; Because I have several things to check for, I've made a function to +; handle it. Note the question mark in the function name, this convention +; is often used in Forth to indicate test of some sort. + +valid?: func [s n][ + error? try [n: to-integer n] ; Ignore error if conversion fails. + all [0 < length? s 75000 = n]] + +; I don't want to give up until I've gotten something useful, so I +; loop until the user enters valid data. + +while [not valid? s n][ + print "Please enter a string, and the number 75000:" + s: ask "string: " + n: ask "number: " +] + +; It always pays to be polite... + +print rejoin [ "Thank you. Your string was '" s "'."] diff --git a/Task/User-input-Text/REXX/user-input-text.rexx b/Task/User-input-Text/REXX/user-input-text.rexx new file mode 100644 index 0000000000..8d8641c382 --- /dev/null +++ b/Task/User-input-Text/REXX/user-input-text.rexx @@ -0,0 +1,11 @@ +/*REXX program gets a string and the number 75000 from the console. */ + +say 'Please enter a text string:' /*show prompt for a text string. */ +parse pull userString /*get the user text and store it.*/ + + do until userNumber=75000 /*repeat until correct.*/ + say /*display a blank line.*/ + say 'Please enter the number 75000' /*show the nice prompt.*/ + parse pull userNumber /*get the user text. */ + end /*until*/ /*now, check if it's OK*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/User-input-Text/Rascal/user-input-text.rascal b/Task/User-input-Text/Rascal/user-input-text.rascal new file mode 100644 index 0000000000..aca3b0fd12 --- /dev/null +++ b/Task/User-input-Text/Rascal/user-input-text.rascal @@ -0,0 +1,8 @@ +import util::IDE; +public void InputConsole(){ + x = ""; + createConsole("Input Console", + "Welcome to the Input Console\nInput\> ", + str (str inp) {x = ""; + return "\n\nInput\>";}); +} diff --git a/Task/User-input-Text/Raven/user-input-text.raven b/Task/User-input-Text/Raven/user-input-text.raven new file mode 100644 index 0000000000..21df3850da --- /dev/null +++ b/Task/User-input-Text/Raven/user-input-text.raven @@ -0,0 +1,2 @@ +'Input a string: ' print expect as str +'Input an integer: ' print expect 0 prefer as num diff --git a/Task/User-input-Text/Retro/user-input-text.retro b/Task/User-input-Text/Retro/user-input-text.retro new file mode 100644 index 0000000000..06a70210f3 --- /dev/null +++ b/Task/User-input-Text/Retro/user-input-text.retro @@ -0,0 +1,6 @@ +: example ( "- ) + remapping off + "Enter a string: " puts 10 accept tib tempString + [ "Enter 75000: " puts getToken toNumber 75000 = cr ] until + "Your string was: '%s'\n" puts + remapping on ; diff --git a/Task/User-input-Text/Ruby/user-input-text.rb b/Task/User-input-Text/Ruby/user-input-text.rb new file mode 100644 index 0000000000..af62ca7b47 --- /dev/null +++ b/Task/User-input-Text/Ruby/user-input-text.rb @@ -0,0 +1,6 @@ +print "Enter a string: " +s = gets +print "Enter an integer: " +i = gets.to_i # If string entered, will return zero +puts "String = #{s}" +puts "Integer = #{i}" diff --git a/Task/User-input-Text/SNOBOL4/user-input-text.sno b/Task/User-input-Text/SNOBOL4/user-input-text.sno new file mode 100644 index 0000000000..057fd9b000 --- /dev/null +++ b/Task/User-input-Text/SNOBOL4/user-input-text.sno @@ -0,0 +1,6 @@ + output = "Enter a string:" + str = trim(input) + output = "Enter an integer:" + int = trim(input) + output = "String: " str " Integer: " int +end diff --git a/Task/User-input-Text/Scala/user-input-text.scala b/Task/User-input-Text/Scala/user-input-text.scala new file mode 100644 index 0000000000..936f45c9b5 --- /dev/null +++ b/Task/User-input-Text/Scala/user-input-text.scala @@ -0,0 +1,4 @@ +print("Enter a number: ") +val i=Console.readInt +print("Enter a string: ") +val s=Console.readLine diff --git a/Task/User-input-Text/Scheme/user-input-text.ss b/Task/User-input-Text/Scheme/user-input-text.ss new file mode 100644 index 0000000000..2fca4e17de --- /dev/null +++ b/Task/User-input-Text/Scheme/user-input-text.ss @@ -0,0 +1,4 @@ +(define str (read)) +(define num (read)) +(display "String = ") (display str) +(display "Integer = ") (display num) diff --git a/Task/User-input-Text/Seed7/user-input-text.seed7 b/Task/User-input-Text/Seed7/user-input-text.seed7 new file mode 100644 index 0000000000..809a04eb40 --- /dev/null +++ b/Task/User-input-Text/Seed7/user-input-text.seed7 @@ -0,0 +1,12 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var integer: integer_input is 0; + var string: string_input is ""; + begin + write("Enter an integer: "); + readln(integer_input); + write("Enter a string: "); + readln(string_input); + end func; diff --git a/Task/User-input-Text/Slate/user-input-text.slate b/Task/User-input-Text/Slate/user-input-text.slate new file mode 100644 index 0000000000..d37ebbbab5 --- /dev/null +++ b/Task/User-input-Text/Slate/user-input-text.slate @@ -0,0 +1,7 @@ +print: (query: 'Enter a String: '). +[| n | + n: (Integer readFrom: (query: 'Enter an Integer: ')). + (n is: Integer) + ifTrue: [print: n] + ifFalse: [inform: 'Not an integer: ' ; n printString] +] do. diff --git a/Task/User-input-Text/Smalltalk/user-input-text.st b/Task/User-input-Text/Smalltalk/user-input-text.st new file mode 100644 index 0000000000..7c5d381606 --- /dev/null +++ b/Task/User-input-Text/Smalltalk/user-input-text.st @@ -0,0 +1,5 @@ +'Enter a number: ' display. +a := stdin nextLine asInteger. + +'Enter a string: ' display. +b := stdin nextLine. diff --git a/Task/User-input-Text/Standard-ML/user-input-text.ml b/Task/User-input-Text/Standard-ML/user-input-text.ml new file mode 100644 index 0000000000..8a69caad42 --- /dev/null +++ b/Task/User-input-Text/Standard-ML/user-input-text.ml @@ -0,0 +1,7 @@ +print "Enter a string: "; +let val str = valOf (TextIO.inputLine TextIO.stdIn) in (* note: this keeps the trailing newline *) + print "Enter an integer: "; + let val num = valOf (TextIO.scanStream (Int.scan StringCvt.DEC) TextIO.stdIn) in + print (str ^ Int.toString num ^ "\n") + end +end diff --git a/Task/User-input-Text/TI-83-BASIC/user-input-text.ti-83 b/Task/User-input-Text/TI-83-BASIC/user-input-text.ti-83 new file mode 100644 index 0000000000..ab5076e54a --- /dev/null +++ b/Task/User-input-Text/TI-83-BASIC/user-input-text.ti-83 @@ -0,0 +1,6 @@ + :Input "Enter a string:",Str1 + :Prompt i + :If(i ≠ 75000): Then + :Disp "That isn't 75000" + :Else + :Stop diff --git a/Task/User-input-Text/TI-89-BASIC/user-input-text.ti-89 b/Task/User-input-Text/TI-89-BASIC/user-input-text.ti-89 new file mode 100644 index 0000000000..7a1f787dea --- /dev/null +++ b/Task/User-input-Text/TI-89-BASIC/user-input-text.ti-89 @@ -0,0 +1,11 @@ +Prgm + InputStr "Enter a string", s + Loop + Prompt integer + If integer ≠ 75000 Then + Disp "That wasn't 75000." + Else + Exit + EndIf + EndLoop +EndPrgm diff --git a/Task/User-input-Text/TUSCRIPT/user-input-text.tuscript b/Task/User-input-Text/TUSCRIPT/user-input-text.tuscript new file mode 100644 index 0000000000..e44cd080d6 --- /dev/null +++ b/Task/User-input-Text/TUSCRIPT/user-input-text.tuscript @@ -0,0 +1,12 @@ +$$ MODE TUSCRIPT +LOOP +ASK "Enter a string": str="" +ASK "Enter an integer": int="" +IF (int=='digits') THEN +PRINT "int=",int," str=",str +EXIT +ELSE +PRINT/ERROR int," is not an integer" +CYCLE +ENDIF +ENDLOOP diff --git a/Task/User-input-Text/Tcl/user-input-text-1.tcl b/Task/User-input-Text/Tcl/user-input-text-1.tcl new file mode 100644 index 0000000000..9d00ba84b3 --- /dev/null +++ b/Task/User-input-Text/Tcl/user-input-text-1.tcl @@ -0,0 +1,2 @@ +set str [gets stdin] +set num [gets stdin] diff --git a/Task/User-input-Text/Tcl/user-input-text-2.tcl b/Task/User-input-Text/Tcl/user-input-text-2.tcl new file mode 100644 index 0000000000..5ae8fbeaa6 --- /dev/null +++ b/Task/User-input-Text/Tcl/user-input-text-2.tcl @@ -0,0 +1 @@ +if {![string is integer -strict $num]} then { ...do something here...} diff --git a/Task/User-input-Text/Tcl/user-input-text-3.tcl b/Task/User-input-Text/Tcl/user-input-text-3.tcl new file mode 100644 index 0000000000..1ebbac01d8 --- /dev/null +++ b/Task/User-input-Text/Tcl/user-input-text-3.tcl @@ -0,0 +1,6 @@ +set input 0 +while {$input != 75000} { + puts -nonewline "enter the number '75000': " + flush stdout + set input [gets stdin] +} diff --git a/Task/User-input-Text/Tcl/user-input-text-4.tcl b/Task/User-input-Text/Tcl/user-input-text-4.tcl new file mode 100644 index 0000000000..264c42f549 --- /dev/null +++ b/Task/User-input-Text/Tcl/user-input-text-4.tcl @@ -0,0 +1,9 @@ +proc question {var message} { + upvar 1 $var v + puts -nonewline "$message: " + flush stdout + gets stdin $v +} +question name "What is your name" +question task "What is your quest" +question doom "What is the air-speed velocity of an unladen swallow" diff --git a/Task/User-input-Text/Toka/user-input-text.toka b/Task/User-input-Text/Toka/user-input-text.toka new file mode 100644 index 0000000000..a679527589 --- /dev/null +++ b/Task/User-input-Text/Toka/user-input-text.toka @@ -0,0 +1,6 @@ +needs readline +." Enter a string: " readline is-data the-string +." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-number + +the-string type cr +the-number . cr diff --git a/Task/User-input-Text/UNIX-Shell/user-input-text.sh b/Task/User-input-Text/UNIX-Shell/user-input-text.sh new file mode 100644 index 0000000000..8960b2da15 --- /dev/null +++ b/Task/User-input-Text/UNIX-Shell/user-input-text.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +read STRING +read INTEGER diff --git a/Task/User-input-Text/Vedit-macro-language/user-input-text.vedit b/Task/User-input-Text/Vedit-macro-language/user-input-text.vedit new file mode 100644 index 0000000000..3693a481c1 --- /dev/null +++ b/Task/User-input-Text/Vedit-macro-language/user-input-text.vedit @@ -0,0 +1,2 @@ +Get_Input(1, "Enter a string: ") +#2 = Get_Num("Enter a number: ") diff --git a/Task/User-input-Text/Visual-Basic-.NET/user-input-text-1.visual b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-1.visual new file mode 100644 index 0000000000..31986d7aa5 --- /dev/null +++ b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-1.visual @@ -0,0 +1,3 @@ +Dim i As Integer +Console.WriteLine("Enter an Integer") +i = Console.ReadLine() diff --git a/Task/User-input-Text/Visual-Basic-.NET/user-input-text-2.visual b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-2.visual new file mode 100644 index 0000000000..ce988b7e00 --- /dev/null +++ b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-2.visual @@ -0,0 +1,9 @@ +Dim i As Integer +Dim iString As String +Console.WriteLine("Enter an Integer") +iString = Console.ReadLine() +Try + i = Convert.ToInt32(iString) +Catch ex As Exception + Console.WriteLine("This is not an Integer") +End Try diff --git a/Task/User-input-Text/Visual-Basic-.NET/user-input-text-3.visual b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-3.visual new file mode 100644 index 0000000000..77b36379e9 --- /dev/null +++ b/Task/User-input-Text/Visual-Basic-.NET/user-input-text-3.visual @@ -0,0 +1,3 @@ +Dim i As String +Console.WriteLine("Enter a String") +i = Console.ReadLine() diff --git a/Task/User-input-Text/XPL0/user-input-text.xpl0 b/Task/User-input-Text/XPL0/user-input-text.xpl0 new file mode 100644 index 0000000000..628648a0c0 --- /dev/null +++ b/Task/User-input-Text/XPL0/user-input-text.xpl0 @@ -0,0 +1,15 @@ +string 0; \use zero-terminated strings, instead of MSb terminated +include c:\cxpl\codes; +int I; +char Name(128); \the keyboard buffer limits input to 128 characters + +[Text(0, "What's your name? "); +I:= 0; +loop [Name(I):= ChIn(0); \buffered keyboard input + if Name(I) = $0D\CR\ then quit; \Carriage Return = Enter key + I:= I+1; + ]; +Name(I):= 0; \terminate string +Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": "); +IntOut(0, IntIn(0)); CrLf(0); \echo the number +] diff --git a/Task/User-input-Text/ZX-Spectrum-Basic/user-input-text.zx b/Task/User-input-Text/ZX-Spectrum-Basic/user-input-text.zx new file mode 100644 index 0000000000..3c910be03b --- /dev/null +++ b/Task/User-input-Text/ZX-Spectrum-Basic/user-input-text.zx @@ -0,0 +1,2 @@ +10 INPUT "Enter a string:"; s$ +20 INPUT "Enter a number: "; n diff --git a/Task/Vampire-number/0DESCRIPTION b/Task/Vampire-number/0DESCRIPTION new file mode 100644 index 0000000000..d48fafcd19 --- /dev/null +++ b/Task/Vampire-number/0DESCRIPTION @@ -0,0 +1,13 @@ +A [[wp:Vampire_number|vampire number]] is a natural number with an even number of digits, that can be factored into two integers. These two factors are called the ''fangs'', and must have the following properties: +* they each contain half the number of the digits of the original number +* together they consist of exactly the same digits as the original number +* at most one of them has a trailing zero +An example of a Vampire number and its fangs: 1260 : (21, 60) +;Task description: +# Print the first 25 Vampire numbers and their fangs. +# Check if the following numbers are Vampire numbers and, if so, print them and their fangs: 16758243290880, 24959017348650, 14593825548650 +Note that a Vampire number can have more than 1 pair of fangs. +;See also: +* [http://www.numberphile.com/videos/vampire_numbers.html numberphile.com]. +* [http://users.cybercity.dk/~dsl522332/math/vampires/ Vampire search algorithm] +* [[oeis:A014575|Vampire numbers on OEIS]] diff --git a/Task/Vampire-number/1META.yaml b/Task/Vampire-number/1META.yaml new file mode 100644 index 0000000000..aed8ff126a --- /dev/null +++ b/Task/Vampire-number/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Mathematics diff --git a/Task/Vampire-number/C++/vampire-number.cpp b/Task/Vampire-number/C++/vampire-number.cpp new file mode 100644 index 0000000000..6253d513c3 --- /dev/null +++ b/Task/Vampire-number/C++/vampire-number.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include +#include + +bool isVampireNumber( long number, std::vector > & solution ) { + std::ostringstream numberstream ; + numberstream << number ; + std::string numberstring( numberstream.str( ) ) ; + std::sort ( numberstring.begin( ) , numberstring.end( ) ) ; + int fanglength = numberstring.length( ) / 2 ; + long start = static_cast( std::pow( 10 , fanglength - 1 ) ) ; + long end = start * 10 ; + for ( long i = start ; i < ( end - start ) / 2 ; i++ ) { + if ( number % i == 0 ) { + long quotient = number / i ; + if ( ( i % 10 == 0 ) && ( quotient % 10 == 0 ) ) + return false ; + numberstream.str( "" ) ; //clear the number stream + numberstream << i << quotient ; + std::string divisorstring ( numberstream.str( ) ) ; + std::sort ( divisorstring.begin( ) , divisorstring.end( ) ) ; + if ( divisorstring == numberstring ) { + std::pair divisors = std::make_pair( i, quotient ) ; + solution.push_back( divisors ) ; + } + } + } + return !solution.empty( ) ; +} + +void printOut( const std::pair & solution ) { + std::cout << "[ " << solution.first << " , " << solution.second << " ]" ; +} + +int main( ) { + int vampireNumbersFound = 0 ; + std::vector > solutions ; + double i = 1.0 ; + while ( vampireNumbersFound < 25 ) { + long start = static_cast( std::pow( 10 , i ) ) ; + long end = start * 10 ; + for ( long num = start ; num < end ; num++ ) { + if ( isVampireNumber( num , solutions ) ) { + std::cout << vampireNumbersFound << " :" << num << " is a vampire number! These are the fangs:\n" ; + std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; + std::cout << "\n_______________" << std::endl ; + solutions.clear( ) ; + vampireNumbersFound++ ; + if ( vampireNumbersFound == 25 ) + break ; + } + } + i += 2.0 ; + } + std::vector testnumbers ; + testnumbers.push_back( 16758243290880 ) ; + testnumbers.push_back( 2495901734865 ) ; + testnumbers.push_back( 14593825548650 ) ; + for ( std::vector::const_iterator svl = testnumbers.begin( ) ; + svl != testnumbers.end( ) ; svl++ ) { + if ( isVampireNumber( *svl , solutions ) ) { + std::cout << *svl << " is a vampire number! The fangs:\n" ; + std::for_each( solutions.begin( ) , solutions.end( ) , printOut ) ; + std::cout << std::endl ; + solutions.clear( ) ; + } else { + std::cout << *svl << " is not a vampire number!" << std::endl ; + } + } + return 0 ; +} diff --git a/Task/Vampire-number/C/vampire-number.c b/Task/Vampire-number/C/vampire-number.c new file mode 100644 index 0000000000..2e7b982cf9 --- /dev/null +++ b/Task/Vampire-number/C/vampire-number.c @@ -0,0 +1,82 @@ +#include +#include +#include +#include + +typedef uint64_t xint; +typedef unsigned long long ull; + +xint tens[20]; + +inline xint max(xint a, xint b) { return a > b ? a : b; } +inline xint min(xint a, xint b) { return a < b ? a : b; } +inline int ndigits(xint x) +{ + int n = 0; + while (x) n++, x /= 10; + return n; +} + +inline xint dtally(xint x) +{ + xint t = 0; + while (x) t += 1<<((x%10) * 6), x /= 10; + + return t; +} + +int fangs(xint x, xint *f) +{ + int n = 0; + int nd = ndigits(x); + if (nd & 1) return 0; + nd /= 2; + + xint lo, hi; + lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1)); + hi = min(x / lo, sqrt(x)); + + xint a, b, t = dtally(x); + for (a = lo; a <= hi; a++) { + b = x / a; + if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b)) + f[n++] = a; + } + + return n; +} + +void show_fangs(xint x, xint *f, xint cnt) +{ + printf("%llu", (ull)x); + int i; + for (i = 0; i < cnt; i++) + printf(" = %llu x %llu", (ull)f[i], (ull)(x / f[i])); + putchar('\n'); +} + +int main(void) +{ + int i, j, n; + xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0}; + + tens[0] = 1; + for (i = 1; i < 20; i++) + tens[i] = tens[i-1] * 10; + + for (x = 1, n = 0; n < 25; x++) { + if (!(j = fangs(x, f))) continue; + printf("%2d: ", ++n); + show_fangs(x, f, j); + } + + putchar('\n'); + for (i = 0; bigs[i]; i++) { + if ((j = fangs(bigs[i], f))) + show_fangs(bigs[i], f, j); + else + printf("%llu is not vampiric\n", (ull)bigs[i]); + } + + return 0; +} diff --git a/Task/Vampire-number/Clojure/vampire-number.clj b/Task/Vampire-number/Clojure/vampire-number.clj new file mode 100644 index 0000000000..5fcda38878 --- /dev/null +++ b/Task/Vampire-number/Clojure/vampire-number.clj @@ -0,0 +1,23 @@ +(defn factor-pairs [n] + (for [x (range 2 (Math/sqrt n)) + :when (zero? (mod n x))] + [x (quot n x)])) + +(defn fangs [n] + (let [dlen (comp count str) + half (/ (dlen n) 2) + halves? #(apply = (cons half (map dlen %))) + digits #(sort (apply str %))] + (filter #(and (halves? %) + (= (sort (str n)) (digits %))) + (factor-pairs n)))) + +(defn vampiric? [n] + (let [fangs (fangs n)] + (if (empty? fangs) nil [n fangs]))) + +(doseq [n (take 25 (keep vampiric? (range)))] + (prn n)) + +(doseq [n [16758243290880, 24959017348650, 14593825548650]] + (println (or (vampiric? n) (str n " is not vampiric.")))) diff --git a/Task/Vampire-number/D/vampire-number-1.d b/Task/Vampire-number/D/vampire-number-1.d new file mode 100644 index 0000000000..60d50b4eba --- /dev/null +++ b/Task/Vampire-number/D/vampire-number-1.d @@ -0,0 +1,76 @@ +import std.stdio, std.algorithm, std.range, std.array; + +immutable(long[2])[] vampireNumberFactors(in long n) { + + static typeof(return) factorPairs(in long k) pure nothrow { + typeof(return) pairs; + foreach (immutable i; 2 .. cast(long)(k ^^ 0.5 + 1)) + if (k % i == 0) { + immutable q = k / i; + if (q > i) + pairs ~= [i, q]; // Heap-allocated pair. + } + return pairs; + } + + static long[] getDigits(in long k) pure nothrow { + typeof(return) digits; + long m = k; + while (m > 0) { + digits ~= (m % 10); + m /= 10; + } + digits.reverse(); + return digits; + } + + if (n < 2) + return null; + + auto digits = getDigits(n); + if (digits.length % 2 != 0) + return null; + digits.sort(); + + typeof(return) result; + immutable half = digits.length / 2; + + foreach (immutable pair; factorPairs(n)) { + /*immutable*/ auto f1 = getDigits(pair.front); + if (f1.length != half) + continue; + + immutable f2 = getDigits(pair.back); + if (f2.length != half) + continue; + + if (f1.back == 0 && f2.back == 0) + continue; + + if (!(f1 ~ f2).sort().equal(digits)) + continue; + + result ~= pair; + } + + return result; +} + +void main() { + for (long count = 0, n = 0; count < 25; n++) { + immutable factors = vampireNumberFactors(n); + if (!factors.empty) { + writefln("%s : %(%s %)", n, factors); + count++; + } + } + + writeln; + foreach (immutable n; [16_758_243_290_880L, + 24_959_017_348_650L, + 14_593_825_548_650L]) { + immutable factors = vampireNumberFactors(n); + if (!factors.empty) + writefln("%s: %(%s %)", n, vampireNumberFactors(n)); + } +} diff --git a/Task/Vampire-number/D/vampire-number-2.d b/Task/Vampire-number/D/vampire-number-2.d new file mode 100644 index 0000000000..dd692d3867 --- /dev/null +++ b/Task/Vampire-number/D/vampire-number-2.d @@ -0,0 +1,92 @@ +import std.stdio, std.math, std.algorithm, std.array, std.traits; + +T[N] pows(T, size_t N)() { + typeof(return) result; + result[0] = 1; + foreach (i, ref r; result[1 .. $]) + r = result[i] * 10; + return result; +} + +__gshared immutable tenPowsU = pows!(uint, 10); +__gshared immutable tenPowsUL = pows!(ulong, 20); + +size_t nDigits(T)(in T x) pure nothrow { + Unqual!T y = x; + size_t n = 0; + while (y) { + n++; + y /= 10; + } + return n; +} + +T dTally(T)(in T x) pure nothrow { + Unqual!T y = x; + T t = 0; + while (y) { + t += 1 << ((y % 10) * 6); + y /= 10; + } + return t; +} + +T[] fangs(T)(in T x, T[] f) +pure nothrow if (is(T == uint) || is(T == ulong)) { + alias tenPows = Select!(is(T == ulong), tenPowsUL, tenPowsU); + + immutable nd0 = nDigits(x); + if (nd0 & 1) + return null; + immutable nd = nd0 / 2; + + immutable lo = max(tenPows[nd - 1], + (x + tenPows[nd] - 2) / (tenPows[nd] - 1)); + immutable hi = min(x / lo, cast(T)sqrt(cast(real)x)); + immutable t = x.dTally; + + size_t n = 0; + foreach (immutable a; lo .. hi + 1) { + immutable b = x / a; + if (a * b == x + && (a % 10 || b % 10) + && t == (a.dTally + b.dTally)) { + f[n] = a; + n++; + } + } + + return f[0 .. n]; +} + +void showFangs(T)(in T x, in T[] fs) { + x.write; + foreach (immutable fi; fs) + writef(" = %d x %d", fi, x / fi); + writeln; +} + +void main() { + uint[16] fu; + for (uint x = 1, n = 0; n < 25; x++) { + const fs = fangs(x, fu); + if (fs.empty) + continue; + n++; + writef("%2d: ", n); + showFangs(x, fs); + } + writeln; + + __gshared static immutable ulong[3] bigs = [16_758_243_290_880UL, + 24_959_017_348_650UL, + 14_593_825_548_650UL]; + ulong[fu.length] ful; + foreach (immutable bi; bigs) { + const fs = fangs(bi, ful); + if (fs.empty) + writeln(bi, " is not vampiric"); + else + showFangs(bi, fs); + } +} diff --git a/Task/Vampire-number/Haskell/vampire-number.hs b/Task/Vampire-number/Haskell/vampire-number.hs new file mode 100644 index 0000000000..b88b285bb8 --- /dev/null +++ b/Task/Vampire-number/Haskell/vampire-number.hs @@ -0,0 +1,41 @@ +import Data.List (sort) + +primes = 2:filter isPrime [3,5..] where + isPrime n = f n primes where + f n (p:ps) + | p*p > n = True + | n`mod`p == 0 = False + | otherwise = f n ps + +primeFactors n = f n primes where + f n (p:ps) + | p*p > n = if n == 1 then [] else [(n,1)] + | n`mod`p == 0 = (p,e):f res ps + | otherwise = f n ps + where (e,res) = ppower (n`div`p) p 1 + ppower n p e + | n`mod`p /= 0 = (e,n) + | otherwise = ppower (n`div`p) p (e+1) + +factors n = comb (primeFactors n) where + comb [] = [1] + comb ((p,e):others) = [a*b | b<-map (p^) [0 .. e], a<-comb others] + +ndigit 0 = 0 +ndigit n = 1 + ndigit (n`div`10) + +fangs n + | odd w = [] + | otherwise = map (\x->(x,n`div`x)) $ filter isfang (factors n) where + isfang x = x > xmin && x < y && y < ymax && -- same length + ((x`div`10)/=0 || (y`div`10)/=0) && -- not zero-ended + sort (show n) == sort ((show x) ++ (show y)) -- same digits + where y = n`div`x + w = ndigit n + xmin = 10^(w`div`2-1) + ymax = 10^(w`div`2) + +vampires = filter ((0<).length.fangs) [1..] + +main = mapM (\n->print (n,fangs n)) $ + ((take 25 vampires) ++ [16758243290880, 24959017348650, 14593825548650]) diff --git a/Task/Vampire-number/Java/vampire-number.java b/Task/Vampire-number/Java/vampire-number.java new file mode 100644 index 0000000000..04e92d7406 --- /dev/null +++ b/Task/Vampire-number/Java/vampire-number.java @@ -0,0 +1,48 @@ +import java.util.Arrays; +import java.util.HashSet; + +public class VampireNumbers{ + private static int numDigits(long num){ + return Long.toString(Math.abs(num)).length(); + } + + private static boolean fangCheck(long orig, long fang1, long fang2){ + if(Long.toString(fang1).endsWith("0") && Long.toString(fang2).endsWith("0")) return false; + + int origLen = numDigits(orig); + if(numDigits(fang1) != origLen / 2 || numDigits(fang2) != origLen / 2) return false; + + byte[] origBytes = Long.toString(orig).getBytes(); + byte[] fangBytes = (Long.toString(fang1) + Long.toString(fang2)).getBytes(); + Arrays.sort(origBytes); + Arrays.sort(fangBytes); + return Arrays.equals(origBytes, fangBytes); + } + + public static void main(String[] args){ + HashSet vamps = new HashSet(); + for(long i = 10; vamps.size() <= 25; i++ ){ + if((numDigits(i) % 2) != 0) {i = i * 10 - 1; continue;} + for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){ + if(i % fang1 == 0){ + long fang2 = i / fang1; + if(fangCheck(i, fang1, fang2) && fang1 <= fang2){ + vamps.add(i); + System.out.println(i + ": [" + fang1 + ", " + fang2 +"]"); + } + } + } + } + Long[] nums = {16758243290880L, 24959017348650L, 14593825548650L}; + for(Long i : nums){ + for(long fang1 = 2; fang1 <= Math.sqrt(i) + 1; fang1++){ + if(i % fang1 == 0){ + long fang2 = i / fang1; + if(fangCheck(i, fang1, fang2) && fang1 <= fang2){ + System.out.println(i + ": [" + fang1 + ", " + fang2 +"]"); + } + } + } + } + } +} diff --git a/Task/Vampire-number/Perl-6/vampire-number.pl6 b/Task/Vampire-number/Perl-6/vampire-number.pl6 new file mode 100644 index 0000000000..0998a764c0 --- /dev/null +++ b/Task/Vampire-number/Perl-6/vampire-number.pl6 @@ -0,0 +1,38 @@ +my @vampires := gather for 1 .. * -> $start, $end { + map { + my @fangs = is_vampire($_); + take "$_: { @fangs.join(', ') }" if @fangs.elems + }, 10 ** $start .. 10 ** $end +} + +say "\nFirst 25 Vampire Numbers:\n"; + +.say for @vampires[^25]; + +say "\nIndividual tests:\n"; + +for 16758243290880, 24959017348650, 14593825548650 { + print "$_: "; + my @fangs = is_vampire($_); + if @fangs.elems { + say @fangs.join(', '); + } else { + say 'is not a vampire number.'; + } +} + +sub is_vampire (Int $num) { + my $digits = $num.comb.sort; + my @fangs; + for vfactors($num) -> $this { + my $that = $num div $this; + @fangs.push("$this x $that") if + !($this %% 10 && $that %% 10) and + ($this ~ $that).comb.sort eq $digits; + } + return @fangs; +} + +sub vfactors (Int $n) { + map { $_ if $n %% $_ }, 10**$n.sqrt.log(10).floor .. $n.sqrt.ceiling; +} diff --git a/Task/Vampire-number/Python/vampire-number.py b/Task/Vampire-number/Python/vampire-number.py new file mode 100644 index 0000000000..033627cb76 --- /dev/null +++ b/Task/Vampire-number/Python/vampire-number.py @@ -0,0 +1,75 @@ +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/Vampire-number/REXX/vampire-number.rexx b/Task/Vampire-number/REXX/vampire-number.rexx new file mode 100644 index 0000000000..05c2b6ab46 --- /dev/null +++ b/Task/Vampire-number/REXX/vampire-number.rexx @@ -0,0 +1,42 @@ +/*REXX pgm displays X vampire numbers, or verifies if a # is vampiric.*/ +numeric digits 20 /*be able to handle large numbers*/ +parse arg N .; if N=='' then N=25 /*No arg? Then use the default. */ +#=0 /*number of vampire numbers found*/ +if N>0 then do j=1000 until # >= N /*search until N vampire #s found*/ + v=vampire(j) + if words(v)<=1 then iterate + parse var v v f + #=#+1 + say 'vampire number' right(#,length(N)) "is: " v', fangs=' f + end /*j*/ +if N<0 then do + parse value vampire(-N) with v f + if v=='' then say -N "isn't a vampire number." + else say -N "is a vampire number, fangs=" f + end +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────VAMPIRE subroutine──────────────────*/ +vampire: procedure expose !.; parse arg ? 1 z 1 $; L=length(?); W=L%2 +if L//2 then return '' /*Odd length? Then not vampire. */ +$.= /*used to build BOT and TOP value*/ + do k=1 for length(?); _=substr(?,k,1); $._=$._ || _; end /*k*/ +bot=; do m=0 for 10; bot=bot || $.m; end /*m*/ + +top=left(reverse(bot),w); bot=left(bot,w) /*determine limits of search*/ + + do d=max(bot, 10**(w-1)) to min(top, 10**w-1) + if verify(d,?)\==0 then iterate + if ?//d\==0 then iterate + q=?%d; if d>q then iterate + if q*d//9\==(q+d)//9 then iterate /*modulo 9 congruence.*/ + if verify(q,?)\==0 then iterate + if length(q)\==w then iterate + if right(q,1)==0 then if right(d,1)==0 then iterate + dq=d||q; t=z + do i=1 for L; _=substr(dq,i,1); p=pos(_,t) + if p==0 then iterate d + t=delstr(t,p,1) + end /*i*/ + $=$ d','q + end /*d*/ +return $ diff --git a/Task/Vampire-number/Racket/vampire-number.rkt b/Task/Vampire-number/Racket/vampire-number.rkt new file mode 100644 index 0000000000..6f848034a5 --- /dev/null +++ b/Task/Vampire-number/Racket/vampire-number.rkt @@ -0,0 +1,34 @@ +#lang racket + +;; chock full of fun... including divisors +(require math/number-theory) + +;; predicate to tell if n is a vampire number +(define (sub-vampire?-and-fangs n) + (define digit-count-n (add1 (order-of-magnitude n))) + (define (string-sort-characters s) (sort (string->list s) charstring n))) + (define (fangs-of-n? d e) + (and (<= d e) ; avoid duplication + (= (add1 (order-of-magnitude d)) (add1 (order-of-magnitude e)) (/ digit-count-n 2)) + (not (= 0 (modulo d 10) (modulo e 10))) + (equal? digits-in-order-n + (string-sort-characters (string-append (number->string d) (number->string e)))))) + + (let* ((fangses (for*/list ((d (in-list (divisors n))) #:when (fangs-of-n? d (/ n d))) + (list d (/ n d))))) + (and (not (null? fangses)) (cons n fangses)))) + +(define (vampire?-and-fangs n) + (and (odd? (order-of-magnitude n)) ; even number of digits - else not even worth looking! + (sub-vampire?-and-fangs n))) + +(displayln "First 25 vampire numbers:") +(for ((vmp (sequence-filter identity (sequence-map vampire?-and-fangs (in-naturals 1)))) + (cnt (in-range 1 (add1 25)))) + (printf "#~a ~a~%" cnt vmp)) + +(displayln "Test the big numbers:") +(displayln (vampire?-and-fangs 16758243290880)) +(displayln (vampire?-and-fangs 24959017348650)) +(displayln (vampire?-and-fangs 14593825548650)) diff --git a/Task/Vampire-number/Ruby/vampire-number.rb b/Task/Vampire-number/Ruby/vampire-number.rb new file mode 100644 index 0000000000..55a3f9c896 --- /dev/null +++ b/Task/Vampire-number/Ruby/vampire-number.rb @@ -0,0 +1,25 @@ +def factor_pairs n + (2..n ** 0.5 + 1).map { |i| [i, n / i] if n % i == 0 }.compact +end + +def vampire_factors n + half = n.to_s.size / 2 + factor_pairs(n).select do |a, b| + a.to_s.size == half && b.to_s.size == half && + [a, b].map { |x| x % 10 }.count(0) != 2 && + "#{a}#{b}".chars.sort == n.to_s.chars.sort + end +end + +i = vamps = 0 +until vamps == 25 + vf = vampire_factors(i += 1) + unless vf.empty? + puts "#{i}\t#{vf}" + vamps += 1 + end +end + +[16758243290880, 24959017348650, 14593825548650].each do |n| + puts "#{n}\t#{vf}" unless (vf = vampire_factors n).empty? +end diff --git a/Task/Vampire-number/Tcl/vampire-number-1.tcl b/Task/Vampire-number/Tcl/vampire-number-1.tcl new file mode 100644 index 0000000000..f5ebf81227 --- /dev/null +++ b/Task/Vampire-number/Tcl/vampire-number-1.tcl @@ -0,0 +1,24 @@ +proc factorPairs {n {from 2}} { + set result [list 1 $n] + if {$from<=1} {set from 2} + for {set i $from} {$i<=sqrt($n)} {incr i} { + if {$n%$i} {} {lappend result $i [expr {$n/$i}]} + } + return $result +} + +proc vampireFactors {n} { + if {[string length $n]%2} return + set half [expr {[string length $n]/2}] + set digits [lsort [split $n ""]] + set result {} + foreach {a b} [factorPairs $n [expr {10**$half/10}]] { + if { + [string length $a]==$half && [string length $b]==$half && + ($a%10 || $b%10) && $digits eq [lsort [split $a$b ""]] + } then { + lappend result [list $a $b] + } + } + return $result +} diff --git a/Task/Vampire-number/Tcl/vampire-number-2.tcl b/Task/Vampire-number/Tcl/vampire-number-2.tcl new file mode 100644 index 0000000000..c6a74d769f --- /dev/null +++ b/Task/Vampire-number/Tcl/vampire-number-2.tcl @@ -0,0 +1,25 @@ +# A nicer way to print the evidence of vampire-ness +proc printVampire {n pairs} { + set out "${n}:" + foreach p $pairs { + append out " \[[join $p {, }]\]" + } + puts $out +} +set n 0 +for {set i 0} {$i < 25} {incr i} { + while 1 { + if {[llength [set vamps [vampireFactors [incr n]]]]} { + printVampire $n $vamps + break + } + } +} +puts "" +foreach n {16758243290880 24959017348650 14593825548650} { + if {[llength [set vamps [vampireFactors $n]]]} { + printVampire $n $vamps + } else { + puts "$n is not a vampire number" + } +} diff --git a/Task/Van-der-Corput-sequence/0DESCRIPTION b/Task/Van-der-Corput-sequence/0DESCRIPTION new file mode 100644 index 0000000000..79f3470379 --- /dev/null +++ b/Task/Van-der-Corput-sequence/0DESCRIPTION @@ -0,0 +1,51 @@ +When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the next column to the lefts digit has a multiplier of 2^1 and so on. + +So in the following table: +
  0.
+  1.
+ 10.
+ 11.
+ ...
+The binary number "10" is 1 \times 2^1 + 0 \times 2^0. + +You can have binary digits to the right of the “point” just as in the decimal number system too. in this case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on. + +If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''. + +
  .0
+  .1
+  .01
+  .11
+  ...
+ +The third member of the sequence: binary 0.01 is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4. + +
[[File:Van der corput distribution.png|400|thumb|right|Distribution of 2500 points each: Van der Corput (top) vs pseudorandom]] Members of the sequence lie within the interval 0 \leq x < 1. Points within the sequence tend to be evenly distributed which is a useful trait to have for [[wp:Monte Carlo method|Monte Carlo simulations]]. +This sequence is also a superset of the numbers representable by the "fraction" field of [[wp:IEEE 754-1985|an old IEEE floating point standard]]. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. + +'''Hint''' + +A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer: +>>> def base10change(n, base): + digits = [] + while n: + n,remainder = divmod(n, base) + digits.insert(0, remainder) + return digits + +>>> base10change(11, 2) +[1, 0, 1, 1] +the above showing that 11 in decimal is 1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0.
+Reflected this would become .1101 or 1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4} + +'''Task Description''' + +* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2. +* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0). + +* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. + +''See also'' +* [http://www.puc-rio.br/marco.ind/quasi_mc.html#low_discrep The Basic Low Discrepancy Sequences] +* [[Non-decimal radices/Convert]] +* [[wp:Van der Corput sequence|Van der Corput sequence]] diff --git a/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada b/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada new file mode 100644 index 0000000000..41b511f3d0 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada @@ -0,0 +1,27 @@ +with Ada.Text_IO; + +procedure Main is + package Float_IO is new Ada.Text_IO.Float_IO (Float); + function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is + Value : Natural := N; + Result : Float := 0.0; + Exponent : Positive := 1; + begin + while Value > 0 loop + Result := Result + + Float (Value mod Base) / Float (Base ** Exponent); + Value := Value / Base; + Exponent := Exponent + 1; + end loop; + return Result; + end Van_Der_Corput; +begin + for Base in 2 .. 5 loop + Ada.Text_IO.Put ("Base" & Integer'Image (Base) & ":"); + for N in 1 .. 10 loop + Ada.Text_IO.Put (' '); + Float_IO.Put (Item => Van_Der_Corput (N, Base), Exp => 0); + end loop; + Ada.Text_IO.New_Line; + end loop; +end Main; diff --git a/Task/Van-der-Corput-sequence/BBC-BASIC/van-der-corput-sequence.bbc b/Task/Van-der-Corput-sequence/BBC-BASIC/van-der-corput-sequence.bbc new file mode 100644 index 0000000000..3d58a4434b --- /dev/null +++ b/Task/Van-der-Corput-sequence/BBC-BASIC/van-der-corput-sequence.bbc @@ -0,0 +1,19 @@ + @% = &20509 + FOR base% = 2 TO 5 + PRINT "Base " ; STR$(base%) ":" + FOR number% = 0 TO 9 + PRINT FNvdc(number%, base%); + NEXT + PRINT + NEXT + END + + DEF FNvdc(n%, b%) + LOCAL v, s% + s% = 1 + WHILE n% + s% *= b% + v += (n% MOD b%) / s% + n% DIV= b% + ENDWHILE + = v diff --git a/Task/Van-der-Corput-sequence/C++/van-der-corput-sequence.cpp b/Task/Van-der-Corput-sequence/C++/van-der-corput-sequence.cpp new file mode 100644 index 0000000000..34cb20cdfb --- /dev/null +++ b/Task/Van-der-Corput-sequence/C++/van-der-corput-sequence.cpp @@ -0,0 +1,26 @@ +#include +#include + +double vdc(int n, double base = 2) +{ + double vdc = 0, denom = 1; + while (n) + { + vdc += fmod(n, base) / (denom *= base); + n /= base; // note: conversion from 'double' to 'int' + } + return vdc; +} + +int main() +{ + for (double base = 2; base < 6; ++base) + { + std::cout << "Base " << base << "\n"; + for (int n = 0; n < 10; ++n) + { + std::cout << vdc(n, base) << " "; + } + std::cout << "\n\n"; + } +} diff --git a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c new file mode 100644 index 0000000000..4281b56813 --- /dev/null +++ b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-1.c @@ -0,0 +1,35 @@ +#include + +void vc(int n, int base, int *num, int *denom) +{ + int p = 0, q = 1; + + while (n) { + p = p * base + (n % base); + q *= base; + n /= base; + } + + *num = p; + *denom = q; + + while (p) { n = p; p = q % p; q = n; } + *num /= q; + *denom /= q; +} + +int main() +{ + int d, n, i, b; + for (b = 2; b < 6; b++) { + printf("base %d:", b); + for (i = 0; i < 10; i++) { + vc(i, b, &n, &d); + if (n) printf(" %d/%d", n, d); + else printf(" 0"); + } + printf("\n"); + } + + return 0; +} diff --git a/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c new file mode 100644 index 0000000000..7911ed15f4 --- /dev/null +++ b/Task/Van-der-Corput-sequence/C/van-der-corput-sequence-2.c @@ -0,0 +1,4 @@ +base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16 +base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27 +base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8 +base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 diff --git a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp new file mode 100644 index 0000000000..ae1a6f5a5c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-1.lisp @@ -0,0 +1,11 @@ +(defun van-der-Corput (n base) + (loop for d = 1 then (* d base) while (<= d n) + finally + (return (/ (parse-integer + (reverse (write-to-string n :base base)) + :radix base) + d)))) + +(loop for base from 2 to 5 do + (format t "Base ~a: ~{~6a~^~}~%" base + (loop for i to 10 collect (van-der-Corput i base)))) diff --git a/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp new file mode 100644 index 0000000000..0c3a4c0974 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence-2.lisp @@ -0,0 +1,4 @@ +Base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16 5/16 +Base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27 10/27 +Base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8 5/8 +Base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 2/25 diff --git a/Task/Van-der-Corput-sequence/D/van-der-corput-sequence.d b/Task/Van-der-Corput-sequence/D/van-der-corput-sequence.d new file mode 100644 index 0000000000..412c56c562 --- /dev/null +++ b/Task/Van-der-Corput-sequence/D/van-der-corput-sequence.d @@ -0,0 +1,16 @@ +import std.stdio, std.algorithm, std.range; + +double vdc(int n, in double base=2.0) pure nothrow { + double vdc = 0.0, denom = 1.0; + while (n) { + denom *= base; + vdc += (n % base) / denom; + n /= base; + } + return vdc; +} + +void main() { + foreach (b; 2 .. 6) + writeln("\nBase ", b, ": ", iota(10).map!(n => vdc(n, b))()); +} diff --git a/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-1.ela b/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-1.ela new file mode 100644 index 0000000000..c9397ad88d --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-1.ela @@ -0,0 +1,11 @@ +open random number list + +vdc bs n = vdc' 0.0 1.0 n + where vdc' v d n + | n > 0 = vdc' v' d' n' + | else = v + where + d' = d * bs + rem = n % bs + n' = truncate (n / bs) + v' = v + rem / d' diff --git a/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-2.ela b/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-2.ela new file mode 100644 index 0000000000..7e8c2b0de6 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ela/van-der-corput-sequence-2.ela @@ -0,0 +1 @@ +take 10 <| map' (vdc 2.0) [1..] diff --git a/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.euphoria b/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.euphoria new file mode 100644 index 0000000000..f07bcd283c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.euphoria @@ -0,0 +1,20 @@ +function vdc(integer n, atom base) + atom vdc, denom, rem + vdc = 0 + denom = 1 + while n do + denom *= base + rem = remainder(n,base) + n = floor(n/base) + vdc += rem / denom + end while + return vdc +end function + +for i = 2 to 5 do + printf(1,"Base %d\n",i) + for j = 0 to 9 do + printf(1,"%g ",vdc(j,i)) + end for + puts(1,"\n\n") +end for diff --git a/Task/Van-der-Corput-sequence/Forth/van-der-corput-sequence.fth b/Task/Van-der-Corput-sequence/Forth/van-der-corput-sequence.fth new file mode 100644 index 0000000000..535462f96c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Forth/van-der-corput-sequence.fth @@ -0,0 +1,10 @@ +: fvdc ( base n -- f ) + 0e 1e ( F: vdc denominator ) + begin dup while + over s>d d>f f* + over /mod ( base rem n ) + swap s>d d>f fover f/ + frot f+ fswap + repeat 2drop fdrop ; + +: test 10 0 do 2 i fvdc cr f. loop ; diff --git a/Task/Van-der-Corput-sequence/Go/van-der-corput-sequence.go b/Task/Van-der-Corput-sequence/Go/van-der-corput-sequence.go new file mode 100644 index 0000000000..85046b844c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Go/van-der-corput-sequence.go @@ -0,0 +1,40 @@ +package main + +import "fmt" + +func v2(n uint) (r float64) { + p := .5 + for n > 0 { + if n&1 == 1 { + r += p + } + p *= .5 + n >>= 1 + } + return +} + +func newV(base uint) func(uint) float64 { + invb := 1 / float64(base) + return func(n uint) (r float64) { + p := invb + for n > 0 { + r += p * float64(n%base) + p *= invb + n /= base + } + return + } +} + +func main() { + fmt.Println("Base 2:") + for i := uint(0); i < 10; i++ { + fmt.Println(i, v2(i)) + } + fmt.Println("Base 3:") + v3 := newV(3) + for i := uint(0); i < 10; i++ { + fmt.Println(i, v3(i)) + } +} diff --git a/Task/Van-der-Corput-sequence/Haskell/van-der-corput-sequence.hs b/Task/Van-der-Corput-sequence/Haskell/van-der-corput-sequence.hs new file mode 100644 index 0000000000..346cbf0a52 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Haskell/van-der-corput-sequence.hs @@ -0,0 +1,46 @@ +import Data.List +import Data.Ratio +import System.Environment +import Text.Printf + +-- A wrapper type for Rationals to make them look nicer when we print them. +newtype Rat = Rat Rational +instance Show Rat where + show (Rat n) = show (numerator n) ++ "/" ++ show (denominator n) + +-- Convert a list of base b digits to its corresponding number. We assume the +-- digits are valid base b numbers and that their order is from least to most +-- significant. +digitsToNum :: Integer -> [Integer] -> Integer +digitsToNum b = foldr1 (\d acc -> b * acc + d) + +-- Convert a number to the list of its base b digits. The order will be from +-- least to most significant. +numToDigits :: Integer -> Integer -> [Integer] +numToDigits _ 0 = [0] +numToDigits b n = unfoldr step n + where step 0 = Nothing + step m = let (q,r) = m `quotRem` b in Just (r,q) + +-- Return the n'th element in the base b van der Corput sequence. The base +-- must be ≥ 2. +vdc :: Integer -> Integer -> Rat +vdc b n | b < 2 = error "vdc: base must be ≥ 2" + | otherwise = let ds = reverse $ numToDigits b n + in Rat (digitsToNum b ds % b ^ length ds) + +-- Print the base followed by a sequence of van der Corput numbers. +printVdc :: (Integer,[Rat]) -> IO () +printVdc (b,ns) = putStrLn $ printf "Base %d:" b + ++ concatMap (printf " %5s" . show) ns + +-- To print the n'th van der Corput numbers for n in [2,3,4,5] call the program +-- with no arguments. Otherwise, passing the base b, first n, next n and +-- maximum n will print the base b numbers for n in [firstN, nextN, ..., maxN]. +main :: IO () +main = do + args <- getArgs + let (bases, nums) = case args of + [b, f, s, m] -> ([read b], [read f, read s..read m]) + _ -> ([2,3,4,5], [0..9]) + mapM_ printVdc [(b,rs) | b <- bases, let rs = map (vdc b) nums] diff --git a/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-1.icon b/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-1.icon new file mode 100644 index 0000000000..740455255f --- /dev/null +++ b/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-1.icon @@ -0,0 +1,17 @@ +procedure main(A) + base := integer(get(A)) | 2 + every writes(round(vdc(0 to 9,base),10)," ") + write() +end + +procedure vdc(n, base) + e := 1.0 + x := 0.0 + while x +:= 1(((0 < n) % base) / (e *:= base), n /:= base) + return x +end + +procedure round(n,d) + places := 10 ^ d + return real(integer(n*places + 0.5)) / places +end diff --git a/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-2.icon b/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-2.icon new file mode 100644 index 0000000000..b84aa3f373 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Icon/van-der-corput-sequence-2.icon @@ -0,0 +1,6 @@ +procedure vdc(n, base) + s1 := create |((0 < 1(.n, n /:= base)) % base) + s2 := create 2(e := 1.0, |(e *:= base)) + every (result := 0) +:= |s1() / s2() + return result +end diff --git a/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-1.j b/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-1.j new file mode 100644 index 0000000000..643fbb6bd1 --- /dev/null +++ b/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-1.j @@ -0,0 +1 @@ +vdc=: ([ %~ %@[ #. #.inv)"0 _ diff --git a/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-2.j b/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-2.j new file mode 100644 index 0000000000..d8f316ab9d --- /dev/null +++ b/Task/Van-der-Corput-sequence/J/van-der-corput-sequence-2.j @@ -0,0 +1,9 @@ + 2 vdc i.10 NB. 1st 10 nums of Van der Corput sequence in base 2 +0 0.5 0.25 0.75 0.125 0.625 0.375 0.875 0.0625 0.5625 + 2x vdc i.10 NB. as above but using rational nums +0 1r2 1r4 3r4 1r8 5r8 3r8 7r8 1r16 9r16 + 2 3 4 5x vdc i.10 NB. 1st 10 nums of Van der Corput sequence in bases 2 3 4 5 +0 1r2 1r4 3r4 1r8 5r8 3r8 7r8 1r16 9r16 +0 1r3 2r3 1r9 4r9 7r9 2r9 5r9 8r9 1r27 +0 1r4 1r2 3r4 1r16 5r16 9r16 13r16 1r8 3r8 +0 1r5 2r5 3r5 4r5 1r25 6r25 11r25 16r25 21r25 diff --git a/Task/Van-der-Corput-sequence/Java/van-der-corput-sequence.java b/Task/Van-der-Corput-sequence/Java/van-der-corput-sequence.java new file mode 100644 index 0000000000..4a412a5d06 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Java/van-der-corput-sequence.java @@ -0,0 +1,17 @@ +public class VanDerCorput{ + public static double vdc(int n){ + double vdc = 0; + int denom = 1; + while(n != 0){ + vdc += n % 2.0 / (denom *= 2); + n /= 2; + } + return vdc; + } + + public static void main(String[] args){ + for(int i = 0; i <= 10; i++){ + System.out.println(vdc(i)); + } + } +} diff --git a/Task/Van-der-Corput-sequence/MATLAB/van-der-corput-sequence.m b/Task/Van-der-Corput-sequence/MATLAB/van-der-corput-sequence.m new file mode 100644 index 0000000000..02bd200f6a --- /dev/null +++ b/Task/Van-der-Corput-sequence/MATLAB/van-der-corput-sequence.m @@ -0,0 +1,6 @@ + function x = corput (n) + b = dec2bin(1:n)-'0'; % generate sequence of binary numbers from 1 to n + l = size(b,2); % get number of binary digits + w = (1:l)-l-1; % 2.^w are the weights + x = b * ( 2.^w'); % matrix times vector multiplication for + end; diff --git a/Task/Van-der-Corput-sequence/Mathematica/van-der-corput-sequence.math b/Task/Van-der-Corput-sequence/Mathematica/van-der-corput-sequence.math new file mode 100644 index 0000000000..78640db9b6 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Mathematica/van-der-corput-sequence.math @@ -0,0 +1,3 @@ +VanDerCorput[n_,base_:2]:=Table[ + FromDigits[{Reverse[IntegerDigits[k,base]],0},base], +{k,n}] diff --git a/Task/Van-der-Corput-sequence/PARI-GP/van-der-corput-sequence.pari b/Task/Van-der-Corput-sequence/PARI-GP/van-der-corput-sequence.pari new file mode 100644 index 0000000000..30108c01dd --- /dev/null +++ b/Task/Van-der-Corput-sequence/PARI-GP/van-der-corput-sequence.pari @@ -0,0 +1,3 @@ +VdC(n)=n=binary(n);sum(i=1,#n,if(n[i],1.>>(#n+1-i))); +VdC(n)=sum(i=1,#binary(n),if(bittest(n,i-1),1.>>i)); \\ Alternate approach +vector(10,n,VdC(n)) diff --git a/Task/Van-der-Corput-sequence/PL-I/van-der-corput-sequence.pli b/Task/Van-der-Corput-sequence/PL-I/van-der-corput-sequence.pli new file mode 100644 index 0000000000..c25e7a3135 --- /dev/null +++ b/Task/Van-der-Corput-sequence/PL-I/van-der-corput-sequence.pli @@ -0,0 +1,18 @@ +vdcb: procedure (an) returns (bit (31)); /* 6 July 2012 */ + declare an fixed binary (31); + declare (n, i) fixed binary (31); + declare v bit (31) varying; + + n = an; v = ''b; + do i = 1 by 1 while (n > 0); + if iand(n, 1) = 1 then v = v || '1'b; else v = v || '0'b; + n = isrl(n, 1); + end; + return (v); +end vdcb; + + declare i fixed binary (31); + + do i = 0 to 10; + put skip list ('0.' || vdcb(i)); + end; diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 new file mode 100644 index 0000000000..71a36847c8 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 @@ -0,0 +1,16 @@ +sub vdc($num, $base = 2) { + my $n = $num; + my $vdc = 0; + my $denom = 1; + while $n { + $vdc += $n mod $base / ($denom *= $base); + $n div= $base; + } + $vdc; +} + +for 2..5 -> $b { + say "Base $b"; + say (vdc($_,$b) for ^10).perl; + say ''; +} diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 new file mode 100644 index 0000000000..169d45a9ed --- /dev/null +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 @@ -0,0 +1,7 @@ +sub vdc($value, $base = 2) { + my @values := $value, { $_ div $base } ... 0; + my @denoms := $base, { $_ * $base } ... *; + [+] do for @values Z @denoms -> $v, $d { + $v mod $base / $d; + } +} diff --git a/Task/Van-der-Corput-sequence/PicoLisp/van-der-corput-sequence.l b/Task/Van-der-Corput-sequence/PicoLisp/van-der-corput-sequence.l new file mode 100644 index 0000000000..a5ed8a1248 --- /dev/null +++ b/Task/Van-der-Corput-sequence/PicoLisp/van-der-corput-sequence.l @@ -0,0 +1,14 @@ +(scl 6) + +(de vdc (N B) + (default B 2) + (let (R 0 A 1.0) + (until (=0 N) + (inc 'R (* (setq A (/ A B)) (% N B))) + (setq N (/ N B)) ) + R ) ) + +(for B (2 3 4) + (prinl "Base: " B) + (for N (range 0 9) + (prinl N ": " (round (vdc N B) 4)) ) ) diff --git a/Task/Van-der-Corput-sequence/Prolog/van-der-corput-sequence.pro b/Task/Van-der-Corput-sequence/Prolog/van-der-corput-sequence.pro new file mode 100644 index 0000000000..3881b577ac --- /dev/null +++ b/Task/Van-der-Corput-sequence/Prolog/van-der-corput-sequence.pro @@ -0,0 +1,41 @@ +% vdc( N, Base, Out ) +% Out = the Van der Corput representation of N in given Base +vdc( 0, _, [] ). +vdc( N, Base, Out ) :- + Nr is mod(N, Base), + Nq is N // Base, + vdc( Nq, Base, Tmp ), + Out = [Nr|Tmp]. + +% Writes every element of a list to stdout; no newlines +write_list( [] ). +write_list( [H|T] ) :- + write( H ), + write_list( T ). + +% Writes the Nth Van der Corput item. +print_vdc( N, Base ) :- + vdc( N, Base, Lst ), + write('0.'), + write_list( Lst ). +print_vdc( N ) :- + print_vdc( N, 2 ). + +% Prints the first N+1 elements of the Van der Corput +% sequence, each to its own line +print_some( 0, _ ) :- + write( '0.0' ). +print_some( N, Base ) :- + M is N - 1, + print_some( M, Base ), + nl, + print_vdc( N, Base ). +print_some( N ) :- + print_some( N, 2 ). + +test :- + writeln('First 10 members in base 2:'), + print_some( 9 ), + nl, + write('7th member in base 4 (stretch goal) => '), + print_vdc( 7, 4 ). diff --git a/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-1.py b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-1.py new file mode 100644 index 0000000000..6319aa82b5 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-1.py @@ -0,0 +1,7 @@ +def vdc(n, base=2): + vdc, denom = 0,1 + while n: + denom *= base + n, remainder = divmod(n, base) + vdc += remainder / denom + return vdc diff --git a/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-2.py b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-2.py new file mode 100644 index 0000000000..39e5540945 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-2.py @@ -0,0 +1,5 @@ +>>> [vdc(i) for i in range(10)] +[0, 0.5, 0.25, 0.75, 0.125, 0.625, 0.375, 0.875, 0.0625, 0.5625] +>>> [vdc(i, 3) for i in range(10)] +[0, 0.3333333333333333, 0.6666666666666666, 0.1111111111111111, 0.4444444444444444, 0.7777777777777777, 0.2222222222222222, 0.5555555555555556, 0.8888888888888888, 0.037037037037037035] +>>> diff --git a/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-3.py b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-3.py new file mode 100644 index 0000000000..b463c0d970 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-3.py @@ -0,0 +1,4 @@ +>>> from fractions import Fraction +>>> Fraction.__repr__ = lambda x: '%i/%i' % (x.numerator, x.denominator) +>>> [vdc(i, base=Fraction(2)) for i in range(10)] +[0, 1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16] diff --git a/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-4.py b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-4.py new file mode 100644 index 0000000000..387156ba48 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Python/van-der-corput-sequence-4.py @@ -0,0 +1,12 @@ +>>> for b in range(3,6): + print('\nBase', b) + print([vdc(i, base=Fraction(b)) for i in range(10)]) + +Base 3 +[0, 1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27] + +Base 4 +[0, 1/4, 1/2, 3/4, 1/16, 5/16, 9/16, 13/16, 1/8, 3/8] + +Base 5 +[0, 1/5, 2/5, 3/5, 4/5, 1/25, 6/25, 11/25, 16/25, 21/25] diff --git a/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-1.rexx b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-1.rexx new file mode 100644 index 0000000000..96344d4fa3 --- /dev/null +++ b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-1.rexx @@ -0,0 +1,18 @@ +/*REXX pgm converts any integer (or a range) to a van der Corput number in base 2*/ +/*convert any integer (or a range) to a van der Corput number in base 2*/ + +numeric digits 1000 /*handle anything the user wants.*/ +parse arg a b . /*obtain the number(s) [maybe]. */ +if a=='' then do; a=0; b=10; end /*if none specified, use defaults*/ +if b=='' then b=a /*assume a "range" of a single #.*/ + + do j=a to b /*traipse through the range. */ + _=vdC(abs(j)) /*convert abs value of integer. */ + leading=substr('-',2+sign(j)) /*if needed, leading minus sign. */ + say leading || _ /*show number (with leading - ?)*/ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────VDC [van der Corput] subroutine─────*/ +vdC: procedure; y=x2b(d2x(arg(1))) /*convert to hex, then binary. */ +if y=0 then return 0 /*zero has been converted to 0000*/ + else return '.'reverse(strip(y,"L",0)) /*heavy lifting by REXX*/ diff --git a/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx new file mode 100644 index 0000000000..faae11c32a --- /dev/null +++ b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx @@ -0,0 +1,64 @@ +/*REXX pgm converts any integer (or a range) to a van der Corput number in base 2,*/ +/* or optionaly, any other base up to base 90. */ +/*If the base is negative, the output is shown as a list. */ + +numeric digits 1000 /*handle anything the user wants.*/ +parse arg a b r . /*obtain the number(s) [maybe]. */ +if a=='' then do; a=0; b=10; end /*if none specified, use defaults*/ +if b=='' then b=a /*assume a "range" of a single #.*/ +if r=='' then r=2 /*assume a radix (base) of 2. */ +z= /*placeholder for a list of nums.*/ + + do j=a to b /*traipse through the range. */ + _=vdC(abs(j),abs(r)) /*convert abs value of integer. */ + _=substr('-',2+sign(j))_ /*if needed, leading minus sign. */ + if r>0 then say _ /*if positive base, just show it.*/ + else z=z _ /* ... else build a list. */ + end /*j*/ + +if z\=='' then say strip(z) /*if list wanted, then show it. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────VDC [van der Corput] subroutine─────*/ +vdC: return '.'reverse(base(arg(1),arg(2))) /*convert, reverse, append.*/ +/*──────────────────────────────────BASE subroutine (up to base 90)─────*/ +base: procedure; parse arg x,toB,inB /*get a number, toBase, inBase */ + +/*┌────────────────────────────────────────────────────────────────────┐ +┌─┘ Input to this subroutine (all must be positive whole numbers): └─┐ +│ │ +│ x (is required). │ +│ toBase the base to convert X to. │ +│ inBase the base X is expressed in. │ +│ │ +│ toBase or inBase can be omitted which causes the default of │ +└─┐ 10 to be used. The limits of both are: 2 ──► 90. ┌─┘ + └────────────────────────────────────────────────────────────────────┘*/ + +@abc='abcdefghijklmnopqrstuvwxyz' /*random characters, sorted. */ +@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ +@@@=0123456789||@abc||@abcU /*prefix 'em with numeric digits.*/ +@@@=@@@'<>[]{}()?~!@#$%^&*_+-=|\/;:~' /*add some special chars as well.*/ + /*spec. chars should be viewable.*/ +numeric digits 1000 /*what the hey, support biggies. */ +maxB=length(@@@) /*max base (radix) supported here*/ +parse arg x,toB,inB /*get a number, toBase, inBase */ +if toB=='' then toB=10 /*if skipped, assume default (10)*/ +if inB=='' then inB=10 /* " " " " " */ + +/*══════════════════════════════════convert X from base inB ──► base 10.*/ +#=0 + do j=1 for length(x) + _=substr(x,j,1) /*pick off a "digit" from X. */ + v=pos(_,@@@) /*get the value of this "digits".*/ + if v==0 |v>inB then call erd x,j,inB /*illegal "digit"? */ + #=#*inB+v-1 /*construct new num, dig by dig. */ + end /*j*/ + +/*══════════════════════════════════convert # from base 10 ──► base toB.*/ +y= + do while #>=toB /*deconstruct the new number (#).*/ + y=substr(@@@,(#//toB)+1,1)y /*construnct the output number. */ + #=#%toB /*... and whittle # down also. */ + end /*while*/ + +return substr(@@@,#+1,1)y diff --git a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb new file mode 100644 index 0000000000..ab99246947 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-1.rb @@ -0,0 +1,4 @@ +def vdc(n, base=2) + str = n.to_s(base).reverse + str.to_i(base).quo(base ** str.length) +end diff --git a/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb new file mode 100644 index 0000000000..e74a339a5e --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence-2.rb @@ -0,0 +1,2 @@ +> Array.new(10){|i| vdc(i,3)} +=> [Rational(0, 1), Rational(1, 3), Rational(2, 3), Rational(1, 9), Rational(4, 9), Rational(7, 9), Rational(2, 9), Rational(5, 9), Rational(8, 9), Rational(1, 27)] diff --git a/Task/Van-der-Corput-sequence/Seed7/van-der-corput-sequence.seed7 b/Task/Van-der-Corput-sequence/Seed7/van-der-corput-sequence.seed7 new file mode 100644 index 0000000000..dacb2b8596 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Seed7/van-der-corput-sequence.seed7 @@ -0,0 +1,32 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const func float: vdc (in var integer: number, in integer: base) is func + result + var float: vdc is 0.0; + local + var integer: denom is 1; + var integer: remainder is 0; + begin + while number <> 0 do + denom *:= base; + remainder := number rem base; + number := number div base; + vdc +:= flt(remainder) / flt(denom); + end while; + end func; + +const proc: main is func + local + var integer: base is 0; + var integer: number is 0; + begin + for base range 2 to 5 do + writeln; + writeln("Base " <& base); + for number range 0 to 9 do + write(vdc(number, base) digits 6 <& " "); + end for; + writeln; + end for; + end func; diff --git a/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-1.tcl b/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-1.tcl new file mode 100644 index 0000000000..f921d68d71 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-1.tcl @@ -0,0 +1,10 @@ +proc digitReverse {n {base 2}} { + set n [expr {[set neg [expr {$n < 0}]] ? -$n : $n}] + set result 0.0 + set bit [expr {1.0 / $base}] + for {} {$n > 0} {set n [expr {$n / $base}]} { + set result [expr {$result + $bit * ($n % $base)}] + set bit [expr {$bit / $base}] + } + return [expr {$neg ? -$result : $result}] +} diff --git a/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-2.tcl b/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-2.tcl new file mode 100644 index 0000000000..46388155b1 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Tcl/van-der-corput-sequence-2.tcl @@ -0,0 +1,13 @@ +# Print the first 10 terms of the Van der Corput sequence +for {set i 1} {$i <= 10} {incr i} { + puts "vanDerCorput($i) = [digitReverse $i]" +} + +# In other bases +foreach base {3 4 5} { + set seq {} + for {set i 1} {$i <= 10} {incr i} { + lappend seq [format %.5f [digitReverse $i $base]] + } + puts "${base}: [join $seq {, }]" +} diff --git a/Task/Van-der-Corput-sequence/XPL0/van-der-corput-sequence.xpl0 b/Task/Van-der-Corput-sequence/XPL0/van-der-corput-sequence.xpl0 new file mode 100644 index 0000000000..e63641b450 --- /dev/null +++ b/Task/Van-der-Corput-sequence/XPL0/van-der-corput-sequence.xpl0 @@ -0,0 +1,16 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +func real VdC(N); \Return Nth term of van der Corput sequence in base 2 +int N; +real V, U; +[V:= 0.0; U:= 0.5; +repeat N:= N/2; + if rem(0) then V:= V+U; + U:= U/2.0; +until N=0; +return V; +]; + +int N; +for N:= 0 to 10-1 do + [IntOut(0, N); RlOut(0, VdC(N)); CrLf(0)] diff --git a/Task/Variable-length-quantity/0DESCRIPTION b/Task/Variable-length-quantity/0DESCRIPTION new file mode 100644 index 0000000000..cd5b7c7620 --- /dev/null +++ b/Task/Variable-length-quantity/0DESCRIPTION @@ -0,0 +1,6 @@ +Implement some operations on [[wp:Variable-length quantity|variable-length quantities]], at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and ''vice versa''. Any variants are acceptable. + +'''Task :''' With above operations, +*convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); +*display these sequences of octets; +*convert these sequences of octets back to numbers, and check that they are equal to original numbers. diff --git a/Task/Variable-length-quantity/1META.yaml b/Task/Variable-length-quantity/1META.yaml new file mode 100644 index 0000000000..32d20151af --- /dev/null +++ b/Task/Variable-length-quantity/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Data Structures diff --git a/Task/Variable-length-quantity/Ada/variable-length-quantity.ada b/Task/Variable-length-quantity/Ada/variable-length-quantity.ada new file mode 100644 index 0000000000..7855d1a0fa --- /dev/null +++ b/Task/Variable-length-quantity/Ada/variable-length-quantity.ada @@ -0,0 +1,92 @@ +with Ada.Containers.Vectors; +with Ada.Text_IO; +with Ada.Unchecked_Conversion; + +procedure VLQ is + + package Nat_IO is new Ada.Text_IO.Integer_IO (Natural); + + type Byte is mod 2**8; + + package Byte_IO is new Ada.Text_IO.Modular_IO (Byte); + + type Int7 is mod 2**7; + + package Int7_IO is new Ada.Text_IO.Modular_IO (Int7); + + type VLQ_Octet is record + Value : Int7 := 0; + Next : Boolean := True; + end record; + pragma Pack (VLQ_Octet); + for VLQ_Octet'Size use 8; + + function VLQ_To_Byte is new Ada.Unchecked_Conversion (VLQ_Octet, Byte); + function Byte_To_VLQ is new Ada.Unchecked_Conversion (Byte, VLQ_Octet); + + package VLQ_Vectors is new Ada.Containers.Vectors (Natural, VLQ_Octet); + + procedure Hex_Print (Position : in VLQ_Vectors.Cursor) is + Value : Byte := VLQ_To_Byte (VLQ_Vectors.Element (Position)); + begin + Ada.Text_IO.Put (':'); + Byte_IO.Put (Item => Value, Width => 6, Base => 16); + end Hex_Print; + + procedure Print (X : VLQ_Vectors.Vector) is + begin + X.Iterate (Hex_Print'Access); + Ada.Text_IO.New_Line; + end Print; + + function To_VLQ (From : Natural) return VLQ_Vectors.Vector is + Result : VLQ_Vectors.Vector; + Current : Natural := From; + Element : VLQ_Octet; + begin + loop + Element.Value := Int7 (Current mod 2**7); + Result.Prepend (Element); + Current := Current / 2**7; + exit when Current = 0; + end loop; + Element := Result.Last_Element; + Element.Next := False; + VLQ_Vectors.Replace_Element (Result, Result.Last, Element); + return Result; + end To_VLQ; + + function To_Int (From : VLQ_Vectors.Vector) return Natural is + use type VLQ_Vectors.Cursor; + Result : Natural := 0; + Iterator : VLQ_Vectors.Cursor := From.First; + begin + while Iterator /= VLQ_Vectors.No_Element loop + Result := Result * 2**7; + Result := Result + Natural(VLQ_Vectors.Element (Iterator).Value); + VLQ_Vectors.Next (Iterator); + end loop; + return Result; + end To_Int; + + Test : VLQ_Vectors.Vector; +begin + Test := To_VLQ (16#7f#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#4000#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#0#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#3FFFFE#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#1FFFFF#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#200000#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); +end VLQ; diff --git a/Task/Variable-length-quantity/C/variable-length-quantity-1.c b/Task/Variable-length-quantity/C/variable-length-quantity-1.c new file mode 100644 index 0000000000..b6a38097e8 --- /dev/null +++ b/Task/Variable-length-quantity/C/variable-length-quantity-1.c @@ -0,0 +1,43 @@ +#include +#include + +void to_seq(uint64_t x, uint8_t *out) +{ + int i, j; + for (i = 9; i > 0; i--) { + if (x & 127ULL << i * 7) break; + } + for (j = 0; j <= i; j++) + out[j] = ((x >> ((i - j) * 7)) & 127) | 128; + + out[i] ^= 128; +} + +uint64_t from_seq(uint8_t *in) +{ + uint64_t r = 0; + + do { + r = (r << 7) | (uint64_t)(*in & 127); + } while (*in++ & 128); + + return r; +} + +int main() +{ + uint8_t s[10]; + uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL}; + + int i, j; + for (j = 0; j < sizeof(x)/8; j++) { + to_seq(x[j], s); + printf("seq from %llx: [ ", x[j]); + + i = 0; + do { printf("%02x ", s[i]); } while ((s[i++] & 128)); + printf("] back: %llx\n", from_seq(s)); + } + + return 0; +} diff --git a/Task/Variable-length-quantity/C/variable-length-quantity-2.c b/Task/Variable-length-quantity/C/variable-length-quantity-2.c new file mode 100644 index 0000000000..70658aa40e --- /dev/null +++ b/Task/Variable-length-quantity/C/variable-length-quantity-2.c @@ -0,0 +1,7 @@ +seq from 7f: [ 7f ] back: 7f +seq from 4000: [ 81 80 00 ] back: 4000 +seq from 0: [ 00 ] back: 0 +seq from 3ffffe: [ 81 ff ff 7e ] back: 3ffffe +seq from 1fffff: [ ff ff 7f ] back: 1fffff +seq from 200000: [ 81 80 80 00 ] back: 200000 +seq from 3311a1234df31413: [ b3 88 e8 a4 b4 ef cc a8 13 ] back: 3311a1234df31413 diff --git a/Task/Variable-length-quantity/D/variable-length-quantity.d b/Task/Variable-length-quantity/D/variable-length-quantity.d new file mode 100644 index 0000000000..0f778dfbcd --- /dev/null +++ b/Task/Variable-length-quantity/D/variable-length-quantity.d @@ -0,0 +1,85 @@ +import std.stdio, std.string, std.file, std.algorithm; + +/// Variable length quantity (unsigned long, max 63-bit). +struct VLQ { + ulong value; + + // This allows VLQ to work like an ulong. + alias value this; + + uint extract(in ubyte[] v) pure + in { + assert(v.length > 0); + } body { + immutable limit = min(v.length - 1, 8); + ulong t = 0; + size_t idx = 0; + while ((idx < limit) && ((v[idx] & 0x80) > 0)) + t = (t << 7) | (0x7f & v[idx++]); + if (idx > limit) + throw new Exception( + "Too large for ulong or invalid format."); + else + value = (t << 7) | v[idx]; + return idx + 1; + } + + VLQ from(in ubyte[] v) pure { + extract(v); + return this; + } + + @property ubyte[] toVLQ() const pure { + ubyte[] v = [0x7f & value]; + for (ulong k = value >>> 7; k > 0; k >>>= 7) + v ~= (k & 0x7f) | 0x80; + if (v.length > 9) + throw new Exception("Too large value."); + v.reverse(); + return v; + } + + static ulong[] split(in ubyte[] b) pure { + ulong[] res; + VLQ v; + for (size_t i = 0; i < b.length; ) { + i += v.extract(b[i .. $]); + res ~= v.value; + } + return res; + } + + string toString() const /*pure nothrow*/ { + return format("(%(%02X:%))", this.toVLQ); + } +} + + +void main() { // VLQ demo code. + VLQ a = VLQ(0x7f), + b = VLQ(0x4000), + c; + writefln("a:%8x = %s\nb:%8x = %s\nc:%8x = %s", + a.value, a, b.value, b, c.value, c); + + // Some operations. + c = (a + 1) * b; + a = c - 1; + b = VLQ().from(a.toVLQ); + a <<= 1; + + // Convert ulong to octet sequence. + writefln("\na:%8x = %s\nb:%8x = %s\nc:%8x = %s", + a.value, a, b.value, b, c.value, c); + + // Write them to a binary file. + std.file.write("vlqtest.bin", a.toVLQ ~ b.toVLQ ~ c.toVLQ); + + // Read them back. + const buf = cast(ubyte[])std.file.read("vlqtest.bin"); + writefln("\nFile length: %d bytes.", buf.length); + + // Convert octet sequence to ulongs. + foreach (immutable i, immutable v; VLQ.split(buf)) + writefln("%d:%8x = %s", i + 1, v, VLQ(v)); +} diff --git a/Task/Variable-length-quantity/Euphoria/variable-length-quantity.euphoria b/Task/Variable-length-quantity/Euphoria/variable-length-quantity.euphoria new file mode 100644 index 0000000000..3a8c22f055 --- /dev/null +++ b/Task/Variable-length-quantity/Euphoria/variable-length-quantity.euphoria @@ -0,0 +1,41 @@ +function vlq_encode(integer n) + sequence s + s = {} + while n > 0 do + s = prepend(s, #80 * (length(s) > 0) + and_bits(n, #7F)) + n = floor(n / #80) + end while + if length(s) = 0 then + s = {0} + end if + return s +end function + +function vlq_decode(sequence s) + integer n + n = 0 + for i = 1 to length(s) do + n *= #80 + n += and_bits(s[i], #7F) + if not and_bits(s[i], #80) then + exit + end if + end for + return n +end function + +function svlg(sequence s) + sequence out + out = "" + for i = 1 to length(s) do + out &= sprintf("#%02x:", {s[i]}) + end for + return out[1..$-1] +end function + +constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 } +sequence s +for i = 1 to length(testNumbers) do + s = vlq_encode(testNumbers[i]) + printf(1, "#%02x -> %s -> #%02x\n", {testNumbers[i], svlg(s), vlq_decode(s)}) +end for diff --git a/Task/Variable-length-quantity/Go/variable-length-quantity.go b/Task/Variable-length-quantity/Go/variable-length-quantity.go new file mode 100644 index 0000000000..6c1e65ab56 --- /dev/null +++ b/Task/Variable-length-quantity/Go/variable-length-quantity.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + "encoding/binary" +) + +func main() { + buf := make([]byte, binary.MaxVarintLen64) + for _, x := range []int64{0x200000, 0x1fffff} { + v := buf[:binary.PutVarint(buf, x)] + fmt.Printf("%d encodes into %d bytes: %x\n", x, len(v), v) + x, _ = binary.Varint(v) + fmt.Println(x, "decoded") + } +} diff --git a/Task/Variable-length-quantity/Groovy/variable-length-quantity-1.groovy b/Task/Variable-length-quantity/Groovy/variable-length-quantity-1.groovy new file mode 100644 index 0000000000..06d7957ad8 --- /dev/null +++ b/Task/Variable-length-quantity/Groovy/variable-length-quantity-1.groovy @@ -0,0 +1,16 @@ +final RADIX = 7 +final MASK = 2**RADIX - 1 + +def octetify = { n -> + def octets = [] + for (def i = n; i != 0; i >>>= RADIX) { + octets << ((byte)((i & MASK) + (octets.empty ? 0 : MASK + 1))) + } + octets.reverse() +} + +def deoctetify = { octets -> + octets.inject(0) { long n, octet -> + (n << RADIX) + ((int)(octet) & MASK) + } +} diff --git a/Task/Variable-length-quantity/Groovy/variable-length-quantity-2.groovy b/Task/Variable-length-quantity/Groovy/variable-length-quantity-2.groovy new file mode 100644 index 0000000000..69bae58a95 --- /dev/null +++ b/Task/Variable-length-quantity/Groovy/variable-length-quantity-2.groovy @@ -0,0 +1,8 @@ +def testNumbers = [ 0x200000, 0x1fffff, 1, 127, 128, 589723405834L ] + +testNumbers.each { a -> + def octets = octetify(a) + octets.each { printf "0x%02x ", it }; println () + def a1 = deoctetify(octets) + assert a1 == a +} diff --git a/Task/Variable-length-quantity/Icon/variable-length-quantity.icon b/Task/Variable-length-quantity/Icon/variable-length-quantity.icon new file mode 100644 index 0000000000..52482c4cc9 --- /dev/null +++ b/Task/Variable-length-quantity/Icon/variable-length-quantity.icon @@ -0,0 +1,30 @@ +procedure main() +every i := 2097152 | 2097151 | 1 | 127 | 128 | 589723405834 | 165 | 256 do + write(image(i)," = ",string2hex(v := uint2vlq(i))," = ",vlq2uint(v)) +end + +procedure vlq2uint(s) #: decode a variable length quantity + if *s > 0 then { + i := 0 + s ? while h := ord(move(1)) do { + if (pos(0) & h > 128) | (not pos(0) & h < 128) then fail + i := 128 * i + h % 128 + } + return i + } +end + +procedure uint2vlq(i,c) #: encode a whole number as a variable length quantity + if "integer" == type(-1 < i) then + return if i = 0 then + char((/c := 0)) | "" + else + uint2vlq(i/128,1) || char((i % 128) + ((/c := 0) | 128) ) +end + +procedure string2hex(s) #: convert a string to hex + h := "" + every i := ord(!s) do + h ||:= "0123456789abcdef"[i/16+1] || "0123456789abcdef"[i%16+1] + return h +end diff --git a/Task/Variable-length-quantity/J/variable-length-quantity-1.j b/Task/Variable-length-quantity/J/variable-length-quantity-1.j new file mode 100644 index 0000000000..cf8fab439a --- /dev/null +++ b/Task/Variable-length-quantity/J/variable-length-quantity-1.j @@ -0,0 +1,5 @@ +N=: 128x +v2i=: (N&| N&#./.~ [: +/\ _1 |. N&>)@i.~&a. +i2v=: a. {~ [:;}.@(N+//.@,:N&#.inv)&.> +ifv=: v2i :. i2v +vfi=: i2v :. v2i diff --git a/Task/Variable-length-quantity/J/variable-length-quantity-2.j b/Task/Variable-length-quantity/J/variable-length-quantity-2.j new file mode 100644 index 0000000000..d86f7b0b93 --- /dev/null +++ b/Task/Variable-length-quantity/J/variable-length-quantity-2.j @@ -0,0 +1,6 @@ + require'convert' + numbers=: 16b7f 16b4000 0 16b3ffffe 16b1fffff 200000 + av vlq=: vfi numbers +127 129 128 0 0 129 255 255 126 255 255 127 140 154 64 + av (vfi 1 2 3 4 5 6) +&.ifv vlq +129 0 129 128 2 3 130 128 128 2 129 128 128 4 140 154 70 diff --git a/Task/Variable-length-quantity/Java/variable-length-quantity.java b/Task/Variable-length-quantity/Java/variable-length-quantity.java new file mode 100644 index 0000000000..e20634ddc3 --- /dev/null +++ b/Task/Variable-length-quantity/Java/variable-length-quantity.java @@ -0,0 +1,59 @@ +public class VLQCode +{ + public static byte[] encode(long n) + { + int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); + int numBytes = (numRelevantBits + 6) / 7; + if (numBytes == 0) + numBytes = 1; + byte[] output = new byte[numBytes]; + for (int i = numBytes - 1; i >= 0; i--) + { + int curByte = (int)(n & 0x7F); + if (i != (numBytes - 1)) + curByte |= 0x80; + output[i] = (byte)curByte; + n >>>= 7; + } + return output; + } + + public static long decode(byte[] b) + { + long n = 0; + for (int i = 0; i < b.length; i++) + { + int curByte = b[i] & 0xFF; + n = (n << 7) | (curByte & 0x7F); + if ((curByte & 0x80) == 0) + break; + } + return n; + } + + public static String byteArrayToString(byte[] b) + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < b.length; i++) + { + if (i > 0) + sb.append(", "); + String s = Integer.toHexString(b[i] & 0xFF); + if (s.length() < 2) + s = "0" + s; + sb.append(s); + } + return sb.toString(); + } + + public static void main(String[] args) + { + long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L }; + for (long n : testNumbers) + { + byte[] encoded = encode(n); + long decoded = decode(encoded); + System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL")); + } + } +} diff --git a/Task/Variable-length-quantity/Mathematica/variable-length-quantity.math b/Task/Variable-length-quantity/Mathematica/variable-length-quantity.math new file mode 100644 index 0000000000..aeb8dfb749 --- /dev/null +++ b/Task/Variable-length-quantity/Mathematica/variable-length-quantity.math @@ -0,0 +1,10 @@ +toOctets[n_Integer] := + StringJoin @@@ + Partition[ + PadLeft[Characters@IntegerString[n, 16], + 2 Ceiling[Plus @@ DigitCount[n, 16]/2], {"0"}], 2] + +fromOctets[octets_List] := FromDigits[StringJoin @@ octets, 16] + +Grid[{#, toOctets@#, fromOctets[toOctets@#]} & /@ {16^^3ffffe, + 16^^1fffff, 16^^200000}] diff --git a/Task/Variable-length-quantity/OCaml/variable-length-quantity.ocaml b/Task/Variable-length-quantity/OCaml/variable-length-quantity.ocaml new file mode 100644 index 0000000000..36a2dc8de3 --- /dev/null +++ b/Task/Variable-length-quantity/OCaml/variable-length-quantity.ocaml @@ -0,0 +1,24 @@ +let to_vlq n = + let a, b = n lsr 7, n land 0x7F in + let rec aux n acc = + let x = (n land 0x7F) lor 0x80 + and xs = n lsr 7 in + if xs > 0 + then aux xs (x::acc) + else x::acc + in + aux a [b] + +let to_num = List.fold_left (fun n x -> n lsl 7 + (x land 0x7F)) 0 + +let v_rep n = + Printf.printf "%d ->" n; + let seq = to_vlq n in + List.iter (Printf.printf " 0x%02X") seq; + let num = to_num seq in + Printf.printf "-> %d\n%!" num; + assert (n = num) + +let _ = + v_rep 0x200000; + v_rep 0x1FFFFF diff --git a/Task/Variable-length-quantity/PL-I/variable-length-quantity.pli b/Task/Variable-length-quantity/PL-I/variable-length-quantity.pli new file mode 100644 index 0000000000..f7b5914e41 --- /dev/null +++ b/Task/Variable-length-quantity/PL-I/variable-length-quantity.pli @@ -0,0 +1,28 @@ +test: procedure options(main); + declare s character (20) varying; + declare c character (1); + declare v fixed binary (31); + declare (i, k) fixed binary; + + get edit (s) (L); + s = trim (s); + v = 0; + do i = 1 to length(s); + c = substr(s, i, 1); + k = index('0123456789abcdef', c); + if k > 0 then v = v*16 + k - 1; + end; + put skip data (s, v); + + /* Convert back to hex */ + declare hex character(16) initial ('0123456789abcdef'); + declare hs character (20) initial (''); + declare d fixed binary; + + do i = length(hs) to 1 by -1 until (v = 0); + d = mod(v, 16) + 1; + substr(hs, i, 1) = substr(hex, d, 1); + v = v/16; + end; + put skip list (hs); +end test; diff --git a/Task/Variable-length-quantity/Perl-6/variable-length-quantity.pl6 b/Task/Variable-length-quantity/Perl-6/variable-length-quantity.pl6 new file mode 100644 index 0000000000..bc6ca6f9be --- /dev/null +++ b/Task/Variable-length-quantity/Perl-6/variable-length-quantity.pl6 @@ -0,0 +1,32 @@ +sub vlq_encode ($number is copy) { + my $string = ''; + my $t = 0x7F +& $number; + $number +>= 7; + $string = $t.chr ~ $string; + while ($number) { + $t = 0x7F +& $number; + $string = (0x80 +| $t).chr ~ $string; + $number +>= 7; + } + return $string; +} + +sub vlq_decode ($string is copy) { + my $number = '0b'; + for $string.ords -> $oct { + $number ~= ($oct +& 0x7F).fmt("%07b"); + } + return :2($number); +} + +#test encoding and decoding +for ( + 0, 0xa, 123, 254, 255, 256, + 257, 65534, 65535, 65536, 65537, 0x1fffff, + 0x200000 + ) -> $testcase { + my $encoded = vlq_encode($testcase); + printf "%8s %12s %8s\n", $testcase, + ( join ':', $encoded.ords>>.fmt("%02X") ), + vlq_decode($encoded); +} diff --git a/Task/Variable-length-quantity/Perl/variable-length-quantity.pl b/Task/Variable-length-quantity/Perl/variable-length-quantity.pl new file mode 100644 index 0000000000..42b8497f26 --- /dev/null +++ b/Task/Variable-length-quantity/Perl/variable-length-quantity.pl @@ -0,0 +1,30 @@ +use warnings; +use strict; + +for my $testcase ( + 0, 0xa, 123, 254, 255, 256, + 257, 65534, 65535, 65536, 65537, 0x1fffff, + 0x200000 + ) +{ + my @vlq = vlq_encode($testcase); + printf "%8s %12s %8s\n", $testcase, ( join ':', @vlq ), vlq_decode(@vlq); +} + +sub vlq_encode { + my @vlq; + my $binary = sprintf "%s%b", 0 x 7, shift; + $binary =~ s/(.{7})$//; + @vlq = ( unpack 'H2', ( pack 'B8', '0' . $1 ) ); + while ( 0 + $binary ) { + $binary =~ s/(.{7})$//; + unshift @vlq, ( unpack 'H2', pack 'B8', '1' . $1 ); + } + return @vlq; +} + +sub vlq_decode { + my $num; + $num .= sprintf "%07b", hex(shift @_) & 0x7f while @_; + return oct '0b' . $num; +} diff --git a/Task/Variable-length-quantity/PicoLisp/variable-length-quantity.l b/Task/Variable-length-quantity/PicoLisp/variable-length-quantity.l new file mode 100644 index 0000000000..814d386569 --- /dev/null +++ b/Task/Variable-length-quantity/PicoLisp/variable-length-quantity.l @@ -0,0 +1,14 @@ +(de numToVlq (Num) + (let Res (cons (& Num 127)) + (while (gt0 (setq Num (>> 7 Num))) + (push 'Res (| 128 (& Num 127))) ) + Res ) ) + +(de vlqToNum (Vlq) + (let Res 0 + (for N Vlq + (setq Res (| (>> -7 Res) (& N 127))) ) ) ) + +(for Num (0 15 16 127 128 255 2097151 2097152) + (let Vlq (numToVlq Num) + (tab (12 12 12) Num (glue ":" (mapcar hex Vlq)) (vlqToNum Vlq)) ) ) diff --git a/Task/Variable-length-quantity/Python/variable-length-quantity-1.py b/Task/Variable-length-quantity/Python/variable-length-quantity-1.py new file mode 100644 index 0000000000..938967bb45 --- /dev/null +++ b/Task/Variable-length-quantity/Python/variable-length-quantity-1.py @@ -0,0 +1,23 @@ +def tobits(n, _group=8, _sep='_', _pad=False): + 'Express n as binary bits with separator' + bits = '{0:b}'.format(n)[::-1] + if _pad: + bits = '{0:0{1}b}'.format(n, + ((_group+len(bits)-1)//_group)*_group)[::-1] + answer = _sep.join(bits[i:i+_group] + for i in range(0, len(bits), _group))[::-1] + answer = '0'*(len(_sep)-1) + answer + else: + answer = _sep.join(bits[i:i+_group] + for i in range(0, len(bits), _group))[::-1] + return answer + +def tovlq(n): + return tobits(n, _group=7, _sep='1_', _pad=True) + +def toint(vlq): + return int(''.join(vlq.split('_1')), 2) + +def vlqsend(vlq): + for i, byte in enumerate(vlq.split('_')[::-1]): + print('Sent byte {0:3}: {1:#04x}'.format(i, int(byte,2))) diff --git a/Task/Variable-length-quantity/Python/variable-length-quantity-2.py b/Task/Variable-length-quantity/Python/variable-length-quantity-2.py new file mode 100644 index 0000000000..b1eddf2df0 --- /dev/null +++ b/Task/Variable-length-quantity/Python/variable-length-quantity-2.py @@ -0,0 +1,24 @@ +>>> for n in (254, 255, 256, 257, -2+(1<<16), -1+(1<<16), 1<<16, 1+(1<<16), 0x200000, 0x1fffff ): + print('int: %7i bin: %26s vlq: %35s vlq->int: %7i' % (n, tobits(n,_pad=True), tovlq(n), toint(tovlq(n)))) + + +int: 254 bin: 11111110 vlq: 00000001_11111110 vlq->int: 254 +int: 255 bin: 11111111 vlq: 00000001_11111111 vlq->int: 255 +int: 256 bin: 00000001_00000000 vlq: 00000010_10000000 vlq->int: 256 +int: 257 bin: 00000001_00000001 vlq: 00000010_10000001 vlq->int: 257 +int: 65534 bin: 11111111_11111110 vlq: 00000011_11111111_11111110 vlq->int: 65534 +int: 65535 bin: 11111111_11111111 vlq: 00000011_11111111_11111111 vlq->int: 65535 +int: 65536 bin: 00000001_00000000_00000000 vlq: 00000100_10000000_10000000 vlq->int: 65536 +int: 65537 bin: 00000001_00000000_00000001 vlq: 00000100_10000000_10000001 vlq->int: 65537 +int: 2097152 bin: 00100000_00000000_00000000 vlq: 00000001_10000000_10000000_10000000 vlq->int: 2097152 +int: 2097151 bin: 00011111_11111111_11111111 vlq: 01111111_11111111_11111111 vlq->int: 2097151 +>>> vlqsend(tovlq(0x200000)) +Sent byte 0: 0x80 +Sent byte 1: 0x80 +Sent byte 2: 0x80 +Sent byte 3: 0x01 +>>> vlqsend(tovlq(0x1fffff)) +Sent byte 0: 0xff +Sent byte 1: 0xff +Sent byte 2: 0x7f +>>> diff --git a/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx b/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx new file mode 100644 index 0000000000..3bdc992404 --- /dev/null +++ b/Task/Variable-length-quantity/REXX/variable-length-quantity.rexx @@ -0,0 +1,30 @@ +/*REXX program to test displaying of octets. */ + +num1=x2d(200000) ; say 'number1='num1 ' [in hex='d2x(num1)"]" +num2=x2d(1fffff) ; say 'number2='num2 ' [in hex='d2x(num2)"]" +num3=2097172 ; say 'number3='num3 ' [in hex='d2x(num3)"]" +num4=2097151 ; say 'number4='num4 ' [in hex='d2x(num4)"]" + say +onum1=octet(num1) ; say 'number1 octet='onum1 +onum2=octet(num2) ; say 'number2 octet='onum2 +onum3=octet(num3) ; say 'number3 octet='onum3 +onum4=octet(num4) ; say 'number4 octet='onum4 + say +bnum1=x2d(space(onum1,0)) ; say 'number1='bnum1 +bnum2=x2d(space(onum2,0)) ; say 'number2='bnum2 +bnum3=x2d(space(onum3,0)) ; say 'number3='bnum3 +bnum4=x2d(space(onum4,0)) ; say 'number4='bnum4 + say +if num1==bnum1 &, + num2==bnum2 &, + num3==bnum3 &, + num4==bnum4 then say 'numbers are OK' + else say 'trouble in River City' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────OCTET subroutine────────────────────*/ +octet: procedure; parse arg a,_; x=d2x(a) /*convert A to hex octet.*/ + + do j=length(x) by -2 to 1 /*process little end first.*/ + _=substr(x,j-1,2,0) _ /*pad odd hexchars with an 0 on left*/ + end /*j*/ +return _ diff --git a/Task/Variable-length-quantity/Ruby/variable-length-quantity.rb b/Task/Variable-length-quantity/Ruby/variable-length-quantity.rb new file mode 100644 index 0000000000..bf6c48e258 --- /dev/null +++ b/Task/Variable-length-quantity/Ruby/variable-length-quantity.rb @@ -0,0 +1,10 @@ +[2097152, 2097151].each do |i| + # Encode i => BER + ber = [i].pack("w") + hex = ber.unpack("C*").collect {|c| "%02x" % c}.join(":") + printf "%s => %s\n", i, hex + + # Decode BER => j + j = ber.unpack("w").first + i == j or fail "BER not preserve integer" +end diff --git a/Task/Variable-length-quantity/Scala/variable-length-quantity.scala b/Task/Variable-length-quantity/Scala/variable-length-quantity.scala new file mode 100644 index 0000000000..14776b5998 --- /dev/null +++ b/Task/Variable-length-quantity/Scala/variable-length-quantity.scala @@ -0,0 +1,27 @@ +object VlqCode { + def encode(x:Long)={ + val result=scala.collection.mutable.Stack[Byte]() + result push (x&0x7f).toByte + var l = x >>> 7 + while(l>0){ + result push ((l&0x7f)|0x80).toByte + l >>>= 7 + } + result.toArray + } + + def decode(a:Array[Byte])=a.foldLeft(0L)((r, b) => r<<7|b&0x7f) + + def toString(a:Array[Byte])=a map("%02x".format(_)) mkString("[", ", ", "]") + + def test(x:Long)={ + val enc=encode(x) + println("0x%x => %s => 0x%x".format(x, toString(enc), decode(enc))) + } + + def main(args: Array[String]): Unit = { + val xs=Seq(0, 0x7f, 0x80, 0x2000, 0x3fff, 0x4000, 0x1FFFFF, 0x200000, 0x8000000, + 0xFFFFFFF, 0xFFFFFFFFL, 0x842FFFFFFFFL, 0x0FFFFFFFFFFFFFFFL) + xs foreach test + } +} diff --git a/Task/Variable-length-quantity/Seed7/variable-length-quantity.seed7 b/Task/Variable-length-quantity/Seed7/variable-length-quantity.seed7 new file mode 100644 index 0000000000..f1e5b75571 --- /dev/null +++ b/Task/Variable-length-quantity/Seed7/variable-length-quantity.seed7 @@ -0,0 +1,47 @@ +$ include "seed7_05.s7i"; + include "bigint.s7i"; + +const func string: toSequence (in var bigInteger: number) is func + result + var string: sequence is ""; + begin + sequence := str(chr(ord(number mod 128_))); + number >>:= 7; + while number <> 0_ do + sequence := str(chr(ord(number mod 128_) + 128)) & sequence; + number >>:= 7; + end while; + end func; + +const func bigInteger: fromSequence (in string: sequence) is func + result + var bigInteger: number is 0_; + local + var integer: index is 1; + begin + while ord(sequence[index]) >= 128 do + number <<:= 7; + number +:= bigInteger conv (ord(sequence[index]) - 128); + incr(index); + end while; + number <<:= 7; + number +:= bigInteger conv ord(sequence[index]); + end func; + +const proc: main is func + local + const array bigInteger: testValues is [] ( + 0_, 10_, 123_, 254_, 255_, 256_, 257_, 65534_, 65535_, 65536_, 65537_, 2097151_, 2097152_); + var string: sequence is ""; + var bigInteger: testValue is 0_; + var char: element is ' '; + begin + for testValue range testValues do + sequence := toSequence(testValue); + write("sequence from " <& testValue <& ": [ "); + for element range sequence do + write(ord(element) radix 16 lpad0 2 <& " "); + end for; + writeln("] back: " <& fromSequence(sequence)); + end for; + end func; diff --git a/Task/Variable-length-quantity/Tcl/variable-length-quantity-1.tcl b/Task/Variable-length-quantity/Tcl/variable-length-quantity-1.tcl new file mode 100644 index 0000000000..30fede2aaf --- /dev/null +++ b/Task/Variable-length-quantity/Tcl/variable-length-quantity-1.tcl @@ -0,0 +1,23 @@ +package require Tcl 8.5 + +proc vlqEncode number { + if {$number < 0} {error "negative not supported"} + while 1 { + lappend digits [expr {$number & 0x7f}] + if {[set number [expr {$number >> 7}]] == 0} break + } + set out [format %c [lindex $digits 0]] + foreach digit [lrange $digits 1 end] { + set out [format %c%s [expr {0x80+$digit}] $out] + } + return $out +} +proc vlqDecode chars { + set n 0 + foreach c [split $chars ""] { + scan $c %c c + set n [expr {($n<<7) | ($c&0x7f)}] + if {!($c&0x80)} break + } + return $n +} diff --git a/Task/Variable-length-quantity/Tcl/variable-length-quantity-2.tcl b/Task/Variable-length-quantity/Tcl/variable-length-quantity-2.tcl new file mode 100644 index 0000000000..934bc613d5 --- /dev/null +++ b/Task/Variable-length-quantity/Tcl/variable-length-quantity-2.tcl @@ -0,0 +1,23 @@ +proc numtohex {num} { + binary scan [string trimleft [binary format W $num] \0] H* hexEncoded + regsub -all "..(?=.)" $hexEncoded "&:" +} +proc strtohex {string} { + binary scan $string H* hexEncoded + regsub -all "..(?=.)" $hexEncoded "&:" +} +foreach testcase { + 123 + 254 255 256 257 + 65534 65535 65536 65537 + 2097152 2097151 + 12345678901234566789 +} { + set encoded [vlqEncode $testcase] + binary scan $encoded H* hexEncoded + regsub -all {..(?=.)} $hexEncoded &: hexEncoded + set decoded [vlqDecode $encoded] + puts "$testcase ([numtohex $testcase]) ==>\ + [strtohex $encoded] ([string length $encoded] bytes) ==>\ + $decoded" +} diff --git a/Task/Variable-size-Get/0DESCRIPTION b/Task/Variable-size-Get/0DESCRIPTION new file mode 100644 index 0000000000..2235071179 --- /dev/null +++ b/Task/Variable-size-Get/0DESCRIPTION @@ -0,0 +1,3 @@ +Demonstrate how to get the size of a variable. + +See also: [[Host introspection]] diff --git a/Task/Variable-size-Get/1META.yaml b/Task/Variable-size-Get/1META.yaml new file mode 100644 index 0000000000..a1563fda10 --- /dev/null +++ b/Task/Variable-size-Get/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Type System diff --git a/Task/Variable-size-Get/ALGOL-68/variable-size-get.alg b/Task/Variable-size-Get/ALGOL-68/variable-size-get.alg new file mode 100644 index 0000000000..ae98286431 --- /dev/null +++ b/Task/Variable-size-Get/ALGOL-68/variable-size-get.alg @@ -0,0 +1,7 @@ +INT i; BYTES b; # typically INT and BYTES are the same size # +STRING s:="DCLXVI", [666]CHAR c; +print(( + "sizeof INT i =",bytes width, new line, + "UPB STRING s =",UPB s, new line, + "UPB []CHAR c =",UPB c, new line +)) diff --git a/Task/Variable-size-Get/Ada/variable-size-get.ada b/Task/Variable-size-Get/Ada/variable-size-get.ada new file mode 100644 index 0000000000..2e6ba329e9 --- /dev/null +++ b/Task/Variable-size-Get/Ada/variable-size-get.ada @@ -0,0 +1,2 @@ +Int_Bits : constant Integer := Integer'size; +Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element diff --git a/Task/Variable-size-Get/AutoHotkey/variable-size-get.ahk b/Task/Variable-size-Get/AutoHotkey/variable-size-get.ahk new file mode 100644 index 0000000000..a555a008b8 --- /dev/null +++ b/Task/Variable-size-Get/AutoHotkey/variable-size-get.ahk @@ -0,0 +1,2 @@ +VarSetCapacity(Var, 10240000) ; allocate 10 megabytes +MsgBox % size := VarSetCapacity(Var) ; 10240000 diff --git a/Task/Variable-size-Get/BASIC/variable-size-get-1.basic b/Task/Variable-size-Get/BASIC/variable-size-get-1.basic new file mode 100644 index 0000000000..02459967a7 --- /dev/null +++ b/Task/Variable-size-Get/BASIC/variable-size-get-1.basic @@ -0,0 +1,2 @@ +10 REM this only works with strings +20 PRINT LEN(variable$) diff --git a/Task/Variable-size-Get/BASIC/variable-size-get-2.basic b/Task/Variable-size-Get/BASIC/variable-size-get-2.basic new file mode 100644 index 0000000000..ada22090d5 --- /dev/null +++ b/Task/Variable-size-Get/BASIC/variable-size-get-2.basic @@ -0,0 +1,2 @@ +DIM a AS INTEGER, b AS LONG, c AS SINGLE, d AS DOUBLE, e AS STRING +PRINT LEN(a), LEN(b), LEN(c), LEN(d), LEN(e) diff --git a/Task/Variable-size-Get/BBC-BASIC/variable-size-get.bbc b/Task/Variable-size-Get/BBC-BASIC/variable-size-get.bbc new file mode 100644 index 0000000000..dd604ee01a --- /dev/null +++ b/Task/Variable-size-Get/BBC-BASIC/variable-size-get.bbc @@ -0,0 +1,11 @@ + DIM bstruct{b&} + DIM istruct{i%} + DIM fstruct{f} + DIM dstruct{d#} + DIM sstruct{s$} + + PRINT "Size of b& is ";DIM(bstruct{}) + PRINT "Size of i% is ";DIM(istruct{}) + PRINT "Size of f is ";DIM(fstruct{}) + PRINT "Size of d# is ";DIM(dstruct{}) + PRINT "Size of s$ is ";DIM(sstruct{}) diff --git a/Task/Variable-size-Get/Babel/variable-size-get-1.pb b/Task/Variable-size-Get/Babel/variable-size-get-1.pb new file mode 100644 index 0000000000..19fa982d5a --- /dev/null +++ b/Task/Variable-size-Get/Babel/variable-size-get-1.pb @@ -0,0 +1,20 @@ +main: + { (1 2 (3 4) 5 6) + dup mu disp + dup nva disp + dup npt disp + dup nlf disp + dup nin disp + dup nhref disp + dup nhword disp } + +disp! : { %d cr << } + +Output: +38 +6 +14 +6 +7 +1 +4 diff --git a/Task/Variable-size-Get/Babel/variable-size-get-2.pb b/Task/Variable-size-Get/Babel/variable-size-get-2.pb new file mode 100644 index 0000000000..90f5ee7b67 --- /dev/null +++ b/Task/Variable-size-Get/Babel/variable-size-get-2.pb @@ -0,0 +1,3 @@ +main : { (1 2 (3 4) 5 6) unload size %d << } +Output: +38 diff --git a/Task/Variable-size-Get/C++/variable-size-get-1.cpp b/Task/Variable-size-Get/C++/variable-size-get-1.cpp new file mode 100644 index 0000000000..184d9e5e5d --- /dev/null +++ b/Task/Variable-size-Get/C++/variable-size-get-1.cpp @@ -0,0 +1,2 @@ +#include +std::size_t intsize = sizeof(int); diff --git a/Task/Variable-size-Get/C++/variable-size-get-2.cpp b/Task/Variable-size-Get/C++/variable-size-get-2.cpp new file mode 100644 index 0000000000..5d61a4024b --- /dev/null +++ b/Task/Variable-size-Get/C++/variable-size-get-2.cpp @@ -0,0 +1,3 @@ +#include +#include +std::size_t intbits = CHAR_BITS*sizeof(int); diff --git a/Task/Variable-size-Get/C++/variable-size-get-3.cpp b/Task/Variable-size-Get/C++/variable-size-get-3.cpp new file mode 100644 index 0000000000..779d15acc6 --- /dev/null +++ b/Task/Variable-size-Get/C++/variable-size-get-3.cpp @@ -0,0 +1,3 @@ +#include +int a = 1; +std::size_t a_size = sizeof a; diff --git a/Task/Variable-size-Get/C++/variable-size-get-4.cpp b/Task/Variable-size-Get/C++/variable-size-get-4.cpp new file mode 100644 index 0000000000..89e91ce361 --- /dev/null +++ b/Task/Variable-size-Get/C++/variable-size-get-4.cpp @@ -0,0 +1,2 @@ +#include +std::size_t size = sizeof (3*6 + 7.5); diff --git a/Task/Variable-size-Get/C/variable-size-get.c b/Task/Variable-size-Get/C/variable-size-get.c new file mode 100644 index 0000000000..3c05d99d0d --- /dev/null +++ b/Task/Variable-size-Get/C/variable-size-get.c @@ -0,0 +1 @@ +printf("An int contains %u bytes.\n", sizeof(int)); diff --git a/Task/Variable-size-Get/Common-Lisp/variable-size-get-1.lisp b/Task/Variable-size-Get/Common-Lisp/variable-size-get-1.lisp new file mode 100644 index 0000000000..32811b969f --- /dev/null +++ b/Task/Variable-size-Get/Common-Lisp/variable-size-get-1.lisp @@ -0,0 +1,6 @@ +(let ((a (cons 1 2)) + (b (make-array 10)) + (c "a string")) + (list (hcl:find-object-size a) + (hcl:find-object-size b) + (hcl:find-object-size c))) diff --git a/Task/Variable-size-Get/Common-Lisp/variable-size-get-2.lisp b/Task/Variable-size-Get/Common-Lisp/variable-size-get-2.lisp new file mode 100644 index 0000000000..e7045d5226 --- /dev/null +++ b/Task/Variable-size-Get/Common-Lisp/variable-size-get-2.lisp @@ -0,0 +1 @@ +(12 48 24) diff --git a/Task/Variable-size-Get/Common-Lisp/variable-size-get-3.lisp b/Task/Variable-size-Get/Common-Lisp/variable-size-get-3.lisp new file mode 100644 index 0000000000..4ebaea6a85 --- /dev/null +++ b/Task/Variable-size-Get/Common-Lisp/variable-size-get-3.lisp @@ -0,0 +1,7 @@ +(let (items) + (gc) ; name varies by implementation + (room) + (dotimes (x 512) + (push (allocate-something-of-interest) items)) + (gc) + (room)) diff --git a/Task/Variable-size-Get/D/variable-size-get.d b/Task/Variable-size-Get/D/variable-size-get.d new file mode 100644 index 0000000000..1b1299369a --- /dev/null +++ b/Task/Variable-size-Get/D/variable-size-get.d @@ -0,0 +1,7 @@ +int i ; +writefln(i.sizeof) ; // print 4 +int[13] ints1 ; // static integer array of length 13 +writefln(ints1.sizeof) ; // print 52 +int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13 +writefln(ints2.sizeof) ; // print 8, all dynamic array has this size +writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type diff --git a/Task/Variable-size-Get/Delphi/variable-size-get.delphi b/Task/Variable-size-Get/Delphi/variable-size-get.delphi new file mode 100644 index 0000000000..c75188e2e8 --- /dev/null +++ b/Task/Variable-size-Get/Delphi/variable-size-get.delphi @@ -0,0 +1 @@ +i := sizeof([any variable or structure]); diff --git a/Task/Variable-size-Get/Fortran/variable-size-get.f b/Task/Variable-size-Get/Fortran/variable-size-get.f new file mode 100644 index 0000000000..f4c268d479 --- /dev/null +++ b/Task/Variable-size-Get/Fortran/variable-size-get.f @@ -0,0 +1,14 @@ +INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2) +INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4) +INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8) +INTEGER, PARAMETER :: i64 = SELECTED_INT_KIND(16) +INTEGER(i8) :: onebyte = 0 +INTEGER(i16) :: twobytes = 0 +INTEGER(i32) :: fourbytes = 0 +INTEGER(i64) :: eightbytes = 0 + +WRITE (*,*) BIT_SIZE(onebyte), DIGITS(onebyte) ! prints 8 and 7 +WRITE (*,*) BIT_SIZE(twobytes), DIGITS(twobytes) ! prints 16 and 15 +WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31 +WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63 +WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53 diff --git a/Task/Variable-size-Get/Go/variable-size-get.go b/Task/Variable-size-Get/Go/variable-size-get.go new file mode 100644 index 0000000000..b2ad824901 --- /dev/null +++ b/Task/Variable-size-Get/Go/variable-size-get.go @@ -0,0 +1,3 @@ +import "unsafe" + +unsafe.Sizeof(x) diff --git a/Task/Variable-size-Get/Haskell/variable-size-get.hs b/Task/Variable-size-Get/Haskell/variable-size-get.hs new file mode 100644 index 0000000000..6a688f312b --- /dev/null +++ b/Task/Variable-size-Get/Haskell/variable-size-get.hs @@ -0,0 +1,6 @@ +import Foreign + +sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine) +sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine) +sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine) +sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine) diff --git a/Task/Variable-size-Get/IDL/variable-size-get.idl b/Task/Variable-size-Get/IDL/variable-size-get.idl new file mode 100644 index 0000000000..04c504b37e --- /dev/null +++ b/Task/Variable-size-Get/IDL/variable-size-get.idl @@ -0,0 +1,4 @@ +arr = intarr(3,4) +print,size(arr) +;=> prints this: + 2 3 4 2 12 diff --git a/Task/Variable-size-Get/Icon/variable-size-get.icon b/Task/Variable-size-Get/Icon/variable-size-get.icon new file mode 100644 index 0000000000..cf18bbe7a9 --- /dev/null +++ b/Task/Variable-size-Get/Icon/variable-size-get.icon @@ -0,0 +1,29 @@ +record rec0() +record rec4(a,b,c,d) + +procedure main() # get size + +every i := seq(1) do { + a0 := &allocated + x := case i of { + 1 : "ABCDEFGH" + 2 : reverse(x) + 10 : &digits + 11 : x--x + 20 : [] + 21 : [1,2] + 22 : [1,2,3] + 30 : set() + 31 : set("X") + 32 : set("A","B") + 40 : table(1) + 50 : rec0() + 51 : rec4() + 60 : create seq(1) + 99 : break + default : next + } + a1 := &allocated + write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0) + } +end diff --git a/Task/Variable-size-Get/J/variable-size-get-1.j b/Task/Variable-size-Get/J/variable-size-get-1.j new file mode 100644 index 0000000000..9a3c995c0a --- /dev/null +++ b/Task/Variable-size-Get/J/variable-size-get-1.j @@ -0,0 +1,2 @@ +some_variable =: 42 +7!:5<'some_variable' diff --git a/Task/Variable-size-Get/J/variable-size-get-2.j b/Task/Variable-size-Get/J/variable-size-get-2.j new file mode 100644 index 0000000000..0eb4d29111 --- /dev/null +++ b/Task/Variable-size-Get/J/variable-size-get-2.j @@ -0,0 +1,2 @@ +some_function =: +/ % # +7!:5<'some_function' diff --git a/Task/Variable-size-Get/Julia/variable-size-get.julia b/Task/Variable-size-Get/Julia/variable-size-get.julia new file mode 100644 index 0000000000..ea192e76f9 --- /dev/null +++ b/Task/Variable-size-Get/Julia/variable-size-get.julia @@ -0,0 +1,8 @@ +julia> sizeof(Int8) +1 + +julia> t = 1 +1 + +julia> sizeof(t) +4 diff --git a/Task/Variable-size-Get/Mathematica/variable-size-get.math b/Task/Variable-size-Get/Mathematica/variable-size-get.math new file mode 100644 index 0000000000..cbd7768928 --- /dev/null +++ b/Task/Variable-size-Get/Mathematica/variable-size-get.math @@ -0,0 +1 @@ +ByteCount["somerandomstring"] diff --git a/Task/Variable-size-Get/Modula-3/variable-size-get.mod3 b/Task/Variable-size-Get/Modula-3/variable-size-get.mod3 new file mode 100644 index 0000000000..57ddd4b50a --- /dev/null +++ b/Task/Variable-size-Get/Modula-3/variable-size-get.mod3 @@ -0,0 +1,9 @@ +MODULE Size EXPORTS Main; + +FROM IO IMPORT Put; +FROM Fmt IMPORT Int; + +BEGIN + Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n"); + Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n"); +END Size. diff --git a/Task/Variable-size-Get/OCaml/variable-size-get-1.ocaml b/Task/Variable-size-Get/OCaml/variable-size-get-1.ocaml new file mode 100644 index 0000000000..a1aad53f8e --- /dev/null +++ b/Task/Variable-size-Get/OCaml/variable-size-get-1.ocaml @@ -0,0 +1,25 @@ +(** The result is the size given in word. + The word size in octet can be found with (Sys.word_size / 8). + (The size of all the datas in OCaml is at least one word, even chars and bools.) +*) +let sizeof v = + let rec rec_size d r = + if List.memq r d then (1, d) else + if not(Obj.is_block r) then (1, r::d) else + if (Obj.tag r) = (Obj.double_tag) then (2, r::d) else + if (Obj.tag r) = (Obj.string_tag) then (Obj.size r, r::d) else + if (Obj.tag r) = (Obj.object_tag) || + (Obj.tag r) = (Obj.closure_tag) + then invalid_arg "please only provide datas" + else + let len = Obj.size r in + let rec aux d sum i = + if i >= len then (sum, r::d) else + let this = Obj.field r i in + let this_size, d = rec_size d this in + aux d (sum + this_size) (i+1) + in + aux d (1) 0 + in + fst(rec_size [] (Obj.repr v)) +;; diff --git a/Task/Variable-size-Get/OCaml/variable-size-get-2.ocaml b/Task/Variable-size-Get/OCaml/variable-size-get-2.ocaml new file mode 100644 index 0000000000..5c2406559a --- /dev/null +++ b/Task/Variable-size-Get/OCaml/variable-size-get-2.ocaml @@ -0,0 +1,85 @@ +# sizeof 234 ;; +- : int = 1 + +# sizeof 23.4 ;; +- : int = 2 + +# sizeof (1,2);; +- : int = 3 + +# sizeof (2, 3.4) ;; +- : int = 4 + +# sizeof (1,2,3,4,5) ;; +- : int = 6 + +# sizeof [| 1;2;3;4;5 |] ;; +- : int = 6 + +# sizeof [1;2;3;4;5] ;; +- : int = 11 + +(* because a list is equivalent to *) + +# sizeof (1,(2,(3,(4,(5,0))))) ;; +- : int = 11 + +# type foo = A | B of int | C of int * int ;; +type foo = A | B of int | C of int * int + +# sizeof A ;; +- : int = 1 + +# sizeof (B 3) ;; +- : int = 2 + +# sizeof (C(1,2)) ;; +- : int = 3 + +# sizeof true ;; +- : int = 1 + +# sizeof 'A' ;; +- : int = 1 + +# sizeof `some_pvar ;; +- : int = 1 + +# sizeof "" ;; +- : int = 1 + +# sizeof "Hello!" ;; +- : int = 2 +(* remember the size is given in words + (so 4 octets on 32 bits machines) *) + +# for i=0 to 16 do + Printf.printf "%d -> %d\n" i (sizeof(String.create i)) + done;; +0 -> 1 +1 -> 1 +2 -> 1 +3 -> 1 +4 -> 2 +5 -> 2 +6 -> 2 +7 -> 2 +8 -> 3 +9 -> 3 +10 -> 3 +11 -> 3 +12 -> 4 +13 -> 4 +14 -> 4 +15 -> 4 +16 -> 5 +- : unit = () + +# sizeof(Array.create 10 0) ;; +- : int = 11 + +# sizeof(Array.create 10 (String.create 20)) ;; +- : int = 16 + +# sizeof(Array.init 10 (fun _ -> String.create 20)) ;; +- : int = 61 diff --git a/Task/Variable-size-Get/PARI-GP/variable-size-get-1.pari b/Task/Variable-size-Get/PARI-GP/variable-size-get-1.pari new file mode 100644 index 0000000000..140f75a7a2 --- /dev/null +++ b/Task/Variable-size-Get/PARI-GP/variable-size-get-1.pari @@ -0,0 +1 @@ +sizebyte(x) diff --git a/Task/Variable-size-Get/PARI-GP/variable-size-get-2.pari b/Task/Variable-size-Get/PARI-GP/variable-size-get-2.pari new file mode 100644 index 0000000000..ea5d125566 --- /dev/null +++ b/Task/Variable-size-Get/PARI-GP/variable-size-get-2.pari @@ -0,0 +1 @@ +lg(x) diff --git a/Task/Variable-size-Get/PL-I/variable-size-get.pli b/Task/Variable-size-Get/PL-I/variable-size-get.pli new file mode 100644 index 0000000000..5f9ac1e088 --- /dev/null +++ b/Task/Variable-size-Get/PL-I/variable-size-get.pli @@ -0,0 +1,8 @@ +put skip list (SIZE(x)); /* gives the number of bytes occupied by X */ + /* whatever data type or structure it is. */ + +put skip list (CURRENTSIZE(x)); + /* gives the current number of bytes of X */ + /* actually used by such things as a */ + /* varying-length string, including its */ + /* length field. */ diff --git a/Task/Variable-size-Get/Pascal/variable-size-get.pascal b/Task/Variable-size-Get/Pascal/variable-size-get.pascal new file mode 100644 index 0000000000..c75188e2e8 --- /dev/null +++ b/Task/Variable-size-Get/Pascal/variable-size-get.pascal @@ -0,0 +1 @@ +i := sizeof([any variable or structure]); diff --git a/Task/Variable-size-Get/Perl/variable-size-get.pl b/Task/Variable-size-Get/Perl/variable-size-get.pl new file mode 100644 index 0000000000..db1e6823ee --- /dev/null +++ b/Task/Variable-size-Get/Perl/variable-size-get.pl @@ -0,0 +1,6 @@ +use Devel::Size; + +my $var = 9384752; +my @arr = (1, 2, 3, 4, 5, 6); +print size($var); +print total_size(@arr); diff --git a/Task/Variable-size-Get/Pop11/variable-size-get.pop11 b/Task/Variable-size-Get/Pop11/variable-size-get.pop11 new file mode 100644 index 0000000000..d6861234d2 --- /dev/null +++ b/Task/Variable-size-Get/Pop11/variable-size-get.pop11 @@ -0,0 +1,10 @@ +;;; Prints 0 because small integers need no heap storage +datasize(12) => +;;; Prints 3: 3 character fits into single machine word, 1 word +;;; for tag, 1 for length +datasize('str') => +;;; 3 element vector takes 5 words: 3 for values, 1 for tag, 1 for +;;; length +datasize({1 2 3}) => +;;; Prints 3 because only first node counts +datasize([1 2 3]) => diff --git a/Task/Variable-size-Get/PureBasic/variable-size-get.purebasic b/Task/Variable-size-Get/PureBasic/variable-size-get.purebasic new file mode 100644 index 0000000000..b79bc3788d --- /dev/null +++ b/Task/Variable-size-Get/PureBasic/variable-size-get.purebasic @@ -0,0 +1,3 @@ +Define a +Debug SizeOf(a) +; This also works for structured variables diff --git a/Task/Variable-size-Get/Python/variable-size-get-1.py b/Task/Variable-size-Get/Python/variable-size-get-1.py new file mode 100644 index 0000000000..0e4310818c --- /dev/null +++ b/Task/Variable-size-Get/Python/variable-size-get-1.py @@ -0,0 +1,15 @@ +>>> from array import array +>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), + ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] +>>> for typecode, initializer in argslist: + a = array(typecode, initializer) + print a, '\tSize =', a.buffer_info()[1] * a.itemsize + del a + + +array('l') Size = 0 +array('c', 'hello world') Size = 11 +array('u', u'hello \u2641') Size = 14 +array('l', [1, 2, 3, 4, 5]) Size = 20 +array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24 +>>> diff --git a/Task/Variable-size-Get/Python/variable-size-get-2.py b/Task/Variable-size-Get/Python/variable-size-get-2.py new file mode 100644 index 0000000000..f06e2d33d3 --- /dev/null +++ b/Task/Variable-size-Get/Python/variable-size-get-2.py @@ -0,0 +1,2 @@ +import sys +sys.getsizeof(obj) diff --git a/Task/Variable-size-Get/R/variable-size-get.r b/Task/Variable-size-Get/R/variable-size-get.r new file mode 100644 index 0000000000..5784b94774 --- /dev/null +++ b/Task/Variable-size-Get/R/variable-size-get.r @@ -0,0 +1,14 @@ +# Results are system dependent +num <- c(1, 3, 6, 10) +object.size(num) # e.g. 56 bytes + +#Allocating vectors using ':' results in less memory being (reportedly) used +num2 <- 1:4 +object.size(num2) # e.g. 40 bytes + +#Memory shared by objects isn't always counted +l <- list(a=c(1, 3, 6, 10), b=1:4) +object.size(l) # e.g. 280 bytes + +l2 <- list(num, num2) +object.size(l2) # e.g. 128 bytes diff --git a/Task/Variable-size-Get/REXX/variable-size-get.rexx b/Task/Variable-size-Get/REXX/variable-size-get.rexx new file mode 100644 index 0000000000..3edbcfd1ca --- /dev/null +++ b/Task/Variable-size-Get/REXX/variable-size-get.rexx @@ -0,0 +1,60 @@ +/*REXX program demonstrates (see the penultimate statment) how to */ +/* to find the size (length) of the value of a REXX variable. */ + +/*REXX doesn't reserve any storage for any variables, as all variables */ +/*are stored as character strings, including boolean. Storage is */ +/*obtained as necessary when REXX variables are assigned (or reassigned)*/ + +a = 456 /*length of A is 3 */ +b = "heptathlon" /*length of B is 10 */ +c = "heptathlon (7 events)" /*length of C is 21 */ +d = '' /*length of D is 0 */ +d = "" /*same as above. */ +d = left('space junk' ,0) /*same as above. */ +d = /*same as above. */ +e = 99-9 /*length of E is 2 (e=90) */ +f = copies(a,100) /*length of F is 300 (a=456)*/ +g.1 = -1 /*length of G.1 is 2 */ +g.2 = -1.0000 /*length of G.2 is 7 */ + /*length of HHH is 3 */ + + /*Note that when a REXX variable */ + /*isn't SET, then the value of it*/ + /*is the uppercased name itself, */ + /*so in this case (upper): HHH */ + +something = copies(a, random(100)) /*length is something, all right,*/ + /*could be 3 to 300 bytes, by gum*/ +thingLen = length(something) /*use LENGTH bif to find its len.*/ +say 'length of SOMETHING =' thingLen /*display the length of SOMETHING*/ + +/*┌────────────────────────────────────────────────────────────────────┐ + │ Note that the variable's data (value) isn't the true cost of the │ + │ size of the variable's value. REXX also keeps the name of │ + │ the (fully qualified) variable as well. │ + │ │ + │ Most REXX interpreters keep (at a miminum): │ + │ │ + │ ∙ a four-byte field which contains the length of the value │ + │ ∙ a four-byte field which contains the length of the var name │ + │ ∙ an N-byte field which contains the name of the variable │ + │ ∙ an X-byte field which contains the variable's value │ + │ ∙ a one-byte field which contains the status of the variable │ + │ │ + │ [Note that PC/REXX uses a two-byte field for the first two fields] │ + │ │ + │ │ + │ Consider the following two DO loops assigning a million variables: │ + │ │ + │ do j=1 to 1000000 │ + │ integer_numbers.j=j │ + │ end │ + │ ════════ and ════════ │ + │ do k=1 to 1000000 │ + │ #.k=k │ + │ end │ + │ │ + │ The "j" loop uses 35,777,792 bytes for the compound variables, │ + │ The "k" loop uses 21,777,792 bytes for the compound variables, │ + │ (excluding the DO loop indices [j and k] themselves). │ + └────────────────────────────────────────────────────────────────────┘*/ diff --git a/Task/Variable-size-Get/TUSCRIPT/variable-size-get.tuscript b/Task/Variable-size-Get/TUSCRIPT/variable-size-get.tuscript new file mode 100644 index 0000000000..156a4e90a3 --- /dev/null +++ b/Task/Variable-size-Get/TUSCRIPT/variable-size-get.tuscript @@ -0,0 +1,8 @@ +$$ MODE TUSCRIPT,{} +string="somerandomstring" +size=SIZE(string) +length=LENGTH(string) + +PRINT "string: ",string +PRINT "has size: ",size +PRINT "and length: ",length diff --git a/Task/Variable-size-Get/Tcl/variable-size-get.tcl b/Task/Variable-size-Get/Tcl/variable-size-get.tcl new file mode 100644 index 0000000000..6f82be9503 --- /dev/null +++ b/Task/Variable-size-Get/Tcl/variable-size-get.tcl @@ -0,0 +1 @@ +string bytelength $var diff --git a/Task/Variable-size-Get/Toka/variable-size-get-1.toka b/Task/Variable-size-Get/Toka/variable-size-get-1.toka new file mode 100644 index 0000000000..9332a1843c --- /dev/null +++ b/Task/Variable-size-Get/Toka/variable-size-get-1.toka @@ -0,0 +1,2 @@ +char-size . +cell-size . diff --git a/Task/Variable-size-Get/Toka/variable-size-get-2.toka b/Task/Variable-size-Get/Toka/variable-size-get-2.toka new file mode 100644 index 0000000000..15e63c4cd7 --- /dev/null +++ b/Task/Variable-size-Get/Toka/variable-size-get-2.toka @@ -0,0 +1,2 @@ +needs floats +float-size . diff --git a/Task/Variable-size-Get/UNIX-Shell/variable-size-get.sh b/Task/Variable-size-Get/UNIX-Shell/variable-size-get.sh new file mode 100644 index 0000000000..ca5c226509 --- /dev/null +++ b/Task/Variable-size-Get/UNIX-Shell/variable-size-get.sh @@ -0,0 +1,5 @@ +# In the shell all variables are stored as strings, so we use the same technique +# as for finding the length of a string: +greeting='Hello, world!' +greetinglength=`printf '%s' "$greeting" | wc -c` +echo "The greeting is $greetinglength characters in length" diff --git a/Task/Variable-size-Get/Ursala/variable-size-get.ursala b/Task/Variable-size-Get/Ursala/variable-size-get.ursala new file mode 100644 index 0000000000..67abaebefd --- /dev/null +++ b/Task/Variable-size-Get/Ursala/variable-size-get.ursala @@ -0,0 +1,5 @@ +#import std + +#cast %nL + +examples = diff --git a/Task/Variable-size-Get/Vala/variable-size-get.vala b/Task/Variable-size-Get/Vala/variable-size-get.vala new file mode 100644 index 0000000000..12c8d2f09a --- /dev/null +++ b/Task/Variable-size-Get/Vala/variable-size-get.vala @@ -0,0 +1,5 @@ +void main(){ + ulong x = sizeof(int); // returns # of bytes used to store an int + // is returned as a ulong, but could be typecasted to int with: int x = (int) sizeof(int) + stdout.printf("%lu\n", x); +} diff --git a/Task/Variable-size-Get/XPL0/variable-size-get.xpl0 b/Task/Variable-size-Get/XPL0/variable-size-get.xpl0 new file mode 100644 index 0000000000..fb84487f4d --- /dev/null +++ b/Task/Variable-size-Get/XPL0/variable-size-get.xpl0 @@ -0,0 +1,9 @@ +include c:\cxpl\codes; +int Size; +int A, B; +real X, Y; +[Size:= addr B - addr A; +IntOut(0, Size); CrLf(0); +Size:= addr Y - addr X; +IntOut(0, Size); CrLf(0); +] diff --git a/Task/Variable-size-Set/0DESCRIPTION b/Task/Variable-size-Set/0DESCRIPTION new file mode 100644 index 0000000000..f293e894c6 --- /dev/null +++ b/Task/Variable-size-Set/0DESCRIPTION @@ -0,0 +1 @@ +Demonstrate how to specify the minimum size of a variable or a data type. diff --git a/Task/Variable-size-Set/1META.yaml b/Task/Variable-size-Set/1META.yaml new file mode 100644 index 0000000000..a1563fda10 --- /dev/null +++ b/Task/Variable-size-Set/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Type System diff --git a/Task/Variable-size-Set/Ada/variable-size-set.ada b/Task/Variable-size-Set/Ada/variable-size-set.ada new file mode 100644 index 0000000000..ed3cf74ea8 --- /dev/null +++ b/Task/Variable-size-Set/Ada/variable-size-set.ada @@ -0,0 +1,2 @@ +type Response is (Yes, No); -- Definition of an enumeration type with two values +for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size diff --git a/Task/Variable-size-Set/BASIC/variable-size-set.basic b/Task/Variable-size-Set/BASIC/variable-size-set.basic new file mode 100644 index 0000000000..de45102ac1 --- /dev/null +++ b/Task/Variable-size-Set/BASIC/variable-size-set.basic @@ -0,0 +1,3 @@ +10 DIM A%(10): REM the array size is 10 integers +20 DIM B(10): REM the array will hold 10 floating point values +30 DIM C$(12): REM a character array of 12 bytes diff --git a/Task/Variable-size-Set/BBC-BASIC/variable-size-set.bbc b/Task/Variable-size-Set/BBC-BASIC/variable-size-set.bbc new file mode 100644 index 0000000000..1b2e93e037 --- /dev/null +++ b/Task/Variable-size-Set/BBC-BASIC/variable-size-set.bbc @@ -0,0 +1,4 @@ + var& = 1 : REM Variable occupies 8 bits + var% = 1 : REM Variable occupies 32 bits + var = 1 : REM Variable occupies 40 bits + var# = 1 : REM Variable occupies 64 bits diff --git a/Task/Variable-size-Set/C++/variable-size-set.cpp b/Task/Variable-size-Set/C++/variable-size-set.cpp new file mode 100644 index 0000000000..2e157f10da --- /dev/null +++ b/Task/Variable-size-Set/C++/variable-size-set.cpp @@ -0,0 +1,3 @@ +#include + +boost::int_least32_t foo; diff --git a/Task/Variable-size-Set/C/variable-size-set.c b/Task/Variable-size-Set/C/variable-size-set.c new file mode 100644 index 0000000000..9da61e0c55 --- /dev/null +++ b/Task/Variable-size-Set/C/variable-size-set.c @@ -0,0 +1,3 @@ +#include + +int_least32_t foo; diff --git a/Task/Variable-size-Set/D/variable-size-set-1.d b/Task/Variable-size-Set/D/variable-size-set-1.d new file mode 100644 index 0000000000..bcb85bb0dd --- /dev/null +++ b/Task/Variable-size-Set/D/variable-size-set-1.d @@ -0,0 +1,2 @@ +typedef long[0] zeroLength ; +writefln(zeroLength.sizeof) ; // print 0 diff --git a/Task/Variable-size-Set/D/variable-size-set-2.d b/Task/Variable-size-Set/D/variable-size-set-2.d new file mode 100644 index 0000000000..41ed2a760e --- /dev/null +++ b/Task/Variable-size-Set/D/variable-size-set-2.d @@ -0,0 +1,4 @@ +byte b ; +ubyte ub ; +char c ; +bool t ; diff --git a/Task/Variable-size-Set/D/variable-size-set-3.d b/Task/Variable-size-Set/D/variable-size-set-3.d new file mode 100644 index 0000000000..66f66d59f5 --- /dev/null +++ b/Task/Variable-size-Set/D/variable-size-set-3.d @@ -0,0 +1,2 @@ +struct Empty { } +writefln(Empty.sizeof) ; // print 1 diff --git a/Task/Variable-size-Set/Fortran/variable-size-set.f b/Task/Variable-size-Set/Fortran/variable-size-set.f new file mode 100644 index 0000000000..b8e02a48f0 --- /dev/null +++ b/Task/Variable-size-Set/Fortran/variable-size-set.f @@ -0,0 +1,43 @@ +program setsize +implicit none + + integer, parameter :: p1 = 6 + integer, parameter :: p2 = 12 + integer, parameter :: r1 = 30 + integer, parameter :: r2 = 1000 + integer, parameter :: r3 = 2 + integer, parameter :: r4 = 4 + integer, parameter :: r5 = 8 + integer, parameter :: r6 = 16 + integer, parameter :: rprec1 = selected_real_kind(p1, r1) + integer, parameter :: rprec2 = selected_real_kind(p2, r1) + integer, parameter :: rprec3 = selected_real_kind(p2, r2) + integer, parameter :: iprec1 = selected_int_kind(r3) + integer, parameter :: iprec2 = selected_int_kind(r4) + integer, parameter :: iprec3 = selected_int_kind(r5) + integer, parameter :: iprec4 = selected_int_kind(r6) + + real(rprec1) :: n1 + real(rprec2) :: n2 + real(rprec3) :: n3 + integer(iprec1) :: n4 + integer(iprec2) :: n5 + integer(iprec3) :: n6 + integer(iprec4) :: n7 + character(30) :: form + + form = "(a7, i11, i10, i6, i9, i8)" + write(*, "(a)") "KIND NAME KIND NUMBER PRECISION RANGE " + write(*, "(a)") " min set min set" + write(*, "(a)") "______________________________________________________" + write(*, form) "rprec1", kind(n1), p1, precision(n1), r1, range(n1) + write(*, form) "rprec2", kind(n2), p2, precision(n2), r1, range(n2) + write(*, form) "rprec3", kind(n3), p2, precision(n3), r2, range(n3) + write(*,*) + form = "(a7, i11, i25, i8)" + write(*, form) "iprec1", kind(n4), r3, range(n4) + write(*, form) "iprec2", kind(n5), r4, range(n5) + write(*, form) "iprec3", kind(n6), r5, range(n6) + write(*, form) "iprec4", kind(n7), r6, range(n7) + +end program diff --git a/Task/Variable-size-Set/Go/variable-size-set.go b/Task/Variable-size-Set/Go/variable-size-set.go new file mode 100644 index 0000000000..c416ce6515 --- /dev/null +++ b/Task/Variable-size-Set/Go/variable-size-set.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "unsafe" +) + +func main() { + i := 5 // default type is int + r := '5' // default type is rune (which is int32) + f := 5. // default type is float64 + c := 5i // default type is complex128 + fmt.Println("i:", unsafe.Sizeof(i), "bytes") + fmt.Println("r:", unsafe.Sizeof(r), "bytes") + fmt.Println("f:", unsafe.Sizeof(f), "bytes") + fmt.Println("c:", unsafe.Sizeof(c), "bytes") + iMin := int8(5) + rMin := byte('5') + fMin := float32(5.) + cMin := complex64(5i) + fmt.Println("iMin:", unsafe.Sizeof(iMin), "bytes") + fmt.Println("rMin:", unsafe.Sizeof(rMin), "bytes") + fmt.Println("fMin:", unsafe.Sizeof(fMin), "bytes") + fmt.Println("cMin:", unsafe.Sizeof(cMin), "bytes") +} diff --git a/Task/Variable-size-Set/Icon/variable-size-set.icon b/Task/Variable-size-Set/Icon/variable-size-set.icon new file mode 100644 index 0000000000..fe6cde6a89 --- /dev/null +++ b/Task/Variable-size-Set/Icon/variable-size-set.icon @@ -0,0 +1 @@ + L := list(10) # 10 element list diff --git a/Task/Variable-size-Set/J/variable-size-set.j b/Task/Variable-size-Set/J/variable-size-set.j new file mode 100644 index 0000000000..f883d77983 --- /dev/null +++ b/Task/Variable-size-Set/J/variable-size-set.j @@ -0,0 +1 @@ +v=: '' diff --git a/Task/Variable-size-Set/Modula-3/variable-size-set.mod3 b/Task/Variable-size-Set/Modula-3/variable-size-set.mod3 new file mode 100644 index 0000000000..5c95e0e954 --- /dev/null +++ b/Task/Variable-size-Set/Modula-3/variable-size-set.mod3 @@ -0,0 +1 @@ +TYPE UByte = BITS 8 FOR [0..255]; diff --git a/Task/Variable-size-Set/PARI-GP/variable-size-set-1.pari b/Task/Variable-size-Set/PARI-GP/variable-size-set-1.pari new file mode 100644 index 0000000000..64aabfb6c7 --- /dev/null +++ b/Task/Variable-size-Set/PARI-GP/variable-size-set-1.pari @@ -0,0 +1 @@ +default(precision, 1000) diff --git a/Task/Variable-size-Set/PARI-GP/variable-size-set-2.pari b/Task/Variable-size-Set/PARI-GP/variable-size-set-2.pari new file mode 100644 index 0000000000..97c8089229 --- /dev/null +++ b/Task/Variable-size-Set/PARI-GP/variable-size-set-2.pari @@ -0,0 +1 @@ +\p 1000 diff --git a/Task/Variable-size-Set/PL-I/variable-size-set.pli b/Task/Variable-size-Set/PL-I/variable-size-set.pli new file mode 100644 index 0000000000..6b3a0438fd --- /dev/null +++ b/Task/Variable-size-Set/PL-I/variable-size-set.pli @@ -0,0 +1,16 @@ +declare i fixed binary (7), /* occupies one byte */ + j fixed binary (15), /* occupies two bytes */ + k fixed binary (31), /* occupies 4 bytes */ + l fixed binary (63); /* occupies 8 bytes */ + +declare d fixed decimal (1), /* occupies 1 byte */ + e fixed decimal (3), /* occupies 2 bytes */ + /* an so on ... */ + f fixed decimal (15); /* occupies 8 bytes. */ + +declare b(16) bit (1) unaligned; /* occupies 2 bytes */ +declare c(16) bit (1) aligned; /* occupies 16 bytes */ + +declare x float, /* occupies 4 bytes. */ + y float (15), /* occupies 8 bytes. */ + z float (18); /* occupies 10 bytes */ diff --git a/Task/Variable-size-Set/Pascal/variable-size-set.pascal b/Task/Variable-size-Set/Pascal/variable-size-set.pascal new file mode 100644 index 0000000000..ed186194a5 --- /dev/null +++ b/Task/Variable-size-Set/Pascal/variable-size-set.pascal @@ -0,0 +1,8 @@ +var + a: byte; // 1 byte + b: word; // 2 byte + c: cardinal; // 4 byte + d: QWord; // 8 byte + + x: real; // 4 byte + y: double; // 8 byte diff --git a/Task/Variable-size-Set/REXX/variable-size-set.rexx b/Task/Variable-size-Set/REXX/variable-size-set.rexx new file mode 100644 index 0000000000..d48b741ec7 --- /dev/null +++ b/Task/Variable-size-Set/REXX/variable-size-set.rexx @@ -0,0 +1,2 @@ +numeric digits 100 +abc=12345678901111111112222222222333333333344444444445555555555.66 diff --git a/Task/Variable-size-Set/Tcl/variable-size-set-1.tcl b/Task/Variable-size-Set/Tcl/variable-size-set-1.tcl new file mode 100644 index 0000000000..57bac41005 --- /dev/null +++ b/Task/Variable-size-Set/Tcl/variable-size-set-1.tcl @@ -0,0 +1,9 @@ +% proc format_trace {fmt _var el op} {upvar 1 $_var v; set v [format $fmt $v]} + +% trace var foo w {format_trace %10s} +% puts "/[set foo bar]/" +/ bar/ + +% trace var grill w {format_trace %-10s} +% puts "/[set grill bar]/" +/bar / diff --git a/Task/Variable-size-Set/Tcl/variable-size-set-2.tcl b/Task/Variable-size-Set/Tcl/variable-size-set-2.tcl new file mode 100644 index 0000000000..d5ab0d25fe --- /dev/null +++ b/Task/Variable-size-Set/Tcl/variable-size-set-2.tcl @@ -0,0 +1,5 @@ +% proc range_trace {n _var el op} {upvar 1 $_var v; set v [string range $v 0 [incr n -1]]} + +% trace var baz w {range_trace 2} +% set baz Frankfurt +Fr diff --git a/Task/Variable-size-Set/Ursala/variable-size-set.ursala b/Task/Variable-size-Set/Ursala/variable-size-set.ursala new file mode 100644 index 0000000000..f84c806dbe --- /dev/null +++ b/Task/Variable-size-Set/Ursala/variable-size-set.ursala @@ -0,0 +1,11 @@ +p = mpfr..pi 200 # 200 bits of precision + +x = mpfr..grow(1.0E+0,1000) # 160 default precision, grown to 1160 + +y = mpfr..shrink(1.0+0,40) # 160 default shrunk to 120 + +z = mpfr..add(p,y) # inherits 200 bits of precision + +a = # 180 bits (not the default 160) because of more digits in the constant + +1.00000000000000000000000000000000000000000000000000000E0 diff --git a/Task/Variable-size-Set/XPL0/variable-size-set.xpl0 b/Task/Variable-size-Set/XPL0/variable-size-set.xpl0 new file mode 100644 index 0000000000..429be74345 --- /dev/null +++ b/Task/Variable-size-Set/XPL0/variable-size-set.xpl0 @@ -0,0 +1,13 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +string 0; \use zero-terminated strings +char S, + A(1), \sets up an array containing one byte + B(0); \sets up an array containing no bytes +int I; +[S:= ""; \a zero-length (null) string +A:= Reserve(1); \sets up a 1-byte array at runtime +B:= Reserve(0); \sets up a 0-byte array at runtime +I:= I ! 1<<3; \stores a single 1 bit into an integer +I:= I & ~(1<<29); \stores a 0 bit into bit 29 of the integer +IntOut(0, I>>3 & 1); \displays value of bit 3 +] diff --git a/Task/Variable-size-Set/ZX-Spectrum-Basic/variable-size-set.zx b/Task/Variable-size-Set/ZX-Spectrum-Basic/variable-size-set.zx new file mode 100644 index 0000000000..c14cc28c83 --- /dev/null +++ b/Task/Variable-size-Set/ZX-Spectrum-Basic/variable-size-set.zx @@ -0,0 +1,3 @@ +10 DIM a$(10): REM This array will be 10 characters long +20 DIM b(10): REM this will hold a set of numbers. The fixed number of bytes per number is implementation specific +30 LET c=5: REM this is a single numerical value of fixed size diff --git a/Task/Variables/0DESCRIPTION b/Task/Variables/0DESCRIPTION new file mode 100644 index 0000000000..366cec74bc --- /dev/null +++ b/Task/Variables/0DESCRIPTION @@ -0,0 +1 @@ +Demonstrate the language's methods of variable declaration, initialization, assignment, datatypes, scope, referencing, and other variable related facilities. diff --git a/Task/Variables/1META.yaml b/Task/Variables/1META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/Variables/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/Variables/ALGOL-68/variables-1.alg b/Task/Variables/ALGOL-68/variables-1.alg new file mode 100644 index 0000000000..a12cb7afba --- /dev/null +++ b/Task/Variables/ALGOL-68/variables-1.alg @@ -0,0 +1 @@ +int j; diff --git a/Task/Variables/ALGOL-68/variables-2.alg b/Task/Variables/ALGOL-68/variables-2.alg new file mode 100644 index 0000000000..773780f747 --- /dev/null +++ b/Task/Variables/ALGOL-68/variables-2.alg @@ -0,0 +1 @@ +LONG REAL double1, double2, double3; diff --git a/Task/Variables/ALGOL-68/variables-3.alg b/Task/Variables/ALGOL-68/variables-3.alg new file mode 100644 index 0000000000..7aa2646c88 --- /dev/null +++ b/Task/Variables/ALGOL-68/variables-3.alg @@ -0,0 +1,2 @@ +SHORT INT b1 := 2500; +LONG INT elwood = 3*bsize, jake = bsize -2; diff --git a/Task/Variables/ALGOL-68/variables-4.alg b/Task/Variables/ALGOL-68/variables-4.alg new file mode 100644 index 0000000000..a7a0f9c4b2 --- /dev/null +++ b/Task/Variables/ALGOL-68/variables-4.alg @@ -0,0 +1 @@ +FLEX[20]CHAR mystring; diff --git a/Task/Variables/ALGOL-68/variables-5.alg b/Task/Variables/ALGOL-68/variables-5.alg new file mode 100644 index 0000000000..c96518cf70 --- /dev/null +++ b/Task/Variables/ALGOL-68/variables-5.alg @@ -0,0 +1 @@ +[]CHAR mytext = "The ALGOL 68 Language"; diff --git a/Task/Variables/AWK/variables-1.awk b/Task/Variables/AWK/variables-1.awk new file mode 100644 index 0000000000..603376414b --- /dev/null +++ b/Task/Variables/AWK/variables-1.awk @@ -0,0 +1,2 @@ +a = 1 # Here we declare a numeric variable +fruit = "banana" # Here we declare a string datatype diff --git a/Task/Variables/AWK/variables-2.awk b/Task/Variables/AWK/variables-2.awk new file mode 100644 index 0000000000..718766c3a6 --- /dev/null +++ b/Task/Variables/AWK/variables-2.awk @@ -0,0 +1 @@ +x = y = z = 3 diff --git a/Task/Variables/AWK/variables-3.awk b/Task/Variables/AWK/variables-3.awk new file mode 100644 index 0000000000..8b05c8c4a9 --- /dev/null +++ b/Task/Variables/AWK/variables-3.awk @@ -0,0 +1,7 @@ +function foo(j k) { + # j is an argument passed from caller + # k is a dummy not passed by caller, but because it is in the + # argument list, it will have a scope local to the function + k = length(j) + print j "contains " k " characters" +} diff --git a/Task/Variables/Ada/variables.ada b/Task/Variables/Ada/variables.ada new file mode 100644 index 0000000000..caaf892e70 --- /dev/null +++ b/Task/Variables/Ada/variables.ada @@ -0,0 +1,7 @@ +declare + X : String := "Hello"; -- Create and initialize a local variable + Y : Integer; -- Create an uninitialized variable + Z : Integer renames Y: -- Rename Y (creates a view) +begin + Y := 1; -- Assign variable +end; -- End of the scope diff --git a/Task/Variables/AppleScript/variables-1.applescript b/Task/Variables/AppleScript/variables-1.applescript new file mode 100644 index 0000000000..892bdf15dd --- /dev/null +++ b/Task/Variables/AppleScript/variables-1.applescript @@ -0,0 +1 @@ +set x to 1 diff --git a/Task/Variables/AppleScript/variables-2.applescript b/Task/Variables/AppleScript/variables-2.applescript new file mode 100644 index 0000000000..c87a292f61 --- /dev/null +++ b/Task/Variables/AppleScript/variables-2.applescript @@ -0,0 +1,4 @@ +global x +set x to 1 +local y +set y to 2 diff --git a/Task/Variables/AppleScript/variables-3.applescript b/Task/Variables/AppleScript/variables-3.applescript new file mode 100644 index 0000000000..f93952570f --- /dev/null +++ b/Task/Variables/AppleScript/variables-3.applescript @@ -0,0 +1,15 @@ +on localx() + set x to 0 -- implicit local + return x +end localx + +on globalx() + set x to 0 -- implicit local + return my x +end globalx + +on run + set x to 1 -- top-level implicit global + return {localx(), globalx()} +end run +--> RETURNS: {0, 1} diff --git a/Task/Variables/AppleScript/variables-4.applescript b/Task/Variables/AppleScript/variables-4.applescript new file mode 100644 index 0000000000..8739486803 --- /dev/null +++ b/Task/Variables/AppleScript/variables-4.applescript @@ -0,0 +1 @@ +property x : 1 diff --git a/Task/Variables/AutoHotkey/variables.ahk b/Task/Variables/AutoHotkey/variables.ahk new file mode 100644 index 0000000000..8df20a54b3 --- /dev/null +++ b/Task/Variables/AutoHotkey/variables.ahk @@ -0,0 +1,10 @@ +x = hello ; assign verbatim as a string +z := 3 + 4 ; assign an expression +if !y ; uninitialized variables are assumed to be 0 or "" (blank string) +Msgbox %x% ; variable dereferencing is done by surrounding '%' signs +fx() +{ +local x ; variable default scope in a function is local anyways +global y ; +static z=4 ; initialized once, then value is remembered between function calls +} diff --git a/Task/Variables/BASIC/variables.basic b/Task/Variables/BASIC/variables.basic new file mode 100644 index 0000000000..28d0944c8a --- /dev/null +++ b/Task/Variables/BASIC/variables.basic @@ -0,0 +1,16 @@ +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/BBC-BASIC/variables.bbc b/Task/Variables/BBC-BASIC/variables.bbc new file mode 100644 index 0000000000..fe8b9e2f36 --- /dev/null +++ b/Task/Variables/BBC-BASIC/variables.bbc @@ -0,0 +1,33 @@ + REM BBC BASIC (for Windows) has the following scalar variable types; + REM the type is explicitly indicated by means of a suffix character. + REM Variable names must start with A-Z, a-z, _ or `, and may contain + REM any of those characters plus 0-9 and @; they are case-sensitive. + + A& = 123 : REM Unsigned 8-bit byte (0 to 255) + A% = 12345678 : REM Signed 32-bit integer (-2147483648 to +2147483647) + A = 123.45E6 : REM Variant 40-bit float or 32-bit integer (no suffix) + A# = 123.45E6 : REM Variant 64-bit double or 32-bit integer + A$ = "Abcdef" : REM String (0 to 65535 bytes) + + REM Scalar variables do not need to be declared but must be initialised + REM before being read, otherwise a 'No such variable' error is reported + REM The static integer variables A% to Z% are permanently defined. + + REM BBC BASIC also has indirection operators which allow variable-like + REM entities to be created in memory: + + DIM addr 7 : REM Allocate 8 bytes of heap + ?addr = 123 : REM Unsigned 8-bit byte (0 to 255) + !addr = 12345 : REM Signed 32-bit integer (-2147483648 to +2147483647) + |addr = 12.34 : REM Variant 40-bit or 64-bit float or 32-bit integer + $addr = "Abc" : REM String terminated by CR (0 to 65535 bytes) + $$addr = "Abc": REM String terminated by NUL (0 to 65535 bytes) + + REM The integer indirection operators may be used in a dyadic form: + offset = 4 + addr?offset = 12345678 : REM Unsigned 8-bit byte at addr+offset + addr!offset = 12345678 : REM Signed 32-bit integer at addr+offset + + REM All variables in BBC BASIC have global scope unless they are used + REM as a formal parameter of a function or procedure, or are declared + REM as LOCAL or PRIVATE. This is different from most other BASICs. diff --git a/Task/Variables/C++/variables.cpp b/Task/Variables/C++/variables.cpp new file mode 100644 index 0000000000..4e610c04d5 --- /dev/null +++ b/Task/Variables/C++/variables.cpp @@ -0,0 +1 @@ +int a; diff --git a/Task/Variables/C/variables-1.c b/Task/Variables/C/variables-1.c new file mode 100644 index 0000000000..a12cb7afba --- /dev/null +++ b/Task/Variables/C/variables-1.c @@ -0,0 +1 @@ +int j; diff --git a/Task/Variables/C/variables-2.c b/Task/Variables/C/variables-2.c new file mode 100644 index 0000000000..e66181da9f --- /dev/null +++ b/Task/Variables/C/variables-2.c @@ -0,0 +1 @@ +double double1, double2, double3; diff --git a/Task/Variables/C/variables-3.c b/Task/Variables/C/variables-3.c new file mode 100644 index 0000000000..777154e184 --- /dev/null +++ b/Task/Variables/C/variables-3.c @@ -0,0 +1,2 @@ +short b1 = 2500; +long elwood = 3*BSIZE, jake = BSIZE -2; diff --git a/Task/Variables/C/variables-4.c b/Task/Variables/C/variables-4.c new file mode 100644 index 0000000000..c1a563f6dc --- /dev/null +++ b/Task/Variables/C/variables-4.c @@ -0,0 +1 @@ +char mystring[21]; diff --git a/Task/Variables/C/variables-5.c b/Task/Variables/C/variables-5.c new file mode 100644 index 0000000000..cbea60053c --- /dev/null +++ b/Task/Variables/C/variables-5.c @@ -0,0 +1 @@ +const char * mytext = "The C Language"; diff --git a/Task/Variables/D/variables.d b/Task/Variables/D/variables.d new file mode 100644 index 0000000000..fd483c1f5d --- /dev/null +++ b/Task/Variables/D/variables.d @@ -0,0 +1,3 @@ +float bite = 36.321; ///_Defines a floating-point number (float), "bite", with a value of 36.321 +float[3] bites; ///_Defines a static array of 3 floats +float[] more_bites; ///_Defines a dynamic array of floats diff --git a/Task/Variables/DWScript/variables.dwscript b/Task/Variables/DWScript/variables.dwscript new file mode 100644 index 0000000000..4afa731644 --- /dev/null +++ b/Task/Variables/DWScript/variables.dwscript @@ -0,0 +1,4 @@ +var i := 123; // inferred type of i is Integer +var s := 'abc'; // inferred type of s is String +var o := TObject.Create; // inferred type of o is TObject +var s2 := o.ClassName; // inferred type of s2 is String as that's the type returned by ClassName diff --git a/Task/Variables/Delphi/variables.delphi b/Task/Variables/Delphi/variables.delphi new file mode 100644 index 0000000000..1a2058f21d --- /dev/null +++ b/Task/Variables/Delphi/variables.delphi @@ -0,0 +1,14 @@ +var + i: Integer; + s: string; + o: TObject; +begin + i := 123; + s := 'abc'; + o := TObject.Create; + try + // ... + finally + o.Free; + end; +end; diff --git a/Task/Variables/E/variables-1.e b/Task/Variables/E/variables-1.e new file mode 100644 index 0000000000..e3c42da01f --- /dev/null +++ b/Task/Variables/E/variables-1.e @@ -0,0 +1,2 @@ +def x := 1 +x + x # returns 2 diff --git a/Task/Variables/E/variables-2.e b/Task/Variables/E/variables-2.e new file mode 100644 index 0000000000..fad6edf12c --- /dev/null +++ b/Task/Variables/E/variables-2.e @@ -0,0 +1,3 @@ +def var x := 1 +x := 2 +x # returns 2 diff --git a/Task/Variables/E/variables-3.e b/Task/Variables/E/variables-3.e new file mode 100644 index 0000000000..85a11dca6c --- /dev/null +++ b/Task/Variables/E/variables-3.e @@ -0,0 +1,7 @@ +def var x := 1 +x += 1 # equivalent to x := x + 1, or x := x.add(1) +x # returns 2 + +def var list := ["x"] +list with= "y" # equivalent to list := list.with("y") +list # returns ["x", "y"] diff --git a/Task/Variables/E/variables-4.e b/Task/Variables/E/variables-4.e new file mode 100644 index 0000000000..c43c24979b --- /dev/null +++ b/Task/Variables/E/variables-4.e @@ -0,0 +1 @@ +def [hair, eyes, var shirt, var pants] := ["black", "brown", "plaid", "jeans"] diff --git a/Task/Variables/E/variables-5.e b/Task/Variables/E/variables-5.e new file mode 100644 index 0000000000..29ba0cb650 --- /dev/null +++ b/Task/Variables/E/variables-5.e @@ -0,0 +1 @@ +[shirt, pants] := ["white", "black"] # This does not do anything useful. diff --git a/Task/Variables/E/variables-6.e b/Task/Variables/E/variables-6.e new file mode 100644 index 0000000000..22ac49b11e --- /dev/null +++ b/Task/Variables/E/variables-6.e @@ -0,0 +1,2 @@ +def list := [def x := timer.now(), x] # two copies of the current time +list[0] == x # x is still visible here; returns true diff --git a/Task/Variables/E/variables-7.e b/Task/Variables/E/variables-7.e new file mode 100644 index 0000000000..8e48299715 --- /dev/null +++ b/Task/Variables/E/variables-7.e @@ -0,0 +1,10 @@ +def makeSum() { + var a := 0 + var b := 0 + return [&a, &b, fn { a + b }] +} + +def [&x, &y, sum] := makeSum() +x := 3 +y := 4 +sum() # returns 7 diff --git a/Task/Variables/E/variables-8.e b/Task/Variables/E/variables-8.e new file mode 100644 index 0000000000..cb44057adf --- /dev/null +++ b/Task/Variables/E/variables-8.e @@ -0,0 +1,8 @@ +def getUniqueId(&counter) { + counter += 1 + return counter +} + +var idc := 0 +getUniqueId(&idc) # returns 1 +getUniqueId(&idc) # returns 2 diff --git a/Task/Variables/Ela/variables-1.ela b/Task/Variables/Ela/variables-1.ela new file mode 100644 index 0000000000..87c90efa5b --- /dev/null +++ b/Task/Variables/Ela/variables-1.ela @@ -0,0 +1,3 @@ +x = 42 + +sum x y = x + y diff --git a/Task/Variables/Ela/variables-2.ela b/Task/Variables/Ela/variables-2.ela new file mode 100644 index 0000000000..ab89f4f972 --- /dev/null +++ b/Task/Variables/Ela/variables-2.ela @@ -0,0 +1,4 @@ +sum x y = let z = x + y in z + +sum x y = z + where z = x + y diff --git a/Task/Variables/Factor/variables.factor b/Task/Variables/Factor/variables.factor new file mode 100644 index 0000000000..67753dea61 --- /dev/null +++ b/Task/Variables/Factor/variables.factor @@ -0,0 +1,11 @@ +SYMBOL: foo + +: use-foo ( -- ) + 1 foo set + foo get 2 + foo set ! foo now = 3 + foo get number>string print ; + +:: named-param-example ( a b -- ) + a b + number>string print ; + +: local-example ( -- str ) [let "a" :> b "c" :> a a " " b 3append ] ; diff --git a/Task/Variables/Forth/variables-1.fth b/Task/Variables/Forth/variables-1.fth new file mode 100644 index 0000000000..0277f646c1 --- /dev/null +++ b/Task/Variables/Forth/variables-1.fth @@ -0,0 +1,3 @@ +: hypot ( a b -- a^2 + b^2 ) + LOCALS| b a | \ note: reverse order from the conventional stack comment + b b * a a * + ; diff --git a/Task/Variables/Forth/variables-2.fth b/Task/Variables/Forth/variables-2.fth new file mode 100644 index 0000000000..1a17600c08 --- /dev/null +++ b/Task/Variables/Forth/variables-2.fth @@ -0,0 +1,2 @@ +: hypot { a b -- a^2 + b^2 } \ text between "--" and "}" remains commentary + a a * b b * + ; diff --git a/Task/Variables/Forth/variables-3.fth b/Task/Variables/Forth/variables-3.fth new file mode 100644 index 0000000000..cf140779da --- /dev/null +++ b/Task/Variables/Forth/variables-3.fth @@ -0,0 +1,2 @@ +: length { F: a F: b F: c -- len } \ floating point locals + a a F* b b F* F+ c c F* F+ FSQRT ; diff --git a/Task/Variables/Fortran/variables.f b/Task/Variables/Fortran/variables.f new file mode 100644 index 0000000000..a20c60125a --- /dev/null +++ b/Task/Variables/Fortran/variables.f @@ -0,0 +1,28 @@ + program test + implicit none + + integer :: i !scalar integer + integer,dimension(10) :: ivec !integer vector + real :: r !scalar real + real,dimension(10) :: rvec !real vector + character(len=:),allocatable :: char1, char2 !fortran 2003 allocatable strings + +!assignments: + +!-- scalars: + i = 1 + r = 3.14 + +!-- vectors: + ivec = 1 !(all elements set to 1) + ivec(1:5) = 2 + + rvec(1:9) = 0.0 + rvec(10) = 1.0 + +!-- strings: + char1 = 'hello world!' + char2 = char1 !copy from one string to another + char2(1:1) = 'H' !change first character + +end program test diff --git a/Task/Variables/GAP/variables.gap b/Task/Variables/GAP/variables.gap new file mode 100644 index 0000000000..0be16d9f6d --- /dev/null +++ b/Task/Variables/GAP/variables.gap @@ -0,0 +1,24 @@ +# At top level, global variables are declared when they are assigned, so one only writes +global_var := 1; + +# In a function, local variables are declared like this +func := function(n) + local a; + a := n*n; + return n + a; +end; + +# One can test whether a variable is assigned +IsBound(global_var); +# true; + +# And destroy a variable +Unbind(global_var); + +# This works with list elements too +u := [11, 12, , 14]; +IsBound(u[4]); +# true +IsBound(u[3]); +# false +Unbind(u[4]); diff --git a/Task/Variables/Go/variables-1.go b/Task/Variables/Go/variables-1.go new file mode 100644 index 0000000000..dae5bebf71 --- /dev/null +++ b/Task/Variables/Go/variables-1.go @@ -0,0 +1 @@ +x := 3 diff --git a/Task/Variables/Go/variables-2.go b/Task/Variables/Go/variables-2.go new file mode 100644 index 0000000000..5a4e116e92 --- /dev/null +++ b/Task/Variables/Go/variables-2.go @@ -0,0 +1,2 @@ +var x int // declaration +x = 3 // assignment diff --git a/Task/Variables/Go/variables-3.go b/Task/Variables/Go/variables-3.go new file mode 100644 index 0000000000..c6a6417386 --- /dev/null +++ b/Task/Variables/Go/variables-3.go @@ -0,0 +1,4 @@ +y := x+1 // y is int, assuming declaration above +same := x == y // same declared as bool +p := &same // type of p is pointer to bool +pi := math.Floor(math.Pi) // math.Floor returns float64, so that is the type of pi diff --git a/Task/Variables/Go/variables-4.go b/Task/Variables/Go/variables-4.go new file mode 100644 index 0000000000..3f63656c45 --- /dev/null +++ b/Task/Variables/Go/variables-4.go @@ -0,0 +1,2 @@ +var x, y int // two variables, initialized to zero. +var p *int // initialized to nil diff --git a/Task/Variables/Go/variables-5.go b/Task/Variables/Go/variables-5.go new file mode 100644 index 0000000000..7850bf9a93 --- /dev/null +++ b/Task/Variables/Go/variables-5.go @@ -0,0 +1,4 @@ +var ( + x, y int + s string +) diff --git a/Task/Variables/Go/variables-6.go b/Task/Variables/Go/variables-6.go new file mode 100644 index 0000000000..219684564d --- /dev/null +++ b/Task/Variables/Go/variables-6.go @@ -0,0 +1,4 @@ +x, y = y, x // swap x and y +sinX, cosX = math.Sincos(x) // Sincos function returns two values +// map lookup optionally returns a second value indicating if the key was found. +value, ok = mapObject[key] diff --git a/Task/Variables/Go/variables-7.go b/Task/Variables/Go/variables-7.go new file mode 100644 index 0000000000..d459376264 --- /dev/null +++ b/Task/Variables/Go/variables-7.go @@ -0,0 +1,5 @@ +func increase (x int) (more int) { + x++ + more = x+x + return +} diff --git a/Task/Variables/Go/variables-8.go b/Task/Variables/Go/variables-8.go new file mode 100644 index 0000000000..9209ec7917 --- /dev/null +++ b/Task/Variables/Go/variables-8.go @@ -0,0 +1 @@ +x, y := 3, 4 diff --git a/Task/Variables/Haskell/variables-1.hs b/Task/Variables/Haskell/variables-1.hs new file mode 100644 index 0000000000..bb93a9916f --- /dev/null +++ b/Task/Variables/Haskell/variables-1.hs @@ -0,0 +1,11 @@ +foobar = 15 + +f x = x + foobar + where foobar = 15 + +f x = let foobar = 15 + in x + foobar + +f x = do + let foobar = 15 + return $ x + foobar diff --git a/Task/Variables/Haskell/variables-2.hs b/Task/Variables/Haskell/variables-2.hs new file mode 100644 index 0000000000..0f805f4076 --- /dev/null +++ b/Task/Variables/Haskell/variables-2.hs @@ -0,0 +1,7 @@ +main = do + s <- getLine + print (s, s) + +-- The above is equivalent to: + +main = getLine >>= \s -> print (s, s) diff --git a/Task/Variables/Haskell/variables-3.hs b/Task/Variables/Haskell/variables-3.hs new file mode 100644 index 0000000000..8d26828279 --- /dev/null +++ b/Task/Variables/Haskell/variables-3.hs @@ -0,0 +1,4 @@ +funkshun True x = x + 1 +funkshun False x = x - 1 + +foobar = funkshun True 5 + funkshun False 5 -- 6 + 4 diff --git a/Task/Variables/Haskell/variables-4.hs b/Task/Variables/Haskell/variables-4.hs new file mode 100644 index 0000000000..9ca275e9d5 --- /dev/null +++ b/Task/Variables/Haskell/variables-4.hs @@ -0,0 +1,4 @@ +funkshun m = case foo m of + [a, b] -> a - b + a : b : c : rest -> a + b - c + sum rest + a -> sum a diff --git a/Task/Variables/Haskell/variables-5.hs b/Task/Variables/Haskell/variables-5.hs new file mode 100644 index 0000000000..bf2911b172 --- /dev/null +++ b/Task/Variables/Haskell/variables-5.hs @@ -0,0 +1,3 @@ +signum x | x > 0 = 1 + | x < 0 = -1 + | otherwise = 0 diff --git a/Task/Variables/Haskell/variables-6.hs b/Task/Variables/Haskell/variables-6.hs new file mode 100644 index 0000000000..d4a5b9bebd --- /dev/null +++ b/Task/Variables/Haskell/variables-6.hs @@ -0,0 +1,10 @@ +dotProduct :: [Int] -> [Int] -> Int +dotProduct ns ms = sum $ zipWith (+) ns ms +-- Without the type signature, dotProduct would +-- have a more general type. + +foobar :: Num a => a +foobar = 15 +-- Without the type signature, the monomorphism +-- restriction would cause foobar to have a less +-- general type. diff --git a/Task/Variables/HicEst/variables-1.hicest b/Task/Variables/HicEst/variables-1.hicest new file mode 100644 index 0000000000..9fba6b1dab --- /dev/null +++ b/Task/Variables/HicEst/variables-1.hicest @@ -0,0 +1,33 @@ +! Strings and arrays must be declared. +! Everything else is 8-byte float, READ/WRITE converts + CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/ + REAL, PARAMETER :: named_constant = 3.1415 + REAL :: n=2, cols=4, vec(cols), mtx(n, cols) + DATA vec/2,3,4,5/, mtx/1,2,3.1415,4, 5,6,7,8/ + + named = ALIAS(alpha, beta, gamma) ! gamma == named(3) + ALIAS(vec,n, subvec,2) ! share subvec and vec(n...n+1) + ALIAS(str,3, substr,n) ! share substr and str(3:3+n-1) + + a = EXP(b + c) ! assign/initialze a=1, b=0, c=0 + str = "blahblah" ! truncate/expand if needed + beta = "blahblah" ! illegal + + CALL noArguments_noUSE ! global scope SUBROUTINE + CALL Arguments_or_USE(a) ! local scope SUBROUTINE + t = func() ! local scope FUNCTION + +SUBROUTINE noArguments_noUSE() ! all global + vec2 = $ ! 1,2,3,... +END + +SUBROUTINE Arguments_or_USE(var) ! all local + USE : vec ! use global object + var = SUM(vec) + t = TIME() ! local, static, USEd by func() +END + +FUNCTION func() ! all local + USE Arguments_or_USE : t ! use local object + func = t +END diff --git a/Task/Variables/HicEst/variables-2.hicest b/Task/Variables/HicEst/variables-2.hicest new file mode 100644 index 0000000000..42df93c8ff --- /dev/null +++ b/Task/Variables/HicEst/variables-2.hicest @@ -0,0 +1,13 @@ +global gvar # a global + +procedure main(arglist) # arglist is a parameter of main +local a,b,i,x # a, b, i, x are locals withing main +static y # a static (silly in main) + +x := arglist[1] +a := 1.0 +i := 10 +b := [x,a,i,b] + +# ... rest of program +end diff --git a/Task/Variables/J/variables-1.j b/Task/Variables/J/variables-1.j new file mode 100644 index 0000000000..dcbb742512 --- /dev/null +++ b/Task/Variables/J/variables-1.j @@ -0,0 +1 @@ +val=. 0 diff --git a/Task/Variables/J/variables-2.j b/Task/Variables/J/variables-2.j new file mode 100644 index 0000000000..067bb4e558 --- /dev/null +++ b/Task/Variables/J/variables-2.j @@ -0,0 +1,12 @@ +fun =: 3 :0 + val1 =: 0 + val1 =. 2 + val2 =. 3 + val1, val2 +) + fun'' +2 3 + val1 +0 + val2 +|value error diff --git a/Task/Variables/J/variables-3.j b/Task/Variables/J/variables-3.j new file mode 100644 index 0000000000..e4eae69f0f --- /dev/null +++ b/Task/Variables/J/variables-3.j @@ -0,0 +1,6 @@ +fun1 =: 3 :0 + val3=. 0 + val3=: 0 +) + fun1'' +|domain error diff --git a/Task/Variables/J/variables-4.j b/Task/Variables/J/variables-4.j new file mode 100644 index 0000000000..6b3e301ee7 --- /dev/null +++ b/Task/Variables/J/variables-4.j @@ -0,0 +1,5 @@ +fun2 =: 3 :0 + val4=. 0 + 3 :'val4=:y' y +) + fun2 '' diff --git a/Task/Variables/Java/variables-1.java b/Task/Variables/Java/variables-1.java new file mode 100644 index 0000000000..2d0f324718 --- /dev/null +++ b/Task/Variables/Java/variables-1.java @@ -0,0 +1,3 @@ +int a; +double b; +AClassNameHere c; diff --git a/Task/Variables/Java/variables-2.java b/Task/Variables/Java/variables-2.java new file mode 100644 index 0000000000..b60f8c1d7c --- /dev/null +++ b/Task/Variables/Java/variables-2.java @@ -0,0 +1 @@ +int a, b, c; diff --git a/Task/Variables/Java/variables-3.java b/Task/Variables/Java/variables-3.java new file mode 100644 index 0000000000..29dc9d8d73 --- /dev/null +++ b/Task/Variables/Java/variables-3.java @@ -0,0 +1,6 @@ +int a = 5; +double b; +int c = 5, d = 6, e, f; +String x = "test"; +String y = x; +b = 3.14; diff --git a/Task/Variables/Java/variables-4.java b/Task/Variables/Java/variables-4.java new file mode 100644 index 0000000000..a6e7aa2a70 --- /dev/null +++ b/Task/Variables/Java/variables-4.java @@ -0,0 +1,10 @@ +final String x = "blah"; +final String y; +final double[] nums = new double[15]; +y = "test"; +x = "blahblah"; //not legal +nums[5] = 2.5; //legal +nums = new double[10]; //not legal +final Date now = new java.util.Date(); +now.setTime(1234567890); //legal +now = new Date(1234567890); //not legal diff --git a/Task/Variables/JavaScript/variables.js b/Task/Variables/JavaScript/variables.js new file mode 100644 index 0000000000..82e5a05a83 --- /dev/null +++ b/Task/Variables/JavaScript/variables.js @@ -0,0 +1,67 @@ +// a globally-scoped variable +var a=1; + +// global scope +function one(){ + alert(a); +} + +// local scope +function two(a){ + alert(a); +} + +// local scope again +function three(){ + var a = 3; + alert(a); +} + +// Intermediate: no such thing as block scope in javascript +function four(){ + if(true){ + var a=4; + } + + alert(a); // alerts '4', not the global value of '1' +} + + +// Intermediate: object properties +function Five(){ + this.a = 5; +} + + +// Advanced: closure +var six = function(){ + var foo = 6; + + return function(){ + // javascript "closure" means I have access to foo in here, + // because it is defined in the function in which I was defined. + alert(foo); + } +}() + + +// Advanced: prototype-based scope resolution +function Seven(){ + this.a = 7; +} + +// [object].prototype.property loses to [object].property in the scope chain +Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above. +Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor. + + + +// These will print 1-8 +one(); +two(2); +three(); +four(); +alert(new Five().a); +six(); +alert(new Seven().a); +alert(new Seven().b); diff --git a/Task/Variables/Joy/variables-1.joy b/Task/Variables/Joy/variables-1.joy new file mode 100644 index 0000000000..ce128df9a7 --- /dev/null +++ b/Task/Variables/Joy/variables-1.joy @@ -0,0 +1 @@ +[] unstack diff --git a/Task/Variables/Joy/variables-2.joy b/Task/Variables/Joy/variables-2.joy new file mode 100644 index 0000000000..d81cc0710e --- /dev/null +++ b/Task/Variables/Joy/variables-2.joy @@ -0,0 +1 @@ +42 diff --git a/Task/Variables/Joy/variables-3.joy b/Task/Variables/Joy/variables-3.joy new file mode 100644 index 0000000000..b69c73632d --- /dev/null +++ b/Task/Variables/Joy/variables-3.joy @@ -0,0 +1 @@ +stack diff --git a/Task/Variables/Julia/variables-1.julia b/Task/Variables/Julia/variables-1.julia new file mode 100644 index 0000000000..967946d86b --- /dev/null +++ b/Task/Variables/Julia/variables-1.julia @@ -0,0 +1,15 @@ +#declaration/assignment, declaration is optional +x::Int32 = 1 +#datatypes are inferred dynamically, but can also be set thru convert functions and datatype literals +x = 1 #x is inferred as Int, which is Int32 for 32-bit machines, Int64 for 64-bit machines +#variable reference +julia>x +1 + +x = int8(1) #x is of type Int8 +x = 1.0 #x is Float64 +x = y = 1 #assign both x and y to 1 +global x = 1 #assigns 1 to global variable x (used inside scope blocks) +local x = 1 #assigns 1 to local variable x (used inside scope blocks) +x = 'a' #x is a 'Char' type, designated by single quotes +x = "a" #x is a 1-element string, designated by double quotes diff --git a/Task/Variables/Julia/variables-2.julia b/Task/Variables/Julia/variables-2.julia new file mode 100644 index 0000000000..e03c13f05b --- /dev/null +++ b/Task/Variables/Julia/variables-2.julia @@ -0,0 +1,2 @@ +const e = 2.71828182845904523536 +const pi = 3.14159265358979323846 diff --git a/Task/Variables/Liberty-BASIC/variables.liberty b/Task/Variables/Liberty-BASIC/variables.liberty new file mode 100644 index 0000000000..7d80dbca20 --- /dev/null +++ b/Task/Variables/Liberty-BASIC/variables.liberty @@ -0,0 +1,29 @@ +'In Liberty BASIC variables are either string or numeric. +'A variable name can start with any letter and it can contain both letters and numerals, as well as dots (for example: user.firstname). +'There is no practical limit to the length of a variable name... up to ~2M characters. +'The variable names are case sensitive. + +'assignments: -numeric variables. LB assumes integers unless assigned or calculated otherwise. +'Because of its Smalltalk heritage, LB integers are of arbitrarily long precision. +'They lose this if a calculation yields a non-integer, switching to floating point. + i = 1 + r = 3.14 + +'assignments -string variables. Any string-length, from zero to ~2M. + t$ ="21:12:45" + flag$ ="TRUE" + +'assignments -1D or 2D arrays +'A default array size of 10 is available. Larger arrays need pre-'DIM'ming. + height( 3) =1.87 + dim height( 50) + height( 23) =123.5 + potential( 3, 5) =4.5 + name$( 4) ="John" + +'There are no Boolean /bit variables as such. + +'Arrays in a main program are global. +'However variables used in the main program code are not visible inside functions and subroutines. +'They can be declared 'global' if such visibility is desired. +'Functions can receive variables by name or by reference. diff --git a/Task/Variables/Logo/variables.logo b/Task/Variables/Logo/variables.logo new file mode 100644 index 0000000000..6110e3ef3d --- /dev/null +++ b/Task/Variables/Logo/variables.logo @@ -0,0 +1,20 @@ +make "g1 0 +name 2 "g2 ; same as make with parameters reversed +global "g3 ; no initial value +to func :x + make "g4 4 ; still global + localmake "L1 6 + local ["L2 "L3] ; local variables, collection syntax + func2 :g4 + print :L2 ; 9, modified by func2 + print :L3 ; L3 has no value, was not modified by func2 +end +to func2 :y + make "g3 :y + make "L2 :L1 + 3 ; dynamic scope: can see variables of callers + localmake "L3 5 ; locally override L3 from caller + (print :y :L1 :L2 :L3) ; 4 6 9 5 +end +print :g4 ; 4 +print :L1 ; L1 has no value +print name? "L1 ; false, L1 is not bound in the current scope diff --git a/Task/Variables/LotusScript/variables.lotusscript b/Task/Variables/LotusScript/variables.lotusscript new file mode 100644 index 0000000000..b9ab125bf6 --- /dev/null +++ b/Task/Variables/LotusScript/variables.lotusscript @@ -0,0 +1,12 @@ +Sub Click() +'a few declarations as example +Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession +Dim i as Integer ' i = 0 +Dim s as String ' s= "" +Dim v as Variant ' v is nothing +Dim l as Long ' l = 0 +Dim doc as NotesDocument 'doc is EMTPY + +'... + +End Sub diff --git a/Task/Variables/Lua/variables-1.lua b/Task/Variables/Lua/variables-1.lua new file mode 100644 index 0000000000..0ba1649570 --- /dev/null +++ b/Task/Variables/Lua/variables-1.lua @@ -0,0 +1,4 @@ +a = 1 -- Here we declare a numeric variable +fruit = "banana" -- Here we declare a string datatype +needspeeling = True -- This is a boolean +local b = 2 -- This variable declaration is prefixed with a scope modifier diff --git a/Task/Variables/Lua/variables-2.lua b/Task/Variables/Lua/variables-2.lua new file mode 100644 index 0000000000..b538656bea --- /dev/null +++ b/Task/Variables/Lua/variables-2.lua @@ -0,0 +1 @@ +A, B, C, D, E = 2, 4, 6, 8, "It's never too late" diff --git a/Task/Variables/MATLAB/variables-1.m b/Task/Variables/MATLAB/variables-1.m new file mode 100644 index 0000000000..43269922f0 --- /dev/null +++ b/Task/Variables/MATLAB/variables-1.m @@ -0,0 +1,17 @@ + a = 4; % declare variable and initialize double value, + s = 'abc'; % string + i8 = int8(5); % signed byte + u8 = uint8(5); % unsigned byte + i16 = int16(5); % signed 2 byte + u16 = uint16(5); % unsigned 2 byte integer + i32 = int32(5); % signed 4 byte integer + u32 = uint32(5);% unsigned 4 byte integers + i64 = int64(5); % signed 8 byte integer + u64 = uint64(5);% unsigned 8 byte integer + f32 = float32(5); % single precission floating point number + f64 = float64(5); % double precission floating point number , float 64 is the default data type. + + c = 4+5i; % complex number + colvec = [1;2;4]; % column vector + crowvec = [1,2,4]; % row vector + m = [1,2,3;4,5,6]; % matrix with size 2x3 diff --git a/Task/Variables/MATLAB/variables-2.m b/Task/Variables/MATLAB/variables-2.m new file mode 100644 index 0000000000..d45006c4c0 --- /dev/null +++ b/Task/Variables/MATLAB/variables-2.m @@ -0,0 +1 @@ + global b diff --git a/Task/Variables/Modula-3/variables-1.mod3 b/Task/Variables/Modula-3/variables-1.mod3 new file mode 100644 index 0000000000..e761f30988 --- /dev/null +++ b/Task/Variables/Modula-3/variables-1.mod3 @@ -0,0 +1,15 @@ +MODULE Foo EXPORTS Main; + +IMPORT IO, Fmt; + +VAR foo: INTEGER := 5; (* foo is global (to the module). *) + +PROCEDURE Foo() = + VAR bar: INTEGER := 10; (* bar is local to the procedure Foo. *) + BEGIN + IO.Put("foo + bar = " & Fmt.Int(foo + bar) & "\n"); + END Foo; + +BEGIN + Foo(); +END Foo. diff --git a/Task/Variables/Modula-3/variables-2.mod3 b/Task/Variables/Modula-3/variables-2.mod3 new file mode 100644 index 0000000000..94250c8f14 --- /dev/null +++ b/Task/Variables/Modula-3/variables-2.mod3 @@ -0,0 +1 @@ +PROCEDURE Foo(n: INTEGER) = diff --git a/Task/Variables/Modula-3/variables-3.mod3 b/Task/Variables/Modula-3/variables-3.mod3 new file mode 100644 index 0000000000..5f33a66c2f --- /dev/null +++ b/Task/Variables/Modula-3/variables-3.mod3 @@ -0,0 +1 @@ +PROCEDURE Foo(VAR n: INTEGER) = diff --git a/Task/Variables/OCaml/variables-1.ocaml b/Task/Variables/OCaml/variables-1.ocaml new file mode 100644 index 0000000000..0c887fff86 --- /dev/null +++ b/Task/Variables/OCaml/variables-1.ocaml @@ -0,0 +1 @@ +let x = 28 diff --git a/Task/Variables/OCaml/variables-2.ocaml b/Task/Variables/OCaml/variables-2.ocaml new file mode 100644 index 0000000000..b28f7d1de0 --- /dev/null +++ b/Task/Variables/OCaml/variables-2.ocaml @@ -0,0 +1 @@ +let y = ref 28 diff --git a/Task/Variables/OCaml/variables-3.ocaml b/Task/Variables/OCaml/variables-3.ocaml new file mode 100644 index 0000000000..7a6fc8d3bd --- /dev/null +++ b/Task/Variables/OCaml/variables-3.ocaml @@ -0,0 +1,2 @@ + !y (* access *) + y := 34 (* modification *) diff --git a/Task/Variables/OCaml/variables-4.ocaml b/Task/Variables/OCaml/variables-4.ocaml new file mode 100644 index 0000000000..f5839dab83 --- /dev/null +++ b/Task/Variables/OCaml/variables-4.ocaml @@ -0,0 +1,9 @@ +let sum = (* sum is bound to 181 *) + let a = 31 + and b = 150 in + (a + b) + +let sum () = (* sum is a function which returns 181 *) + let a = 31 + and b = 150 in + (a + b) diff --git a/Task/Variables/Objeck/variables.objeck b/Task/Variables/Objeck/variables.objeck new file mode 100644 index 0000000000..52ddbffeaf --- /dev/null +++ b/Task/Variables/Objeck/variables.objeck @@ -0,0 +1,3 @@ +a : Int; +b : Int := 13; +c := 7; diff --git a/Task/Variables/Openscad/variables.scad b/Task/Variables/Openscad/variables.scad new file mode 100644 index 0000000000..724fcb547f --- /dev/null +++ b/Task/Variables/Openscad/variables.scad @@ -0,0 +1 @@ +mynumber=5+4; // This gives a value of nine diff --git a/Task/Variables/Oz/variables-1.oz b/Task/Variables/Oz/variables-1.oz new file mode 100644 index 0000000000..ebaf4e47a0 --- /dev/null +++ b/Task/Variables/Oz/variables-1.oz @@ -0,0 +1,7 @@ +declare +Var %% new variable Var, initially free +{Show Var} +Var = 42 %% now Var has the value 42 +{Show Var} +Var = 42 %% the same value is assigned again: ok +Var = 43 %% a different value is assigned: exception diff --git a/Task/Variables/Oz/variables-10.oz b/Task/Variables/Oz/variables-10.oz new file mode 100644 index 0000000000..8652e1da9a --- /dev/null +++ b/Task/Variables/Oz/variables-10.oz @@ -0,0 +1,10 @@ +declare + V = 42 +in + {Wait V} %% explicitly wait for V to become determined + + if {IsDet V} then %% check whether V is determined; not recommended + {Show determined} + elseif {IsFree V} then %% check whether V is free; not recommended + {Show free} + end diff --git a/Task/Variables/Oz/variables-11.oz b/Task/Variables/Oz/variables-11.oz new file mode 100644 index 0000000000..b1ccf82921 --- /dev/null +++ b/Task/Variables/Oz/variables-11.oz @@ -0,0 +1,7 @@ +declare + A = {NewCell 42} + OldVal +in + {Show @A} %% read a cell with @ + A := 43 %% change its value + OldVal = A := 44 %% read and write at the same time (atomically) diff --git a/Task/Variables/Oz/variables-2.oz b/Task/Variables/Oz/variables-2.oz new file mode 100644 index 0000000000..34c1a6e273 --- /dev/null +++ b/Task/Variables/Oz/variables-2.oz @@ -0,0 +1,6 @@ +declare + A = 3 + B +in + A = B + {Show B} diff --git a/Task/Variables/Oz/variables-3.oz b/Task/Variables/Oz/variables-3.oz new file mode 100644 index 0000000000..4b4a002535 --- /dev/null +++ b/Task/Variables/Oz/variables-3.oz @@ -0,0 +1,5 @@ +declare + A = 3 + A = B %% Error: variable B not introduced +in + {Show B} diff --git a/Task/Variables/Oz/variables-4.oz b/Task/Variables/Oz/variables-4.oz new file mode 100644 index 0000000000..aeb47bfa00 --- /dev/null +++ b/Task/Variables/Oz/variables-4.oz @@ -0,0 +1,2 @@ +declare + [A B C D] = [1 2 3 4] %% unification of two lists diff --git a/Task/Variables/Oz/variables-5.oz b/Task/Variables/Oz/variables-5.oz new file mode 100644 index 0000000000..6271e164bb --- /dev/null +++ b/Task/Variables/Oz/variables-5.oz @@ -0,0 +1,9 @@ +functor +export Function +define + ToplevelVariable = 42 + + fun {Function} + 42 + end +end diff --git a/Task/Variables/Oz/variables-6.oz b/Task/Variables/Oz/variables-6.oz new file mode 100644 index 0000000000..80476e4e81 --- /dev/null +++ b/Task/Variables/Oz/variables-6.oz @@ -0,0 +1,15 @@ +fun {Function Arg} + LocalVar1 +in + LocalVar1 = if Arg == 42 then + LocalVar2 + in + LocalVar2 = yes + LocalVar2 + else + LocalVar3 = no %% variables can be initialized when declared + in + LocalVar3 + end + LocalVar1 +end diff --git a/Task/Variables/Oz/variables-7.oz b/Task/Variables/Oz/variables-7.oz new file mode 100644 index 0000000000..25df5dc437 --- /dev/null +++ b/Task/Variables/Oz/variables-7.oz @@ -0,0 +1,8 @@ +if {IsEven 42} then + {System.showInfo "Here, LocalVar is not visible."} + local + LocalVar = "Here, LocalVar IS visible" + in + {System.showInfo LocalVar} + end +end diff --git a/Task/Variables/Oz/variables-8.oz b/Task/Variables/Oz/variables-8.oz new file mode 100644 index 0000000000..05c494ad76 --- /dev/null +++ b/Task/Variables/Oz/variables-8.oz @@ -0,0 +1 @@ +case "Rosetta code" of First|_ then {Show First} end %% prints "R" diff --git a/Task/Variables/Oz/variables-9.oz b/Task/Variables/Oz/variables-9.oz new file mode 100644 index 0000000000..928d3f81a1 --- /dev/null +++ b/Task/Variables/Oz/variables-9.oz @@ -0,0 +1,8 @@ +declare + A + B = !!A %% B is a read-only view of A +in + thread + B = 43 %% this blocks until A is known; then it fails because 43 \= 42 + end + A = 42 diff --git a/Task/Variables/PARI-GP/variables-1.pari b/Task/Variables/PARI-GP/variables-1.pari new file mode 100644 index 0000000000..6f00367a0c --- /dev/null +++ b/Task/Variables/PARI-GP/variables-1.pari @@ -0,0 +1 @@ +'x diff --git a/Task/Variables/PARI-GP/variables-2.pari b/Task/Variables/PARI-GP/variables-2.pari new file mode 100644 index 0000000000..e00f2688c2 --- /dev/null +++ b/Task/Variables/PARI-GP/variables-2.pari @@ -0,0 +1 @@ +'x^3+7 diff --git a/Task/Variables/PHP/variables.php b/Task/Variables/PHP/variables.php new file mode 100644 index 0000000000..9003230a9d --- /dev/null +++ b/Task/Variables/PHP/variables.php @@ -0,0 +1,162 @@ + + */ + + +/* + * PHP is a weak typed language, + * no separation between variable declaration, initialization and assignment. + * + * variable type is defined by the value that is assigned to it. + * a variable name must start with a "$" sign (called "sigil", not a dollar sign). + * variable naming rules: + * + case-sensitive. + * + first character after $ must not be a number. + * + after the first character all alphanumeric chars and _(underscore) sign is allowed, e.g. $i_am_a_new_var_with_the_number_0 + * + */ + +# NULL typed variable +$null = NULL; var_dump($null); // output: null + +# defining a boolean +$boolean = true; var_dump($boolean); // output: boolean true +$boolean = false; var_dump($boolean); // output: boolean false + +/* + * casting is made using (TYPE) as a prefix + */ +# bool and boolean is the same +$boolean = (bool)1; var_dump($boolean); // output: boolean true +$boolean = (boolean)1; var_dump($boolean); // output: boolean true + +$boolean = (bool)0; var_dump($boolean); // output: boolean false +$boolean = (boolean)0; var_dump($boolean); // output: boolean false + +# defining an integer +$int = 0; var_dump($int); // output: int 0 + +# defining a float, +$float = 0.01; var_dump($float); // output: float 0.01 + +# which is also identical to "real" and "double" +var_dump((double)$float); // output: float 0.01 +var_dump((real)$float); // output: float 0.01 + +# casting back to int (auto flooring the value) +var_dump((int)$float); // output: int 0 +var_dump((int)($float+1)); // output: int 1 +var_dump((int)($float+1.9)); // output: int 1 + +# defining a string +$string = 'string'; +var_dump($string); // output: string 'string' (length=6) + +# referencing a variable (there are no pointers in PHP). +$another_string = &$string; +var_dump($another_string); + // output: string 'string' (length=6) + +$string = "I'm the same string!"; +var_dump($another_string); + // output: string 'I'm the same string!' (length=20) +# "deleting" a variable from memory +unset($another_string); + +$string = 'string'; +/* + * a string can also be defined with double-quotes, HEREDOC and NOWDOC operators. + * content inside double-quotes is being parsed before assignment. + * concatenation operator is .= + */ +$parsed_string = "This is a $string"; +var_dump($parsed_string); + // output: string 'This is a string' (length=16) +$parsed_string .= " with another {$string}"; +var_dump($parsed_string); + // output: string 'This is a string with another string' (length=36) + +# with string parsing +$heredoc = << standard class +$stdObject = new stdClass(); var_dump($stdObject); + // output: object(stdClass)[1] +# defining an object typed Foo +class Foo {} +$foo = new Foo(); var_dump($foo); + // output: object(Foo)[2] +# defining an empty array +$array = array(); var_dump($array); + // output: array {empty} + +/* + * an array with non-integer key is also considered as an associative array(i.e. hash table) + * can contain mixed variable types, can contain integer based keys and non-integer keys + */ +$assoc = array( + 0 => $int, + 'integer' => $int, + 1 => $float, + 'float' => $float, + 2 => $string, + 'string' => $string, + 3 => NULL, // <=== key 3 is NULL + 3, // <=== this is a value, not a key (key is 4) + 5 => $stdObject, + 'Foo' => $foo, +); +var_dump($assoc); + +// output: +// ======= +// array +// 0 => int 0 +// 'integer' => int 0 +// 1 => float 0.01 +// 'float' => float 0.01 +// 2 => string 'string' (length=6) +// 'string' => string 'string' (length=6) +// 3 => null +// 4 => int 3 +// 5 => +// object(stdClass)[1] +// 'Foo' => +// object(Foo)[2] + + + +/* + * all variables are "global" but not reachable inside functions(unless specifically "globalized" inside) + */ + +function a_function() +{ + # not reachable + var_dump(isset($foo)); // output: boolean false + + global $foo; + # "global" (reachable) inside a_function()'s scope + var_dump(isset($foo)); // output: boolean true +} + +a_function(); + +/** + * there is another special type of variable called (Resource). + * for more info regarding Resources: + * @url http://php.net/manual/en/language.types.resource.php + * @url http://php.net/manual/en/resource.php + */ diff --git a/Task/Variables/PL-I/variables.pli b/Task/Variables/PL-I/variables.pli new file mode 100644 index 0000000000..580c4bd54f --- /dev/null +++ b/Task/Variables/PL-I/variables.pli @@ -0,0 +1,22 @@ +/* The PROCEDURE block and BEGIN block are used to delimit scopes. */ + +declare i float; /* external, global variable, excluded from the */ + /* local ares (BEGIN block) below. */ +begin; + declare (i, j) fixed binary; /* local variable */ + get list (i, j); + put list (i,j); +end; + +/* Examples of initialization. */ + +declare p fixed initial (25); +declare q(7) fixed initial (9, 3, 5, 1, 2, 8, 15); + /* sets all elements of array Q at run time, on block entry. */ +declare r(7) fixed initial (9, 3, 5, 1, 2, 8, 15); + /* sets all elements of array R at compile time. */ + +p = 44; /* run-time assignment. */ +q = 0; /* run-time initialization of all elements of Q to zero. */ +q = r; /* run-time assignment of all elements of array R to */ + /* corresponding elemets of S. */ diff --git a/Task/Variables/Perl-6/variables-1.pl6 b/Task/Variables/Perl-6/variables-1.pl6 new file mode 100644 index 0000000000..2159b4448e --- /dev/null +++ b/Task/Variables/Perl-6/variables-1.pl6 @@ -0,0 +1,5 @@ +my @y =
; #Array of strings 'A', 'B', 'C', and 'D' + +my $x = @y; # $x is now a reference for the array @y + +say $x[1]; # prints 'B' follow by a newline character diff --git a/Task/Variables/Perl-6/variables-2.pl6 b/Task/Variables/Perl-6/variables-2.pl6 new file mode 100644 index 0000000000..c4f6701ac8 --- /dev/null +++ b/Task/Variables/Perl-6/variables-2.pl6 @@ -0,0 +1,14 @@ + # $x can contain only Int objects + my Int $x; + + # $x can only contain native integers (not integer objects) + my int $x; + + #A variable may itself be bound to a container type that specifies how the container works, without specifying what kinds of things it contains. + # $x is implemented by the MyScalar class + my $x is MyScalar; + + #Constraints and container types can be used together: + # $x can contain only Int objects, + # and is implemented by the MyScalar class + my Int $x is MyScalar; diff --git a/Task/Variables/Perl/variables-1.pl b/Task/Variables/Perl/variables-1.pl new file mode 100644 index 0000000000..f2194f870f --- /dev/null +++ b/Task/Variables/Perl/variables-1.pl @@ -0,0 +1,6 @@ +sub dofruit { + $fruit='apple'; +} + +dofruit; +print "The fruit is $fruit"; diff --git a/Task/Variables/Perl/variables-2.pl b/Task/Variables/Perl/variables-2.pl new file mode 100644 index 0000000000..b98a5b624c --- /dev/null +++ b/Task/Variables/Perl/variables-2.pl @@ -0,0 +1,10 @@ +my $x = @a; # Scalar assignment; $x is set to the + # number of elements in @a. +my ($x) = @a; # List assignment; $x is set to the first + # element of @a. +my @b = @a; # List assignment; @b becomes the same length + # as @a and each element becomes the same. +my ($x, $y, @b) = @a; # List assignment; $x and $y get the first + # two elements of @a, and @b the rest. +my ($x, $y, @b, @c, $z) = @a; # Same thing, and also @c becomes empty + # and $z undefined. diff --git a/Task/Variables/Perl/variables-3.pl b/Task/Variables/Perl/variables-3.pl new file mode 100644 index 0000000000..6b9d906c24 --- /dev/null +++ b/Task/Variables/Perl/variables-3.pl @@ -0,0 +1,3 @@ +use strict; +our $fruit; # declare a variable as global +our $veg = "carrot"; # declare a global variable and define its value diff --git a/Task/Variables/Perl/variables-4.pl b/Task/Variables/Perl/variables-4.pl new file mode 100644 index 0000000000..ada28c38ed --- /dev/null +++ b/Task/Variables/Perl/variables-4.pl @@ -0,0 +1,10 @@ +$fruit="apple"; # this will be global by default + +sub dofruit { + print "My global fruit was $fruit,"; # use the global variable + my $fruit="banana"; # declare a new local variable + print "and the local fruit is $fruit.\n"; +} + +dofruit; +print "The global fruit is still $fruit"; diff --git a/Task/Variables/PicoLisp/variables-1.l b/Task/Variables/PicoLisp/variables-1.l new file mode 100644 index 0000000000..9d1174899f --- /dev/null +++ b/Task/Variables/PicoLisp/variables-1.l @@ -0,0 +1,3 @@ +(use (A B C) + (setq A 1 B 2 C 3) + ... ) diff --git a/Task/Variables/PicoLisp/variables-2.l b/Task/Variables/PicoLisp/variables-2.l new file mode 100644 index 0000000000..c1b942740a --- /dev/null +++ b/Task/Variables/PicoLisp/variables-2.l @@ -0,0 +1,2 @@ +(let (A 1 B 2 C 3) + ... ) diff --git a/Task/Variables/PicoLisp/variables-3.l b/Task/Variables/PicoLisp/variables-3.l new file mode 100644 index 0000000000..5e46a96d2b --- /dev/null +++ b/Task/Variables/PicoLisp/variables-3.l @@ -0,0 +1,6 @@ +(use A + (setq A ..) + ... ) + +(let A 1 + ...) diff --git a/Task/Variables/PowerShell/variables-1.psh b/Task/Variables/PowerShell/variables-1.psh new file mode 100644 index 0000000000..89cb34393f --- /dev/null +++ b/Task/Variables/PowerShell/variables-1.psh @@ -0,0 +1,2 @@ +$s = "abc" +$i = 123 diff --git a/Task/Variables/PowerShell/variables-2.psh b/Task/Variables/PowerShell/variables-2.psh new file mode 100644 index 0000000000..fb48339ad5 --- /dev/null +++ b/Task/Variables/PowerShell/variables-2.psh @@ -0,0 +1,2 @@ +4 + $foo # yields 4 +"abc" + $foo + "def" # yields "abcdef" diff --git a/Task/Variables/PowerShell/variables-3.psh b/Task/Variables/PowerShell/variables-3.psh new file mode 100644 index 0000000000..f055177dcf --- /dev/null +++ b/Task/Variables/PowerShell/variables-3.psh @@ -0,0 +1 @@ +Get-ChildItem Variable: diff --git a/Task/Variables/PowerShell/variables-4.psh b/Task/Variables/PowerShell/variables-4.psh new file mode 100644 index 0000000000..ecdf3ba52f --- /dev/null +++ b/Task/Variables/PowerShell/variables-4.psh @@ -0,0 +1 @@ +Remove-Item Variable:foo diff --git a/Task/Variables/PowerShell/variables-5.psh b/Task/Variables/PowerShell/variables-5.psh new file mode 100644 index 0000000000..8335695f7e --- /dev/null +++ b/Task/Variables/PowerShell/variables-5.psh @@ -0,0 +1,5 @@ +Get-Variable # retrieves the value of a variable +New-Variable # creates a new variable +Set-Variable # sets the value of a variable +Clear-Variable # deletes the value of a variable, but not the variable itself +Remove-Variable # deletes a variable completely diff --git a/Task/Variables/PureBasic/variables.purebasic b/Task/Variables/PureBasic/variables.purebasic new file mode 100644 index 0000000000..1f3968a938 --- /dev/null +++ b/Task/Variables/PureBasic/variables.purebasic @@ -0,0 +1,47 @@ +; Variables are initialized when they appear in sourcecode with default value of 0 and type int +Debug a +; or value "" for a string, they are not case sensitive +Debug b$ +; This initializes a double precision float, if type is following the dot +Debug c.d +; They can be initialized with define (double precision float, string, integer) +Define d.d = 3.5, e$ = "Test", f.i = a + 2 +; Define can have a default type (all bytes except j which is long): +Define.b g, h, j.l +; Define without following variables sets default type. In this case to single precision float +Define.f +; So this will be an single precision float and no integer +Debug k +; EnableExplicit forces declaration of used variables with define +EnableExplicit +; Will throw an error because L isn't initialized +Debug L +DisableExplicit +; Global Variables are available in Procedures and Threads too +Global M = 3, N = 2 +Procedure Dummy(parameter1, parameter2 = 20) + ; Parameter contain values which where used when calling the function, + ; their types have to be specified in the above Procedure header. + ; The last ones can have default values which get applied if this parameter is not given. + + ; Variables in Procedures are separate from those outside, + ; so d can be initialized again with another type + ; which would otherwise lead to an error + d.i + ; Protected makes a variable local even if another one with same name is declared as global (see above) + Protected M = 2 + ; Shares a variable with main program like it was declared by global + Shared a + ; prevents a variable to be initialized with default value again when procedure is called a second time, + ; could be used for example as a counter, which contains the number of times a function was called + Static a + ; N here also would have a value of 2, while for example + ; f would, when named, initialize a new variable, and so have a value of 0 +EndProcedure +; finally there are constants which are prefixed by an #: +#Test = 1 +; Their value cannot be changed while program is running +#String_Constant = "blubb" +; In constrast to variables, a constant has no types except an (optional) $ sign to mark it as string constant +#Float_Constant = 2.3 +; Maps, LinkedLists , Arrays and Structures are not handled here, because they are no elemental variables diff --git a/Task/Variables/R/variables-1.r b/Task/Variables/R/variables-1.r new file mode 100644 index 0000000000..cf9f74066d --- /dev/null +++ b/Task/Variables/R/variables-1.r @@ -0,0 +1,2 @@ +foo <- 3.4 +bar = "abc" diff --git a/Task/Variables/R/variables-2.r b/Task/Variables/R/variables-2.r new file mode 100644 index 0000000000..a104eaee0a --- /dev/null +++ b/Task/Variables/R/variables-2.r @@ -0,0 +1,2 @@ +baz <- quux <- 1:10 +TRUE -> quuux diff --git a/Task/Variables/R/variables-3.r b/Task/Variables/R/variables-3.r new file mode 100644 index 0000000000..108c25c716 --- /dev/null +++ b/Task/Variables/R/variables-3.r @@ -0,0 +1,15 @@ +a <- 3 + +assignmentdemo <- function() +{ + message("assign 'a' locally, i.e. within the scope of the function") + a <- 5 + message(paste("inside assignmentdemo, a = ", a)) + message(paste("in the global environment, a = ", get("a", envir=globalenv()))) + + message("assign 'a' globally") + a <<- 7 + message(paste("inside assignmentdemo, a = ", a)) + message(paste("in the global environment, a = ", get("a", envir=globalenv()))) +} +assignmentdemo() diff --git a/Task/Variables/R/variables-4.r b/Task/Variables/R/variables-4.r new file mode 100644 index 0000000000..ab18a600da --- /dev/null +++ b/Task/Variables/R/variables-4.r @@ -0,0 +1,2 @@ +assign("b", TRUE) #equivalent to b <- TRUE +assign("c", runif(10), envir=globalenv()) #equivalent to c <<- runif(10) diff --git a/Task/Variables/REXX/variables-1.rexx b/Task/Variables/REXX/variables-1.rexx new file mode 100644 index 0000000000..da739fe8e4 --- /dev/null +++ b/Task/Variables/REXX/variables-1.rexx @@ -0,0 +1,10 @@ +aa = 10 /*assigns chars 10 ───► AA */ +bb = '' /*assigns a null value ───► BB */ +cc = 2*10 /*assigns charser 20 ───► CC */ +dd = 'Adam' /*assigns chars Adam ───► DD */ +ee = "Adam" /*same as above ───► EE */ +ff = 10. /*assigns chars 10. ───► FF */ +gg = '10.' /*same as above ───► GG */ +hh = "+10" /*assigns chars +10 ───► hh */ +ii = 1e1 /*assigns chars 1e1 ───► ii */ +jj = +.1e+2 /*assigns chars +.1e+2 ───► jj */ diff --git a/Task/Variables/REXX/variables-2.rexx b/Task/Variables/REXX/variables-2.rexx new file mode 100644 index 0000000000..21e6c5d712 --- /dev/null +++ b/Task/Variables/REXX/variables-2.rexx @@ -0,0 +1,12 @@ +kk = '123'x /*assigns hex 00000123 ───► KK */ +kk = 'dead beaf'X /*assigns hex deadbeaf ───► KK */ +ll = '0000 0010'b /*assigns blank ───► LL (ASCII) */ +mm = '0000 0100'B /*assigns blank ───► MM (EBCDIC)*/ + +xxx = '11 2. 333 -5' +parse var xxx nn oo pp qq rr + /*assigns 11 ───► NN */ + /*assigns 2. ───► OO */ + /*assigns 333 ───► PP */ + /*assigns ─5 ───► QQ */ + /*assigns "null" ───► RR */ diff --git a/Task/Variables/REXX/variables-3.rexx b/Task/Variables/REXX/variables-3.rexx new file mode 100644 index 0000000000..e40a416983 --- /dev/null +++ b/Task/Variables/REXX/variables-3.rexx @@ -0,0 +1,20 @@ +/*REXX pgm to do a "bad" assignment (with an unassigned REXX variable).*/ + +signal on novalue /*usually, placed at pgm start. */ + +xxx=aaaaa /*tries to assign aaaaa ───► xxx */ + +say xxx 'or somesuch' +exit + +novalue: /*this can be dressed up better. */ +badLine =sigl /*REXX statement num that failed.*/ +badSource=sourceline(badLine) /*REXX source statement ··· */ +badVar =condition('D') /*REXX var name that's ¬ defined.*/ +say +say '*** error! ***' +say 'undefined variable' badvar "at REXX statement number" badLine +say +say badSource +say +exit 13 diff --git a/Task/Variables/Rascal/variables-1.rascal b/Task/Variables/Rascal/variables-1.rascal new file mode 100644 index 0000000000..407fbba72d --- /dev/null +++ b/Task/Variables/Rascal/variables-1.rascal @@ -0,0 +1 @@ + Type Name = Exp; diff --git a/Task/Variables/Rascal/variables-2.rascal b/Task/Variables/Rascal/variables-2.rascal new file mode 100644 index 0000000000..3e7ef148a0 --- /dev/null +++ b/Task/Variables/Rascal/variables-2.rascal @@ -0,0 +1 @@ +Type Name; diff --git a/Task/Variables/Rascal/variables-3.rascal b/Task/Variables/Rascal/variables-3.rascal new file mode 100644 index 0000000000..52cd97af45 --- /dev/null +++ b/Task/Variables/Rascal/variables-3.rascal @@ -0,0 +1,4 @@ +rascal>int max = 100; +int: 100 +rascal>min = 0; +int: 0 diff --git a/Task/Variables/Rascal/variables-4.rascal b/Task/Variables/Rascal/variables-4.rascal new file mode 100644 index 0000000000..2f02e65edb --- /dev/null +++ b/Task/Variables/Rascal/variables-4.rascal @@ -0,0 +1,11 @@ +rascal>day = {<"mon", 1>, <"tue", 2>, <"wed",3>, +>>>>>>> <"thu", 4>, <"fri", 5>, <"sat",6>, <"sun",7>}; +rel[str, int]: { + <"thu",4>, + <"mon",1>, + <"sat",6>, + <"wed",3>, + <"tue",2>, + <"fri",5>, + <"sun",7> +} diff --git a/Task/Variables/Rascal/variables-5.rascal b/Task/Variables/Rascal/variables-5.rascal new file mode 100644 index 0000000000..5db31c9b68 --- /dev/null +++ b/Task/Variables/Rascal/variables-5.rascal @@ -0,0 +1,4 @@ +rascal>int month = 12; +int: 12 +rascal>month ="December"; +|stdin:///|(7,10,<1,7>,<1,17>): Expected int, but got str diff --git a/Task/Variables/Rascal/variables-6.rascal b/Task/Variables/Rascal/variables-6.rascal new file mode 100644 index 0000000000..a06c6f822d --- /dev/null +++ b/Task/Variables/Rascal/variables-6.rascal @@ -0,0 +1,4 @@ +rascal>if( 4 > 3){ x = "abc"; } else { x = "def";} +str: "abc" +rascal>x; +|stdin:///|(0,1,<1,0>,<1,1>): Undeclared variable, function or constructor: x diff --git a/Task/Variables/Ruby/variables.rb b/Task/Variables/Ruby/variables.rb new file mode 100644 index 0000000000..556c7e6217 --- /dev/null +++ b/Task/Variables/Ruby/variables.rb @@ -0,0 +1,11 @@ +$a_global_var = 5 +class Demo + @@a_class_var = 6 + A_CONSTANT = 8 + def initialize + @an_instance_var = 7 + end + def incr(a_local_var) + @an_instance_var += a_local_var + end +end diff --git a/Task/Variables/SNOBOL4/variables.sno b/Task/Variables/SNOBOL4/variables.sno new file mode 100644 index 0000000000..b5da628f6e --- /dev/null +++ b/Task/Variables/SNOBOL4/variables.sno @@ -0,0 +1,4 @@ + define('foo(x,y)a,b,c') :(foo_end) +foo a = 1; b = 2; c = 3 + foo = a * ( x * x ) + b * y + c :(return) +foo_end diff --git a/Task/Variables/Seed7/variables.seed7 b/Task/Variables/Seed7/variables.seed7 new file mode 100644 index 0000000000..1e25a029d3 --- /dev/null +++ b/Task/Variables/Seed7/variables.seed7 @@ -0,0 +1,15 @@ +$ include "seed7_05.s7i"; + +var integer: foo is 5; # foo is global + +const proc: aFunc is func + local + var integer: bar is 10; # bar is local to aFunc + begin + writeln("foo + bar = " <& foo + bar); + end func; + +const proc: main is func + begin + aFunc; + end func; diff --git a/Task/Variables/TI-83-BASIC/variables.ti-83 b/Task/Variables/TI-83-BASIC/variables.ti-83 new file mode 100644 index 0000000000..16ae7045ce --- /dev/null +++ b/Task/Variables/TI-83-BASIC/variables.ti-83 @@ -0,0 +1 @@ +:1→A diff --git a/Task/Variables/TI-89-BASIC/variables-1.ti-89 b/Task/Variables/TI-89-BASIC/variables-1.ti-89 new file mode 100644 index 0000000000..a26f217a45 --- /dev/null +++ b/Task/Variables/TI-89-BASIC/variables-1.ti-89 @@ -0,0 +1 @@ +Local mynum, myfunc diff --git a/Task/Variables/TI-89-BASIC/variables-2.ti-89 b/Task/Variables/TI-89-BASIC/variables-2.ti-89 new file mode 100644 index 0000000000..65d9731333 --- /dev/null +++ b/Task/Variables/TI-89-BASIC/variables-2.ti-89 @@ -0,0 +1,13 @@ +Define mynum = 1 © Two ways to assign a number +1 → mynum + +Define myfunc(x) = (sin(x))^2 © Two ways to assign a function +(sin(x))^2 → myfunc(x) + +Define myfunc(x) = Func © Multi-statement function + If x < 0 Then + Return –x + Else + Return x + EndIf +EndFunc diff --git a/Task/Variables/TUSCRIPT/variables.tuscript b/Task/Variables/TUSCRIPT/variables.tuscript new file mode 100644 index 0000000000..416e34f926 --- /dev/null +++ b/Task/Variables/TUSCRIPT/variables.tuscript @@ -0,0 +1,15 @@ +$$ MODE TUSCRIPT,{} +var1=1, var2="b" +PRINT "var1=",var1 +PRINT "var2=",var2 + +basket=* +DATA apples +DATA bananas +DATA cherry + +LOOP n,letter="a'b'c",fruit=basket +var=CONCAT (letter,n) +SET @var=VALUE(fruit) +PRINT var,"=",@var +ENDLOOP diff --git a/Task/Variables/TXR/variables-1.txr b/Task/Variables/TXR/variables-1.txr new file mode 100644 index 0000000000..d91ee2a2aa --- /dev/null +++ b/Task/Variables/TXR/variables-1.txr @@ -0,0 +1,7 @@ +@(cases) +hey @a +how are you +@(or) +hey @b +long time no see +@(end) diff --git a/Task/Variables/TXR/variables-2.txr b/Task/Variables/TXR/variables-2.txr new file mode 100644 index 0000000000..3443a8c443 --- /dev/null +++ b/Task/Variables/TXR/variables-2.txr @@ -0,0 +1,5 @@ +@(maybe) +@a bar +@(or) +foo @b +@(end) diff --git a/Task/Variables/Tcl/variables.tcl b/Task/Variables/Tcl/variables.tcl new file mode 100644 index 0000000000..eed946c428 --- /dev/null +++ b/Task/Variables/Tcl/variables.tcl @@ -0,0 +1,23 @@ +namespace eval foo { + # Define a procedure with two formal arguments; they are local variables + proc bar {callerVarName argumentVar} { + ### Associate some non-local variables with the procedure + global globalVar; # Variable in global namespace + variable namespaceVar; # Variable in local (::foo) namespace + # Access to variable in caller's context; may be local or global + upvar 1 callerVarName callerVar + + ### Reading a variable uses the same syntax in all cases + puts "caller's var has $callerVar" + # But global and namespace vars can be accessed by using qualified names + puts "global var has $globalVar which is $::globalVar" + + ### Writing a variable has no special syntax + ### but [set] is by far the most common command for writing + set namespaceVar $globalVar + incr globalVar + + ### Destroying a variable is done like this + unset argumentVar + } +} diff --git a/Task/Variables/UNIX-Shell/variables.sh b/Task/Variables/UNIX-Shell/variables.sh new file mode 100644 index 0000000000..36dd5045ab --- /dev/null +++ b/Task/Variables/UNIX-Shell/variables.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# The unix shell uses typeless variables +apples=6 +# pears=5+4 # Some shells cannot perform addition this way +pears = `expr 5+4` # We use the external expr to perform the calculation +myfavourite="raspberries" diff --git a/Task/Variables/XSLT/variables.xslt b/Task/Variables/XSLT/variables.xslt new file mode 100644 index 0000000000..fa2c50c621 --- /dev/null +++ b/Task/Variables/XSLT/variables.xslt @@ -0,0 +1,2 @@ + +... diff --git a/Task/Variadic-function/0DESCRIPTION b/Task/Variadic-function/0DESCRIPTION new file mode 100644 index 0000000000..6b00216cf5 --- /dev/null +++ b/Task/Variadic-function/0DESCRIPTION @@ -0,0 +1,4 @@ +Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. +Functions of this type are also known as [[wp:Variadic_function|Variadic Functions]]. + +Related: [[Call a function]] diff --git a/Task/Variadic-function/1META.yaml b/Task/Variadic-function/1META.yaml new file mode 100644 index 0000000000..659c8686af --- /dev/null +++ b/Task/Variadic-function/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Basic language learning diff --git a/Task/Variadic-function/ACL2/variadic-function.acl2 b/Task/Variadic-function/ACL2/variadic-function.acl2 new file mode 100644 index 0000000000..cce2a2fc7d --- /dev/null +++ b/Task/Variadic-function/ACL2/variadic-function.acl2 @@ -0,0 +1,8 @@ +(defun print-all-fn (xs) + (if (endp xs) + nil + (prog2$ (cw "~x0~%" (first xs)) + (print-all-fn (rest xs))))) + +(defmacro print-all (&rest args) + `(print-all-fn (quote ,args))) diff --git a/Task/Variadic-function/ALGOL-68/variadic-function.alg b/Task/Variadic-function/ALGOL-68/variadic-function.alg new file mode 100644 index 0000000000..91213fc5c3 --- /dev/null +++ b/Task/Variadic-function/ALGOL-68/variadic-function.alg @@ -0,0 +1,17 @@ +main:( + MODE STRINT = UNION(STRING, INT, PROC(REF FILE)VOID, VOID); + + PROC print strint = (FLEX[]STRINT argv)VOID: ( + FOR i TO UPB argv DO + CASE argv[i] IN + (INT i):print(whole(i,-1)), + (STRING s):print(s), + (PROC(REF FILE)VOID f):f(stand out), + (VOID):print(error char) + ESAC; + IF i NE UPB argv THEN print((" ")) FI + OD + ); + + print strint(("Mary","had",1,"little",EMPTY,new line)) +) diff --git a/Task/Variadic-function/AWK/variadic-function-1.awk b/Task/Variadic-function/AWK/variadic-function-1.awk new file mode 100644 index 0000000000..2887de0521 --- /dev/null +++ b/Task/Variadic-function/AWK/variadic-function-1.awk @@ -0,0 +1,11 @@ +function f(a, b, c){ + if (a != "") print a + if (b != "") print b + if (c != "") print c +} + +BEGIN { + print "[1 arg]"; f(1) + print "[2 args]"; f(1, 2) + print "[3 args]"; f(1, 2, 3) +} diff --git a/Task/Variadic-function/AWK/variadic-function-2.awk b/Task/Variadic-function/AWK/variadic-function-2.awk new file mode 100644 index 0000000000..42119ad13b --- /dev/null +++ b/Task/Variadic-function/AWK/variadic-function-2.awk @@ -0,0 +1,13 @@ +function f(a, b, c) { + if (a != "") print a + if (b != "") print b + if (c != "") print c +} + +BEGIN { + # Set ary[1] and ary[2] at runtime. + split("Line 1:Line 2", ary, ":") + + # Pass to f(). + f(ary[1], ary[2], ary[3]) +} diff --git a/Task/Variadic-function/AWK/variadic-function-3.awk b/Task/Variadic-function/AWK/variadic-function-3.awk new file mode 100644 index 0000000000..54abae3173 --- /dev/null +++ b/Task/Variadic-function/AWK/variadic-function-3.awk @@ -0,0 +1,9 @@ +function g(len, ary, i) { + for (i = 1; i <= len; i++) print ary[i]; +} + +BEGIN { + c = split("Line 1:Line 2:Next line is empty::Last line", a, ":") + g(c, a) # Pass a[1] = "Line 1", a[4] = "", ... + +} diff --git a/Task/Variadic-function/ActionScript/variadic-function.as b/Task/Variadic-function/ActionScript/variadic-function.as new file mode 100644 index 0000000000..edd84081ac --- /dev/null +++ b/Task/Variadic-function/ActionScript/variadic-function.as @@ -0,0 +1,5 @@ +public function printArgs(... args):void +{ + for (var i:int = 0; i < args.length; i++) + trace(args[i]); +} diff --git a/Task/Variadic-function/Ada/variadic-function.ada b/Task/Variadic-function/Ada/variadic-function.ada new file mode 100644 index 0000000000..be8b459403 --- /dev/null +++ b/Task/Variadic-function/Ada/variadic-function.ada @@ -0,0 +1,30 @@ +with Ada.Strings.Unbounded, Ada.Text_IO; + +procedure Variadic is + + subtype U_String is Ada.Strings.Unbounded.Unbounded_String; + use type U_String; + + function "+"(S: String) return U_String + renames Ada.Strings.Unbounded.To_Unbounded_String; + + function "-"(U: U_String) return String + renames Ada.Strings.Unbounded.To_String; + + type Variadic_Array is array(Positive range <>) of U_String; + + procedure Print_Line(Params: Variadic_Array) is + begin + for I in Params'Range loop + Ada.Text_IO.Put(-Params(I)); + if I < Params'Last then + Ada.Text_IO.Put(" "); + end if; + end loop; + Ada.Text_IO.New_Line; + end Print_Line; + +begin + Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings + Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string +end; diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-1.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-1.ahk new file mode 100644 index 0000000000..fb6c46b6e4 --- /dev/null +++ b/Task/Variadic-function/AutoHotkey/variadic-function-1.ahk @@ -0,0 +1,5 @@ +printAll(args*) { + for k,v in args + t .= v "`n" + MsgBox, %t% +} diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk new file mode 100644 index 0000000000..847a58e4e1 --- /dev/null +++ b/Task/Variadic-function/AutoHotkey/variadic-function-2.ahk @@ -0,0 +1,3 @@ +printAll(4, 3, 5, 6, 4, 3) +printAll(4, 3, 5) +printAll("Rosetta", "Code", "Is", "Awseome!") diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk new file mode 100644 index 0000000000..afdbd63ebf --- /dev/null +++ b/Task/Variadic-function/AutoHotkey/variadic-function-3.ahk @@ -0,0 +1,2 @@ +args := ["Rosetta", "Code", "Is", "Awseome!"] +printAll(args*) diff --git a/Task/Variadic-function/AutoHotkey/variadic-function-4.ahk b/Task/Variadic-function/AutoHotkey/variadic-function-4.ahk new file mode 100644 index 0000000000..b3ae64441d --- /dev/null +++ b/Task/Variadic-function/AutoHotkey/variadic-function-4.ahk @@ -0,0 +1,13 @@ +string = Mary had a little lamb +StringSplit, arg, string, %A_Space% + +Function(arg1,arg2,arg3,arg4,arg5) ;Calls the function with 5 arguments. +Function() ;Calls the function with no arguments. +return + +Function(arg1="",arg2="",arg3="",arg4="",arg5="") { + Loop,5 + If arg%A_Index% != + out .= arg%A_Index% "`n" + MsgBox,% out ? out:"No non-blank arguments were passed." +} diff --git a/Task/Variadic-function/BASIC/variadic-function.basic b/Task/Variadic-function/BASIC/variadic-function.basic new file mode 100644 index 0000000000..affbd57bc1 --- /dev/null +++ b/Task/Variadic-function/BASIC/variadic-function.basic @@ -0,0 +1,12 @@ +SUB printAll cdecl (count As Integer, ... ) + DIM arg AS Any Ptr + DIM i AS Integer + + arg = va_first() + FOR i = 1 To count + PRINT va_arg(arg, Double) + arg = va_next(arg, Double) + NEXT i +END SUB + +printAll 3, 3.1415, 1.4142, 2.71828 diff --git a/Task/Variadic-function/C++/variadic-function.cpp b/Task/Variadic-function/C++/variadic-function.cpp new file mode 100644 index 0000000000..91d4504565 --- /dev/null +++ b/Task/Variadic-function/C++/variadic-function.cpp @@ -0,0 +1,21 @@ +#include + +template + void print(T const& t) +{ + std::cout << t; +} + +template + void print(First const& first, Rest const& ... rest) +{ + std::cout << first; + print(rest ...); +} + +int main() +{ + int i = 10; + std::string s = "Hello world"; + print("i = ", i, " and s = \"", s, "\"\n"); +} diff --git a/Task/Variadic-function/C/variadic-function.c b/Task/Variadic-function/C/variadic-function.c new file mode 100644 index 0000000000..cf3e569a97 --- /dev/null +++ b/Task/Variadic-function/C/variadic-function.c @@ -0,0 +1,13 @@ +#include +#include + +void varstrings(int count, ...) /* the ellipsis indicates variable arguments */ +{ + va_list args; + va_start(args, count); + while (count--) + puts(va_arg(args, const char *)); + va_end(args); +} + +varstrings(5, "Mary", "had", "a", "little", "lamb"); diff --git a/Task/Variadic-function/Clojure/variadic-function.clj b/Task/Variadic-function/Clojure/variadic-function.clj new file mode 100644 index 0000000000..0d840a36ca --- /dev/null +++ b/Task/Variadic-function/Clojure/variadic-function.clj @@ -0,0 +1,6 @@ +(defn foo [& args] + (doseq [a args] + (println a))) + +(foo :bar :baz :quux) +(apply foo [:bar :baz :quux]) diff --git a/Task/Variadic-function/Common-Lisp/variadic-function.lisp b/Task/Variadic-function/Common-Lisp/variadic-function.lisp new file mode 100644 index 0000000000..8eb3876900 --- /dev/null +++ b/Task/Variadic-function/Common-Lisp/variadic-function.lisp @@ -0,0 +1,8 @@ +(defun example (&rest args) + (dolist (arg args) + (print arg))) + +(example "Mary" "had" "a" "little" "lamb") + +(let ((args '("Mary" "had" "a" "little" "lamb"))) + (apply #'example args)) diff --git a/Task/Variadic-function/D/variadic-function.d b/Task/Variadic-function/D/variadic-function.d new file mode 100644 index 0000000000..002528ae9d --- /dev/null +++ b/Task/Variadic-function/D/variadic-function.d @@ -0,0 +1,23 @@ +import std.stdio, std.algorithm; + +void printAll(TyArgs...)(TyArgs args) { + foreach (el; args) + writeln(el); +} + +// Typesafe variadic function for dynamic array +void showSum1(int[] items...) { + writeln(reduce!q{a + b}(0, items)); +} + +// Typesafe variadic function for fixed size array +void showSum2(int[4] items...) { + writeln(reduce!q{a + b}(0, items)); +} + +void main() { + printAll(4, 5.6, "Rosetta", "Code", "is", "awseome"); + writeln(); + showSum1(1, 3, 50); + showSum2(1, 3, 50, 10); +} diff --git a/Task/Variadic-function/E/variadic-function-1.e b/Task/Variadic-function/E/variadic-function-1.e new file mode 100644 index 0000000000..49e5e2fc68 --- /dev/null +++ b/Task/Variadic-function/E/variadic-function-1.e @@ -0,0 +1,11 @@ +def example { + match [`run`, args] { + for x in args { + println(x) + } + } +} + +example("Mary", "had", "a", "little", "lamb") + +E.call(example, "run", ["Mary", "had", "a", "little", "lamb"]) diff --git a/Task/Variadic-function/E/variadic-function-2.e b/Task/Variadic-function/E/variadic-function-2.e new file mode 100644 index 0000000000..561999767e --- /dev/null +++ b/Task/Variadic-function/E/variadic-function-2.e @@ -0,0 +1,6 @@ +def non_example { + to run(x, y) { + println(x) + println(y) + } +} diff --git a/Task/Variadic-function/E/variadic-function-3.e b/Task/Variadic-function/E/variadic-function-3.e new file mode 100644 index 0000000000..2d7d658c39 --- /dev/null +++ b/Task/Variadic-function/E/variadic-function-3.e @@ -0,0 +1,4 @@ +def non_example(x, y) { + println(x) + println(y) +} diff --git a/Task/Variadic-function/Euler-Math-Toolbox/variadic-function.euler b/Task/Variadic-function/Euler-Math-Toolbox/variadic-function.euler new file mode 100644 index 0000000000..801fddcc90 --- /dev/null +++ b/Task/Variadic-function/Euler-Math-Toolbox/variadic-function.euler @@ -0,0 +1,15 @@ +>function allargs () ... +$ loop 1 to argn(); +$ args(#), +$ end +$endfunction +>allargs(1,3,"Test",1:2) + 1 + 3 + Test + [ 1 2 ] +>function args test (x) := {x,x^2,x^3} +>allargs(test(4)) + 4 + 16 + 64 diff --git a/Task/Variadic-function/Euphoria/variadic-function.euphoria b/Task/Variadic-function/Euphoria/variadic-function.euphoria new file mode 100644 index 0000000000..ff444de5f2 --- /dev/null +++ b/Task/Variadic-function/Euphoria/variadic-function.euphoria @@ -0,0 +1,8 @@ +procedure print_args(sequence args) + for i = 1 to length(args) do + puts(1,args[i]) + puts(1,' ') + end for +end procedure + +print_args({"Mary", "had", "a", "little", "lamb"}) diff --git a/Task/Variadic-function/Forth/variadic-function-1.fth b/Task/Variadic-function/Forth/variadic-function-1.fth new file mode 100644 index 0000000000..017daa269d --- /dev/null +++ b/Task/Variadic-function/Forth/variadic-function-1.fth @@ -0,0 +1,2 @@ +: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ; +4 3 2 1 4 sum . \ 10 diff --git a/Task/Variadic-function/Forth/variadic-function-2.fth b/Task/Variadic-function/Forth/variadic-function-2.fth new file mode 100644 index 0000000000..a0008a7e4f --- /dev/null +++ b/Task/Variadic-function/Forth/variadic-function-2.fth @@ -0,0 +1 @@ +: .stack ( -- ) depth 0 ?do i pick . loop ; diff --git a/Task/Variadic-function/Fortran/variadic-function.f b/Task/Variadic-function/Fortran/variadic-function.f new file mode 100644 index 0000000000..5401097429 --- /dev/null +++ b/Task/Variadic-function/Fortran/variadic-function.f @@ -0,0 +1,33 @@ +program varargs + + integer, dimension(:), allocatable :: va + integer :: i + + ! using an array (vector) static + call v_func() + call v_func( (/ 100 /) ) + call v_func( (/ 90, 20, 30 /) ) + + ! dynamically creating an array of 5 elements + allocate(va(5)) + va = (/ (i,i=1,5) /) + call v_func(va) + deallocate(va) + +contains + + subroutine v_func(arglist) + integer, dimension(:), intent(in), optional :: arglist + + integer :: i + + if ( present(arglist) ) then + do i = lbound(arglist, 1), ubound(arglist, 1) + print *, arglist(i) + end do + else + print *, "no argument at all" + end if + end subroutine v_func + +end program varargs diff --git a/Task/Variadic-function/Go/variadic-function-1.go b/Task/Variadic-function/Go/variadic-function-1.go new file mode 100644 index 0000000000..e44a2b65e9 --- /dev/null +++ b/Task/Variadic-function/Go/variadic-function-1.go @@ -0,0 +1,6 @@ +func printAll(things ... string) { + // it's as if you declared "things" as a []string, containing all the arguments + for _, x := range things { + fmt.Println(x) + } +} diff --git a/Task/Variadic-function/Go/variadic-function-2.go b/Task/Variadic-function/Go/variadic-function-2.go new file mode 100644 index 0000000000..403c1e2c1d --- /dev/null +++ b/Task/Variadic-function/Go/variadic-function-2.go @@ -0,0 +1,2 @@ +args := []string{"foo", "bar"} +printAll(args...) diff --git a/Task/Variadic-function/Groovy/variadic-function.groovy b/Task/Variadic-function/Groovy/variadic-function.groovy new file mode 100644 index 0000000000..62a7f9d7cb --- /dev/null +++ b/Task/Variadic-function/Groovy/variadic-function.groovy @@ -0,0 +1,3 @@ +def printAll( Object[] args) { args.each{ arg -> println arg } } + +printAll(1, 2, "three", ["3", "4"]) diff --git a/Task/Variadic-function/Haskell/variadic-function.hs b/Task/Variadic-function/Haskell/variadic-function.hs new file mode 100644 index 0000000000..9e5e116cc4 --- /dev/null +++ b/Task/Variadic-function/Haskell/variadic-function.hs @@ -0,0 +1,17 @@ +class PrintAllType t where + process :: [String] -> t + +instance PrintAllType (IO a) where + process args = do mapM_ putStrLn args + return undefined + +instance (Show a, PrintAllType r) => PrintAllType (a -> r) where + process args = \a -> process (args ++ [show a]) + +printAll :: (PrintAllType t) => t +printAll = process [] + +main :: IO () +main = do printAll 5 "Mary" "had" "a" "little" "lamb" + printAll 4 3 5 + printAll "Rosetta" "Code" "Is" "Awseome!" diff --git a/Task/Variadic-function/Icon/variadic-function.icon b/Task/Variadic-function/Icon/variadic-function.icon new file mode 100644 index 0000000000..4bb6cb69b8 --- /dev/null +++ b/Task/Variadic-function/Icon/variadic-function.icon @@ -0,0 +1,9 @@ +procedure main () + varargs("some", "extra", "args") + write() + varargs ! ["a","b","c","d"] +end + +procedure varargs(args[]) + every write(!args) +end diff --git a/Task/Variadic-function/Io/variadic-function.io b/Task/Variadic-function/Io/variadic-function.io new file mode 100644 index 0000000000..8ed04e17ce --- /dev/null +++ b/Task/Variadic-function/Io/variadic-function.io @@ -0,0 +1 @@ +printAll := method(call message arguments foreach(println)) diff --git a/Task/Variadic-function/J/variadic-function-1.j b/Task/Variadic-function/J/variadic-function-1.j new file mode 100644 index 0000000000..458fe33d92 --- /dev/null +++ b/Task/Variadic-function/J/variadic-function-1.j @@ -0,0 +1,6 @@ + A=:2 + B=:3 + C=:5 + sum=:+/ + sum 1,A,B,4,C +15 diff --git a/Task/Variadic-function/J/variadic-function-2.j b/Task/Variadic-function/J/variadic-function-2.j new file mode 100644 index 0000000000..180cb8f4db --- /dev/null +++ b/Task/Variadic-function/J/variadic-function-2.j @@ -0,0 +1,3 @@ + commaAnd=: [: ; (<' and ') _2} ::] 1 }.&, (<', ') ,. ":each + commaAnd 'dog';A;B;'cat';C +dog, 2, 3, cat and 5 diff --git a/Task/Variadic-function/Java/variadic-function-1.java b/Task/Variadic-function/Java/variadic-function-1.java new file mode 100644 index 0000000000..75022ddcbe --- /dev/null +++ b/Task/Variadic-function/Java/variadic-function-1.java @@ -0,0 +1,6 @@ +public static void printAll(Object... things){ + // "things" is an Object[] + for(Object i:things){ + System.out.println(i); + } +} diff --git a/Task/Variadic-function/Java/variadic-function-2.java b/Task/Variadic-function/Java/variadic-function-2.java new file mode 100644 index 0000000000..0e43a38e15 --- /dev/null +++ b/Task/Variadic-function/Java/variadic-function-2.java @@ -0,0 +1,3 @@ +printAll(4, 3, 5, 6, 4, 3); +printAll(4, 3, 5); +printAll("Rosetta", "Code", "Is", "Awseome!"); diff --git a/Task/Variadic-function/Java/variadic-function-3.java b/Task/Variadic-function/Java/variadic-function-3.java new file mode 100644 index 0000000000..d27e07c71d --- /dev/null +++ b/Task/Variadic-function/Java/variadic-function-3.java @@ -0,0 +1,2 @@ +Object[] args = {"Rosetta", "Code", "Is", "Awseome!"}; +printAll(args); diff --git a/Task/Variadic-function/Java/variadic-function-4.java b/Task/Variadic-function/Java/variadic-function-4.java new file mode 100644 index 0000000000..5e8b70335c --- /dev/null +++ b/Task/Variadic-function/Java/variadic-function-4.java @@ -0,0 +1,3 @@ +Object[] args = {"Rosetta", "Code", "Is", "Awseome,"}; +printAll(args, "Dude!");//does not print "Rosetta Code Is Awesome, Dude!" +//instead prints the type and hashcode for args followed by "Dude!" diff --git a/Task/Variadic-function/Java/variadic-function-5.java b/Task/Variadic-function/Java/variadic-function-5.java new file mode 100644 index 0000000000..bf7e157f51 --- /dev/null +++ b/Task/Variadic-function/Java/variadic-function-5.java @@ -0,0 +1 @@ +printAll((Object)args); diff --git a/Task/Variadic-function/JavaScript/variadic-function-1.js b/Task/Variadic-function/JavaScript/variadic-function-1.js new file mode 100644 index 0000000000..e4896c9b23 --- /dev/null +++ b/Task/Variadic-function/JavaScript/variadic-function-1.js @@ -0,0 +1,7 @@ +function printAll() { + for (var i=0; i bar(1,2) +(1,2,()) + +julia> bar(1,2,3) +(1,2,(3,)) + +julia> bar(1,2,3,4) +(1,2,(3,4)) + +julia> bar(1,2,3,4,5,6) +(1,2,(3,4,5,6)) diff --git a/Task/Variadic-function/Julia/variadic-function-3.julia b/Task/Variadic-function/Julia/variadic-function-3.julia new file mode 100644 index 0000000000..74e3a313d1 --- /dev/null +++ b/Task/Variadic-function/Julia/variadic-function-3.julia @@ -0,0 +1,5 @@ +julia> x = (3,4) +(3,4) + +julia> bar(1,2,x...) +(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-4.julia b/Task/Variadic-function/Julia/variadic-function-4.julia new file mode 100644 index 0000000000..8e165f017a --- /dev/null +++ b/Task/Variadic-function/Julia/variadic-function-4.julia @@ -0,0 +1,11 @@ +julia> x = (2,3,4) +(2,3,4) + +julia> bar(1,x...) +(1,2,(3,4)) + +julia> x = (1,2,3,4) +(1,2,3,4) + +julia> bar(x...) +(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-5.julia b/Task/Variadic-function/Julia/variadic-function-5.julia new file mode 100644 index 0000000000..623a7dd0b0 --- /dev/null +++ b/Task/Variadic-function/Julia/variadic-function-5.julia @@ -0,0 +1,17 @@ +julia> x = [3,4] +2-element Int64 Array: + 3 + 4 + +julia> bar(1,2,x...) +(1,2,(3,4)) + +julia> x = [1,2,3,4] +4-element Int64 Array: + 1 + 2 + 3 + 4 + +julia> bar(x...) +(1,2,(3,4)) diff --git a/Task/Variadic-function/Julia/variadic-function-6.julia b/Task/Variadic-function/Julia/variadic-function-6.julia new file mode 100644 index 0000000000..9a5c08759e --- /dev/null +++ b/Task/Variadic-function/Julia/variadic-function-6.julia @@ -0,0 +1,17 @@ +baz(a,b) = a + b + +julia> args = [1,2] +2-element Int64 Array: + 1 + 2 + +julia> baz(args...) +3 + +julia> args = [1,2,3] +3-element Int64 Array: + 1 + 2 + 3 + +julia> baz(args...) diff --git a/Task/Variadic-function/Logo/variadic-function.logo b/Task/Variadic-function/Logo/variadic-function.logo new file mode 100644 index 0000000000..5291ed997b --- /dev/null +++ b/Task/Variadic-function/Logo/variadic-function.logo @@ -0,0 +1,6 @@ +to varargs [:args] + foreach :args [print ?] +end + +(varargs "Mary "had "a "little "lamb) +apply "varargs [Mary had a little lamb] diff --git a/Task/Variadic-function/Lua/variadic-function.lua b/Task/Variadic-function/Lua/variadic-function.lua new file mode 100644 index 0000000000..bcea3d1889 --- /dev/null +++ b/Task/Variadic-function/Lua/variadic-function.lua @@ -0,0 +1,3 @@ +function varar(...) + for i, v in ipairs{...} do print(v) end +end diff --git a/Task/Variadic-function/M4/variadic-function.m4 b/Task/Variadic-function/M4/variadic-function.m4 new file mode 100644 index 0000000000..d407e97731 --- /dev/null +++ b/Task/Variadic-function/M4/variadic-function.m4 @@ -0,0 +1,10 @@ +define(`showN', + `ifelse($1,0,`',`$2 +$0(decr($1),shift(shift($@)))')')dnl +define(`showargs',`showN($#,$@)')dnl +dnl +showargs(a,b,c) +dnl +define(`x',`1,2') +define(`y',`,3,4,5') +showargs(x`'y) diff --git a/Task/Variadic-function/MATLAB/variadic-function-1.m b/Task/Variadic-function/MATLAB/variadic-function-1.m new file mode 100644 index 0000000000..311327b2de --- /dev/null +++ b/Task/Variadic-function/MATLAB/variadic-function-1.m @@ -0,0 +1,7 @@ +function variadicFunction(varargin) + + for i = (1:numel(varargin)) + disp(varargin{i}); + end + +end diff --git a/Task/Variadic-function/MATLAB/variadic-function-2.m b/Task/Variadic-function/MATLAB/variadic-function-2.m new file mode 100644 index 0000000000..392604d51d --- /dev/null +++ b/Task/Variadic-function/MATLAB/variadic-function-2.m @@ -0,0 +1,10 @@ +>> variadicFunction(1,2,3,4,'cat') + 1 + + 2 + + 3 + + 4 + +cat diff --git a/Task/Variadic-function/Mathematica/variadic-function-1.math b/Task/Variadic-function/Mathematica/variadic-function-1.math new file mode 100644 index 0000000000..6e076b4f10 --- /dev/null +++ b/Task/Variadic-function/Mathematica/variadic-function-1.math @@ -0,0 +1 @@ +ShowMultiArg[x___] := Do[Print[i], {i, {x}}] diff --git a/Task/Variadic-function/Mathematica/variadic-function-2.math b/Task/Variadic-function/Mathematica/variadic-function-2.math new file mode 100644 index 0000000000..40d69cbc73 --- /dev/null +++ b/Task/Variadic-function/Mathematica/variadic-function-2.math @@ -0,0 +1,3 @@ +ShowMultiArg[] +ShowMultiArg[a, b, c] +ShowMultiArg[5, 3, 1] diff --git a/Task/Variadic-function/Mathematica/variadic-function-3.math b/Task/Variadic-function/Mathematica/variadic-function-3.math new file mode 100644 index 0000000000..acf727a362 --- /dev/null +++ b/Task/Variadic-function/Mathematica/variadic-function-3.math @@ -0,0 +1,9 @@ +[nothing] + +a +b +c + +5 +3 +1 diff --git a/Task/Variadic-function/Maxima/variadic-function.maxima b/Task/Variadic-function/Maxima/variadic-function.maxima new file mode 100644 index 0000000000..135bef4e77 --- /dev/null +++ b/Task/Variadic-function/Maxima/variadic-function.maxima @@ -0,0 +1,10 @@ +show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$ + +show(1, 2, 3, 4); + +apply(show, [1, 2, 3, 4]); + +/* Actually, the built-in function "disp" is already what we want */ +disp(1, 2, 3, 4); + +apply(disp, [1, 2, 3, 4]); diff --git a/Task/Variadic-function/Metafont/variadic-function.metafont b/Task/Variadic-function/Metafont/variadic-function.metafont new file mode 100644 index 0000000000..03a0096444 --- /dev/null +++ b/Task/Variadic-function/Metafont/variadic-function.metafont @@ -0,0 +1,14 @@ +ddef print_arg(text t) = +for x = t: + if unknown x: message "unknown value" + elseif numeric x: message decimal x + elseif string x: message x + elseif path x: message "a path" + elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x)) + elseif boolean x: if x: message "true!" else: message "false!" fi + elseif pen x: message "a pen" + elseif picture x: message "a picture" + elseif transform x: message "a transform" fi; endfor enddef; + +print_arg("hello", x, 12, fullcircle, currentpicture, down, identity, false, pencircle); +end diff --git a/Task/Variadic-function/Modula-3/variadic-function-1.mod3 b/Task/Variadic-function/Modula-3/variadic-function-1.mod3 new file mode 100644 index 0000000000..7618c76594 --- /dev/null +++ b/Task/Variadic-function/Modula-3/variadic-function-1.mod3 @@ -0,0 +1,16 @@ +MODULE Varargs EXPORTS Main; + +IMPORT IO; + +VAR strings := ARRAY [1..5] OF TEXT {"foo", "bar", "baz", "quux", "zeepf"}; + +PROCEDURE Variable(VAR arr: ARRAY OF TEXT) = + BEGIN + FOR i := FIRST(arr) TO LAST(arr) DO + IO.Put(arr[i] & "\n"); + END; + END Variable; + +BEGIN + Variable(strings); +END Varargs. diff --git a/Task/Variadic-function/Modula-3/variadic-function-2.mod3 b/Task/Variadic-function/Modula-3/variadic-function-2.mod3 new file mode 100644 index 0000000000..f1554dc0fd --- /dev/null +++ b/Task/Variadic-function/Modula-3/variadic-function-2.mod3 @@ -0,0 +1,26 @@ +MODULE Varargs EXPORTS Main; + +IMPORT IO, Fmt; + +VAR + strings := NEW(REF TEXT); + ints := NEW(REF INTEGER); + reals := NEW(REF REAL); + refarr := ARRAY [1..3] OF REFANY {strings, ints, reals}; + +PROCEDURE Variable(VAR arr: ARRAY OF REFANY) = + BEGIN + FOR i := FIRST(arr) TO LAST(arr) DO + TYPECASE arr[i] OF + | REF TEXT(n) => IO.Put(n^ & "\n"); + | REF INTEGER(n) => IO.Put(Fmt.Int(n^) & "\n"); + | REF REAL(n) => IO.Put(Fmt.Real(n^) & "\n"); + ELSE (* skip *) + END; + END; + END Variable; + +BEGIN + strings^ := "Rosetta"; ints^ := 1; reals^ := 3.1415; + Variable(refarr); +END Varargs. diff --git a/Task/Variadic-function/Objective-C/variadic-function.m b/Task/Variadic-function/Objective-C/variadic-function.m new file mode 100644 index 0000000000..d920816610 --- /dev/null +++ b/Task/Variadic-function/Objective-C/variadic-function.m @@ -0,0 +1,17 @@ +#include + +void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list +{ + va_list args; + va_start(args, firstObject); + id obj; + for (obj = firstObject; obj != nil; obj = va_arg(args, id)) + NSLog(@"%@", obj); + va_end(args); +} + +// This function can be called with any number or type of objects, as long as you terminate it with "nil": +logObjects(@"Rosetta", @"Code", @"Is", @"Awseome!", nil); +logObjects([NSNumber numberWithInt:4], + [NSNumber numberWithInt:3], + @"foo", nil); diff --git a/Task/Variadic-function/Oz/variadic-function.oz b/Task/Variadic-function/Oz/variadic-function.oz new file mode 100644 index 0000000000..3e11d34d02 --- /dev/null +++ b/Task/Variadic-function/Oz/variadic-function.oz @@ -0,0 +1,12 @@ +declare + class Demo from BaseObject + meth test(...)=Msg + {Record.forAll Msg Show} + end + end + + D = {New Demo noop} + Constructed = {List.toTuple test {List.number 1 10 1}} +in + {D test(1 2 3 4)} + {D Constructed} diff --git a/Task/Variadic-function/PHP/variadic-function-1.php b/Task/Variadic-function/PHP/variadic-function-1.php new file mode 100644 index 0000000000..ea0999343b --- /dev/null +++ b/Task/Variadic-function/PHP/variadic-function-1.php @@ -0,0 +1,11 @@ +function printAll() { + foreach (func_get_args() as $x) // first way + echo "$x\n"; + + $numargs = func_num_args(); // second way + for ($i = 0; $i < $numargs; $i++) + echo func_get_arg($i), "\n"; +} +printAll(4, 3, 5, 6, 4, 3); +printAll(4, 3, 5); +printAll("Rosetta", "Code", "Is", "Awseome!"); diff --git a/Task/Variadic-function/PHP/variadic-function-2.php b/Task/Variadic-function/PHP/variadic-function-2.php new file mode 100644 index 0000000000..7a377668d9 --- /dev/null +++ b/Task/Variadic-function/PHP/variadic-function-2.php @@ -0,0 +1,2 @@ +$args = array("Rosetta", "Code", "Is", "Awseome!"); +call_user_func_array('printAll', $args); diff --git a/Task/Variadic-function/PL-I/variadic-function.pli b/Task/Variadic-function/PL-I/variadic-function.pli new file mode 100644 index 0000000000..0090677abb --- /dev/null +++ b/Task/Variadic-function/PL-I/variadic-function.pli @@ -0,0 +1,9 @@ +/* PL/I permits optional arguments, but not an infinitely varying */ +/* argument list: */ +s: procedure (a, b, c, d); + declare (a, b, c, d, e) float optional; + if ^omitted(a) then put skip list (a); + if ^omitted(b) then put skip list (b); + if ^omitted(c) then put skip list (c); + if ^omitted(d) then put skip list (d); +end s; diff --git a/Task/Variadic-function/Perl-6/variadic-function-1.pl6 b/Task/Variadic-function/Perl-6/variadic-function-1.pl6 new file mode 100644 index 0000000000..d8df17d2fa --- /dev/null +++ b/Task/Variadic-function/Perl-6/variadic-function-1.pl6 @@ -0,0 +1,7 @@ +sub foo { + .say for @_; + say .key, ': ', .value for %_; +} + +foo 1, 2, command => 'buckle my shoe', + 3, 4, order => 'knock at the door'; diff --git a/Task/Variadic-function/Perl-6/variadic-function-2.pl6 b/Task/Variadic-function/Perl-6/variadic-function-2.pl6 new file mode 100644 index 0000000000..83dab79990 --- /dev/null +++ b/Task/Variadic-function/Perl-6/variadic-function-2.pl6 @@ -0,0 +1,4 @@ +sub foo (*@positional, *%named) { + .say for @positional; + say .key, ': ', .value for %named; +} diff --git a/Task/Variadic-function/Perl-6/variadic-function-3.pl6 b/Task/Variadic-function/Perl-6/variadic-function-3.pl6 new file mode 100644 index 0000000000..b1ad29fae8 --- /dev/null +++ b/Task/Variadic-function/Perl-6/variadic-function-3.pl6 @@ -0,0 +1 @@ +foo |@ary, |%hsh; diff --git a/Task/Variadic-function/Perl/variadic-function-1.pl b/Task/Variadic-function/Perl/variadic-function-1.pl new file mode 100644 index 0000000000..c055415767 --- /dev/null +++ b/Task/Variadic-function/Perl/variadic-function-1.pl @@ -0,0 +1,5 @@ +sub print_all { + foreach (@_) { + print "$_\n"; + } +} diff --git a/Task/Variadic-function/Perl/variadic-function-2.pl b/Task/Variadic-function/Perl/variadic-function-2.pl new file mode 100644 index 0000000000..ed2482f5c3 --- /dev/null +++ b/Task/Variadic-function/Perl/variadic-function-2.pl @@ -0,0 +1,3 @@ +print_all(4, 3, 5, 6, 4, 3); +print_all(4, 3, 5); +print_all("Rosetta", "Code", "Is", "Awseome!"); diff --git a/Task/Variadic-function/Perl/variadic-function-3.pl b/Task/Variadic-function/Perl/variadic-function-3.pl new file mode 100644 index 0000000000..dc8870e987 --- /dev/null +++ b/Task/Variadic-function/Perl/variadic-function-3.pl @@ -0,0 +1,2 @@ +@args = ("Rosetta", "Code", "Is", "Awseome!"); +print_all(@args); diff --git a/Task/Variadic-function/PicoLisp/variadic-function-1.l b/Task/Variadic-function/PicoLisp/variadic-function-1.l new file mode 100644 index 0000000000..e9dcd049fb --- /dev/null +++ b/Task/Variadic-function/PicoLisp/variadic-function-1.l @@ -0,0 +1,3 @@ +(de varargs @ + (while (args) + (println (next)) ) ) diff --git a/Task/Variadic-function/PicoLisp/variadic-function-2.l b/Task/Variadic-function/PicoLisp/variadic-function-2.l new file mode 100644 index 0000000000..c347d60e47 --- /dev/null +++ b/Task/Variadic-function/PicoLisp/variadic-function-2.l @@ -0,0 +1,5 @@ +(de varargs (Arg1 Arg2 . @) + (println Arg1) + (println Arg2) + (while (args) + (println (next)) ) ) diff --git a/Task/Variadic-function/PicoLisp/variadic-function-3.l b/Task/Variadic-function/PicoLisp/variadic-function-3.l new file mode 100644 index 0000000000..a7c9e24fb7 --- /dev/null +++ b/Task/Variadic-function/PicoLisp/variadic-function-3.l @@ -0,0 +1 @@ +(varargs 'a 123 '(d e f) "hello") diff --git a/Task/Variadic-function/PicoLisp/variadic-function-4.l b/Task/Variadic-function/PicoLisp/variadic-function-4.l new file mode 100644 index 0000000000..24a7382acc --- /dev/null +++ b/Task/Variadic-function/PicoLisp/variadic-function-4.l @@ -0,0 +1 @@ +(apply varargs '(a 123 (d e f) "hello")) diff --git a/Task/Variadic-function/PowerShell/variadic-function-1.psh b/Task/Variadic-function/PowerShell/variadic-function-1.psh new file mode 100644 index 0000000000..527f144401 --- /dev/null +++ b/Task/Variadic-function/PowerShell/variadic-function-1.psh @@ -0,0 +1,5 @@ +function print_all { + foreach ($x in $args) { + Write-Host $x + } +} diff --git a/Task/Variadic-function/PowerShell/variadic-function-2.psh b/Task/Variadic-function/PowerShell/variadic-function-2.psh new file mode 100644 index 0000000000..438fbbc3cf --- /dev/null +++ b/Task/Variadic-function/PowerShell/variadic-function-2.psh @@ -0,0 +1 @@ +print_all 1 2 'foo' diff --git a/Task/Variadic-function/PowerShell/variadic-function-3.psh b/Task/Variadic-function/PowerShell/variadic-function-3.psh new file mode 100644 index 0000000000..c2774206da --- /dev/null +++ b/Task/Variadic-function/PowerShell/variadic-function-3.psh @@ -0,0 +1,2 @@ +$array = 1,2,'foo' +Invoke-Expression "& print_all $array" diff --git a/Task/Variadic-function/PowerShell/variadic-function-4.psh b/Task/Variadic-function/PowerShell/variadic-function-4.psh new file mode 100644 index 0000000000..4262eeaaab --- /dev/null +++ b/Task/Variadic-function/PowerShell/variadic-function-4.psh @@ -0,0 +1 @@ +print_all @array diff --git a/Task/Variadic-function/Python/variadic-function-1.py b/Task/Variadic-function/Python/variadic-function-1.py new file mode 100644 index 0000000000..f4f11f4bd8 --- /dev/null +++ b/Task/Variadic-function/Python/variadic-function-1.py @@ -0,0 +1,3 @@ +def print_all(*things): + for x in things: + print x diff --git a/Task/Variadic-function/Python/variadic-function-2.py b/Task/Variadic-function/Python/variadic-function-2.py new file mode 100644 index 0000000000..c7218d045c --- /dev/null +++ b/Task/Variadic-function/Python/variadic-function-2.py @@ -0,0 +1,3 @@ +print_all(4, 3, 5, 6, 4, 3) +print_all(4, 3, 5) +print_all("Rosetta", "Code", "Is", "Awseome!") diff --git a/Task/Variadic-function/Python/variadic-function-3.py b/Task/Variadic-function/Python/variadic-function-3.py new file mode 100644 index 0000000000..be843c2caa --- /dev/null +++ b/Task/Variadic-function/Python/variadic-function-3.py @@ -0,0 +1,2 @@ +args = ["Rosetta", "Code", "Is", "Awseome!"] +print_all(*args) diff --git a/Task/Variadic-function/Python/variadic-function-4.py b/Task/Variadic-function/Python/variadic-function-4.py new file mode 100644 index 0000000000..42cbb8fbdb --- /dev/null +++ b/Task/Variadic-function/Python/variadic-function-4.py @@ -0,0 +1,25 @@ +>>> def printargs(*positionalargs, **keywordargs): + print "POSITIONAL ARGS:\n " + "\n ".join(repr(x) for x in positionalargs) + print "KEYWORD ARGS:\n " + '\n '.join( + "%r = %r" % (k,v) for k,v in keywordargs.iteritems()) + + +>>> printargs(1,'a',1+0j, fee='fi', fo='fum') +POSITIONAL ARGS: + 1 + 'a' + (1+0j) +KEYWORD ARGS: + 'fee' = 'fi' + 'fo' = 'fum' +>>> alist = [1,'a',1+0j] +>>> adict = {'fee':'fi', 'fo':'fum'} +>>> printargs(*alist, **adict) +POSITIONAL ARGS: + 1 + 'a' + (1+0j) +KEYWORD ARGS: + 'fee' = 'fi' + 'fo' = 'fum' +>>> diff --git a/Task/Variadic-function/Qi/variadic-function.qi b/Task/Variadic-function/Qi/variadic-function.qi new file mode 100644 index 0000000000..e636202c6c --- /dev/null +++ b/Task/Variadic-function/Qi/variadic-function.qi @@ -0,0 +1,8 @@ +(define varargs-func + A -> (print A)) + +(define varargs + [varargs | Args] -> [varargs-func [list | Args]] + A -> A) + +(sugar in varargs 1) diff --git a/Task/Variadic-function/R/variadic-function-1.r b/Task/Variadic-function/R/variadic-function-1.r new file mode 100644 index 0000000000..f38b11b99a --- /dev/null +++ b/Task/Variadic-function/R/variadic-function-1.r @@ -0,0 +1,10 @@ + printallargs1 <- function(...) list(...) + printallargs1(1:5, "abc", TRUE) +# [[1]] +# [1] 1 2 3 4 5 +# +# [[2]] +# [1] "abc" +# +# [[3]] +# [1] TRUE diff --git a/Task/Variadic-function/R/variadic-function-2.r b/Task/Variadic-function/R/variadic-function-2.r new file mode 100644 index 0000000000..01763347e3 --- /dev/null +++ b/Task/Variadic-function/R/variadic-function-2.r @@ -0,0 +1,10 @@ + printallargs2 <- function(...) + { + args <- list(...) + lapply(args, print) + invisible() + } + printallargs2(1:5, "abc", TRUE) +# [1] 1 2 3 4 5 +# [1] "abc" +# [1] TRUE diff --git a/Task/Variadic-function/R/variadic-function-3.r b/Task/Variadic-function/R/variadic-function-3.r new file mode 100644 index 0000000000..8343994839 --- /dev/null +++ b/Task/Variadic-function/R/variadic-function-3.r @@ -0,0 +1,2 @@ +arglist <- list(x=runif(10), trim=0.1, na.rm=TRUE) +do.call(mean, arglist) diff --git a/Task/Variadic-function/REBOL/variadic-function.rebol b/Task/Variadic-function/REBOL/variadic-function.rebol new file mode 100644 index 0000000000..2c93abee6c --- /dev/null +++ b/Task/Variadic-function/REBOL/variadic-function.rebol @@ -0,0 +1,11 @@ +REBOL [ + Title: "Variadic Arguments" +] + +print-all: func [ + args [block!] {the arguments to print} +] [ + foreach arg args [print arg] +] + +print-all [rebol works this way] diff --git a/Task/Variadic-function/REXX/variadic-function-1.rexx b/Task/Variadic-function/REXX/variadic-function-1.rexx new file mode 100644 index 0000000000..ba750aa516 --- /dev/null +++ b/Task/Variadic-function/REXX/variadic-function-1.rexx @@ -0,0 +1,5 @@ +print_all: procedure + do j=1 for arg() + say arg(j) + end /*j*/ +return diff --git a/Task/Variadic-function/REXX/variadic-function-2.rexx b/Task/Variadic-function/REXX/variadic-function-2.rexx new file mode 100644 index 0000000000..591bad21e3 --- /dev/null +++ b/Task/Variadic-function/REXX/variadic-function-2.rexx @@ -0,0 +1,5 @@ +print_all: procedure + do j=1 for arg() + say '[argument' j"]: " arg(j) + end /*j*/ +return diff --git a/Task/Variadic-function/REXX/variadic-function-3.rexx b/Task/Variadic-function/REXX/variadic-function-3.rexx new file mode 100644 index 0000000000..e8256135ea --- /dev/null +++ b/Task/Variadic-function/REXX/variadic-function-3.rexx @@ -0,0 +1,10 @@ +call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 1 || 1, 'seven numbers are prime, 8th is null' + +call print_all "Hello", "World", "Bang", "Slash-N" + +call print_all "One ringy-dingy,", + "two ringy-dingy,", + "three ringy-dingy...", + "Hello? This is Ma Bell.", + "Have you been misusing your instrument?", + "(Lily Tomlin routine)" /*example showing multi-line arguments.*/ diff --git a/Task/Variadic-function/RapidQ/variadic-function.rapidq b/Task/Variadic-function/RapidQ/variadic-function.rapidq new file mode 100644 index 0000000000..146e73d686 --- /dev/null +++ b/Task/Variadic-function/RapidQ/variadic-function.rapidq @@ -0,0 +1,12 @@ +SUBI printAll (...) + FOR i = 1 TO ParamValCount + PRINT ParamVal(i) + NEXT i + FOR i = 1 TO ParamStrCount + PRINT ParamStr$(i) + NEXT i +END SUBI + +printAll 4, 3, 5, 6, 4, 3 +printAll 4, 3, 5 +printAll "Rosetta", "Code", "Is", "Awseome!" diff --git a/Task/Variadic-function/Ruby/variadic-function-1.rb b/Task/Variadic-function/Ruby/variadic-function-1.rb new file mode 100644 index 0000000000..405888f815 --- /dev/null +++ b/Task/Variadic-function/Ruby/variadic-function-1.rb @@ -0,0 +1,3 @@ +def print_all(*things) + things.each { |x| puts x } +end diff --git a/Task/Variadic-function/Ruby/variadic-function-2.rb b/Task/Variadic-function/Ruby/variadic-function-2.rb new file mode 100644 index 0000000000..c7218d045c --- /dev/null +++ b/Task/Variadic-function/Ruby/variadic-function-2.rb @@ -0,0 +1,3 @@ +print_all(4, 3, 5, 6, 4, 3) +print_all(4, 3, 5) +print_all("Rosetta", "Code", "Is", "Awseome!") diff --git a/Task/Variadic-function/Ruby/variadic-function-3.rb b/Task/Variadic-function/Ruby/variadic-function-3.rb new file mode 100644 index 0000000000..be843c2caa --- /dev/null +++ b/Task/Variadic-function/Ruby/variadic-function-3.rb @@ -0,0 +1,2 @@ +args = ["Rosetta", "Code", "Is", "Awseome!"] +print_all(*args) diff --git a/Task/Variadic-function/Scala/variadic-function.scala b/Task/Variadic-function/Scala/variadic-function.scala new file mode 100644 index 0000000000..92b4150ec0 --- /dev/null +++ b/Task/Variadic-function/Scala/variadic-function.scala @@ -0,0 +1 @@ +def printAll(args: Any*) = args foreach println diff --git a/Task/Variadic-function/Scheme/variadic-function-1.ss b/Task/Variadic-function/Scheme/variadic-function-1.ss new file mode 100644 index 0000000000..802bfc525e --- /dev/null +++ b/Task/Variadic-function/Scheme/variadic-function-1.ss @@ -0,0 +1,4 @@ +(define (print-all . things) + (for-each + (lambda (x) (display x) (newline)) + things)) diff --git a/Task/Variadic-function/Scheme/variadic-function-2.ss b/Task/Variadic-function/Scheme/variadic-function-2.ss new file mode 100644 index 0000000000..08d4fe9c53 --- /dev/null +++ b/Task/Variadic-function/Scheme/variadic-function-2.ss @@ -0,0 +1,5 @@ +(define print-all + (lambda things + (for-each + (lambda (x) (display x) (newline)) + things))) diff --git a/Task/Variadic-function/Scheme/variadic-function-3.ss b/Task/Variadic-function/Scheme/variadic-function-3.ss new file mode 100644 index 0000000000..b31c04cdf7 --- /dev/null +++ b/Task/Variadic-function/Scheme/variadic-function-3.ss @@ -0,0 +1,3 @@ +(print-all 4 3 5 6 4 3) +(print-all 4 3 5) +(print-all "Rosetta" "Code" "Is" "Awseome!") diff --git a/Task/Variadic-function/Scheme/variadic-function-4.ss b/Task/Variadic-function/Scheme/variadic-function-4.ss new file mode 100644 index 0000000000..0e15ae4d31 --- /dev/null +++ b/Task/Variadic-function/Scheme/variadic-function-4.ss @@ -0,0 +1,2 @@ +(define args '("Rosetta" "Code" "Is" "Awseome!")) +(apply print-all args) diff --git a/Task/Variadic-function/Slate/variadic-function-1.slate b/Task/Variadic-function/Slate/variadic-function-1.slate new file mode 100644 index 0000000000..4f0ce9fb68 --- /dev/null +++ b/Task/Variadic-function/Slate/variadic-function-1.slate @@ -0,0 +1,4 @@ +define: #printAll -> [| *rest | rest do: [| :arg | inform: arg printString]]. + +printAll applyTo: #(4 3 5 6 4 3). +printAll applyTo: #('Rosetta' 'Code' 'Is' 'Awesome!'). diff --git a/Task/Variadic-function/Slate/variadic-function-2.slate b/Task/Variadic-function/Slate/variadic-function-2.slate new file mode 100644 index 0000000000..cea7229eba --- /dev/null +++ b/Task/Variadic-function/Slate/variadic-function-2.slate @@ -0,0 +1,3 @@ +_@lobby printAll [| *rest | rest do: [| :arg | inform: arg printString]]. +lobby printAll, 4, 3, 5, 6, 4, 3. +lobby printAll, 'Rosetta', 'Code', 'Is', 'Awesome!'. diff --git a/Task/Variadic-function/TIScript/variadic-function.tiscript b/Task/Variadic-function/TIScript/variadic-function.tiscript new file mode 100644 index 0000000000..125ce876a5 --- /dev/null +++ b/Task/Variadic-function/TIScript/variadic-function.tiscript @@ -0,0 +1,9 @@ +function printAll(separator,argv..) { + if(argv.length) + stdout.print(argv[0]); + for (var i=1; i < argv.length; i++) + stdout.print(separator, argv[i]); +} +printAll(" ", 4, 3, 5, 6, 4, 3); +printAll(",", 4, 3, 5); +printAll("! ","Rosetta", "Code", "Is", "Awseome"); diff --git a/Task/Variadic-function/Tcl/variadic-function-1.tcl b/Task/Variadic-function/Tcl/variadic-function-1.tcl new file mode 100644 index 0000000000..5a16589a5b --- /dev/null +++ b/Task/Variadic-function/Tcl/variadic-function-1.tcl @@ -0,0 +1,10 @@ +proc print_all {args} {puts [join $args \n]} + +print_all 4 3 5 6 4 3 +print_all 4 3 5 +print_all Rosetta Code Is Awesome! + +set things {Rosetta Code Is Awesome!} + +print_all $things ;# ==> incorrect: passes a single argument (a list) to print_all +print_all {*}$things ;# ==> correct: passes each element of the list to the procedure diff --git a/Task/Variadic-function/Tcl/variadic-function-2.tcl b/Task/Variadic-function/Tcl/variadic-function-2.tcl new file mode 100644 index 0000000000..915df8415d --- /dev/null +++ b/Task/Variadic-function/Tcl/variadic-function-2.tcl @@ -0,0 +1 @@ +eval [list print_all] [lrange $things 0 end] diff --git a/Task/Variadic-function/Ursala/variadic-function.ursala b/Task/Variadic-function/Ursala/variadic-function.ursala new file mode 100644 index 0000000000..df84cd93fd --- /dev/null +++ b/Task/Variadic-function/Ursala/variadic-function.ursala @@ -0,0 +1,5 @@ +f = %gP*= + +#show+ + +main = f <'foo',12.5,('x','y'),100> diff --git a/Task/Variadic-function/V/variadic-function-1.v b/Task/Variadic-function/V/variadic-function-1.v new file mode 100644 index 0000000000..6c458353f9 --- /dev/null +++ b/Task/Variadic-function/V/variadic-function-1.v @@ -0,0 +1,6 @@ +[myfn + [zero? not] [swap puts pred] + while +]. + +100 200 300 400 500 3 myfn diff --git a/Task/Variadic-function/V/variadic-function-2.v b/Task/Variadic-function/V/variadic-function-2.v new file mode 100644 index 0000000000..cd5c425a24 --- /dev/null +++ b/Task/Variadic-function/V/variadic-function-2.v @@ -0,0 +1,3 @@ +500 +400 +300 diff --git a/Task/Variadic-function/Visual-Basic/variadic-function.vb b/Task/Variadic-function/Visual-Basic/variadic-function.vb new file mode 100644 index 0000000000..8104b982e7 --- /dev/null +++ b/Task/Variadic-function/Visual-Basic/variadic-function.vb @@ -0,0 +1,5 @@ +Sub varargs(ParamArray a()) + For n = 0 To UBound(a) + Debug.Print a(n&) + Next +End Sub diff --git a/Task/Variadic-function/Vorpal/variadic-function.vorpal b/Task/Variadic-function/Vorpal/variadic-function.vorpal new file mode 100644 index 0000000000..c4d1d4c9fb --- /dev/null +++ b/Task/Variadic-function/Vorpal/variadic-function.vorpal @@ -0,0 +1,13 @@ +self.f = method(x, y[ ], z){ + x.print() + for(i = 0, i < y.size(), i = i + 1){ + ('[' + y[i] + ']').print() + } + z.print() +} + +self.f(1, 2, 3) +'---'.print() +self.f(1, 2, 3, 4) +'---'.print() +self.f(1, 2) diff --git a/Task/Variadic-function/XPL0/variadic-function.xpl0 b/Task/Variadic-function/XPL0/variadic-function.xpl0 new file mode 100644 index 0000000000..dd5f4e713b --- /dev/null +++ b/Task/Variadic-function/XPL0/variadic-function.xpl0 @@ -0,0 +1,12 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +def IntSize=4; \number of bytes in an integer + +proc Var(N...); \Display N strings passed as arguments +int N; +[N:= Reserve(N*IntSize); \reserve space for N string pointers +repeat Text(0,N(0)); CrLf(0); \display strings pointed to by N(0) + N:= N+IntSize; \point to next string +until N=GetHp; \pointing beyond reserved space? +]; + +Var(4, "Mary", "had", "a", "little") diff --git a/Task/Vector-products/0DESCRIPTION b/Task/Vector-products/0DESCRIPTION new file mode 100644 index 0000000000..26d9101b2d --- /dev/null +++ b/Task/Vector-products/0DESCRIPTION @@ -0,0 +1,30 @@ +Define a vector having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point. + +Given vectors A = (a1, a2, a3); B = (b1, b2, b3); and C = (c1, c2, c3); then the following common vector products are defined: +* '''The dot product''' +: A • B = a1b1 + a2b2 + a3b3; a scalar quantity +* '''The cross product''' +: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1); a vector quantity +* '''The scalar triple product''' +: A • (B x C); a scalar quantity +* '''The vector triple product''' +: A x (B x C); a vector quantity + +;Task description +Given the three vectors: a = (3, 4, 5); b = (4, 3, 5); c = (-5, -12, -13): +# Create a named function/subroutine/method to compute the dot product of two vectors. +# Create a function to compute the cross product of two vectors. +# Optionally create a function to compute the scalar triple product of three vectors. +# Optionally create a function to compute the vector triple product of three vectors. +# Compute and display: a • b +# Compute and display: a x b +# Compute and display: a • b x c, the scaler triple product. +# Compute and display: a x b x c, the vector triple product. + +;References: +* [[Dot product]] here on RC. +* [http://mathworld.wolfram.com/VectorMultiplication.html A starting page] to the Wolfram Mathworld information on vector multiplication. +* Wikipedias [[wp:Dot product|dot product]], [[wp:Cross product|cross product]] and [[wp:Triple product|triple product]] entries. + +;C.f. +* [[Quaternion type]] diff --git a/Task/Vector-products/ALGOL-68/vector-products.alg b/Task/Vector-products/ALGOL-68/vector-products.alg new file mode 100644 index 0000000000..2da5c27875 --- /dev/null +++ b/Task/Vector-products/ALGOL-68/vector-products.alg @@ -0,0 +1,53 @@ +MODE FIELD = INT; +FORMAT field fmt = $g(-0)$; + +MODE VEC = [3]FIELD; +FORMAT vec fmt = $"("f(field fmt)", "f(field fmt)", "f(field fmt)")"$; + +PROC crossp = (VEC a, b)VEC:( + #Cross product of two 3D vectors# + CO ASSERT(LWB a = LWB b AND UPB a = UPB b AND UPB b = 3 # "For 3D vectors only" #); CO + (a[2]*b[3] - a[3]*b[2], a[3]*b[1] - a[1]*b[3], a[1]*b[2] - a[2]*b[1]) +); + +PRIO MAXLWB = 8, MINUPB=8; + +OP MAXLWB = (VEC a, b)INT: (LWB aUPB b|UPB a|UPB b); + +PROC dotp = (VEC a, b)FIELD:( + #Dot product of two vectors# + FIELD sum := 0; + FOR i FROM a MAXLWB b TO a MINUPB b DO sum +:= a[i]*b[i] OD; + sum +); + +PROC scalartriplep = (VEC a, b, c)VEC:( + #Scalar triple product of three vectors: "a . (b x c)"# + dotp(a, crossp(b, c)) +); + +PROC vectortriplep = (VEC a, b, c)VEC:( + #Vector triple product of three vectors: "a x (b x c)"# + crossp(a, crossp(b, c)) +); + +# Declare some useful operators # +PRIO DOT = 5, X = 5; +OP (VEC, VEC)FIELD DOT = dotp; +OP (VEC, VEC)VEC X = crossp; + +main:( + VEC a=(3, 4, 5), b=(4, 3, 5), c=(-5, -12, -13); + printf(($"a = "f(vec fmt)"; b = "f(vec fmt)"; c = "f(vec fmt)l$ , a, b, c)); + printf($"Using PROCedures:"l$); + printf(($"a . b = "f(field fmt)l$, dotp(a,b))); + printf(($"a x b = "f(vec fmt)l$, crossp(a,b))); + printf(($"a . (b x c) = "f(field fmt)l$, scalartriplep(a, b, c))); + printf(($"a x (b x c) = "f(vec fmt)l$, vectortriplep(a, b, c))); + printf($"Using OPerators:"l$); + printf(($"a . b = "f(field fmt)l$, a DOT b)); + printf(($"a x b = "f(vec fmt)l$, a X b)); + printf(($"a . (b x c) = "f(field fmt)l$, a DOT (b X c))); + printf(($"a x (b x c) = "f(vec fmt)l$, a X (b X c))) +) diff --git a/Task/Vector-products/AWK/vector-products.awk b/Task/Vector-products/AWK/vector-products.awk new file mode 100644 index 0000000000..57821f70de --- /dev/null +++ b/Task/Vector-products/AWK/vector-products.awk @@ -0,0 +1,29 @@ +#!/usr/bin/awk -f +BEGIN { + a[1] = 3; a[2]= 4; a[3] = 5; + b[1] = 4; b[2]= 3; b[3] = 5; + c[1] = -5; c[2]= -12; c[3] = -13; + + print "a = ",printVec(a); + print "b = ",printVec(b); + print "c = ",printVec(c); + print "a.b = ",dot(a,b); + ## upper case variables are used as temporary or intermediate results + cross(a,b,D);print "a.b = ",printVec(D); + cross(b,c,D);print "a.(b x c) = ",dot(a,D); + cross(b,c,D);cross(a,D,E); print "a x (b x c) = ",printVec(E); +} + +function dot(A,B) { + return A[1]*B[1]+A[2]*B[2]+A[3]*B[3]; +} + +function cross(A,B,C) { + C[1] = A[2]*B[3]-A[3]*B[2]; + C[2] = A[3]*B[1]-A[1]*B[3]; + C[3] = A[1]*B[2]-A[2]*B[1]; +} + +function printVec(C) { + return "[ "C[1]" "C[2]" "C[3]" ]"; +} diff --git a/Task/Vector-products/Ada/vector-products.ada b/Task/Vector-products/Ada/vector-products.ada new file mode 100644 index 0000000000..f49f0b3222 --- /dev/null +++ b/Task/Vector-products/Ada/vector-products.ada @@ -0,0 +1,78 @@ +with Ada.Text_IO; + +procedure Vector is + type Float_Vector is array (Positive range <>) of Float; + package Float_IO is new Ada.Text_IO.Float_IO (Float); + + procedure Vector_Put (X : Float_Vector) is + begin + Ada.Text_IO.Put ("("); + for I in X'Range loop + Float_IO.Put (X (I), Aft => 1, Exp => 0); + if I /= X'Last then + Ada.Text_IO.Put (", "); + end if; + end loop; + Ada.Text_IO.Put (")"); + end Vector_Put; + + -- cross product + function "*" (Left, Right : Float_Vector) return Float_Vector is + begin + if Left'Length /= Right'Length then + raise Constraint_Error with "vectors of different size in dot product"; + end if; + if Left'Length /= 3 then + raise Constraint_Error with "dot product only implemented for R**3"; + end if; + return Float_Vector'(Left (Left'First + 1) * Right (Right'First + 2) - + Left (Left'First + 2) * Right (Right'First + 1), + Left (Left'First + 2) * Right (Right'First) - + Left (Left'First) * Right (Right'First + 2), + Left (Left'First) * Right (Right'First + 1) - + Left (Left'First + 1) * Right (Right'First)); + end "*"; + + -- scalar product + function "*" (Left, Right : Float_Vector) return Float is + Result : Float := 0.0; + I, J : Positive; + begin + if Left'Length /= Right'Length then + raise Constraint_Error with "vectors of different size in scalar product"; + end if; + I := Left'First; J := Right'First; + while I <= Left'Last and then J <= Right'Last loop + Result := Result + Left (I) * Right (J); + I := I + 1; J := J + 1; + end loop; + return Result; + end "*"; + + -- stretching + function "*" (Left : Float_Vector; Right : Float) return Float_Vector is + Result : Float_Vector (Left'Range); + begin + for I in Left'Range loop + Result (I) := Left (I) * Right; + end loop; + return Result; + end "*"; + + A : constant Float_Vector := (3.0, 4.0, 5.0); + B : constant Float_Vector := (4.0, 3.0, 5.0); + C : constant Float_Vector := (-5.0, -12.0, -13.0); +begin + Ada.Text_IO.Put ("A: "); Vector_Put (A); Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("B: "); Vector_Put (B); Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("C: "); Vector_Put (C); Ada.Text_IO.New_Line; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("A dot B = "); Float_IO.Put (A * B, Aft => 1, Exp => 0); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("A x B = "); Vector_Put (A * B); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("A dot (B x C) = "); Float_IO.Put (A * (B * C), Aft => 1, Exp => 0); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("A x (B x C) = "); Vector_Put (A * Float_Vector'(B * C)); + Ada.Text_IO.New_Line; +end Vector; diff --git a/Task/Vector-products/BASIC256/vector-products.basic256 b/Task/Vector-products/BASIC256/vector-products.basic256 new file mode 100644 index 0000000000..c1e00a13c5 --- /dev/null +++ b/Task/Vector-products/BASIC256/vector-products.basic256 @@ -0,0 +1,32 @@ + a={3,4,5}:b={4,3,5}:c={-5,-12,-13} + +print "A.B = "+dot_product(ref(a),ref(b)) +call cross_product(ref(a),ref(b),ref(y)) +Print "AxB = ("+y[0]+","+y[1]+","+y[2]+")" +print "A.(BxC) = "+s_tri(ref(a),ref(b),ref(c)) +call v_tri(ref(a),ref(b),ref(c),ref(x),ref(y)) +Print "A x (BxC) = ("+y[0]+","+y[1]+","+y[2]+")" + +function dot_product(ref(x1),ref(x2)) + dot_product= 0 + for t = 0 to 2 + dot_product += x1[t]*x2[t] + next t +end function + +subroutine cross_product(ref(x1),ref(x2),ref(y1)) + y1={0,0,0} + y1[0]=x1[1]*x2[2]-x1[2]*x2[1] + y1[1]=x1[2]*x2[0]-x1[0]*x2[2] + y1[2]=x1[0]*x2[1]-x1[1]*x2[0] +end subroutine + +function s_tri(ref(x1),ref(x2),ref(x3)) + call cross_product(ref(x2),ref(x3),ref(y1)) + s_tri=dot_product(ref(x1),ref(y1)) +end function + +subroutine v_tri(ref(x1),ref(x2),ref(x3),ref(y1),ref(y2)) + call cross_product(ref(x2),ref(x3),ref(y1)) + call cross_product(ref(x1),ref(y1),ref(y2)) +end subroutine diff --git a/Task/Vector-products/BBC-BASIC/vector-products.bbc b/Task/Vector-products/BBC-BASIC/vector-products.bbc new file mode 100644 index 0000000000..ced0981df6 --- /dev/null +++ b/Task/Vector-products/BBC-BASIC/vector-products.bbc @@ -0,0 +1,31 @@ + DIM a(2), b(2), c(2), d(2) + a() = 3, 4, 5 + b() = 4, 3, 5 + c() = -5, -12, -13 + + PRINT "a . b = "; FNdot(a(),b()) + PROCcross(a(),b(),d()) + PRINT "a x b = (";d(0)", ";d(1)", ";d(2)")" + PRINT "a . (b x c) = "; FNscalartriple(a(),b(),c()) + PROCvectortriple(a(),b(),c(),d()) + PRINT "a x (b x c) = (";d(0)", ";d(1)", ";d(2)")" + END + + DEF FNdot(A(),B()) + LOCAL C() : DIM C(0,0) + C() = A().B() + = C(0,0) + + DEF PROCcross(A(),B(),C()) + C() = A(1)*B(2)-A(2)*B(1), A(2)*B(0)-A(0)*B(2), A(0)*B(1)-A(1)*B(0) + ENDPROC + + DEF FNscalartriple(A(),B(),C()) + LOCAL D() : DIM D(2) + PROCcross(B(),C(),D()) + = FNdot(A(),D()) + + DEF PROCvectortriple(A(),B(),C(),D()) + PROCcross(B(),C(),D()) + PROCcross(A(),D(),D()) + ENDPROC diff --git a/Task/Vector-products/C++/vector-products.cpp b/Task/Vector-products/C++/vector-products.cpp new file mode 100644 index 0000000000..d6a3c92878 --- /dev/null +++ b/Task/Vector-products/C++/vector-products.cpp @@ -0,0 +1,54 @@ +#include + +template< class T > +class D3Vector { + +template< class U > +friend std::ostream & operator<<( std::ostream & , const D3Vector & ) ; + +public : + D3Vector( T a , T b , T c ) { + x = a ; + y = b ; + z = c ; + } + + T dotproduct ( const D3Vector & rhs ) { + T scalar = x * rhs.x + y * rhs.y + z * rhs.z ; + return scalar ; + } + + D3Vector crossproduct ( const D3Vector & rhs ) { + T a = y * rhs.z - z * rhs.y ; + T b = z * rhs.x - x * rhs.z ; + T c = x * rhs.y - y * rhs.x ; + D3Vector product( a , b , c ) ; + return product ; + } + + D3Vector triplevec( D3Vector & a , D3Vector & b ) { + return crossproduct ( a.crossproduct( b ) ) ; + } + + T triplescal( D3Vector & a, D3Vector & b ) { + return dotproduct( a.crossproduct( b ) ) ; + } + +private : + T x , y , z ; +} ; + +template< class T > +std::ostream & operator<< ( std::ostream & os , const D3Vector & vec ) { + os << "( " << vec.x << " , " << vec.y << " , " << vec.z << " )" ; + return os ; +} + +int main( ) { + D3Vector a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ; + std::cout << "a . b : " << a.dotproduct( b ) << "\n" ; + std::cout << "a x b : " << a.crossproduct( b ) << "\n" ; + std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ; + std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ; + return 0 ; +} diff --git a/Task/Vector-products/C/vector-products.c b/Task/Vector-products/C/vector-products.c new file mode 100644 index 0000000000..69e37f3c77 --- /dev/null +++ b/Task/Vector-products/C/vector-products.c @@ -0,0 +1,47 @@ +#include + +typedef struct{ + float i,j,k; + }Vector; + +Vector a = {3, 4, 5},b = {4, 3, 5},c = {-5, -12, -13}; + +float dotProduct(Vector a, Vector b) +{ + return a.i*b.i+a.j*b.j+a.k*b.k; +} + +Vector crossProduct(Vector a,Vector b) +{ + Vector c = {a.j*b.k - a.k*b.j, a.k*b.i - a.i*b.k, a.i*b.j - a.j*b.i}; + + return c; +} + +float scalarTripleProduct(Vector a,Vector b,Vector c) +{ + return dotProduct(a,crossProduct(b,c)); +} + +Vector vectorTripleProduct(Vector a,Vector b,Vector c) +{ + return crossProduct(a,crossProduct(b,c)); +} + +void printVector(Vector a) +{ + printf("( %f, %f, %f)",a.i,a.j,a.k); +} + +int main() +{ + printf("\n a = "); printVector(a); + printf("\n b = "); printVector(b); + printf("\n c = "); printVector(c); + printf("\n a . b = %f",dotProduct(a,b)); + printf("\n a x b = "); printVector(crossProduct(a,b)); + printf("\n a . (b x c) = %f",scalarTripleProduct(a,b,c)); + printf("\n a x (b x c) = "); printVector(vectorTripleProduct(a,b,c)); + + return 0; +} diff --git a/Task/Vector-products/Clojure/vector-products.clj b/Task/Vector-products/Clojure/vector-products.clj new file mode 100644 index 0000000000..f8ec72fb1f --- /dev/null +++ b/Task/Vector-products/Clojure/vector-products.clj @@ -0,0 +1,25 @@ +(defrecord Vector [x y z]) + +(defn dot + [U V] + (+ (* (:x U) (:x V)) + (* (:y U) (:y V)) + (* (:z U) (:z V)))) + +(defn cross + [U V] + (new Vector + (- (* (:y U) (:z V)) (* (:z U) (:y V))) + (- (* (:z U) (:x V)) (* (:x U) (:z V))) + (- (* (:x U) (:y V)) (* (:y U) (:x V))))) + +(let [a (new Vector 3 4 5) + b (new Vector 4 3 5) + c (new Vector -5 -12 -13)] + (doseq + [prod (list + (dot a b) + (cross a b) + (dot a (cross b c)) + (cross a (cross b c)))] + (println prod))) diff --git a/Task/Vector-products/Common-Lisp/vector-products.lisp b/Task/Vector-products/Common-Lisp/vector-products.lisp new file mode 100644 index 0000000000..c430cdc76b --- /dev/null +++ b/Task/Vector-products/Common-Lisp/vector-products.lisp @@ -0,0 +1,45 @@ +(defclass 3d-vector () + ((x :type number :initarg :x) + (y :type number :initarg :y) + (z :type number :initarg :z))) + +(defmethod print-object ((object 3d-vector) stream) + (print-unreadable-object (object stream :type t) + (with-slots (x y z) object + (format stream "~a ~a ~a" x y z)))) + +(defun make-3d-vector (x y z) + (make-instance '3d-vector :x x :y y :z z)) + +(defmethod dot-product ((a 3d-vector) (b 3d-vector)) + (with-slots ((a1 x) (a2 y) (a3 z)) a + (with-slots ((b1 x) (b2 y) (b3 z)) b + (+ (* a1 b1) (* a2 b2) (* a3 b3))))) + +(defmethod cross-product ((a 3d-vector) + (b 3d-vector)) + (with-slots ((a1 x) (a2 y) (a3 z)) a + (with-slots ((b1 x) (b2 y) (b3 z)) b + (make-instance '3d-vector + :x (- (* a2 b3) (* a3 b2)) + :y (- (* a3 b1) (* a1 b3)) + :z (- (* a1 b2) (* a2 b1)))))) + +(defmethod scalar-triple-product ((a 3d-vector) + (b 3d-vector) + (c 3d-vector)) + (dot-product a (cross-product b c))) + +(defmethod vector-triple-product ((a 3d-vector) + (b 3d-vector) + (c 3d-vector)) + (cross-product a (cross-product b c))) + +(defun vector-products-example () + (let ((a (make-3d-vector 3 4 5)) + (b (make-3d-vector 4 3 5)) + (c (make-3d-vector -5 -12 -13))) + (values (dot-product a b) + (cross-product a b) + (scalar-triple-product a b c) + (vector-triple-product a b c)))) diff --git a/Task/Vector-products/D/vector-products.d b/Task/Vector-products/D/vector-products.d new file mode 100644 index 0000000000..8d8a20173e --- /dev/null +++ b/Task/Vector-products/D/vector-products.d @@ -0,0 +1,44 @@ +import std.stdio, std.conv, std.numeric; + +struct V3 { + union { + immutable static struct { double x, y, z; } + immutable double[3] v; + } + + double dot(in V3 rhs) /*@safe*/ const pure nothrow { + return dotProduct(v, rhs.v); + } + + V3 cross(in V3 rhs) @safe const pure nothrow { + return V3(y * rhs.z - z * rhs.y, + z * rhs.x - x * rhs.z, + x * rhs.y - y * rhs.x); + } + + string toString() /*@safe*/ const { return text(v); } +} + +double scalarTriple(in V3 a, in V3 b, in V3 c) +/*@safe*/ pure nothrow { + return a.dot(b.cross(c)); + // function vector_products.V3.cross (const(V3) rhs) immutable + // is not callable using argument types (const(V3)) const +} + +V3 vectorTriple(in V3 a, in V3 b, in V3 c) @safe pure nothrow { + return a.cross(b.cross(c)); +} + +void main() { + immutable V3 a = {3, 4, 5}, + b = {4, 3, 5}, + c = {-5, -12, -13}; + writeln("a = ", a); + writeln("b = ", b); + writeln("c = ", c); + writeln("a . b = ", a.dot(b)); + writeln("a x b = ", a.cross(b)); + writeln("a . (b x c) = ", scalarTriple(a, b, c)); + writeln("a x (b x c) = ", vectorTriple(a, b, c)); +} diff --git a/Task/Vector-products/Euphoria/vector-products.euphoria b/Task/Vector-products/Euphoria/vector-products.euphoria new file mode 100644 index 0000000000..6e522e7de1 --- /dev/null +++ b/Task/Vector-products/Euphoria/vector-products.euphoria @@ -0,0 +1,36 @@ +constant X = 1, Y = 2, Z = 3 + +function dot_product(sequence a, sequence b) + return a[X]*b[X] + a[Y]*b[Y] + a[Z]*b[Z] +end function + +function cross_product(sequence a, sequence b) + return { a[Y]*b[Z] - a[Z]*b[Y], + a[Z]*b[X] - a[X]*b[Z], + a[X]*b[Y] - a[Y]*b[X] } +end function + +function scalar_triple(sequence a, sequence b, sequence c) + return dot_product( a, cross_product( b, c ) ) +end function + +function vector_triple( sequence a, sequence b, sequence c) + return cross_product( a, cross_product( b, c ) ) +end function + +constant a = { 3, 4, 5 }, b = { 4, 3, 5 }, c = { -5, -12, -13 } + +puts(1,"a = ") +? a +puts(1,"b = ") +? b +puts(1,"c = ") +? c +puts(1,"a dot b = ") +? dot_product( a, b ) +puts(1,"a x b = ") +? cross_product( a, b ) +puts(1,"a dot (b x c) = ") +? scalar_triple( a, b, c ) +puts(1,"a x (b x c) = ") +? vector_triple( a, b, c ) diff --git a/Task/Vector-products/Fantom/vector-products.fantom b/Task/Vector-products/Fantom/vector-products.fantom new file mode 100644 index 0000000000..1cc40e1033 --- /dev/null +++ b/Task/Vector-products/Fantom/vector-products.fantom @@ -0,0 +1,34 @@ +class Main +{ + Int dot_product (Int[] a, Int[] b) + { + a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + } + + Int[] cross_product (Int[] a, Int[] b) + { + [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + } + + Int scalar_triple_product (Int[] a, Int[] b, Int[] c) + { + dot_product (a, cross_product (b, c)) + } + + Int[] vector_triple_product (Int[] a, Int[] b, Int[] c) + { + cross_product (a, cross_product (b, c)) + } + + Void main () + { + a := [3, 4, 5] + b := [4, 3, 5] + c := [-5, -12, -13] + + echo ("a . b = " + dot_product (a, b)) + echo ("a x b = [" + cross_product(a, b).join (", ") + "]") + echo ("a . (b x c) = " + scalar_triple_product (a, b, c)) + echo ("a x (b x c) = [" + vector_triple_product(a, b, c).join (", ") + "]") + } +} diff --git a/Task/Vector-products/Fortran/vector-products.f b/Task/Vector-products/Fortran/vector-products.f new file mode 100644 index 0000000000..fee14d2fe4 --- /dev/null +++ b/Task/Vector-products/Fortran/vector-products.f @@ -0,0 +1,39 @@ +program VectorProducts + + real, dimension(3) :: a, b, c + + a = (/ 3, 4, 5 /) + b = (/ 4, 3, 5 /) + c = (/ -5, -12, -13 /) + + print *, dot_product(a, b) + print *, cross_product(a, b) + print *, s3_product(a, b, c) + print *, v3_product(a, b, c) + +contains + + function cross_product(a, b) + real, dimension(3) :: cross_product + real, dimension(3), intent(in) :: a, b + + cross_product(1) = a(2)*b(3) - a(3)*b(2) + cross_product(2) = a(3)*b(1) - a(1)*b(3) + cross_product(3) = a(1)*b(2) - b(1)*a(2) + end function cross_product + + function s3_product(a, b, c) + real :: s3_product + real, dimension(3), intent(in) :: a, b, c + + s3_product = dot_product(a, cross_product(b, c)) + end function s3_product + + function v3_product(a, b, c) + real, dimension(3) :: v3_product + real, dimension(3), intent(in) :: a, b, c + + v3_product = cross_product(a, cross_product(b, c)) + end function v3_product + +end program VectorProducts diff --git a/Task/Vector-products/GAP/vector-products.gap b/Task/Vector-products/GAP/vector-products.gap new file mode 100644 index 0000000000..e04b4bc7f8 --- /dev/null +++ b/Task/Vector-products/GAP/vector-products.gap @@ -0,0 +1,38 @@ +DotProduct := function(u, v) + return u*v; +end; + +CrossProduct := function(u, v) + return [ + u[2]*v[3] - u[3]*v[2], + u[3]*v[1] - u[1]*v[3], + u[1]*v[2] - u[2]*v[1] ]; +end; + +ScalarTripleProduct := function(u, v, w) + return DotProduct(u, CrossProduct(v, w)); +end; + +VectorTripleProduct := function(u, v, w) + return CrossProduct(u, CrossProduct(v, w)); +end; + +a := [3, 4, 5]; +b := [4, 3, 5]; +c := [-5, -12, -13]; + +DotProduct(a, b); +# 49 + +CrossProduct(a, b); +# [ 5, 5, -7 ] + +ScalarTripleProduct(a, b, c); +# 6 + +# Another way to get it +Determinant([a, b, c]); +# 6 + +VectorTripleProduct(a, b, c); +# [ -267, 204, -3 ] diff --git a/Task/Vector-products/Go/vector-products.go b/Task/Vector-products/Go/vector-products.go new file mode 100644 index 0000000000..c6f73cc96f --- /dev/null +++ b/Task/Vector-products/Go/vector-products.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +type vector struct { + x, y, z float64 +} + +var ( + a = vector{3, 4, 5} + b = vector{4, 3, 5} + c = vector{-5, -12, -13} +) + +func dot(a, b vector) float64 { + return a.x*b.x + a.y*b.y + a.z*b.z +} + +func cross(a, b vector) vector { + return vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x} +} + +func s3(a, b, c vector) float64 { + return dot(a, cross(b, c)) +} + +func v3(a, b, c vector) vector { + return cross(a, cross(b, c)) +} + +func main() { + fmt.Println(dot(a, b)) + fmt.Println(cross(a, b)) + fmt.Println(s3(a, b, c)) + fmt.Println(v3(a, b, c)) +} diff --git a/Task/Vector-products/Groovy/vector-products-1.groovy b/Task/Vector-products/Groovy/vector-products-1.groovy new file mode 100644 index 0000000000..9cc5153bdc --- /dev/null +++ b/Task/Vector-products/Groovy/vector-products-1.groovy @@ -0,0 +1,11 @@ +def pairwiseOperation = { x, y, Closure binaryOp -> + assert x && y && x.size() == y.size() + [x, y].transpose().collect(binaryOp) +} + +def pwMult = pairwiseOperation.rcurry { it[0] * it[1] } + +def dotProduct = { x, y -> + assert x && y && x.size() == y.size() + pwMult(x, y).sum() +} diff --git a/Task/Vector-products/Groovy/vector-products-2.groovy b/Task/Vector-products/Groovy/vector-products-2.groovy new file mode 100644 index 0000000000..44ea4a2fc9 --- /dev/null +++ b/Task/Vector-products/Groovy/vector-products-2.groovy @@ -0,0 +1,4 @@ +def crossProductS = { x, y -> + assert x && y && x.size() == 3 && y.size() == 3 + [x[1]*y[2] - x[2]*y[1], x[2]*y[0] - x[0]*y[2] , x[0]*y[1] - x[1]*y[0]] +} diff --git a/Task/Vector-products/Groovy/vector-products-3.groovy b/Task/Vector-products/Groovy/vector-products-3.groovy new file mode 100644 index 0000000000..9aa2381eec --- /dev/null +++ b/Task/Vector-products/Groovy/vector-products-3.groovy @@ -0,0 +1,16 @@ +def rotR = { + assert it && it.size() > 2 + [it[-1]] + it[0..-2] +} + +def rotL = { + assert it && it.size() > 2 + it[1..-1] + [it[0]] +} + +def pwSubtr = pairwiseOperation.rcurry { it[0] - it[1] } + +def crossProductV = { x, y -> + assert x && y && x.size() == 3 && y.size() == 3 + pwSubtr(pwMult(rotL(x), rotR(y)), pwMult(rotL(y), rotR(x))) +} diff --git a/Task/Vector-products/Groovy/vector-products-4.groovy b/Task/Vector-products/Groovy/vector-products-4.groovy new file mode 100644 index 0000000000..b7d32e7bf8 --- /dev/null +++ b/Task/Vector-products/Groovy/vector-products-4.groovy @@ -0,0 +1,23 @@ +def test = { crossProduct -> + + def scalarTripleProduct = { x, y, z -> + dotProduct(x, crossProduct(y, z)) + } + + def vectorTripleProduct = { x, y, z -> + crossProduct(x, crossProduct(y, z)) + } + + def a = [3, 4, 5] + def b = [4, 3, 5] + def c = [-5, -12, -13] + + println(" a . b = " + dotProduct(a,b)) + println(" a x b = " + crossProduct(a,b)) + println("a . (b x c) = " + scalarTripleProduct(a,b,c)) + println("a x (b x c) = " + vectorTripleProduct(a,b,c)) + println() +} + +test(crossProductS) +test(crossProductV) diff --git a/Task/Vector-products/Haskell/vector-products.hs b/Task/Vector-products/Haskell/vector-products.hs new file mode 100644 index 0000000000..2af1123876 --- /dev/null +++ b/Task/Vector-products/Haskell/vector-products.hs @@ -0,0 +1,32 @@ +type Vector a = [a] +type Scalar a = a + +a,b,c,d :: Vector Int +a = [ 3, 4, 5 ] +b = [ 4, 3, 5 ] +c = [-5,-12,-13 ] +d = [ 3, 4, 5, 6 ] + +dot :: (Num t) => Vector t -> Vector t -> Scalar t +dot u v | length u == length v = sum $ zipWith (*) u v + | otherwise = error "Dotted Vectors must be of equal dimension." + +cross :: (Num t) => Vector t -> Vector t -> Vector t +cross u v | length u == 3 && length v == 3 = + [u !! 1 * v !! 2 - u !! 2 * v !! 1, + u !! 2 * v !! 0 - u !! 0 * v !! 2, + u !! 0 * v !! 1 - u !! 1 * v !! 0] + | otherwise = error "Crossed Vectors must both be three dimensional." + +scalarTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Scalar t +scalarTriple q r s = dot q $ cross r s + +vectorTriple :: (Num t) => Vector t -> Vector t -> Vector t -> Vector t +vectorTriple q r s = cross q $ cross r s + +main = do + mapM_ putStrLn [ "a . b = " ++ (show $ dot a b) + , "a x b = " ++ (show $ cross a b) + , "a . b x c = " ++ (show $ scalarTriple a b c) + , "a x b x c = " ++ (show $ vectorTriple a b c) + , "a . d = " ++ (show $ dot a d) ] diff --git a/Task/Vector-products/Icon/vector-products.icon b/Task/Vector-products/Icon/vector-products.icon new file mode 100644 index 0000000000..9ea2d61b86 --- /dev/null +++ b/Task/Vector-products/Icon/vector-products.icon @@ -0,0 +1,42 @@ +# record type to store a 3D vector +record Vector3D(x, y, z) + +# procedure to display vector as a string +procedure toString (vector) + return "(" || vector.x || ", " || vector.y || ", " || vector.z || ")" +end + +procedure dotProduct (a, b) + return a.x * b.x + a.y * b.y + a.z * b.z +end + +procedure crossProduct (a, b) + x := a.y * b.z - a.z * b.y + y := a.z * b.x - a.x * b.z + z := a.x * b.y - a.y * b.x + return Vector3D(x, y, z) +end + +procedure scalarTriple (a, b, c) + return dotProduct (a, crossProduct (b, c)) +end + +procedure vectorTriple (a, b, c) + return crossProduct (a, crossProduct (b, c)) +end + +# main procedure, to run given test +procedure main () + a := Vector3D(3, 4, 5) + b := Vector3D(4, 3, 5) + c := Vector3D(-5, -12, -13) + + writes ("A.B : " || toString(a) || "." || toString(b) || " = ") + write (dotProduct (a, b)) + writes ("AxB : " || toString(a) || "x" || toString(b) || " = ") + write (toString(crossProduct (a, b))) + writes ("A.(BxC) : " || toString(a) || ".(" || toString(b) || "x" || toString(c) || ") = ") + write (scalarTriple (a, b, c)) + writes ("Ax(BxC) : " || toString(a) || "x(" || toString(b) || "x" || toString(c) || ") = ") + write (toString(vectorTriple (a, b, c))) +end diff --git a/Task/Vector-products/J/vector-products-1.j b/Task/Vector-products/J/vector-products-1.j new file mode 100644 index 0000000000..10e812887a --- /dev/null +++ b/Task/Vector-products/J/vector-products-1.j @@ -0,0 +1,3 @@ +CT=: C.!.2 @ (#:i.) @ $~ +ip=: +/ .* NB. inner product +cross=: ] ip CT@#@[ ip [ diff --git a/Task/Vector-products/J/vector-products-2.j b/Task/Vector-products/J/vector-products-2.j new file mode 100644 index 0000000000..81ad3d17fc --- /dev/null +++ b/Task/Vector-products/J/vector-products-2.j @@ -0,0 +1 @@ +cross=: [: > [: -&.>/ .(*&.>) (<"1=i.3) , ,:&:(<"0) diff --git a/Task/Vector-products/J/vector-products-3.j b/Task/Vector-products/J/vector-products-3.j new file mode 100644 index 0000000000..15ef0dd933 --- /dev/null +++ b/Task/Vector-products/J/vector-products-3.j @@ -0,0 +1,12 @@ +a=: 3 4 5 +b=: 4 3 5 +c=: -5 12 13 + +A=: 0 {:: ] NB. contents of the first box on the right +B=: 1 {:: ] NB. contents of the second box on the right +C=: 2 {:: ] NB. contents of the third box on the right + +dotP=: A ip B +crossP=: A cross B +scTriP=: A ip B cross C +veTriP=: A cross B cross C diff --git a/Task/Vector-products/J/vector-products-4.j b/Task/Vector-products/J/vector-products-4.j new file mode 100644 index 0000000000..398e30e19d --- /dev/null +++ b/Task/Vector-products/J/vector-products-4.j @@ -0,0 +1,8 @@ + dotP a;b +49 + crossP a;b +5 5 _7 + scTriP a;b;c +6 + veTriP a;b;c +_267 204 _3 diff --git a/Task/Vector-products/Java/vector-products.java b/Task/Vector-products/Java/vector-products.java new file mode 100644 index 0000000000..b577beb3e1 --- /dev/null +++ b/Task/Vector-products/Java/vector-products.java @@ -0,0 +1,48 @@ +public class VectorProds{ + public static class Vector3D{ + private T a, b, c; + + public Vector3D(T a, T b, T c){ + this.a = a; + this.b = b; + this.c = c; + } + + public double dot(Vector3D vec){ + return (a.doubleValue() * vec.a.doubleValue() + + b.doubleValue() * vec.b.doubleValue() + + c.doubleValue() * vec.c.doubleValue()); + } + + public Vector3D cross(Vector3D vec){ + Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue(); + Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue(); + Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue(); + return new Vector3D(newA, newB, newC); + } + + public double scalTrip(Vector3D vecB, Vector3D vecC){ + return this.dot(vecB.cross(vecC)); + } + + public Vector3D vecTrip(Vector3D vecB, Vector3D vecC){ + return this.cross(vecB.cross(vecC)); + } + + @Override + public String toString(){ + return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">"; + } + } + + public static void main(String[] args){ + Vector3D a = new Vector3D(3, 4, 5); + Vector3D b = new Vector3D(4, 3, 5); + Vector3D c = new Vector3D(-5, -12, -13); + + System.out.println(a.dot(b)); + System.out.println(a.cross(b)); + System.out.println(a.scalTrip(b, c)); + System.out.println(a.vecTrip(b, c)); + } +} diff --git a/Task/Vector-products/JavaScript/vector-products.js b/Task/Vector-products/JavaScript/vector-products.js new file mode 100644 index 0000000000..2d5f10cd6c --- /dev/null +++ b/Task/Vector-products/JavaScript/vector-products.js @@ -0,0 +1,70 @@ +function dotProduct() { + var len = arguments[0] && arguments[0].length; + var argsLen = arguments.length; + var i, j = len; + var prod, sum = 0; + + // If no arguments supplied, return undefined + if (!len) { + return; + } + + // If all vectors not same length, return undefined + i = argsLen; + while (i--) { + + if (arguments[i].length != len) { + return; // return undefined + } + } + + // Sum terms + while (j--) { + i = argsLen; + prod = 1; + + while (i--) { + prod *= arguments[i][j]; + } + sum += prod; + } + return sum; +} + +function crossProduct(a, b) { + + // Check lengths + if (a.length != 3 || b.length != 3) { + return; + } + + return [a[1]*b[2] - a[2]*b[1], + a[2]*b[0] - a[0]*b[2], + a[0]*b[1] - a[1]*b[0]]; + +} + +function scalarTripleProduct(a, b, c) { + return dotProduct(a, crossProduct(b, c)); +} + +function vectorTripleProduct(a, b, c) { + return crossProduct(a, crossProduct(b, c)); +} + +// Run tests +(function () { + var a = [3, 4, 5]; + var b = [4, 3, 5]; + var c = [-5, -12, -13]; + + alert( + 'A . B: ' + dotProduct(a, b) + + '\n' + + 'A x B: ' + crossProduct(a, b) + + '\n' + + 'A . (B x C): ' + scalarTripleProduct(a, b, c) + + '\n' + + 'A x (B x C): ' + vectorTripleProduct(a, b, c) + ); +}()); diff --git a/Task/Vector-products/Liberty-BASIC/vector-products.liberty b/Task/Vector-products/Liberty-BASIC/vector-products.liberty new file mode 100644 index 0000000000..4d386325e9 --- /dev/null +++ b/Task/Vector-products/Liberty-BASIC/vector-products.liberty @@ -0,0 +1,45 @@ + print "Vector products of 3-D vectors" + + print "Dot product of 3,4,5 and 4,3,5 is " + print DotProduct( "3,4,5", "4,3,5") + print "Cross product of 3,4,5 and 4,3,5 is " + print CrossProduct$( "3,4,5", "4,3,5") + print "Scalar triple product of 3,4,5, 4,3,5 -5, -12, -13 is " + print ScalarTripleProduct( "3,4,5", "4,3,5", "-5, -12, -13") + print "Vector triple product of 3,4,5, 4,3,5 -5, -12, -13 is " + print VectorTripleProduct$( "3,4,5", "4,3,5", "-5, -12, -13") + + + end + + function DotProduct( i$, j$) + ix =val( word$( i$, 1, ",")) + iy =val( word$( i$, 2, ",")) + iz =val( word$( i$, 3, ",")) + jx =val( word$( j$, 1, ",")) + jy =val( word$( j$, 2, ",")) + jz =val( word$( j$, 3, ",")) + DotProduct = ix *jx +iy *jy + iz *jz + end function + + function CrossProduct$( i$, j$) + ix =val( word$( i$, 1, ",")) + iy =val( word$( i$, 2, ",")) + iz =val( word$( i$, 3, ",")) + jx =val( word$( j$, 1, ",")) + jy =val( word$( j$, 2, ",")) + jz =val( word$( j$, 3, ",")) + cpx =iy *jz -iz *jy + cpy =iz *jx -ix *jz + cpz =ix *jy -iy *jx + CrossProduct$ =str$( cpx); ","; str$( cpy); ","; str$( cpz) + end function + + function ScalarTripleProduct( i$, j$, k$)) + ScalarTripleProduct =DotProduct( i$, CrossProduct$( j$, k$)) + end function + + function VectorTripleProduct$( i$, j$, k$)) + VectorTripleProduct$ =CrossProduct$( i$, CrossProduct$( j$, k$)) + end function + END SUB diff --git a/Task/Vector-products/Lua/vector-products.lua b/Task/Vector-products/Lua/vector-products.lua new file mode 100644 index 0000000000..ffb7555ac8 --- /dev/null +++ b/Task/Vector-products/Lua/vector-products.lua @@ -0,0 +1,37 @@ +Vector = {} +function Vector.new( _x, _y, _z ) + return { x=_x, y=_y, z=_z } +end + +function Vector.dot( A, B ) + return A.x*B.x + A.y*B.y + A.z*B.z +end + +function Vector.cross( A, B ) + return { x = A.y*B.z - A.z*B.y, + y = A.z*B.x - A.x*B.z, + z = A.x*B.y - A.y*B.x } +end + +function Vector.scalar_triple( A, B, C ) + return Vector.dot( A, Vector.cross( B, C ) ) +end + +function Vector.vector_triple( A, B, C ) + return Vector.cross( A, Vector.cross( B, C ) ) +end + + +A = Vector.new( 3, 4, 5 ) +B = Vector.new( 4, 3, 5 ) +C = Vector.new( -5, -12, -13 ) + +print( Vector.dot( A, B ) ) + +r = Vector.cross(A, B ) +print( r.x, r.y, r.z ) + +print( Vector.scalar_triple( A, B, C ) ) + +r = Vector.vector_triple( A, B, C ) +print( r.x, r.y, r.z ) diff --git a/Task/Vector-products/MATLAB/vector-products.m b/Task/Vector-products/MATLAB/vector-products.m new file mode 100644 index 0000000000..b8523da824 --- /dev/null +++ b/Task/Vector-products/MATLAB/vector-products.m @@ -0,0 +1,16 @@ +% Create a named function/subroutine/method to compute the dot product of two vectors. + dot(a,b) +% Create a function to compute the cross product of two vectors. + cross(a,b) +% Optionally create a function to compute the scalar triple product of three vectors. + dot(a,cross(b,c)) +% Optionally create a function to compute the vector triple product of three vectors. + cross(a,cross(b,c)) +% Compute and display: a • b + cross(a,b) +% Compute and display: a x b + cross(a,b) +% Compute and display: a • b x c, the scaler triple product. + dot(a,cross(b,c)) +% Compute and display: a x b x c, the vector triple product. + cross(a,cross(b,c)) diff --git a/Task/Vector-products/Mathematica/vector-products.math b/Task/Vector-products/Mathematica/vector-products.math new file mode 100644 index 0000000000..560d248a90 --- /dev/null +++ b/Task/Vector-products/Mathematica/vector-products.math @@ -0,0 +1,7 @@ +a={3,4,5}; +b={4,3,5}; +c={-5,-12,-13}; +a.b +Cross[a,b] +a.Cross[b,c] +Cross[a,Cross[b,c]] diff --git a/Task/Vector-products/Mercury/vector-products.mercury b/Task/Vector-products/Mercury/vector-products.mercury new file mode 100644 index 0000000000..c3a812f94b --- /dev/null +++ b/Task/Vector-products/Mercury/vector-products.mercury @@ -0,0 +1,42 @@ +:- module vector_product. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module int, list, string. + +main(!IO) :- + A = vector3d(3, 4, 5), + B = vector3d(4, 3, 5), + C = vector3d(-5, -12, -13), + io.format("A . B = %d\n", [i(A `dot_product` B)], !IO), + io.format("A x B = %s\n", [s(to_string(A `cross_product` B))], !IO), + io.format("A . (B x C) = %d\n", [i(scalar_triple_product(A, B, C))], !IO), + io.format("A x (B x C) = %s\n", [s(to_string(vector_triple_product(A, B, C)))], !IO). + +:- type vector3d ---> vector3d(int, int, int). + +:- func dot_product(vector3d, vector3d) = int. + +dot_product(vector3d(A1, A2, A3), vector3d(B1, B2, B3)) = + A1 * B1 + A2 * B2 + A3 * B3. + +:- func cross_product(vector3d, vector3d) = vector3d. + +cross_product(vector3d(A1, A2, A3), vector3d(B1, B2, B3)) = + vector3d(A2 * B3 - A3 * B2, A3 * B1 - A1 * B3, A1 * B2 - A2 * B1). + +:- func scalar_triple_product(vector3d, vector3d, vector3d) = int. + +scalar_triple_product(A, B, C) = A `dot_product` (B `cross_product` C). + +:- func vector_triple_product(vector3d, vector3d, vector3d) = vector3d. + +vector_triple_product(A, B, C) = A `cross_product` (B `cross_product` C). + +:- func to_string(vector3d) = string. + +to_string(vector3d(X, Y, Z)) = + string.format("(%d, %d, %d)", [i(X), i(Y), i(Z)]). diff --git a/Task/Vector-products/Nemerle/vector-products.nemerle b/Task/Vector-products/Nemerle/vector-products.nemerle new file mode 100644 index 0000000000..5bb2837177 --- /dev/null +++ b/Task/Vector-products/Nemerle/vector-products.nemerle @@ -0,0 +1,36 @@ +using System.Console; + +module VectorProducts3d +{ + Dot(x : int * int * int, y : int * int * int) : int + { + def (x1, x2, x3) = x; + def (y1, y2, y3) = y; + (x1 * y1) + (x2 * y2) + (x3 * y3) + } + + Cross(x : int * int * int, y : int * int * int) : int * int * int + { + def (x1, x2, x3) = x; + def (y1, y2, y3) = y; + ((x2 * y3 - x3 * y2), (x3 * y1 - x1 * y3), (x1 * y2 - x2 * y1)) + } + + ScalarTriple(a : int * int * int, b : int * int * int, c : int * int * int) : int + { + Dot(a, Cross(b, c)) + } + + VectorTriple(a : int * int * int, b : int * int * int, c : int * int * int) : int * int * int + { + Cross(a, Cross(b, c)) + } + + Main() : void + { + def a = (3, 4, 5); def b = (4, 3, 5); def c = (-5, -12, -13); + WriteLine(Dot(a, b)); WriteLine(Cross(a, b)); + WriteLine(ScalarTriple(a, b, c)); + WriteLine(VectorTriple(a, b, c)); + } +} diff --git a/Task/Vector-products/OCaml/vector-products.ocaml b/Task/Vector-products/OCaml/vector-products.ocaml new file mode 100644 index 0000000000..694e0bcaaa --- /dev/null +++ b/Task/Vector-products/OCaml/vector-products.ocaml @@ -0,0 +1,30 @@ +let a = (3.0, 4.0, 5.0) +let b = (4.0, 3.0, 5.0) +let c = (-5.0, -12.0, -13.0) + +let string_of_vector (x,y,z) = + Printf.sprintf "(%g, %g, %g)" x y z + +let dot (a1, a2, a3) (b1, b2, b3) = + (a1 *. b1) +. (a2 *. b2) +. (a3 *. b3) + +let cross (a1, a2, a3) (b1, b2, b3) = + (a2 *. b3 -. a3 *. b2, + a3 *. b1 -. a1 *. b3, + a1 *. b2 -. a2 *. b1) + +let scalar_triple a b c = + dot a (cross b c) + +let vector_triple a b c = + cross a (cross b c) + +let () = + Printf.printf "a: %s\n" (string_of_vector a); + Printf.printf "b: %s\n" (string_of_vector b); + Printf.printf "c: %s\n" (string_of_vector c); + Printf.printf "a . b = %g\n" (dot a b); + Printf.printf "a x b = %s\n" (string_of_vector (cross a b)); + Printf.printf "a . (b x c) = %g\n" (scalar_triple a b c); + Printf.printf "a x (b x c) = %s\n" (string_of_vector (vector_triple a b c)); +;; diff --git a/Task/Vector-products/Objeck/vector-products.objeck b/Task/Vector-products/Objeck/vector-products.objeck new file mode 100644 index 0000000000..79f6879971 --- /dev/null +++ b/Task/Vector-products/Objeck/vector-products.objeck @@ -0,0 +1,63 @@ +bundle Default { + class VectorProduct { + function : Main(args : String[]) ~ Nil { + a := Vector3D->New(3.0, 4.0, 5.0); + b := Vector3D->New(4.0, 3.0, 5.0); + c := Vector3D->New(-5.0, -12.0, -13.0); + + a->Dot(b)->Print(); + a->Cross(b)->Print(); + a->ScaleTrip(b, c)->Print(); + a->VectorTrip(b, c)->Print(); + } + } + + class Vector3D { + @a : Float; + @b : Float; + @c : Float; + + New(a : Float, b : Float, c : Float) { + @a := a; + @b := b; + @c := c; + } + + method : GetA() ~ Float { + return @a; + } + + method : GetB() ~ Float { + return @b; + } + + method : GetC() ~ Float { + return @c; + } + + method : public : Dot(vec : Vector3D) ~ Float { + return @a * vec->GetA() + @b * vec->GetB() + @c * vec->GetC(); + } + + method : public : Cross(vec : Vector3D) ~ Vector3D { + newA := @b * vec->GetC() - @c * vec->GetB(); + newB := @c * vec->GetA() - @a * vec->GetC(); + newC := @a * vec->GetB() - @b * vec->GetA(); + + return Vector3D->New(newA, newB, newC); + } + + method : public : ScaleTrip(vec_b: Vector3D, vec_c : Vector3D) ~ Float { + return Dot(vec_b->Cross(vec_c)); + } + + method : public : Print() ~ Nil { + IO.Console->Print('<')->Print(@a)->Print(" ,") + ->Print(@b)->Print(", ")->Print(@c)->PrintLine('>'); + } + + method : public : VectorTrip(vec_b: Vector3D, vec_c : Vector3D) ~ Vector3D { + return Cross(vec_b->Cross(vec_c)); + } + } +} diff --git a/Task/Vector-products/Octave/vector-products.octave b/Task/Vector-products/Octave/vector-products.octave new file mode 100644 index 0000000000..8e7f1ae733 --- /dev/null +++ b/Task/Vector-products/Octave/vector-products.octave @@ -0,0 +1,25 @@ +a = [3, 4, 5]; +b = [4, 3, 5]; +c = [-5, -12, -13]; + +function r = s3prod(a, b, c) + r = dot(a, cross(b, c)); +endfunction + +function r = v3prod(a, b, c) + r = cross(a, cross(b, c)); +endfunction + +% 49 +dot(a, b) +% or matrix-multiplication between row and column vectors +a * b' + +% 5 5 -7 +cross(a, b) % only for 3d-vectors + +% 6 +s3prod(a, b, c) + +% -267 204 -3 +v3prod(a, b, c) diff --git a/Task/Vector-products/PARI-GP/vector-products.pari b/Task/Vector-products/PARI-GP/vector-products.pari new file mode 100644 index 0000000000..61589e1222 --- /dev/null +++ b/Task/Vector-products/PARI-GP/vector-products.pari @@ -0,0 +1,18 @@ +dot(u,v)={ + sum(i=1,#u,u[i]*v[i]) +}; +cross(u,v)={ + [u[2]*v[3] - u[3]*v[2], u[3]*v[1] - u[1]*v[3], u[1]*v[2] - u[2]*v[1]] +}; +striple(a,b,c)={ + dot(a,cross(b,c)) +}; +vtriple(a,b,c)={ + cross(a,cross(b,c)) +}; + +a = [3,4,5]; b = [4,3,5]; c = [-5,-12,-13]; +dot(a,b) +cross(a,b) +striple(a,b,c) +vtriple(a,b,c) diff --git a/Task/Vector-products/PL-I/vector-products-1.pli b/Task/Vector-products/PL-I/vector-products-1.pli new file mode 100644 index 0000000000..65a7999927 --- /dev/null +++ b/Task/Vector-products/PL-I/vector-products-1.pli @@ -0,0 +1,42 @@ +/* dot product, cross product, etc. 4 June 2011 */ + +test_products: procedure options (main); + + declare a(3) fixed initial (3, 4, 5); + declare b(3) fixed initial (4, 3, 5); + declare c(3) fixed initial (-5, -12, -13); + declare e(3) fixed; + + put skip list ('a . b =', dot_product(a, b)); + call cross_product(a, b, e); put skip list ('a x b =', e); + put skip list ('a . (b x c) =', scalar_triple_product(a, b, c)); + call vector_triple_product(a, b, c, e); put skip list ('a x (b x c) =', e); + + +dot_product: procedure (a, b) returns (fixed); + declare (a, b) (*) fixed; + return (sum(a*b)); +end dot_product; + +cross_product: procedure (a, b, c); + declare (a, b, c) (*) fixed; + c(1) = a(2)*b(3) - a(3)*b(2); + c(2) = a(3)*b(1) - a(1)*b(3); + c(3) = a(1)*b(2) - a(2)*b(1); +end cross_product; + +scalar_triple_product: procedure (a, b, c) returns (fixed); + declare (a, b, c)(*) fixed; + declare t(hbound(a, 1)) fixed; + call cross_product(b, c, t); + return (dot_product(a, t)); +end scalar_triple_product; + +vector_triple_product: procedure (a, b, c, e); + declare (a, b, c, e)(*) fixed; + declare t(hbound(a,1)) fixed; + call cross_product(b, c, t); + call cross_product(a, t, e); +end vector_triple_product; + +end test_products; diff --git a/Task/Vector-products/PL-I/vector-products-2.pli b/Task/Vector-products/PL-I/vector-products-2.pli new file mode 100644 index 0000000000..f0bd3ffc67 --- /dev/null +++ b/Task/Vector-products/PL-I/vector-products-2.pli @@ -0,0 +1,48 @@ +/* This version uses the ability of PL/I to return arrays. */ + +/* dot product, cross product, etc. 6 June 2011 */ + +test_products: procedure options (main); + define structure 1 vector, 2 vec(3) fixed; + declare (a, b, c) type(vector); + + a.vec(1) = 3; a.vec(2) = 4; a.vec(3) = 5; + b.vec(1) = 4; b.vec(2) = 3; b.vec(3) = 5; + c.vec(1) = -5; c.vec(2) = -12; c.vec(3) = -13; + + put skip list ('a . b =', dot_product (a, b) ); + put skip list ('a x b =', cross_product(a, b).vec); + put skip list ('a . (b x c) =', scalar_triple_product(a, b, c) ); + put skip list ('a x (b x c) =', vector_triple_product(a, b, c).vec); + + +dot_product: procedure (a, b) returns (fixed); + declare (a, b) type(vector); + return (sum(a.vec*b.vec)); +end dot_product; + +cross_product: procedure (a, b) returns (type(vector)); + declare (a, b) type(vector); + declare c type vector; + c.vec(1) = a.vec(2)*b.vec(3) - a.vec(3)*b.vec(2); + c.vec(2) = a.vec(3)*b.vec(1) - a.vec(1)*b.vec(3); + c.vec(3) = a.vec(1)*b.vec(2) - a.vec(2)*b.vec(1); + return (c); +end cross_product; + +scalar_triple_product: procedure (a, b, c) returns (fixed); + declare (a, b, c) type(vector); + declare t type (vector); + t = cross_product(b, c); + return (dot_product(a, t)); +end scalar_triple_product; + +vector_triple_product: procedure (a, b, c) returns (type(vector)); + declare (a, b, c) type(vector); + declare (t, e) type (vector); + t = cross_product(b, c); + e = cross_product(a, t); + return (e); +end vector_triple_product; + +end test_products; diff --git a/Task/Vector-products/Pascal/vector-products.pascal b/Task/Vector-products/Pascal/vector-products.pascal new file mode 100644 index 0000000000..6ef99e69e8 --- /dev/null +++ b/Task/Vector-products/Pascal/vector-products.pascal @@ -0,0 +1,48 @@ +Program VectorProduct (output); + +type + Tvector = record + x, y, z: double + end; + +function dotProduct(a, b: Tvector): double; +begin + dotProduct := a.x*b.x + a.y*b.y + a.z*b.z; +end; + +function crossProduct(a, b: Tvector): Tvector; +begin + crossProduct.x := a.y*b.z - a.z*b.y; + crossProduct.y := a.z*b.x - a.x*b.z; + crossProduct.z := a.x*b.y - a.y*b.x; +end; + +function scalarTripleProduct(a, b, c: Tvector): double; +begin + scalarTripleProduct := dotProduct(a, crossProduct(b, c)); +end; + +function vectorTripleProduct(a, b, c: Tvector): Tvector; +begin + vectorTripleProduct := crossProduct(a, crossProduct(b, c)); +end; + +procedure printVector(a: Tvector); +begin + writeln(a.x:15:8, a.y:15:8, a.z:15:8); +end; + +var + a: Tvector = (x: 3; y: 4; z: 5); + b: Tvector = (x: 4; y: 3; z: 5); + c: Tvector = (x:-5; y:-12; z:-13); + +begin + write('a: '); printVector(a); + write('b: '); printVector(b); + write('c: '); printVector(c); + writeln('a . b: ', dotProduct(a,b):15:8); + write('a x b: '); printVector(crossProduct(a,b)); + writeln('a . (b x c): ', scalarTripleProduct(a,b,c):15:8); + write('a x (b x c): '); printVector(vectorTripleProduct(a,b,c)); +end. diff --git a/Task/Vector-products/Perl-6/vector-products.pl6 b/Task/Vector-products/Perl-6/vector-products.pl6 new file mode 100644 index 0000000000..e5f4898a71 --- /dev/null +++ b/Task/Vector-products/Perl-6/vector-products.pl6 @@ -0,0 +1,20 @@ +sub infix:<⋅> { [+] @^a »*« @^b } + +sub infix:<⨯>([$a1, $a2, $a3], [$b1, $b2, $b3]) { + [ $a2*$b3 - $a3*$b2, + $a3*$b1 - $a1*$b3, + $a1*$b2 - $a2*$b1 ]; +} + +sub scalar-triple-product { @^a ⋅ (@^b ⨯ @^c) } +sub vector-triple-product { @^a ⨯ (@^b ⨯ @^c) } + +my @a = <3 4 5>; +my @b = <4 3 5>; +my @c = <-5 -12 -13>; + +say (:@a, :@b, :@c).perl; +say "a ⋅ b = { @a ⋅ @b }"; +say "a ⨯ b = <{ @a ⨯ @b }>"; +say "a ⋅ (b ⨯ c) = { scalar-triple-product(@a, @b, @c) }"; +say "a ⨯ (b ⨯ c) = <{ vector-triple-product(@a, @b, @c) }>"; diff --git a/Task/Vector-products/Perl/vector-products.pl b/Task/Vector-products/Perl/vector-products.pl new file mode 100644 index 0000000000..8d3757e1b0 --- /dev/null +++ b/Task/Vector-products/Perl/vector-products.pl @@ -0,0 +1,28 @@ +package Vector; +use List::Util 'sum'; +use List::MoreUtils 'pairwise'; + +sub new { shift; bless [@_] } + +use overload ( + '""' => sub { "(@{+shift})" }, + '&' => sub { sum pairwise { $a * $b } @{+shift}, @{+shift} }, + '^' => sub { + my @a = @{+shift}; + my @b = @{+shift}; + bless [ $a[1]*$b[2] - $a[2]*$b[1], + $a[2]*$b[0] - $a[0]*$b[2], + $a[0]*$b[1] - $a[1]*$b[0] ] + }, +); + +package main; +my $a = Vector->new(3, 4, 5); +my $b = Vector->new(4, 3, 5); +my $c = Vector->new(-5, -12, -13); + +print "a = $a b = $b c = $c\n"; +print "$a . $b = ", $a & $b, "\n"; +print "$a x $b = ", $a ^ $b, "\n"; +print "$a . ($b x $c) = ", $a & ($b ^ $c), "\n"; +print "$a x ($b x $c) = ", $a ^ ($b ^ $c), "\n"; diff --git a/Task/Vector-products/PicoLisp/vector-products.l b/Task/Vector-products/PicoLisp/vector-products.l new file mode 100644 index 0000000000..7d5fdf83e5 --- /dev/null +++ b/Task/Vector-products/PicoLisp/vector-products.l @@ -0,0 +1,14 @@ +(de dotProduct (A B) + (sum * A B) ) + +(de crossProduct (A B) + (list + (- (* (cadr A) (caddr B)) (* (caddr A) (cadr B))) + (- (* (caddr A) (car B)) (* (car A) (caddr B))) + (- (* (car A) (cadr B)) (* (cadr A) (car B))) ) ) + +(de scalarTriple (A B C) + (dotProduct A (crossProduct B C)) ) + +(de vectorTriple (A B C) + (crossProduct A (crossProduct B C)) ) diff --git a/Task/Vector-products/PureBasic/vector-products.purebasic b/Task/Vector-products/PureBasic/vector-products.purebasic new file mode 100644 index 0000000000..f2d948f75c --- /dev/null +++ b/Task/Vector-products/PureBasic/vector-products.purebasic @@ -0,0 +1,50 @@ +Structure vector + x.f + y.f + z.f +EndStructure + +;convert vector to a string for display +Procedure.s toString(*v.vector) + ProcedureReturn "[" + StrF(*v\x, 2) + ", " + StrF(*v\y, 2) + ", " + StrF(*v\z, 2) + "]" +EndProcedure + +Procedure.f dotProduct(*a.vector, *b.vector) + ProcedureReturn *a\x * *b\x + *a\y * *b\y + *a\z * *b\z +EndProcedure + +Procedure crossProduct(*a.vector, *b.vector, *r.vector) + *r\x = *a\y * *b\z - *a\z * *b\y + *r\y = *a\z * *b\x - *a\x * *b\z + *r\z = *a\x * *b\y - *a\y * *b\x +EndProcedure + +Procedure.f scalarTriple(*a.vector, *b.vector, *c.vector) + Protected r.vector + crossProduct(*b, *c, r) + ProcedureReturn dotProduct(*a, r) +EndProcedure + +Procedure vectorTriple(*a.vector, *b.vector, *c.vector, *r.vector) + Protected r.vector + crossProduct(*b, *c, r) + crossProduct(*a, r, *r) +EndProcedure + +If OpenConsole() + Define.vector a, b, c, r + a\x = 3: a\y = 4: a\z = 5 + b\x = 4: b\y = 3: b\z = 5 + c\x = -5: c\y = -12: c\z = -13 + + PrintN("a = " + toString(a) + ", b = " + toString(b) + ", c = " + toString(c)) + PrintN("a . b = " + StrF(dotProduct(a, b), 2)) + crossProduct(a, b, r) + PrintN("a x b = " + toString(r)) + PrintN("a . b x c = " + StrF(scalarTriple(a, b, c), 2)) + vectorTriple(a, b, c, r) + PrintN("a x b x c = " + toString(r)) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Vector-products/Python/vector-products.py b/Task/Vector-products/Python/vector-products.py new file mode 100644 index 0000000000..06e97e9a99 --- /dev/null +++ b/Task/Vector-products/Python/vector-products.py @@ -0,0 +1,27 @@ +def crossp(a, b): + '''Cross product of two 3D vectors''' + assert len(a) == len(b) == 3, 'For 3D vectors only' + a1, a2, a3 = a + b1, b2, b3 = b + return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) + +def dotp(a,b): + '''Dot product of two eqi-dimensioned vectors''' + assert len(a) == len(b), 'Vector sizes must match' + return sum(aterm * bterm for aterm,bterm in zip(a, b)) + +def scalartriplep(a, b, c): + '''Scalar triple product of three vectors: "a . (b x c)"''' + return dotp(a, crossp(b, c)) + +def vectortriplep(a, b, c): + '''Vector triple product of three vectors: "a x (b x c)"''' + return crossp(a, crossp(b, c)) + +if __name__ == '__main__': + a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13) + print("a = %r; b = %r; c = %r" % (a, b, c)) + print("a . b =", dotp(a,b)) + print("a x b =", crossp(a,b)) + print("a . (b x c) =", scalartriplep(a, b, c)) + print("a x (b x c) =", vectortriplep(a, b, c)) diff --git a/Task/Vector-products/R/vector-products.r b/Task/Vector-products/R/vector-products.r new file mode 100644 index 0000000000..581fb55776 --- /dev/null +++ b/Task/Vector-products/R/vector-products.r @@ -0,0 +1,10 @@ +a <- c( 3.0, 4.0, 5.0) +b <- c( 4.0, 3.0, 5.0) + +cross <- function(a, b) + c(a[2]*b[3] - a[3]*b[2], + a[3]*b[1] - a[1]*b[3], + a[1]*b[2] - a[2]*b[1]) + +cross(a, b) +# [1] 5 5 -7 diff --git a/Task/Vector-products/REXX/vector-products.rexx b/Task/Vector-products/REXX/vector-products.rexx new file mode 100644 index 0000000000..74dda1bb68 --- /dev/null +++ b/Task/Vector-products/REXX/vector-products.rexx @@ -0,0 +1,29 @@ +/*REXX program computes the products: the dot product, */ +/* the cross product, */ +/* the scalar triple product, and*/ +/* the vector triple product. */ + +a = 3 4 5 /*positive numbers don't need " */ +b = 4 3 5 +c = "-5 -12 -13" + +call tellV 'vector A =',a /*show the A vector, aligned #s*/ +call tellV 'vector B =',b /*show the B vector, aligned #s*/ +call tellV 'vector C =',c /*show the C vector, aligned #s*/ +say +call tellV ' dot product [A∙B] =',dot(a,b) +call tellV 'cross product [AxB] =',cross(a,b) +call tellV 'scalar triple product [A∙(BxC)] =',dot(a,cross(b,c)) +call tellV 'vector triple product [Ax(BxC)] =',cross(a,cross(b,c)) +exit /*stick a fork in it, we're done.*/ +/*─────────────────────────────────────cross subroutine─────────────────*/ +cross: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the CROSS product.*/ + return x2*y3-x3*y2 x3*y1-x1*y3 x1*y2-x2*y1 /*a vector quantity.*/ +/*─────────────────────────────────────dot subroutine───────────────────*/ +dot: procedure; parse arg x1 x2 x3,y1 y2 y3 /*the DOT product.*/ + return x1*y1 + x2*y2 + x3*y3 /*a scaler quantity.*/ +/*─────────────────────────────────────tellV subroutine─────────────────*/ +tellV: procedure; parse arg name,x y z /*display the vector*/ + w=max(4,length(x),length(y),length(z)) /*max width of nums.*/ + say right(name,40) right(x,w) right(y,w) right(z,w) + return diff --git a/Task/Vector-products/Ruby/vector-products.rb b/Task/Vector-products/Ruby/vector-products.rb new file mode 100644 index 0000000000..574aa061c3 --- /dev/null +++ b/Task/Vector-products/Ruby/vector-products.rb @@ -0,0 +1,29 @@ +require 'matrix' + +class Vector + def cross_product(v) + unless size == 3 && v.size == 3 + raise ArgumentError, "Vectors must have size 3" + end + Vector[self[1] * v[2] - self[2] * v[1], + self[2] * v[0] - self[0] * v[2], + self[0] * v[1] - self[1] * v[0]] + end + + def scalar_triple_product(b, c) + self.inner_product(b.cross_product c) + end + + def vector_triple_product(b, c) + self.cross_product(b.cross_product c) + end +end + +a = Vector[3, 4, 5] +b = Vector[4, 3, 5] +c = Vector[-5, -12, -13] + +puts "a dot b = #{a.inner_product b}" +puts "a cross b = #{a.cross_product b}" +puts "a dot (b cross c) = #{a.scalar_triple_product b, c}" +puts "a cross (b cross c) = #{a.vector_triple_product b, c}" diff --git a/Task/Vector-products/Scala/vector-products.scala b/Task/Vector-products/Scala/vector-products.scala new file mode 100644 index 0000000000..5aa0c77df0 --- /dev/null +++ b/Task/Vector-products/Scala/vector-products.scala @@ -0,0 +1,19 @@ +case class Vector3D(x:Double, y:Double, z:Double) { + def dot(v:Vector3D):Double=x*v.x + y*v.y + z*v.z; + def cross(v:Vector3D)=Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x) + def scalarTriple(v1:Vector3D, v2:Vector3D)=this dot (v1 cross v2) + def vectorTriple(v1:Vector3D, v2:Vector3D)=this cross (v1 cross v2) +} + +object VectorTest { + def main(args:Array[String])={ + val a=Vector3D(3,4,5) + val b=Vector3D(4,3,5) + val c=Vector3D(-5,-12,-13) + + println(" a . b : " + (a dot b)) + println(" a x b : " + (a cross b)) + println("a . (b x c) : " + (a scalarTriple(b, c))) + println("a x (b x c) : " + (a vectorTriple(b, c))) + } +} diff --git a/Task/Vector-products/Scheme/vector-products.ss b/Task/Vector-products/Scheme/vector-products.ss new file mode 100644 index 0000000000..d5aabf23f7 --- /dev/null +++ b/Task/Vector-products/Scheme/vector-products.ss @@ -0,0 +1,35 @@ +(define (dot-product A B) + (apply + (map * (vector->list A) (vector->list B)))) + +(define (cross-product A B) + (define len (vector-length A)) + (define xp (make-vector (vector-length A) #f)) + (let loop ((n 0)) + (vector-set! xp n (- + (* (vector-ref A (modulo (+ n 1) len)) + (vector-ref B (modulo (+ n 2) len))) + (* (vector-ref A (modulo (+ n 2) len)) + (vector-ref B (modulo (+ n 1) len))))) + (if (eqv? len (+ n 1)) + xp + (loop (+ n 1))))) + +(define (scalar-triple-product A B C) + (dot-product A (cross-product B C))) + +(define (vector-triple-product A B C) + (cross-product A (cross-product B C))) + + +(define A #( 3 4 5)) +(define B #(4 3 5)) +(define C #(-5 -12 -13)) + +(display "A = ")(display A)(newline) +(display "B = ")(display B)(newline) +(display "C = ")(display C)(newline) +(newline) +(display "A . B = ")(display (dot-product A B))(newline) +(display "A x B = ")(display (cross-product A B))(newline) +(display "A . B x C = ")(display (scalar-triple-product A B C))(newline) +(display "A x B x C = ") (display (vector-triple-product A B C))(newline) diff --git a/Task/Vector-products/Seed7/vector-products.seed7 b/Task/Vector-products/Seed7/vector-products.seed7 new file mode 100644 index 0000000000..e9cae49115 --- /dev/null +++ b/Task/Vector-products/Seed7/vector-products.seed7 @@ -0,0 +1,51 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const type: vec3 is new struct + var float: x is 0.0; + var float: y is 0.0; + var float: z is 0.0; + end struct; + +const func vec3: vec3 (in float: x, in float: y, in float: z) is func + result + var vec3: aVector is vec3.value; + begin + aVector.x := x; + aVector.y := y; + aVector.z := z; + end func; + +$ syntax expr: .(). dot .() is -> 6; +const func float: (in vec3: a) dot (in vec3: b) is + return a.x*b.x + a.y*b.y + a.z*b.z; + +$ syntax expr: .(). X .() is -> 6; +const func vec3: (in vec3: a) X (in vec3: b) is + return vec3(a.y*b.z - a.z*b.y, + a.z*b.x - a.x*b.z, + a.x*b.y - a.y*b.x); + +const func string: str (in vec3: v) is + return "(" <& v.x <& ", " <& v.y <& ", " <& v.z <& ")"; + +enable_output(vec3); + +const func float: scalarTriple (in vec3: a, in vec3: b, in vec3: c) is + return a dot (b X c); + +const func vec3: vectorTriple (in vec3: a, in vec3: b, in vec3: c) is + return a X (b X c); + +const proc: main is func + local + const vec3: a is vec3(3.0, 4.0, 5.0); + const vec3: b is vec3(4.0, 3.0, 5.0); + const vec3: c is vec3(-5.0, -12.0, -13.0); + begin + writeln("a = " <& a <& ", b = " <& b <& ", c = " <& c); + writeln("a . b = " <& a dot b); + writeln("a x b = " <& a X b); + writeln("a .(b x c) = " <& scalarTriple(a, b, c)); + writeln("a x(b x c) = " <& vectorTriple(a, b, c)); + end func; diff --git a/Task/Vector-products/Tcl/vector-products-1.tcl b/Task/Vector-products/Tcl/vector-products-1.tcl new file mode 100644 index 0000000000..ae94efa178 --- /dev/null +++ b/Task/Vector-products/Tcl/vector-products-1.tcl @@ -0,0 +1,18 @@ +proc dot {A B} { + lassign $A a1 a2 a3 + lassign $B b1 b2 b3 + expr {$a1*$b1 + $a2*$b2 + $a3*$b3} +} +proc cross {A B} { + lassign $A a1 a2 a3 + lassign $B b1 b2 b3 + list [expr {$a2*$b3 - $a3*$b2}] \ + [expr {$a3*$b1 - $a1*$b3}] \ + [expr {$a1*$b2 - $a2*$b1}] +} +proc scalarTriple {A B C} { + dot $A [cross $B $C] +} +proc vectorTriple {A B C} { + cross $A [cross $B $C] +} diff --git a/Task/Vector-products/Tcl/vector-products-2.tcl b/Task/Vector-products/Tcl/vector-products-2.tcl new file mode 100644 index 0000000000..3e6c0c341d --- /dev/null +++ b/Task/Vector-products/Tcl/vector-products-2.tcl @@ -0,0 +1,7 @@ +set a {3 4 5} +set b {4 3 5} +set c {-5 -12 -13} +puts "a • b = [dot $a $b]" +puts "a x b = [cross $a $b]" +puts "a • b x c = [scalarTriple $a $b $c]" +puts "a x b x c = [vectorTriple $a $b $c]" diff --git a/Task/Vector-products/Visual-Basic-.NET/vector-products-1.visual b/Task/Vector-products/Visual-Basic-.NET/vector-products-1.visual new file mode 100644 index 0000000000..158e313f22 --- /dev/null +++ b/Task/Vector-products/Visual-Basic-.NET/vector-products-1.visual @@ -0,0 +1,58 @@ +Public Class Vector3D + Private _x, _y, _z As Double + + Public Sub New(ByVal X As Double, ByVal Y As Double, ByVal Z As Double) + _x = X + _y = Y + _z = Z + End Sub + + Public Property X() As Double + Get + Return _x + End Get + Set(ByVal value As Double) + _x = value + End Set + End Property + + Public Property Y() As Double + Get + Return _y + End Get + Set(ByVal value As Double) + _y = value + End Set + End Property + + Public Property Z() As Double + Get + Return _z + End Get + Set(ByVal value As Double) + _z = value + End Set + End Property + + Public Function Dot(ByVal v2 As Vector3D) As Double + Return (X * v2.X) + (Y * v2.Y) + (Z * v2.Z) + End Function + + Public Function Cross(ByVal v2 As Vector3D) As Vector3D + Return New Vector3D((Y * v2.Z) - (Z * v2.Y), _ + (Z * v2.X) - (X * v2.Z), _ + (X * v2.Y) - (Y * v2.X)) + End Function + + Public Function ScalarTriple(ByVal v2 As Vector3D, ByVal v3 As Vector3D) As Double + Return Me.Dot(v2.Cross(v3)) + End Function + + Public Function VectorTriple(ByRef v2 As Vector3D, ByVal v3 As Vector3D) As Vector3D + Return Me.Cross(v2.Cross(v3)) + End Function + + Public Overrides Function ToString() As String + Return String.Format("({0}, {1}, {2})", _x, _y, _z) + End Function +End Class diff --git a/Task/Vector-products/Visual-Basic-.NET/vector-products-2.visual b/Task/Vector-products/Visual-Basic-.NET/vector-products-2.visual new file mode 100644 index 0000000000..472ca57074 --- /dev/null +++ b/Task/Vector-products/Visual-Basic-.NET/vector-products-2.visual @@ -0,0 +1,19 @@ +Module Module1 + + Sub Main() + Dim v1 As New Vector3D(3, 4, 5) + Dim v2 As New Vector3D(4, 3, 5) + Dim v3 As New Vector3D(-5, -12, -13) + + Console.WriteLine("v1: {0}", v1.ToString()) + Console.WriteLine("v2: {0}", v2.ToString()) + Console.WriteLine("v3: {0}", v3.ToString()) + Console.WriteLine() + + Console.WriteLine("v1 . v2 = {0}", v1.Dot(v2)) + Console.WriteLine("v1 x v2 = {0}", v1.Cross(v2).ToString()) + Console.WriteLine("v1 . (v2 x v3) = {0}", v1.ScalarTriple(v2, v3)) + Console.WriteLine("v1 x (v2 x v3) = {0}", v1.VectorTriple(v2, v3)) + End Sub + +End Module diff --git a/Task/Vector-products/XPL0/vector-products.xpl0 b/Task/Vector-products/XPL0/vector-products.xpl0 new file mode 100644 index 0000000000..2b887a8a27 --- /dev/null +++ b/Task/Vector-products/XPL0/vector-products.xpl0 @@ -0,0 +1,45 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +func DotProd(A, B); \Return the dot product of two 3D vectors +int A, B; \A ù B +return A(0)*B(0) + A(1)*B(1) + A(2)*B(2); + +proc CrossProd(A, B, C); \Calculate the cross product of two 3D vectors +int A, B, C; \C:= A x B +[C(0):= A(1)*B(2) - A(2)*B(1); + C(1):= A(2)*B(0) - A(0)*B(2); + C(2):= A(0)*B(1) - A(1)*B(0); +]; \CrossProd + +func ScalarTriProd(A, B, C); \Return the scalar triple product +int A, B, C; \A ù (B x C) +int D(3); +[CrossProd(B, C, D); +return DotProd(A, D); +]; \ScalarTriProd + +proc VectTriProd(A, B, C, D); \Calculate the vector triple product +int A, B, C, D; \D:= A x (B x C) +int E(3); +[CrossProd(B, C, E); + CrossProd(A, E, D); +]; \CrossProd + + +int A, B, C, D(3); +[A:= [3, 4, 5]; B:= [4, 3, 5]; C:= [-5, -12, -13]; + +IntOut(0, DotProd(A,B)); CrLf(0); + +CrossProd(A, B, D); +IntOut(0, D(0)); ChOut(0, 9\tab\); +IntOut(0, D(1)); ChOut(0, 9\tab\); +IntOut(0, D(2)); CrLf(0); + +IntOut(0, ScalarTriProd(A,B,C)); CrLf(0); + +VectTriProd(A, B, C, D); +IntOut(0, D(0)); ChOut(0, 9\tab\); +IntOut(0, D(1)); ChOut(0, 9\tab\); +IntOut(0, D(2)); CrLf(0); +] diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/0DESCRIPTION b/Task/Verify-distribution-uniformity-Chi-squared-test/0DESCRIPTION new file mode 100644 index 0000000000..432c74807c --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/0DESCRIPTION @@ -0,0 +1,4 @@ +In this task, write a function to verify that a given distribution of values is uniform by using the [[wp:Pearson's chi-square test|\chi^2 test]] to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce. + +More information about the \chi^2 distribution may be found at +[http://mathworld.wolfram.com/Chi-SquaredDistribution.html mathworld]. diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/1META.yaml b/Task/Verify-distribution-uniformity-Chi-squared-test/1META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-1.c b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-1.c new file mode 100644 index 0000000000..ce0cbd75fd --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-1.c @@ -0,0 +1,68 @@ +#include +#include +#include +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +typedef double (* Ifctn)( double t); +/* Numerical integration method */ +double Simpson3_8( Ifctn f, double a, double b, int N) +{ + int j; + double l1; + double h = (b-a)/N; + double h1 = h/3.0; + double sum = f(a) + f(b); + + for (j=3*N-1; j>0; j--) { + l1 = (j%3)? 3.0 : 2.0; + sum += l1*f(a+h1*j) ; + } + return h*sum/8.0; +} + +#define A 12 +double Gamma_Spouge( double z ) +{ + int k; + static double cspace[A]; + static double *coefs = NULL; + double accum; + double a = A; + + if (!coefs) { + double k1_factrl = 1.0; + coefs = cspace; + coefs[0] = sqrt(2.0*M_PI); + for(k=1; k 2.0e-8) && (y < x)) y += .4; + if (y>x) y=x; + + return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a); +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-2.c b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-2.c new file mode 100644 index 0000000000..0311b11aa2 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-2.c @@ -0,0 +1,28 @@ +double chi2UniformDistance( double *ds, int dslen) +{ + double expected = 0.0; + double sum = 0.0; + int k; + + for (k=0; k significance; +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-3.c b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-3.c new file mode 100644 index 0000000000..95c33e9931 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/C/verify-distribution-uniformity-chi-squared-test-3.c @@ -0,0 +1,25 @@ +int main(int argc, char **argv) +{ + double dset1[] = { 199809., 200665., 199607., 200270., 199649. }; + double dset2[] = { 522573., 244456., 139979., 71531., 21461. }; + double *dsets[] = { dset1, dset2 }; + int dslens[] = { 5, 5 }; + int k, l; + double dist, prob; + int dof; + + for (k=0; k<2; k++) { + printf("Dataset: [ "); + for(l=0;l a + (b - avg) ^^ 2)(0.0L, data); + return sqs / avg; +} + +real x2Prob(in real dof, in real distance) /*pure nothrow*/ { + return gammaIncompleteCompl(dof / 2, distance / 2); +} + +bool x2IsUniform(T)(in T[] data, in real significance=0.05L) +/*pure nothrow*/ { + return x2Prob(data.length - 1.0L, x2Dist(data)) > significance; +} + +void main() { + immutable dataSets = [[199809, 200665, 199607, 200270, 199649], + [522573, 244456, 139979, 71531, 21461]]; + writefln(" %4s %12s %12s %8s %s", + "dof", "distance", "probability", "Uniform?", "dataset"); + foreach (immutable(int[]) ds; dataSets) { + immutable dof = ds.length - 1; + immutable dist = x2Dist(ds); + immutable prob = x2Prob(dof, dist); + writefln("%4d %12.3f %12.8f %5s %6s", + dof, dist, prob, x2IsUniform(ds) ? "YES" : "NO", ds); + } +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-1.f b/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-1.f new file mode 100644 index 0000000000..cad37897ef --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-1.f @@ -0,0 +1,10 @@ +module GSLMiniBind + implicit none + + interface + real(c_double) function gsl_sf_gamma_inc(a, x) bind(C) + use iso_c_binding + real(c_double), value, intent(in) :: a, x + end function gsl_sf_gamma_inc + end interface +end module GSLMiniBind diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-2.f b/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-2.f new file mode 100644 index 0000000000..11f9fa42b1 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Fortran/verify-distribution-uniformity-chi-squared-test-2.f @@ -0,0 +1,67 @@ +program ChiTest + use GSLMiniBind + use iso_c_binding + implicit none + + real, dimension(5) :: dset1 = (/ 199809., 200665., 199607., 200270., 199649. /) + real, dimension(5) :: dset2 = (/ 522573., 244456., 139979., 71531., 21461. /) + + real :: dist, prob + integer :: dof + + print *, "Dataset 1:" + print *, dset1 + dist = chi2UniformDistance(dset1) + dof = size(dset1) - 1 + write(*, '(A,I4,A,F12.4)') 'dof: ', dof, ' distance: ', dist + prob = chi2Probability(dof, dist) + write(*, '(A,F9.6)') 'probability: ', prob + write(*, '(A,L)') 'uniform? ', chiIsUniform(dset1, 0.05) + + ! Lazy copy/past :| + print *, "Dataset 2:" + print *, dset2 + dist = chi2UniformDistance(dset2) + dof = size(dset2) - 1 + write(*, '(A,I4,A,F12.4)') 'dof: ', dof, ' distance: ', dist + prob = chi2Probability(dof, dist) + write(*, '(A,F9.6)') 'probability: ', prob + write(*, '(A,L)') 'uniform? ', chiIsUniform(dset2, 0.05) + +contains + +function chi2Probability(dof, distance) + real :: chi2Probability + integer, intent(in) :: dof + real, intent(in) :: distance + + ! in order to make this work, we need linking with GSL library + chi2Probability = gsl_sf_gamma_inc(real(0.5*dof, c_double), real(0.5*distance, c_double)) +end function chi2Probability + +function chiIsUniform(dset, significance) + logical :: chiIsUniform + real, dimension(:), intent(in) :: dset + real, intent(in) :: significance + + integer :: dof + real :: dist + + dof = size(dset) - 1 + dist = chi2UniformDistance(dset) + chiIsUniform = chi2Probability(dof, dist) > significance +end function chiIsUniform + +function chi2UniformDistance(ds) + real :: chi2UniformDistance + real, dimension(:), intent(in) :: ds + + real :: expected, summa = 0.0 + + expected = sum(ds) / size(ds) + summa = sum( (ds - expected) ** 2 ) + + chi2UniformDistance = summa / expected +end function chi2UniformDistance + +end program ChiTest diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Go/verify-distribution-uniformity-chi-squared-test.go b/Task/Verify-distribution-uniformity-Chi-squared-test/Go/verify-distribution-uniformity-chi-squared-test.go new file mode 100644 index 0000000000..f95ec1dded --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Go/verify-distribution-uniformity-chi-squared-test.go @@ -0,0 +1,90 @@ +package main + +import ( + "fmt" + "math" +) + +type ifctn func(float64) float64 + +func simpson38(f ifctn, a, b float64, n int) float64 { + h := (b - a) / float64(n) + h1 := h / 3 + sum := f(a) + f(b) + for j := 3*n - 1; j > 0; j-- { + if j%3 == 0 { + sum += 2 * f(a+h1*float64(j)) + } else { + sum += 3 * f(a+h1*float64(j)) + } + } + return h * sum / 8 +} + +func gammaIncQ(a, x float64) float64 { + aa1 := a - 1 + var f ifctn = func(t float64) float64 { + return math.Pow(t, aa1) * math.Exp(-t) + } + y := aa1 + h := 1.5e-2 + for f(y)*(x-y) > 2e-8 && y < x { + y += .4 + } + if y > x { + y = x + } + return 1 - simpson38(f, 0, y, int(y/h/math.Gamma(a))) +} + +func chi2ud(ds []int) float64 { + var sum, expected float64 + for _, d := range ds { + expected += float64(d) + } + expected /= float64(len(ds)) + for _, d := range ds { + x := float64(d) - expected + sum += x * x + } + return sum / expected +} + +func chi2p(dof int, distance float64) float64 { + return gammaIncQ(.5*float64(dof), .5*distance) +} + +const sigLevel = .05 + +func main() { + for _, dset := range [][]int{ + {199809, 200665, 199607, 200270, 199649}, + {522573, 244456, 139979, 71531, 21461}, + } { + utest(dset) + } +} + +func utest(dset []int) { + fmt.Println("Uniform distribution test") + var sum int + for _, c := range dset { + sum += c + } + fmt.Println(" dataset:", dset) + fmt.Println(" samples: ", sum) + fmt.Println(" categories: ", len(dset)) + + dof := len(dset) - 1 + fmt.Println(" degrees of freedom: ", dof) + + dist := chi2ud(dset) + fmt.Println(" chi square test statistic: ", dist) + + p := chi2p(dof, dist) + fmt.Println(" p-value of test statistic: ", p) + + sig := p < sigLevel + fmt.Printf(" significant at %2.0f%% level? %t\n", sigLevel*100, sig) + fmt.Println(" uniform? ", !sig, "\n") +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-1.j b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-1.j new file mode 100644 index 0000000000..4f35f6b4b3 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-1.j @@ -0,0 +1,13 @@ +require 'stats/base' + +countCats=: #@~. NB. counts the number of unique items +getExpected=: #@] % [ NB. divides no of items by category count +getObserved=: #/.~@] NB. counts frequency for each category +calcX2=: [: +/ *:@(getObserved - getExpected) % getExpected NB. calculates test statistic +calcDf=: <:@[ NB. calculates degrees of freedom for uniform distribution + +NB.*isUniform v Tests (5%) whether y is uniformly distributed +NB. result is: boolean describing if distribution y is uniform +NB. y is: distribution to test +NB. x is: optionally specify number of categories possible +isUniform=: (countCats $: ]) : (0.95 > calcDf chisqcdf :: 1: calcX2) diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-2.j b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-2.j new file mode 100644 index 0000000000..b86f7ff8d5 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-2.j @@ -0,0 +1,16 @@ +require 'stats/base' + +NB.*isUniformX v Tests (5%) whether y is uniformly distributed +NB. result is: boolean describing if distribution y is uniform +NB. y is: distribution to test +NB. x is: optionally specify number of categories possible +isUniformX=: verb define + (#~. y) isUniformX y +: + signif=. 0.95 NB. set significance level + expected=. (#y) % x NB. number of items divided by the category count + observed=. #/.~ y NB. frequency count for each category + X2=. +/ (*: observed - expected) % expected NB. the test statistic + degfreedom=. <: x NB. degrees of freedom + signif > degfreedom chisqcdf :: 1: X2 +) diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-3.j b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-3.j new file mode 100644 index 0000000000..793c47b719 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/J/verify-distribution-uniformity-chi-squared-test-3.j @@ -0,0 +1,10 @@ + FairDistrib=: 1e6 ?@$ 5 + UnfairDistrib=: (9.5e5 ?@$ 5) , (5e4 ?@$ 4) + isUniformX FairDistrib +1 + isUniformX UnfairDistrib +0 + isUniform 4 4 4 5 5 5 5 5 5 5 NB. uniform if only 2 categories possible +1 + 4 isUniform 4 4 4 5 5 5 5 5 5 5 NB. not uniform if 4 categories possible +0 diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-1.math b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-1.math new file mode 100644 index 0000000000..7bbf564c49 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-1.math @@ -0,0 +1,8 @@ +discreteUniformDistributionQ[data_, {min_Integer, max_Integer}, confLevel_: .05] := +If[$VersionNumber >= 8, + confLevel <= PearsonChiSquareTest[data, DiscreteUniformDistribution[{min, max}]], + Block[{v, k = max - min, n = Length@data}, + v = (k + 1) (Plus @@ (((Length /@ Split[Sort@data]))^2))/n - n; + GammaRegularized[k/2, 0, v/2] <= 1 - confLevel]] + +discreteUniformDistributionQ[data_] :=discreteUniformDistributionQ[data, data[[Ordering[data][[{1, -1}]]]]] diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-2.math b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-2.math new file mode 100644 index 0000000000..99ed9fa712 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-2.math @@ -0,0 +1,2 @@ +uniformData = RandomInteger[10, 100]; +nonUniformData = Total@RandomInteger[10, {5, 100}]; diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-3.math b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-3.math new file mode 100644 index 0000000000..b5305f9399 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Mathematica/verify-distribution-uniformity-chi-squared-test-3.math @@ -0,0 +1 @@ +{discreteUniformDistributionQ[uniformData],discreteUniformDistributionQ[nonUniformData]} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/OCaml/verify-distribution-uniformity-chi-squared-test.ocaml b/Task/Verify-distribution-uniformity-Chi-squared-test/OCaml/verify-distribution-uniformity-chi-squared-test.ocaml new file mode 100644 index 0000000000..982914e3e4 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/OCaml/verify-distribution-uniformity-chi-squared-test.ocaml @@ -0,0 +1,34 @@ +let sqr x = x *. x + +let chi2UniformDistance distrib = + let count, len = Array.fold_left (fun (s, c) e -> s + e, succ c) + (0, 0) distrib in + let expected = float count /. float len in + let distance = Array.fold_left (fun s e -> + s +. sqr (float e -. expected) /. expected + ) 0. distrib in + let dof = float (pred len) in + dof, distance + +let chi2Proba dof distance = + Gsl_sf.gamma_inc_Q (0.5 *. dof) (0.5 *. distance) + +let chi2IsUniform distrib significance = + let dof, distance = chi2UniformDistance distrib in + let likelihoodOfRandom = chi2Proba dof distance in + likelihoodOfRandom > significance + +let _ = + List.iter (fun distrib -> + let dof, distance = chi2UniformDistance distrib in + Printf.printf "distribution "; + Array.iter (Printf.printf "\t%d") distrib; + Printf.printf "\tdistance %g" distance; + Printf.printf "\t[%g > 0.05]" (chi2Proba dof distance); + if chi2IsUniform distrib 0.05 then Printf.printf " fair\n" + else Printf.printf " unfair\n" + ) + [ + [| 199809; 200665; 199607; 200270; 199649 |]; + [| 522573; 244456; 139979; 71531; 21461 |] + ] diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/PARI-GP/verify-distribution-uniformity-chi-squared-test.pari b/Task/Verify-distribution-uniformity-Chi-squared-test/PARI-GP/verify-distribution-uniformity-chi-squared-test.pari new file mode 100644 index 0000000000..cdf020bd15 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/PARI-GP/verify-distribution-uniformity-chi-squared-test.pari @@ -0,0 +1,17 @@ +cumChi2(chi2,dof)={ + my(g=gamma(dof/2)); + incgam(dof/2,chi2/2,g)/g +}; +test(v,alpha=.05)={ + my(chi2,p,s=sum(i=1,#v,v[i]),ave=s/#v); + print("chi^2 statistic: ",chi2=sum(i=1,#v,(v[i]-ave)^2)/ave); + print("p-value: ",p=cumChi2(chi2,#v-1)); + if(p(Int $n) { [*] 2..$n } + +sub Γ-of-half(Int $n where * > 0) { + ($n %% 2) ?? (($_-1)! given $n div 2) + !! ((2*$_)! / (4**$_ * $_!) * sqrt(pi) given ($n-1) div 2); +} + +# degrees of freedom constrained due to numerical limitations +sub chi-squared-cdf(Int $k where 1..200, $x where * >= 0) { + my $f = $k < 20 ?? 20 !! 10; + given $x { + when 0 { 0.0 } + when * < $k + $f*sqrt($k) { incomplete-γ-series($k/2, $x/2) / Γ-of-half($k) } + default { 1.0 } + } +} + +sub chi-squared-test(@bins, :$significance = 0.05) { + my $n = +@bins; + my $N = [+] @bins; + my $expected = $N / $n; + my $chi-squared = [+] @bins.map: { ($^bin - $expected)**2 / $expected } + my $p-value = 1 - chi-squared-cdf($n-1, $chi-squared); + return (:$chi-squared, :$p-value, :uniform($p-value > $significance)); +} + +for [< 199809 200665 199607 200270 199649 >], + [< 522573 244456 139979 71531 21461 >] + -> $dataset +{ + my %t = chi-squared-test($dataset); + say 'data: ', $dataset; + say "χ² = {%t}, p-value = {%t.fmt('%.4f')}, uniform = {%t}"; +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Python/verify-distribution-uniformity-chi-squared-test.py b/Task/Verify-distribution-uniformity-Chi-squared-test/Python/verify-distribution-uniformity-chi-squared-test.py new file mode 100644 index 0000000000..484574e877 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Python/verify-distribution-uniformity-chi-squared-test.py @@ -0,0 +1,67 @@ +import math +import random + +def GammaInc_Q( a, x): + a1 = a-1 + a2 = a-2 + def f0( t ): + return t**a1*math.exp(-t) + + def df0(t): + return (a1-t)*t**a2*math.exp(-t) + + y = a1 + while f0(y)*(x-y) >2.0e-8 and y < x: y += .3 + if y > x: y = x + + h = 3.0e-4 + n = int(y/h) + h = y/n + hh = 0.5*h + gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1))) + + return gamax/gamma_spounge(a) + +c = None +def gamma_spounge( z): + global c + a = 12 + + if c is None: + k1_factrl = 1.0 + c = [] + c.append(math.sqrt(2.0*math.pi)) + for k in range(1,a): + c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl ) + k1_factrl *= -k + + accm = c[0] + for k in range(1,a): + accm += c[k] / (z+k) + accm *= math.exp( -(z+a)) * (z+a)**(z+0.5) + return accm/z; + +def chi2UniformDistance( dataSet ): + expected = sum(dataSet)*1.0/len(dataSet) + cntrd = (d-expected for d in dataSet) + return sum(x*x for x in cntrd)/expected + +def chi2Probability(dof, distance): + return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance) + +def chi2IsUniform(dataSet, significance): + dof = len(dataSet)-1 + dist = chi2UniformDistance(dataSet) + return chi2Probability( dof, dist ) > significance + +dset1 = [ 199809, 200665, 199607, 200270, 199649 ] +dset2 = [ 522573, 244456, 139979, 71531, 21461 ] + +for ds in (dset1, dset2): + print "Data set:", ds + dof = len(ds)-1 + distance =chi2UniformDistance(ds) + print "dof: %d distance: %.4f" % (dof, distance), + prob = chi2Probability( dof, distance) + print "probability: %.4f"%prob, + print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No" diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/R/verify-distribution-uniformity-chi-squared-test.r b/Task/Verify-distribution-uniformity-Chi-squared-test/R/verify-distribution-uniformity-chi-squared-test.r new file mode 100644 index 0000000000..e1f43b04aa --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/R/verify-distribution-uniformity-chi-squared-test.r @@ -0,0 +1,12 @@ +dset1=c(199809,200665,199607,200270,199649) +dset2=c(522573,244456,139979,71531,21461) + +chi2IsUniform<-function(dataset,significance=0.05){ + chi2IsUniform=(chisq.test(dataset)$p.value>significance) +} + +for (ds in list(dset1,dset2)){ + print(c("Data set:",ds)) + print(chisq.test(ds)) + print(paste("uniform?",chi2IsUniform(ds))) +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-1.tcl b/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-1.tcl new file mode 100644 index 0000000000..00e19bedb2 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-1.tcl @@ -0,0 +1,15 @@ +package require Tcl 8.5 +package require math::statistics + +proc isUniform {distribution {significance 0.05}} { + set count [tcl::mathop::+ {*}[dict values $distribution]] + set expected [expr {double($count) / [dict size $distribution]}] + set X2 0.0 + foreach value [dict values $distribution] { + set X2 [expr {$X2 + ($value - $expected)**2 / $expected}] + } + set degreesOfFreedom [expr {[dict size $distribution] - 1}] + set likelihoodOfRandom [::math::statistics::incompleteGamma \ + [expr {$degreesOfFreedom / 2.0}] [expr {$X2 / 2.0}]] + expr {$likelihoodOfRandom > $significance} +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-2.tcl b/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-2.tcl new file mode 100644 index 0000000000..3ad9c90bef --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Tcl/verify-distribution-uniformity-chi-squared-test-2.tcl @@ -0,0 +1,9 @@ +proc makeDistribution {operation {count 1000000}} { + for {set i 0} {$i<$count} {incr i} {incr distribution([uplevel 1 $operation])} + return [array get distribution] +} + +set distFair [makeDistribution {expr int(rand()*5)}] +puts "distribution \"$distFair\" assessed as [expr [isUniform $distFair]?{fair}:{unfair}]" +set distUnfair [makeDistribution {expr int(rand()*rand()*5)}] +puts "distribution \"$distUnfair\" assessed as [expr [isUniform $distUnfair]?{fair}:{unfair}]" diff --git a/Task/Verify-distribution-uniformity-Naive/0DESCRIPTION b/Task/Verify-distribution-uniformity-Naive/0DESCRIPTION new file mode 100644 index 0000000000..52df8b5ccf --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/0DESCRIPTION @@ -0,0 +1,17 @@ +This task is an adjunct to [[Seven-dice from Five-dice]]. + +Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. + +The function should take as arguments: +* The function (or object) producing random integers. +* The number of times to call the integer generator. +* A 'delta' value of some sort that indicates how close to a flat distribution is close enough. + +The function should produce: +* Some indication of the distribution achieved. +* An 'error' if the distribution is not flat enough. + +Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-dice from Five-dice]]). + +See also: +*[[Verify distribution uniformity/Chi-squared test]] diff --git a/Task/Verify-distribution-uniformity-Naive/1META.yaml b/Task/Verify-distribution-uniformity-Naive/1META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/Verify-distribution-uniformity-Naive/Ada/verify-distribution-uniformity-naive.ada b/Task/Verify-distribution-uniformity-Naive/Ada/verify-distribution-uniformity-naive.ada new file mode 100644 index 0000000000..b0c2dd6de3 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Ada/verify-distribution-uniformity-naive.ada @@ -0,0 +1,51 @@ +with Ada.Numerics.Discrete_Random, Ada.Text_IO; + +procedure Naive_Random is + + type M_1000 is mod 1000; + package Rand is new Ada.Numerics.Discrete_Random(M_1000); + Gen: Rand.Generator; + + procedure Perform(Modulus: Positive; Expected, Margin: Natural; + Passed: out boolean) is + Low: Natural := (100-Margin) * Expected/100; + High: Natural := (100+Margin) * Expected/100; + Buckets: array(0 .. Modulus-1) of Natural := (others => 0); + Index: Natural; + begin + for I in 1 .. Expected * Modulus loop + Index := Integer(Rand.Random(Gen)) mod Modulus; + Buckets(Index) := Buckets(Index) + 1; + end loop; + Passed := True; + for I in Buckets'Range loop + Ada.Text_IO.Put("Bucket" & Integer'Image(I+1) & ":" & + Integer'Image(Buckets(I))); + if Buckets(I) < Low or else Buckets(I) > High then + Ada.Text_IO.Put_Line(" (failed)"); + Passed := False; + else + Ada.Text_IO.Put_Line(" (passed)"); + end if; + end loop; + Ada.Text_IO.New_Line; + end Perform; + + Number_Of_Buckets: Positive := Natural'Value(Ada.Text_IO.Get_Line); + Expected_Per_Bucket: Natural := Natural'Value(Ada.Text_IO.Get_Line); + Margin_In_Percent: Natural := Natural'Value(Ada.Text_IO.Get_Line); + OK: Boolean; + +begin + Ada.Text_IO.Put_Line( "Buckets:" & Integer'Image(Number_Of_Buckets) & + ", Expected:" & Integer'Image(Expected_Per_Bucket) & + ", Margin:" & Integer'Image(Margin_In_Percent)); + Rand.Reset(Gen); + + Perform(Modulus => Number_Of_Buckets, + Expected => Expected_Per_Bucket, + Margin => Margin_In_Percent, + Passed => OK); + + Ada.Text_IO.Put_Line("Test Passed? (" & Boolean'Image(OK) & ")"); +end Naive_Random; diff --git a/Task/Verify-distribution-uniformity-Naive/AutoHotkey/verify-distribution-uniformity-naive.ahk b/Task/Verify-distribution-uniformity-Naive/AutoHotkey/verify-distribution-uniformity-naive.ahk new file mode 100644 index 0000000000..a03115f5da --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/AutoHotkey/verify-distribution-uniformity-naive.ahk @@ -0,0 +1,23 @@ +MsgBox, % DistCheck("dice7",10000,3) + +DistCheck(function, repetitions, delta) +{ Loop, % 7 ; initialize array + { bucket%A_Index% := 0 + } + + Loop, % repetitions ; populate buckets + { v := %function%() + bucket%v% += 1 + } + + lbnd := round((repetitions/7)*(100-delta)/100) + ubnd := round((repetitions/7)*(100+delta)/100) + text := "Distribution check:`n`nTotal elements = " repetitions + . "`n`nMargin = " delta "% --> Lbound = " lbnd ", Ubound = " ubnd "`n" + Loop, % 7 + { text := text "`nBucket " A_Index " contains " bucket%A_Index% " elements." + If bucket%A_Index% not between %lbnd% and %ubnd% + text := text " Skewed." + } + Return, text +} diff --git a/Task/Verify-distribution-uniformity-Naive/BBC-BASIC/verify-distribution-uniformity-naive.bbc b/Task/Verify-distribution-uniformity-Naive/BBC-BASIC/verify-distribution-uniformity-naive.bbc new file mode 100644 index 0000000000..5fc073c8a5 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/BBC-BASIC/verify-distribution-uniformity-naive.bbc @@ -0,0 +1,27 @@ + MAXRND = 7 + FOR r% = 2 TO 5 + check% = FNdistcheck(FNdice5, 10^r%, 0.05) + PRINT "Over "; 10^r% " runs dice5 "; + IF check% THEN + PRINT "failed distribution check with "; check% " bin(s) out of range" + ELSE + PRINT "passed distribution check" + ENDIF + NEXT + END + + DEF FNdistcheck(RETURN func%, repet%, delta) + LOCAL i%, m%, r%, s%, bins%() + DIM bins%(MAXRND) + FOR i% = 1 TO repet% + r% = FN(^func%) + bins%(r%) += 1 + IF r%>m% m% = r% + NEXT + FOR i% = 1 TO m% + IF bins%(i%)/(repet%/m%) > 1+delta s% += 1 + IF bins%(i%)/(repet%/m%) < 1-delta s% += 1 + NEXT + = s% + + DEF FNdice5 = RND(5) diff --git a/Task/Verify-distribution-uniformity-Naive/C++/verify-distribution-uniformity-naive.cpp b/Task/Verify-distribution-uniformity-Naive/C++/verify-distribution-uniformity-naive.cpp new file mode 100644 index 0000000000..eb77effdf3 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/C++/verify-distribution-uniformity-naive.cpp @@ -0,0 +1,31 @@ +#include +#include +#include + +template + bool test_distribution(F f, int calls, double delta) +{ + typedef std::map distmap; + distmap dist; + + for (int i = 0; i < calls; ++i) + ++dist[f()]; + + double mean = 1.0/dist.size(); + + bool good = true; + + for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) + { + if (std::abs((1.0 * i->second)/calls - mean) > delta) + { + std::cout << "Relative frequency " << i->second/(1.0*calls) + << " of result " << i->first + << " deviates by more than " << delta + << " from the expected value " << mean << "\n"; + good = false; + } + } + + return good; +} diff --git a/Task/Verify-distribution-uniformity-Naive/C/verify-distribution-uniformity-naive.c b/Task/Verify-distribution-uniformity-Naive/C/verify-distribution-uniformity-naive.c new file mode 100644 index 0000000000..54b0cfdafe --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/C/verify-distribution-uniformity-naive.c @@ -0,0 +1,46 @@ +#include +#include +#include + +inline int rand5() +{ + int r, rand_max = RAND_MAX - (RAND_MAX % 5); + while ((r = rand()) >= rand_max); + return r / (rand_max / 5) + 1; +} + +inline int rand5_7() +{ + int r; + while ((r = rand5() * 5 + rand5()) >= 27); + return r / 3 - 1; +} + +/* assumes gen() returns a value from 1 to n */ +int check(int (*gen)(), int n, int cnt, double delta) /* delta is relative */ +{ + int i = cnt, *bins = calloc(sizeof(int), n); + double ratio; + while (i--) bins[gen() - 1]++; + for (i = 0; i < n; i++) { + ratio = bins[i] * n / (double)cnt - 1; + if (ratio > -delta && ratio < delta) continue; + + printf("bin %d out of range: %d (%g%% vs %g%%), ", + i + 1, bins[i], ratio * 100, delta * 100); + break; + } + free(bins); + return i == n; +} + +int main() +{ + int cnt = 1; + while ((cnt *= 10) <= 1000000) { + printf("Count = %d: ", cnt); + printf(check(rand5_7, 7, cnt, 0.03) ? "flat\n" : "NOT flat\n"); + } + + return 0; +} diff --git a/Task/Verify-distribution-uniformity-Naive/Clojure/verify-distribution-uniformity-naive.clj b/Task/Verify-distribution-uniformity-Naive/Clojure/verify-distribution-uniformity-naive.clj new file mode 100644 index 0000000000..9d0aa9ddfb --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Clojure/verify-distribution-uniformity-naive.clj @@ -0,0 +1,12 @@ +(defn verify [rand n & [delta]] + (let [rands (frequencies (repeatedly n rand)) + avg (/ (reduce + (map val rands)) (count rands)) + max-delta (* avg (or delta 1/10)) + acceptable? #(<= (- avg max-delta) % (+ avg max-delta))] + (for [[num count] (sort rands)] + [num count (acceptable? count)]))) + +(doseq [n [100 1000 10000] + [num count okay?] (verify #(rand-int 7) n)] + (println "Saw" num count "times:" + (if okay? "that's" " not") "acceptable")) diff --git a/Task/Verify-distribution-uniformity-Naive/Common-Lisp/verify-distribution-uniformity-naive.lisp b/Task/Verify-distribution-uniformity-Naive/Common-Lisp/verify-distribution-uniformity-naive.lisp new file mode 100644 index 0000000000..9c13084454 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Common-Lisp/verify-distribution-uniformity-naive.lisp @@ -0,0 +1,9 @@ +(defun check-distribution (function n &optional (delta 1.0)) + (let ((bins (make-hash-table))) + (loop repeat n do (incf (gethash (funcall function) bins 0))) + (loop with target = (/ n (hash-table-count bins)) + for key being each hash-key of bins using (hash-value value) + when (> (abs (- value target)) (* 0.01 delta n)) + do (format t "~&Distribution potentially skewed for ~w:~ + expected around ~w got ~w." key target value) + finally (return bins)))) diff --git a/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d b/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d new file mode 100644 index 0000000000..33ae525986 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/D/verify-distribution-uniformity-naive.d @@ -0,0 +1,31 @@ +import std.stdio, std.string, std.math, std.algorithm, std.traits; + +/** +Bin the answers to fn() and check bin counts are within ++/- delta % of repeats/bincount. +*/ +void distCheck(TF)(in TF func, in int nRepeats, in double delta) +if (isCallable!TF) { + int[int] counts; + foreach (i; 0 .. nRepeats) + counts[func()]++; + immutable double target = nRepeats / cast(double)counts.length; + immutable int deltaCount = cast(int)(delta / 100.0 * target); + + foreach (k, count; counts) + if (abs(target - count) >= deltaCount) + throw new Exception(format( + "distribution potentially skewed for '%s': '%d'\n", + k, count)); + + foreach (k; counts.keys.sort()) + writeln(k, " ", counts[k]); + writeln(); +} + +version (verify_distribution_uniformity_naive_main) { + void main() { + import std.random; + distCheck(() => uniform(1, 6), 1_000_000, 1); + } +} diff --git a/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-1.euler b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-1.euler new file mode 100644 index 0000000000..d93e116178 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-1.euler @@ -0,0 +1,15 @@ +>function checkrandom (frand$, n:index, delta:positive real) ... +$ v=zeros(1,n); +$ loop 1 to n; v{#}=frand$(); end; +$ K=max(v); +$ fr=getfrequencies(v,1:K); +$ return max(fr/n-1/K)function dice () := intrandom(1,1,6); +>checkrandom("dice",1000000,1) + 1 +>wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6 + [ 0 0.165 0.335 0.5 0.666666666667 0.833333333333 1 ] +>function wrongdice () := find(wd,random()) +>checkrandom("wrongdice",1000000,1) + 0 diff --git a/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-2.euler b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-2.euler new file mode 100644 index 0000000000..a06823110c --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-2.euler @@ -0,0 +1,9 @@ +>function dice5 () := intrandom(1,1,5); +>function dice7 () ... +$ repeat +$ k=(dice5()-1)*5+dice5(); +$ if k<=21 then return ceil(k/3); endif; +$ end; +$ endfunction +>checkrandom("dice7",1000000,1) + 1 diff --git a/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-3.euler b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-3.euler new file mode 100644 index 0000000000..de444c66b7 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Euler-Math-Toolbox/verify-distribution-uniformity-naive-3.euler @@ -0,0 +1,18 @@ +>function dice5(n) := intrandom(1,n,5)-1; +>function dice7(n) ... +$ v=dice5(2*n)*5+dice5(2*n); +$ return v[nonzeros(v<=21)][1:n]; +$ endfunction +>test=dice7(1000000); +>function checkrandom (v, delta=1) ... +$ K=max(v); n=cols(v); +$ fr=getfrequencies(v,1:K); +$ return max(fr/n-1/K)checkrandom(test) + 1 +>wd = 0|((1:6)+[-0.01,0.01,0,0,0,0])/6 + [ 0 0.165 0.335 0.5 0.666666666667 0.833333333333 1 ] +>function wrongdice (n) := find(wd,random(1,n)) +>checkrandom(wrongdice(1000000)) + 0 diff --git a/Task/Verify-distribution-uniformity-Naive/Fortran/verify-distribution-uniformity-naive.f b/Task/Verify-distribution-uniformity-Naive/Fortran/verify-distribution-uniformity-naive.f new file mode 100644 index 0000000000..13581309c2 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Fortran/verify-distribution-uniformity-naive.f @@ -0,0 +1,46 @@ +subroutine distcheck(randgen, n, delta) + + interface + function randgen + integer :: randgen + end function randgen + end interface + + real, intent(in) :: delta + integer, intent(in) :: n + integer :: i, mval, lolim, hilim + integer, allocatable :: buckets(:) + integer, allocatable :: rnums(:) + logical :: skewed = .false. + + allocate(rnums(n)) + + do i = 1, n + rnums(i) = randgen() + end do + + mval = maxval(rnums) + allocate(buckets(mval)) + buckets = 0 + + do i = 1, n + buckets(rnums(i)) = buckets(rnums(i)) + 1 + end do + + lolim = n/mval - n/mval*delta + hilim = n/mval + n/mval*delta + + do i = 1, mval + if(buckets(i) < lolim .or. buckets(i) > hilim) then + write(*,"(a,i0,a,i0,a,i0)") "Distribution potentially skewed for bucket ", i, " Expected: ", & + n/mval, " Actual: ", buckets(i) + skewed = .true. + end if + end do + + if (.not. skewed) write(*,"(a)") "Distribution uniform" + + deallocate(rnums) + deallocate(buckets) + +end subroutine diff --git a/Task/Verify-distribution-uniformity-Naive/Go/verify-distribution-uniformity-naive.go b/Task/Verify-distribution-uniformity-Naive/Go/verify-distribution-uniformity-naive.go new file mode 100644 index 0000000000..99be996c41 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Go/verify-distribution-uniformity-naive.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "time" +) + +// "given" +func dice5() int { + return rand.Intn(5) + 1 +} + +// function specified by task "Seven-sided dice from five-sided dice" +func dice7() (i int) { + for { + i = 5*dice5() + dice5() + if i < 27 { + break + } + } + return (i / 3) - 1 +} + +// function specified by task "Verify distribution uniformity/Naive" +// +// Parameter "f" is expected to return a random integer in the range 1..n. +// (Values out of range will cause an unceremonious crash.) +// "Max" is returned as an "indication of distribution achieved." +// It is the maximum delta observed from the count representing a perfectly +// uniform distribution. +// Also returned is a boolean, true if "max" is less than threshold +// parameter "delta." +func distCheck(f func() int, n int, + repeats int, delta float64) (max float64, flatEnough bool) { + count := make([]int, n) + for i := 0; i < repeats; i++ { + count[f()-1]++ + } + expected := float64(repeats) / float64(n) + for _, c := range count { + max = math.Max(max, math.Abs(float64(c)-expected)) + } + return max, max < delta +} + +// Driver, produces output satisfying both tasks. +func main() { + rand.Seed(time.Now().UnixNano()) + const calls = 1000000 + max, flatEnough := distCheck(dice7, 7, calls, 500) + fmt.Println("Max delta:", max, "Flat enough:", flatEnough) + max, flatEnough = distCheck(dice7, 7, calls, 500) + fmt.Println("Max delta:", max, "Flat enough:", flatEnough) +} diff --git a/Task/Verify-distribution-uniformity-Naive/Haskell/verify-distribution-uniformity-naive-1.hs b/Task/Verify-distribution-uniformity-Naive/Haskell/verify-distribution-uniformity-naive-1.hs new file mode 100644 index 0000000000..7f52976a67 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Haskell/verify-distribution-uniformity-naive-1.hs @@ -0,0 +1,13 @@ +import System.Random +import Data.List +import Control.Monad +import Control.Arrow + +distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))] +distribCheck f n d = do + nrs <- replicateM n f + let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs + avg = (fromIntegral n) / fromIntegral (length group) + ul = round $ (100 + fromIntegral d)/100 * avg + ll = round $ (100 - fromIntegral d)/100 * avg + return $ map (head &&& (id &&& liftM2 (&&) (>ll)( mapM_ print .sort =<< distribCheck (randomRIO(1,6)) 100000 3 +(1,(16911,True)) +(2,(16599,True)) +(3,(16670,True)) +(4,(16624,True)) +(5,(16526,True)) +(6,(16670,True)) diff --git a/Task/Verify-distribution-uniformity-Naive/Icon/verify-distribution-uniformity-naive.icon b/Task/Verify-distribution-uniformity-Naive/Icon/verify-distribution-uniformity-naive.icon new file mode 100644 index 0000000000..204a12d2f2 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Icon/verify-distribution-uniformity-naive.icon @@ -0,0 +1,31 @@ +# rnd : a co-expression, which will generate the random numbers +# n : the number of numbers to test +# delta: tolerance in non-uniformity +# This procedure fails if after the sampling the difference +# in uniformity exceeds delta, a proportion of n / number-of-alternatives +procedure verify_uniform (rnd, n, delta) + # generate a table counting the outcome of the generator + results := table (0) + every (1 to n) do results[@rnd] +:= 1 + # retrieve the statistics + smallest := n + largest := 0 + every num := key(results) do { # record result and limits + write (num || " " || results[num]) + if results[num] < smallest then smallest := results[num] + if results[num] > largest then largest := results[num] + } + # decide if difference is within bounds defined by delta + return largest-smallest < delta * n / *results +end + +procedure main () + gen_1 := create (|?10) # uniform integers, 1 to 10 + if verify_uniform (gen_1, 1000000, 0.01) + then write ("uniform") + else write ("skewed") + gen_2 := create (|(if ?2 = 1 then 6 else ?10)) # skewed integers, 1 to 10 + if verify_uniform (gen_2, 1000000, 0.01) + then write ("uniform") + else write ("skewed") +end diff --git a/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-1.j b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-1.j new file mode 100644 index 0000000000..71eb59f78a --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-1.j @@ -0,0 +1,12 @@ +checkUniform=: adverb define + 0.05 u checkUniform y + : + n=. */y + delta=. x + sample=. u n NB. the "u" refers to the verb to left of adverb + freqtable=. /:~ (~. sample) ,. #/.~ sample + expected=. n % # freqtable + errmsg=. 'Distribution is potentially skewed' + errmsg assert (delta * expected) > | expected - {:"1 freqtable + freqtable +) diff --git a/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-2.j b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-2.j new file mode 100644 index 0000000000..544732e6f6 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-2.j @@ -0,0 +1,8 @@ +checkUniformT=: adverb define + 0.05 u checkUniformT y + : + freqtable=. /:~ (~. ,. #/.~) u n=. */y + errmsg=. 'Distribution is potentially skewed' + errmsg assert ((n % #) (x&*@[ > |@:-) {:"1) freqtable + freqtable +) diff --git a/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-3.j b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-3.j new file mode 100644 index 0000000000..1a208a9d47 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/J/verify-distribution-uniformity-naive-3.j @@ -0,0 +1,11 @@ + 0.05 rollD7t checkUniform 1e5 +1 14082 +2 14337 +3 14242 +4 14470 +5 14067 +6 14428 +7 14374 + 0.05 rollD7t checkUniform 1e2 +|Distribution is potentially skewed: assert +| errmsg assert(delta*expected)>|expected-{:"1 freqtable diff --git a/Task/Verify-distribution-uniformity-Naive/JavaScript/verify-distribution-uniformity-naive.js b/Task/Verify-distribution-uniformity-Naive/JavaScript/verify-distribution-uniformity-naive.js new file mode 100644 index 0000000000..8070990c84 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/JavaScript/verify-distribution-uniformity-naive.js @@ -0,0 +1,40 @@ +function distcheck(random_func, times, opts) { + if (opts === undefined) opts = {} + opts['delta'] = opts['delta'] || 2; + + var count = {}, vals = []; + for (var i = 0; i < times; i++) { + var val = random_func(); + if (! has_property(count, val)) { + count[val] = 1; + vals.push(val); + } + else + count[val] ++; + } + vals.sort(function(a,b) {return a-b}); + + var target = times / vals.length; + var tolerance = target * opts['delta'] / 100; + + for (var i = 0; i < vals.length; i++) { + var val = vals[i]; + if (Math.abs(count[val] - target) > tolerance) + throw "distribution potentially skewed for " + val + + ": expected result around " + target + ", got " +count[val]; + else + print(val + "\t" + count[val]); + } +} + +function has_property(obj, propname) { + return typeof(obj[propname]) == "undefined" ? false : true; +} + +try { + distcheck(function() {return Math.floor(10 * Math.random())}, 100000); + print(); + distcheck(function() {return (Math.random() > 0.95 ? 1 : 0)}, 100000); +} catch (e) { + print(e); +} diff --git a/Task/Verify-distribution-uniformity-Naive/Mathematica/verify-distribution-uniformity-naive.math b/Task/Verify-distribution-uniformity-Naive/Mathematica/verify-distribution-uniformity-naive.math new file mode 100644 index 0000000000..d95205b392 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Mathematica/verify-distribution-uniformity-naive.math @@ -0,0 +1,4 @@ +SetAttributes[CheckDistribution, HoldFirst] +CheckDistribution[function_,number_,delta_] :=(Print["Expected: ", N[number/7], ", Generated :", +Transpose[Tally[Table[function, {number}]]][[2]] // Sort]; If[(Max[#]-Min[#])& + [Transpose[Tally[Table[function, {number}]]][[2]]] < delta*number/700, "Flat", "Skewed"]) diff --git a/Task/Verify-distribution-uniformity-Naive/OCaml/verify-distribution-uniformity-naive.ocaml b/Task/Verify-distribution-uniformity-Naive/OCaml/verify-distribution-uniformity-naive.ocaml new file mode 100644 index 0000000000..2010b075d6 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/OCaml/verify-distribution-uniformity-naive.ocaml @@ -0,0 +1,19 @@ +let distcheck fn n ?(delta=1.0) () = + let h = Hashtbl.create 5 in + for i = 1 to n do + let v = fn() in + let n = + try Hashtbl.find h v + with Not_found -> 0 + in + Hashtbl.replace h v (n+1) + done; + Hashtbl.iter (fun v n -> Printf.printf "%d => %d\n%!" v n) h; + let target = (float n) /. float (Hashtbl.length h) in + Hashtbl.iter (fun key value -> + if abs_float(float value -. target) > 0.01 *. delta *. (float n) + then (Printf.eprintf + "distribution potentially skewed for '%d': expected around %f, got %d\n%!" + key target value) + ) h; +;; diff --git a/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari b/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari new file mode 100644 index 0000000000..3bf4564b5e --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/PARI-GP/verify-distribution-uniformity-naive.pari @@ -0,0 +1,30 @@ +dice5()=random(5)+1; + +dice7()={ + my(t); + while((t=dice5()*5+dice5()) > 21,); + (t+2)\3 +}; + +cumChi2(chi2,dof)={ + my(g=gamma(dof/2)); + incgam(dof/2,chi2/2,g)/g +}; + +test(f,n,alpha=.05)={ + v=vector(n,i,f()); + my(s,ave,dof,chi2,p); + s=sum(i=1,n,v[i],0.); + ave=s/n; + dof=n-1; + chi2=sum(i=1,n,(v[i]-ave)^2)/ave; + p=cumChi2(chi2,dof); + if(pif(random(1000),random(1000),1), 10^5) diff --git a/Task/Verify-distribution-uniformity-Naive/Perl-6/verify-distribution-uniformity-naive.pl6 b/Task/Verify-distribution-uniformity-Naive/Perl-6/verify-distribution-uniformity-naive.pl6 new file mode 100644 index 0000000000..a77c6780bc --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Perl-6/verify-distribution-uniformity-naive.pl6 @@ -0,0 +1,25 @@ +my $d7 = 1..7; +sub roll7 { $d7.roll }; + +my $threshold = 3; + +for 14, 105, 1001, 10003, 100002, 1000006 -> $n + { dist( $n, $threshold, &roll7 ) }; + + +sub dist ( $n is copy, $threshold, &producer ) { + my @dist; + my $expect = $n / 7; + say "Expect\t",$expect.fmt("%.3f"); + + loop ($_ = $n; $n; --$n) { @dist[&producer()]++; } + + for @dist.kv -> $i, $v is copy { + next unless $i; + $v //= 0; + my $pct = ($v - $expect)/$expect*100; + printf "%d\t%d\t%+.2f%% %s\n", $i, $v, $pct, + ($pct.abs > $threshold ?? '- skewed' !! ''); + } + say ''; +} diff --git a/Task/Verify-distribution-uniformity-Naive/PicoLisp/verify-distribution-uniformity-naive.l b/Task/Verify-distribution-uniformity-Naive/PicoLisp/verify-distribution-uniformity-naive.l new file mode 100644 index 0000000000..214f59b3f9 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/PicoLisp/verify-distribution-uniformity-naive.l @@ -0,0 +1,9 @@ +(de checkDistribution (Cnt Pm . Prg) + (let Res NIL + (do Cnt (accu 'Res (run Prg 1) 1)) + (let + (N (/ Cnt (length Res)) + Min (*/ N (- 1000 Pm) 1000) + Max (*/ N (+ 1000 Pm) 1000) ) + (for R Res + (prinl (cdr R) " " (if (>= Max (cdr R) Min) "Good" "Bad")) ) ) ) ) diff --git a/Task/Verify-distribution-uniformity-Naive/PureBasic/verify-distribution-uniformity-naive.purebasic b/Task/Verify-distribution-uniformity-Naive/PureBasic/verify-distribution-uniformity-naive.purebasic new file mode 100644 index 0000000000..c022302693 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/PureBasic/verify-distribution-uniformity-naive.purebasic @@ -0,0 +1,31 @@ +Prototype RandNum_prt() + +Procedure.s distcheck(*function.RandNum_prt, repetitions, delta.d) + Protected text.s, maxIndex = 0 + Dim bucket(maxIndex) ;array will be resized as needed + + For i = 1 To repetitions ;populate buckets + v = *function() + If v > maxIndex + maxIndex = v + Redim bucket(maxIndex) + EndIf + bucket(v) + 1 + Next + + + lbnd = Round((repetitions / maxIndex) * (100 - delta) / 100, #PB_Round_Up) + ubnd = Round((repetitions / maxIndex) * (100 + delta) / 100, #PB_Round_Down) + text = "Distribution check:" + #crlf$ + #crlf$ + text + "Total elements = " + Str(repetitions) + #crlf$ + #crlf$ + text + "Margin = " + StrF(delta, 2) + "% --> Lbound = " + Str(lbnd) + ", Ubound = " + Str(ubnd) + #crlf$ + + For i = 1 To maxIndex + If bucket(i) < lbnd Or bucket(i) > ubnd + text + #crlf$ + "Bucket " + Str(i) + " contains " + Str(bucket(i)) + " elements. Skewed." + EndIf + Next + ProcedureReturn text +EndProcedure + +MessageRequester("Results", distcheck(@dice7(), 1000000, 0.20)) diff --git a/Task/Verify-distribution-uniformity-Naive/Python/verify-distribution-uniformity-naive.py b/Task/Verify-distribution-uniformity-Naive/Python/verify-distribution-uniformity-naive.py new file mode 100644 index 0000000000..c57fe29cec --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Python/verify-distribution-uniformity-naive.py @@ -0,0 +1,16 @@ +from collections import Counter +from pprint import pprint as pp + +def distcheck(fn, repeats, delta): + '''\ + Bin the answers to fn() and check bin counts are within +/- delta % + of repeats/bincount''' + bin = Counter(fn() for i in range(repeats)) + target = repeats // len(bin) + deltacount = int(delta / 100. * target) + assert all( abs(target - count) < deltacount + for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % ( + target, deltacount, [ (key, target - count) + for key, count in sorted(bin.items()) ] + ) + pp(dict(bin)) diff --git a/Task/Verify-distribution-uniformity-Naive/R/verify-distribution-uniformity-naive.r b/Task/Verify-distribution-uniformity-Naive/R/verify-distribution-uniformity-naive.r new file mode 100644 index 0000000000..e5e1fc0530 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/R/verify-distribution-uniformity-naive.r @@ -0,0 +1,20 @@ +distcheck <- function(fn, repetitions=1e4, delta=3) +{ + if(is.character(fn)) + { + fn <- get(fn) + } + if(!is.function(fn)) + { + stop("fn is not a function") + } + samp <- fn(n=repetitions) + counts <- table(samp) + expected <- repetitions/length(counts) + lbound <- expected * (1 - 0.01*delta) + ubound <- expected * (1 + 0.01*delta) + status <- ifelse(counts < lbound, "under", + ifelse(counts > ubound, "over", "okay")) + data.frame(value=names(counts), counts=as.vector(counts), status=status) +} +distcheck(dice7.vec) diff --git a/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb b/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb new file mode 100644 index 0000000000..01a622f4f5 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Ruby/verify-distribution-uniformity-naive.rb @@ -0,0 +1,28 @@ +def distcheck(n, delta=1) + unless block_given? + raise ArgumentError, "pass a block to this method" + end + + h = Hash.new(0) + n.times {h[ yield ] += 1} + + target = 1.0 * n / h.length + h.each do |key, value| + if (value - target).abs > 0.01 * delta * n + raise StandardError, + "distribution potentially skewed for '#{key}': expected around #{target}, got #{value}" + end + end + + h.keys.sort.each {|k| print "#{k} #{h[k]} "} + puts +end + +if __FILE__ == $0 + begin + distcheck(100_000) {rand(10)} + distcheck(100_000) {rand > 0.95} + rescue StandardError => e + p e + end +end diff --git a/Task/Verify-distribution-uniformity-Naive/Run-BASIC/verify-distribution-uniformity-naive.run b/Task/Verify-distribution-uniformity-Naive/Run-BASIC/verify-distribution-uniformity-naive.run new file mode 100644 index 0000000000..f274b49789 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Run-BASIC/verify-distribution-uniformity-naive.run @@ -0,0 +1,10 @@ +s$ = "#########################" +dim num(100) +for i = 1 to 1000 + n = (rnd(1) * 10) + 1 + num(n) = num(n) + 1 +next i + +for i = 1 to 10 + print using("###",i);" "; using("#####",num(i));" ";left$(s$,num(i) / 5) +next i diff --git a/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-1.tcl b/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-1.tcl new file mode 100644 index 0000000000..e2518dbf36 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-1.tcl @@ -0,0 +1,11 @@ +proc distcheck {random times {delta 1}} { + for {set i 0} {$i<$times} {incr i} {incr vals([uplevel 1 $random])} + set target [expr {$times / [array size vals]}] + foreach {k v} [array get vals] { + if {abs($v - $target) > $times * $delta / 100.0} { + error "distribution potentially skewed for $k: expected around $target, got $v" + } + } + foreach k [lsort -integer [array names vals]] {lappend result $k $vals($k)} + return $result +} diff --git a/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-2.tcl b/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-2.tcl new file mode 100644 index 0000000000..dc1b1c52fe --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Tcl/verify-distribution-uniformity-naive-2.tcl @@ -0,0 +1,5 @@ +# First, a uniformly distributed random variable +puts [distcheck {expr {int(10*rand())}} 100000] + +# Now, one that definitely isn't! +puts [distcheck {expr {rand()>0.95}} 100000] diff --git a/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-1.vbscript b/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-1.vbscript new file mode 100644 index 0000000000..96250cf447 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-1.vbscript @@ -0,0 +1,24 @@ +Option Explicit + +sub verifydistribution(calledfunction, samples, delta) + Dim i, n, maxdiff + 'We could cheat via Dim d(7), but "7" wasn't mentioned in the Task. Heh. + Dim d : Set d = CreateObject("Scripting.Dictionary") + wscript.echo "Running """ & calledfunction & """ " & samples & " times..." + for i = 1 to samples + Execute "n = " & calledfunction + d(n) = d(n) + 1 + next + n = d.Count + maxdiff = 0 + wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets." + for each i in d.Keys + dim diff : diff = abs(1 - d(i) / (samples/n)) + if diff > maxdiff then maxdiff = diff + wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _ + & vbTab & " difference from expected=" & FormatPercent(diff, 2) + next + wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _ + & ", desired limit is " & FormatPercent(delta, 2) & "." + if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!" +end sub diff --git a/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-2.vbscript b/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-2.vbscript new file mode 100644 index 0000000000..d8d7799cab --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-2.vbscript @@ -0,0 +1,2 @@ +verifydistribution "dice7", 1000, 0.03 +verifydistribution "dice7", 100000, 0.03 diff --git a/Task/Video-display-modes/0DESCRIPTION b/Task/Video-display-modes/0DESCRIPTION new file mode 100644 index 0000000000..a5e019984a --- /dev/null +++ b/Task/Video-display-modes/0DESCRIPTION @@ -0,0 +1 @@ +The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful. diff --git a/Task/Video-display-modes/1META.yaml b/Task/Video-display-modes/1META.yaml new file mode 100644 index 0000000000..ede7070638 --- /dev/null +++ b/Task/Video-display-modes/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Initialization diff --git a/Task/Video-display-modes/BBC-BASIC/video-display-modes.bbc b/Task/Video-display-modes/BBC-BASIC/video-display-modes.bbc new file mode 100644 index 0000000000..e84c6ff6af --- /dev/null +++ b/Task/Video-display-modes/BBC-BASIC/video-display-modes.bbc @@ -0,0 +1 @@ +10 MODE 1: REM 320x256 4 colour graphics diff --git a/Task/Video-display-modes/GW-BASIC/video-display-modes.gw-basic b/Task/Video-display-modes/GW-BASIC/video-display-modes.gw-basic new file mode 100644 index 0000000000..9497a525df --- /dev/null +++ b/Task/Video-display-modes/GW-BASIC/video-display-modes.gw-basic @@ -0,0 +1,2 @@ +10 REM GW Basic can switch VGA modes +20 SCREEN 18: REM Mode 12h 640x480 16 colour graphics diff --git a/Task/Video-display-modes/Locomotive-Basic/video-display-modes.locomotive b/Task/Video-display-modes/Locomotive-Basic/video-display-modes.locomotive new file mode 100644 index 0000000000..1165254e05 --- /dev/null +++ b/Task/Video-display-modes/Locomotive-Basic/video-display-modes.locomotive @@ -0,0 +1 @@ +10 MODE 0: REM switch to mode 0 diff --git a/Task/Video-display-modes/REXX/video-display-modes-1.rexx b/Task/Video-display-modes/REXX/video-display-modes-1.rexx new file mode 100644 index 0000000000..ce599fe5a7 --- /dev/null +++ b/Task/Video-display-modes/REXX/video-display-modes-1.rexx @@ -0,0 +1,5 @@ +/*REXX program to switch video display modes based on columns and lines.*/ + +parse arg cols lines . +'MODE' "CON: COLS="cols 'LINES='lines + /*stick a fork in it, we're done.*/ diff --git a/Task/Video-display-modes/REXX/video-display-modes-2.rexx b/Task/Video-display-modes/REXX/video-display-modes-2.rexx new file mode 100644 index 0000000000..bd9e22fde2 --- /dev/null +++ b/Task/Video-display-modes/REXX/video-display-modes-2.rexx @@ -0,0 +1,16 @@ +/*REXX program to switch video display modes based on columns and lines.*/ +parse arg !; if !all() then exit /*exit if documentation specified*/ +if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */ + +parse arg cols lines . +'MODE' "CON: COLS="cols 'LINES='lines + +exit /*stick a fork in it, we're done.*/ +/*══════════════════════════════════general 1-line subs═════════════════*/ +!all:!!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 +!cal:if symbol('!CALL')\=="VAR" then !call=;return !call +!env:!env='ENVIRONMENT';if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM';if !os2 then !env='OS2'!env;!ebcdic=1=='f0'x;return +!fid:parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;call !sys;if !dos then do;_=lastpos('\',!fn);!fm=left(!fn,_);!fn=substr(!fn,_+1);parse var !fn !fn '.' !ft;end;return word(0 !fn !ft !fm,1+('0'arg(1))) +!rex:parse upper version !ver !vernum !verdate .;!brexx='BY'==!vernum;!kexx='KEXX'==!ver;!pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver;!r4='REXX-R4'==!ver;!regina='REXX-REGINA'==left(!ver,11);!roo='REXX-ROO'==!ver;call !env;return +!sys:!cms=!sys=='CMS';!os2=!sys=='OS2';!tso=!sys=='TSO'|!sys=='MVS';!vse=!sys=='VSE';!dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD';call !rex;return +!var:call !fid;if !kexx then return space(dosenv(arg(1)));return space(value(arg(1),,!env)) diff --git a/Task/Video-display-modes/UNIX-Shell/video-display-modes-1.sh b/Task/Video-display-modes/UNIX-Shell/video-display-modes-1.sh new file mode 100644 index 0000000000..089b0dea95 --- /dev/null +++ b/Task/Video-display-modes/UNIX-Shell/video-display-modes-1.sh @@ -0,0 +1 @@ +$ xrandr -q diff --git a/Task/Video-display-modes/UNIX-Shell/video-display-modes-2.sh b/Task/Video-display-modes/UNIX-Shell/video-display-modes-2.sh new file mode 100644 index 0000000000..10fdef4a29 --- /dev/null +++ b/Task/Video-display-modes/UNIX-Shell/video-display-modes-2.sh @@ -0,0 +1 @@ +$ xrandr -s 1024x768 diff --git a/Task/Video-display-modes/XPL0/video-display-modes.xpl0 b/Task/Video-display-modes/XPL0/video-display-modes.xpl0 new file mode 100644 index 0000000000..5b119465c8 --- /dev/null +++ b/Task/Video-display-modes/XPL0/video-display-modes.xpl0 @@ -0,0 +1,2 @@ +code SetVid=45; +SetVid(Mode) diff --git a/Task/Vigen-re-cipher-Cryptanalysis/0DESCRIPTION b/Task/Vigen-re-cipher-Cryptanalysis/0DESCRIPTION new file mode 100644 index 0000000000..bd64cb9607 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/0DESCRIPTION @@ -0,0 +1,29 @@ +Given some text you suspect has been encrypted with a Vigenère cipher, extract the key and plaintext. There are several methods for doing this. See [[wp:Vigenère_cipher#Cryptanalysis|the Wikipedia entry]] for more information. Use the following encrypted text: +
+MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
+VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
+ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS
+FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG
+ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ
+ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS
+JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT
+LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST
+MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH
+QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV
+RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW
+TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO
+SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR
+ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX
+BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB
+BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA
+FWAML ZZRXJ EKAHV FASMU LVVUT TGK
+
+ +Letter frequencies for English can be found [[wp:Letter_frequency|here]]. + +Specifics for this task: +* Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace. +* Assume the plaintext is written in English. +* Find and output the key. +* Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional. +* The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm. diff --git a/Task/Vigen-re-cipher-Cryptanalysis/1META.yaml b/Task/Vigen-re-cipher-Cryptanalysis/1META.yaml new file mode 100644 index 0000000000..c4379d41cf --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Encryption +note: Encryption diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Ada/vigen-re-cipher-cryptanalysis.ada b/Task/Vigen-re-cipher-Cryptanalysis/Ada/vigen-re-cipher-cryptanalysis.ada new file mode 100644 index 0000000000..9d3249e390 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Ada/vigen-re-cipher-cryptanalysis.ada @@ -0,0 +1,167 @@ +with Ada.Text_IO; + +procedure Vignere_Cryptanalysis is + + subtype Letter is Character range 'A' .. 'Z'; + + function "+"(X, Y: Letter) return Letter is + begin + return Character'Val( ( (Character'Pos(X)-Character'Pos('A')) + + (Character'Pos(Y)-Character'Pos('A')) ) mod 26 + + Character'Pos('A')); + end; + + function "-"(X, Y: Letter) return Letter is + begin + return Character'Val( ( (Character'Pos(X)-Character'Pos('A')) + - (Character'Pos(Y)-Character'Pos('A')) ) mod 26 + + Character'Pos('A')); + end; + + type Frequency_Array is array (Letter) of Float; + + English: Frequency_Array := + ( 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 ); + + function Get_Frequency(S: String) return Frequency_Array is + Result: Frequency_Array := (others => 0.0); + Offset: Float := 1.0/Float(S'Length); + begin + for I in S'Range loop + if S(I) in Letter then + Result(S(I)) := Result(S(I)) + Offset; + end if; + end loop; + return Result; + end Get_Frequency; + + function Remove_Whitespace(S: String) return String is + begin + if S="" then + return ""; + elsif S(S'First) in Letter then + return S(S'First) & Remove_Whitespace(S(S'First+1 .. S'Last)); + else + return Remove_Whitespace(S(S'First+1 .. S'Last)); + end if; + end Remove_Whitespace; + + function Distance(A, B: Frequency_Array; + Offset: Character := 'A') return Float is + Result: Float := 0.0; + Diff: Float; + begin + for C in A'Range loop + Diff := A(C+Offset) - B(C); + Result := Result + (Diff * Diff); + end loop; + return Result; + end Distance; + + function Find_Key(Cryptogram: String; Key_Length: Positive) return String is + + function Find_Caesar_Key(S: String) return Letter is + Frequency: Frequency_Array := Get_Frequency(S); + Candidate: Letter := 'A'; -- a fake candidate + Candidate_Dist : Float := Distance(Frequency, English, 'A'); + New_Dist: Float; + + begin + + for L in Letter range 'B' .. 'Z' loop + New_Dist := Distance(Frequency, English, L); + if New_Dist <= Candidate_Dist then + Candidate_Dist := New_Dist; + Candidate := L; + end if; + end loop; + return Candidate; + end Find_Caesar_Key; + + function Get_Slide(S: String; Step: Positive) return String is + begin + if S'Length= 0 then + return ""; + else + return S(S'First) & Get_Slide(S(S'First+Step .. S'Last), Step); + end if; + end Get_Slide; + + Key: String(1 .. Key_Length); + + S: String renames Cryptogram; + + begin + for I in Key'Range loop + Key(I) := Find_Caesar_Key(Get_Slide(S(S'First+I-1 .. S'Last), + Key_Length)); + end loop; + return Key; + end Find_Key; + + function Key_Char(Key: String; Index: Positive) return Letter is + begin + if Index > Key'Last then + return Key_Char(Key, Index-Key'Last); + else + return Key(Index); + end if; + end Key_Char; + + Ciphertext: String := Remove_Whitespace( + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" & + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" & + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" & + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" & + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" & + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" & + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" & + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" & + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" & + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" & + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" & + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" & + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" & + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" & + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" & + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" & + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"); + + Best_Plain: String := Ciphertext; + Best_Dist: Float := Distance(English, Get_Frequency(Best_Plain)); + Best_Key: String := Ciphertext; + Best_Key_L: Natural := 0; + +begin -- Vignere_Cryptanalysis + for I in 1 .. Ciphertext'Length/10 loop + declare + Key: String(1 .. I) := Find_Key(Ciphertext, I); + Plaintext: String(Ciphertext'Range); + begin + for I in Ciphertext'Range loop + Plaintext(I) := Ciphertext(I) - Key_Char(Key, I); + end loop; + if Distance(English, Get_Frequency(Plaintext)) < Best_Dist then + Best_Plain := Plaintext; + Best_Dist := Distance(English, Get_Frequency(Plaintext)); + Best_Key(1 .. I) := Key; + Best_Key_L := I; + if Best_dist < 0.01 then + declare + use Ada.Text_IO; + begin + Put_Line("Key =" & Best_Key(1 .. Best_Key_L)); + Put_Line("Distance = " & Float'Image(Best_Dist)); + New_Line; + Put_Line("Plaintext ="); + Put_Line(Best_Plain); + New_Line; New_Line; + end; + end if; + end if; + end; + end loop; +end Vignere_Cryptanalysis; diff --git a/Task/Vigen-re-cipher-Cryptanalysis/C++/vigen-re-cipher-cryptanalysis.cpp b/Task/Vigen-re-cipher-Cryptanalysis/C++/vigen-re-cipher-cryptanalysis.cpp new file mode 100644 index 0000000000..913b54ef25 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/C++/vigen-re-cipher-cryptanalysis.cpp @@ -0,0 +1,167 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +typedef array, 26> FreqArray; + +class VigenereAnalyser +{ +private: + array targets; + array sortedTargets; + FreqArray freq; + + // Update the freqs array + FreqArray& frequency(const string& input) + { + for (char c = 'A'; c <= 'Z'; ++c) + freq[c - 'A'] = make_pair(c, 0); + + for (size_t i = 0; i < input.size(); ++i) + freq[input[i] - 'A'].second++; + + return freq; + } + + double correlation(const string& input) + { + double result = 0.0; + frequency(input); + + sort(freq.begin(), freq.end(), [](pair u, pair v)->bool + { return u.second < v.second; }); + + for (size_t i = 0; i < 26; ++i) + result += freq[i].second * sortedTargets[i]; + + return result; + } + +public: + VigenereAnalyser(const array& targetFreqs) + { + targets = targetFreqs; + sortedTargets = targets; + sort(sortedTargets.begin(), sortedTargets.end()); + } + + pair analyze(string input) + { + string cleaned; + for (size_t i = 0; i < input.size(); ++i) + { + if (input[i] >= 'A' && input[i] <= 'Z') + cleaned += input[i]; + else if (input[i] >= 'a' && input[i] <= 'z') + cleaned += input[i] + 'A' - 'a'; + } + + size_t bestLength = 0; + double bestCorr = -100.0; + + // Assume that if there are less than 20 characters + // per column, the key's too long to guess + for (size_t i = 2; i < cleaned.size() / 20; ++i) + { + vector pieces(i); + for (size_t j = 0; j < cleaned.size(); ++j) + pieces[j % i] += cleaned[j]; + + // The correlation increases artificially for smaller + // pieces/longer keys, so weigh against them a little + double corr = -0.5*i; + for (size_t j = 0; j < i; ++j) + corr += correlation(pieces[j]); + + if (corr > bestCorr) + { + bestLength = i; + bestCorr = corr; + } + } + + if (bestLength == 0) + return make_pair("Text is too short to analyze", ""); + + vector pieces(bestLength); + for (size_t i = 0; i < cleaned.size(); ++i) + pieces[i % bestLength] += cleaned[i]; + + vector freqs; + for (size_t i = 0; i < bestLength; ++i) + freqs.push_back(frequency(pieces[i])); + + string key = ""; + for (size_t i = 0; i < bestLength; ++i) + { + sort(freqs[i].begin(), freqs[i].end(), [](pair u, pair v)->bool + { return u.second > v.second; }); + + size_t m = 0; + double mCorr = 0.0; + for (size_t j = 0; j < 26; ++j) + { + double corr = 0.0; + char c = 'A' + j; + for (size_t k = 0; k < 26; ++k) + { + int d = (freqs[i][k].first - c + 26) % 26; + corr += freqs[i][k].second * targets[d]; + } + + if (corr > mCorr) + { + m = j; + mCorr = corr; + } + } + + key += m + 'A'; + } + + string result = ""; + for (size_t i = 0; i < cleaned.size(); ++i) + result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A'; + + return make_pair(result, key); + } +}; + +int main() +{ + string input = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; + + array english = { + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, + 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, + 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, + 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, + 0.01974, 0.00074}; + + VigenereAnalyser va(english); + pair output = va.analyze(input); + + cout << "Key: " << output.second << endl << endl; + cout << "Text: " << output.first << endl; +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/C/vigen-re-cipher-cryptanalysis.c b/Task/Vigen-re-cipher-Cryptanalysis/C/vigen-re-cipher-cryptanalysis.c new file mode 100644 index 0000000000..4d79aa7ae4 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/C/vigen-re-cipher-cryptanalysis.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include + +const char *encoded = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; + +const double freq[] = { + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 +}; + +int best_match(const double *a, const double *b) { + double sum = 0, fit, d, best_fit = 1e100; + int i, rotate, best_rotate = 0; + for (i = 0; i < 26; i++) + sum += a[i]; + for (rotate = 0; rotate < 26; rotate++) { + fit = 0; + for (i = 0; i < 26; i++) { + d = a[(i + rotate) % 26] / sum - b[i]; + fit += d * d / b[i]; + } + + if (fit < best_fit) { + best_fit = fit; + best_rotate = rotate; + } + } + + return best_rotate; +} + +double freq_every_nth(const int *msg, int len, int interval, char *key) { + double sum, d, ret; + double out[26], accu[26] = {0}; + int i, j, rot; + + for (j = 0; j < interval; j++) { + for (i = 0; i < 26; i++) + out[i] = 0; + for (i = j; i < len; i += interval) + out[msg[i]]++; + key[j] = rot = best_match(out, freq); + key[j] += 'A'; + for (i = 0; i < 26; i++) + accu[i] += out[(i + rot) % 26]; + } + + for (i = 0, sum = 0; i < 26; i++) + sum += accu[i]; + + for (i = 0, ret = 0; i < 26; i++) { + d = accu[i] / sum - freq[i]; + ret += d * d / freq[i]; + } + + key[interval] = '\0'; + return ret; +} + +int main() { + int txt[strlen(encoded)]; + int len = 0, j; + char key[100]; + double fit, best_fit = 1e100; + + for (j = 0; encoded[j] != '\0'; j++) + if (isupper(encoded[j])) + txt[len++] = encoded[j] - 'A'; + + for (j = 1; j < 30; j++) { + fit = freq_every_nth(txt, len, j, key); + printf("%f, key length: %2d, %s", fit, j, key); + if (fit < best_fit) { + best_fit = fit; + printf(" <--- best so far"); + } + printf("\n"); + } + + return 0; +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d b/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d new file mode 100644 index 0000000000..a17f853d61 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/D/vigen-re-cipher-cryptanalysis.d @@ -0,0 +1,132 @@ +import std.stdio, std.algorithm, std.typecons, std.string, + std.array, std.numeric, std.ascii; + +string[2] vigenereDecrypt(in double[] targetFreqs, in string input) { + enum nAlpha = std.ascii.uppercase.length; + + static double correlation(in string txt, in double[] sTargets) + /*pure nothrow*/ { + uint[nAlpha] charCounts = 0; + foreach (immutable c; txt) + charCounts[c - 'A']++; + return charCounts[].sort().release().dotProduct(sTargets); + } + + static frequency(in string txt) pure nothrow { + auto freqs = new Tuple!(char,"c", uint,"d")[nAlpha]; + foreach (immutable i, immutable c; std.ascii.uppercase) + freqs[i] = tuple(c, 0); + foreach (immutable c; txt) + freqs[c - 'A'].d++; + return freqs; + } + + static string[2] decode(in string cleaned, in string key) + pure nothrow { + assert(key.length > 0); + string decoded; + foreach (immutable i, immutable c; cleaned) + decoded ~= (c - key[i % $] + nAlpha) % nAlpha + 'A'; + return [key, decoded]; + } + + static size_t findBestLength(in string cleaned, + in double[] sTargets) + /*pure nothrow*/ { + size_t bestLength; + double bestCorr = -100.0; + + // Assume that if there are less than 20 characters + // per column, the key's too long to guess + foreach (immutable i; 2 .. cleaned.length / 20) { + auto pieces = new Appender!string[i]; + foreach (immutable j, immutable c; cleaned) + pieces[j % i] ~= c; + + // The correlation seems to increase for smaller + // pieces/longer keys, so weigh against them a little + double corr = -0.5 * i; + foreach (const p; pieces) + corr += correlation(p.data, sTargets); + + if (corr > bestCorr) { + bestLength = i; + bestCorr = corr; + } + } + + return bestLength; + } + + static string findKey(in string cleaned, in size_t bestLength, + in double[] targetFreqs) /*pure*/ { + auto pieces = new string[bestLength]; + foreach (immutable i, immutable c; cleaned) + pieces[i % bestLength] ~= c; + + string key; + foreach (fr; map!frequency(pieces)) { + fr.sort!q{ a.d > b.d }(); + + size_t m; + double maxCorr = 0.0; + foreach (immutable j, immutable c; std.ascii.uppercase) { + double corr = 0.0; + foreach (immutable frc; fr) { + immutable di = (frc.c - c + nAlpha) % nAlpha; + corr += frc.d * targetFreqs[di]; + } + + if (corr > maxCorr) { + m = j; + maxCorr = corr; + } + } + + key ~= m + 'A'; + } + + return key; + } + + immutable cleaned = input.toUpper().removechars("^A-Z"); + + //immutable sortedTargets = sorted(targetFreqs); + immutable sortedTargets = targetFreqs.dup.sort().release().idup; + + immutable bestLength = findBestLength(cleaned, sortedTargets); + if (bestLength == 0) + throw new Exception("Text is too short to analyze."); + + immutable string key = findKey(cleaned, bestLength, targetFreqs); + return decode(cleaned, key); +} + + +void main() { + immutable encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG +JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF +WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA +LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG +ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV +RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF +XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA +ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ +AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA +GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY +IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV +YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV +GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO +ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB +BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML +ZZRXJ EKAHV FASMU LVVUT TGK"; + + immutable englishFrequences = [0.08167, 0.01492, 0.02782, 0.04253, + 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, + 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, + 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, + 0.00074]; + + immutable key_dec = vigenereDecrypt(englishFrequences, encoded); + writefln("Key: %s\n\nText: %s", key_dec[0], key_dec[1]); +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Python/vigen-re-cipher-cryptanalysis.py b/Task/Vigen-re-cipher-Cryptanalysis/Python/vigen-re-cipher-cryptanalysis.py new file mode 100644 index 0000000000..e67187c8c4 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Python/vigen-re-cipher-cryptanalysis.py @@ -0,0 +1,106 @@ +from string import uppercase +from operator import itemgetter + +def vigenere_decrypt(target_freqs, input): + nchars = len(uppercase) + ordA = ord('A') + sorted_targets = sorted(target_freqs) + + def frequency(input): + result = [[c, 0.0] for c in uppercase] + for c in input: + result[c - ordA][1] += 1 + return result + + def correlation(input): + result = 0.0 + freq = frequency(input) + freq.sort(key=itemgetter(1)) + + for i, f in enumerate(freq): + result += f[1] * sorted_targets[i] + return result + + cleaned = [ord(c) for c in input.upper() if c.isupper()] + best_len = 0 + best_corr = -100.0 + + # Assume that if there are less than 20 characters + # per column, the key's too long to guess + for i in xrange(2, len(cleaned) // 20): + pieces = [[] for _ in xrange(i)] + for j, c in enumerate(cleaned): + pieces[j % i].append(c) + + # The correlation seems to increase for smaller + # pieces/longer keys, so weigh against them a little + corr = -0.5 * i + sum(correlation(p) for p in pieces) + + if corr > best_corr: + best_len = i + best_corr = corr + + if best_len == 0: + return ("Text is too short to analyze", "") + + pieces = [[] for _ in xrange(best_len)] + for i, c in enumerate(cleaned): + pieces[i % best_len].append(c) + + freqs = [frequency(p) for p in pieces] + + key = "" + for fr in freqs: + fr.sort(key=itemgetter(1), reverse=True) + + m = 0 + max_corr = 0.0 + for j in xrange(nchars): + corr = 0.0 + c = ordA + j + for frc in fr: + d = (ord(frc[0]) - c + nchars) % nchars + corr += frc[1] * target_freqs[d] + + if corr > max_corr: + m = j + max_corr = corr + + key += chr(m + ordA) + + r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA) + for i, c in enumerate(cleaned)) + return (key, "".join(r)) + + +def main(): + encoded = """ + MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH + VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD + ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS + FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG + ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ + ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS + JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT + LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST + MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH + QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV + RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW + TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO + SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR + ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX + BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB + BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA + FWAML ZZRXJ EKAHV FASMU LVVUT TGK""" + + english_frequences = [ + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] + + (key, decoded) = vigenere_decrypt(english_frequences, encoded) + print "Key:", key + print "\nText:", decoded + +main() diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-1.tcl b/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-1.tcl new file mode 100644 index 0000000000..07af2da3d8 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-1.tcl @@ -0,0 +1,118 @@ +package require Tcl 8.6 + +oo::class create VigenereAnalyzer { + variable letterFrequencies sortedTargets + constructor {{frequencies { + 0.08167 0.01492 0.02782 0.04253 0.12702 0.02228 0.02015 + 0.06094 0.06966 0.00153 0.00772 0.04025 0.02406 0.06749 + 0.07507 0.01929 0.00095 0.05987 0.06327 0.09056 0.02758 + 0.00978 0.02360 0.00150 0.01974 0.00074 + }}} { + set letterFrequencies $frequencies + set sortedTargets [lsort -real $frequencies] + if {[llength $frequencies] != 26} { + error "wrong length of frequency table" + } + } + + ### Utility methods + # Find the value of $idxvar in the range [$from..$to) that maximizes the value + # in $scorevar (which is computed by evaluating $body) + method Best {idxvar from to scorevar body} { + upvar 1 $idxvar i $scorevar s + set bestI $from + for {set i $from} {$i < $to} {incr i} { + uplevel 1 $body + if {![info exist bestS] || $bestS < $s} { + set bestI $i + set bestS $s + } + } + return $bestI + } + # Simple list map + method Map {var list body} { + upvar 1 $var v + set result {} + foreach v $list {lappend result [uplevel 1 $body]} + return $result + } + # Simple partition of $list into $groups groups; thus, the partition of + # {a b c d e f} into 3 produces {a d} {b e} {c f} + method Partition {list groups} { + set i 0 + foreach val $list { + dict lappend result $i $val + if {[incr i] >= $groups} { + set i 0 + } + } + return [dict values $result] + } + + ### Helper methods + # Get the actual counts of different types of characters in the given list + method Frequency cleaned { + for {set i 0} {$i < 26} {incr i} { + dict set tbl $i 0 + } + foreach ch $cleaned { + dict incr tbl [expr {[scan $ch %c] - 65}] + } + return $tbl + } + + # Get the correlation factor of the characters in a given list with the + # class-specified language frequency corpus + method Correlation cleaned { + set result 0.0 + set freq [lsort -integer [dict values [my Frequency $cleaned]]] + foreach f $freq s $sortedTargets { + set result [expr {$result + $f * $s}] + } + return $result + } + + # Compute an estimate for the key length + method GetKeyLength {cleaned {required 20}} { + # Assume that we need at least 20 characters per column to guess + set bestLength [my Best i 2 [expr {[llength $cleaned] / $required}] corr { + set corr [expr {-0.5 * $i}] + foreach chars [my Partition $cleaned $i] { + set corr [expr {$corr + [my Correlation $chars]}] + } + }] + if {$bestLength == 0} { + error "text is too short to analyze" + } + return $bestLength + } + + # Compute the key from the given frequency tables and the class-specified + # language frequency corpus + method GetKeyFromFreqs freqs { + foreach f $freqs { + set m [my Best i 0 26 corr { + set corr 0.0 + foreach {ch count} $f { + set d [expr {($ch - $i) % 26}] + set corr [expr {$corr + $count*[lindex $letterFrequencies $d]}] + } + }] + append key [format %c [expr {65 + $m}]] + } + return $key + } + + ##### The main analyzer method ##### + method analyze input { + # Turn the input into a clean letter sequence + set cleaned [regexp -all -inline {[A-Z]} [string toupper $input]] + # Get the (estimated) key length + set bestLength [my GetKeyLength $cleaned] + # Get the frequency mapping for the partitioned input text + set freqs [my Map p [my Partition $cleaned $bestLength] {my Frequency $p}] + # Get the key itself + return [my GetKeyFromFreqs $freqs] + } +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-2.tcl b/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-2.tcl new file mode 100644 index 0000000000..cafc057fb5 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Tcl/vigen-re-cipher-cryptanalysis-2.tcl @@ -0,0 +1,25 @@ +set encoded " + MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH + VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD + ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS + FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG + ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ + ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS + JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT + LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST + MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH + QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV + RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW + TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO + SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR + ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX + BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB + BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA + FWAML ZZRXJ EKAHV FASMU LVVUT TGK +" +VigenereAnalyzer create englishVigenereAnalyzer +set key [englishVigenereAnalyzer analyze $encoded] +Vigenere create decoder $key +set decoded [decoder decrypt $encoded] +puts "Key: $key" +puts "Text: $decoded" diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Vedit-macro-language/vigen-re-cipher-cryptanalysis.vedit b/Task/Vigen-re-cipher-Cryptanalysis/Vedit-macro-language/vigen-re-cipher-cryptanalysis.vedit new file mode 100644 index 0000000000..473da970a1 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Vedit-macro-language/vigen-re-cipher-cryptanalysis.vedit @@ -0,0 +1,317 @@ +// (1) Copy text into tmp buffer and remove non-alpha chars. + +Chdir(PATH_ONLY) +BOF +Reg_Copy(10, ALL) // copy text to new buffer +Buf_Switch(Buf_Free) +Reg_Ins(10) +BOF +Replace ("|!|A", "", BEGIN+ALL+NOERR) // remove non-alpha chars +Reg_Copy_Block(10,0,EOB_pos) // @10 = text to be analysed + +#20 = Buf_Num // buffer for text being analyzed +#21 = Buf_Free // buffer for English frequency list (A-Z) +Buf_Switch(#21) +Ins_Text("8167 1492 2782 4253 12702 2228 2015 6094 6966 153 772 4025 2406 6749 7507 1929 95 5987 6327 9056 2758 978 2360 150 1974 74") +File_Open("unixdict.txt") // or use "|(MACRO_DIR)\scribe\english.vdf" +#23 = Buf_Num // buffer for dictionary +#24 = Buf_Free // buffer for key canditates + +Buf_Switch(#24) +for (#1=0; #1<5; #1++) { // Fill table for 5 keys of 50 chars + Ins_Char('.', COUNT, 50) + Ins_Newline +} +#22 = Buf_Free // buffer for results + +#25 = Reg_Size(10) // number of letters in the text +#26 = 26 // number of characters in the alphabet +#61 = min(#25/10, 50) // max key length to try + +// (2) Check Index of coincidence (or Kp) for each key length + +Buf_Switch(#22) // buffer for results +Ins_Text("KeyLen Kp dist ") Ins_Newline +Ins_Text("-----------------") Ins_Newline +#13 = Cur_Pos +#7 = 0 // no Caesar encryption +for (#5=1; #5<=#61; #5++) { + Buf_Switch(#20) // text being analyzed + BOF + #54 = 0; // sum of Kp's + for (#6=0; #6<#5; #6++) { // for each slide + Goto_Pos(#6) + Call("CHARACTER_FREQUENCIES") + Call("INDEX_OF_COINCIDENCE") // #51 = Kp * 10000 + #54 += #51 + } + #54 /= #5 // average of Kp's + Buf_Switch(#22) + Num_Ins(#5, COUNT, 3) // write key length + IT(": ") + Num_Ins(#54, NOCR) // average Kp + Num_Ins(670-#54) // distance to English Kp +} +Buf_Switch(#22) +Sort_Merge("5,12", #13, Cur_Pos, REVERSE) // sort the results by Kp value +Ins_Newline + +// (3) Check the best 4 key lengths to find which one gives the best decrypt result + +#38 = 0 // max number of correct characters found +#19 = 1 // best key length +for (#14 = 0; #14<4; #14++) { // try 4 best key lengths + Buf_Switch(#22) // results buffer + Goto_Pos(#13) Line(#14) + #5 = Num_Eval(SUPPRESS) // #5 = key length + Call("FIND_KEYS") // find Caesar key for each key character + #4 = -1 // try best match key chars only + Call("BUILD_KEY") + EOF + Ins_Text("Key length ") + Num_Ins(#5, LEFT) + Reg_Ins(10) // encrypted text + BOL + Call("DECRYPT_LINE") + BOL + Call("FIND_ENGLISH_WORDS") // #37 = number of English chars + EOL Ins_Newline + Ins_Text("Correct chars: ") + Num_Ins(#37) + if (#37 > #38) { + #38 = #37 + #19 = #5 + } + Update() +} + +Ins_Text("Using key length: ") Num_Ins(#19) Ins_Newline +#5 = #19 +Call("FIND_KEYS") // find Caesar key for each key character + +// (4) Decrypt with different key combinations and try to find English words. +// Try key combinations where max one char is taken from 2nd best Caesar key. + +#38 = 0 // max number of chars in English words found +#39 = -1 // best key number found +for (#4 = -1; #4 < #19; #4++) +{ + Call("BUILD_KEY") + Buf_Switch(#22) // results + Reg_Ins(10) // encrypted text + BOL + Call("DECRYPT_LINE") + BOL + Update() + Call("FIND_ENGLISH_WORDS") // #37 := number of correct letters in text + if (#37 > #38) { + #38 = #37 // new highest number of correct chars + #39 = #4 // new best key + } + + EOL IT(" -- ") // display results + Num_Ins(#4, COUNT, 3) // key number + Ins_Text(": ") + for (#6=0; #6<#19; #6++) { // display key + #9 = 130 + #6 + Ins_Char(#@9) + } + Ins_Text(" correct chars =") + Num_Ins(#37) +} +Ins_Text("Best key = ") +Num_Ins(#39, LEFT) +#4 = #39 +Ins_Newline + +// Display results +// +Buf_Switch(#24) // table for key canditates +BOF +Reg_Copy_Block(14, Cur_Pos, Cur_Pos+#19) // best Caesar key chars +Line(1) +Reg_Copy_Block(15, Cur_Pos, Cur_Pos+#19) // 2nd best Caesar key chars +Call("BUILD_KEY") +Buf_Switch(#22) +Ins_Text("Key 1: ") Reg_Ins(14) Ins_Newline +Ins_Text("Key 2: ") Reg_Ins(15) Ins_Newline +Ins_Text("Key: ") +for (#6=0; #6 < #19; #6++) { + #9 = #6+130 + Ins_Char(#@9) +} +Ins_Newline +Ins_Newline + +// decrypt the text with selected key +Ins_Text("Decrypted text:") Ins_Newline +Reg_Ins(10) +BOL +Call("DECRYPT_LINE") +BOL Reg_Copy(13,1) +EOL Ins_Newline + +// Find English words from the text +Reg_Ins(13) +Call("FIND_ENGLISH_WORDS") +EOL +Ins_Newline +Num_Ins(#37, NOCR) IT(" of ") +Num_Ins(#25, NOCR) IT(" characters are English words. ") +Ins_Newline + +Buf_Switch(#20) Buf_Quit(OK) +Buf_Switch(#21) Buf_Quit(OK) +Buf_Switch(#23) Buf_Quit(OK) +Buf_Switch(#24) Buf_Quit(OK) + +Statline_Message("Done!") +Return + +///////////////////////////////////////////////////////////////////////////// +// +// Caesar decrypt current line and count character frequencies. +// in: #5 = step size, #7 = encryption key, #26 = num of chars in alphabet +// out: #65...#90 = frequencies, #60 = number of chars + +:CHARACTER_FREQUENCIES: + Save_Pos + for (#8 = 'A'; #8<='Z'; #8++) { + #@8 = 0 // reset frequency counters + } + #60 = 0 // total number of chars + while (!At_EOL) { + if (Cur_Char >= 'A' && Cur_Char <= 'Z') { + #8 = (Cur_Char-'A'+#26-#7) % #26 + 'A' // decrypted char + #@8++ + #60++ + } + Char(#5) + } + Restore_Pos +Return + +// Calculate Index of Coincidence (Kp). +// in: character frequencies in #65...#90, #60 = num of chars +// out: #51 = IC * 10000 +// +:INDEX_OF_COINCIDENCE: + Num_Push(10,15) + #10 = 0 + for (#11 = 'A'; #11<='Z'; #11++) { + #10 += (#@11 * (#@11-1)) // Calculate sigma{ni * (ni-1)} + } + #12 = #60 * (#60-1) // #12 = N * (N-1) + #51 = #10 * 10000 / #12 // #51 = Kp * 10000 + Num_Pop(10,15) +Return + +// Find best and 2nd best Caesar key for each character position of Vigenère key. +// in: #5=step size (key length) +// out: keys in buffer #24 +// +:FIND_KEYS: + for (#6 = 0; #6 < #5; #6++) { // for each char position in the key + #30 = -1 // best key char found so far + #31 = -1 // 2nd best key char + #32 = MAXNUM // smallest error found so far + #33 = MAXNUM // 2nd smallest error found so far + for (#7 = 0; #7 < #26; #7++) { // for each possible key value + #35 = 0 // total frequency error compared to English + Buf_Switch(#20) // text being analyzed + Goto_Pos(#6) + Call("CHARACTER_FREQUENCIES") + Buf_Switch(#21) // English frequency table + BOF + for (#8 = 'A'; #8<='Z'; #8++) { // calculate total frequency error + #34 = Num_Eval(SUPPRESS+ADVANCE) + #35 += abs((#@8*100000+50000)/#60-#34) + } + + if (#35 < #32) { // found better match? + #33 = #32 + #32 = #35 + #31 = #30 + #30 = #7 + } else { + if (#35 < #33) { // 2nd best match? + #33 = #35 + #31 = #7 + } + } + } + Buf_Switch(#24) // table for key canditates + BOF + Goto_Col(#6+1) + Ins_Char(#30+'A', OVERWRITE) // save the best match + Line(1) + Goto_Col(#6+1) + Ins_Char(#31+'A', OVERWRITE) // save 2nd best match + } + Buf_Switch(#22) // results buffer +Return + +// Combine actual key from 1st and 2nd best Caesar key characters +// Use 1st key chars and (possibly) one character from 2nd key. +// #4 = index of the char to be picked from 2nd key, -1 = none. +// #5 = key length +// +:BUILD_KEY: + Buf_Switch(#24) // table for key canditates + BOF + for (#6=0; #6<#5; #6++) { // copy 1st key + #8 = 130 + #6 + #@8 = Cur_Char + Char(1) + } + if (#4 >= 0) { + #8 = 130 + #4 // pick one char from 2st key + Line(1) + Goto_Col(#4+1) + #@8 = Cur_Char + } + Buf_Switch(#22) // results buffer +Return + +// Decrypt text on current line +// in: #5 = key length, #130...#189 = key +// +:DECRYPT_LINE: + Num_Push(6,9) + #6 = 0 + While (!At_EOL) { + #9 = #6+130 + #7 = #@9 + #8 = (Cur_Char - #7 + #26) % #26 + 'A' // decrypted char + Ins_Char(#8, OVERWRITE) + #6++ + if (#6 >= #5) { + #6 = 0 + } + } + Num_Pop(6,9) +Return + +// Find English words from text on current line +// out: #37 = number of chars matched +// +:FIND_ENGLISH_WORDS: + Buf_Switch(#23) // dictionary + BOF + While (!At_EOF) { + Reg_Copy_Block(12, Cur_Pos, EOL_Pos) + if (Reg_Size(12) > 2) { + Buf_Switch(#22) // buffer for results + BOL + while (Search_Block(@12, Cur_Pos, EOL_Pos, NOERR)) { + Reg_Ins(12, OVERWRITE) + } + Buf_Switch(#23) + } + Line(1, ERRBREAK) + } + + Buf_Switch(#22) + BOL + #37 = Search_Block("|V", Cur_Pos, EOL_Pos, ALL+NOERR) +Return diff --git a/Task/Vigen-re-cipher/0DESCRIPTION b/Task/Vigen-re-cipher/0DESCRIPTION new file mode 100644 index 0000000000..8efaf7c351 --- /dev/null +++ b/Task/Vigen-re-cipher/0DESCRIPTION @@ -0,0 +1,4 @@ +Implement a [[wp:Vigen%C3%A8re_cipher|Vigenère cypher]], both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) + +See also: +* [[Vigenère Cipher/Cryptanalysis]] diff --git a/Task/Vigen-re-cipher/1META.yaml b/Task/Vigen-re-cipher/1META.yaml new file mode 100644 index 0000000000..fdbbfe89ad --- /dev/null +++ b/Task/Vigen-re-cipher/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Encryption diff --git a/Task/Vigen-re-cipher/ALGOL-68/vigen-re-cipher.alg b/Task/Vigen-re-cipher/ALGOL-68/vigen-re-cipher.alg new file mode 100644 index 0000000000..150d910bf3 --- /dev/null +++ b/Task/Vigen-re-cipher/ALGOL-68/vigen-re-cipher.alg @@ -0,0 +1,62 @@ +STRING key := ""; + +PROC vigenere cipher = (REF STRING key)VOID: +( + FOR i FROM LWB key TO UPB key DO + IF key[i] >= "A" AND key[i] <= "Z" THEN + key +:= key[i] FI; + IF key[i] >= "a" AND key[i] <= "z" THEN + key +:= REPR(ABS key[i] + ABS"A" - ABS"a") FI + OD +); + +PROC encrypt = (STRING text)STRING: +( + STRING out := ""; + + INT j := LWB text; + FOR i FROM LWB text TO UPB text DO + CHAR c := text[i]; + + IF c >= "a" AND c <= "z" THEN + c := REPR(ABS c + (ABS"A" - ABS"a")) FI; + IF c >= "A" AND c <= "Z" THEN + out +:= REPR((ABS c + ABS key[j] - 2*ABS"A") MOD 26 + ABS"A"); + j := j MOD UPB key + 1 + FI + OD; + + out +); + +PROC decrypt = (STRING text)STRING: +( + STRING out; + + INT j := LWB text; + FOR i FROM LWB text TO UPB text DO + CHAR c := text[i]; + + IF c >= "a" AND c <= "z" THEN + c := REPR(ABS c + (ABS"A" - ABS"a")) FI; + IF c >= "A" AND c <= "Z" THEN + out +:= REPR((ABS c - ABS key[j] + 26) MOD 26 + ABS"A"); + j := j MOD UPB key + 1 + FI + OD; + + out +); + +main: +( + vigenere cipher(key:="VIGENERECIPHER"); + + STRING original := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; + STRING encrypted := encrypt(original); + STRING decrypted := decrypt(encrypted); + + print((original, new line)); + print(("Encrypted: ", encrypted, new line)); + print(("Decrypted: ", decrypted, new line)) +) diff --git a/Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada b/Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada new file mode 100644 index 0000000000..d5c8c2f064 --- /dev/null +++ b/Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada @@ -0,0 +1,63 @@ +with Ada.Text_IO; + +procedure Vignere_Cipher is + + subtype Letter is Character range 'A' .. 'Z'; + subtype Lowercase is Character range 'a' .. 'z'; + + function "+"(X, Y: Letter) return Letter is + begin + return Character'Val( ( (Character'Pos(X)-Character'Pos('A')) + + (Character'Pos(Y)-Character'Pos('A')) ) mod 26 + + Character'Pos('A')); + end; + + function Normalize(S: String) return String is + -- removes all characters except for uppercase and lowercase letters + -- replaces lowercase by uppercase letters + Offset: Integer := Character'Pos('A') - Character'Pos('a'); + begin + if S="" then + return ""; + elsif S(S'First) in Letter then + return S(S'First) & Normalize(S(S'First+1 .. S'Last)); + elsif S(S'First) in Lowercase then + return (Character'Val(Character'Pos(S(S'First)) + Offset) + & Normalize(S(S'First+1 .. S'Last))); + else + return Normalize(S(S'First+1 .. S'Last)); + end if; + end Normalize; + + function Encrypt(Key: String; Text: String) return String is + Ciphertext: String(Text'Range); + begin + for I in Text'Range loop + Ciphertext(I) := Text(I) + + Key(Key'First + ((I-Text'First) mod Key'Length)); + end loop; + return Ciphertext; + end Encrypt; + + function Invert(Key: String) return String is + Result: String(Key'Range); + begin + for I in Key'Range loop + Result(I) + := Character'Val( 26 - (Character'Pos(Key(I))-Character'Pos('A')) + + Character'Pos('A') ); + end loop; + return Result; + end Invert; + + use Ada.Text_IO; + Input: String := Get_Line; + Key: String := Normalize(Get_Line); + Ciph: String := Encrypt(Key => Key, Text => Normalize(Input)); + +begin + Put_Line("Input =" & Input); + Put_Line("Key =" & Key); + Put_Line("Ciphertext =" & Ciph); + Put_Line("Decryption =" & Encrypt(Key => Invert(Key), Text => Ciph)); +end Vignere_Cipher; diff --git a/Task/Vigen-re-cipher/AutoHotkey/vigen-re-cipher.ahk b/Task/Vigen-re-cipher/AutoHotkey/vigen-re-cipher.ahk new file mode 100644 index 0000000000..2b8fb52edd --- /dev/null +++ b/Task/Vigen-re-cipher/AutoHotkey/vigen-re-cipher.ahk @@ -0,0 +1,23 @@ +Key = VIGENERECIPHER +Text= Beware the Jabberwock, my son! The jaws that bite, the claws that catch! + +out := "Input =" text "`nkey =" key "`nCiphertext =" (c := VigenereCipher(Text, Key)) "`nDecrypted =" VigenereDecipher(c, key) +MsgBox % clipboard := out + +VigenereCipher(Text, Key){ + StringUpper, Text, Text + Text := RegExReplace(Text, "[^A-Z]") + Loop Parse, Text + { + a := Asc(A_LoopField) - Asc("A") + b := Asc(SubStr(Key, 1+Mod(A_Index-1, StrLen(Key)), 1)) - Asc("A") + out .= Chr(Mod(a+b,26)+Asc("A")) + } + return out +} + +VigenereDecipher(Text, key){ + Loop Parse, key + decoderKey .= Chr(26-(Asc(A_LoopField)-65)+65) + return VigenereCipher(Text, decoderKey) +} diff --git a/Task/Vigen-re-cipher/BBC-BASIC/vigen-re-cipher.bbc b/Task/Vigen-re-cipher/BBC-BASIC/vigen-re-cipher.bbc new file mode 100644 index 0000000000..cf0cf021fb --- /dev/null +++ b/Task/Vigen-re-cipher/BBC-BASIC/vigen-re-cipher.bbc @@ -0,0 +1,40 @@ + key$ = "LEMON" + plaintext$ = "ATTACK AT DAWN" + ciphertext$ = FNencrypt(plaintext$, key$) + PRINT "Key = """ key$ """" + PRINT "Plaintext = """ plaintext$ """" + PRINT "Ciphertext = """ ciphertext$ """" + PRINT "Decrypted = """ FNdecrypt(ciphertext$, key$) """" + END + + DEF FNencrypt(plain$, key$) + LOCAL i%, k%, n%, o$ + plain$ = FNupper(plain$) + key$ = FNupper(key$) + FOR i% = 1 TO LEN(plain$) + n% = ASCMID$(plain$, i%) + IF n% >= 65 IF n% <= 90 THEN + o$ += CHR$(65 + (n% + ASCMID$(key$, k%+1)) MOD 26) + k% = (k% + 1) MOD LEN(key$) + ENDIF + NEXT + = o$ + + DEF FNdecrypt(cipher$, key$) + LOCAL i%, k%, n%, o$ + cipher$ = FNupper(cipher$) + key$ = FNupper(key$) + FOR i% = 1 TO LEN(cipher$) + n% = ASCMID$(cipher$, i%) + o$ += CHR$(65 + (n% + 26 - ASCMID$(key$, k%+1)) MOD 26) + k% = (k% + 1) MOD LEN(key$) + NEXT + = o$ + + DEF FNupper(A$) + LOCAL A%,C% + FOR A% = 1 TO LEN(A$) + C% = ASCMID$(A$,A%) + IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32) + NEXT + = A$ diff --git a/Task/Vigen-re-cipher/C++/vigen-re-cipher.cpp b/Task/Vigen-re-cipher/C++/vigen-re-cipher.cpp new file mode 100644 index 0000000000..2d2c31c22a --- /dev/null +++ b/Task/Vigen-re-cipher/C++/vigen-re-cipher.cpp @@ -0,0 +1,73 @@ +#include +#include +using namespace std; + +class Vigenere +{ +public: + string key; + + Vigenere(string key) + { + for(int i = 0; i < key.size(); ++i) + { + if(key[i] >= 'A' && key[i] <= 'Z') + this->key += key[i]; + else if(key[i] >= 'a' && key[i] <= 'z') + this->key += key[i] + 'A' - 'a'; + } + } + + string encrypt(string text) + { + string out; + + for(int i = 0, j = 0; i < text.length(); ++i) + { + char c = text[i]; + + if(c >= 'a' && c <= 'z') + c += 'A' - 'a'; + else if(c < 'A' || c > 'Z') + continue; + + out += (c + key[j] - 2*'A') % 26 + 'A'; + j = (j + 1) % key.length(); + } + + return out; + } + + string decrypt(string text) + { + string out; + + for(int i = 0, j = 0; i < text.length(); ++i) + { + char c = text[i]; + + if(c >= 'a' && c <= 'z') + c += 'A' - 'a'; + else if(c < 'A' || c > 'Z') + continue; + + out += (c - key[j] + 26) % 26 + 'A'; + j = (j + 1) % key.length(); + } + + return out; + } +}; + +int main() +{ + Vigenere cipher("VIGENERECIPHER"); + + string original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; + string encrypted = cipher.encrypt(original); + string decrypted = cipher.decrypt(encrypted); + + cout << original << endl; + cout << "Encrypted: " << encrypted << endl; + cout << "Decrypted: " << decrypted << endl; +} diff --git a/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c b/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c new file mode 100644 index 0000000000..36760f589e --- /dev/null +++ b/Task/Vigen-re-cipher/C/vigen-re-cipher-1.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +void upper_case(char *src) +{ + while (*src != '\0') { + if (islower(*src)) *src &= ~0x20; + src++; + } +} + +char* encipher(const char *src, char *key, int is_encode) +{ + int i, klen, slen; + char *dest; + + dest = strdup(src); + upper_case(dest); + upper_case(key); + + /* strip out non-letters */ + for (i = 0, slen = 0; dest[slen] != '\0'; slen++) + if (isupper(dest[slen])) + dest[i++] = dest[slen]; + + dest[slen = i] = '\0'; /* null pad it, make it safe to use */ + + klen = strlen(key); + for (i = 0; i < slen; i++) { + if (!isupper(dest[i])) continue; + dest[i] = 'A' + (is_encode + ? dest[i] - 'A' + key[i % klen] - 'A' + : dest[i] - key[i % klen] + 26) % 26; + } + + return dest; +} + +int main() +{ + const char *str = "Beware the Jabberwock, my son! The jaws that bite, " + "the claws that catch!"; + const char *cod, *dec; + char key[] = "VIGENERECIPHER"; + + printf("Text: %s\n", str); + printf("key: %s\n", key); + + cod = encipher(str, key, 1); printf("Code: %s\n", cod); + dec = encipher(cod, key, 0); printf("Back: %s\n", dec); + + /* free(dec); free(cod); */ /* nah */ + return 0; +} diff --git a/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c b/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c new file mode 100644 index 0000000000..98b82cf348 --- /dev/null +++ b/Task/Vigen-re-cipher/C/vigen-re-cipher-2.c @@ -0,0 +1,4 @@ +Text: Beware the Jabberwock, my son! The jaws that bite, the claws that catch! +key: VIGENERECIPHER +Code: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY +Back: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH diff --git a/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-1.clj b/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-1.clj new file mode 100644 index 0000000000..bf00601767 --- /dev/null +++ b/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-1.clj @@ -0,0 +1,29 @@ +(ns org.rosettacode.clojure.vigenere + (:require [clojure.string :as string])) + +; convert letter to offset from \A +(defn to-num [char] (- (int char) (int \A))) + +; convert number to letter, treating it as modulo 26 offset from \A +(defn from-num [num] (char (+ (mod num 26) (int \A)))) + +; Convert a string to a sequence of just the letters as uppercase chars +(defn to-normalized-seq [str] + (map #'first (re-seq #"[A-Z]" (string/upper-case str)))) + +; add (op=+) or subtract (op=-) the numerical value of the key letter from the +; text letter. +(defn crypt1 [op text key] + (from-num (apply op (list (to-num text) (to-num key))))) + +(defn crypt [op text key] + (let [xcrypt1 (partial #'crypt1 op)] + (apply #'str + (map xcrypt1 (to-normalized-seq text) + (cycle (to-normalized-seq key)))))) + +; encipher a text +(defn encrypt [plaintext key] (crypt #'+ plaintext key)) + +; decipher a text +(defn decrypt [ciphertext key] (crypt #'- ciphertext key)) diff --git a/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-2.clj b/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-2.clj new file mode 100644 index 0000000000..e8c13bb664 --- /dev/null +++ b/Task/Vigen-re-cipher/Clojure/vigen-re-cipher-2.clj @@ -0,0 +1,11 @@ +(ns org.rosettacode.clojure.test-vigenere + (:require [org.rosettacode.clojure.vigenere :as vigenere])) + +(let + [ plaintext "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" + key "Vigenere cipher" + ciphertext (vigenere/encrypt plaintext key) + recovered (vigenere/decrypt ciphertext key) ] + + (doall (map (fn [[k v]] (printf "%9s: %s\n" k v)) + [ ["Original" plaintext] ["Key" key] ["Encrypted" ciphertext] ["Decrypted" recovered] ]))) diff --git a/Task/Vigen-re-cipher/CoffeeScript/vigen-re-cipher.coffeescript b/Task/Vigen-re-cipher/CoffeeScript/vigen-re-cipher.coffeescript new file mode 100644 index 0000000000..61de3c4688 --- /dev/null +++ b/Task/Vigen-re-cipher/CoffeeScript/vigen-re-cipher.coffeescript @@ -0,0 +1,35 @@ +# Simple helper since charCodeAt is quite long to write. +code = (char) -> char.charCodeAt() + +encrypt = (text, key) -> + res = [] + j = 0 + + for c in text.toUpperCase() + continue if c < 'A' or c > 'Z' + + res.push ((code c) + (code key[j]) - 130) % 26 + 65 + j = ++j % key.length + + String.fromCharCode res... + +decrypt = (text, key) -> + res = [] + j = 0 + + for c in text.toUpperCase() + continue if c < 'A' or c > 'Z' + + res.push ((code c) - (code key[j]) + 26) % 26 + 65 + j = ++j % key.length + + String.fromCharCode res... + +# Trying it out +key = "VIGENERECIPHER" +original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" +encrypted = encrypt original, key + +console.log "Original : #{original}" +console.log "Encrypted : #{encrypted}" +console.log "Decrypted : #{decrypt encrypted, key}" diff --git a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp new file mode 100644 index 0000000000..bae0b77dba --- /dev/null +++ b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-1.lisp @@ -0,0 +1,26 @@ +(defun strip (s) + (remove-if-not + (lambda (c) (char<= #\A c #\Z)) + (string-upcase s))) + +(defun vigenère (s key &key decipher + &aux (A (char-code #\A)) + (op (if decipher #'- #'+))) + (labels + ((to-char (c) (code-char (+ c A))) + (to-code (c) (- (char-code c) A))) + (let ((k (map 'list #'to-code (strip key)))) + (setf (cdr (last k)) k) + (map 'string + (lambda (c) + (prog1 + (to-char + (mod (funcall op (to-code c) (car k)) 26)) + (setf k (cdr k)))) + (strip s))))) + +(let* ((msg "Beware the Jabberwock... The jaws that... the claws that catch!") + (key "vigenere cipher") + (enc (vigenère msg key)) + (dec (vigenère enc key :decipher t))) + (format t "msg: ~a~%enc: ~a~%dec: ~a~%" msg enc dec)) diff --git a/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp new file mode 100644 index 0000000000..42b5098c24 --- /dev/null +++ b/Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher-2.lisp @@ -0,0 +1,3 @@ +msg: Beware the Jabberwock... The jaws that... the claws that catch! +enc: WMCEEIKLGRPIFVMEUGXXYILILZXYVBZLRGCEYAIOEKXIZGU +dec: BEWARETHEJABBERWOCKTHEJAWSTHATTHECLAWSTHATCATCH diff --git a/Task/Vigen-re-cipher/D/vigen-re-cipher.d b/Task/Vigen-re-cipher/D/vigen-re-cipher.d new file mode 100644 index 0000000000..7d2fc88813 --- /dev/null +++ b/Task/Vigen-re-cipher/D/vigen-re-cipher.d @@ -0,0 +1,29 @@ +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/Vigen-re-cipher/Erlang/vigen-re-cipher-1.erl b/Task/Vigen-re-cipher/Erlang/vigen-re-cipher-1.erl new file mode 100644 index 0000000000..bb6eee8d2b --- /dev/null +++ b/Task/Vigen-re-cipher/Erlang/vigen-re-cipher-1.erl @@ -0,0 +1,47 @@ +% Erlang implementation of Vigenère cipher +-module(vigenere). +-export([encrypt/2, decrypt/2]). +-import(lists, [append/2, filter/2, map/2, zipwith/3]). + +% Utility functions for character tests and conversions +isupper([C|_]) -> isupper(C); +isupper(C) -> (C >= $A) and (C =< $Z). + +islower([C|_]) -> islower(C); +islower(C) -> (C >= $a) and (C =< $z). + +isalpha([C|_]) -> isalpha(C); +isalpha(C) -> isupper(C) or islower(C). + +toupper(S) when is_list(S) -> lists:map(fun toupper/1, S); +toupper(C) when (C >= $a) and (C =< $z) -> C - $a + $A; +toupper(C) -> C. + +% modulo function that normalizes into positive range for positive divisor +mod(X,Y) -> (X rem Y + Y) rem Y. + +% convert letter to position in alphabet (A=0,B=1,...,Y=24,Z=25). +to_pos(L) when L >= $A, L =< $Z -> L - $A. + +% convert position in alphabet back to letter +from_pos(N) -> mod(N, 26) + $A. + +% encode the given letter given the single-letter key +encipher(P, K) -> from_pos(to_pos(P) + to_pos(K)). + +% decode the given letter given the single-letter key +decipher(C, K) -> from_pos(to_pos(C) - to_pos(K)). + +% extend a list by repeating it until it is at least N elements long +cycle_to(N, List) when length(List) >= N -> List; +cycle_to(N, List) -> append(List, cycle_to(N-length(List), List)). + +% Encryption prep: reduce string to only its letters, in uppercase +normalize(Str) -> toupper(filter(fun isalpha/1, Str)). + +crypt(RawText, RawKey, Func) -> + PlainText = normalize(RawText), + zipwith(Func, PlainText, cycle_to(length(PlainText), normalize(RawKey))). + +encrypt(Text, Key) -> crypt(Text, Key, fun encipher/2). +decrypt(Text, Key) -> crypt(Text, Key, fun decipher/2). diff --git a/Task/Vigen-re-cipher/Erlang/vigen-re-cipher-2.erl b/Task/Vigen-re-cipher/Erlang/vigen-re-cipher-2.erl new file mode 100644 index 0000000000..dd7fabae46 --- /dev/null +++ b/Task/Vigen-re-cipher/Erlang/vigen-re-cipher-2.erl @@ -0,0 +1,7 @@ +-module(testvigenere). +-import(vigenere,[encrypt/2, decrypt/2]). +main(_) -> + Key = "Vigenere cipher", + CipherText = encrypt("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", Key), + RecoveredText = decrypt(CipherText, Key), + io:fwrite("Ciphertext: ~s~nDecrypted: ~s~n", [CipherText, RecoveredText]). diff --git a/Task/Vigen-re-cipher/Go/vigen-re-cipher.go b/Task/Vigen-re-cipher/Go/vigen-re-cipher.go new file mode 100644 index 0000000000..1a00990ada --- /dev/null +++ b/Task/Vigen-re-cipher/Go/vigen-re-cipher.go @@ -0,0 +1,69 @@ +package main + +import "fmt" + +type vkey string + +func newVigenère(key string) (vkey, bool) { + v := vkey(upperOnly(key)) + return v, len(v) > 0 // key length 0 invalid +} + +func (k vkey) encipher(pt string) string { + ct := upperOnly(pt) + for i, c := range ct { + ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26 + } + return string(ct) +} + +func (k vkey) decipher(ct string) (string, bool) { + pt := make([]byte, len(ct)) + for i := range pt { + c := ct[i] + if c < 'A' || c > 'Z' { + return "", false // invalid ciphertext + } + pt[i] = 'A' + (c-k[i%len(k)]+26)%26 + } + return string(pt), true +} + +// upperOnly extracts letters A-Z, a-z from a string and +// returns them all upper case in a byte slice. +// Useful for vkey constructor and encipher function. +func upperOnly(s string) []byte { + u := make([]byte, 0, len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + if c >= 'A' && c <= 'Z' { + u = append(u, c) + } else if c >= 'a' && c <= 'z' { + u = append(u, c-32) + } + } + return u +} + +const testKey = "Vigenère Cipher" +const testPT = `Beware the Jabberwock, my son! + The jaws that bite, the claws that catch!` + +func main() { + fmt.Println("Supplied key: ", testKey) + v, ok := newVigenère(testKey) + if !ok { + fmt.Println("Invalid key") + return + } + fmt.Println("Effective key:", v) + fmt.Println("Plain text:", testPT) + ct := v.encipher(testPT) + fmt.Println("Enciphered:", ct) + dt, ok := v.decipher(ct) + if !ok { + fmt.Println("Invalid ciphertext") + return + } + fmt.Println("Deciphered:", dt) +} diff --git a/Task/Vigen-re-cipher/Haskell/vigen-re-cipher.hs b/Task/Vigen-re-cipher/Haskell/vigen-re-cipher.hs new file mode 100644 index 0000000000..41968fd431 --- /dev/null +++ b/Task/Vigen-re-cipher/Haskell/vigen-re-cipher.hs @@ -0,0 +1,26 @@ +import Data.Char +import Text.Printf + +-- Perform encryption or decryption, depending on f. +crypt f key = map toLetter . zipWith f (cycle key) + where toLetter = chr . (+) (ord 'A') + +-- Encrypt or decrypt one letter. +enc k c = (ord k + ord c) `mod` 26 +dec k c = (ord c - ord k) `mod` 26 + +-- Given a key, encrypt or decrypt an input string. +encrypt = crypt enc +decrypt = crypt dec + +-- Convert a string to have only upper case letters. +convert = map toUpper . filter isLetter + +main = do + let key = "VIGENERECIPHER" + text = "Beware the Jabberwock, my son! The jaws that bite, " + ++ "the claws that catch!" + encr = encrypt key $ convert text + decr = decrypt key encr + printf " Input: %s\n Key: %s\nEncrypted: %s\nDecrypted: %s\n" + text key encr decr diff --git a/Task/Vigen-re-cipher/Icon/vigen-re-cipher-1.icon b/Task/Vigen-re-cipher/Icon/vigen-re-cipher-1.icon new file mode 100644 index 0000000000..ee3c103282 --- /dev/null +++ b/Task/Vigen-re-cipher/Icon/vigen-re-cipher-1.icon @@ -0,0 +1,24 @@ +procedure main() + ptext := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" + write("Key = ",ekey := "VIGENERECIPHER") + write("Plain Text = ",ptext) + write("Normalized = ",GFormat(ptext := NormalizeText(ptext))) + write("Enciphered = ",GFormat(ctext := Vignere("e",ekey,ptext))) + write("Deciphered = ",GFormat(ptext := Vignere("d",ekey,ctext))) +end + +procedure Vignere(mode,ekey,ptext,alpha) #: Vignere cipher + /alpha := &ucase # default + if *alpha ~= *cset(alpha) then runerr(205,alpha) # no dups + alpha ||:= alpha # unobstructed + + every ctext:="" & p:=ptext[i := 1 to *ptext] & k:=ekey[(i-1)%*ekey+1] do + case mode of { + "e"|"encrypt": + ctext||:=map(p,alpha[1+:*alpha/2],alpha[find(k,alpha)+:(*alpha/2)]) + "d"|"decrypt": + ctext||:=map(p,alpha[find(k,alpha)+:(*alpha/2)],alpha[1+:*alpha/2]) + default: runerr(205,mode) + } +return ctext +end diff --git a/Task/Vigen-re-cipher/Icon/vigen-re-cipher-2.icon b/Task/Vigen-re-cipher/Icon/vigen-re-cipher-2.icon new file mode 100644 index 0000000000..d05dc0a44d --- /dev/null +++ b/Task/Vigen-re-cipher/Icon/vigen-re-cipher-2.icon @@ -0,0 +1,13 @@ +link strings + +procedure NormalizeText(ptext,alpha) #: text/case classical crypto helper + /alpha := &ucase # default + if &lcase === (alpha := cset(alpha)) then ptext := map(ptext) # lower + if &ucase === alpha then ptext := map(ptext,&lcase,&ucase) # upper + return deletec(ptext,&cset--alpha) # only alphas +end + +procedure GFormat(text) #: 5 letter group formatting helper + text ? (s := "", until pos(0) do s ||:= " " || move(5)|tab(0)) + return s[2:0] +end diff --git a/Task/Vigen-re-cipher/J/vigen-re-cipher-1.j b/Task/Vigen-re-cipher/J/vigen-re-cipher-1.j new file mode 100644 index 0000000000..aaaf890247 --- /dev/null +++ b/Task/Vigen-re-cipher/J/vigen-re-cipher-1.j @@ -0,0 +1,13 @@ +NB.*vig c Vigenère cipher +NB. cipher=. key 0 vig charset plain +NB. plain=. key 1 vig charset cipher +vig=: conjunction define +: + r=. (#y) $ n i.x + n {~ (#n) | (r*_1^m) + n i.y +) + +ALPHA=: (65,:26) ];.0 a. NB. Character Set +preprocess=: (#~ e.&ALPHA)@toupper NB. force uppercase and discard non-alpha chars +vigEncryptRC=: 0 vig ALPHA preprocess +vigDecryptRC=: 1 vig ALPHA preprocess diff --git a/Task/Vigen-re-cipher/J/vigen-re-cipher-2.j b/Task/Vigen-re-cipher/J/vigen-re-cipher-2.j new file mode 100644 index 0000000000..6e6f1a17a8 --- /dev/null +++ b/Task/Vigen-re-cipher/J/vigen-re-cipher-2.j @@ -0,0 +1,4 @@ + 'VIGENERECIPHER' vigEncryptRC 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!' +WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY + 'VIGENERECIPHER' vigDecryptRC 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY' +BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH diff --git a/Task/Vigen-re-cipher/Java/vigen-re-cipher.java b/Task/Vigen-re-cipher/Java/vigen-re-cipher.java new file mode 100644 index 0000000000..ab2501f9a3 --- /dev/null +++ b/Task/Vigen-re-cipher/Java/vigen-re-cipher.java @@ -0,0 +1,33 @@ +public class VigenereCipher { + public static void main(String[] args) { + String key = "VIGENERECIPHER"; + String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; + String enc = encrypt(ori, key); + System.out.println(enc); + System.out.println(decrypt(enc, key)); + } + + static String encrypt(String text, final String key) { + String res = ""; + text = text.toUpperCase(); + for (int i = 0, j = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c < 'A' || c > 'Z') continue; + res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A'); + j = ++j % key.length(); + } + return res; + } + + static String decrypt(String text, final String key) { + String res = ""; + text = text.toUpperCase(); + for (int i = 0, j = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c < 'A' || c > 'Z') continue; + res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); + j = ++j % key.length(); + } + return res; + } +} diff --git a/Task/Vigen-re-cipher/JavaScript/vigen-re-cipher.js b/Task/Vigen-re-cipher/JavaScript/vigen-re-cipher.js new file mode 100644 index 0000000000..5f063220ad --- /dev/null +++ b/Task/Vigen-re-cipher/JavaScript/vigen-re-cipher.js @@ -0,0 +1,29 @@ +Vigenère +

+
diff --git a/Task/Vigen-re-cipher/Liberty-BASIC/vigen-re-cipher.liberty b/Task/Vigen-re-cipher/Liberty-BASIC/vigen-re-cipher.liberty
new file mode 100644
index 0000000000..2d6ef11199
--- /dev/null
+++ b/Task/Vigen-re-cipher/Liberty-BASIC/vigen-re-cipher.liberty
@@ -0,0 +1,50 @@
+ori$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
+key$ = filter$("vigenerecipher")
+print ori$
+print key$
+enc$ = encrypt$(ori$, key$)
+print enc$
+dec$ = decrypt$(enc$, key$)
+print dec$
+
+end
+
+function encrypt$(text$, key$)
+    flt$ = filter$(text$)
+    encrypt$ = ""
+    j = 1
+    for i = 1 to len(flt$)
+        m$ = mid$(flt$, i, 1)
+        m = asc(m$)-asc("A")
+        k$ = mid$(key$, j, 1)
+        k = asc(k$)-asc("A")
+        j = (j mod len(key$)) + 1
+        c = (m + k) mod 26
+        c$=chr$(asc("A")+c)
+        encrypt$=encrypt$+c$
+    next
+end function
+
+function decrypt$(flt$, key$)
+    decrypt$ = ""
+    j = 1
+    for i = 1 to len(flt$)
+        m$ = mid$(flt$, i, 1)
+        m = asc(m$)-asc("A")
+        k$ = mid$(key$, j, 1)
+        k = asc(k$)-asc("A")
+        j = (j mod len(key$)) + 1
+        c = (m - k + 26) mod 26
+        c$=chr$(asc("A")+c)
+        decrypt$=decrypt$+c$
+    next
+end function
+
+function filter$(ori$)
+'a..z A..Z go caps, other skipped
+    filter$=""
+    for i = 1 to len(ori$)
+        c$ = upper$(mid$(ori$,i,1))
+        if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c$) then filter$ = filter$ + c$
+    next
+end function
diff --git a/Task/Vigen-re-cipher/Lua/vigen-re-cipher.lua b/Task/Vigen-re-cipher/Lua/vigen-re-cipher.lua
new file mode 100644
index 0000000000..7b7ecdd73c
--- /dev/null
+++ b/Task/Vigen-re-cipher/Lua/vigen-re-cipher.lua
@@ -0,0 +1,42 @@
+function Encrypt( _msg, _key )
+    local msg = { _msg:upper():byte( 1, -1 ) }
+    local key = { _key:upper():byte( 1, -1 ) }
+    local enc = {}
+
+    local j, k = 1, 1
+    for i = 1, #msg do
+        if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then
+            enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')
+
+            k = k + 1
+            if j == #key then j = 1 else j = j + 1 end
+        end
+    end
+
+    return string.char( unpack(enc) )
+end
+
+function Decrypt( _msg, _key )
+    local msg = { _msg:byte( 1, -1 ) }
+    local key = { _key:upper():byte( 1, -1 ) }
+    local dec = {}
+
+    local j = 1
+    for i = 1, #msg do
+       dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')
+
+       if j == #key then j = 1 else j = j + 1 end
+    end
+
+    return string.char( unpack(dec) )
+end
+
+
+original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
+key = "VIGENERECIPHER";
+
+encrypted = Encrypt( original, key )
+decrypted = Decrypt( encrypted, key )
+
+print( encrypted )
+print( decrypted )
diff --git a/Task/Vigen-re-cipher/Mathematica/vigen-re-cipher.math b/Task/Vigen-re-cipher/Mathematica/vigen-re-cipher.math
new file mode 100644
index 0000000000..c4a6a84f18
--- /dev/null
+++ b/Task/Vigen-re-cipher/Mathematica/vigen-re-cipher.math
@@ -0,0 +1,31 @@
+encode[text_String, key_String] :=
+ Module[{textCode, keyCode},
+  textCode =
+   Cases[ToCharacterCode[
+      ToUpperCase@
+       text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
+  keyCode =
+   Cases[ToCharacterCode[
+      ToUpperCase@
+       key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
+  keyCode =
+   If[Length[textCode] < Length[keyCode],
+    keyCode[[;; Length@textCode]],
+    PadRight[keyCode, Length@textCode, keyCode]];
+  FromCharacterCode[Mod[textCode + keyCode, 26] + 65]]
+
+decode[text_String, key_String] :=
+ Module[{textCode, keyCode},
+  textCode =
+   Cases[ToCharacterCode[
+      ToUpperCase@
+       text], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
+  keyCode =
+   Cases[ToCharacterCode[
+      ToUpperCase@
+       key], _?(IntervalMemberQ[Interval@{65, 90}, #] &)] - 65;
+  keyCode =
+   If[Length[textCode] < Length[keyCode],
+    keyCode[[;; Length@textCode]],
+    PadRight[keyCode, Length@textCode, keyCode]];
+  FromCharacterCode[Mod[textCode - keyCode, 26] + 65]]
diff --git a/Task/Vigen-re-cipher/NetRexx/vigen-re-cipher.netrexx b/Task/Vigen-re-cipher/NetRexx/vigen-re-cipher.netrexx
new file mode 100644
index 0000000000..8e212bcf6d
--- /dev/null
+++ b/Task/Vigen-re-cipher/NetRexx/vigen-re-cipher.netrexx
@@ -0,0 +1,152 @@
+/* NetRexx */
+options replace format comments java crossref savelog symbols nobinary
+
+pt  = 'Attack at dawn!'
+key = 'LEMON'
+test(key, pt)
+
+key = 'N' -- rot-13
+test(key, pt)
+
+key = 'B' -- Caesar
+test(key, pt)
+
+pt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+key = 'A'
+test(key, pt)
+
+pt = sampledata()
+key = 'Hamlet; Prince of Denmark'
+test(key, pt)
+
+return
+
+method vigenere(meth, key, text) public static
+
+  select
+    when 'encipher'.abbrev(meth.lower, 1) then df = 1
+    when 'decipher'.abbrev(meth.lower, 1) then df = -1
+    otherwise signal IllegalArgumentException(meth 'must be "encipher" or "decipher"')
+    end
+
+  alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+
+  text = stringscrubber(text)
+  key  = stringscrubber(key)
+  code = ''
+  loop l_ = 1 to text.length()
+    M = alpha.pos(text.substr(l_, 1)) - 1
+    k_ = (l_ - 1) // key.length()
+    K = alpha.pos(key.substr(k_ + 1, 1)) - 1
+    C = mod((M + K * df), alpha.length())
+    C = alpha.substr(C + 1, 1)
+    code = code || C
+    end l_
+
+  return code
+
+method vigenere_encipher(key, plaintext) public static
+
+  return vigenere('encipher', key, plaintext)
+
+method vigenere_decipher(key, ciphertext) public static
+
+  return vigenere('decipher', key, ciphertext)
+
+method mod(N = int, D = int) private static
+
+return (D + (N // D)) // D
+
+method stringscrubber(cleanup) private static
+
+  alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+
+  cleanup = cleanup.upper.space(0)
+  loop label f_ forever
+    x_ = cleanup.verify(alpha)
+    if x_ = 0 then leave f_
+    cleanup = cleanup.changestr(cleanup.substr(x_, 1), '')
+    end f_
+
+  return cleanup
+
+method test(key, pt) private static
+
+  ct = vigenere_encipher(key, pt)
+  display(ct)
+  dt = vigenere_decipher(key, ct)
+  display(dt)
+
+  return
+
+method display(text) public static
+
+  line = ''
+  o_ = 0
+  loop c_ = 1 to text.length()
+    b_ = o_ // 5
+    o_ = o_ + 1
+    if b_ = 0 then line = line' '
+    line = line || text.substr(c_, 1)
+    end c_
+
+  say '....+....|'.copies(8)
+  loop label l_ forever
+    parse line w1 w2 w3 w4 w5 w6 W7 w8 w9 w10 w11 w12 line
+    pline = w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w11 w12
+    say pline.strip()
+    if line.strip().length() = 0 then leave l_
+    end l_
+  say
+
+  return
+
+method sampledata() private static returns Rexx
+
+  NL = char('\n')
+  antic_disposition = Rexx[]
+
+  antic_disposition = [                                         -
+    Rexx("To be, or not to be--that is the question:"        ), -
+    Rexx("Whether 'tis nobler in the mind to suffer"         ), -
+    Rexx("The slings and arrows of outrageous fortune"       ), -
+    Rexx("Or to take arms against a sea of troubles"         ), -
+    Rexx("And by opposing end them. To die, to sleep--"      ), -
+    Rexx("No more--and by a sleep to say we end"             ), -
+    Rexx("The heartache, and the thousand natural shocks"    ), -
+    Rexx("That flesh is heir to. 'Tis a consummation"        ), -
+    Rexx("Devoutly to be wished. To die, to sleep--"         ), -
+    Rexx("To sleep--perchance to dream: ay, there's the rub,"), -
+    Rexx("For in that sleep of death what dreams may come"   ), -
+    Rexx("When we have shuffled off this mortal coil,"       ), -
+    Rexx("Must give us pause. There's the respect"           ), -
+    Rexx("That makes calamity of so long life."              ), -
+    Rexx("For who would bear the whips and scorns of time,"  ), -
+    Rexx("Th' oppressor's wrong, the proud man's contumely"  ), -
+    Rexx("The pangs of despised love, the law's delay,"      ), -
+    Rexx("The insolence of office, and the spurns"           ), -
+    Rexx("That patient merit of th' unworthy takes,"         ), -
+    Rexx("When he himself might his quietus make"            ), -
+    Rexx("With a bare bodkin? Who would fardels bear,"       ), -
+    Rexx("To grunt and sweat under a weary life,"            ), -
+    Rexx("But that the dread of something after death,"      ), -
+    Rexx("The undiscovered country, from whose bourn"        ), -
+    Rexx("No traveller returns, puzzles the will,"           ), -
+    Rexx("And makes us rather bear those ills we have"       ), -
+    Rexx("Than fly to others that we know not of?"           ), -
+    Rexx("Thus conscience does make cowards of us all,"      ), -
+    Rexx("And thus the native hue of resolution"             ), -
+    Rexx("Is sicklied o'er with the pale cast of thought,"   ), -
+    Rexx("And enterprise of great pith and moment"           ), -
+    Rexx("With this regard their currents turn awry"         ), -
+    Rexx("And lose the name of action. -- Soft you now,"     ), -
+    Rexx("The fair Ophelia! -- Nymph, in thy orisons"        ), -
+    Rexx("Be all my sins remembered."                        )  -
+    ]
+
+    melancholy_dane = Rexx('')
+    loop l_ = 0 for antic_disposition.length
+      melancholy_dane = melancholy_dane || antic_disposition[l_] || NL
+      end l_
+
+    return melancholy_dane
diff --git a/Task/Vigen-re-cipher/OCaml/vigen-re-cipher.ocaml b/Task/Vigen-re-cipher/OCaml/vigen-re-cipher.ocaml
new file mode 100644
index 0000000000..3ee752cb18
--- /dev/null
+++ b/Task/Vigen-re-cipher/OCaml/vigen-re-cipher.ocaml
@@ -0,0 +1,41 @@
+let cipher src key crypt =
+  let str = String.uppercase src in
+  let key = String.uppercase key in
+
+  (* strip out non-letters *)
+  let len = String.length str in
+  let rec aux i j =
+    if j >= len then String.sub str 0 i else
+    if str.[j] >= 'A' && str.[j] <= 'Z'
+    then (str.[i] <- str.[j]; aux (succ i) (succ j))
+    else aux i (succ j)
+  in
+  let res = aux 0 0 in
+
+  let slen = String.length res in
+  let klen = String.length key in
+
+  let d = int_of_char in
+  let f =
+    if crypt
+    then fun i -> d res.[i] - d 'A' + d key.[i mod klen] - d 'A'
+    else fun i -> d res.[i] - d key.[i mod klen] + 26
+  in
+  for i = 0 to pred slen do
+    res.[i] <- char_of_int (d 'A' + (f i) mod 26)
+  done;
+  (res)
+
+let () =
+  let str = "Beware the Jabberwock, my son! The jaws that bite, \
+             the claws that catch!" in
+  let key = "VIGENERECIPHER" in
+
+  let cod = cipher str key true in
+  let dec = cipher cod key false in
+
+  Printf.printf "Text: %s\n" str;
+  Printf.printf "key:  %s\n" key;
+  Printf.printf "Code: %s\n" cod;
+  Printf.printf "Back: %s\n" dec;
+;;
diff --git a/Task/Vigen-re-cipher/Objeck/vigen-re-cipher.objeck b/Task/Vigen-re-cipher/Objeck/vigen-re-cipher.objeck
new file mode 100644
index 0000000000..d1ac2bfef3
--- /dev/null
+++ b/Task/Vigen-re-cipher/Objeck/vigen-re-cipher.objeck
@@ -0,0 +1,45 @@
+bundle Default {
+   class VigenereCipher {
+      function : Main(args : String[]) ~ Nil {
+         key := "VIGENERECIPHER";
+         ori := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
+         enc := encrypt(ori, key);
+         IO.Console->Print("encrypt: ")->PrintLine(enc);
+         IO.Console->Print("decrypt: ")->PrintLine(decrypt(enc, key));
+      }
+
+      function : native : encrypt(text : String, key : String) ~ String {
+         res := "";
+         text := text->ToUpper();
+         j := 0;
+
+         each(i : text) {
+            c := text->Get(i);
+            if(c >= 'A' & c <= 'Z') {
+               res->Append(((c + key->Get(j) - 2 * 'A') % 26 + 'A')->As(Char));
+               j += 1;
+               j := j % key->Size();
+            };
+        };
+
+        return res;
+      }
+
+      function : native : decrypt(text : String, key : String) ~ String {
+         res := "";
+         text := text->ToUpper();
+         j := 0;
+
+         each(i : text) {
+            c := text->Get(i);
+            if(c >= 'A' & c <= 'Z') {
+               res->Append(((c - key->Get(j) + 26) % 26 + 'A')->As(Char));
+               j += 1;
+               j := j % key->Size();
+            };
+         };
+
+         return res;
+      }
+   }
+}
diff --git a/Task/Vigen-re-cipher/PL-I/vigen-re-cipher.pli b/Task/Vigen-re-cipher/PL-I/vigen-re-cipher.pli
new file mode 100644
index 0000000000..8d6dfabe95
--- /dev/null
+++ b/Task/Vigen-re-cipher/PL-I/vigen-re-cipher.pli
@@ -0,0 +1,44 @@
+cypher: procedure options (main);      /* 21 September 2012 */
+   declare t(26) character (26);
+   declare (i, j, k, L) fixed binary;
+   declare (original, encoded, coder) character (1000) varying initial ('');
+   declare cypher character (30) varying;
+   declare (co, ct, cc) character (1);
+
+   /* Set up cypher table. */
+   t(1) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+   do i = 2 to 26;
+      t(i) =  substr(t(i-1), 2, 25) || substr(t(i-1), 1, 1);
+   end;
+
+   cypher = 'VIGILANCE';
+   original = 'Meet me on Tuesday evening at seven.';
+   put edit ('Message=', original) (a);
+   original = uppercase(original);
+
+   /* Create the cypher text, same length as original, or longer. */
+   coder = repeat(cypher, length(original)/length(cypher));
+
+   /* Encode the original message, character by character. */
+   /* Non-alphabetic characters are ignored. */
+   L = 0;
+   do i = 1 to length(original);
+      co = substr(original, i, 1);
+      j = index(t(1), co);
+      if j = 0 then iterate; /* Ignore non-alphabetic character */
+      L = L + 1;
+      ct = substr(coder, L, 1);
+      k = index(t(1), ct);
+      encoded = encoded || substr(t(j), k, 1);
+   end;
+   put skip data (encoded);
+
+   /* DECODING. */
+   put skip list ('Decoded=');
+   do i = 1 to length(encoded);
+      cc = substr(coder, i, 1);
+      j = index(t(1), cc);
+      k = index(t(j), substr(encoded, i, 1));
+      put edit (substr(t(1), k, 1) ) (a(1));
+   end;
+end cypher;
diff --git a/Task/Vigen-re-cipher/Perl-6/vigen-re-cipher.pl6 b/Task/Vigen-re-cipher/Perl-6/vigen-re-cipher.pl6
new file mode 100644
index 0000000000..7579b63fbf
--- /dev/null
+++ b/Task/Vigen-re-cipher/Perl-6/vigen-re-cipher.pl6
@@ -0,0 +1,12 @@
+sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 }
+sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }
+
+sub blacken ($red, $key) { v2s s2v($red) »+» s2v($key) }
+sub redden  ($blk, $key) { v2s s2v($blk) »-» s2v($key) }
+
+my $red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
+my $key = "Vigenere Cipher!!!";
+
+say $red;
+say my $black = blacken($red, $key);
+say redden($black, $key);
diff --git a/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl b/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl
new file mode 100644
index 0000000000..47d4729b28
--- /dev/null
+++ b/Task/Vigen-re-cipher/Perl/vigen-re-cipher.pl
@@ -0,0 +1,40 @@
+if( @ARGV != 3 ){
+  printHelp();
+}
+
+  # translate to upper-case, remove anything else
+map( (tr/a-z/A-Z/, s/[^A-Z]//g), @ARGV );
+
+my $cipher_decipher = $ARGV[ 0 ];
+
+if( $cipher_decipher !~ /ENC|DEC/ ){
+  printHelp();  # user should say what to do
+}
+
+print "Key: " . (my $key = $ARGV[ 2 ]) . "\n";
+
+if( $cipher_decipher =~ /ENC/ ){
+  print "Plain-text: " . (my $plain = $ARGV[ 1 ]) . "\n";
+  print "Encrypted: " . Vigenere( 1, $plain ) . "\n";
+}elsif( $cipher_decipher =~ /DEC/ ){
+  print "Cipher-text: " . (my $cipher = $ARGV[ 1 ]) . "\n";
+  print "Decrypted: " . Vigenere( -1, $cipher ) . "\n";
+}
+
+sub printHelp{
+  print "Usage:\n" .
+        "Encrypting:\n perl cipher.pl ENC (plain text) (key)\n" .
+        "Decrypting:\n perl cipher.pl DEC (cipher text) (key)\n";
+  exit -1;
+}
+
+sub Vigenere{
+  my ($direction, $text) = @_;
+  for( my $count = 0; $count < length $text; $count ++ ){
+    $key_offset = $direction * ord substr( $key, $count % length $key, 1);
+    $char_offset = ord substr( $text, $count, 1 );
+    $cipher .= chr 65 + ((($char_offset % 26) + ($key_offset % 26)) % 26);
+      # 65 is the ASCII character code for 'A'
+  }
+  return $cipher;
+}
diff --git a/Task/Vigen-re-cipher/PicoLisp/vigen-re-cipher.l b/Task/Vigen-re-cipher/PicoLisp/vigen-re-cipher.l
new file mode 100644
index 0000000000..8d99a2be96
--- /dev/null
+++ b/Task/Vigen-re-cipher/PicoLisp/vigen-re-cipher.l
@@ -0,0 +1,22 @@
+(de vigenereKey (Str)
+   (extract
+      '((C)
+         (when (>= "Z" (uppc C) "A")
+            (- (char (uppc C)) 65) ) )
+      (chop Str) ) )
+
+(de vigenereEncrypt (Str Key)
+   (pack
+      (mapcar
+         '((C K)
+            (char (+ 65 (% (+ C K) 26))) )
+         (vigenereKey Str)
+         (apply circ (vigenereKey Key)) ) ) )
+
+(de vigenereDecrypt (Str Key)
+   (pack
+      (mapcar
+         '((C K)
+            (char (+ 65 (% (+ 26 (- C K)) 26))) )
+         (vigenereKey Str)
+         (apply circ (vigenereKey Key)) ) ) )
diff --git a/Task/Vigen-re-cipher/PureBasic/vigen-re-cipher.purebasic b/Task/Vigen-re-cipher/PureBasic/vigen-re-cipher.purebasic
new file mode 100644
index 0000000000..ac83113de4
--- /dev/null
+++ b/Task/Vigen-re-cipher/PureBasic/vigen-re-cipher.purebasic
@@ -0,0 +1,61 @@
+Procedure prepString(text.s, Array letters(1))
+  ;convert characters to an ordinal (0-25) and remove non-alphabetic characters,
+  ;returns dimension size of result array letters()
+  Protected *letter.Character, index
+  Dim letters(Len(text))
+  text = UCase(text)
+  *letter = @text
+  While *letter\c
+    Select *letter\c
+      Case 'A' To 'Z'
+        letters(index) = *letter\c - 65
+        index + 1
+    EndSelect
+    *letter + SizeOf(Character)
+  Wend
+  If index > 0
+    Redim letters(index - 1)
+  EndIf
+  ProcedureReturn index - 1
+EndProcedure
+
+Procedure.s VC_encrypt(text.s, keyText.s, reverse = 0)
+  ;if reverse <> 0 then reverse the key (decrypt)
+  Protected *letter.Character
+  Dim text(0)
+  Dim keyText(0)
+  If prepString(text, text()) < 0 Or prepString(keyText, keyText()) < 0: ProcedureReturn: EndIf ;exit, nothing to work with
+
+  Protected i, keyLength = ArraySize(keyText())
+  If reverse
+    For i = 0 To keyLength
+      keyText(i) = 26 - keyText(i)
+    Next
+  EndIf
+
+  Protected textLength = ArraySize(text()) ;zero-based length
+  Protected result.s = Space(textLength + 1), *resultLetter.Character
+  keyLength + 1 ;convert from zero-based to one-based count
+  *resultLetter = @result
+  For i = 0 To textLength
+    *resultLetter\c = ((text(i) + keyText(i % keyLength)) % 26) + 65
+    *resultLetter + SizeOf(Character)
+  Next
+  ProcedureReturn result
+EndProcedure
+
+Procedure.s VC_decrypt(cypherText.s, keyText.s)
+  ProcedureReturn VC_encrypt(cypherText, keyText.s, 1)
+EndProcedure
+
+If OpenConsole()
+  Define VignereCipher.s, plainText.s, encryptedText.s, decryptedText.s
+
+  VignereCipher.s = "VIGNERECIPHER"
+  plainText = "The quick brown fox jumped over the lazy dogs.": PrintN(RSet("Plain text = ", 17) + #DQUOTE$ + plainText + #DQUOTE$)
+  encryptedText = VC_encrypt(plainText, VignereCipher): PrintN(RSet("Encrypted text = ", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)
+  decryptedText = VC_decrypt(encryptedText, VignereCipher): PrintN(RSet("Decrypted text = ", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)
+
+  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
+  CloseConsole()
+EndIf
diff --git a/Task/Vigen-re-cipher/Python/vigen-re-cipher-1.py b/Task/Vigen-re-cipher/Python/vigen-re-cipher-1.py
new file mode 100644
index 0000000000..9b04725ae0
--- /dev/null
+++ b/Task/Vigen-re-cipher/Python/vigen-re-cipher-1.py
@@ -0,0 +1,19 @@
+from itertools import starmap, cycle
+
+def encrypt(message, key):
+
+    # convert to uppercase.
+    # strip out non-alpha characters.
+    message = filter(lambda _: _.isalpha(), message.upper())
+
+    # single letter encrpytion.
+    def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))
+
+    return "".join(starmap(enc, zip(message, cycle(key))))
+
+def decrpyt(message, key):
+
+    # single letter decryption.
+    def dec(c,k): return chr(((ord(c) - ord(k)) % 26) + ord('A'))
+
+    return "".join(starmap(dec, zip(message, cycle(key))))
diff --git a/Task/Vigen-re-cipher/Python/vigen-re-cipher-2.py b/Task/Vigen-re-cipher/Python/vigen-re-cipher-2.py
new file mode 100644
index 0000000000..ee822944d1
--- /dev/null
+++ b/Task/Vigen-re-cipher/Python/vigen-re-cipher-2.py
@@ -0,0 +1,9 @@
+text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
+key = "VIGENERECIPHER"
+
+encr = encrypt(text, key)
+decr = decrpyt(encr, key)
+
+print text
+print encr
+print decr
diff --git a/Task/Vigen-re-cipher/R/vigen-re-cipher.r b/Task/Vigen-re-cipher/R/vigen-re-cipher.r
new file mode 100644
index 0000000000..de0d1c2721
--- /dev/null
+++ b/Task/Vigen-re-cipher/R/vigen-re-cipher.r
@@ -0,0 +1,18 @@
+mod1 = function(v, n)
+# mod1(1:20, 6)   =>   1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2
+    ((v - 1) %% n) + 1
+
+str2ints = function(s)
+    as.integer(Filter(Negate(is.na),
+        factor(levels = LETTERS, strsplit(toupper(s), "")[[1]])))
+
+vigen = function(input, key, decrypt = F)
+   {input = str2ints(input)
+    key = rep(str2ints(key), len = length(input)) - 1
+    paste(collapse = "", LETTERS[
+        mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}
+
+message(vigen("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher"))
+  # WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
+message(vigen("WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY", "vigenerecipher", decrypt = T))
+  # BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
diff --git a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx
new file mode 100644
index 0000000000..9a0a94ce48
--- /dev/null
+++ b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx
@@ -0,0 +1,31 @@
+/*REXX program encrypts uppercased text using the  Vigenère  cypher.    */
+@.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+L=length(@.1)
+                         do j=2 to L;    jm=j-1;    q=@.jm
+                         @.j=substr(q,2,L-1)left(q,1)
+                         end   /*j*/
+
+cypher = space('WHOOP DE DOO    NO BIG DEAL HERE OR THERE',0)
+oMsg   = 'People solve problems by trial and error; judgement helps pick the trial.'
+oMsgU  = oMsg;    upper oMsgU
+cypher_=copies(cypher,length(oMsg)%length(cypher))
+say '   original text =' oMsg
+                         xMsg=Ncypher(oMsgU)
+say '   cyphered text =' xMsg
+                         bMsg=Dcypher(xMsg)
+say 're-cyphered text =' bMsg
+exit
+/*───────────────────────────────Ncypher subroutine─────────────────────*/
+Ncypher:  parse arg stuff;     #=1;   nMsg=
+   do i=1 for length(stuff);   x=substr(stuff,i,1)    /*pick off 1 char.*/
+   if \datatype(x,'U') then iterate    /*not a letter?   Then ignore it.*/
+   j=pos(x,@.1);   nMsg=nMsg || substr(@.j,pos(substr(cypher_,#,1),@.1),1)
+   #=#+1                               /*bump the character counter.    */
+   end
+return nMsg
+/*───────────────────────────────Dcypher subroutine──────────────────────*/
+Dcypher:  parse arg stuff;     #=1;   dMsg=
+   do i=1 for length(stuff);   x=substr(cypher_,i,1)  /*pick off 1 char.*/
+   j=pos(x,@.1);   dMsg=dMsg || substr(@.1, pos(substr(stuff,i,1),@.j),1)
+   end
+return dMsg
diff --git a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx
new file mode 100644
index 0000000000..4d3c0be53c
--- /dev/null
+++ b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx
@@ -0,0 +1,30 @@
+/*REXX program encrypts uppercased text using the  Vigenère  cypher.    */
+@abc='abcdefghijklmnopqrstuvwxyz';    @abcU=@abc;    upper @abcU
+@.1 = @abcU || @abc'0123456789~`!@#$%^&*()_-+={}|[]\:;<>?,./" '''
+L=length(@.1)
+                         do j=2 to length(@.1);    jm=j-1;    q=@.jm
+                         @.j=substr(q,2,length(@.1)-1)left(q,1)
+                         end   /*j*/
+
+cypher = space('WHOOP DE DOO    NO BIG DEAL HERE OR THERE',0)
+oMsg   = 'Making things easy is just knowing the shortcuts. --- Gerard J. Schildberger'
+cypher_=copies(cypher,length(oMsg)%length(cypher))
+say '   original text =' oMsg
+                         xMsg=Ncypher(oMsg)
+say '   cyphered text =' xMsg
+                         bMsg=Dcypher(xMsg)
+say 're-cyphered text =' bMsg
+exit
+/*───────────────────────────────Ncypher subroutine─────────────────────*/
+Ncypher:  parse arg stuff;     #=1;     nMsg=
+   do i=1 for length(stuff);   x=substr(stuff,i,1)    /*pick off 1 char.*/
+   j=pos(x,@.1); if j==0 then iterate  /*character not supported? Ignore*/
+   nMsg=nMsg || substr(@.j,pos(substr(cypher_,#,1),@.1),1);   #=#+1
+   end    /*j*/
+return nMsg
+/*───────────────────────────────Dcypher subroutine──────────────────────*/
+Dcypher:  parse arg stuff;     #=1;   dMsg=
+   do i=1 for length(stuff);   x=substr(cypher_,i,1)  /*pick off 1 char.*/
+   j=pos(x,@.1);   dMsg=dMsg || substr(@.1, pos(substr(stuff,i,1),@.j),1)
+   end    /*j*/
+return dMsg
diff --git a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb
new file mode 100644
index 0000000000..273d929aea
--- /dev/null
+++ b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-1.rb
@@ -0,0 +1,34 @@
+class VigenereCipher
+
+  BASE = 'A'.ord
+  SIZE = 'Z'.ord - BASE + 1
+
+  def key=(key)
+    @key = key.upcase.gsub(/[^A-Z]/, '')
+  end
+
+  def initialize(key)
+    self.key= key
+  end
+
+  def encrypt(text)
+    crypt(text, :+)
+  end
+
+  def decrypt(text)
+    crypt(text, :-)
+  end
+
+  def crypt(text, dir)
+    plaintext = text.upcase.gsub(/[^A-Z]/, '')
+    key_iterator = @key.chars.cycle
+    ciphertext = ''
+    plaintext.each_char do |plain_char|
+      offset = key_iterator.next.ord - BASE
+      ciphertext +=
+        ((plain_char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
+    end
+    return ciphertext
+  end
+
+end
diff --git a/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb
new file mode 100644
index 0000000000..02c285509a
--- /dev/null
+++ b/Task/Vigen-re-cipher/Ruby/vigen-re-cipher-2.rb
@@ -0,0 +1,7 @@
+vc = VigenereCipher.new('Vigenere cipher')
+plaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'
+ciphertext = vc.encrypt(plaintext)
+recovered  = vc.decrypt(ciphertext)
+puts "Original: #{plaintext}"
+puts "Encrypted: #{ciphertext}"
+puts "Decrypted: #{recovered}"
diff --git a/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust
new file mode 100644
index 0000000000..c17684f387
--- /dev/null
+++ b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust
@@ -0,0 +1,49 @@
+fn uppercase_and_filter(in: &str) -> ~[u8] {
+    let mut result = ~[];
+
+    for in.each_char |c| {
+        if char::is_ascii(c) {
+            if char::is_lowercase(c) {
+                // We know it's ascii, so just do the math directly
+                result.push((c + ('A' - 'a')) as u8)
+            } else if char::is_uppercase(c) {
+                result.push(c as u8);
+            }
+        }
+    }
+
+    return result;
+}
+
+fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str {
+    const A: u8 = 'A' as u8;
+
+    let key_bytes = uppercase_and_filter(key);
+    let text_bytes = uppercase_and_filter(text);
+
+    let mut result_bytes = ~[];
+
+    for text_bytes.eachi |i, &c| {
+        let c2 = if is_encoding {
+            (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A
+        } else {
+            (c - key_bytes[i % key_bytes.len()] + 26) % 26 + A
+        };
+        result_bytes.push(c2);
+    }
+
+    return str::from_bytes(result_bytes);
+}
+
+fn main() {
+    let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
+    let key = "VIGENERECIPHER";
+
+    io::println(fmt!("Text: %s", text));
+    io::println(fmt!("Key:  %s", key));
+
+    let encoded = vigenere(key, text, true);
+    io::println(fmt!("Code: %s", encoded));
+    let decoded = vigenere(key, encoded, false);
+    io::println(fmt!("Back: %s", decoded));
+}
diff --git a/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala b/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala
new file mode 100644
index 0000000000..10bbd97862
--- /dev/null
+++ b/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala
@@ -0,0 +1,115 @@
+import scala.language.implicitConversions
+
+//
+// Translate Special Chars to Names
+// --------------------------------
+//
+class VText
+
+class KeyText( key:String ) extends VText {
+  override def toString = key
+}
+
+object KeyText {
+  def apply(k:String) = new KeyText( "[^A-Z]*".r.replaceAllIn(k.toUpperCase,"") )
+}
+
+
+class PlainText( message:String ) extends VText {
+  override def toString = {
+    "[^A-Z]*".r.replaceAllIn(message.toUpperCase,"")
+    .replaceAll("FULLSTOP",".")
+    .replaceAll("CERO","0")
+    .replaceAll("EINZ","1")
+    .replaceAll("ZWEI","2")
+    .replaceAll("TRES","3")
+    .replaceAll("CUATRO","4")
+    .replaceAll("CINQ","5")
+    .replaceAll("SECHS","6")
+    .replaceAll("SIETE","7")
+    .replaceAll("HUIT","8")
+    .replaceAll("NEUF","9")
+  }
+
+  def toRawString = message
+}
+
+object PlainText {
+  def apply(k:String) = new PlainText( k.toList.map(_.toString).map {
+    case "0" => "CERO"
+    case "1" => "EINZ"
+    case "2" => "ZWEI"
+    case "3" => "TRES"
+    case "4" => "CUATRO"
+    case "5" => "CINQ"
+    case "6" => "SECHS"
+    case "7" => "SIETE"
+    case "8" => "HUIT"
+    case "9" => "NEUF"
+    case "." => "FULLSTOP"
+    case a:String => "[^A-Z]*".r.replaceAllIn(a.toUpperCase,"")
+  }.mkString )
+}
+
+
+class CipherText( cipher:String ) extends VText {
+  override def toString = cipher
+}
+
+object CipherText {
+  def apply(k:String) = new CipherText(
+    "[^A-Z]*".r.replaceAllIn(k.toUpperCase,"")
+  )
+}
+
+
+//
+// The Vigenère Cipher
+// -------------------
+//
+def vcipher( key:KeyText )( plaintext:PlainText ) : CipherText = {
+  val k = key.toString
+  val p = plaintext.toRawString
+  val kp = (k * (p.length / k.length + 1)) zip (p)
+
+  CipherText( (for( t <- kp; k = (t._1 - 'A'); p = (t._2 - 'A'); a = 'A' + (p + k) % 26 ) yield (a.toChar)).mkString )
+}
+
+def vdecipher( key:KeyText )( ciphertext:CipherText ) : PlainText = {
+  val k = key.toString
+  val c = ciphertext.toString
+  val kc = (k * (c.length / k.length + 1)) zip (c)
+
+  PlainText( (for( t <- kc; k = (t._1 - 'A'); c = (t._2 - 'A'); a = 'A' + (26 + c - k) % 26 ) yield (a.toChar)).mkString )
+}
+
+
+// Use Implicits to overcome the ambiguity problem of overloaded partial functions
+implicit def VTextToString( v:VText ) : String = v match {
+  case k:KeyText => k.toString
+  case p:PlainText => p.toString
+  case c:CipherText => c.toString
+  case _ => ""
+}
+implicit def StringToKeyText( s:String ) = KeyText(s)
+implicit def StringToPlainText( s:String ) = PlainText(s)
+implicit def StringToCipherText( s:String ) = CipherText(s)
+
+
+
+// Validate cipher/decipher
+assert( vcipher("LEMON")("ATTACKATDAWN").toString == "LXFOPVEFRNHR" )
+assert( vdecipher("LEMON")("LXFOPVEFRNHR").toString == "ATTACKATDAWN" )
+
+
+// A quick test
+val todaysKey = "lemon"
+val todaysCipher = vcipher(todaysKey) _
+val todaysDecipher = vdecipher(todaysKey) _
+
+val plaintext = "Attack at 0620."
+val ciphertext = todaysCipher(plaintext)
+
+println( "   Message:  " + plaintext + "\n" )
+println( "Enciphered:  " + ciphertext + "\n" )
+println( "Deciphered:  " + todaysDecipher( ciphertext ) + "\n" )
diff --git a/Task/Vigen-re-cipher/Seed7/vigen-re-cipher.seed7 b/Task/Vigen-re-cipher/Seed7/vigen-re-cipher.seed7
new file mode 100644
index 0000000000..94f7e21ea2
--- /dev/null
+++ b/Task/Vigen-re-cipher/Seed7/vigen-re-cipher.seed7
@@ -0,0 +1,51 @@
+$ include "seed7_05.s7i";
+
+const func string: vigenereCipher (in string: source, in var string: keyword) is func
+  result
+    var string: dest is "";
+  local
+    var char: ch is ' ';
+    var integer: index is 1;
+    var integer: shift is 0;
+  begin
+    keyword := upper(keyword);
+    for ch range source do
+      if ch in {'A' .. 'Z'} | {'a' .. 'z'} then
+        shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A');
+        dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') + shift) rem 26);
+        incr(index);
+      end if;
+    end for;
+  end func;
+
+const func string: vigenereDecipher (in string: source, in var string: keyword) is func
+  result
+    var string: dest is "";
+  local
+    var char: ch is ' ';
+    var integer: index is 0;
+    var integer: shift is 0;
+  begin
+    keyword := upper(keyword);
+    for ch key index range source do
+      if ch in {'A' .. 'Z'} | {'a' .. 'z'} then
+        shift := ord(keyword[succ(pred(index) rem length(keyword))]) - ord('A');
+        dest &:= chr(ord('A') + (ord(upper(ch)) - ord('A') - shift) mod 26);
+      end if;
+    end for;
+  end func;
+
+const proc: main is func
+  local
+    const string: input is "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
+    const string: keyword is "VIGENERECIPHER";
+    var string: encrypted is "";
+    var string: decrypted is "";
+  begin
+    writeln("Input:     " <& input);
+    writeln("key:       " <& keyword);
+    encrypted := vigenereCipher(input, keyword);
+    writeln("Encrypted: " <& encrypted);
+    decrypted := vigenereDecipher(encrypted, keyword);
+    writeln("Decrypted: " <& decrypted);
+  end func;
diff --git a/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-1.st b/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-1.st
new file mode 100644
index 0000000000..a0167fd02b
--- /dev/null
+++ b/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-1.st
@@ -0,0 +1,3 @@
+prep := [:s | s select:[:ch | ch isLetter] thenCollect:[:ch | ch asUppercase]].
+encrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:((cypher at:((i-1)\\key size+1))-$A) ]].
+decrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:26-((cypher at:((i-1)\\key size+1))-$A) ]].
diff --git a/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-2.st b/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-2.st
new file mode 100644
index 0000000000..6616995643
--- /dev/null
+++ b/Task/Vigen-re-cipher/Smalltalk/vigen-re-cipher-2.st
@@ -0,0 +1,7 @@
+plain := 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'.
+cypher := 'VIGENERECIPHER'.
+crypted := encrypt value:plain value:cypher.
+plain2 := decrypt value:crypted value:cypher.
+
+crypted -> 'WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY'
+plain2  -> 'BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH'
diff --git a/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr b/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr
new file mode 100644
index 0000000000..be41e7f79d
--- /dev/null
+++ b/Task/Vigen-re-cipher/TXR/vigen-re-cipher.txr
@@ -0,0 +1,24 @@
+@(next :args)
+@(do
+   (defun letter-mod26-op (func)  ;; add or subtract capital letters modulo 26
+     (lambda (a b) (+ #\A (mod (call func (- a #\A) (- b #\A)) 26))))
+   (defun vig (msg key encrypt)
+     (cat-str (mapcar (letter-mod26-op (if encrypt (fun +) (fun -)))
+                      (list-str msg)
+                      (repeat (list-str key))) "")))
+@(coll)@{key /[A-Za-z]/}@(end)
+@(coll)@{msg /[A-Za-z]/}@(end)
+@(cat key "")
+@(filter :upcase key)
+@(cat msg "")
+@(filter :upcase msg)
+@(bind encoded @(vig msg key t))
+@(bind decoded @(vig msg key nil))
+@(bind check @(vig encoded key nil))
+@(output)
+text:  @msg
+key:   @key
+enc:   @encoded
+dec:   @decoded
+check: @check
+@(end)
diff --git a/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-1.tcl b/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-1.tcl
new file mode 100644
index 0000000000..fd45909bb9
--- /dev/null
+++ b/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-1.tcl
@@ -0,0 +1,36 @@
+package require Tcl 8.6
+
+oo::class create Vigenere {
+    variable key
+    constructor {protoKey} {
+	foreach c [split $protoKey ""] {
+	    if {[regexp {[A-Za-z]} $c]} {
+		lappend key [scan [string toupper $c] %c]
+	    }
+	}
+    }
+
+    method encrypt {text} {
+	set out ""
+	set j 0
+	foreach c [split $text ""] {
+	    if {[regexp {[^a-zA-Z]} $c]} continue
+	    scan [string toupper $c] %c c
+	    append out [format %c [expr {($c+[lindex $key $j]-130)%26+65}]]
+	    set j [expr {($j+1) % [llength $key]}]
+	}
+	return $out
+    }
+
+    method decrypt {text} {
+	set out ""
+	set j 0
+	foreach c [split $text ""] {
+	    if {[regexp {[^A-Z]} $c]} continue
+	    scan $c %c c
+	    append out [format %c [expr {($c-[lindex $key $j]+26)%26+65}]]
+	    set j [expr {($j+1) % [llength $key]}]
+	}
+	return $out
+    }
+}
diff --git a/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-2.tcl b/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-2.tcl
new file mode 100644
index 0000000000..49ab70313e
--- /dev/null
+++ b/Task/Vigen-re-cipher/Tcl/vigen-re-cipher-2.tcl
@@ -0,0 +1,7 @@
+set cypher [Vigenere new "Vigenere Cipher"]
+set original "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
+set encrypted [$cypher encrypt $original]
+set decrypted [$cypher decrypt $encrypted]
+puts $original
+puts "Encrypted: $encrypted"
+puts "Decrypted: $decrypted"
diff --git a/Task/Vigen-re-cipher/Vedit-macro-language/vigen-re-cipher.vedit b/Task/Vigen-re-cipher/Vedit-macro-language/vigen-re-cipher.vedit
new file mode 100644
index 0000000000..7b20c131b6
--- /dev/null
+++ b/Task/Vigen-re-cipher/Vedit-macro-language/vigen-re-cipher.vedit
@@ -0,0 +1,48 @@
+Get_Input(10, "Key: ", STATLINE+NOCR)		// @10 = key
+Reg_Copy_Block(11, Cur_Pos, EOL_Pos)		// @11 = copy of original text
+EOL Ins_Newline
+Ins_Text("Key = ") Reg_Ins(10) Ins_Newline
+
+// Prepare the key into numeric registers #130..:
+Buf_Switch(Buf_Free)
+Reg_Ins(10)
+Case_Upper_Block(0, Cur_Pos)
+BOF
+#2 = Reg_Size(10)				// #2 = key length
+for (#3=130; #3 < 130+#2; #3++) {
+    #@3 = Cur_Char
+    Char(1)
+}
+Buf_Quit(OK)
+
+Ins_Text("Encrypted: ")
+#4 = Cur_Pos
+Reg_Ins(11)					// copy of original text
+Replace_Block("|!|A", "", #4, EOL_Pos, BEGIN+ALL+NOERR) // remove non-alpha chars
+Case_Upper_Block(#4, EOL_Pos)			// convert to upper case
+Goto_Pos(#4)
+#1 = 1; Call("ENCRYPT_DECRYPT")			// Encrypt the line
+Reg_Copy_Block(11, #4, Cur_Pos)			// Copy encrypted text text to next line
+Ins_Newline
+Ins_Text("Decrypted: ")
+Reg_Ins(11, BEGIN)
+#1 = -1; Call("ENCRYPT_DECRYPT")		// Decrypt the line
+
+Return
+
+// Encrypt or decrypt text on current line in-place, starting from cursor position.
+//   in: #1 = direction (1=encrypt, -1=decrypt)
+//       #2 = key length,  #130...#189 = the key
+//
+:ENCRYPT_DECRYPT:
+    Num_Push(6,9)
+    #6 = 0
+    While (!At_EOL) {
+       #7 = #6+130				// pointer to key array
+       #8 = #@7					// get key character
+       #9 = (Cur_Char + #8*#1 + 26) % 26 + 'A'	// decrypt/encrypt
+       Ins_Char(#9, OVERWRITE)			// write the converted char
+       #6 = (#6+1) % #2
+    }
+    Num_Pop(6,9)
+Return
diff --git a/Task/Vigen-re-cipher/XPL0/vigen-re-cipher.xpl0 b/Task/Vigen-re-cipher/XPL0/vigen-re-cipher.xpl0
new file mode 100644
index 0000000000..1ddb0239e8
--- /dev/null
+++ b/Task/Vigen-re-cipher/XPL0/vigen-re-cipher.xpl0
@@ -0,0 +1,21 @@
+code ChIn=7, ChOut=8;
+int  Neg, C, Len, I, Key;
+char KeyWord(80);
+[Neg:= false;                                   \skip to KEYWORD
+repeat C:= ChIn(8);  if C=^- then Neg:= true;  until C>=^A & C<=^Z;
+Len:= 0;                                        \read in KEYWORD
+repeat KeyWord(Len):= C-^A;  Len:= Len+1;  C:= ChIn(8);  until C<^A ! C>^Z;
+I:= 0;                                          \initialize cycling index
+repeat  C:= ChIn(1);
+        if C>=^a & C<=^z then C:= C-$20;        \capitalize
+        if C>=^A & C<=^Z then                   \discard non-alphas
+            [Key:= KeyWord(I);  I:= I+1;  if I>=Len then I:= 0;
+            if Neg then Key:= -Key;             \decrypting?
+            C:= C+Key;
+            if C>^Z then C:= C-26
+            else if C<^A then C:= C+26;
+            ChOut(0, C);
+            ];
+until   C=$1A;  \EOF
+ChOut(0, $1A);  \encrypted file must end with EOF otherwise the decode will hang
+]
diff --git a/Task/Visualize-a-tree/0DESCRIPTION b/Task/Visualize-a-tree/0DESCRIPTION
new file mode 100644
index 0000000000..a403c5b58b
--- /dev/null
+++ b/Task/Visualize-a-tree/0DESCRIPTION
@@ -0,0 +1,3 @@
+A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming.  It's often helpful to visually examine such a structure.  There are many ways to represent trees to a reader, such as indented text (à la unix tree command), nested HTML tables, hierarchical GUI widgets, 2D or 3D images, etc.
+
+'''Task''': Write a program to produce a visual representation of some tree.  The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
diff --git a/Task/Visualize-a-tree/BBC-BASIC/visualize-a-tree.bbc b/Task/Visualize-a-tree/BBC-BASIC/visualize-a-tree.bbc
new file mode 100644
index 0000000000..fca93defd1
--- /dev/null
+++ b/Task/Visualize-a-tree/BBC-BASIC/visualize-a-tree.bbc
@@ -0,0 +1,55 @@
+      INSTALL @lib$+"WINLIB5"
+      ON ERROR SYS "MessageBox", @hwnd%, REPORT$, 0, 0 : QUIT
+
+      REM!WC Windows constants:
+      TVI_SORT = -65533
+      TVIF_TEXT = 1
+      TVM_INSERTITEM = 4352
+      TVS_HASBUTTONS = 1
+      TVS_HASLINES = 2
+      TVS_LINESATROOT = 4
+
+      REM. TV_INSERTSTRUCT
+      DIM tvi{hParent%,       \
+      \       hInsertAfter%,  \
+      \       mask%,          \
+      \       hItem%,         \
+      \       state%,         \
+      \       stateMask%,     \
+      \       pszText%,       \
+      \       cchTextMax%,    \
+      \       iImage%,        \
+      \       iSelectedImage%,\
+      \       cChildren%,     \
+      \       lParam%         \
+      \      }
+
+      SYS "InitCommonControls"
+      hTree% = FN_createwindow("SysTreeView32", "", 0, 0, @vdu.tr%, @vdu.tb%, 0, \
+      \                        TVS_HASLINES OR TVS_HASBUTTONS OR TVS_LINESATROOT, 0)
+      hroot% = FNinsertnode(0, "Root")
+      hchild1% = FNinsertnode(hroot%, "Child 1")
+      hchild2% = FNinsertnode(hroot%, "Child 2")
+      hchild11% = FNinsertnode(hchild1%, "Grandchild 1")
+      hchild12% = FNinsertnode(hchild1%, "Grandchild 2")
+      hchild21% = FNinsertnode(hchild2%, "Grandchild 3")
+      hchild22% = FNinsertnode(hchild2%, "Grandchild 4")
+
+      REPEAT
+        WAIT 1
+      UNTIL FALSE
+      END
+
+      DEF FNinsertnode(hparent%, text$)
+      LOCAL hnode%
+      text$ += CHR$0
+
+      tvi.hParent% = hparent%
+      tvi.hInsertAfter% = TVI_SORT
+      tvi.mask% = TVIF_TEXT
+      tvi.pszText% = !^text$
+
+      SYS "SendMessage", hTree%, TVM_INSERTITEM, 0, tvi{} TO hnode%
+      IF hnode% = 0 ERROR 100, "TVM_INSERTITEM failed"
+      SYS "InvalidateRect", hTree%, 0, 0
+      = hnode%
diff --git a/Task/Visualize-a-tree/C/visualize-a-tree.c b/Task/Visualize-a-tree/C/visualize-a-tree.c
new file mode 100644
index 0000000000..1db25f3fb2
--- /dev/null
+++ b/Task/Visualize-a-tree/C/visualize-a-tree.c
@@ -0,0 +1,45 @@
+#include 
+#include 
+
+typedef struct stem_t *stem;
+struct stem_t { const char *str; stem next; };
+
+void tree(int root, stem head)
+{
+	static const char *sdown = "  |", *slast = "  `", *snone = "   ";
+	struct stem_t col = {0, 0}, *tail;
+
+	for (tail = head; tail; tail = tail->next) {
+		printf("%s", tail->str);
+		if (!tail->next) break;
+	}
+
+	printf("--%d\n", root);
+
+	if (root <= 1) return;
+
+	if (tail && tail->str == slast)
+		tail->str = snone;
+
+	if (!tail)	tail = head = &col;
+	else		tail->next = &col;
+
+	while (root) { // make a tree by doing something random
+		int r = 1 + (rand() % root);
+		root -= r;
+		col.str = root ? sdown : slast;
+
+		tree(r, head);
+	}
+
+	tail->next = 0;
+}
+
+int main(int c, char**v)
+{
+	int n;
+	if (c < 2 || (n = atoi(v[1])) < 0) n = 8;
+
+	tree(n, 0);
+	return 0;
+}
diff --git a/Task/Visualize-a-tree/D/visualize-a-tree.d b/Task/Visualize-a-tree/D/visualize-a-tree.d
new file mode 100644
index 0000000000..34cd596c29
--- /dev/null
+++ b/Task/Visualize-a-tree/D/visualize-a-tree.d
@@ -0,0 +1,20 @@
+import std.stdio, std.conv, std.algorithm, std.array;
+
+struct BTNode(T) { T value; BTNode* left, right; }
+
+string[] treeIndent(T)(in BTNode!T* t) {
+    if (t is null) return ["-- (null)"];
+    const tr = treeIndent(t.right);
+    return text("--", t.value) ~
+           map!q{"  |" ~ a}(treeIndent(t.left)).array() ~
+           ("  `" ~ tr[0]) ~ map!q{"   " ~ a}(tr[1..$]).array();
+}
+
+void main () {
+    static N(T)(T v, BTNode!T* l=null, BTNode!T* r=null) {
+        return new BTNode!T(v, l, r);
+    }
+
+    const tree = N(1, N(2, N(4, N(7)), N(5)), N(3, N(6, N(8), N(9))));
+    writefln("%-(%s\n%)", tree.treeIndent());
+}
diff --git a/Task/Visualize-a-tree/Go/visualize-a-tree.go b/Task/Visualize-a-tree/Go/visualize-a-tree.go
new file mode 100644
index 0000000000..96502c4a03
--- /dev/null
+++ b/Task/Visualize-a-tree/Go/visualize-a-tree.go
@@ -0,0 +1,29 @@
+package main
+
+import (
+    "encoding/json"
+    "fmt"
+    "log"
+)
+
+type Node struct {
+    Name     string
+    Children []*Node
+}
+
+func main() {
+    tree := &Node{"root", []*Node{
+        &Node{"a", []*Node{
+            &Node{"d", nil},
+            &Node{"e", []*Node{
+                &Node{"f", nil},
+            }}}},
+        &Node{"b", nil},
+        &Node{"c", nil},
+    }}
+    b, err := json.MarshalIndent(tree, "", "   ")
+    if err != nil {
+        log.Fatal(err)
+    }
+    fmt.Println(string(b))
+}
diff --git a/Task/Visualize-a-tree/Haskell/visualize-a-tree.hs b/Task/Visualize-a-tree/Haskell/visualize-a-tree.hs
new file mode 100644
index 0000000000..63c93de325
--- /dev/null
+++ b/Task/Visualize-a-tree/Haskell/visualize-a-tree.hs
@@ -0,0 +1,15 @@
+data Tree a = Empty | Node { value :: a, left :: Tree a, right :: Tree a }
+	deriving (Show, Eq)
+
+tree = Node 1 (Node 2 (Node 4 (Node 7 Empty Empty) Empty)
+	(Node 5 Empty Empty)) (Node 3 (Node 6 (Node 8 Empty Empty)
+	(Node 9 Empty Empty)) Empty)
+
+treeIndent Empty = ["-- (nil)"]
+treeIndent t = ["--" ++ show (value t)]
+	++ map ("  |"++) ls ++ ("  `" ++ r):map ("   "++) rs
+	where
+	(r:rs) = treeIndent$right t
+	ls     = treeIndent$left t
+
+main = mapM_ putStrLn $ treeIndent tree
diff --git a/Task/Visualize-a-tree/JavaScript/visualize-a-tree.js b/Task/Visualize-a-tree/JavaScript/visualize-a-tree.js
new file mode 100644
index 0000000000..bec7112f82
--- /dev/null
+++ b/Task/Visualize-a-tree/JavaScript/visualize-a-tree.js
@@ -0,0 +1,83 @@
+
+
+  
+    Stuff
+    
+    
+  
+  
+    
+
+

Headline

+ Blah blah +
+
+

More headline

+
Something something
+

Nested section

+ Somethin somethin list: +
    +
  • Apples
  • +
  • Oranges
  • +
  • Cetera Fruits
  • +
+
+
+
+
+ + diff --git a/Task/Visualize-a-tree/Mathematica/visualize-a-tree-1.math b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-1.math new file mode 100644 index 0000000000..ee24caa260 --- /dev/null +++ b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-1.math @@ -0,0 +1,3 @@ +edges = {1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5, + 3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}; +t = TreeGraph[edges, GraphStyle -> "VintageDiagram"] diff --git a/Task/Visualize-a-tree/Mathematica/visualize-a-tree-2.math b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-2.math new file mode 100644 index 0000000000..45133e06a2 --- /dev/null +++ b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-2.math @@ -0,0 +1,3 @@ +TreeForm[Defer@ + TreeGraph[{1 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 2 \[DirectedEdge] 5, + 3 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}, VertexLabels -> "Name"]] diff --git a/Task/Visualize-a-tree/Mathematica/visualize-a-tree-3.math b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-3.math new file mode 100644 index 0000000000..5ce3bcbffd --- /dev/null +++ b/Task/Visualize-a-tree/Mathematica/visualize-a-tree-3.math @@ -0,0 +1,3 @@ +OpenerView[{1, Column@{OpenerView[{2, Column@{OpenerView[{4, 7}, True], 5}}, True], + OpenerView[{3, OpenerView[{TraditionalForm[Cos[x]], Plot[Cos[x], {x, 0, 10}, ImageSize -> 150]}, + True]}, True]}}, True] diff --git a/Task/Visualize-a-tree/Maxima/visualize-a-tree.maxima b/Task/Visualize-a-tree/Maxima/visualize-a-tree.maxima new file mode 100644 index 0000000000..051743e7c9 --- /dev/null +++ b/Task/Visualize-a-tree/Maxima/visualize-a-tree.maxima @@ -0,0 +1,8 @@ +load(graphs)$ + +g: random_tree(10)$ + +is_tree(g); +true + +draw_graph(g)$ diff --git a/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 b/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 new file mode 100644 index 0000000000..dc3712b0c3 --- /dev/null +++ b/Task/Visualize-a-tree/Perl-6/visualize-a-tree.pl6 @@ -0,0 +1,23 @@ +sub visualize-tree($tree, &label, &children, + :$indent = '', + :@mid = ('├─', '│ '), + :@end = ('└─', ' '), +) { + sub visit($node, *@pre) { + gather { + take @pre[0] ~ label($node); + my @children := children($node); + my $end = @children.end; + for @children.kv -> $_, $child { + when $end { take visit($child, (@pre[1] X~ @end)) } + default { take visit($child, (@pre[1] X~ @mid)) } + } + } + } + visit($tree, $indent xx 2); +} + +# example tree built up of pairs +my $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]]; + +.say for visualize-tree($tree, *.key, *.value.list); diff --git a/Task/Visualize-a-tree/Prolog/visualize-a-tree.pro b/Task/Visualize-a-tree/Prolog/visualize-a-tree.pro new file mode 100644 index 0000000000..b68bffd25a --- /dev/null +++ b/Task/Visualize-a-tree/Prolog/visualize-a-tree.pro @@ -0,0 +1,19 @@ +% direction may be horizontal/vertical/list +display_tree(Direction) :- + sformat(A, 'Display tree ~w', [Direction]), + new(D, window(A)), + send(D, size, size(350,200)), + new(T, tree(text('Root'))), + send(T, neighbour_gap, 10), + new(S1, node(text('Child1'))), + new(S2, node(text('Child2'))), + send_list(T, son,[S1,S2]), + new(S11, node(text('Grandchild1'))), + new(S12, node(text('Grandchild2'))), + send_list(S1, son, [S11, S12]), + new(S21, node(text('Grandchild3'))), + new(S22, node(text('Grandchild4'))), + send_list(S2, son, [S21, S22]), + send(T, direction, Direction), + send(D, display, T), + send(D, open). diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree.py b/Task/Visualize-a-tree/Python/visualize-a-tree.py new file mode 100644 index 0000000000..4eaf4c9aeb --- /dev/null +++ b/Task/Visualize-a-tree/Python/visualize-a-tree.py @@ -0,0 +1,48 @@ +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/Visualize-a-tree/Tcl/visualize-a-tree-1.tcl b/Task/Visualize-a-tree/Tcl/visualize-a-tree-1.tcl new file mode 100644 index 0000000000..286db8ff2b --- /dev/null +++ b/Task/Visualize-a-tree/Tcl/visualize-a-tree-1.tcl @@ -0,0 +1,26 @@ +package require struct::tree + +proc visualize_tree {tree {nameattr name}} { + set path {} + $tree walk [$tree rootname] -order both {mode node} { + if {$mode eq "enter"} { + set s "" + foreach p $path { + append s [expr {[$tree next $p] eq "" ? " " : "\u2502 "}] + } + lappend path $node + append s [expr { + [$tree next $node] eq "" ? "\u2514\u2500" : "\u251c\u2500" + }] + if {[$tree keyexists $node $nameattr]} { + set name [$tree get $node $nameattr] + } else { + # No node name attribute; use the raw name + set name $node + } + puts "$s$name" + } else { + set path [lrange $path 0 end-1] + } + } +} diff --git a/Task/Visualize-a-tree/Tcl/visualize-a-tree-2.tcl b/Task/Visualize-a-tree/Tcl/visualize-a-tree-2.tcl new file mode 100644 index 0000000000..55f9cf6782 --- /dev/null +++ b/Task/Visualize-a-tree/Tcl/visualize-a-tree-2.tcl @@ -0,0 +1,3 @@ +# Sample tree to demonstrate with +struct::tree t deserialize {root {} {} a 0 {} d 3 {} e 3 {} f 9 {} b 0 {} c 0 {}} +visualize_tree t diff --git a/Task/Voronoi-diagram/0DESCRIPTION b/Task/Voronoi-diagram/0DESCRIPTION new file mode 100644 index 0000000000..2fc31b4e67 --- /dev/null +++ b/Task/Voronoi-diagram/0DESCRIPTION @@ -0,0 +1,3 @@ +A [[wp:Voronoi diagram|Voronoi diagram]] is a diagram consisting of a number of sites. Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''. + +The task is to demonstrate how to generate and display a Voroni diagram. See algo [[K-means++ clustering]]. diff --git a/Task/Voronoi-diagram/C/voronoi-diagram.c b/Task/Voronoi-diagram/C/voronoi-diagram.c new file mode 100644 index 0000000000..cb41165dae --- /dev/null +++ b/Task/Voronoi-diagram/C/voronoi-diagram.c @@ -0,0 +1,119 @@ +#include +#include +#include + +#define N_SITES 150 +double site[N_SITES][2]; +unsigned char rgb[N_SITES][3]; + +int size_x = 640, size_y = 480; + +inline double sq2(double x, double y) +{ + return x * x + y * y; +} + +#define for_k for (k = 0; k < N_SITES; k++) +int nearest_site(double x, double y) +{ + int k, ret = 0; + double d, dist = 0; + for_k { + d = sq2(x - site[k][0], y - site[k][1]); + if (!k || d < dist) { + dist = d, ret = k; + } + } + return ret; +} + +/* see if a pixel is different from any neighboring ones */ +int at_edge(int *color, int y, int x) +{ + int i, j, c = color[y * size_x + x]; + for (i = y - 1; i <= y + 1; i++) { + if (i < 0 || i >= size_y) continue; + + for (j = x - 1; j <= x + 1; j++) { + if (j < 0 || j >= size_x) continue; + if (color[i * size_x + j] != c) return 1; + } + } + return 0; +} + +#define AA_RES 4 /* average over 4x4 supersampling grid */ +void aa_color(unsigned char *pix, int y, int x) +{ + int i, j, n; + double r = 0, g = 0, b = 0, xx, yy; + for (i = 0; i < AA_RES; i++) { + yy = y + 1. / AA_RES * i + .5; + for (j = 0; j < AA_RES; j++) { + xx = x + 1. / AA_RES * j + .5; + n = nearest_site(xx, yy); + r += rgb[n][0]; + g += rgb[n][1]; + b += rgb[n][2]; + } + } + pix[0] = r / (AA_RES * AA_RES); + pix[1] = g / (AA_RES * AA_RES); + pix[2] = b / (AA_RES * AA_RES); +} + +#define for_i for (i = 0; i < size_y; i++) +#define for_j for (j = 0; j < size_x; j++) +void gen_map() +{ + int i, j, k; + int *nearest = malloc(sizeof(int) * size_y * size_x); + unsigned char *ptr, *buf, color; + + ptr = buf = malloc(3 * size_x * size_y); + for_i for_j nearest[i * size_x + j] = nearest_site(j, i); + + for_i for_j { + if (!at_edge(nearest, i, j)) + memcpy(ptr, rgb[nearest[i * size_x + j]], 3); + else /* at edge, do anti-alias rastering */ + aa_color(ptr, i, j); + ptr += 3; + } + + /* draw sites */ + for (k = 0; k < N_SITES; k++) { + color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255; + + for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) { + if (i < 0 || i >= size_y) continue; + + for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) { + if (j < 0 || j >= size_x) continue; + + ptr = buf + 3 * (i * size_x + j); + ptr[0] = ptr[1] = ptr[2] = color; + } + } + } + + printf("P6\n%d %d\n255\n", size_x, size_y); + fflush(stdout); + fwrite(buf, size_y * size_x * 3, 1, stdout); +} + +#define frand(x) (rand() / (1. + RAND_MAX) * x) +int main() +{ + int k; + for_k { + site[k][0] = frand(size_x); + site[k][1] = frand(size_y); + rgb [k][0] = frand(256); + rgb [k][1] = frand(256); + rgb [k][2] = frand(256); + } + + gen_map(); + return 0; +} diff --git a/Task/Voronoi-diagram/D/voronoi-diagram.d b/Task/Voronoi-diagram/D/voronoi-diagram.d new file mode 100644 index 0000000000..da129df906 --- /dev/null +++ b/Task/Voronoi-diagram/D/voronoi-diagram.d @@ -0,0 +1,40 @@ +import std.random, std.algorithm, std.range, bitmap; + +struct Point { int x, y; } + +Point[] randomPoints(in size_t nPoints, in size_t nx, in size_t ny) { + immutable RndPt = (int) => Point(uniform(0, nx), uniform(0, ny)); + return iota(nPoints).map!RndPt().array(); +} + +Image!RGB generateVoronoi(in Point[] pts, + in size_t nx, in size_t ny) { + // Generate a random color for each site. + immutable RndRBG = (int) => RGB(cast(ubyte)uniform(0, 256), + cast(ubyte)uniform(0, 256), + cast(ubyte)uniform(0, 256)); + const colors = iota(pts.length).map!RndRBG().array(); + + // Generate diagram by coloring pixels with color of nearest site. + auto img = new typeof(return)(nx, ny); + foreach (immutable x; 0 .. nx) + foreach (immutable y; 0 .. ny) { + immutable dCmp = (in Point a, in Point b) nothrow => + ((a.x - x) ^^ 2 + (a.y - y) ^^ 2) < + ((b.x - x) ^^ 2 + (b.y - y) ^^ 2); + img[x, y] = colors[pts.length - minPos!dCmp(pts).length]; + } + + // Mark each site with a black dot. + foreach (immutable p; pts) + img[p.x, p.y] = RGB.black; + return img; +} + +void main() { + enum imageWidth = 640, + imageHeight = 480; + randomPoints(150, imageWidth, imageHeight) + .generateVoronoi(imageWidth, imageHeight) + .savePPM6("voronoi.ppm"); +} diff --git a/Task/Voronoi-diagram/Go/voronoi-diagram.go b/Task/Voronoi-diagram/Go/voronoi-diagram.go new file mode 100644 index 0000000000..590f906a0d --- /dev/null +++ b/Task/Voronoi-diagram/Go/voronoi-diagram.go @@ -0,0 +1,83 @@ +package main + +import ( + "fmt" + "image" + "image/color" + "image/draw" + "image/png" + "math/rand" + "os" + "time" +) + +const ( + imageWidth = 300 + imageHeight = 200 + nSites = 10 +) + +func main() { + writePngFile(generateVoronoi(randomSites())) +} + +func generateVoronoi(sx, sy []int) image.Image { + // generate a random color for each site + sc := make([]color.NRGBA, nSites) + for i := range sx { + sc[i] = color.NRGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), + uint8(rand.Intn(256)), 255} + } + + // generate diagram by coloring each pixel with color of nearest site + img := image.NewNRGBA(image.Rect(0, 0, imageWidth, imageHeight)) + for x := 0; x < imageWidth; x++ { + for y := 0; y < imageHeight; y++ { + dMin := dot(imageWidth, imageHeight) + var sMin int + for s := 0; s < nSites; s++ { + if d := dot(sx[s]-x, sy[s]-y); d < dMin { + sMin = s + dMin = d + } + } + img.SetNRGBA(x, y, sc[sMin]) + } + } + // mark each site with a black box + black := image.NewUniform(color.Black) + for s := 0; s < nSites; s++ { + draw.Draw(img, image.Rect(sx[s]-2, sy[s]-2, sx[s]+2, sy[s]+2), + black, image.ZP, draw.Src) + } + return img +} + +func dot(x, y int) int { + return x*x + y*y +} + +func randomSites() (sx, sy []int) { + rand.Seed(time.Now().Unix()) + sx = make([]int, nSites) + sy = make([]int, nSites) + for i := range sx { + sx[i] = rand.Intn(imageWidth) + sy[i] = rand.Intn(imageHeight) + } + return +} + +func writePngFile(img image.Image) { + f, err := os.Create("voronoi.png") + if err != nil { + fmt.Println(err) + return + } + if err = png.Encode(f, img); err != nil { + fmt.Println(err) + } + if err = f.Close(); err != nil { + fmt.Println(err) + } +} diff --git a/Task/Voronoi-diagram/Icon/voronoi-diagram.icon b/Task/Voronoi-diagram/Icon/voronoi-diagram.icon new file mode 100644 index 0000000000..6340c466e6 --- /dev/null +++ b/Task/Voronoi-diagram/Icon/voronoi-diagram.icon @@ -0,0 +1,71 @@ +link graphics,printf,strings + +record site(x,y,colour) # site data position and colour +invocable all # needed for string metrics + +procedure main(A) # voronoi + +&window := open("Voronoi","g","bg=black") | stop("Unable to open window") + +WAttrib("canvas=hidden") # figure out maximal size width & height +WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight"))) +WAttrib("canvas=maximal") +height := WAttrib("height") +width := WAttrib("width") + +metrics := ["hypot","taxi","taxi3"] # different metrics + +while case a := get(A) of { # command line arguments + "--sites" | "-s" : sites := 0 < integer(a := get(A)) | runerr(205,a) + "--height" | "-h" : height := 0 < (height >= integer(a := get(A))) | runerr(205,a) + "--width" | "-w" : width := 0 < (width >= integer(a := get(A))) | runerr(205,a) + "--metric" | "-m" : metric := ((a := get(A)) == !metrics) | runerr(205,a) + "--help" | "-?" : write("Usage:\n voronoi [[--sites|-s] n] ", + "[[--height|-h] pixels] [[--width|-w] pixels]", + "[[--metric|-m] metric_procedure]", + "[--help|-?]\n\n") + } + +/metric := metrics[1] # default to normal +/sites := ?(r := integer(.1*width)) + r # sites = random .1 to .2 of width if not given + +WAttrib(sprintf("label=Voronoi %dx%d %d %s",width,height,sites,metric)) +WAttrib(sprintf("size=%d,%d",width,height)) + +x := "0123456789abcdef" # hex for random sites (colour) +siteL := [] +every 1 to sites do # random sites + put(siteL, site(?width,?height,cat("#",?x,?x,?x,?x,?x,?x))) + +VoronoiDiagram(width,height,siteL,metric) # Voronoi-ize it +WDone() +end + +procedure hypot(x,y,site) # normal metric +return sqrt((x-site.x)^2 + (y-site.y)^2) +end + +procedure taxi(x,y,site) # "taxi" metric +return abs(x-site.x)+abs(y-site.y) +end + +procedure taxi3(x,y,site) # copied from a commented out version (TCL) +return (abs(x-site.x)^3+abs(y-site.y)^3)^(.3) +end + +procedure VoronoiDiagram(width,height,siteL,metric) + /metric := hypot + every y := 1 to height & x := 1 to width do { + dist := width+height # anything larger than diagonal + every site := !siteL do { + if dist < (dt := metric(x,y,site)) then next # skip + else if dist >:= dt then Fg(site.colour) # site + else Fg("#000000") # unowned + DrawPoint(x,y) + } + } + + Fg("Black") + every site := !siteL do # mark sites + DrawCircle(site.x,site.y,1) +end diff --git a/Task/Voronoi-diagram/J/voronoi-diagram.j b/Task/Voronoi-diagram/J/voronoi-diagram.j new file mode 100644 index 0000000000..f0de6578a0 --- /dev/null +++ b/Task/Voronoi-diagram/J/voronoi-diagram.j @@ -0,0 +1,7 @@ +NB. (number of points) voronoi (shape) +NB. Generates an array of indices of the nearest point +voronoi =: 4 :0 + p =. (x,2) ?@$ y + (i.<./)@:(+/@:*:@:-"1&p)"1 ,"0/&i./ y +) +viewmat 25 voronoi 500 500 diff --git a/Task/Voronoi-diagram/Liberty-BASIC/voronoi-diagram.liberty b/Task/Voronoi-diagram/Liberty-BASIC/voronoi-diagram.liberty new file mode 100644 index 0000000000..7393c06428 --- /dev/null +++ b/Task/Voronoi-diagram/Liberty-BASIC/voronoi-diagram.liberty @@ -0,0 +1,91 @@ +WindowWidth =600 +WindowHeight =600 + +sites = 100 +xEdge = 400 +yEdge = 400 +graphicbox #w.gb1, 10, 10, xEdge, yEdge + +open "Voronoi neighbourhoods" for window as #w + +#w "trapclose quit" +#w.gb1 "down ; fill black ; size 4" +#w.gb1 "font courier_new 12" + +dim townX( sites), townY( sites), col$( sites) + +for i =1 to sites + townX( i) =int( xEdge *rnd( 1)) + townY( i) =int( yEdge *rnd( 1)) + col$( i) = int( 256 *rnd( 1)); " "; int( 256 *rnd( 1)); " "; int( 256 *rnd( 1)) + #w.gb1 "color "; col$( i) + #w.gb1 "set "; townX( i); " "; townY( i) +next i + +#w.gb1 "size 1" + +dim nearestIndex(xEdge, yEdge) +dim dist(xEdge, yEdge) + +start = time$("ms") + +'fill distance table with distances from the first site +for x = 0 to xEdge - 1 + for y = 0 to yEdge - 1 + dist(x, y) = (townX(1) - x) ^ 2 + (townY(1) - y) ^ 2 + nearestIndex(x, y) = 1 + next y +next x + +#w.gb1 "color darkblue" +'for other towns +for i = 2 to sites + 'display some progress + #w.gb1 "place 0 20" + #w.gb1 "\computing: "; using("###.#", i / sites * 100); "%" + 'look left + for x = townX(i) to 0 step -1 + if not(checkRow(i, x,0, yEdge - 1)) then exit for + next x + 'look right + for x = townX(i) + 1 to xEdge - 1 + if not(checkRow(i, x, 0, yEdge - 1)) then exit for + next x + scan +next i + +for x = 0 to xEdge - 1 + for y =0 to yEdge - 1 + #w.gb1 "color "; col$(nearestIndex(x, y)) + startY = y + nearest = nearestIndex(x, y) + for y = y + 1 to yEdge + if nearestIndex(x, y) <> nearest then y = y - 1 : exit for + next y + #w.gb1 "line "; x; " "; startY; " "; x; " "; y + 1 + next y +next x + +#w.gb1 "color black; size 4" +for i =1 to sites + #w.gb1 "set "; townX( i); " "; townY( i) +next i +print time$("ms") - start +wait + +sub quit w$ + close #w$ + end +end sub + +function checkRow(site, x, startY, endY) + dxSquared = (townX(site) - x) ^ 2 + for y = startY to endY + dSquared = (townY(site) - y) ^ 2 + dxSquared + if dSquared <= dist(x, y) then + dist(x, y) = dSquared + nearestIndex(x, y) = site + checkRow = 1 + end if + next y +end function diff --git a/Task/Voronoi-diagram/Mathematica/voronoi-diagram.math b/Task/Voronoi-diagram/Mathematica/voronoi-diagram.math new file mode 100644 index 0000000000..ada5acc590 --- /dev/null +++ b/Task/Voronoi-diagram/Mathematica/voronoi-diagram.math @@ -0,0 +1,3 @@ +Needs["ComputationalGeometry`"] +DiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, +{6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}] diff --git a/Task/Voronoi-diagram/Prolog/voronoi-diagram.pro b/Task/Voronoi-diagram/Prolog/voronoi-diagram.pro new file mode 100644 index 0000000000..f6af7b08da --- /dev/null +++ b/Task/Voronoi-diagram/Prolog/voronoi-diagram.pro @@ -0,0 +1,61 @@ +:- dynamic pt/6. +voronoi :- + V is random(20) + 20, + retractall(pt(_,_,_,_)), + forall(between(1, V, I), + ( X is random(390) + 5, + Y is random(390) + 5, + R is random(65535), + G is random(65535), + B is random(65535), + assertz(pt(I,X,Y, R, G, B)) + )), + voronoi(manhattan, V), + voronoi(euclide, V), + voronoi(minkowski_3, V). + +voronoi(Distance, V) :- + sformat(A, 'Voronoi 400X400 ~w ~w', [V, Distance]), + new(D, window(A)), + send(D, size, size(400,400)), + new(Img, image(@nil, width := 400, height := 400 , kind := pixmap)), + + % get the list of the sites + bagof((N, X, Y), R^G^B^pt(N, X, Y, R, G, B), L), + + forall(between(0,399, I), + forall(between(0,399, J), + ( get_nearest_site(V, Distance, I, J, L, S), + pt(S, _, _, R, G, B), + send(Img, pixel(I, J, colour(@default, R, G, B)))))), + + new(Bmp, bitmap(Img)), + send(D, display, Bmp, point(0,0)), + send(D, open). + +% define predicatea foldl (functionnal spirit) +foldl([], _Pred, R, R). + +foldl([H | T], Pred, Acc, R) :- + call(Pred, H, Acc, R1), + foldl(T, Pred, R1, R). + +% predicate for foldl +compare(Distance, XP, YP, (N, X, Y), (D, S), R) :- + call(Distance, XP, YP, X, Y, DT), + ( DT < D -> R = (DT, N) ; R = (D, S)). + +% use of a fake site for the init of foldl +get_nearest_site(Distance, I, J, L, S) :- + foldl(L, compare(Distance, I, J), (65535, nil), (_, S)). + + + +manhattan(X1, Y1, X2, Y2, D) :- + D is abs(X2 - X1) + abs(Y2-Y1). + +euclide(X1, Y1, X2, Y2, D) :- + D is sqrt((X2 - X1)**2 + (Y2-Y1)**2). + +minkowski_3(X1, Y1, X2, Y2, D) :- + D is (abs(X2 - X1)**3 + abs(Y2-Y1)**3)**0.33. diff --git a/Task/Voronoi-diagram/PureBasic/voronoi-diagram-1.purebasic b/Task/Voronoi-diagram/PureBasic/voronoi-diagram-1.purebasic new file mode 100644 index 0000000000..63cc19726b --- /dev/null +++ b/Task/Voronoi-diagram/PureBasic/voronoi-diagram-1.purebasic @@ -0,0 +1,70 @@ +Structure VCoo + x.i: y.i + Colour.i: FillColour.i +EndStructure + +Macro RandInt(MAXLIMIT) + Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG)) +EndMacro + +Macro SQ2(X, Y) + ((X)*(X) + (Y)*(Y)) +EndMacro + +Procedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt) + Protected i, j, k, l + cnt-1 + Dim a(cnt) + For i=0 To cnt + a(i)\x = RandInt(xMax): a(i)\y = RandInt(yMax) + j = RandInt(255): k = RandInt(255): l = RandInt(255) + a(i)\Colour = RGBA(j, k, l, 255) + a(i)\FillColour = RGBA(255-j, 255-k, 255-l, 255) + Next i + ProcedureReturn #True +EndProcedure + +Procedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax) ; Euclidean + Protected i, x, y, img, dist.d, dt.d + img = CreateImage(#PB_Any, xMax+1, yMax+1) + If StartDrawing(ImageOutput(img)) + For y=0 To yMax + For x=0 To xMax + dist = Infinity() + For i=0 To ArraySize(a()) + dt = SQ2(x-a(i)\x, y-a(i)\y) + If dt > dist + Continue + ElseIf dt < dist + dist = dt + Plot(x,y,a(i)\FillColour) + Else ; 'Owner ship' is unclear, set pixel to transparent. + Plot(x,y,RGBA(0, 0, 0, 0)) + EndIf + Next + Next + Next + For i=0 To ArraySize(a()) + Circle(a(i)\x, a(i)\y, 1, a(i)\Colour) + Next + StopDrawing() + EndIf + ProcedureReturn img +EndProcedure + +; Main code +Define img, x, y, file$ +Dim V.VCoo(0) +x = 640: y = 480 +If Not GenRandomPoints(V(), x, y, 150): End: EndIf +img = MakeVoronoiDiagram(V(), x, y) +If img And OpenWindow(0, 0, 0, x, y, "Voronoi Diagram in PureBasic", #PB_Window_SystemMenu) + ImageGadget(0, 0, 0, x, y, ImageID(img)) + Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow +EndIf + +UsePNGImageEncoder() +file$ = SaveFileRequester("Save Image?", "Voronoi_Diagram_in_PureBasic.png", "PNG|*.png", 0) +If file$ <> "" + SaveImage(img, file$, #PB_ImagePlugin_PNG) +EndIf diff --git a/Task/Voronoi-diagram/PureBasic/voronoi-diagram-2.purebasic b/Task/Voronoi-diagram/PureBasic/voronoi-diagram-2.purebasic new file mode 100644 index 0000000000..2cd89ba349 --- /dev/null +++ b/Task/Voronoi-diagram/PureBasic/voronoi-diagram-2.purebasic @@ -0,0 +1,68 @@ +Structure VCoo + x.i: y.i + Colour.i: FillColour.i +EndStructure + +Macro RandInt(MAXLIMIT) + Int(MAXLIMIT*(Random(#MAXLONG)/#MAXLONG)) +EndMacro + +Procedure GenRandomPoints(Array a.VCoo(1), xMax, yMax, cnt) + Protected i, j, k, l + cnt-1 + Dim a(cnt) + For i=0 To cnt + a(i)\x = RandInt(xMax): a(i)\y = RandInt(yMax) + j = RandInt(255): k = RandInt(255): l = RandInt(255) + a(i)\Colour = RGBA(j, k, l, 255) + a(i)\FillColour = RGBA(255-j, 255-k, 255-l, 255) + Next i + ProcedureReturn #True +EndProcedure + +Procedure MakeVoronoiDiagram(Array a.VCoo(1),xMax, yMax) + Protected i, x, y, img, dist, dt, dx, dy + img = CreateImage(#PB_Any, xMax+1, yMax+1, 32) + If StartDrawing(ImageOutput(img)) + For y=0 To yMax + For x=0 To xMax + dist = #MAXLONG + For i=0 To ArraySize(a()) + dx = x-a(i)\x + dy = y-a(i)\y + dt = Sign(dx)*dx + Sign(dy)*dy + If dt > dist ; no update + Continue + ElseIf dt < dist ; an new 'owner' is found + dist = dt + Plot(x,y,a(i)\FillColour) + Else ; dt = dist + Plot(x,y,RGBA(0,0,0,0)) ; no clear 'owner', make the pixel transparent + EndIf + Next + Next + Next + For i=0 To ArraySize(a()) + Circle(a(i)\x, a(i)\y, 1, a(i)\Colour) + Next + StopDrawing() + EndIf + ProcedureReturn img +EndProcedure + +; Main code +Define img, x, y, file$ +Dim V.VCoo(0) +x = 640: y = 480 +If Not GenRandomPoints(V(), x, y, 150): End: EndIf +img = MakeVoronoiDiagram(V(), x, y) +If img And OpenWindow(0, 0, 0, x, y, "Voronoi Diagram in PureBasic", #PB_Window_SystemMenu) + ImageGadget(0, 0, 0, x, y, ImageID(img)) + Repeat: Until WaitWindowEvent() = #PB_Event_CloseWindow +EndIf + +UsePNGImageEncoder() +file$ = SaveFileRequester("Save Image?", "Voronoi_Diagram_in_PureBasic.png", "PNG|*.png", 0) +If file$ <> "" + SaveImage(img, file$, #PB_ImagePlugin_PNG) +EndIf diff --git a/Task/Voronoi-diagram/Python/voronoi-diagram.py b/Task/Voronoi-diagram/Python/voronoi-diagram.py new file mode 100644 index 0000000000..5503fd96c3 --- /dev/null +++ b/Task/Voronoi-diagram/Python/voronoi-diagram.py @@ -0,0 +1,33 @@ +from PIL import Image +import random +import math + +def generate_voronoi_diagram(width, height, num_cells): + image = Image.new("RGB", (width, height)) + putpixel = image.putpixel + imgx, imgy = image.size + nx = [] + ny = [] + nr = [] + ng = [] + nb = [] + for i in range(num_cells): + nx.append(random.randrange(imgx)) + ny.append(random.randrange(imgy)) + nr.append(random.randrange(256)) + ng.append(random.randrange(256)) + nb.append(random.randrange(256)) + for y in range(imgy): + for x in range(imgx): + dmin = math.hypot(imgx-1, imgy-1) + j = -1 + for i in range(num_cells): + d = math.hypot(nx[i]-x, ny[i]-y) + if d < dmin: + dmin = d + j = i + putpixel((x, y), (nr[j], ng[j], nb[j])) + image.save("VoronoiDiagram.png", "PNG") + image.show() + +generate_voronoi_diagram(500, 500, 25) diff --git a/Task/Voronoi-diagram/Ruby/voronoi-diagram.rb b/Task/Voronoi-diagram/Ruby/voronoi-diagram.rb new file mode 100644 index 0000000000..23b9c75275 --- /dev/null +++ b/Task/Voronoi-diagram/Ruby/voronoi-diagram.rb @@ -0,0 +1,36 @@ +load 'raster_graphics.rb' + +class ColourPixel < Pixel + def initialize(x, y, colour) + @colour = colour + super x, y + end + attr_accessor :colour + + def distance_to(px, py) + Math::hypot(px - x, py - y) + end +end + +width, height = 300, 200 +npoints = 20 +pixmap = Pixmap.new(width,height) + +@bases = npoints.times.collect do |i| + ColourPixel.new( + 3+rand(width-6), 3+rand(height-6), # provide a margin to draw a circle + RGBColour.new(rand(256), rand(256), rand(256)) + ) +end + +pixmap.each_pixel do |x, y| + nearest = @bases.min_by {|base| base.distance_to(x, y)} + pixmap[x, y] = nearest.colour +end + +@bases.each do |base| + pixmap[base.x, base.y] = RGBColour::BLACK + pixmap.draw_circle(base, 2, RGBColour::BLACK) +end + +pixmap.save_as_png("voronoi_rb.png") diff --git a/Task/Voronoi-diagram/Seed7/voronoi-diagram.seed7 b/Task/Voronoi-diagram/Seed7/voronoi-diagram.seed7 new file mode 100644 index 0000000000..ba666717ce --- /dev/null +++ b/Task/Voronoi-diagram/Seed7/voronoi-diagram.seed7 @@ -0,0 +1,52 @@ +$ include "seed7_05.s7i"; + include "draw.s7i"; + include "keybd.s7i"; + +const type: point is new struct + var integer: xPos is 0; + var integer: yPos is 0; + var color: col is black; + end struct; + +const proc: generateVoronoiDiagram (in integer: width, in integer: height, in integer: numCells) is func + local + var array point: points is 0 times point.value; + var integer: index is 0; + var integer: x is 0; + var integer: y is 0; + var integer: distSquare is 0; + var integer: minDistSquare is 0; + var integer: indexOfNearest is 0; + begin + screen(width, height); + points := numCells times point.value; + for index range 1 to numCells do + points[index].xPos := rand(0, width); + points[index].yPos := rand(0, height); + points[index].col := color(rand(0, 65535), rand(0, 65535), rand(0, 65535)); + end for; + for y range 0 to height do + for x range 0 to width do + minDistSquare := width ** 2 + height ** 2; + for index range 1 to numCells do + distSquare := (points[index].xPos - x) ** 2 + (points[index].yPos - y) ** 2; + if distSquare < minDistSquare then + minDistSquare := distSquare; + indexOfNearest := index; + end if; + end for; + point(x, y, points[indexOfNearest].col); + end for; + end for; + for index range 1 to numCells do + line(points[index].xPos - 2, points[index].yPos, 4, 0, black); + line(points[index].xPos, points[index].yPos - 2, 0, 4, black); + end for; + end func; + +const proc: main is func + begin + generateVoronoiDiagram(500, 500, 25); + KEYBOARD := GRAPH_KEYBOARD; + readln(KEYBOARD); + end func; diff --git a/Task/Voronoi-diagram/Tcl/voronoi-diagram.tcl b/Task/Voronoi-diagram/Tcl/voronoi-diagram.tcl new file mode 100644 index 0000000000..b9b8611cb5 --- /dev/null +++ b/Task/Voronoi-diagram/Tcl/voronoi-diagram.tcl @@ -0,0 +1,35 @@ +package require Tk +proc r to {expr {int(rand()*$to)}}; # Simple helper + +proc voronoi {photo pointCount} { + for {set i 0} {$i < $pointCount} {incr i} { + lappend points [r [image width $photo]] [r [image height $photo]] + } + foreach {x y} $points { + lappend colors [format "#%02x%02x%02x" [r 256] [r 256] [r 256]] + } + set initd [expr {[image width $photo] + [image height $photo]}] + for {set i 0} {$i < [image width $photo]} {incr i} { + for {set j 0} {$j < [image height $photo]} {incr j} { + set color black + set d $initd + foreach {x y} $points c $colors { + set h [expr {hypot($x-$i,$y-$j)}] + ### Other interesting metrics + #set h [expr {abs($x-$i)+abs($y-$j)}] + #set h [expr {(abs($x-$i)**3+abs($y-$j)**3)**0.3}] + if {$d > $h} {set d $h;set color $c} + } + $photo put $color -to $i $j + } + # To display while generating, uncomment this line and the other one so commented + #if {$i%4==0} {update idletasks} + } +} + +# Generate a 600x400 Voronoi diagram with 60 random points +image create photo demo -width 600 -height 400 +pack [label .l -image demo] +# To display while generating, uncomment this line and the other one so commented +#update +voronoi demo 60 diff --git a/Task/Walk-a-directory-Non-recursively/0DESCRIPTION b/Task/Walk-a-directory-Non-recursively/0DESCRIPTION new file mode 100644 index 0000000000..6b34e7c317 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/0DESCRIPTION @@ -0,0 +1,5 @@ +Walk a given directory and print the ''names'' of files matching a given pattern. + +'''Note:''' This task is for non-recursive methods. These tasks should read a ''single directory'', not an entire directory tree. For code examples that read entire directory trees, see [[Walk Directory Tree]] + +'''Note:''' Please be careful when running any code presented here. diff --git a/Task/Walk-a-directory-Non-recursively/1META.yaml b/Task/Walk-a-directory-Non-recursively/1META.yaml new file mode 100644 index 0000000000..40458d9f21 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/1META.yaml @@ -0,0 +1,2 @@ +--- +note: File System Operations diff --git a/Task/Walk-a-directory-Non-recursively/ALGOL-68/walk-a-directory-non-recursively.alg b/Task/Walk-a-directory-Non-recursively/ALGOL-68/walk-a-directory-non-recursively.alg new file mode 100644 index 0000000000..cc79a1942b --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/ALGOL-68/walk-a-directory-non-recursively.alg @@ -0,0 +1,9 @@ +INT match=0, no match=1, out of memory error=2, other error=3; + +[]STRING directory = get directory("."); +FOR file index TO UPB directory DO + STRING file = directory[file index]; + IF grep in string("[Ss]ort*.[.]a68$", file, NIL, NIL) = match THEN + print((file, new line)) + FI +OD diff --git a/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.ada b/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.ada new file mode 100644 index 0000000000..c243ea48e5 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.ada @@ -0,0 +1,19 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Walk_Directory + (Directory : in String := "."; + Pattern : in String := "") -- empty pattern = all file names/subdirectory names +is + Search : Search_Type; + Dir_Ent : Directory_Entry_Type; +begin + Start_Search (Search, Directory, Pattern); + + while More_Entries (Search) loop + Get_Next_Entry (Search, Dir_Ent); + Put_Line (Simple_Name (Dir_Ent)); + end loop; + + End_Search (Search); +end Walk_Directory; diff --git a/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-1.applescript b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-1.applescript new file mode 100644 index 0000000000..774d11714a --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-1.applescript @@ -0,0 +1,2 @@ +tell application "Finder" to return name of every item in (startup disk) +--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"} diff --git a/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-2.applescript b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-2.applescript new file mode 100644 index 0000000000..56d9d826c8 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-2.applescript @@ -0,0 +1,2 @@ +tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name ends with "pdf" +--> EXAMPLE RESULT: {"About Stacks.pdf", "Test.pdf"} diff --git a/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-3.applescript b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-3.applescript new file mode 100644 index 0000000000..326d83af78 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-3.applescript @@ -0,0 +1,2 @@ +tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name does not contain "about" and name ends with "pdf" +--> RETURNS: {"Test.pdf"} diff --git a/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-4.applescript b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-4.applescript new file mode 100644 index 0000000000..861a91ff79 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/AppleScript/walk-a-directory-non-recursively-4.applescript @@ -0,0 +1 @@ +tell application "Finder" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with "pdf" diff --git a/Task/Walk-a-directory-Non-recursively/AutoHotkey/walk-a-directory-non-recursively.ahk b/Task/Walk-a-directory-Non-recursively/AutoHotkey/walk-a-directory-non-recursively.ahk new file mode 100644 index 0000000000..31dfd47910 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/AutoHotkey/walk-a-directory-non-recursively.ahk @@ -0,0 +1,3 @@ +Loop, %A_WinDir%\*.ini + out .= A_LoopFileName "`n" +MsgBox,% out diff --git a/Task/Walk-a-directory-Non-recursively/BASIC/walk-a-directory-non-recursively.basic b/Task/Walk-a-directory-Non-recursively/BASIC/walk-a-directory-non-recursively.basic new file mode 100644 index 0000000000..1644e3220c --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/BASIC/walk-a-directory-non-recursively.basic @@ -0,0 +1,12 @@ +DECLARE SUB show (pattern AS STRING) + +show "*.*" + +SUB show (pattern AS STRING) + DIM f AS STRING + f = DIR$(pattern) + DO WHILE LEN(f) + PRINT f + f = DIR$ + LOOP +END SUB diff --git a/Task/Walk-a-directory-Non-recursively/BBC-BASIC/walk-a-directory-non-recursively.bbc b/Task/Walk-a-directory-Non-recursively/BBC-BASIC/walk-a-directory-non-recursively.bbc new file mode 100644 index 0000000000..b3222a0c83 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/BBC-BASIC/walk-a-directory-non-recursively.bbc @@ -0,0 +1,17 @@ + directory$ = "C:\Windows\" + pattern$ = "*.ini" + PROClistdir(directory$ + pattern$) + END + + DEF PROClistdir(afsp$) + LOCAL dir%, sh%, res% + DIM dir% LOCAL 317 + SYS "FindFirstFile", afsp$, dir% TO sh% + IF sh% <> -1 THEN + REPEAT + PRINT $$(dir%+44) + SYS "FindNextFile", sh%, dir% TO res% + UNTIL res% = 0 + SYS "FindClose", sh% + ENDIF + ENDPROC diff --git a/Task/Walk-a-directory-Non-recursively/C++/walk-a-directory-non-recursively.cpp b/Task/Walk-a-directory-Non-recursively/C++/walk-a-directory-non-recursively.cpp new file mode 100644 index 0000000000..bf45303c73 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/C++/walk-a-directory-non-recursively.cpp @@ -0,0 +1,23 @@ +#include "boost/filesystem.hpp" +#include "boost/regex.hpp" +#include + +using namespace boost::filesystem; + +int main() +{ + path current_dir("."); + // list all files starting with a + boost::regex pattern("a.*"); + for (directory_iterator iter(current_dir), end; + iter != end; + ++iter) + { + boost::smatch match; + std::string fn = iter->path().filename().string(); // must make local variable + if (boost::regex_match( fn, match, pattern)) + { + std::cout << match[0] << "\n"; + } + } +} diff --git a/Task/Walk-a-directory-Non-recursively/C/walk-a-directory-non-recursively.c b/Task/Walk-a-directory-Non-recursively/C/walk-a-directory-non-recursively.c new file mode 100644 index 0000000000..69fd1ef545 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/C/walk-a-directory-non-recursively.c @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +enum { + WALK_OK = 0, + WALK_BADPATTERN, + WALK_BADOPEN, +}; + +int walker(const char *dir, const char *pattern) +{ + struct dirent *entry; + regex_t reg; + DIR *d; + + if (regcomp(®, pattern, REG_EXTENDED | REG_NOSUB)) + return WALK_BADPATTERN; + if (!(d = opendir(dir))) + return WALK_BADOPEN; + while (entry = readdir(d)) + if (!regexec(®, entry->d_name, 0, NULL, 0)) + puts(entry->d_name); + closedir(d); + regfree(®); + return WALK_OK; +} + +int main() +{ + walker(".", ".\\.c$"); + return 0; +} diff --git a/Task/Walk-a-directory-Non-recursively/ColdFusion/walk-a-directory-non-recursively.cfm b/Task/Walk-a-directory-Non-recursively/ColdFusion/walk-a-directory-non-recursively.cfm new file mode 100644 index 0000000000..a80b68d1c0 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/ColdFusion/walk-a-directory-non-recursively.cfm @@ -0,0 +1,4 @@ + + + #dirListing.name# (#dirListing.type#)
+
diff --git a/Task/Walk-a-directory-Non-recursively/Common-Lisp/walk-a-directory-non-recursively.lisp b/Task/Walk-a-directory-Non-recursively/Common-Lisp/walk-a-directory-non-recursively.lisp new file mode 100644 index 0000000000..978079dad7 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Common-Lisp/walk-a-directory-non-recursively.lisp @@ -0,0 +1,2 @@ +(defun walk-directory (directory pattern) + (directory (merge-pathnames pattern directory))) diff --git a/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d b/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d new file mode 100644 index 0000000000..b1fbd30b76 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/D/walk-a-directory-non-recursively.d @@ -0,0 +1,16 @@ +import std.stdio; +import std.file; +import std.path; + +void main(string[] args) { + auto path = args.length > 1 ? args[1] : "." ; // default current + auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file + + bool matchNPrint(DirEntry* de){ + if(!de.isdir && fnmatch(de.name, pattern)) + writefln(de.name) ; + return true ; // continue + } + + listdir(path, &matchNPrint) ; +} diff --git a/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-1.e b/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-1.e new file mode 100644 index 0000000000..2f905075a0 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-1.e @@ -0,0 +1,5 @@ +def walkDirectory(directory, pattern) { + for name => file ? (name =~ rx`.*$pattern.*`) in directory { + println(name) + } +} diff --git a/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-2.e b/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-2.e new file mode 100644 index 0000000000..53bf4511ec --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/E/walk-a-directory-non-recursively-2.e @@ -0,0 +1,4 @@ +? walkDirectory(, "bash_") +.bash_history +.bash_profile +.bash_profile~ diff --git a/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.l b/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.l new file mode 100644 index 0000000000..4051a4f5ba --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.l @@ -0,0 +1,6 @@ +(directory-files "/some/dir/name" + nil ;; just the filenames, not full paths + "\\.c\\'" ;; regexp + t) ;; don't sort the filenames +=> +("foo.c" "bar.c" ...) diff --git a/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.euphoria b/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.euphoria new file mode 100644 index 0000000000..ddaf437fc9 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.euphoria @@ -0,0 +1,12 @@ +include file.e + +procedure show(sequence pattern) + sequence f + f = dir(pattern) + for i = 1 to length(f) do + puts(1,f[i][D_NAME]) + puts(1,'\n') + end for +end procedure + +show("*.*") diff --git a/Task/Walk-a-directory-Non-recursively/Factor/walk-a-directory-non-recursively.factor b/Task/Walk-a-directory-Non-recursively/Factor/walk-a-directory-non-recursively.factor new file mode 100644 index 0000000000..53ab9993b5 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Factor/walk-a-directory-non-recursively.factor @@ -0,0 +1,6 @@ +USING: globs io io.directories kernel regexp sequences ; +IN: walk-directory-non-recursively + +: print-files ( path pattern -- ) + [ directory-files ] [ ] bi* [ matches? ] curry filter + [ print ] each ; diff --git a/Task/Walk-a-directory-Non-recursively/Forth/walk-a-directory-non-recursively.fth b/Task/Walk-a-directory-Non-recursively/Forth/walk-a-directory-non-recursively.fth new file mode 100644 index 0000000000..e7a97d9296 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Forth/walk-a-directory-non-recursively.fth @@ -0,0 +1,25 @@ +defer ls-filter ( name len -- ? ) +: ls-all 2drop true ; +: ls-visible drop c@ [char] . <> ; + +: ls ( dir len -- ) + open-dir throw ( dirid ) + begin + dup pad 256 rot read-dir throw + while + pad over ls-filter if + cr pad swap type + else drop then + repeat + drop close-dir throw ; + +\ only show C language source and header files (*.c *.h) +: c-file? ( str len -- ? ) + dup 3 < if 2drop false exit then + + 1- dup c@ + dup [char] c <> swap [char] h <> and if drop false exit then + 1- dup c@ [char] . <> if drop false exit then + drop true ; +' c-file? is ls-filter + +s" ." ls diff --git a/Task/Walk-a-directory-Non-recursively/Go/walk-a-directory-non-recursively.go b/Task/Walk-a-directory-Non-recursively/Go/walk-a-directory-non-recursively.go new file mode 100644 index 0000000000..759bf7ff30 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Go/walk-a-directory-non-recursively.go @@ -0,0 +1,10 @@ +package main + +import ( + "fmt" + "path/filepath" +) + +func main() { + fmt.Println(filepath.Glob("*.go")) +} diff --git a/Task/Walk-a-directory-Non-recursively/Groovy/walk-a-directory-non-recursively.groovy b/Task/Walk-a-directory-Non-recursively/Groovy/walk-a-directory-non-recursively.groovy new file mode 100644 index 0000000000..71ffd2139e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Groovy/walk-a-directory-non-recursively.groovy @@ -0,0 +1,9 @@ +// *** print *.txt files in current directory + new File('.').eachFileMatch(~/.*\.txt/) { + println it + } + + // *** print *.txt files in /foo/bar + new File('/foo/bar').eachFileMatch(~/.*\.txt/) { + println it + } diff --git a/Task/Walk-a-directory-Non-recursively/Haskell/walk-a-directory-non-recursively.hs b/Task/Walk-a-directory-Non-recursively/Haskell/walk-a-directory-non-recursively.hs new file mode 100644 index 0000000000..22daf18cf9 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Haskell/walk-a-directory-non-recursively.hs @@ -0,0 +1,10 @@ +import System.Directory +import Text.Regex +import Data.Maybe + +walk :: FilePath -> String -> IO () +walk dir pattern = do + filenames <- getDirectoryContents dir + mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames + +main = walk "." ".\\.hs$" diff --git a/Task/Walk-a-directory-Non-recursively/HicEst/walk-a-directory-non-recursively.hicest b/Task/Walk-a-directory-Non-recursively/HicEst/walk-a-directory-non-recursively.hicest new file mode 100644 index 0000000000..052b436b35 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/HicEst/walk-a-directory-non-recursively.hicest @@ -0,0 +1,10 @@ +CHARACTER dirtxt='dir.txt', filename*80 + +SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess +OPEN(FIle=dirtxt, Format='"",', LENgth=files) ! parses column 1 ("file names") + +DO nr = 1, files + filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename + ! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128: + IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename +ENDDO diff --git a/Task/Walk-a-directory-Non-recursively/IDL/walk-a-directory-non-recursively.idl b/Task/Walk-a-directory-Non-recursively/IDL/walk-a-directory-non-recursively.idl new file mode 100644 index 0000000000..49a4790fc6 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/IDL/walk-a-directory-non-recursively.idl @@ -0,0 +1,2 @@ +f = file_search('*.txt', count=cc) +if cc gt 0 then print,f diff --git a/Task/Walk-a-directory-Non-recursively/Icon/walk-a-directory-non-recursively.icon b/Task/Walk-a-directory-Non-recursively/Icon/walk-a-directory-non-recursively.icon new file mode 100644 index 0000000000..56de2908c8 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Icon/walk-a-directory-non-recursively.icon @@ -0,0 +1,14 @@ +procedure main() +every write(getdirs(".","icn")) # writes out all directories from the current directory down +end + +procedure getdirs(s,pat) #: return a list of directories beneath the directory 's' +local d,f + +if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { + while f := read(d) do + if find(pat,f) then + suspend f + close(d) + } +end diff --git a/Task/Walk-a-directory-Non-recursively/J/walk-a-directory-non-recursively.j b/Task/Walk-a-directory-Non-recursively/J/walk-a-directory-non-recursively.j new file mode 100644 index 0000000000..8326e597b6 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/J/walk-a-directory-non-recursively.j @@ -0,0 +1,3 @@ +require 'dir' +0 dir '*.png' +0 dir '/mydir/*.txt' diff --git a/Task/Walk-a-directory-Non-recursively/Java/walk-a-directory-non-recursively.java b/Task/Walk-a-directory-Non-recursively/Java/walk-a-directory-non-recursively.java new file mode 100644 index 0000000000..81ae448b5e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Java/walk-a-directory-non-recursively.java @@ -0,0 +1,6 @@ +File dir = new File("/foo/bar"); + +String[] contents = dir.list(); +for (String file : contents) + if (file.endsWith(".mp3")) + System.out.println(file); diff --git a/Task/Walk-a-directory-Non-recursively/JavaScript/walk-a-directory-non-recursively.js b/Task/Walk-a-directory-Non-recursively/JavaScript/walk-a-directory-non-recursively.js new file mode 100644 index 0000000000..54075cb41b --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/JavaScript/walk-a-directory-non-recursively.js @@ -0,0 +1,22 @@ +var fso = new ActiveXObject("Scripting.FileSystemObject"); +var dir = fso.GetFolder('test_folder'); + +function walkDirectory(dir, re_pattern) { + WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':"); + walkDirectoryFilter(dir.Files, re_pattern); + + WScript.Echo("Folders in " + dir.name + " matching '" + re_pattern +"':"); + walkDirectoryFilter(dir.Subfolders, re_pattern); +} + +function walkDirectoryFilter(items, re_pattern) { + var e = new Enumerator(items); + while (! e.atEnd()) { + var item = e.item(); + if (item.name.match(re_pattern)) + WScript.Echo(item.name); + e.moveNext(); + } +} + +walkDirectory(dir, '\\.txt$'); diff --git a/Task/Walk-a-directory-Non-recursively/Lua/walk-a-directory-non-recursively.lua b/Task/Walk-a-directory-Non-recursively/Lua/walk-a-directory-non-recursively.lua new file mode 100644 index 0000000000..fc93ef496d --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Lua/walk-a-directory-non-recursively.lua @@ -0,0 +1,7 @@ +require "lfs" +directorypath = "." -- current working directory +for filename in lfs.dir(directorypath) do + if filename:match("%.lua$") then -- "%." is an escaped ".", "$" is end of string + print(filename) + end +end diff --git a/Task/Walk-a-directory-Non-recursively/MAXScript/walk-a-directory-non-recursively.maxscript b/Task/Walk-a-directory-Non-recursively/MAXScript/walk-a-directory-non-recursively.maxscript new file mode 100644 index 0000000000..88ea3bc205 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/MAXScript/walk-a-directory-non-recursively.maxscript @@ -0,0 +1 @@ +getFiles "C:\\*.txt" diff --git a/Task/Walk-a-directory-Non-recursively/Mathematica/walk-a-directory-non-recursively.math b/Task/Walk-a-directory-Non-recursively/Mathematica/walk-a-directory-non-recursively.math new file mode 100644 index 0000000000..c7dc703450 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Mathematica/walk-a-directory-non-recursively.math @@ -0,0 +1,2 @@ +FileNames["*"] +FileNames["*.png", $RootDirectory] diff --git a/Task/Walk-a-directory-Non-recursively/OCaml/walk-a-directory-non-recursively.ocaml b/Task/Walk-a-directory-Non-recursively/OCaml/walk-a-directory-non-recursively.ocaml new file mode 100644 index 0000000000..bcd6a90601 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/OCaml/walk-a-directory-non-recursively.ocaml @@ -0,0 +1,4 @@ +#load "str.cma" +let contents = Array.to_list (Sys.readdir ".") in +let select pat str = Str.string_match (Str.regexp pat) str 0 in +List.filter (select ".*\\.jpg") contents diff --git a/Task/Walk-a-directory-Non-recursively/Objeck/walk-a-directory-non-recursively.objeck b/Task/Walk-a-directory-Non-recursively/Objeck/walk-a-directory-non-recursively.objeck new file mode 100644 index 0000000000..3866fd2044 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Objeck/walk-a-directory-non-recursively.objeck @@ -0,0 +1,14 @@ +use IO; + +bundle Default { + class Test { + function : Main(args : System.String[]) ~ Nil { + dir := Directory->List("/src/code"); + for(i := 0; i < dir->Size(); i += 1;) { + if(dir[i]->EndsWith(".obs")) { + dir[i]->PrintLine(); + }; + }; + } + } +} diff --git a/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m b/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m new file mode 100644 index 0000000000..f6296edf3e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Objective-C/walk-a-directory-non-recursively.m @@ -0,0 +1,12 @@ +NSString *dir = @"/foo/bar"; + +// Pre-OS X 10.5 +NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; +// OS X 10.5+ +NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL]; + +NSEnumerator *enm = [contents objectEnumerator]; +NSString *file; +while ((file = [enm nextObject])) + if ([[file pathExtension] isEqualToString:@"mp3"]) + NSLog(@"%@", file); diff --git a/Task/Walk-a-directory-Non-recursively/Oz/walk-a-directory-non-recursively.oz b/Task/Walk-a-directory-Non-recursively/Oz/walk-a-directory-non-recursively.oz new file mode 100644 index 0000000000..ed8e5eb75e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Oz/walk-a-directory-non-recursively.oz @@ -0,0 +1,9 @@ +declare + [Path] = {Module.link ['x-oz://system/os/Path.ozf']} + [Regex] = {Module.link ['x-oz://contrib/regex']} + + Files = {Filter {Path.readdir "."} Path.isFile} + Pattern = ".*\\.oz$" + MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} +in + {ForAll MatchingFiles System.showInfo} diff --git a/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-1.php b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-1.php new file mode 100644 index 0000000000..ed1b79e594 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-1.php @@ -0,0 +1,13 @@ +$pattern = 'php'; +$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux +while (false !== ($file = readdir($dh))) +{ + if ($file != '.' and $file != '..') + { + if (preg_match("/$pattern/", $file)) + { + echo "$file matches $pattern\n"; + } + } +} +closedir($dh); diff --git a/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-2.php b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-2.php new file mode 100644 index 0000000000..74651c64b1 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-2.php @@ -0,0 +1,11 @@ +$pattern = 'php'; +foreach (scandir('/home/foo/bar') as $file) +{ + if ($file != '.' and $file != '..') + { + if (preg_match("/$pattern/", $file)) + { + echo "$file matches $pattern\n"; + } + } +} diff --git a/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-3.php b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-3.php new file mode 100644 index 0000000000..49008da984 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PHP/walk-a-directory-non-recursively-3.php @@ -0,0 +1,3 @@ +foreach (glob('/home/foo/bar/*.php') as $file){ + echo "$file\n"; +} diff --git a/Task/Walk-a-directory-Non-recursively/Pascal/walk-a-directory-non-recursively.pascal b/Task/Walk-a-directory-Non-recursively/Pascal/walk-a-directory-non-recursively.pascal new file mode 100644 index 0000000000..ceb9abb4ae --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Pascal/walk-a-directory-non-recursively.pascal @@ -0,0 +1,31 @@ +{$H+} + +program Walk; + +uses SysUtils; + +var Res: TSearchRec; + Pattern, Path, Name: String; + FileAttr: LongInt; + Attr: Integer; + +begin + Write('File pattern: '); + ReadLn(Pattern); { For example .\*.pas } + + Attr := faAnyFile; + if FindFirst(Pattern, Attr, Res) = 0 then + begin + Path := ExtractFileDir(Pattern); + repeat + Name := ConcatPaths([Path, Res.Name]); + FileAttr := FileGetAttr(Name); + if FileAttr and faDirectory = 0 then + begin + { Do something with file name } + WriteLn(Name); + end + until FindNext(Res) <> 0; + end; + FindClose(Res); +end. diff --git a/Task/Walk-a-directory-Non-recursively/Perl-6/walk-a-directory-non-recursively.pl6 b/Task/Walk-a-directory-Non-recursively/Perl-6/walk-a-directory-non-recursively.pl6 new file mode 100644 index 0000000000..0e19598c8b --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Perl-6/walk-a-directory-non-recursively.pl6 @@ -0,0 +1 @@ +.say for dir(".", :test(/foo/)) diff --git a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl new file mode 100644 index 0000000000..0fc4f27922 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-1.pl @@ -0,0 +1,5 @@ +use 5.010; +my $pattern = qr{ \A a }xmso; # match files whose first character is 'a' +opendir my $dh, 'the_directory'; +say for grep { $pattern } readdir $dh; +closedir $dh; diff --git a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-2.pl b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-2.pl new file mode 100644 index 0000000000..7163b8dc6f --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-2.pl @@ -0,0 +1 @@ +use 5.010; say while ; diff --git a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-3.pl b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-3.pl new file mode 100644 index 0000000000..1f85d81f1c --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-3.pl @@ -0,0 +1 @@ +my @filenames = glob('/home/foo/bar/*.php'); diff --git a/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-4.pl b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-4.pl new file mode 100644 index 0000000000..25369f4eac --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Perl/walk-a-directory-non-recursively-4.pl @@ -0,0 +1,2 @@ +my $pattern = '*.c'; +my @filenames = glob($pattern); diff --git a/Task/Walk-a-directory-Non-recursively/PicoLisp/walk-a-directory-non-recursively.l b/Task/Walk-a-directory-Non-recursively/PicoLisp/walk-a-directory-non-recursively.l new file mode 100644 index 0000000000..1db1f06e0f --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PicoLisp/walk-a-directory-non-recursively.l @@ -0,0 +1,3 @@ +(for F (dir "@src/") # Iterate directory + (when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'? + (println F) ) ) # Yes: Print it diff --git a/Task/Walk-a-directory-Non-recursively/Pike/walk-a-directory-non-recursively.pike b/Task/Walk-a-directory-Non-recursively/Pike/walk-a-directory-non-recursively.pike new file mode 100644 index 0000000000..1d9fc7a350 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Pike/walk-a-directory-non-recursively.pike @@ -0,0 +1,3 @@ +array(string) files = get_dir("/home/foo/bar"); +foreach(files, string file) + write(file + "\n"); diff --git a/Task/Walk-a-directory-Non-recursively/Pop11/walk-a-directory-non-recursively.pop11 b/Task/Walk-a-directory-Non-recursively/Pop11/walk-a-directory-non-recursively.pop11 new file mode 100644 index 0000000000..b64f750bf6 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Pop11/walk-a-directory-non-recursively.pop11 @@ -0,0 +1,8 @@ +lvars repp, fil; +;;; create path repeater +sys_file_match('*.p', '', false, 0) -> repp; +;;; iterate over files +while (repp() ->> fil) /= termin do + ;;; print the file + printf(fil, '%s\n'); +endwhile; diff --git a/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.psh b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.psh new file mode 100644 index 0000000000..5379f1124a --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.psh @@ -0,0 +1,2 @@ +Get-ChildItem *.txt -Name +Get-ChildItem f* -Name diff --git a/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.psh b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.psh new file mode 100644 index 0000000000..e12b551711 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.psh @@ -0,0 +1 @@ +Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' } diff --git a/Task/Walk-a-directory-Non-recursively/PureBasic/walk-a-directory-non-recursively.purebasic b/Task/Walk-a-directory-Non-recursively/PureBasic/walk-a-directory-non-recursively.purebasic new file mode 100644 index 0000000000..4db0e9885d --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PureBasic/walk-a-directory-non-recursively.purebasic @@ -0,0 +1,19 @@ +Procedure walkDirectory(directory.s = "", pattern.s = "") + Protected directoryID + + directoryID = ExamineDirectory(#PB_Any,directory,pattern) + If directoryID + While NextDirectoryEntry(directoryID) + PrintN(DirectoryEntryName(directoryID)) + Wend + FinishDirectory(directoryID) + EndIf +EndProcedure + +If OpenConsole() + walkDirectory() + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-1.py b/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-1.py new file mode 100644 index 0000000000..9cc4baef6e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-1.py @@ -0,0 +1,3 @@ +import glob +for filename in glob.glob('/foo/bar/*.mp3'): + print filename diff --git a/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-2.py b/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-2.py new file mode 100644 index 0000000000..72501f62cc --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Python/walk-a-directory-non-recursively-2.py @@ -0,0 +1,4 @@ +import os +for filename in os.listdir('/foo/bar'): + if filename.endswith('.mp3'): + print filename diff --git a/Task/Walk-a-directory-Non-recursively/R/walk-a-directory-non-recursively.r b/Task/Walk-a-directory-Non-recursively/R/walk-a-directory-non-recursively.r new file mode 100644 index 0000000000..21919f5ca3 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/R/walk-a-directory-non-recursively.r @@ -0,0 +1 @@ +dir("/foo/bar", "mp3") diff --git a/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal b/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal new file mode 100644 index 0000000000..83a15892f5 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal @@ -0,0 +1,5 @@ +import IO; +public void Walk(loc a, str pattern){ + for (entry <- listEntries(a)) + endsWith(entry, pattern) ? println(entry); +} diff --git a/Task/Walk-a-directory-Non-recursively/Raven/walk-a-directory-non-recursively.raven b/Task/Walk-a-directory-Non-recursively/Raven/walk-a-directory-non-recursively.raven new file mode 100644 index 0000000000..4c8c640199 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Raven/walk-a-directory-non-recursively.raven @@ -0,0 +1,2 @@ +'dir://.' open each as item + item m/\.txt$/ if "%(item)s\n" print diff --git a/Task/Walk-a-directory-Non-recursively/Ruby/walk-a-directory-non-recursively.rb b/Task/Walk-a-directory-Non-recursively/Ruby/walk-a-directory-non-recursively.rb new file mode 100644 index 0000000000..b680b3e949 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Ruby/walk-a-directory-non-recursively.rb @@ -0,0 +1,12 @@ +# Files under this directory: +Dir.glob('*') { |file| puts file } + +# Files under path '/foo/bar': +Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file } + +# As a method +def file_match(pattern=/\.txt/, path='.') + Dir[File.join(path,'*')].each do |file| + puts file if file =~ pattern + end +end diff --git a/Task/Walk-a-directory-Non-recursively/Scala/walk-a-directory-non-recursively.scala b/Task/Walk-a-directory-Non-recursively/Scala/walk-a-directory-non-recursively.scala new file mode 100644 index 0000000000..d05948aace --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Scala/walk-a-directory-non-recursively.scala @@ -0,0 +1,4 @@ +import java.io.File + +val dir = new File("/foo/bar").list() +dir.filter(file => file.endsWith(".mp3")).foreach(println) diff --git a/Task/Walk-a-directory-Non-recursively/Seed7/walk-a-directory-non-recursively.seed7 b/Task/Walk-a-directory-Non-recursively/Seed7/walk-a-directory-non-recursively.seed7 new file mode 100644 index 0000000000..aa25d6440f --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Seed7/walk-a-directory-non-recursively.seed7 @@ -0,0 +1,13 @@ +$ include "seed7_05.s7i"; + include "osfiles.s7i"; + +const proc: main is func + local + var string: fileName is ""; + begin + for fileName range readDir(".") do + if endsWith(fileName, ".sd7") then + writeln(fileName); + end if; + end for; + end func; diff --git a/Task/Walk-a-directory-Non-recursively/Smalltalk/walk-a-directory-non-recursively.st b/Task/Walk-a-directory-Non-recursively/Smalltalk/walk-a-directory-non-recursively.st new file mode 100644 index 0000000000..9d0b20d672 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Smalltalk/walk-a-directory-non-recursively.st @@ -0,0 +1,2 @@ +(Directory name: 'a_directory') + allFilesMatching: '*.st' do: [ :f | (f name) displayNl ] diff --git a/Task/Walk-a-directory-Non-recursively/TUSCRIPT/walk-a-directory-non-recursively.tuscript b/Task/Walk-a-directory-Non-recursively/TUSCRIPT/walk-a-directory-non-recursively.tuscript new file mode 100644 index 0000000000..78d788b232 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/TUSCRIPT/walk-a-directory-non-recursively.tuscript @@ -0,0 +1,4 @@ +$$ MODE TUSCRIPT +files=FILE_NAMES (+,-std-) +fileswtxt= FILTER_INDEX (files,":*.txt:",-) +txtfiles= SELECT (files,#fileswtxt) diff --git a/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-1.tcl b/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-1.tcl new file mode 100644 index 0000000000..f93685fead --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-1.tcl @@ -0,0 +1,3 @@ +foreach filename [glob *.txt] { + puts $filename +} diff --git a/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-2.tcl b/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-2.tcl new file mode 100644 index 0000000000..fe9e1789c8 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Tcl/walk-a-directory-non-recursively-2.tcl @@ -0,0 +1,6 @@ +set dir /foo/bar +foreach filename [glob -directory $dir *.txt] { + puts $filename + ### Or, if you only want the local filename part... + # puts [file tail $filename] +} diff --git a/Task/Walk-a-directory-Non-recursively/Toka/walk-a-directory-non-recursively.toka b/Task/Walk-a-directory-Non-recursively/Toka/walk-a-directory-non-recursively.toka new file mode 100644 index 0000000000..3a869b8c65 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Toka/walk-a-directory-non-recursively.toka @@ -0,0 +1,2 @@ +needs shell +" ." " .\\.txt$" dir.listByPattern diff --git a/Task/Walk-a-directory-Non-recursively/UNIX-Shell/walk-a-directory-non-recursively.sh b/Task/Walk-a-directory-Non-recursively/UNIX-Shell/walk-a-directory-non-recursively.sh new file mode 100644 index 0000000000..6d0d145eff --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/UNIX-Shell/walk-a-directory-non-recursively.sh @@ -0,0 +1,2 @@ +ls -d *.c # *.c files in current directory +(cd mydir && ls -d *.c) # *.c files in mydir diff --git a/Task/Walk-a-directory-Non-recursively/UnixPipes/walk-a-directory-non-recursively.unixpipes b/Task/Walk-a-directory-Non-recursively/UnixPipes/walk-a-directory-non-recursively.unixpipes new file mode 100644 index 0000000000..958eb3e74e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/UnixPipes/walk-a-directory-non-recursively.unixpipes @@ -0,0 +1 @@ +ls | grep '\.c$' diff --git a/Task/Walk-a-directory-Non-recursively/Visual-Basic-.NET/walk-a-directory-non-recursively.visual b/Task/Walk-a-directory-Non-recursively/Visual-Basic-.NET/walk-a-directory-non-recursively.visual new file mode 100644 index 0000000000..a28079f5ac --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Visual-Basic-.NET/walk-a-directory-non-recursively.visual @@ -0,0 +1,14 @@ +'Using the OS pattern matching +For Each file In IO.Directory.GetFiles("\temp", "*.txt") + Console.WriteLine(file) +Next + +'Using VB's pattern matching and LINQ +For Each file In (From name In IO.Directory.GetFiles("\temp") Where name Like "*.txt") + Console.WriteLine(file) +Next + +'Using VB's pattern matching and dot-notation +For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt") + Console.WriteLine(file) +Next diff --git a/Task/Walk-a-directory-Recursively/0DESCRIPTION b/Task/Walk-a-directory-Recursively/0DESCRIPTION new file mode 100644 index 0000000000..ea4158d255 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/0DESCRIPTION @@ -0,0 +1,5 @@ +Walk a given directory ''tree'' and print files matching a given pattern. + +'''Note:''' This task is for recursive methods. These tasks should read an entire directory tree, not a ''single directory''. For code examples that read a ''single directory'', see [[Walk a directory/Non-recursively]]. + +'''Note:''' Please be careful when running any code examples found here. diff --git a/Task/Walk-a-directory-Recursively/1META.yaml b/Task/Walk-a-directory-Recursively/1META.yaml new file mode 100644 index 0000000000..1169d9a893 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Recursion +note: File System Operations diff --git a/Task/Walk-a-directory-Recursively/ALGOL-68/walk-a-directory-recursively.alg b/Task/Walk-a-directory-Recursively/ALGOL-68/walk-a-directory-recursively.alg new file mode 100644 index 0000000000..f279b021d6 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/ALGOL-68/walk-a-directory-recursively.alg @@ -0,0 +1,27 @@ +INT match=0, no match=1, out of memory error=2, other error=3; + +STRING slash = "/", pwd=".", parent=".."; + +PROC walk tree = (STRING path, PROC (STRING)VOID call back)VOID: ( + []STRING files = get directory(path); + FOR file index TO UPB files DO + STRING file = files[file index]; + STRING path file = path+slash+file; + IF file is directory(path file) THEN + IF file NE pwd AND file NE parent THEN + walk tree(path file, call back) + FI + ELSE + call back(path file) + FI + OD +); + +STRING re sort a68 = "[Ss]ort[^/]*[.]a68$"; + +PROC match sort a68 and print = (STRING path file)VOID: + IF grep in string(re sort a68, path file, NIL, NIL) = match THEN + print((path file, new line)) + FI; + +walk tree(".", match sort a68 and print) diff --git a/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.ada b/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.ada new file mode 100644 index 0000000000..f866c6c9c4 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.ada @@ -0,0 +1,24 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; + +procedure Test_Directory_Walk is + procedure Walk (Name : String; Pattern : String) is + procedure Print (Item : Directory_Entry_Type) is + begin + Ada.Text_IO.Put_Line (Full_Name (Item)); + end Print; + procedure Walk (Item : Directory_Entry_Type) is + begin + if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then + Walk (Full_Name (Item), Pattern); + end if; + exception + when Name_Error => null; + end Walk; + begin + Search (Name, Pattern, (others => True), Print'Access); + Search (Name, "", (Directory => True, others => False), Walk'Access); + end Walk; +begin + Walk (".", "*.adb"); +end Test_Directory_Walk; diff --git a/Task/Walk-a-directory-Recursively/AutoHotkey/walk-a-directory-recursively.ahk b/Task/Walk-a-directory-Recursively/AutoHotkey/walk-a-directory-recursively.ahk new file mode 100644 index 0000000000..9e402c0cfa --- /dev/null +++ b/Task/Walk-a-directory-Recursively/AutoHotkey/walk-a-directory-recursively.ahk @@ -0,0 +1,3 @@ +Loop, %A_Temp%\*.tmp,,1 + out .= A_LoopFileName "`n" +MsgBox,% out diff --git a/Task/Walk-a-directory-Recursively/BBC-BASIC/walk-a-directory-recursively.bbc b/Task/Walk-a-directory-Recursively/BBC-BASIC/walk-a-directory-recursively.bbc new file mode 100644 index 0000000000..ba68e484c4 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/BBC-BASIC/walk-a-directory-recursively.bbc @@ -0,0 +1,28 @@ + directory$ = "C:\Windows\" + pattern$ = "*.chm" + PROClisttree(directory$, pattern$) + END + + DEF PROClisttree(dir$, filter$) + LOCAL dir%, sh%, res% + DIM dir% LOCAL 317 + IF RIGHT$(dir$) <> "\" IF RIGHT$(dir$) <> "/" dir$ += "\" + SYS "FindFirstFile", dir$ + filter$, dir% TO sh% + IF sh% <> -1 THEN + REPEAT + IF (!dir% AND 16) = 0 PRINT dir$ + $$(dir%+44) + SYS "FindNextFile", sh%, dir% TO res% + UNTIL res% = 0 + SYS "FindClose", sh% + ENDIF + SYS "FindFirstFile", dir$ + "*", dir% TO sh% + IF sh% <> -1 THEN + REPEAT + IF (!dir% AND 16) IF dir%?44 <> &2E THEN + PROClisttree(dir$ + $$(dir%+44) + "\", filter$) + ENDIF + SYS "FindNextFile", sh%, dir% TO res% + UNTIL res% = 0 + SYS "FindClose", sh% + ENDIF + ENDPROC diff --git a/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat new file mode 100644 index 0000000000..2bc84f47fc --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat @@ -0,0 +1 @@ +dir /a-d %1 diff --git a/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-2.bat b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-2.bat new file mode 100644 index 0000000000..799a81ea2b --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-2.bat @@ -0,0 +1 @@ +FOR /R C:\Windows\System32 %%F IN (*.DLL) DO ECHO "%%F" diff --git a/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-3.bat b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-3.bat new file mode 100644 index 0000000000..3caab35ee0 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-3.bat @@ -0,0 +1 @@ +FOR /R C:\Windows\System32 %F IN (*.DLL) DO ECHO "%F" diff --git a/Task/Walk-a-directory-Recursively/C++/walk-a-directory-recursively.cpp b/Task/Walk-a-directory-Recursively/C++/walk-a-directory-recursively.cpp new file mode 100644 index 0000000000..cc016a00be --- /dev/null +++ b/Task/Walk-a-directory-Recursively/C++/walk-a-directory-recursively.cpp @@ -0,0 +1,19 @@ +#include "boost/filesystem.hpp" +#include "boost/regex.hpp" +#include + +using namespace boost::filesystem; + +int main() +{ + path current_dir("."); // + boost::regex pattern("a.*"); // list all files starting with a + for (recursive_directory_iterator iter(current_dir), end; + iter != end; + ++iter) + { + std::string name = iter->path().leaf(); + if (regex_match(name, pattern)) + std::cout << iter->path() << "\n"; + } +} diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c new file mode 100644 index 0000000000..1b7a904885 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { + WALK_OK = 0, + WALK_BADPATTERN, + WALK_NAMETOOLONG, + WALK_BADIO, +}; + +#define WS_NONE 0 +#define WS_RECURSIVE (1 << 0) +#define WS_DEFAULT WS_RECURSIVE +#define WS_FOLLOWLINK (1 << 1) /* follow symlinks */ +#define WS_DOTFILES (1 << 2) /* per unix convention, .file is hidden */ +#define WS_MATCHDIRS (1 << 3) /* if pattern is used on dir names too */ + +int walk_recur(char *dname, regex_t *reg, int spec) +{ + struct dirent *dent; + DIR *dir; + struct stat st; + char fn[FILENAME_MAX]; + int res = WALK_OK; + int len = strlen(dname); + if (len >= FILENAME_MAX - 1) + return WALK_NAMETOOLONG; + + strcpy(fn, dname); + fn[len++] = '/'; + + if (!(dir = opendir(dname))) { + warn("can't open %s", dname); + return WALK_BADIO; + } + + errno = 0; + while ((dent = readdir(dir))) { + if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') + continue; + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + continue; + + strncpy(fn + len, dent->d_name, FILENAME_MAX - len); + if (lstat(fn, &st) == -1) { + warn("Can't stat %s", fn); + res = WALK_BADIO; + continue; + } + + /* don't follow symlink unless told so */ + if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) + continue; + + /* will be false for symlinked dirs */ + if (S_ISDIR(st.st_mode)) { + /* recursively follow dirs */ + if ((spec & WS_RECURSIVE)) + walk_recur(fn, reg, spec); + + if (!(spec & WS_MATCHDIRS)) continue; + } + + /* pattern match */ + if (!regexec(reg, fn, 0, 0, 0)) puts(fn); + } + + if (dir) closedir(dir); + return res ? res : errno ? WALK_BADIO : WALK_OK; +} + +int walk_dir(char *dname, char *pattern, int spec) +{ + regex_t r; + int res; + if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) + return WALK_BADPATTERN; + res = walk_recur(dname, &r, spec); + regfree(&r); + + return res; +} + +int main() +{ + int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); + switch(r) { + case WALK_OK: break; + case WALK_BADIO: err(1, "IO error"); + case WALK_BADPATTERN: err(1, "Bad pattern"); + case WALK_NAMETOOLONG: err(1, "Filename too long"); + default: + err(1, "Unknown error?"); + } + return 0; +} diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c new file mode 100644 index 0000000000..986febb68a --- /dev/null +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include +#include +#include + +/* Compare files by name. */ +int +entcmp(const FTSENT **a, const FTSENT **b) +{ + return strcmp((*a)->fts_name, (*b)->fts_name); +} + +/* + * Print all files in the directory tree that match the glob pattern. + * Example: pmatch("/usr/src", "*.c"); + */ +void +pmatch(char *dir, const char *pattern) +{ + FTS *tree; + FTSENT *f; + char *argv[] = { dir, NULL }; + + /* + * FTS_LOGICAL follows symbolic links, including links to other + * directories. It detects cycles, so we never have an infinite + * loop. FTS_NOSTAT is because we never use f->statp. It uses + * our entcmp() to sort files by name. + */ + tree = fts_open(argv, FTS_LOGICAL | FTS_NOSTAT, entcmp); + if (tree == NULL) + err(1, "fts_open"); + + /* + * Iterate files in tree. This iteration always skips + * "." and ".." because we never use FTS_SEEDOT. + */ + while ((f = fts_read(tree))) { + switch (f->fts_info) { + case FTS_DNR: /* Cannot read directory */ + case FTS_ERR: /* Miscellaneous error */ + case FTS_NS: /* stat() error */ + /* Show error, then continue to next files. */ + warn("%s", f->fts_path); + continue; + case FTS_DP: + /* Ignore post-order visit to directory. */ + continue; + } + + /* + * Check if name matches pattern. If so, then print + * path. This check uses FNM_PERIOD, so "*.c" will not + * match ".invisible.c". + */ + if (fnmatch(pattern, f->fts_name, FNM_PERIOD) == 0) + puts(f->fts_path); + + /* + * A cycle happens when a symbolic link (or perhaps a + * hard link) puts a directory inside itself. Tell user + * when this happens. + */ + if (f->fts_info == FTS_DC) + warnx("%s: cycle in directory tree", f->fts_path); + } + + /* fts_read() sets errno = 0 unless it has error. */ + if (errno != 0) + err(1, "fts_read"); + + if (fts_close(tree) < 0) + err(1, "fts_close"); +} + +int +main() +{ + pmatch(".", "*.c"); + return 0; +} diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c new file mode 100644 index 0000000000..5bd6c16362 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c @@ -0,0 +1,238 @@ +#include +#include +#include +#include + +/* Print "message: last Win32 error" to stderr. */ +void +oops(const wchar_t *message) +{ + wchar_t *buf; + DWORD error; + + buf = NULL; + error = GetLastError(); + FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error, 0, (wchar_t *)&buf, 0, NULL); + + if (buf) { + fwprintf(stderr, L"%ls: %ls", message, buf); + LocalFree(buf); + } else { + /* FormatMessageW failed. */ + fwprintf(stderr, L"%ls: unknown error 0x%x\n", + message, error); + } +} + +/* + * Print all files in a given directory tree that match a given wildcard + * pattern. + */ +int +main() +{ + struct stack { + wchar_t *path; + size_t pathlen; + size_t slashlen; + HANDLE ffh; + WIN32_FIND_DATAW ffd; + struct stack *next; + } *dir, dir0, *ndir; + size_t patternlen; + int argc; + wchar_t **argv, *buf, c, *pattern; + + /* MinGW never provides wmain(argc, argv). */ + argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argv == NULL) { + oops(L"CommandLineToArgvW"); + exit(1); + } + + if (argc != 3) { + fwprintf(stderr, L"usage: %ls dir pattern\n", argv[0]); + exit(1); + } + + dir0.path = argv[1]; + dir0.pathlen = wcslen(dir0.path); + pattern = argv[2]; + patternlen = wcslen(pattern); + + if (patternlen == 0 || + wcscmp(pattern, L".") == 0 || + wcscmp(pattern, L"..") == 0 || + wcschr(pattern, L'/') || + wcschr(pattern, L'\\')) { + fwprintf(stderr, L"%ls: invalid pattern\n", pattern); + exit(1); + } + + /* + * Must put backslash between path and pattern, unless + * last character of path is slash or colon. + * + * 'dir' => 'dir\*' + * 'dir\' => 'dir\*' + * 'dir/' => 'dir/*' + * 'c:' => 'c:*' + * + * 'c:*' and 'c:\*' are different files! + */ + c = dir0.path[dir0.pathlen - 1]; + if (c == ':' || c == '/' || c == '\\') + dir0.slashlen = dir0.pathlen; + else + dir0.slashlen = dir0.pathlen + 1; + + /* Allocate space for path + backslash + pattern + \0. */ + buf = calloc(dir0.slashlen + patternlen + 1, sizeof buf[0]); + if (buf == NULL) { + perror("calloc"); + exit(1); + } + dir0.path = wmemcpy(buf, dir0.path, dir0.pathlen + 1); + + dir0.ffh = INVALID_HANDLE_VALUE; + dir0.next = NULL; + dir = &dir0; + + /* Loop for each directory in linked list. */ +loop: + while (dir) { + /* + * At first visit to directory: + * Print the matching files. Then, begin to find + * subdirectories. + * + * At later visit: + * dir->ffh is the handle to find subdirectories. + * Continue to find them. + */ + if (dir->ffh == INVALID_HANDLE_VALUE) { + /* Append backslash + pattern + \0 to path. */ + dir->path[dir->pathlen] = '\\'; + wmemcpy(dir->path + dir->slashlen, + pattern, patternlen + 1); + + /* Find all files to match pattern. */ + dir->ffh = FindFirstFileW(dir->path, &dir->ffd); + if (dir->ffh == INVALID_HANDLE_VALUE) { + /* Check if no files match pattern. */ + if (GetLastError() == ERROR_FILE_NOT_FOUND) + goto subdirs; + + /* Bail out from other errors. */ + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + goto popdir; + } + + /* Remove pattern from path; keep backslash. */ + dir->path[dir->slashlen] = '\0'; + + /* Print all files to match pattern. */ + do { + wprintf(L"%ls%ls\n", + dir->path, dir->ffd.cFileName); + } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); + if (GetLastError() != ERROR_NO_MORE_FILES) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + } + FindClose(dir->ffh); + +subdirs: + /* Append * + \0 to path. */ + dir->path[dir->slashlen] = '*'; + dir->path[dir->slashlen + 1] = '\0'; + + /* Find first possible subdirectory. */ + dir->ffh = FindFirstFileExW(dir->path, + FindExInfoStandard, &dir->ffd, + FindExSearchLimitToDirectories, NULL, 0); + if (dir->ffh == INVALID_HANDLE_VALUE) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + goto popdir; + } + } else { + /* Find next possible subdirectory. */ + if (FindNextFileW(dir->ffh, &dir->ffd) == 0) + goto closeffh; + } + + /* Enter subdirectories. */ + do { + const wchar_t *fn = dir->ffd.cFileName; + const DWORD attr = dir->ffd.dwFileAttributes; + size_t buflen, fnlen; + + /* + * Skip '.' and '..', because they are links to + * the current and parent directories, so they + * are not subdirectories. + * + * Skip any file that is not a directory. + * + * Skip all reparse points, because they might + * be symbolic links. They might form a cycle, + * with a directory inside itself. + */ + if (wcscmp(fn, L".") == 0 || + wcscmp(fn, L"..") == 0 || + (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 || + (attr & FILE_ATTRIBUTE_REPARSE_POINT)) + continue; + + ndir = malloc(sizeof *ndir); + if (ndir == NULL) { + perror("malloc"); + exit(1); + } + + /* + * Allocate space for path + backslash + + * fn + backslash + pattern + \0. + */ + fnlen = wcslen(fn); + buflen = dir->slashlen + fnlen + patternlen + 2; + buf = calloc(buflen, sizeof buf[0]); + if (buf == NULL) { + perror("malloc"); + exit(1); + } + + /* Copy path + backslash + fn + \0. */ + wmemcpy(buf, dir->path, dir->slashlen); + wmemcpy(buf + dir->slashlen, fn, fnlen + 1); + + /* Push dir to list. Enter dir. */ + ndir->path = buf; + ndir->pathlen = dir->slashlen + fnlen; + ndir->slashlen = ndir->pathlen + 1; + ndir->ffh = INVALID_HANDLE_VALUE; + ndir->next = dir; + dir = ndir; + goto loop; /* Continue outer loop. */ + } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); +closeffh: + if (GetLastError() != ERROR_NO_MORE_FILES) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + } + FindClose(dir->ffh); + +popdir: + /* Pop dir from list, free dir, but never free dir0. */ + free(dir->path); + if (ndir = dir->next) + free(dir); + dir = ndir; + } + + return 0; +} diff --git a/Task/Walk-a-directory-Recursively/Cache-ObjectScript/walk-a-directory-recursively.cos b/Task/Walk-a-directory-Recursively/Cache-ObjectScript/walk-a-directory-recursively.cos new file mode 100644 index 0000000000..ca6e2c38ba --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Cache-ObjectScript/walk-a-directory-recursively.cos @@ -0,0 +1,22 @@ +Class Utils.File [ Abstract ] +{ + +ClassMethod WalkTree(pDir As %String = "", pMask As %String = "*.*") As %Status +{ + // do some validation + If pDir="" Quit $$$ERROR($$$GeneralError, "No directory specified.") + + // search input directory for files matching wildcard + Set fs=##class(%ResultSet).%New("%File.FileSet") + Set sc=fs.Execute(pDir, pMask) + While (fs.Next()) { + Write !, fs.Name + // sub-directory + If fs.Type="D" Set sc=..WalkTree(fs.Name, pMask) + } + + // finished + Quit $$$OK +} + +} diff --git a/Task/Walk-a-directory-Recursively/Clojure/walk-a-directory-recursively.clj b/Task/Walk-a-directory-Recursively/Clojure/walk-a-directory-recursively.clj new file mode 100644 index 0000000000..102531e06d --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Clojure/walk-a-directory-recursively.clj @@ -0,0 +1,7 @@ +(use '[clojure.java.io]) + +(defn walk [dirpath pattern] + (doall (filter #(re-matches pattern (.getName %)) + (file-seq (file dirpath))))) + +(map #(println (.getPath %)) (walk "src" #".*\.clj")) diff --git a/Task/Walk-a-directory-Recursively/CoffeeScript/walk-a-directory-recursively.coffeescript b/Task/Walk-a-directory-Recursively/CoffeeScript/walk-a-directory-recursively.coffeescript new file mode 100644 index 0000000000..e6687e9e18 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/CoffeeScript/walk-a-directory-recursively.coffeescript @@ -0,0 +1,17 @@ +fs = require 'fs' + +walk = (dir, f_match, f_visit) -> + _walk = (dir) -> + fns = fs.readdirSync dir + for fn in fns + fn = dir + '/' + fn + if f_match fn + f_visit fn + if fs.statSync(fn).isDirectory() + _walk fn + _walk(dir) + +dir = '..' +matcher = (fn) -> fn.match /\.coffee/ +action = console.log +walk dir, matcher, action diff --git a/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-1.lisp b/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-1.lisp new file mode 100644 index 0000000000..dd2534d093 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-1.lisp @@ -0,0 +1,5 @@ +(defun mapc-directory-tree (fn directory) + (dolist (entry (cl-fad:list-directory directory)) + (when (cl-fad:directory-pathname-p entry) + (mapc-directory-tree fn entry)) + (funcall fn entry))) diff --git a/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-2.lisp b/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-2.lisp new file mode 100644 index 0000000000..140011b490 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Common-Lisp/walk-a-directory-recursively-2.lisp @@ -0,0 +1,10 @@ +CL-USER> (mapc-directory-tree (lambda (x) + (when (equal (pathname-type x) "lisp") + (write-line (namestring x)))) + "lang/") +/home/sthalik/lang/lisp/.#bitmap.lisp +/home/sthalik/lang/lisp/avg.lisp +/home/sthalik/lang/lisp/bitmap.lisp +/home/sthalik/lang/lisp/box-muller.lisp +/home/sthalik/lang/lisp/displaced-subseq.lisp +[...] diff --git a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d new file mode 100644 index 0000000000..4d51ab8754 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-1.d @@ -0,0 +1,18 @@ +import std.stdio; +import std.file; +import std.regexp; + +void main(string[] args) { + auto path = args.length > 1 ? args[1] : "." ; // default current + auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file + bool useRegExp = (args.length > 3 && args[3] == "-re") ; // pattern matching method + + if (args.length > 3 && args[3] == "-re") + // use Regular Expression + foreach (d; listdir(path, RegExp(pattern))) + writefln(d); + else + // use unix shell style pattern matching + foreach (d; listdir(path, pattern)) + writefln(d); + } diff --git a/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d new file mode 100644 index 0000000000..63c2e960ea --- /dev/null +++ b/Task/Walk-a-directory-Recursively/D/walk-a-directory-recursively-2.d @@ -0,0 +1,29 @@ +import std.stdio; +import std.file; +import std.regexp; +import std.path ; + +void main(string[] args) { + auto path = args.length > 1 ? args[1] : "." ; // default current + auto pattern = args.length > 2 ? args[2] : "*.*"; // default all file + bool useRegExp = (args.length > 3 && args[3] == "-re") ; // pattern matching method + bool recursive = (args.length <= 4 || args[4] != "-nr") ; // recursive? + + bool matchNPrint(DirEntry* de) { + bool bPrint = false ; + if(!de.isdir) { + if(useRegExp){ + if(search(de.name, pattern)) // this _search_ from regexp module + writefln(de.name) ; + }else{ + if(fnmatch(de.name, pattern)) // this _fnmatch_ from path module + writefln(de.name) ; + } + } else + if(recursive) + listdir(de.name, &matchNPrint) ; // recursive sub dir + return true ; // continue + } + + listdir(path, &matchNPrint) ; +} diff --git a/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-1.e b/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-1.e new file mode 100644 index 0000000000..9a7629c0ba --- /dev/null +++ b/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-1.e @@ -0,0 +1,10 @@ +def walkTree(directory, pattern) { + for name => file in directory { + if (name =~ rx`.*$pattern.*`) { + println(file.getPath()) + } + if (file.isDirectory()) { + walkTree(file, pattern) + } + } +} diff --git a/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-2.e b/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-2.e new file mode 100644 index 0000000000..1460a2e872 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/E/walk-a-directory-recursively-2.e @@ -0,0 +1,3 @@ +? walkTree(, "rmdir") +/usr/share/man/man1/rmdir.1 +/usr/share/man/man2/rmdir.2 diff --git a/Task/Walk-a-directory-Recursively/Factor/walk-a-directory-recursively.factor b/Task/Walk-a-directory-Recursively/Factor/walk-a-directory-recursively.factor new file mode 100644 index 0000000000..aef5940c03 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Factor/walk-a-directory-recursively.factor @@ -0,0 +1,5 @@ +USE: io.directories.search + +"." t [ + dup ".factor" tail? [ print ] [ drop ] if +] each-file diff --git a/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth b/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth new file mode 100644 index 0000000000..eb668135b8 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth @@ -0,0 +1,30 @@ +defer ls-filter + +: dots? ( name len -- ? ) + dup 1 = if drop c@ [char] . = + else 2 = if dup c@ [char] . = swap 1+ c@ [char] . = and + else drop false then then ; + +: ls-r ( dir len -- ) + open-dir if drop exit then ( dirid) + begin + dup pad 256 rot read-dir throw + while + pad over dots? 0= if \ ignore current and parent dirs + pad over recurse + pad over ls-filter if + cr pad swap type + else drop then + else drop then + repeat + drop close-dir throw ; + +: c-file? ( str len -- ? ) + dup 3 < if 2drop false exit then + + 1- dup c@ 32 or + dup [char] c <> swap [char] h <> and if drop false exit then + 1- dup c@ [char] . <> if drop false exit then + drop true ; +' c-file? is ls-filter + +s" ." ls-r diff --git a/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap b/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap new file mode 100644 index 0000000000..f0a3a38c0c --- /dev/null +++ b/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap @@ -0,0 +1,17 @@ +Walk := function(name, op) + local dir, file, e; + dir := Directory(name); + for e in SortedList(DirectoryContents(name)) do + file := Filename(dir, e); + if IsDirectoryPath(file) then + if not (e in [".", ".."]) then + Walk(file, op); + fi; + else + op(file); + fi; + od; +end; + +# This will print filenames +Walk(".", Display); diff --git a/Task/Walk-a-directory-Recursively/GUISS/walk-a-directory-recursively.guiss b/Task/Walk-a-directory-Recursively/GUISS/walk-a-directory-recursively.guiss new file mode 100644 index 0000000000..be42790dd7 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/GUISS/walk-a-directory-recursively.guiss @@ -0,0 +1,2 @@ +Start,Find,Files and Folders,Dropdown: Look in>My Documents, +Inputbox: filename>m*.txt,Button:Search diff --git a/Task/Walk-a-directory-Recursively/Go/walk-a-directory-recursively.go b/Task/Walk-a-directory-Recursively/Go/walk-a-directory-recursively.go new file mode 100644 index 0000000000..dc62858604 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Go/walk-a-directory-recursively.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" +) + +func VisitFile(fp string, fi os.FileInfo, err error) error { + if err != nil { + fmt.Println(err) // can't walk here, + return nil // but continue walking elsewhere + } + if !!fi.IsDir() { + return nil // not a file. ignore. + } + matched, err := filepath.Match("*.mp3", fi.Name()) + if err != nil { + fmt.Println(err) // malformed pattern + return err // this is fatal. + } + if matched { + fmt.Println(fp) + } + return nil +} + +func main() { + filepath.Walk("/", VisitFile) +} diff --git a/Task/Walk-a-directory-Recursively/Groovy/walk-a-directory-recursively.groovy b/Task/Walk-a-directory-Recursively/Groovy/walk-a-directory-recursively.groovy new file mode 100644 index 0000000000..245aa15bd6 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Groovy/walk-a-directory-recursively.groovy @@ -0,0 +1,3 @@ +new File('.').eachFileRecurse { + if (it.name =~ /.*\.txt/) println it; +} diff --git a/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively.hs b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively.hs new file mode 100644 index 0000000000..f5a42fc7f9 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Haskell/walk-a-directory-recursively.hs @@ -0,0 +1,11 @@ +import System.Environment +import System.Directory +import System.FilePath.Find + +search pat dir = + find always (fileName ~~? pat) dir + +main = do [pat] <- getArgs + dir <- getCurrentDirectory + files <- search pat dir + mapM_ putStrLn files diff --git a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl new file mode 100644 index 0000000000..965dac6580 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-1.idl @@ -0,0 +1 @@ +result = file_search( directory, '*.txt', count=cc ) diff --git a/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl new file mode 100644 index 0000000000..9e2be5fd22 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/IDL/walk-a-directory-recursively-2.idl @@ -0,0 +1,16 @@ +procedure main() +every write(!getdirs(".")) # writes out all directories from the current directory down +end + +procedure getdirs(s) #: return a list of directories beneath the directory 's' +local D,d,f + +if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { + D := [s] + while f := read(d) do + if not ( ".." ? =f ) then # skip . and .. + D |||:= getdirs(s || "/" ||f) + close(d) + return D + } +end diff --git a/Task/Walk-a-directory-Recursively/J/walk-a-directory-recursively.j b/Task/Walk-a-directory-Recursively/J/walk-a-directory-recursively.j new file mode 100644 index 0000000000..fa4c34259a --- /dev/null +++ b/Task/Walk-a-directory-Recursively/J/walk-a-directory-recursively.j @@ -0,0 +1,2 @@ +require 'dir' +>{."1 dirtree '*.html' diff --git a/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-1.java b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-1.java new file mode 100644 index 0000000000..96c766f239 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-1.java @@ -0,0 +1,29 @@ +import java.io.File; + +public class MainEntry { + public static void main(String[] args) { + walkin(new File("/home/user")); //Replace this with a suitable directory + } + + /** + * Recursive function to descend into the directory tree and find all the files + * that end with ".mp3" + * @param dir A file object defining the top directory + **/ + public static void walkin(File dir) { + String pattern = ".mp3"; + + File listFile[] = dir.listFiles(); + if (listFile != null) { + for (int i=0; i() { + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { + if (file.toString().endsWith(".mp3")) { + System.out.println(file); + } + return FileVisitResult.CONTINUE; + } + }); + } +} diff --git a/Task/Walk-a-directory-Recursively/JavaScript/walk-a-directory-recursively.js b/Task/Walk-a-directory-Recursively/JavaScript/walk-a-directory-recursively.js new file mode 100644 index 0000000000..58ee342330 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/JavaScript/walk-a-directory-recursively.js @@ -0,0 +1,30 @@ +var fso = new ActiveXObject("Scripting.FileSystemObject"); + +function walkDirectoryTree(folder, folder_name, re_pattern) { + WScript.Echo("Files in " + folder_name + " matching '" + re_pattern + "':"); + walkDirectoryFilter(folder.files, re_pattern); + + var subfolders = folder.SubFolders; + WScript.Echo("Folders in " + folder_name + " matching '" + re_pattern + "':"); + walkDirectoryFilter(subfolders, re_pattern); + + WScript.Echo(); + var en = new Enumerator(subfolders); + while (! en.atEnd()) { + var subfolder = en.item(); + walkDirectoryTree(subfolder, folder_name + "/" + subfolder.name, re_pattern); + en.moveNext(); + } +} + +function walkDirectoryFilter(items, re_pattern) { + var e = new Enumerator(items); + while (! e.atEnd()) { + var item = e.item(); + if (item.name.match(re_pattern)) + WScript.Echo(item.name); + e.moveNext(); + } +} + +walkDirectoryTree(dir, dir.name, '\\.txt$'); diff --git a/Task/Walk-a-directory-Recursively/MAXScript/walk-a-directory-recursively.maxscript b/Task/Walk-a-directory-Recursively/MAXScript/walk-a-directory-recursively.maxscript new file mode 100644 index 0000000000..c404bd761f --- /dev/null +++ b/Task/Walk-a-directory-Recursively/MAXScript/walk-a-directory-recursively.maxscript @@ -0,0 +1,18 @@ +fn walkDir dir pattern = +( + dirArr = GetDirectories (dir + "\\*") + + for d in dirArr do + ( + join dirArr (getDirectories (d + "\\*")) + ) + + append dirArr (dir + "\\") -- Need to include the original top level directory + + for f in dirArr do + ( + print (getFiles (f + pattern)) + ) +) + +walkDir "C:" "*.txt" diff --git a/Task/Walk-a-directory-Recursively/Mathematica/walk-a-directory-recursively.math b/Task/Walk-a-directory-Recursively/Mathematica/walk-a-directory-recursively.math new file mode 100644 index 0000000000..b6fa3de597 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Mathematica/walk-a-directory-recursively.math @@ -0,0 +1,3 @@ +FileNames["*"] +FileNames["*.png", $RootDirectory] +FileNames["*", {"*"}, Infinity] diff --git a/Task/Walk-a-directory-Recursively/OCaml/walk-a-directory-recursively.ocaml b/Task/Walk-a-directory-Recursively/OCaml/walk-a-directory-recursively.ocaml new file mode 100644 index 0000000000..d8df9fe444 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/OCaml/walk-a-directory-recursively.ocaml @@ -0,0 +1,30 @@ +#!/usr/bin/env ocaml +#load "unix.cma" +#load "str.cma" +open Unix + +let walk_directory_tree dir pattern = + let select str = Str.string_match (Str.regexp pattern) str 0 in + let rec walk acc = function + | [] -> (acc) + | dir::tail -> + let contents = Array.to_list (Sys.readdir dir) in + let contents = List.rev_map (Filename.concat dir) contents in + let dirs, files = + List.fold_left (fun (dirs,files) f -> + match (stat f).st_kind with + | S_REG -> (dirs, f::files) (* Regular file *) + | S_DIR -> (f::dirs, files) (* Directory *) + | _ -> (dirs, files) + ) ([],[]) contents + in + let matched = List.filter (select) files in + walk (matched @ acc) (dirs @ tail) + in + walk [] [dir] +;; + +let () = + let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in + List.iter print_endline results; +;; diff --git a/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m b/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m new file mode 100644 index 0000000000..68d02bc973 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Objective-C/walk-a-directory-recursively.m @@ -0,0 +1,7 @@ +NSString *dir = NSHomeDirectory(); +NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir]; + +NSString *file; +while ((file = [de nextObject])) + if ([[file pathExtension] isEqualToString:@"mp3"]) + NSLog(@"%@", file); diff --git a/Task/Walk-a-directory-Recursively/Oz/walk-a-directory-recursively.oz b/Task/Walk-a-directory-Recursively/Oz/walk-a-directory-recursively.oz new file mode 100644 index 0000000000..d020d4c6e2 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Oz/walk-a-directory-recursively.oz @@ -0,0 +1,19 @@ +declare + [Path] = {Module.link ['x-oz://system/os/Path.ozf']} + [Regex] = {Module.link ['x-oz://contrib/regex']} + + proc {WalkDirTree Root Pattern Proc} + proc {Walk R} + Entries = {Path.readdir R} + Files = {Filter Entries Path.isFile} + MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} + Subdirs = {Filter Entries Path.isDir} + in + {ForAll MatchingFiles Proc} + {ForAll Subdirs Walk} + end + in + {Walk Root} + end +in + {WalkDirTree "." ".*\\.oz$" System.showInfo} diff --git a/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-1.php b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-1.php new file mode 100644 index 0000000000..256753f0f2 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-1.php @@ -0,0 +1,13 @@ +function findFiles($dir = '.', $pattern = '/./'){ + $prefix = $dir . '/'; + $dir = dir($dir); + while (false !== ($file = $dir->read())){ + if ($file === '.' || $file === '..') continue; + $file = $prefix . $file; + if (is_dir($file)) findFiles($file, $pattern); + if (preg_match($pattern, $file)){ + echo $file . "\n"; + } + } +} +findFiles('./foo', '/\.bar$/'); diff --git a/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php new file mode 100644 index 0000000000..c6947bb59f --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php @@ -0,0 +1,89 @@ +/* + This script performs a BFS search with recursion protection + it is often faster to search using this method across a + filesystem due to a few reasons: + + * filesystem is accessed in native node order + * a recursive function is not required allowing infinate depth + * multiple directory handles are not required + * the file being searched for is often not that deep in the fs + + This method also leverages PHP array hashing to speed up loop + detection while minimizing the amount of RAM used to track the + search history. + + -Geoffrey McRae + Released as open license for any use. +*/ +if ($_SERVER['argc'] < 3) { + printf( + "\n" . + "Usage: %s (path) (search) [stop]\n" . + " path the path to search\n" . + " search the filename to search for\n" . + " stop stop when file found, default 1\n" . + "\n" + , $_SERVER['argv'][0]); + exit(1); +} + +$path = $_SERVER['argv'][1]; +$search = $_SERVER['argv'][2]; +if ($_SERVER['argc'] > 3) + $stop = $_SERVER['argv'][3] == 1; +else $stop = true; + +/* get the absolute path and ensure it has a trailing slash */ +$path = realpath($path); +if (substr($path, -1) !== DIRECTORY_SEPARATOR) + $path .= DIRECTORY_SEPARATOR; + +$queue = array($path => 1); +$done = array(); +$index = 0; +while(!empty($queue)) { + /* get one element from the queue */ + foreach($queue as $path => $unused) { + unset($queue[$path]); + $done[$path] = null; + break; + } + unset($unused); + + $dh = @opendir($path); + if (!$dh) continue; + while(($filename = readdir($dh)) !== false) { + /* dont recurse back up levels */ + if ($filename == '.' || $filename == '..') + continue; + + /* check if the filename matches the search term */ + if ($filename == $search) { + echo "$path$filename\n"; + if ($stop) + break 2; + } + + /* get the full path */ + $filename = $path . $filename; + + /* resolve symlinks to their real path */ + if (is_link($filename)) + $filename = realpath($filename); + + /* queue directories for later search */ + if (is_dir($filename)) { + /* ensure the path has a trailing slash */ + if (substr($filename, -1) !== DIRECTORY_SEPARATOR) + $filename .= DIRECTORY_SEPARATOR; + + /* check if we have already queued this path, or have done it */ + if (array_key_exists($filename, $queue) || array_key_exists($filename, $done)) + continue; + + /* queue the file */ + $queue[$filename] = null; + } + } + closedir($dh); +} diff --git a/Task/Walk-a-directory-Recursively/Perl-6/walk-a-directory-recursively.pl6 b/Task/Walk-a-directory-Recursively/Perl-6/walk-a-directory-recursively.pl6 new file mode 100644 index 0000000000..0a8aa5fa70 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Perl-6/walk-a-directory-recursively.pl6 @@ -0,0 +1,3 @@ +use File::Find; + +.say for find(dir => '.').grep(/foo/); diff --git a/Task/Walk-a-directory-Recursively/Perl/walk-a-directory-recursively.pl b/Task/Walk-a-directory-Recursively/Perl/walk-a-directory-recursively.pl new file mode 100644 index 0000000000..dd9c47ed8f --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Perl/walk-a-directory-recursively.pl @@ -0,0 +1,4 @@ +use File::Find qw(find); +my $dir = '.'; +my $pattern = 'foo'; +find sub {print $File::Find::name if /$pattern/}, $dir; diff --git a/Task/Walk-a-directory-Recursively/PicoLisp/walk-a-directory-recursively.l b/Task/Walk-a-directory-Recursively/PicoLisp/walk-a-directory-recursively.l new file mode 100644 index 0000000000..f71da7874f --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PicoLisp/walk-a-directory-recursively.l @@ -0,0 +1,9 @@ +(let Dir "." + (recur (Dir) + (for F (dir Dir) + (let Path (pack Dir "/" F) + (cond + ((=T (car (info Path))) # Is a subdirectory? + (recurse Path) ) # Yes: Recurse + ((match '`(chop "s@.l") (chop F)) # Matches 's*.l'? + (println Path) ) ) ) ) ) ) # Yes: Print it diff --git a/Task/Walk-a-directory-Recursively/Pop11/walk-a-directory-recursively.pop11 b/Task/Walk-a-directory-Recursively/Pop11/walk-a-directory-recursively.pop11 new file mode 100644 index 0000000000..a403d14882 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Pop11/walk-a-directory-recursively.pop11 @@ -0,0 +1,8 @@ +lvars repp, fil; +;;; create path repeater +sys_file_match('.../*.p', '', false, 0) -> repp; +;;; iterate over paths +while (repp() ->> fil) /= termin do + ;;; print the path + printf(fil, '%s\n'); +endwhile; diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.psh b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.psh new file mode 100644 index 0000000000..5cdab70b97 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.psh @@ -0,0 +1 @@ +Get-ChildItem -Recurse -Include *.mp3 diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.psh b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.psh new file mode 100644 index 0000000000..d801adf5db --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.psh @@ -0,0 +1,2 @@ +Get-ChildItem -Recurse | + Where-Object { $_.Name -match 'foo[0-9]' -and $_.Length -gt 5MB } diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.psh b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.psh new file mode 100644 index 0000000000..e44087b21d --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.psh @@ -0,0 +1,3 @@ +Get-ChildItem -Recurse | + Where-Object { $_.Name -match 'foo[0-9]' } | + ForEach-Object { ... } diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.psh b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.psh new file mode 100644 index 0000000000..82f5b8e122 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.psh @@ -0,0 +1 @@ +| Where-Object { !$_.PSIsContainer } diff --git a/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-1.purebasic b/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-1.purebasic new file mode 100644 index 0000000000..25011df1ba --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-1.purebasic @@ -0,0 +1,23 @@ +Procedure.s WalkRecursive(dir,path.s,Pattern.s="\.txt$") + Static RegularExpression + If Not RegularExpression + RegularExpression=CreateRegularExpression(#PB_Any,Pattern) + EndIf + + While NextDirectoryEntry(dir) + If DirectoryEntryType(dir)=#PB_DirectoryEntry_Directory + If DirectoryEntryName(dir)<>"." And DirectoryEntryName(dir)<>".." + If ExamineDirectory(dir+1,path+DirectoryEntryName(dir),"") + WalkRecursive(dir+1,path+DirectoryEntryName(dir)+"\",Pattern) + FinishDirectory(dir+1) + Else + Debug "Error in "+path+DirectoryEntryName(dir) + EndIf + EndIf + Else ; e.g. #PB_DirectoryEntry_File + If MatchRegularExpression(RegularExpression,DirectoryEntryName(dir)) + Debug DirectoryEntryName(dir) + EndIf + EndIf + Wend +EndProcedure diff --git a/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-2.purebasic b/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-2.purebasic new file mode 100644 index 0000000000..3aa6b2d72c --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PureBasic/walk-a-directory-recursively-2.purebasic @@ -0,0 +1,4 @@ +;- Implementation; Find all .log-files in the C:\Windows tree +ExamineDirectory(1,"C:\WINDOWS\","") +WalkRecursive(1,"C:\WINDOWS\","\.log$") +FinishDirectory(1) diff --git a/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-1.py b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-1.py new file mode 100644 index 0000000000..2050734bd9 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-1.py @@ -0,0 +1,9 @@ +import fnmatch +import os + +rootPath = '/' +pattern = '*.mp3' + +for root, dirs, files in os.walk(rootPath): + for filename in fnmatch.filter(files, pattern): + print( os.path.join(root, filename)) diff --git a/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-2.py b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-2.py new file mode 100644 index 0000000000..fe5c122fab --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-2.py @@ -0,0 +1,9 @@ +from fnmatch import fnmatch +import os, os.path + +def print_fnmatches(pattern, dir, files): + for filename in files: + if fnmatch(filename, pattern): + print os.path.join(dir, filename) + +os.path.walk('/', print_fnmatches, '*.mp3') diff --git a/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-3.py b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-3.py new file mode 100644 index 0000000000..068731f2e2 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Python/walk-a-directory-recursively-3.py @@ -0,0 +1,8 @@ +from path import path + +rootPath = '/' +pattern = '*.mp3' + +d = path(rootPath) +for f in d.walkfiles(pattern): + print f diff --git a/Task/Walk-a-directory-Recursively/R/walk-a-directory-recursively.r b/Task/Walk-a-directory-Recursively/R/walk-a-directory-recursively.r new file mode 100644 index 0000000000..4cab607edc --- /dev/null +++ b/Task/Walk-a-directory-Recursively/R/walk-a-directory-recursively.r @@ -0,0 +1 @@ +dir("/bar/foo", "mp3",recursive=T) diff --git a/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-1.realbasic b/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-1.realbasic new file mode 100644 index 0000000000..246371e8e0 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-1.realbasic @@ -0,0 +1,13 @@ +Sub printFiles(parentDir As FolderItem, pattern As String) + For i As Integer = 1 To parentDir.Count + If parentDir.Item(i).Directory Then + printFiles(parentDir.Item(i), pattern) + Else + Dim rg as New RegEx + Dim myMatch as RegExMatch + rg.SearchPattern = pattern + myMatch = rg.search(parentDir.Item(i).Name) + If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) + End If + Next +End Sub diff --git a/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-2.realbasic b/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-2.realbasic new file mode 100644 index 0000000000..bf45dd8b40 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/REALbasic/walk-a-directory-recursively-2.realbasic @@ -0,0 +1,3 @@ + Dim f As FolderItem = GetFolderItem("C:\Windows\system32") + Dim pattern As String = "((?:[a-z][a-z]+))(\.)(dll)" //all file names ending in .dll + printFiles(f, pattern) diff --git a/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal new file mode 100644 index 0000000000..125f319de9 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal @@ -0,0 +1,8 @@ +import IO; +public void Walk(loc a, str pattern){ + for (entry <- listEntries(a)) + if (endsWith(entry, pattern)) + println(entry); + elseif (isDirectory(a+entry)) + Walk2(a+entry, pattern); +} 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 new file mode 100644 index 0000000000..78070306a5 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively.rb @@ -0,0 +1,6 @@ +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/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala new file mode 100644 index 0000000000..2085f58fbb --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-1.scala @@ -0,0 +1,20 @@ +package io.utils + +import java.io.File + +/** A wrapper around file, allowing iteration either on direct children + or on directory tree */ +class RichFile(file: File) { + + def children = new Iterable[File] { + def iterator = if (file.isDirectory) file.listFiles.iterator else Iterator.empty + } + + def andTree : Iterable[File] = + Seq(file) ++ children.flatMap(child => new RichFile(child).andTree) +} + +/** implicitely enrich java.io.File with methods of RichFile */ +object RichFile { + implicit def toRichFile(file: File) = new RichFile(file) +} diff --git a/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala new file mode 100644 index 0000000000..430adaf205 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scala/walk-a-directory-recursively-2.scala @@ -0,0 +1,12 @@ +package test.io.utils + +import io.utils.RichFile._ // this makes implicit toRichFile active +import java.io.File + +object Test extends Application { + val root = new File("/home/user") + for(f <- root.andTree) Console.println(f) + + // filtering comes for free + for(f <- root.andTree; if f.getName.endsWith(".mp3")) Console.println(f) +} diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.ss b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.ss new file mode 100644 index 0000000000..acad7b2726 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.ss @@ -0,0 +1,16 @@ +(use posix) +(use files) +(use srfi-13) + +(define (walk FN PATH) + (for-each (lambda (ENTRY) + (cond ((not (null? ENTRY)) + + (let ((MYPATH (make-pathname PATH ENTRY))) + + (cond ((directory-exists? MYPATH) + (walk FN MYPATH) )) + + (FN MYPATH) )))) (directory PATH #t) )) + +(walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.ss b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.ss new file mode 100644 index 0000000000..a8af30f152 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.ss @@ -0,0 +1,14 @@ +(use file.util) +(use srfi-13) + +(define (walk FN PATH) + (for-each (lambda (ENTRY) + (cond ((not (null? ENTRY)) + (let ((MYPATH ENTRY)) + + (cond ((file-is-directory? MYPATH) + (walk FN MYPATH) )) + + (FN MYPATH) )))) (directory-list PATH :add-path? #t :children? #t ) )) + +(walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.ss b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.ss new file mode 100644 index 0000000000..9e93907967 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.ss @@ -0,0 +1,16 @@ +#lang scheme + +(require srfi/13) + +(define (walk FN PATH) + (for-each (lambda (ENTRY) + (cond ((not (null? ENTRY)) + + (let ((MYPATH (build-path PATH ENTRY))) + + (cond ((directory-exists? MYPATH) + (walk FN MYPATH) )) + + (FN MYPATH) )))) (directory-list PATH))) + +(walk (lambda (X) (cond ((string-suffix? ".scm" (path->string X)) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st new file mode 100644 index 0000000000..4185e2386a --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st @@ -0,0 +1,26 @@ +Directory extend [ + wholeContent: aPattern do: twoBlock [ + self wholeContent: aPattern withLevel: 0 do: twoBlock. + ] + wholeContent: aPattern withLevel: l do: twoBlock [ + |cont| + cont := (self contents) asSortedCollection. + cont remove: '.'; remove: '..'. + cont + do: [ :n | |fn ps| + ps := (Directory pathSeparator) asString. + fn := (self name), ps, n. + ((File name: fn) isDirectory) + ifTrue: [ + twoBlock value: (n, ps) value: l. + (Directory name: fn) wholeContent: aPattern withLevel: (l+1) do: twoBlock. + ] + ifFalse: [ + ( n =~ aPattern ) + ifMatched: [ :m | + twoBlock value: n value: l + ] + ] + ] + ] +]. diff --git a/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-2.st b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-2.st new file mode 100644 index 0000000000..8d637c2904 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-2.st @@ -0,0 +1,6 @@ +|d| +d := Directory name: '.'. +d wholeContent: '\.st$' do: [ :f :l | + 0 to: l do: [ :i | (Character tab) display ]. + f displayNl +]. diff --git a/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl b/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl new file mode 100644 index 0000000000..a065327028 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Tcl/walk-a-directory-recursively.tcl @@ -0,0 +1,11 @@ +proc walkin {fromDir pattern} { + foreach fname [glob -nocomplain -directory $fromDir *] { + if {[file isdirectory $fname]} { + walkin $fname $pattern + } elseif {[string match $pattern [file tail $fname]]} { + puts [file normalize $fname] + } + } +} +# replace directory with something appropriate +walkin /home/user *.mp3 diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-1.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-1.sh new file mode 100644 index 0000000000..702f947d12 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-1.sh @@ -0,0 +1 @@ +find . -name '*.txt' -type f diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-2.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-2.sh new file mode 100644 index 0000000000..cad73b71b5 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-2.sh @@ -0,0 +1,11 @@ +#! /bin/bash +# Warning: globstar excludes hidden directories. +# Turn on recursive globbing (in this script) or exit if the option is not supported: +shopt -s globstar || exit + +for f in ** +do + if [[ "$f" =~ \.txt$ ]] ; then + echo "$f" + fi +done diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh new file mode 100644 index 0000000000..d377f8015c --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh @@ -0,0 +1,43 @@ +#! /bin/bash + +indent_print() +{ + for((i=0; i < $1; i++)); do + echo -ne "\t" + done + echo "$2" +} + +walk_tree() +{ + local oldifs bn lev pr pmat + if [[ $# -lt 3 ]]; then + if [[ $# -lt 2 ]]; then + pmat=".*" + else + pmat="$2" + fi + walk_tree "$1" "$pmat" 0 + return + fi + lev=$3 + [ -d "$1" ] || return + oldifs=$IFS + IFS=" +" + for el in $1/*; do + bn=$(basename "$el") + if [[ -d "$el" ]]; then + indent_print $lev "$bn/" + pr=$( walk_tree "$el" "$2" $(( lev + 1)) ) + echo "$pr" + else + if [[ "$bn" =~ $2 ]]; then + indent_print $lev "$bn" + fi + fi + done + IFS=$oldifs +} + +walk_tree "$1" "\.sh$" diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh new file mode 100644 index 0000000000..db0740262e --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh @@ -0,0 +1,14 @@ +#! /usr/bin/env bash + +walk_tree() { + ls "$1" | while IFS= read i; do + if [ -d "$1/$i" ]; then + echo "$i/" + walk_tree "$1/$i" "$2" | sed -r 's/^/\t/' + else + echo "$i" | grep -E "$2" + fi + done +} + +walk_tree "$1" "\.sh$" diff --git a/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-1.unixpipes b/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-1.unixpipes new file mode 100644 index 0000000000..644ee70e38 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-1.unixpipes @@ -0,0 +1 @@ +find . -type f | egrep '\.txt$|\.TXT$' diff --git a/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-2.unixpipes b/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-2.unixpipes new file mode 100644 index 0000000000..f61a500def --- /dev/null +++ b/Task/Walk-a-directory-Recursively/UnixPipes/walk-a-directory-recursively-2.unixpipes @@ -0,0 +1 @@ + find . -type f -name "*.txt" -print0 | xargs -0 fgrep sometext diff --git a/Task/Walk-a-directory-Recursively/Visual-Basic-.NET/walk-a-directory-recursively.visual b/Task/Walk-a-directory-Recursively/Visual-Basic-.NET/walk-a-directory-recursively.visual new file mode 100644 index 0000000000..493e3a2679 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Visual-Basic-.NET/walk-a-directory-recursively.visual @@ -0,0 +1,8 @@ +Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String) + For Each file In directory.GetFiles(pattern) + Console.WriteLine(file.FullName) + Next + For Each subDir In directory.GetDirectories + walkTree(subDir, pattern) + Next +End Sub diff --git a/Task/Web-scraping/0DESCRIPTION b/Task/Web-scraping/0DESCRIPTION new file mode 100644 index 0000000000..fecb7cf54d --- /dev/null +++ b/Task/Web-scraping/0DESCRIPTION @@ -0,0 +1,24 @@ +Create a program that downloads the time from this URL: [http://tycho.usno.navy.mil/cgi-bin/timer.pl http://tycho.usno.navy.mil/cgi-bin/timer.pl] and then prints the current UTC time by extracting just the UTC time from the web page's [[HTML]]. + +The page http://tycho.usno.navy.mil/cgi-bin/timer.pl is no longer available since july 2011. The relevant part of that page source looked like this: + +
+
+...
+
+What time is it?
+

US Naval Observatory Master Clock Time

+
Jul. 27, 22:57:22 UTC Universal Time +
Jul. 27, 06:57:22 PM EDT Eastern Time +
Jul. 27, 05:57:22 PM CDT Central Time +
Jul. 27, 04:57:22 PM MDT Mountain Time +
Jul. 27, 03:57:22 PM PDT Pacific Time +
Jul. 27, 02:57:22 PM AKDT Alaska Time +
Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time + +... + +
+ + +If possible, only use libraries that come at no ''extra'' monetary cost with the programming language and that are widely available and popular such as [http://www.cpan.org/ CPAN] for Perl or [[Boost]] for C++. diff --git a/Task/Web-scraping/1META.yaml b/Task/Web-scraping/1META.yaml new file mode 100644 index 0000000000..688669690e --- /dev/null +++ b/Task/Web-scraping/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Networking and Web Interaction diff --git a/Task/Web-scraping/ALGOL-68/web-scraping.alg b/Task/Web-scraping/ALGOL-68/web-scraping.alg new file mode 100644 index 0000000000..1e2c0263e8 --- /dev/null +++ b/Task/Web-scraping/ALGOL-68/web-scraping.alg @@ -0,0 +1,42 @@ +STRING + domain="tycho.usno.navy.mil", + page="cgi-bin/timer.pl"; + +STRING # search for the needle in the haystack # + needle = "UTC", + hay stack = "http://"+domain+"/"+page, + + re success="^HTTP/[0-9.]* 200", + re result description="^HTTP/[0-9.]* [0-9]+ [a-zA-Z ]*", + re doctype ="\s\s]+>\s+"; + +PROC raise error = (STRING msg)VOID: ( put(stand error, (msg, new line)); stop); + +PROC is html page = (REF STRING page) BOOL: ( + BOOL out=grep in string(re success, page, NIL, NIL) = 0; + IF INT start, end; + grep in string(re result description, page, start, end) = 0 + THEN + page:=page[end+1:]; + IF grep in string(re doctype, page, start, end) = 0 + THEN page:=page[start+2:] + ELSE raise error("unknown format retrieving page") + FI + ELSE raise error("unknown error retrieving page") + FI; + out +); + +STRING reply; +INT rc = http content (reply, domain, haystack, 0); +IF rc = 0 AND is html page (reply) +THEN + STRING line; FILE freply; associate(freply, reply); + on logical file end(freply, (REF FILE freply)BOOL: (done; SKIP)); + DO + get(freply,(line, new line)); + IF string in string(needle, NIL, line) THEN print((line, new line)) FI + OD; + done: SKIP +ELSE raise error (strerror (rc)) +FI diff --git a/Task/Web-scraping/AWK/web-scraping.awk b/Task/Web-scraping/AWK/web-scraping.awk new file mode 100644 index 0000000000..dd66fcc93d --- /dev/null +++ b/Task/Web-scraping/AWK/web-scraping.awk @@ -0,0 +1,21 @@ +#! /usr/bin/awk -f + +BEGIN { + purl = "/inet/tcp/0/tycho.usno.navy.mil/80" + ORS = RS = "\r\n\r\n" + print "GET /cgi-bin/timer.pl HTTP/1.0" |& purl + purl |& getline header + while ( (purl |& getline ) > 0 ) + { + split($0, a, "\n") + for(i=1; i <= length(a); i++) + { + if ( a[i] ~ /UTC/ ) + { + sub(/^
/, "", a[i]) + printf "%s\n", a[i] + } + } + } + close(purl) +} diff --git a/Task/Web-scraping/Ada/web-scraping.ada b/Task/Web-scraping/Ada/web-scraping.ada new file mode 100644 index 0000000000..776c41856f --- /dev/null +++ b/Task/Web-scraping/Ada/web-scraping.ada @@ -0,0 +1,34 @@ +with AWS.Client, AWS.Response, AWS.Resources, AWS.Messages; +with Ada.Text_IO, Ada.Strings.Fixed; +use Ada, AWS, AWS.Resources, AWS.Messages; + +procedure Get_UTC_Time is + + Page : Response.Data; + File : Resources.File_Type; + Buffer : String (1 .. 1024); + Position, Last : Natural := 0; + S : Messages.Status_Code; +begin + Page := Client.Get ("http://tycho.usno.navy.mil/cgi-bin/timer.pl"); + S := Response.Status_Code (Page); + if S not in Success then + Text_IO.Put_Line + ("Unable to retrieve data => Status Code :" & Image (S) & + " Reason :" & Reason_Phrase (S)); + return; + end if; + + Response.Message_Body (Page, File); + while not End_Of_File (File) loop + Resources.Get_Line (File, Buffer, Last); + Position := + Strings.Fixed.Index + (Source => Buffer (Buffer'First .. Last), + Pattern => "UTC"); + if Position > 0 then + Text_IO.Put_Line (Buffer (5 .. Position + 2)); + return; + end if; + end loop; +end Get_UTC_Time; diff --git a/Task/Web-scraping/AutoHotkey/web-scraping.ahk b/Task/Web-scraping/AutoHotkey/web-scraping.ahk new file mode 100644 index 0000000000..21c9cf192f --- /dev/null +++ b/Task/Web-scraping/AutoHotkey/web-scraping.ahk @@ -0,0 +1,4 @@ +UrlDownloadToFile, http://tycho.usno.navy.mil/cgi-bin/timer.pl, time.html +FileRead, timefile, time.html +pos := InStr(timefile, "UTC") +msgbox % time := SubStr(timefile, pos - 9, 8) diff --git a/Task/Web-scraping/BBC-BASIC/web-scraping.bbc b/Task/Web-scraping/BBC-BASIC/web-scraping.bbc new file mode 100644 index 0000000000..5366f761fa --- /dev/null +++ b/Task/Web-scraping/BBC-BASIC/web-scraping.bbc @@ -0,0 +1,18 @@ + SYS "LoadLibrary", "URLMON.DLL" TO urlmon% + SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF% + SYS "LoadLibrary", "WININET.DLL" TO wininet% + SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE% + + url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + file$ = @tmp$+"navytime.txt" + + SYS DUCE%, url$ + SYS UDTF%, 0, url$, file$, 0, 0 TO result% + IF result% ERROR 100, "Download failed" + + file% = OPENIN(file$) + REPEAT + text$ = GET$#file% + IF INSTR(text$, "UTC") PRINT MID$(text$, 5) + UNTIL EOF#file% + CLOSE #file% diff --git a/Task/Web-scraping/C++/web-scraping.cpp b/Task/Web-scraping/C++/web-scraping.cpp new file mode 100644 index 0000000000..4ffc92bddb --- /dev/null +++ b/Task/Web-scraping/C++/web-scraping.cpp @@ -0,0 +1,23 @@ +#include +#include +#include +#include +int main() +{ + boost::asio::ip::tcp::iostream s("tycho.usno.navy.mil", "http"); + if(!s) + std::cout << "Could not connect to tycho.usno.navy.mil\n"; + s << "GET /cgi-bin/timer.pl HTTP/1.0\r\n" + << "Host: tycho.usno.navy.mil\r\n" + << "Accept: */*\r\n" + << "Connection: close\r\n\r\n" ; + for(std::string line; getline(s, line); ) + { + boost::smatch matches; + if(regex_search(line, matches, boost::regex("
(.+\\s+UTC)") ) ) + { + std::cout << matches[1] << '\n'; + break; + } + } +} diff --git a/Task/Web-scraping/C/web-scraping.c b/Task/Web-scraping/C/web-scraping.c new file mode 100644 index 0000000000..385383d5bf --- /dev/null +++ b/Task/Web-scraping/C/web-scraping.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +#define BUFSIZE 16384 + +size_t lr = 0; + +size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream) +{ + if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE; + memcpy(stream+lr, ptr, size*nmemb); + lr += size*nmemb; + return size*nmemb; +} + +int main() +{ + CURL *curlHandle; + char buffer[BUFSIZE]; + regmatch_t amatch; + regex_t cregex; + + curlHandle = curl_easy_init(); + curl_easy_setopt(curlHandle, CURLOPT_URL, "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); + curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, filterit); + curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, buffer); + int success = curl_easy_perform(curlHandle); + curl_easy_cleanup(curlHandle); + + buffer[lr] = 0; + + regcomp(&cregex, " UTC", REG_NEWLINE); + regexec(&cregex, buffer, 1, &amatch, 0); + int bi = amatch.rm_so; + while ( bi-- > 0 ) + if ( memcmp(&buffer[bi], "
", 4) == 0 ) break; + + buffer[amatch.rm_eo] = 0; + + printf("%s\n", &buffer[bi+4]); + + regfree(&cregex); + return 0; +} diff --git a/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos b/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos new file mode 100644 index 0000000000..df372892ca --- /dev/null +++ b/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos @@ -0,0 +1,60 @@ +Class Utils.Net [ Abstract ] +{ + +ClassMethod ExtractHTMLData(pHost As %String = "", pPath As %String = "", pRegEx As %String = "", Output list As %List) As %Status +{ + // implement error handling + Try { + + // some initialisation + Set list="", sc=$$$OK + + // check input parameters + If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { + Set sc=$$$ERROR($$$GeneralError, "Invalid host name.") + Quit + } + + // create http request and get page + Set req=##class(%Net.HttpRequest).%New() + Set req.Server=pHost + Do req.Get(pPath) + + // check for success + If $Extract(req.HttpResponse.StatusCode)'=2 { + Set sc=$$$ERROR($$$GeneralError, "Page not loaded.") + Quit + } + + // read http response stream + Set html=req.HttpResponse.Data + Set html.LineTerminator=$Char(10) + Set sc=html.Rewind() + + // read http response stream + While 'html.AtEnd { + Set line=html.ReadLine(, .sc, .eol) + Set pos=$Locate(line, pRegEx) + If pos { + Set parse=$Piece($Extract(line, pos, *), $Char(9)) + Set slot=$ListLength(list)+1 + Set $List(list, slot)=parse + } + } + + } Catch err { + + // an error has occurred + If err.Name="" { + Set sc=$$$ERROR($$$GeneralError, "Invalid regular expression.") + } Else { + Set sc=$$$ERROR($$$CacheError, $ZError) + } + + } + + // return status + Quit sc +} + +} diff --git a/Task/Web-scraping/Clojure/web-scraping.clj b/Task/Web-scraping/Clojure/web-scraping.clj new file mode 100644 index 0000000000..aa35fc3bcd --- /dev/null +++ b/Task/Web-scraping/Clojure/web-scraping.clj @@ -0,0 +1 @@ +(second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "http://tycho.usno.navy.mil/cgi-bin/timer.pl"))) diff --git a/Task/Web-scraping/CoffeeScript/web-scraping-1.coffeescript b/Task/Web-scraping/CoffeeScript/web-scraping-1.coffeescript new file mode 100644 index 0000000000..6f15191051 --- /dev/null +++ b/Task/Web-scraping/CoffeeScript/web-scraping-1.coffeescript @@ -0,0 +1,39 @@ +http = require 'http' + +CONFIG = + host: 'tycho.usno.navy.mil' + path: '/cgi-bin/timer.pl' + +# Web scraping code tends to be brittle, and this is no exception. +# The tycho time page does not use highly structured markup, so +# we do a real dirty scrape. +scrape_tycho_ust_time = (text) -> + for line in text.split '\n' + matches = line.match /(.*:\d\d UTC)/ + if matches + console.log matches[0].replace '
', '' + return + throw Error("unscrapable page!") + +# This is low-level-ish code to get data from a URL. It's +# pretty general purpose, so you'd normally tuck this away +# in a library (or use somebody else's library). +wget = (host, path, cb) -> + options = + host: host + path: path + headers: + "Cache-Control": "max-age=0" + + req = http.request options, (res) -> + s = '' + res.on 'data', (chunk) -> + s += chunk + res.on 'end', -> + cb s + req.end() + +# Do our web scrape +do -> + wget CONFIG.host, CONFIG.path, (data) -> + scrape_tycho_ust_time data diff --git a/Task/Web-scraping/CoffeeScript/web-scraping-2.coffeescript b/Task/Web-scraping/CoffeeScript/web-scraping-2.coffeescript new file mode 100644 index 0000000000..4a8550d2fa --- /dev/null +++ b/Task/Web-scraping/CoffeeScript/web-scraping-2.coffeescript @@ -0,0 +1,2 @@ +> coffee web_scrape.coffee +Jan. 09, 19:19:07 UTC diff --git a/Task/Web-scraping/Common-Lisp/web-scraping.lisp b/Task/Web-scraping/Common-Lisp/web-scraping.lisp new file mode 100644 index 0000000000..a3bd3e53d2 --- /dev/null +++ b/Task/Web-scraping/Common-Lisp/web-scraping.lisp @@ -0,0 +1,10 @@ +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/Web-scraping/D/web-scraping.d b/Task/Web-scraping/D/web-scraping.d new file mode 100644 index 0000000000..4865305442 --- /dev/null +++ b/Task/Web-scraping/D/web-scraping.d @@ -0,0 +1,7 @@ +import std.stdio, std.string, std.net.curl, std.algorithm; + +void main() { + foreach (line; "http://tycho.usno.navy.mil/cgi-bin/timer.pl".byLine) + if (line.length > 4 && line.indexOf(" UTC") != -1) + line[4 .. $].writeln; +} diff --git a/Task/Web-scraping/Delphi/web-scraping-1.delphi b/Task/Web-scraping/Delphi/web-scraping-1.delphi new file mode 100644 index 0000000000..c20e7ad15e --- /dev/null +++ b/Task/Web-scraping/Delphi/web-scraping-1.delphi @@ -0,0 +1,206 @@ +program WebScrape; + +{$APPTYPE CONSOLE} + +{.$DEFINE DEBUG} + +uses + Classes, + Winsock; + + +{ Function to connect to host, send HTTP request and retrieve response } +function DoHTTPGET(const hostName: PAnsiChar; const resource: PAnsiChar; HTTPResponse: TStrings): Boolean; +const + Port: integer = 80; + CRLF = #13#10; // carriage return/line feed +var + WSAData: TWSAData; + Sock: TSocket; + SockAddrIn: TSockAddrIn; + IPAddress: PHostEnt; + bytesIn: integer; + inBuffer: array [0..1023] of char; + Req: string; +begin + Result := False; + HTTPResponse.Clear; + + { Initialise use of the Windows Sockets DLL. + Older Windows versions support Winsock 1.1 whilst newer Windows + include Winsock 2 but support 1.1. Therefore, we'll specify + version 1.1 ($101) as being the highest version of Windows Sockets + that we can use to provide greatest flexibility. + WSAData receives details of the Windows Sockets implementation } + Winsock.WSAStartUp($101, WSAData); + try + + { Create a socket for TCP/IP usage passing in + Address family spec: AF_INET (TCP, UDP, etc.) + Type specification: SOCK_STREAM + Protocol: IPPROTO_TCP (TCP) } + Sock := WinSock.Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + try + + // Check we have a valid socket + if (Sock <> INVALID_SOCKET) then + begin + // Populate socket address structure + with SockAddrIn do + begin + // Address family specification + sin_family := AF_INET; + // Port + sin_port := htons(Port); + // Address + sin_addr.s_addr := inet_addr(hostName); + end; + + if (SockAddrIn.sin_addr.s_addr = INADDR_NONE) then + begin + { As we're using a domain name instead of an + IP Address, we need to resolve the domain name } + IPAddress := Winsock.gethostbyname(hostName); + + // Quit if we didn't get an IP Address + if (IPAddress = nil) then + Exit; + + // Update the structure with the IP Address + SockAddrIn.sin_addr.s_addr := PLongint(IPAddress^.h_addr_list^)^; + end; + + // Try to connect to host + if (Winsock.connect(Sock, SockAddrIn, SizeOf(SockAddrIn)) <> SOCKET_ERROR) then + begin + // OK - Connected + + // Compose our request + // Each line of the request must be terminated with a carriage return/line feed + + { The First line specifies method (e.g. GET, POST), path to required resource, + and the HTTP version being used. These three fields are space separated. } + Req := 'GET '+resource+' HTTP/1.1' + CRLF + + + // Host: is the only Required header in HTTP 1.1 + 'Host: '+hostName + CRLF + + + { Persistent connections are the default in HTTP 1.1 but, as we don't want + or need one for this exercise, we must include the "Connection: close" + header in our request } + 'Connection: close' + CRLF + + + CRLF; // Request must end with an empty line! + + // Try to send the request to the host + if (Winsock.send(Sock,Req[1],Length(Req),0) <> SOCKET_ERROR) then + begin + // Initialise incoming data buffer (i.e. fill array with nulls) + FillChar(inBuffer,SizeOf(inBuffer),#0); + // Loop until nothing left to read + repeat + // Read incoming data from socket + bytesIn := Winsock.recv(Sock, inBuffer, SizeOf(inBuffer), 0); + // Assign buffer to Stringlist + HTTPResponse.Text := HTTPResponse.Text + Copy(string(inBuffer),1,bytesIn); + until + (bytesIn <= 0) or (bytesIn = SOCKET_ERROR); + + { Our list of response strings should + contain at least 1 line } + Result := HTTPResponse.Count > 0; + end; + + end; + + end; + + finally + // Close our socket + Winsock.closesocket(Sock); + end; + + finally + { This causes our application to deregister itself from this + Windows Sockets implementation and allows the implementation + to free any resources allocated on our behalf. } + Winsock.WSACleanup; + end; + +end; + +{ Simple function to locate and return the UTC time from the + request sent to http://tycho.usno.navy.mil/cgi-bin/timer.pl + The HTTPResponse parameter contains both the HTTP Headers and + the HTML served up by the requested resource. } +function ParseResponse(HTTPResponse: TStrings): string; +var + i: Integer; +begin + Result := ''; + + { Check first line for server response code + We want something like this: HTTP/1.1 200 OK } + if Pos('200',HTTPResponse[0]) > 0 then + begin + for i := 0 to Pred(HTTPResponse.Count) do + begin + { The line we're looking for is something like this: +
May. 04. 21:55:19 UTC Universal Time } + + // Check each line + if Pos('UTC',HTTPResponse[i]) > 0 then + begin + Result := Copy(HTTPResponse[i],5,Pos('UTC',HTTPResponse[i])-1); + Break; + end; + + end; + end + else + Result := 'HTTP Error: '+HTTPResponse[0]; +end; + + +const + host: PAnsiChar = 'tycho.usno.navy.mil'; + res : PAnsiChar = '/cgi-bin/timer.pl'; + + +var + Response: TStrings; + +begin + { A TStringList is a TStrings descendant class + that is used to store and manipulate a list + of strings. + + Instantiate a stringlist class to + hold the results of our HTTP GET } + Response := TStringList.Create; + try + // Try an HTTP GET request + if DoHTTPGET(host,res,Response) then + begin + {$IFDEF DEBUG} + { Write the entire response to + the console window } + Writeln(Response.text); + {$ELSE} + { Parse the response and write the + result to the console window } + Writeln(ParseResponse(Response)); + {$ENDIF DEBUG} + end + else + Writeln('Error retrieving data'); + + finally + Response.Free; + end; + + // Keep console window open + Readln; + + +end. diff --git a/Task/Web-scraping/Delphi/web-scraping-2.delphi b/Task/Web-scraping/Delphi/web-scraping-2.delphi new file mode 100644 index 0000000000..0d93e4be69 --- /dev/null +++ b/Task/Web-scraping/Delphi/web-scraping-2.delphi @@ -0,0 +1,28 @@ +program ReadUTCTime; + +{$APPTYPE CONSOLE} + +uses SysUtils, Classes, IdHTTP; + +var + s: string; + lHTTP: TIdHTTP; + lReader: TStringReader; +begin + lHTTP := TIdHTTP.Create(nil); + try + lReader := TStringReader.Create(lHTTP.Get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')); + while lReader.Peek > 0 do + begin + s := lReader.ReadLine; + if Pos('UTC', s) > 0 then + begin + Writeln(s); + Break; + end; + end; + finally + lHTTP.Free; + lReader.Free; + end; +end. diff --git a/Task/Web-scraping/E/web-scraping.e b/Task/Web-scraping/E/web-scraping.e new file mode 100644 index 0000000000..9b303172d2 --- /dev/null +++ b/Task/Web-scraping/E/web-scraping.e @@ -0,0 +1,4 @@ +interp.waitAtTop(when (def html := .getText()) -> { + def rx`(?s).*>(@time.*? UTC).*` := html + println(time) +}) diff --git a/Task/Web-scraping/Erlang/web-scraping.erl b/Task/Web-scraping/Erlang/web-scraping.erl new file mode 100644 index 0000000000..d99062b287 --- /dev/null +++ b/Task/Web-scraping/Erlang/web-scraping.erl @@ -0,0 +1,10 @@ +-module(scraping). +-export([main/0]). +-define(Url, "http://tycho.usno.navy.mil/cgi-bin/timer.pl"). +-define(Match, "
(.+ UTC)"). + +main() -> + inets:start(), + {ok, {_Status, _Header, HTML}} = http:request(?Url), + {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), + io:format("~s~n",[Time]). diff --git a/Task/Web-scraping/Factor/web-scraping.factor b/Task/Web-scraping/Factor/web-scraping.factor new file mode 100644 index 0000000000..5d799d1faf --- /dev/null +++ b/Task/Web-scraping/Factor/web-scraping.factor @@ -0,0 +1,4 @@ +USING: http.get io sequences ; + +"http://tycho.usno.navy.mil/cgi-bin/timer.pl" http-get nip +[ "UTC" swap start [ 9 - ] [ 1 - ] bi ] keep subseq print diff --git a/Task/Web-scraping/Forth/web-scraping.fth b/Task/Web-scraping/Forth/web-scraping.fth new file mode 100644 index 0000000000..41ee25ed28 --- /dev/null +++ b/Task/Web-scraping/Forth/web-scraping.fth @@ -0,0 +1,15 @@ +include unix/socket.fs + +: extract-time ( addr len type len -- time len ) + dup >r + search 0= abort" that time not present!" + dup >r + begin -1 /string over 1- c@ [char] > = until \ seek back to
at start of line + r> - r> + ; + +s" tycho.usno.navy.mil" 80 open-socket +dup s\" GET /cgi-bin/timer.pl HTTP/1.0\n\n" rot write-socket +dup pad 4096 read-socket +s\" \r\n\r\n" search 0= abort" can't find headers!" \ skip headers +s" UTC" extract-time type cr +close-socket diff --git a/Task/Web-scraping/Go/web-scraping.go b/Task/Web-scraping/Go/web-scraping.go new file mode 100644 index 0000000000..b2f5aae60b --- /dev/null +++ b/Task/Web-scraping/Go/web-scraping.go @@ -0,0 +1,56 @@ +package main + +import ( + "bytes" + "encoding/xml" + "fmt" + "io" + "net/http" + "regexp" + "time" +) + +func main() { + resp, err := http.Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + if err != nil { + fmt.Println(err) // connection or request fail + return + } + defer resp.Body.Close() + var us string + var ux int + utc := []byte("UTC") + for p := xml.NewDecoder(resp.Body); ; { + t, err := p.RawToken() + switch err { + case nil: + case io.EOF: + fmt.Println("UTC not found") + return + default: + fmt.Println(err) // read or parse fail + return + } + if ub, ok := t.(xml.CharData); ok { + if ux = bytes.Index(ub, utc); ux != -1 { + // success: found a line with the string "UTC" + us = string([]byte(ub)) + break + } + } + } + // first thing to try: parsing the expected date format + if t, err := time.Parse("Jan. 2, 15:04:05 UTC", us[:ux+3]); err == nil { + fmt.Println("parsed UTC:", t.Format("January 2, 15:04:05")) + return + } + // fallback: search for anything looking like a time and print that + tx := regexp.MustCompile("[0-2]?[0-9]:[0-5][0-9]:[0-6][0-9]") + if justTime := tx.FindString(us); justTime > "" { + fmt.Println("found UTC:", justTime) + return + } + // last resort: just print the whole element containing "UTC" and hope + // there is a human readable time in there somewhere. + fmt.Println(us) +} diff --git a/Task/Web-scraping/Groovy/web-scraping.groovy b/Task/Web-scraping/Groovy/web-scraping.groovy new file mode 100644 index 0000000000..63f3700754 --- /dev/null +++ b/Task/Web-scraping/Groovy/web-scraping.groovy @@ -0,0 +1,8 @@ +def time = "unknown" +def text = new URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl').eachLine { line -> + def matcher = (line =~ "
(.+) UTC") + if (matcher.find()) { + time = matcher[0][1] + } +} +println "UTC Time was '$time'" diff --git a/Task/Web-scraping/Haskell/web-scraping-1.hs b/Task/Web-scraping/Haskell/web-scraping-1.hs new file mode 100644 index 0000000000..edc46954f1 --- /dev/null +++ b/Task/Web-scraping/Haskell/web-scraping-1.hs @@ -0,0 +1,7 @@ +import Data.List +import Network.HTTP (simpleHTTP, getResponseBody, getRequest) + +tyd = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + +readUTC = simpleHTTP (getRequest tyd)>>= + fmap ((!!2).head.dropWhile ("UTC"`notElem`).map words.lines). getResponseBody>>=putStrLn diff --git a/Task/Web-scraping/Haskell/web-scraping-2.hs b/Task/Web-scraping/Haskell/web-scraping-2.hs new file mode 100644 index 0000000000..6ac385e8e4 --- /dev/null +++ b/Task/Web-scraping/Haskell/web-scraping-2.hs @@ -0,0 +1,2 @@ +*Main> readUTC +08:30:23 diff --git a/Task/Web-scraping/Haskell/web-scraping-3.hs b/Task/Web-scraping/Haskell/web-scraping-3.hs new file mode 100644 index 0000000000..f2e97564f2 --- /dev/null +++ b/Task/Web-scraping/Haskell/web-scraping-3.hs @@ -0,0 +1,7 @@ +procedure main() +m := open(url := "http://tycho.usno.navy.mil/cgi-bin/timer.pl","m") | stop("Unable to open ",url) +every (p := "") ||:= |read(m) # read the page into a single string +close(m) + +map(p) ? ( tab(find("
")), ="
", write("UTC time=",p[&pos:find(" utc")])) # scrape and show +end diff --git a/Task/Web-scraping/J/web-scraping.j b/Task/Web-scraping/J/web-scraping.j new file mode 100644 index 0000000000..0147f9b5a6 --- /dev/null +++ b/Task/Web-scraping/J/web-scraping.j @@ -0,0 +1,4 @@ + require 'web/gethttp' + + _8{. ' UTC' taketo gethttp 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' +04:32:44 diff --git a/Task/Web-scraping/Java/web-scraping.java b/Task/Web-scraping/Java/web-scraping.java new file mode 100644 index 0000000000..aa447c3a00 --- /dev/null +++ b/Task/Web-scraping/Java/web-scraping.java @@ -0,0 +1,24 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; + + +public class WebTime{ + public static void main(String[] args){ + try{ + URL address = new URL( + "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); + URLConnection conn = address.openConnection(); + BufferedReader in = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + String line; + while(!(line = in.readLine()).contains("UTC")); + System.out.println(line.substring(4)); + }catch(IOException e){ + System.err.println("error connecting to server."); + e.printStackTrace(); + } + } +} diff --git a/Task/Web-scraping/Liberty-BASIC/web-scraping.liberty b/Task/Web-scraping/Liberty-BASIC/web-scraping.liberty new file mode 100644 index 0000000000..172c888995 --- /dev/null +++ b/Task/Web-scraping/Liberty-BASIC/web-scraping.liberty @@ -0,0 +1,23 @@ +if DownloadToFile("http://tycho.usno.navy.mil/cgi-bin/timer.pl", DefaultDir$ + "\timer.htm") = 0 then + open DefaultDir$ + "\timer.htm" for input as #f + html$ = lower$(input$(#f, LOF(#f))) + close #f + + a= instr( html$, "utc" )-1 + print "UTC";mid$( html$, a-9,9) + + end if + +end + +function DownloadToFile(urlfile$, localfile$) + open "URLmon" for dll as #url + calldll #url, "URLDownloadToFileA",_ + 0 as long,_ 'null + urlfile$ as ptr,_ 'url to download + localfile$ as ptr,_ 'save file name + 0 as long,_ 'reserved, must be 0 + 0 as long,_ 'callback address, can be 0 + DownloadToFile as ulong '0=success + close #url +end function diff --git a/Task/Web-scraping/Mathematica/web-scraping.math b/Task/Web-scraping/Mathematica/web-scraping.math new file mode 100644 index 0000000000..d86662d246 --- /dev/null +++ b/Task/Web-scraping/Mathematica/web-scraping.math @@ -0,0 +1,2 @@ +test = StringSplit[Import["http://tycho.usno.navy.mil/cgi-bin/timer.pl"], "\n"]; +Extract[test, Flatten@Position[StringFreeQ[test, "UTC"], False]] diff --git a/Task/Web-scraping/NetRexx/web-scraping.netrexx b/Task/Web-scraping/NetRexx/web-scraping.netrexx new file mode 100644 index 0000000000..263554260c --- /dev/null +++ b/Task/Web-scraping/NetRexx/web-scraping.netrexx @@ -0,0 +1,36 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +parse arg full_short . +if 'FULL'.abbrev(full_short.upper(), 1) then + dateFull = isTrue() +else + dateFull = isFalse() +do + timeURL = java.net.URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl') + conn = timeURL.openConnection() + ibr = BufferedReader(InputStreamReader(conn.getInputStream())) + line = Rexx + loop label readLoop while ibr.ready() + line = ibr.readLine() + if line = null then leave readLoop + line = line.translate(' ', '\t') + if line.wordpos('UTC') > 0 then do + parse line . '>' udatetime 'UTC' . - + 0 . '>' . ',' utime 'UTC' . + if dateFull then + say udatetime.strip() 'UTC' + else + say utime.strip() + leave readLoop + end + end readLoop + ibr.close() +catch ex = IOException + ex.printStackTrace() +end + +method isTrue() public constant returns boolean + return 1 == 1 +method isFalse() public constant returns boolean + return \isTrue() diff --git a/Task/Web-scraping/OCaml/web-scraping.ocaml b/Task/Web-scraping/OCaml/web-scraping.ocaml new file mode 100644 index 0000000000..ca39ad6570 --- /dev/null +++ b/Task/Web-scraping/OCaml/web-scraping.ocaml @@ -0,0 +1,14 @@ +let () = + let _,_, page_content = make_request ~url:Sys.argv.(1) ~kind:GET () in + + let lines = Str.split (Str.regexp "\n") page_content in + let str = + List.find + (fun line -> + try ignore(Str.search_forward (Str.regexp "UTC") line 0); true + with Not_found -> false) + lines + in + let str = Str.global_replace (Str.regexp "
") "" str in + print_endline str; +;; diff --git a/Task/Web-scraping/Objeck/web-scraping.objeck b/Task/Web-scraping/Objeck/web-scraping.objeck new file mode 100644 index 0000000000..a861c08e22 --- /dev/null +++ b/Task/Web-scraping/Objeck/web-scraping.objeck @@ -0,0 +1,25 @@ +use Net; +use IO; +use Structure; + +bundle Default { + class Scrape { + function : Main(args : String[]) ~ Nil { + client := HttpClient->New(); + lines := client->Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl", 80); + + i := 0; + found := false; + while(found <> true & i < lines->Size()) { + line := lines->Get(i)->As(String); + index := line->Find("UTC"); + if(index > -1) { + time := line->SubString(index - 9, 9)->Trim(); + time->PrintLine(); + found := true; + }; + i += 1; + }; + } + } +} diff --git a/Task/Web-scraping/Oz/web-scraping.oz b/Task/Web-scraping/Oz/web-scraping.oz new file mode 100644 index 0000000000..4ceb6de441 --- /dev/null +++ b/Task/Web-scraping/Oz/web-scraping.oz @@ -0,0 +1,20 @@ +declare + [Regex] = {Module.link ['x-oz://contrib/regex']} + + fun {GetPage Url} + F = {New Open.file init(url:Url)} + Contents = {F read(list:$ size:all)} + in + {F close} + Contents + end + + fun {GetDateString Doc} + case {Regex.search "
([A-Za-z0-9:., ]+ UTC)" Doc} + of match(1:S#E ...) then {List.take {List.drop Doc S} E-S+1} + end + end + + Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" +in + {System.showInfo {GetDateString {GetPage Url}}} diff --git a/Task/Web-scraping/PHP/web-scraping-1.php b/Task/Web-scraping/PHP/web-scraping-1.php new file mode 100644 index 0000000000..8e8c8ba44b --- /dev/null +++ b/Task/Web-scraping/PHP/web-scraping-1.php @@ -0,0 +1,8 @@ +(.*) UTC.*$/su", + "\\1", + file_get_contents('http://tycho.usno.navy.mil/cgi-bin/timer.pl') +); diff --git a/Task/Web-scraping/Perl-6/web-scraping.pl6 b/Task/Web-scraping/Perl-6/web-scraping.pl6 new file mode 100644 index 0000000000..b8d62ab73c --- /dev/null +++ b/Task/Web-scraping/Perl-6/web-scraping.pl6 @@ -0,0 +1,3 @@ +use HTTP::Client; # http://github.com/carlins/http-client/ +my $site = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"; +HTTP::Client.new.get($site).match(/'
'( .+? UTC )/)[0].say diff --git a/Task/Web-scraping/Perl/web-scraping.pl b/Task/Web-scraping/Perl/web-scraping.pl new file mode 100644 index 0000000000..fe37cfd615 --- /dev/null +++ b/Task/Web-scraping/Perl/web-scraping.pl @@ -0,0 +1,5 @@ +use LWP::Simple; + +my $url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'; +get($url) =~ /
(.+? UTC)/ + and print "$1\n"; diff --git a/Task/Web-scraping/PicoLisp/web-scraping.l b/Task/Web-scraping/PicoLisp/web-scraping.l new file mode 100644 index 0000000000..a0587d1ea1 --- /dev/null +++ b/Task/Web-scraping/PicoLisp/web-scraping.l @@ -0,0 +1,5 @@ +(load "@lib/http.l") + +(client "tycho.usno.navy.mil" 80 "cgi-bin/timer.pl" + (when (from "
") + (pack (trim (till "U"))) ) ) diff --git a/Task/Web-scraping/PowerShell/web-scraping.psh b/Task/Web-scraping/PowerShell/web-scraping.psh new file mode 100644 index 0000000000..31ae4c5319 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping.psh @@ -0,0 +1,4 @@ +$wc = New-Object Net.WebClient +$html = $wc.DownloadString('http://tycho.usno.navy.mil/cgi-bin/timer.pl') +$html -match ', (.*) UTC' | Out-Null +Write-Host $Matches[1] diff --git a/Task/Web-scraping/Protium/web-scraping-1.protium b/Task/Web-scraping/Protium/web-scraping-1.protium new file mode 100644 index 0000000000..c30bf0931c --- /dev/null +++ b/Task/Web-scraping/Protium/web-scraping-1.protium @@ -0,0 +1,5 @@ +<@ DEFAREPRS>Rexx Parse +<@ DEFPRSLIT>Rexx Parse|'
' UTCtime 'UTC' +<@ LETVARURL>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl +<@ ACTRPNPRSVAR>Rexx Parse|timer +<@ SAYVAR>UTCtime diff --git a/Task/Web-scraping/Protium/web-scraping-2.protium b/Task/Web-scraping/Protium/web-scraping-2.protium new file mode 100644 index 0000000000..c92515ee74 --- /dev/null +++ b/Task/Web-scraping/Protium/web-scraping-2.protium @@ -0,0 +1,5 @@ +<# DEFINE WORKAREA PARSEVALUES>Rexx Parse +<# DEFINE PARSEVALUES LITERAL>Rexx Parse|'
' UTCtime 'UTC' +<# LET VARIABLE URLSOURCE>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl +<# ACT REPLACEBYPATTERN PARSEVALUES VARIABLE>Rexx Parse|timer +<# SAY VARIABLE>UTCtime diff --git a/Task/Web-scraping/Protium/web-scraping-3.protium b/Task/Web-scraping/Protium/web-scraping-3.protium new file mode 100644 index 0000000000..cb8fdb898f --- /dev/null +++ b/Task/Web-scraping/Protium/web-scraping-3.protium @@ -0,0 +1 @@ +<@ SAY AFT BEF URL LIT LIT LIT >http://tycho.usno.navy.mil/cgi-bin/timer.pl| UTC|
diff --git a/Task/Web-scraping/PureBasic/web-scraping.purebasic b/Task/Web-scraping/PureBasic/web-scraping.purebasic new file mode 100644 index 0000000000..c7600403ee --- /dev/null +++ b/Task/Web-scraping/PureBasic/web-scraping.purebasic @@ -0,0 +1,4 @@ +URLDownloadToFile_( #Null, "http://tycho.usno.navy.mil/cgi-bin/timer.pl", "timer.htm", 0, #Null) +ReadFile(0, "timer.htm") +While Not Eof(0) : Text$ + ReadString(0) : Wend +MessageRequester("Time", Mid(Text$, FindString(Text$, "UTC", 1) - 9 , 8)) diff --git a/Task/Web-scraping/Python/web-scraping.py b/Task/Web-scraping/Python/web-scraping.py new file mode 100644 index 0000000000..7cbd2d1f4c --- /dev/null +++ b/Task/Web-scraping/Python/web-scraping.py @@ -0,0 +1,7 @@ +import urllib +page = urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') +for line in page: + if ' UTC' in line: + print line.strip()[4:] + break +page.close() diff --git a/Task/Web-scraping/R/web-scraping-1.r b/Task/Web-scraping/R/web-scraping-1.r new file mode 100644 index 0000000000..eea70f0c11 --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-1.r @@ -0,0 +1,4 @@ +all_lines <- readLines("http://tycho.usno.navy.mil/cgi-bin/timer.pl") +utc_line <- grep("UTC", all_lines, value = TRUE) +matched <- regexpr("(\\w{3}.*UTC)", utc_line) +utc_time_str <- substring(line, matched, matched + attr(matched, "match.length") - 1L) diff --git a/Task/Web-scraping/R/web-scraping-2.r b/Task/Web-scraping/R/web-scraping-2.r new file mode 100644 index 0000000000..926ceeba9d --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-2.r @@ -0,0 +1,3 @@ +library(stringr) +utc_line <- all_lines[str_detect(all_lines, "UTC")] +utc_time_str <- str_extract(utc_line, "\\w{3}.*UTC") diff --git a/Task/Web-scraping/R/web-scraping-3.r b/Task/Web-scraping/R/web-scraping-3.r new file mode 100644 index 0000000000..c2d37f074a --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-3.r @@ -0,0 +1,2 @@ +utc_time <- strptime(utc_time_str, "%b. %d, %H:%M:%S UTC") +strftime(utc_time, "%A, %d %B %Y, %H:%M:%S") diff --git a/Task/Web-scraping/R/web-scraping-4.r b/Task/Web-scraping/R/web-scraping-4.r new file mode 100644 index 0000000000..76d2baacc9 --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-4.r @@ -0,0 +1,2 @@ +library(RCurl) +web_page <- getURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") diff --git a/Task/Web-scraping/R/web-scraping-5.r b/Task/Web-scraping/R/web-scraping-5.r new file mode 100644 index 0000000000..1cb4e830eb --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-5.r @@ -0,0 +1,5 @@ +library(XML) +page_tree <- htmlTreeParse(webpage) +times_node <- page_tree$children$html$children$body$children$h3$children$pre$children +times_node <- times_node[names(times_node) == "text"] +time_lines <- sapply(times_node, function(x) x$value) diff --git a/Task/Web-scraping/R/web-scraping-6.r b/Task/Web-scraping/R/web-scraping-6.r new file mode 100644 index 0000000000..db99048939 --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-6.r @@ -0,0 +1,4 @@ +page_tree <- htmlTreeParse(web_page, useInternalNodes = TRUE) +times_node <- xpathSApply(page_tree, "//pre")[[1]] +times_node <- times_node[names(times_node) == "text"] +time_lines <- sapply(times_node, function(x) as(x, "character")) diff --git a/Task/Web-scraping/R/web-scraping-7.r b/Task/Web-scraping/R/web-scraping-7.r new file mode 100644 index 0000000000..6e7644526c --- /dev/null +++ b/Task/Web-scraping/R/web-scraping-7.r @@ -0,0 +1,2 @@ +utc_line <- time_lines[str_detect(time_lines, "UTC")] +#etc. diff --git a/Task/Web-scraping/REBOL/web-scraping.rebol b/Task/Web-scraping/REBOL/web-scraping.rebol new file mode 100644 index 0000000000..df19e68357 --- /dev/null +++ b/Task/Web-scraping/REBOL/web-scraping.rebol @@ -0,0 +1,27 @@ +REBOL [ + Title: "Web Scraping" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/Web_Scraping +] + +; Notice that REBOL understands unquoted URL's: + +service: http://tycho.usno.navy.mil/cgi-bin/timer.pl + +; The 'read' function can read from any data scheme that REBOL knows +; about, which includes web URLs. NOTE: Depending on your security +; settings, REBOL may ask you for permission to contact the service. + +html: read service + +; I parse the HTML to find the first
(note the unquoted HTML tag +; -- REBOL understands those too), then copy the current time from +; there to the "UTC" terminator. + +; I have the "to end" in the parse rule so the parse will succeed. +; Not strictly necessary once I've got the time, but good practice. + +parse html [thru
copy current thru "UTC" to end] + +print ["Current UTC time:" current] diff --git a/Task/Web-scraping/Ruby/web-scraping-1.rb b/Task/Web-scraping/Ruby/web-scraping-1.rb new file mode 100644 index 0000000000..007abeed72 --- /dev/null +++ b/Task/Web-scraping/Ruby/web-scraping-1.rb @@ -0,0 +1,10 @@ +require "open-uri" + +open('http://tycho.usno.navy.mil/cgi-bin/timer.pl') do |p| + p.each_line do |line| + if line =~ /UTC/ + puts line.match(/ (\d{1,2}:\d{1,2}:\d{1,2}) /) + break + end + end +end diff --git a/Task/Web-scraping/Ruby/web-scraping-2.rb b/Task/Web-scraping/Ruby/web-scraping-2.rb new file mode 100644 index 0000000000..9c5cf54e69 --- /dev/null +++ b/Task/Web-scraping/Ruby/web-scraping-2.rb @@ -0,0 +1,2 @@ +require 'open-uri' +puts URI.parse('http://tycho.usno.navy.mil/cgi-bin/timer.pl').read.match(/ (\d{1,2}:\d{1,2}:\d{1,2}) UTC/)[1] diff --git a/Task/Web-scraping/Run-BASIC/web-scraping.run b/Task/Web-scraping/Run-BASIC/web-scraping.run new file mode 100644 index 0000000000..789107d553 --- /dev/null +++ b/Task/Web-scraping/Run-BASIC/web-scraping.run @@ -0,0 +1 @@ +print word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"
") diff --git a/Task/Web-scraping/Scala/web-scraping.scala b/Task/Web-scraping/Scala/web-scraping.scala new file mode 100644 index 0000000000..4158fe8625 --- /dev/null +++ b/Task/Web-scraping/Scala/web-scraping.scala @@ -0,0 +1,10 @@ +import scala.io.Source + +object WebTime extends Application { + val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + val utc = text.getLines.find(_.contains("UTC")) + utc match { + case Some(s) => println(s.substring(4)) + case _ => println("error") + } +} diff --git a/Task/Web-scraping/Scheme/web-scraping.ss b/Task/Web-scraping/Scheme/web-scraping.ss new file mode 100644 index 0000000000..a9c21ab830 --- /dev/null +++ b/Task/Web-scraping/Scheme/web-scraping.ss @@ -0,0 +1,34 @@ +; Use the regular expression module to parse the url +(use-modules (ice-9 regex) (ice-9 rdelim)) + +; Variable to store result +(define time "") + +; Set the url and parse the hostname, port, and path into variables +(define url "http://tycho.usno.navy.mil/cgi-bin/timer.pl") +(define r (make-regexp "^(http://)?([^:/]+)(:)?(([0-9])+)?(/.*)?" regexp/icase)) +(define host (match:substring (regexp-exec r url) 2)) +(define port (match:substring (regexp-exec r url) 4)) +(define path (match:substring (regexp-exec r url) 6)) + +; Set port to 80 if it wasn't set above and convert from a string to a number +(if (eq? port #f) (define port "80")) +(define port (string->number port)) + +; Connect to remote host on specified port +(let ((s (socket PF_INET SOCK_STREAM 0))) + (connect s AF_INET (car (hostent:addr-list (gethostbyname host))) port) + +; Send a HTTP request for the specified path + (display "GET " s) + (display path s) + (display " HTTP/1.0\r\n\r\n" s) + + (set! r (make-regexp "
(.+? UTC)")) + (do ((line (read-line s) (read-line s))) ((eof-object? line)) + (if (regexp-match? (regexp-exec r line)) + (set! time (match:substring (regexp-exec r line) 1))))) + +; Display result +(display time) +(newline) diff --git a/Task/Web-scraping/Seed7/web-scraping.seed7 b/Task/Web-scraping/Seed7/web-scraping.seed7 new file mode 100644 index 0000000000..72e12ba7a8 --- /dev/null +++ b/Task/Web-scraping/Seed7/web-scraping.seed7 @@ -0,0 +1,20 @@ +$ include "seed7_05.s7i"; + include "gethttp.s7i"; + +const proc: main is func + local + var string: pageWithTime is ""; + var integer: posOfUTC is 0; + var integer: posOfBR is 0; + var string: timeStri is ""; + begin + pageWithTime := getHttp("tycho.usno.navy.mil/cgi-bin/timer.pl"); + posOfUTC := pos(pageWithTime, "UTC"); + if posOfUTC <> 0 then + posOfBR := rpos(pageWithTime, "
", posOfUTC); + if posOfBR <> 0 then + timeStri := pageWithTime[posOfBR + 4 .. pred(posOfUTC)]; + writeln(timeStri); + end if; + end if; + end func; diff --git a/Task/Web-scraping/TUSCRIPT/web-scraping.tuscript b/Task/Web-scraping/TUSCRIPT/web-scraping.tuscript new file mode 100644 index 0000000000..a8d9341dfd --- /dev/null +++ b/Task/Web-scraping/TUSCRIPT/web-scraping.tuscript @@ -0,0 +1,3 @@ +$$ MODE TUSCRIPT +SET time = REQUEST ("http://tycho.usno.navy.mil/cgi-bin/timer.pl") +SET utc = FILTER (time,":*UTC*:",-) diff --git a/Task/Web-scraping/TXR/web-scraping-1.txr b/Task/Web-scraping/TXR/web-scraping-1.txr new file mode 100644 index 0000000000..3140c86324 --- /dev/null +++ b/Task/Web-scraping/TXR/web-scraping-1.txr @@ -0,0 +1,19 @@ +@(next `!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null`) + + + +What time is it? +

US Naval Observatory Master Clock Time

+@(collect :vars (MO DD HH MM SS (PM "  ") TZ TZNAME))
+
@MO. @DD, @HH:@MM:@SS @(maybe)@{PM /PM/} @(end)@TZ@/\t+/@TZNAME +@ (until) +
@/.*/ +@(end) +

US Naval Observatory + + +@(output) +@ (repeat) +@MO-@DD @HH:@MM:@SS @PM @TZ +@ (end) +@(end) diff --git a/Task/Web-scraping/TXR/web-scraping-2.txr b/Task/Web-scraping/TXR/web-scraping-2.txr new file mode 100644 index 0000000000..d8a3d96907 --- /dev/null +++ b/Task/Web-scraping/TXR/web-scraping-2.txr @@ -0,0 +1,6 @@ +@(next `!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null`) +@(skip) +
@time@\ UTC@(skip) +@(output) +@time +@(end) diff --git a/Task/Web-scraping/Tcl/web-scraping.tcl b/Task/Web-scraping/Tcl/web-scraping.tcl new file mode 100644 index 0000000000..e5b3061177 --- /dev/null +++ b/Task/Web-scraping/Tcl/web-scraping.tcl @@ -0,0 +1,6 @@ +package require http + +set request [http::geturl "http://tycho.usno.navy.mil/cgi-bin/timer.pl"] +if {[regexp -line {
(.* UTC)} [http::data $request] --> utc]} { + puts $utc +} diff --git a/Task/Web-scraping/UNIX-Shell/web-scraping.sh b/Task/Web-scraping/UNIX-Shell/web-scraping.sh new file mode 100644 index 0000000000..b8e170f026 --- /dev/null +++ b/Task/Web-scraping/UNIX-Shell/web-scraping.sh @@ -0,0 +1,3 @@ +#!/bin/sh +curl -s http://tycho.usno.navy.mil/cgi-bin/timer.pl | + sed -ne 's/^
\(.* UTC\).*$/\1/p' diff --git a/Task/Web-scraping/Ursala/web-scraping.ursala b/Task/Web-scraping/Ursala/web-scraping.ursala new file mode 100644 index 0000000000..3c5c060ac4 --- /dev/null +++ b/Task/Web-scraping/Ursala/web-scraping.ursala @@ -0,0 +1,10 @@ +#import std +#import cli + +#executable ('parameterized','') + +whatime = + +<.file$[contents: --<''>]>+ -+ + @hm skip/*4+ ~=(9%cOi&)-~l*+ *~ ~&K3/'UTC', + (ask bash)/0+ -[wget -O - http://tycho.usno.navy.mil/cgi-bin/timer.pl]-!+- diff --git a/Task/Web-scraping/Visual-Basic-.NET/web-scraping-1.visual b/Task/Web-scraping/Visual-Basic-.NET/web-scraping-1.visual new file mode 100644 index 0000000000..fb66ea1ec7 --- /dev/null +++ b/Task/Web-scraping/Visual-Basic-.NET/web-scraping-1.visual @@ -0,0 +1,12 @@ +Imports System.Net +Imports System.IO + Dim client As WebClient = New WebClient() + Dim content As String = client.DownloadString("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + Dim sr As New StringReader(content) + While sr.peek <> -1 + Dim s As String = sr.ReadLine + If s.Contains("UTC") Then + Dim time As String() = s.Substring(4).Split(vbTab) + Console.WriteLine(time(0)) + End If + End While diff --git a/Task/Web-scraping/Visual-Basic-.NET/web-scraping-2.visual b/Task/Web-scraping/Visual-Basic-.NET/web-scraping-2.visual new file mode 100644 index 0000000000..793fef0e4f --- /dev/null +++ b/Task/Web-scraping/Visual-Basic-.NET/web-scraping-2.visual @@ -0,0 +1,10 @@ +Imports System.Net + Dim client As WebClient = New WebClient() + Dim content As String = client.DownloadString("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + Dim lines() As String = Split(content, vbLf) 'may need vbCrLf + For Each line In lines + If line.Contains("UTC") Then + Dim time As String() = line.Substring(4).Split(vbTab) + Console.WriteLine(time(0)) + End If + Next diff --git a/Task/Window-creation-X11/0DESCRIPTION b/Task/Window-creation-X11/0DESCRIPTION new file mode 100644 index 0000000000..6069cd7655 --- /dev/null +++ b/Task/Window-creation-X11/0DESCRIPTION @@ -0,0 +1 @@ +Create a simple X11 application, using an X11 protocol library such as Xlib or XCB, that draws a box and "Hello World" in a window. Implementations of this task should ''avoid using a toolkit'' as much as possible. diff --git a/Task/Window-creation-X11/1META.yaml b/Task/Window-creation-X11/1META.yaml new file mode 100644 index 0000000000..4c5ed293ba --- /dev/null +++ b/Task/Window-creation-X11/1META.yaml @@ -0,0 +1,4 @@ +--- +note: GUI +requires: +- Graphics diff --git a/Task/Window-creation-X11/ALGOL-68/window-creation-x11.alg b/Task/Window-creation-X11/ALGOL-68/window-creation-x11.alg new file mode 100644 index 0000000000..0d059e85e8 --- /dev/null +++ b/Task/Window-creation-X11/ALGOL-68/window-creation-x11.alg @@ -0,0 +1,10 @@ +FILE window; +draw device (window, "X", "600x400"); +open (window, "Hello, World!", stand draw channel); + draw erase (window); + draw move (window, 0.25, 0.5); + draw colour (window, 1, 0, 0); + draw text (window, "c", "c", "hello world"); + draw show (window); + VOID (read char); +close (window) diff --git a/Task/Window-creation-X11/C/window-creation-x11-1.c b/Task/Window-creation-X11/C/window-creation-x11-1.c new file mode 100644 index 0000000000..0c8afc2468 --- /dev/null +++ b/Task/Window-creation-X11/C/window-creation-x11-1.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +int main(void) { + Display *d; + Window w; + XEvent e; + char *msg = "Hello, World!"; + int s; + + d = XOpenDisplay(NULL); + if (d == NULL) { + fprintf(stderr, "Cannot open display\n"); + exit(1); + } + + s = DefaultScreen(d); + w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1, + BlackPixel(d, s), WhitePixel(d, s)); + XSelectInput(d, w, ExposureMask | KeyPressMask); + XMapWindow(d, w); + + while (1) { + XNextEvent(d, &e); + if (e.type == Expose) { + XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10); + XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg)); + } + if (e.type == KeyPress) + break; + } + + XCloseDisplay(d); + return 0; +} diff --git a/Task/Window-creation-X11/C/window-creation-x11-2.c b/Task/Window-creation-X11/C/window-creation-x11-2.c new file mode 100644 index 0000000000..5d486864af --- /dev/null +++ b/Task/Window-creation-X11/C/window-creation-x11-2.c @@ -0,0 +1,83 @@ +#include +#include +#include + +#include + +int main () +{ + xcb_connection_t *c; + xcb_screen_t *screen; + xcb_drawable_t win; + xcb_gcontext_t foreground; + xcb_gcontext_t background; + xcb_generic_event_t *e; + uint32_t mask = 0; + uint32_t values[2]; + + char string[] = "Hello, XCB!"; + uint8_t string_len = strlen(string); + + xcb_rectangle_t rectangles[] = { + {40, 40, 20, 20}, + }; + + c = xcb_connect (NULL, NULL); + + /* get the first screen */ + screen = xcb_setup_roots_iterator (xcb_get_setup (c)).data; + + /* root window */ + win = screen->root; + + /* create black (foreground) graphic context */ + foreground = xcb_generate_id (c); + mask = XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES; + values[0] = screen->black_pixel; + values[1] = 0; + xcb_create_gc (c, foreground, win, mask, values); + + /* create white (background) graphic context */ + background = xcb_generate_id (c); + mask = XCB_GC_BACKGROUND | XCB_GC_GRAPHICS_EXPOSURES; + values[0] = screen->white_pixel; + values[1] = 0; + xcb_create_gc (c, background, win, mask, values); + + /* create the window */ + win = xcb_generate_id(c); + mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + values[0] = screen->white_pixel; + values[1] = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS; + xcb_create_window (c, /* connection */ + XCB_COPY_FROM_PARENT, /* depth */ + win, /* window Id */ + screen->root, /* parent window */ + 0, 0, /* x, y */ + 150, 150, /* width, height */ + 10, /* border_width */ + XCB_WINDOW_CLASS_INPUT_OUTPUT, /* class */ + screen->root_visual, /* visual */ + mask, values); /* masks */ + + /* map the window on the screen */ + xcb_map_window (c, win); + + xcb_flush (c); + + while ((e = xcb_wait_for_event (c))) { + switch (e->response_type & ~0x80) { + case XCB_EXPOSE: + xcb_poly_rectangle (c, win, foreground, 1, rectangles); + xcb_image_text_8 (c, string_len, win, background, 20, 20, string); + xcb_flush (c); + break; + case XCB_KEY_PRESS: + goto endloop; + } + free (e); + } + endloop: + + return 0; +} diff --git a/Task/Window-creation-X11/Common-Lisp/window-creation-x11.lisp b/Task/Window-creation-X11/Common-Lisp/window-creation-x11.lisp new file mode 100644 index 0000000000..b229ba695d --- /dev/null +++ b/Task/Window-creation-X11/Common-Lisp/window-creation-x11.lisp @@ -0,0 +1,25 @@ +;;; Single-file/interactive setup; large applications should define an ASDF system instead +(cl:require :asdf) +(asdf:operate 'asdf:load-op :clx) +(cl:defpackage #:rc-xlib-window + (:use #:cl #:xlib)) +(cl:in-package #:rc-xlib-window) + +(let ((display (open-default-display))) + (unwind-protect + (let* ((window (create-window :parent (screen-root (display-default-screen display)) + :x 10 + :y 10 + :width 100 + :height 100 + :event-mask '(:exposure :key-press))) + (gc (create-gcontext :drawable window))) + (map-window window) + (event-case (display :discard-p t) + (exposure () + (draw-rectangle window gc 20 20 10 10 t) + (draw-glyphs window gc 10 40 "Hello, World!") + nil #| continue receiving events |#) + (key-press () + t #| non-nil result signals event-case to exit |#)))) + (close-display display)) diff --git a/Task/Window-creation-X11/GUISS/window-creation-x11.guiss b/Task/Window-creation-X11/GUISS/window-creation-x11.guiss new file mode 100644 index 0000000000..de21deb2aa --- /dev/null +++ b/Task/Window-creation-X11/GUISS/window-creation-x11.guiss @@ -0,0 +1,2 @@ +Start,Programs,Applications,Editors,Leafpad,Textbox, +Type:[openbox]Hello World[pling][closebox] diff --git a/Task/Window-creation-X11/Go/window-creation-x11.go b/Task/Window-creation-X11/Go/window-creation-x11.go new file mode 100644 index 0000000000..9d64809d9c --- /dev/null +++ b/Task/Window-creation-X11/Go/window-creation-x11.go @@ -0,0 +1,60 @@ +package main + +import ( + "code.google.com/p/x-go-binding/xgb" + "fmt" +) + +func main() { + c, err := xgb.Dial("") + if err != nil { + fmt.Println(err) + return + } + defer c.Close() + + strBytes := []byte("Hello XGB!") + rectangles := []xgb.Rectangle{{40, 40, 20, 20}} + + // get the first screen + s := c.DefaultScreen() + + // root window + win := s.Root + + // create black (foreground) graphic context + fg := c.NewId() + mask := uint32(xgb.GCForeground | xgb.GCGraphicsExposures) + values := []uint32{s.BlackPixel, 0} + c.CreateGC(fg, win, mask, values) + + // create white (background) graphic context + bg := c.NewId() + mask = uint32(xgb.GCBackground | xgb.GCGraphicsExposures) + values[0] = s.WhitePixel // (values[1] still 0) + c.CreateGC(bg, win, mask, values) + + // create the window + win = c.NewId() + mask = xgb.CWBackPixel | xgb.CWEventMask + // values[0] still s.WhitePixel + values[1] = xgb.EventMaskExposure | xgb.EventMaskKeyPress + c.CreateWindow(0, win, s.Root, 0, 0, 150, 150, 10, + xgb.WindowClassInputOutput, s.RootVisual, mask, values) + c.MapWindow(win) + + for { + event, err := c.WaitForEvent() + if err != nil { + fmt.Println(err) + return + } + switch event.(type) { + case xgb.ExposeEvent: + c.PolyRectangle(win, fg, rectangles) + c.ImageText8(win, bg, 20, 20, strBytes) + case xgb.KeyPressEvent: + return + } + } +} diff --git a/Task/Window-creation-X11/Haskell/window-creation-x11.hs b/Task/Window-creation-X11/Haskell/window-creation-x11.hs new file mode 100644 index 0000000000..99f8f096b5 --- /dev/null +++ b/Task/Window-creation-X11/Haskell/window-creation-x11.hs @@ -0,0 +1,22 @@ +import Graphics.X11.Xlib +import Control.Concurrent (threadDelay) + +main = do + display <- openDisplay "" + let defScr = defaultScreen display + rw <- rootWindow display defScr + + xwin <- createSimpleWindow display rw + 0 0 400 200 1 + (blackPixel display defScr) + (whitePixel display defScr) + + setTextProperty display xwin "Rosetta Code: X11 simple window" wM_NAME + + mapWindow display xwin + + sync display False + threadDelay (5000000) + + destroyWindow display xwin + closeDisplay display diff --git a/Task/Window-creation-X11/Icon/window-creation-x11.icon b/Task/Window-creation-X11/Icon/window-creation-x11.icon new file mode 100644 index 0000000000..281328cea0 --- /dev/null +++ b/Task/Window-creation-X11/Icon/window-creation-x11.icon @@ -0,0 +1,7 @@ +procedure main() + W1 := open("X-Window","g","size=250,250","bg=black","fg=red") | stop("unable to open window") + FillRectangle(W1,50,50,150,150) + WDone(W1) +end + +link graphics diff --git a/Task/Window-creation-X11/Java/window-creation-x11-1.java b/Task/Window-creation-X11/Java/window-creation-x11-1.java new file mode 100644 index 0000000000..61335beb83 --- /dev/null +++ b/Task/Window-creation-X11/Java/window-creation-x11-1.java @@ -0,0 +1,21 @@ +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +public class WindowExample { + + public static void main(String[] args) { + Runnable runnable = new Runnable() { + public void run() { + createAndShow(); + } + }; + SwingUtilities.invokeLater(runnable); + } + + static void createAndShow() { + JFrame frame = new JFrame("Hello World"); + frame.setSize(640,480); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} diff --git a/Task/Window-creation-X11/Java/window-creation-x11-2.java b/Task/Window-creation-X11/Java/window-creation-x11-2.java new file mode 100644 index 0000000000..ac792ab9c3 --- /dev/null +++ b/Task/Window-creation-X11/Java/window-creation-x11-2.java @@ -0,0 +1,27 @@ +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.*; +import javax.swing.*; + +public class WindowExample extends JApplet { + public void paint(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + + g2.setStroke(new BasicStroke(2.0f)); + g2.drawString("Hello java", 20, 20); + g2.setPaint(Color.blue); + g2.draw(new Rectangle2D.Double(40, 40, 20, 20)); + } + + public static void main(String s[]) { + JFrame f = new JFrame("ShapesDemo2D"); + f.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) {System.exit(0);} + }); + JApplet applet = new ShapesDemo2D(); + f.getContentPane().add("Center", applet); + f.pack(); + f.setSize(new Dimension(150, 150)); + f.setVisible(true); + } +} diff --git a/Task/Window-creation-X11/OCaml/window-creation-x11.ocaml b/Task/Window-creation-X11/OCaml/window-creation-x11.ocaml new file mode 100644 index 0000000000..cdec3f486e --- /dev/null +++ b/Task/Window-creation-X11/OCaml/window-creation-x11.ocaml @@ -0,0 +1,24 @@ +open Xlib + +let () = + let d = xOpenDisplay "" in + let s = xDefaultScreen d in + let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 100 100 1 + (xBlackPixel d s) (xWhitePixel d s) in + xSelectInput d w [ExposureMask; KeyPressMask]; + xMapWindow d w; + + let msg = "Hello, World!" in + + let rec main_loop() = + match xEventType(xNextEventFun d) with + | Expose -> + xFillRectangle d w (xDefaultGC d s) 20 20 10 10; + xDrawString d w (xDefaultGC d s) 10 50 msg; + main_loop() + | KeyPress -> () (* exit main loop *) + | _ -> main_loop() + in + main_loop(); + xCloseDisplay d; +;; diff --git a/Task/Window-creation-X11/Perl/window-creation-x11.pl b/Task/Window-creation-X11/Perl/window-creation-x11.pl new file mode 100644 index 0000000000..be925c328b --- /dev/null +++ b/Task/Window-creation-X11/Perl/window-creation-x11.pl @@ -0,0 +1,45 @@ +#!/usr/bin/perl -w +use strict; +use X11::Protocol; + +my $X = X11::Protocol->new; + +my $window = $X->new_rsrc; +$X->CreateWindow ($window, + $X->root, # parent window + 'InputOutput', # class + 0, # depth, copy from parent + 0, # visual, copy from parent + 0,0, # X,Y (window manager will override) + 300,100, # width,height + 0, # border width + background_pixel => $X->black_pixel, + event_mask => $X->pack_event_mask('Exposure', + 'ButtonPress'), + ); + +my $gc = $X->new_rsrc; +$X->CreateGC ($gc, $window, + foreground => $X->white_pixel); + +$X->{'event_handler'} = sub { + my %event = @_; + my $event_name = $event{'name'}; + + if ($event_name eq 'Expose') { + $X->PolyRectangle ($window, $gc, [ 10,10, # x,y top-left corner + 30,20 ]); # width,height + $X->PolyText8 ($window, $gc, + 10, 55, # X,Y of text baseline + [ 0, # delta X + 'Hello ... click mouse button to exit.' ]); + + } elsif ($event_name eq 'ButtonPress') { + exit 0; + } +}; + +$X->MapWindow ($window); +for (;;) { + $X->handle_input; +} diff --git a/Task/Window-creation-X11/PicoLisp/window-creation-x11.l b/Task/Window-creation-X11/PicoLisp/window-creation-x11.l new file mode 100644 index 0000000000..773400e17a --- /dev/null +++ b/Task/Window-creation-X11/PicoLisp/window-creation-x11.l @@ -0,0 +1,48 @@ +#!/usr/bin/picolisp /usr/lib/picolisp/lib.l + +(load "@lib/misc.l" "@lib/gcc.l") + +(gcc "x11" '("-lX11") 'simpleWin) + +#include + +any simpleWin(any ex) { + any x = cdr(ex); + int dx, dy; + Display *disp; + int scrn; + Window win; + XEvent ev; + + x = cdr(ex), dx = (int)evCnt(ex,x); + x = cdr(x), dy = (int)evCnt(ex,x); + x = evSym(cdr(x)); + if (disp = XOpenDisplay(NULL)) { + char msg[bufSize(x)]; + + bufString(x, msg); + scrn = DefaultScreen(disp); + win = XCreateSimpleWindow(disp, RootWindow(disp,scrn), 0, 0, dx, dy, + 1, BlackPixel(disp,scrn), WhitePixel(disp,scrn) ); + XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask); + XMapWindow(disp, win); + for (;;) { + XNextEvent(disp, &ev); + switch (ev.type) { + case Expose: + XDrawRectangle(disp, win, DefaultGC(disp, scrn), 10, 10, dx-20, dy-20); + XDrawString(disp, win, DefaultGC(disp, scrn), 30, 40, msg, strlen(msg)); + break; + case KeyPress: + case ButtonPress: + XCloseDisplay(disp); + return Nil; + } + } + } + return mkStr("Can't open Display"); +} +/**/ + +(simpleWin 300 200 "Hello World") +(bye) diff --git a/Task/Window-creation-X11/Python/window-creation-x11-1.py b/Task/Window-creation-X11/Python/window-creation-x11-1.py new file mode 100644 index 0000000000..36a52f9c4b --- /dev/null +++ b/Task/Window-creation-X11/Python/window-creation-x11-1.py @@ -0,0 +1,34 @@ +from Xlib import X, display + +class Window: + def __init__(self, display, msg): + self.display = display + self.msg = msg + + self.screen = self.display.screen() + self.window = self.screen.root.create_window( + 10, 10, 100, 100, 1, + self.screen.root_depth, + background_pixel=self.screen.white_pixel, + event_mask=X.ExposureMask | X.KeyPressMask, + ) + self.gc = self.window.create_gc( + foreground = self.screen.black_pixel, + background = self.screen.white_pixel, + ) + + self.window.map() + + def loop(self): + while True: + e = self.display.next_event() + + if e.type == X.Expose: + self.window.fill_rectangle(self.gc, 20, 20, 10, 10) + self.window.draw_text(self.gc, 10, 50, self.msg) + elif e.type == X.KeyPress: + raise SystemExit + + +if __name__ == "__main__": + Window(display.Display(), "Hello, World!").loop() diff --git a/Task/Window-creation-X11/Python/window-creation-x11-2.py b/Task/Window-creation-X11/Python/window-creation-x11-2.py new file mode 100644 index 0000000000..163b9eb497 --- /dev/null +++ b/Task/Window-creation-X11/Python/window-creation-x11-2.py @@ -0,0 +1,43 @@ +import xcb +from xcb.xproto import * +import xcb.render + +def main(): + conn = xcb.connect() + conn.render = conn(xcb.render.key) + + setup = conn.get_setup() + root = setup.roots[0].root + depth = setup.roots[0].root_depth + visual = setup.roots[0].root_visual + white = setup.roots[0].white_pixel + + window = conn.generate_id() + conn.core.CreateWindow(depth, window, root, + 0, 0, 640, 480, 0, + WindowClass.InputOutput, + visual, + CW.BackPixel | CW.EventMask, + [ white, EventMask.Exposure | + EventMask.KeyPress ]) + + conn.core.MapWindow(window) + conn.flush() + + while True: + event = conn.wait_for_event() + + if isinstance(event, ExposeEvent): + color = (0, 0, 65535, 65535) + rectangle = (20, 20, 40, 40) + # TODO, fixme: + # I haven't been able to find what I should put for the parameter "op" + # conn.render.FillRectangles(op, window, color, 1, rectangle) + conn.flush() + + elif isinstance(event, KeyPressEvent): + break + + conn.disconnect() + +main() diff --git a/Task/Window-creation-X11/Tcl/window-creation-x11-1.tcl b/Task/Window-creation-X11/Tcl/window-creation-x11-1.tcl new file mode 100644 index 0000000000..6e02f94f9c --- /dev/null +++ b/Task/Window-creation-X11/Tcl/window-creation-x11-1.tcl @@ -0,0 +1,65 @@ +package provide xlib 1 +package require critcl + +critcl::clibraries -L/usr/X11/lib -lX11 +critcl::ccode { + #include + static Display *d; + static GC gc; +} + +# Display connection functions +critcl::cproc XOpenDisplay {Tcl_Interp* interp char* name} ok { + d = XOpenDisplay(name[0] ? name : NULL); + if (d == NULL) { + Tcl_AppendResult(interp, "cannot open display", NULL); + return TCL_ERROR; + } + gc = DefaultGC(d, DefaultScreen(d)); + return TCL_OK; +} +critcl::cproc XCloseDisplay {} void { + XCloseDisplay(d); +} + +# Basic window functions +critcl::cproc XCreateSimpleWindow { + int x int y int width int height int events +} int { + int s = DefaultScreen(d); + Window w = XCreateSimpleWindow(d, RootWindow(d,s), x, y, width, height, 0, + BlackPixel(d,s), WhitePixel(d,s)); + XSelectInput(d, w, ExposureMask | events); + return (int) w; +} +critcl::cproc XDestroyWindow {int w} void { + XDestroyWindow(d, (Window) w); +} +critcl::cproc XMapWindow {int w} void { + XMapWindow(d, (Window) w); +} +critcl::cproc XUnmapWindow {int w} void { + XUnmapWindow(d, (Window) w); +} + +# Event receiver +critcl::cproc XNextEvent {Tcl_Interp* interp} char* { + XEvent e; + XNextEvent(d, &e); + switch (e.type) { + case Expose: return "type expose"; + case KeyPress: return "type key"; + /* etc. This is a cheap hack version. */ + default: return "type ?"; + } +} + +# Painting functions +critcl::cproc XFillRectangle {int w int x int y int width int height} void { + XFillRectangle(d, (Window)w, gc, x, y, width, height); +} +critcl::cproc XDrawString {int w int x int y Tcl_Obj* msg} void { + int len; + const char *str = Tcl_GetStringFromObj(msg, &len); + XDrawString(d, (Window)w, gc, x, y, str, len); +} diff --git a/Task/Window-creation-X11/Tcl/window-creation-x11-2.tcl b/Task/Window-creation-X11/Tcl/window-creation-x11-2.tcl new file mode 100644 index 0000000000..868646a3d3 --- /dev/null +++ b/Task/Window-creation-X11/Tcl/window-creation-x11-2.tcl @@ -0,0 +1,11 @@ +package require xlib + +XOpenDisplay {} +set w [XCreateSimpleWindow 10 10 100 100 1] +XMapWindow $w +while {[lindex [XNextEvent] 0] == "expose"} { + XFillRectangle $w 20 20 10 10 + XDrawString $w 10 50 "Hello, World!" +} +XDestroyWindow $w +XCloseDisplay diff --git a/Task/Window-creation-X11/Tcl/window-creation-x11-3.tcl b/Task/Window-creation-X11/Tcl/window-creation-x11-3.tcl new file mode 100644 index 0000000000..43d2d6fef1 --- /dev/null +++ b/Task/Window-creation-X11/Tcl/window-creation-x11-3.tcl @@ -0,0 +1,53 @@ +package require TclOO +package provide x11 1 + +namespace eval ::x { + namespace export {[a-z]*} + namespace ensemble create + variable mask + array set mask { + KeyPress 1 + KeyRelease 2 + ButtonPress 4 + ButtonRelease 8 + } + + proc display {script} { + XOpenDisplay {} + catch {uplevel 1 $script} msg opts + XCloseDisplay + return -options $opts $msg + } + proc eventloop {var handlers} { + upvar 1 $var v + while 1 { + set v [XNextEvent] + uplevel 1 [list switch [dict get $v type] $handlers] + } + } + + oo::class create window { + variable w + constructor {x y width height events} { + set m 0 + variable ::x::mask + foreach e $events {catch {incr m $mask($e)}} + set w [XCreateSimpleWindow $x $y $width $height $m] + } + method map {} { + XMapWindow $w + } + method unmap {} { + XUnmapWindow $w + } + method fill {x y width height} { + XFillRectangle $w $x $y $width $height + } + method text {x y string} { + XDrawString $w $x $y $string + } + destructor { + XDestroyWindow $w + } + } +} diff --git a/Task/Window-creation-X11/Tcl/window-creation-x11-4.tcl b/Task/Window-creation-X11/Tcl/window-creation-x11-4.tcl new file mode 100644 index 0000000000..a13ac4403e --- /dev/null +++ b/Task/Window-creation-X11/Tcl/window-creation-x11-4.tcl @@ -0,0 +1,21 @@ +package require x11 + +# With a display connection open, create and map a window +x display { + set w [x window new 10 10 100 100 KeyPress] + $w map + + x eventloop ev { + expose { + # Paint the window + $w fill 20 20 10 10 + $w text 10 50 "Hello, World!" + } + key { + # Quit the event loop + break + } + } + + $w destroy +} diff --git a/Task/Window-creation/0DESCRIPTION b/Task/Window-creation/0DESCRIPTION new file mode 100644 index 0000000000..caee21832b --- /dev/null +++ b/Task/Window-creation/0DESCRIPTION @@ -0,0 +1 @@ +Display a [[GUI]] window. The window need not have any contents, but should respond to requests to be closed. diff --git a/Task/Window-creation/1META.yaml b/Task/Window-creation/1META.yaml new file mode 100644 index 0000000000..4c5ed293ba --- /dev/null +++ b/Task/Window-creation/1META.yaml @@ -0,0 +1,4 @@ +--- +note: GUI +requires: +- Graphics diff --git a/Task/Window-creation/ALGOL-68/window-creation.alg b/Task/Window-creation/ALGOL-68/window-creation.alg new file mode 100644 index 0000000000..82ce36d695 --- /dev/null +++ b/Task/Window-creation/ALGOL-68/window-creation.alg @@ -0,0 +1,39 @@ +PROGRAM firstgtk CONTEXT VOID +USE standard +BEGIN +MODE GDATA = REF BITS; +MODE GUINT = BITS; +MODE GSIZE = BITS; +MODE GTYPE = GSIZE; +MODE GTYPECLASS = STRUCT(GTYPE g type); +MODE GTYPEINSTANCE = STRUCT(REF GTYPECLASS g class); +MODE GTKWIDGETPRIVATE = REF BITS; + +MODE GOBJECT = STRUCT( + GTYPEINSTANCE g type instance, + GUINT ref count, + REF GDATA qdata); + +MODE GTKWIDGET = STRUCT( + GOBJECT parent instance, + REF GTKWIDGETPRIVATE priv); + +PROC(REF INT,REF CCHARPTRPTR)VOID gtk init = ALIEN "GTK_INIT" + "#define GTK_INIT(argc,argv) gtk_init(argc,argv)"; +PROC(INT)REF GTKWIDGET gtk window new = ALIEN "GTK_WINDOW_NEW" + "#define GTK_WINDOW_NEW(type) (void *)gtk_window_new(type)"; +PROC(REF GTKWIDGET)VOID gtk widget show = ALIEN "GTK_WIDGET_SHOW" + "#define GTK_WIDGET_SHOW(widget) gtk_widget_show((void *)widget)"; +PROC gtk main = VOID: CODE "gtk_main();"; + +INT gtk window toplevel = 0; +FILE argf; +REF GTKWIDGET window; + +open(argf,"",arg channel); +gtk init(argc,argv); +window:=gtk window new(gtk window toplevel); +gtk widget show(window); +gtk main +END +FINISH diff --git a/Task/Window-creation/Ada/window-creation.ada b/Task/Window-creation/Ada/window-creation.ada new file mode 100644 index 0000000000..485b9a41b3 --- /dev/null +++ b/Task/Window-creation/Ada/window-creation.ada @@ -0,0 +1,41 @@ +with Gtk.Window; use Gtk.Window; +with Gtk.Widget; use Gtk.Widget; + +with Gtk.Handlers; +with Gtk.Main; + +procedure Windowed_Application is + Window : Gtk_Window; + + package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); + package Return_Handlers is + new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean); + + function Delete_Event (Widget : access Gtk_Widget_Record'Class) + return Boolean is + begin + return False; + end Delete_Event; + + procedure Destroy (Widget : access Gtk_Widget_Record'Class) is + begin + Gtk.Main.Main_Quit; + end Destroy; + +begin + Gtk.Main.Init; + Gtk.Window.Gtk_New (Window); + Return_Handlers.Connect + ( Window, + "delete_event", + Return_Handlers.To_Marshaller (Delete_Event'Access) + ); + Handlers.Connect + ( Window, + "destroy", + Handlers.To_Marshaller (Destroy'Access) + ); + Show (Window); + + Gtk.Main.Main; +end Windowed_Application; diff --git a/Task/Window-creation/AutoHotkey/window-creation.ahk b/Task/Window-creation/AutoHotkey/window-creation.ahk new file mode 100644 index 0000000000..c8af256161 --- /dev/null +++ b/Task/Window-creation/AutoHotkey/window-creation.ahk @@ -0,0 +1,2 @@ +Gui, Add, Text,, Hello +Gui, Show diff --git a/Task/Window-creation/AutoIt/window-creation.autoit b/Task/Window-creation/AutoIt/window-creation.autoit new file mode 100644 index 0000000000..31354b386f --- /dev/null +++ b/Task/Window-creation/AutoIt/window-creation.autoit @@ -0,0 +1,9 @@ +GUICreate("Test") +GUISetState(@SW_SHOW) + +Do + Switch GUIGetMsg() + Case -3 ; $GUI_EVENT_CLOSE + Exit + EndSwitch +Until False diff --git a/Task/Window-creation/BBC-BASIC/window-creation.bbc b/Task/Window-creation/BBC-BASIC/window-creation.bbc new file mode 100644 index 0000000000..334047333f --- /dev/null +++ b/Task/Window-creation/BBC-BASIC/window-creation.bbc @@ -0,0 +1,3 @@ + INSTALL @lib$+"WINLIB2" + dlg% = FN_newdialog("GUI Window", 0, 0, 200, 150, 8, 1000) + PROC_showdialog(dlg%) diff --git a/Task/Window-creation/C++/window-creation-1.cpp b/Task/Window-creation/C++/window-creation-1.cpp new file mode 100644 index 0000000000..94a4f33500 --- /dev/null +++ b/Task/Window-creation/C++/window-creation-1.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QMainWindow window; + window.show(); + return app.exec(); +} diff --git a/Task/Window-creation/C++/window-creation-2.cpp b/Task/Window-creation/C++/window-creation-2.cpp new file mode 100644 index 0000000000..e733c2f5d2 --- /dev/null +++ b/Task/Window-creation/C++/window-creation-2.cpp @@ -0,0 +1,21 @@ +#include +#include + +int +main( int argc, char* argv[] ) +{ + try + { + Gtk::Main m( argc, argv ) ; + Gtk::Window win ; + m.run( win ) ; + } + + catch( std::exception const & exc ) + { + std::cout << exc.what() << std::endl ; + exit( -1 ) ; + } + + exit( 0 ) ; +} diff --git a/Task/Window-creation/C/window-creation-1.c b/Task/Window-creation/C/window-creation-1.c new file mode 100644 index 0000000000..52955915fb --- /dev/null +++ b/Task/Window-creation/C/window-creation-1.c @@ -0,0 +1,22 @@ +/* + * Opens an 800x600 16bit color window. + * Done here with ANSI C. + */ + +#include +#include +#include "SDL.h" + +int main() +{ + SDL_Surface *screen; + + if (SDL_Init(SDL_INIT_VIDEO) != 0) { + fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); + return 1; + } + atexit(SDL_Quit); + screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE ); + + return 0; +} diff --git a/Task/Window-creation/C/window-creation-2.c b/Task/Window-creation/C/window-creation-2.c new file mode 100644 index 0000000000..72429550ab --- /dev/null +++ b/Task/Window-creation/C/window-creation-2.c @@ -0,0 +1,16 @@ +#include + +int +main(int argc, char *argv[]) +{ + GtkWidget *window; + + gtk_init(&argc, &argv); + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_signal_connect(GTK_OBJECT(window), "destroy", + GTK_SIGNAL_FUNC(gtk_main_quit), NULL); + gtk_widget_show(window); + gtk_main(); + + return 0; +} diff --git a/Task/Window-creation/C/window-creation-3.c b/Task/Window-creation/C/window-creation-3.c new file mode 100644 index 0000000000..bb29fe3605 --- /dev/null +++ b/Task/Window-creation/C/window-creation-3.c @@ -0,0 +1,15 @@ +#include + +int +main(int argc, char *argv[]) +{ + GtkWidget *window; + + gtk_init(&argc, &argv); + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + g_signal_connect (window, "destroy", G_CALLBACK(gtk_main_quit), NULL); + gtk_widget_show(window); + gtk_main(); + + return 0; +} diff --git a/Task/Window-creation/C/window-creation-4.c b/Task/Window-creation/C/window-creation-4.c new file mode 100644 index 0000000000..b23c112633 --- /dev/null +++ b/Task/Window-creation/C/window-creation-4.c @@ -0,0 +1,40 @@ +// A C+GLUT implementation of the Creating a Window task at Rosetta Code +// http://rosettacode.org/wiki/Creating_a_Window +#include +#include + +// This function is not strictly necessary to meet the requirements of the task. +void onKeyPress(unsigned char key, int x, int y) +{ + // If you have any cleanup or such, you need to use C's + // onexit routine for registering cleanup callbacks. + exit(0); + +} + +int main(int argc, char **argv) +{ + // Pulls out any command-line arguments that are specific to GLUT, + // And leaves a command-line argument set without any of those arguments + // when it returns. + // (If you want a copy, take a copy first.) + glutInit(&argc, argv); + + // Tell GLUT we want to create a window. + // It won't *actually* be created until we call glutMainLoop below. + glutCreateWindow("Goodbye, World!"); + + // Register a callback to handle key press events (so we can quit on + // when someone hits a key) This part is not necessary to meet the + // requirements of the task. + glutKeyboardFunc(&onKeyPress); + + // Put the execution of the app in glut's hands. Most GUI environments + // involve a message loop that communicate window events. GLUT handles + // most of these with defaults, except for any we register callbacks + // for. (Like the onKeyPress above.) + glutMainLoop(); + + return 0; + +} diff --git a/Task/Window-creation/Clojure/window-creation.clj b/Task/Window-creation/Clojure/window-creation.clj new file mode 100644 index 0000000000..7f720c47a1 --- /dev/null +++ b/Task/Window-creation/Clojure/window-creation.clj @@ -0,0 +1,6 @@ +(import '(javax.swing JFrame)) + +(let [frame (JFrame. "A Window")] + (doto frame + (.setSize 600 800) + (.setVisible true))) diff --git a/Task/Window-creation/Common-Lisp/window-creation-1.lisp b/Task/Window-creation/Common-Lisp/window-creation-1.lisp new file mode 100644 index 0000000000..bc90592507 --- /dev/null +++ b/Task/Window-creation/Common-Lisp/window-creation-1.lisp @@ -0,0 +1 @@ +(capi:display (make-instance 'capi:interface :title "A Window")) diff --git a/Task/Window-creation/Common-Lisp/window-creation-2.lisp b/Task/Window-creation/Common-Lisp/window-creation-2.lisp new file mode 100644 index 0000000000..1e272b9570 --- /dev/null +++ b/Task/Window-creation/Common-Lisp/window-creation-2.lisp @@ -0,0 +1,4 @@ +(require :mcclim) +(cl:defpackage #:rc-window + (:use #:clim-lisp #:clim)) +(cl:in-package #:rc-window) diff --git a/Task/Window-creation/Common-Lisp/window-creation-3.lisp b/Task/Window-creation/Common-Lisp/window-creation-3.lisp new file mode 100644 index 0000000000..7e91d52e6b --- /dev/null +++ b/Task/Window-creation/Common-Lisp/window-creation-3.lisp @@ -0,0 +1,5 @@ +(define-application-frame rc-window () + () + (:layouts (:default))) + +(run-frame-top-level (make-application-frame 'rc-window)) diff --git a/Task/Window-creation/Common-Lisp/window-creation-4.lisp b/Task/Window-creation/Common-Lisp/window-creation-4.lisp new file mode 100644 index 0000000000..51840da664 --- /dev/null +++ b/Task/Window-creation/Common-Lisp/window-creation-4.lisp @@ -0,0 +1,7 @@ +(defun create-window () + "Creates a window" + (let ((window (jnew (jconstructor "javax.swing.JFrame")))) + (jcall (jmethod "javax.swing.JFrame" "setVisible" "boolean") + window (make-immediate-object t :boolean)))) + +(create-window) diff --git a/Task/Window-creation/D/window-creation-1.d b/Task/Window-creation/D/window-creation-1.d new file mode 100644 index 0000000000..a1471f8627 --- /dev/null +++ b/Task/Window-creation/D/window-creation-1.d @@ -0,0 +1,9 @@ + module Window; + + import fltk4d.all; + + void main() { + auto window = new Window(300, 300, "A window"); + window.show; + FLTK.run; + } diff --git a/Task/Window-creation/D/window-creation-2.d b/Task/Window-creation/D/window-creation-2.d new file mode 100644 index 0000000000..fa461f1957 --- /dev/null +++ b/Task/Window-creation/D/window-creation-2.d @@ -0,0 +1,32 @@ + import derelict.sdl.sdl; + + int main(char[][] args) + { + DerelictSDL.load(); + + SDL_Event event; + auto done = false; + + SDL_Init(SDL_INIT_VIDEO); + scope(exit) SDL_Quit(); + + SDL_SetVideoMode(1024, 768, 0, SDL_OPENGL); + SDL_WM_SetCaption("My first Window", "SDL test"); + + while (!done) + { + if (SDL_PollEvent(&event) == 1) + { + switch (event.type) + { + case SDL_QUIT: + done = true; + break; + default: + break; + } + } + } + + return 0; + } diff --git a/Task/Window-creation/D/window-creation-3.d b/Task/Window-creation/D/window-creation-3.d new file mode 100644 index 0000000000..cb81d1b4fa --- /dev/null +++ b/Task/Window-creation/D/window-creation-3.d @@ -0,0 +1,6 @@ + import qd; + + void main() { + screen(640, 480); + while (true) events(); + } diff --git a/Task/Window-creation/Delphi/window-creation-1.delphi b/Task/Window-creation/Delphi/window-creation-1.delphi new file mode 100644 index 0000000000..b3285e7ca0 --- /dev/null +++ b/Task/Window-creation/Delphi/window-creation-1.delphi @@ -0,0 +1,56 @@ +// The project file (Project1.dpr) +program Project1; + +uses + Forms, + // Include file with Window class declaration (see below) + Unit0 in 'Unit1.pas' {Form1}; + +{$R *.res} + +begin + Application.Initialize; + Application.CreateForm(TForm1, Form1); + Application.Run; +end. + + +// The Window class declaration +unit Unit1; + +interface + +uses + Forms; + +type + TForm1 = class(TForm) + end; + +var + Form1: TForm1; + +implementation + +{$R *.dfm} // The window definition resource (see below) + +end. + +// A textual rendition of the Window (form) definition file (Unit1.dfm) +object Form1: TForm1 + Left = 469 + Top = 142 + Width = 800 + Height = 600 + Caption = 'Form1' + Color = clBtnFace + Font.Charset = DEFAULT_CHARSET + Font.Color = clWindowText + Font.Height = -11 + Font.Name = 'MS Shell Dlg 2' + Font.Style = [] + OldCreateOrder = False + Position = poScreenCenter + PixelsPerInch = 96 + TextHeight = 13 +end diff --git a/Task/Window-creation/Delphi/window-creation-2.delphi b/Task/Window-creation/Delphi/window-creation-2.delphi new file mode 100644 index 0000000000..fea6ffe337 --- /dev/null +++ b/Task/Window-creation/Delphi/window-creation-2.delphi @@ -0,0 +1,63 @@ +program Project3; + +uses + Windows, + Messages; + +var + WndClass: TWndClass; + Msg: TMsg; + winT, winL: Integer; + +// Initial height/width of the window +const + winW: Integer = 800; + winH: Integer = 600; + +// Callback function to processes messages sent to the window +function WindowProc(hWnd,Msg,wParam,lParam:Integer): Integer; stdcall; +begin + // Trap the WM_DESTROY message + if (Msg = WM_DESTROY) then PostQuitMessage(0); + Result := DefWindowProc(hWnd,Msg,wParam,lParam); +end; + +begin + // Fill the WndClass structure with the window class attributes + // to be registered by the RegisterClass function + with WndClass do + begin + lpszClassName:= 'Form1'; + lpfnWndProc := @WindowProc; // Pointer to our message handling callback + style := CS_OWNDC or // Request a unique device context + CS_VREDRAW or // Redraw window when resized vertically + CS_HREDRAW; // Redraw window when resized horizontally + hInstance := hInstance; // The instance that the window procedure of this class is within + hbrBackground := HBRUSH(COLOR_BTNFACE+1); // Background colour of the window + end; + + // Register the window class for use by CreateWindow + RegisterClass(WndClass); + + // Calculate initial top and left positions of the window + winT := (GetSystemMetrics(SM_CYFULLSCREEN) - winH) div 2; + winL := (GetSystemMetrics(SM_CXFULLSCREEN) - winW) div 2; + + // Create the window + CreateWindow(WndClass.lpszClassName, // Class name + 'Form1', // Window name + WS_OVERLAPPEDWINDOW or WS_VISIBLE, // Window style + winL, // Horizontal Position (Left) + winT, // Vertical Position (Top) + winW, // Width + winH, // Height + 0, // Window parent/owner handle + 0, // Menu handle + hInstance, // Handle to application instance + nil); // Pointer to window creation data + + // Handle messages + while GetMessage(Msg,0,0,0) do + DispatchMessage(Msg); + +end. diff --git a/Task/Window-creation/Eiffel/window-creation-1.e b/Task/Window-creation/Eiffel/window-creation-1.e new file mode 100644 index 0000000000..72a4f82b0b --- /dev/null +++ b/Task/Window-creation/Eiffel/window-creation-1.e @@ -0,0 +1,19 @@ +class + APPLICATION +inherit + EV_APPLICATION +create + make_and_launch +feature {NONE} -- Initialization + make_and_launch + -- Initialize and launch application + do + default_create + create first_window + first_window.show + launch + end +feature {NONE} -- Implementation + first_window: MAIN_WINDOW + -- Main window. +end diff --git a/Task/Window-creation/Eiffel/window-creation-2.e b/Task/Window-creation/Eiffel/window-creation-2.e new file mode 100644 index 0000000000..22b189f5b4 --- /dev/null +++ b/Task/Window-creation/Eiffel/window-creation-2.e @@ -0,0 +1,51 @@ +class + MAIN_WINDOW +inherit + EV_TITLED_WINDOW + redefine + initialize + end +create + default_create +feature {NONE} -- Initialization + initialize + -- Build the interface for this window. + do + -- Call initialize in parent class EV_TITLED_WINDOW + Precursor {EV_TITLED_WINDOW} + -- Build a container for widgets for this window + build_main_container + -- Add the container to this window + extend (main_container) + -- Add `request_close_window' to the actions taken when the user clicks + -- on the cross in the title bar. + close_request_actions.extend (agent request_close_window) + -- Set the title of the window + set_title ("Rosetta Code") + -- Set the initial size of the window + set_size (400, 400) + end +feature {NONE} -- Implementation, Close event + request_close_window + -- The user wants to close the window + do + -- Destroy this window + destroy; + -- Destroy application + (create {EV_ENVIRONMENT}).application.destroy + end +feature {NONE} -- Implementation + main_container: EV_VERTICAL_BOX + -- Main container contains all widgets displayed in this window. + -- In this case a single text area. + build_main_container + -- Create and populate `main_container'. + require + main_container_not_yet_created: main_container = Void + do + create main_container + main_container.extend (create {EV_TEXT}) + ensure + main_container_created: main_container /= Void + end +end diff --git a/Task/Window-creation/Eiffel/window-creation-3.e b/Task/Window-creation/Eiffel/window-creation-3.e new file mode 100644 index 0000000000..7428b21263 --- /dev/null +++ b/Task/Window-creation/Eiffel/window-creation-3.e @@ -0,0 +1,19 @@ +class + APPLICATION +inherit + WINFORMS_FORM + rename + make as make_form + end +create + make +feature {NONE} -- Initialization + make + -- Run application. + do + -- Set window title + set_text ("Rosetta Code") + -- Launch application + {WINFORMS_APPLICATION}.run_form (Current) + end +end diff --git a/Task/Window-creation/Emacs-Lisp/window-creation.l b/Task/Window-creation/Emacs-Lisp/window-creation.l new file mode 100644 index 0000000000..bfed15ab6d --- /dev/null +++ b/Task/Window-creation/Emacs-Lisp/window-creation.l @@ -0,0 +1 @@ +(make-frame) diff --git a/Task/Window-creation/Euphoria/window-creation-1.euphoria b/Task/Window-creation/Euphoria/window-creation-1.euphoria new file mode 100644 index 0000000000..e169fcdeff --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-1.euphoria @@ -0,0 +1,5 @@ +include arwen.ew + +constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0}) + +WinMain(win, SW_NORMAL) diff --git a/Task/Window-creation/Euphoria/window-creation-2.euphoria b/Task/Window-creation/Euphoria/window-creation-2.euphoria new file mode 100644 index 0000000000..d815d258dd --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-2.euphoria @@ -0,0 +1,10 @@ +include GtkEngine.e + +constant win = create(GtkWindow) + connect(win,"destroy",quit) + set(win,"title","Simple Window") + set(win,"default size",300,100) + set(win,"position",GTK_WIN_POS_CENTER) + +show_all(win) +main() diff --git a/Task/Window-creation/Euphoria/window-creation-3.euphoria b/Task/Window-creation/Euphoria/window-creation-3.euphoria new file mode 100644 index 0000000000..20de3dab1a --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-3.euphoria @@ -0,0 +1,10 @@ +include EuWinGUI.ew + +Window("EuWinGUI window",100,100,640,480) + +-- Event loop +while True do + WaitEvent() +end while + +CloseApp(0) diff --git a/Task/Window-creation/Euphoria/window-creation-4.euphoria b/Task/Window-creation/Euphoria/window-creation-4.euphoria new file mode 100644 index 0000000000..1a956e1cb9 --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-4.euphoria @@ -0,0 +1,5 @@ +include Win32Lib.ew + +constant win = createEx( Window, "Win32Lib", 0, Default, Default, 640, 480, 0, 0 ) + +WinMain( win, Normal ) diff --git a/Task/Window-creation/Euphoria/window-creation-5.euphoria b/Task/Window-creation/Euphoria/window-creation-5.euphoria new file mode 100644 index 0000000000..4b34d874b3 --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-5.euphoria @@ -0,0 +1,5 @@ +include wxeu/wxeud.e + +constant win = create( wxFrame, {0, -1, "wxEuphoria window", -1, -1, 640, 480} ) + +wxMain( win ) diff --git a/Task/Window-creation/Factor/window-creation.factor b/Task/Window-creation/Factor/window-creation.factor new file mode 100644 index 0000000000..47370c64e7 --- /dev/null +++ b/Task/Window-creation/Factor/window-creation.factor @@ -0,0 +1,3 @@ +USING: ui ui.gadgets.labels ; + +"This is a window..."

+tH.........
+.   .
+   ...
+.   .
+Ht.. ......
+
+While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex. diff --git a/Task/Wireworld/1META.yaml b/Task/Wireworld/1META.yaml new file mode 100644 index 0000000000..fe8c0bdcea --- /dev/null +++ b/Task/Wireworld/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Cellular automata +note: Games diff --git a/Task/Wireworld/ALGOL-68/wireworld.alg b/Task/Wireworld/ALGOL-68/wireworld.alg new file mode 100644 index 0000000000..d9d9efb270 --- /dev/null +++ b/Task/Wireworld/ALGOL-68/wireworld.alg @@ -0,0 +1,122 @@ +CO +Wireworld implementation. +CO + +PROC exception = ([]STRING args)VOID:( + putf(stand error, ($"Exception"$, $", "g$, args, $l$)); + stop +); + +PROC assertion error = (STRING message)VOID:exception(("assertion error", message)); + +MODE CELL = CHAR; +MODE WORLD = FLEX[0, 0]CELL; +CELL head="H", tail="t", conductor=".", empty = " "; +STRING all states := empty; + +BOOL wrap = FALSE; # is the world round? # + +STRING nl := REPR 10; + +STRING in string := + "tH........."+nl+ + ". ."+nl+ + " ..."+nl+ + ". ."+nl+ + "Ht.. ......"+nl +; + +OP +:= = (REF FLEX[]FLEX[]CELL lines, FLEX[]CELL line)VOID:( + [UPB lines + 1]FLEX[0]CELL new lines; + new lines[:UPB lines]:=lines; + lines := new lines; + lines[UPB lines]:=line +); + +PROC read file = (REF FILE in file)WORLD: ( + # file > initial world configuration" # + FLEX[0]CELL line; + FLEX[0]FLEX[0]CELL lines; + INT upb x:=0, upb y := 0; + BEGIN + # on physical file end(in file, exit read line); # + make term(in file, nl); + FOR x TO 5 DO + get(in file, (line, new line)); + upb x := x; + IF UPB line > upb y THEN upb y := UPB line FI; + lines +:= line + OD; + exit read line: SKIP + END; + [upb x, upb y]CELL out; + FOR x TO UPB out DO + out[x,]:=lines[x]+" "*(upb y-UPB lines[x]) + OD; + out +); + +PROC new cell = (WORLD current world, INT x, y)CELL: ( + CELL istate := current world[x, y]; + IF INT pos; char in string (istate, pos, all states); pos IS REF INT(NIL) THEN + assertion error("Wireworld cell set to unknown value "+istate) FI; + IF istate = head THEN + tail + ELIF istate = tail THEN + conductor + ELIF istate = empty THEN + empty + ELSE # istate = conductor # + [][]INT dxy list = ( (-1,-1), (-1,+0), (-1,+1), + (+0,-1), (+0,+1), + (+1,-1), (+1,+0), (+1,+1) ); + INT n := 0; + FOR enum dxy TO UPB dxy list DO + []INT dxy = dxy list[enum dxy]; + IF wrap THEN + INT px = ( x + dxy[1] - 1 ) MOD 1 UPB current world + 1; + INT py = ( y + dxy[2] - 1 ) MOD 2 UPB current world + 1; + n +:= ABS (current world[px, py] = head) + ELSE + INT px = x + dxy[1]; + INT py = y + dxy[2]; + IF px >= 1 LWB current world AND px <= 1 UPB current world AND + py >= 2 LWB current world AND py <= 2 UPB current world THEN + n +:= ABS (current world[px, py] = head) + FI + FI + OD; + IF 1 <= n AND n <= 2 THEN head ELSE conductor FI + FI +); + +PROC next gen = (WORLD world)WORLD:( + # compute next generation of wireworld # + WORLD new world := world; + FOR x TO 1 UPB world DO + FOR y TO 2 UPB world DO + new world[x,y] := new cell(world, x, y) + OD + OD; + new world +); + +PROC world2string = (WORLD world) STRING:( + STRING out:=""; + FOR x TO UPB world DO + out +:= world[x,]+nl + OD; + out +); + +FILE in file; +associate(in file, in string); + +WORLD ww := read file(in file); +close(in file); + +FOR gen TO 10 DO + printf ( ($lg(-3)" "$, gen-1, $g$,"="* (2 UPB ww-4), $l$)); + print ( world2string(ww) ); + ww := next gen(ww) +OD diff --git a/Task/Wireworld/Ada/wireworld.ada b/Task/Wireworld/Ada/wireworld.ada new file mode 100644 index 0000000000..d01fb1c126 --- /dev/null +++ b/Task/Wireworld/Ada/wireworld.ada @@ -0,0 +1,66 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Wireworld is + type Cell is (' ', 'H', 't', '.'); + type Board is array (Positive range <>, Positive range <>) of Cell; + -- Perform one transition of the cellular automation + procedure Wireworld (State : in out Board) is + function "abs" (Left : Cell) return Natural is + begin + if Left = 'H' then + return 1; + else + return 0; + end if; + end "abs"; + Above : array (State'Range (2)) of Cell := (others => ' '); + Left : Cell := ' '; + Current : Cell; + begin + for I in State'First (1) + 1..State'Last (1) - 1 loop + for J in State'First (2) + 1..State'Last (2) - 1 loop + Current := State (I, J); + case Current is + when ' ' => + null; + when 'H' => + State (I, J) := 't'; + when 't' => + State (I, J) := '.'; + when '.' => + if abs Above ( J - 1) + abs Above ( J) + abs Above ( J + 1) + + abs Left + abs State (I, J + 1) + + abs State (I + 1, J - 1) + abs State (I + 1, J) + abs State (I + 1, J + 1) + in 1..2 then + State (I, J) := 'H'; + else + State (I, J) := '.'; + end if; + end case; + Above (J - 1) := Left; + Left := Current; + end loop; + end loop; + end Wireworld; + -- Print state of the automation + procedure Put (State : Board) is + begin + for I in State'First (1) + 1..State'Last (1) - 1 loop + for J in State'First (2) + 1..State'Last (2) - 1 loop + case State (I, J) is + when ' ' => Put (' '); + when 'H' => Put ('H'); + when 't' => Put ('t'); + when '.' => Put ('.'); + end case; + end loop; + New_Line; + end loop; + end Put; + Oscillator : Board := (" ", " tH ", " . .... ", " .. ", " "); +begin + for Step in 0..9 loop + Put_Line ("Step" & Integer'Image (Step) & " ---------"); Put (Oscillator); + Wireworld (Oscillator); + end loop; +end Test_Wireworld; diff --git a/Task/Wireworld/AutoIt/wireworld.autoit b/Task/Wireworld/AutoIt/wireworld.autoit new file mode 100644 index 0000000000..161ddf7a22 --- /dev/null +++ b/Task/Wireworld/AutoIt/wireworld.autoit @@ -0,0 +1,102 @@ +$ww = "" +$ww &= "tH........." & @CR +$ww &= ". . " & @CR +$ww &= " ... " & @CR +$ww &= ". . " & @CR +$ww &= "Ht.. ......" +$rows = StringSplit($ww, @CR) +$cols = StringSplit($rows[1], "") +Global $Wireworldarray[$rows[0]][$cols[0]] +For $I = 1 To $rows[0] + $cols = StringSplit($rows[$I], "") + For $k = 1 To $cols[0] + $Wireworldarray[$I - 1][$k - 1] = $cols[$k] + Next +Next +Wireworld($Wireworldarray) +Func Wireworld($array) + Local $labelarray = $array + Local $Top = 0, $Left = 0 + $hFui = GUICreate("Wireworld", UBound($array, 2) * 25, UBound($array) * 25) + For $I = 0 To UBound($array) - 1 + For $k = 0 To UBound($array, 2) - 1 + Switch $array[$I][$k] + Case "t" ; Tail + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) + Case "h" ; Head + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) + Case "." ; Conductor + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) + Case " " ; Empty + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) + EndSwitch + $Left += 25 + Next + $Left = 0 + $Top += 25 + Next + GUISetState() + Local $nextsteparray = $array + While 1 + $msg = GUIGetMsg() + $array = $nextsteparray + Sleep(250) + For $I = 0 To UBound($array) - 1 + For $k = 0 To UBound($array, 2) - 1 + If $array[$I][$k] = " " Then ContinueLoop + If $array[$I][$k] = "h" Then $nextsteparray[$I][$k] = "t" + If $array[$I][$k] = "t" Then $nextsteparray[$I][$k] = "." + If $array[$I][$k] = "." Then + $counter = 0 + If $I - 1 >= 0 Then ; Top + If $array[$I - 1][$k] = "h" Then $counter += 1 + EndIf + If $k - 1 >= 0 Then ; left + If $array[$I][$k - 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 Then ; Bottom + If $array[$I + 1][$k] = "h" Then $counter += 1 + EndIf + If $k + 1 <= UBound($array, 2) - 1 Then ;Right + If $array[$I][$k + 1] = "h" Then $counter += 1 + EndIf + If $I - 1 >= 0 And $k - 1 >= 0 Then ; left Top + If $array[$I - 1][$k - 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 And $k + 1 <= UBound($array, 2) - 1 Then ; Right Bottom + If $array[$I + 1][$k + 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 And $k - 1 >= 0 Then ;Left Bottom + If $array[$I + 1][$k - 1] = "h" Then $counter += 1 + EndIf + If $I - 1 >= 0 And $k + 1 <= UBound($array, 2) - 1 Then ; Top Right + If $array[$I - 1][$k + 1] = "h" Then $counter += 1 + EndIf + If $counter = 1 Or $counter = 2 Then $nextsteparray[$I][$k] = "h" + EndIf + Next + Next + For $I = 0 To UBound($nextsteparray) - 1 + For $k = 0 To UBound($nextsteparray, 2) - 1 + Switch $nextsteparray[$I][$k] + Case "t" ; Tail + GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) + Case "h" ; Head + GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) + Case "." ; Conductor + GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) + Case " " ; Empty + GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) + EndSwitch + $Left += 25 + Next + $Left = 0 + $Top += 25 + Next + If $msg = -3 Then Exit + WEnd +EndFunc ;==>Wireworld diff --git a/Task/Wireworld/BBC-BASIC/wireworld.bbc b/Task/Wireworld/BBC-BASIC/wireworld.bbc new file mode 100644 index 0000000000..2f357bbccc --- /dev/null +++ b/Task/Wireworld/BBC-BASIC/wireworld.bbc @@ -0,0 +1,42 @@ + Size% = 20 + DIM P&(Size%-1,Size%-1), Q&(Size%-1,Size%-1) + + VDU 23,22,Size%*8;Size%*8;64,64,16,0 + OFF + + DATA "tH........." + DATA ". . " + DATA " ... " + DATA ". . " + DATA "Ht.. ......" + + FOR Y% = 12 TO 8 STEP -1 + READ A$ + FOR X% = 1 TO LEN(A$) + P&(X%+4, Y%) = ASCMID$(A$, X%, 1) AND 15 + NEXT + NEXT Y% + + COLOUR 8,0,0,255 : REM Electron head = blue + COLOUR 4,255,0,0 : REM Electron tail = red + COLOUR 14,255,200,0 : REM Conductor orange + + REPEAT + FOR Y% = 1 TO Size%-2 + FOR X% = 1 TO Size%-2 + IF P&(X%,Y%)<>Q&(X%,Y%) GCOL P&(X%,Y%) : PLOT X%*16, Y%*16 + CASE P&(X%,Y%) OF + WHEN 0: Q&(X%,Y%) = 0 + WHEN 8: Q&(X%,Y%) = 4 + WHEN 4: Q&(X%,Y%) = 14 + WHEN 14: + T% = (P&(X%+1,Y%)=8) + (P&(X%+1,Y%+1)=8) + (P&(X%+1,Y%-1)=8) + \ + \ (P&(X%-1,Y%)=8) + (P&(X%-1,Y%+1)=8) + (P&(X%-1,Y%-1)=8) + \ + \ (P&(X%,Y%-1)=8) + (P&(X%,Y%+1)=8) + IF T%=-1 OR T%=-2 THEN Q&(X%,Y%) = 8 ELSE Q&(X%,Y%) = 14 + ENDCASE + NEXT + NEXT Y% + SWAP P&(), Q&() + WAIT 50 + UNTIL FALSE diff --git a/Task/Wireworld/C++/wireworld.cpp b/Task/Wireworld/C++/wireworld.cpp new file mode 100644 index 0000000000..963383ef8c --- /dev/null +++ b/Task/Wireworld/C++/wireworld.cpp @@ -0,0 +1,246 @@ +#include +#include +#include +#include +#include +#include +#include + +#include // for usleep + +enum cell_type { none, wire, head, tail }; + +// ***************** +// * display class * +// ***************** + +// this is just a small wrapper for the ggi interface + +class display +{ +public: + display(int sizex, int sizey, int pixsizex, int pixsizey, + ggi_color* colors); + ~display() + { + ggiClose(visual); + ggiExit(); + } + + void flush(); + bool keypressed() { return ggiKbhit(visual); } + void clear(); + void putpixel(int x, int y, cell_type c); +private: + ggi_visual_t visual; + int size_x, size_y; + int pixel_size_x, pixel_size_y; + ggi_pixel pixels[4]; +}; + +display::display(int sizex, int sizey, int pixsizex, int pixsizey, + ggi_color* colors): + pixel_size_x(pixsizex), + pixel_size_y(pixsizey) +{ + if (ggiInit() < 0) + { + std::cerr << "couldn't open ggi\n"; + exit(1); + } + + visual = ggiOpen(NULL); + if (!visual) + { + ggiPanic("couldn't open visual\n"); + } + + ggi_mode mode; + if (ggiCheckGraphMode(visual, sizex, sizey, + GGI_AUTO, GGI_AUTO, GT_4BIT, + &mode) != 0) + { + if (GT_DEPTH(mode.graphtype) < 2) // we need 4 colors! + ggiPanic("low-color displays are not supported!\n"); + } + if (ggiSetMode(visual, &mode) != 0) + { + ggiPanic("couldn't set graph mode\n"); + } + ggiAddFlags(visual, GGIFLAG_ASYNC); + + size_x = mode.virt.x; + size_y = mode.virt.y; + + for (int i = 0; i < 4; ++i) + pixels[i] = ggiMapColor(visual, colors+i); +} + +void display::flush() +{ + // set the current display frame to the one we have drawn to + ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); + + // flush the current visual + ggiFlush(visual); + + // try to set a different frame for drawing (errors are ignored; if + // setting the new frame fails, the current one will be drawn upon, + // with the only adverse effect being some flickering). + ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); +} + +void display::clear() +{ + ggiSetGCForeground(visual, pixels[0]); + ggiDrawBox(visual, 0, 0, size_x, size_y); +} + +void display::putpixel(int x, int y, cell_type cell) +{ + // this draws a logical pixel (i.e. a rectangle of size pixel_size_x + // times pixel_size_y), not a physical pixel + ggiSetGCForeground(visual, pixels[cell]); + ggiDrawBox(visual, + x*pixel_size_x, y*pixel_size_y, + pixel_size_x, pixel_size_y); +} + +// ***************** +// * the wireworld * +// ***************** + +// initialized to an empty wireworld +class wireworld +{ +public: + void set(int posx, int posy, cell_type type); + void draw(display& destination); + void step(); +private: + typedef std::pair position; + typedef std::set position_set; + typedef position_set::iterator positer; + position_set wires, heads, tails; +}; + +void wireworld::set(int posx, int posy, cell_type type) +{ + position p(posx, posy); + wires.erase(p); + heads.erase(p); + tails.erase(p); + switch(type) + { + case head: + heads.insert(p); + break; + case tail: + tails.insert(p); + break; + case wire: + wires.insert(p); + break; + } +} + +void wireworld::draw(display& destination) +{ + destination.clear(); + for (positer i = heads.begin(); i != heads.end(); ++i) + destination.putpixel(i->first, i->second, head); + for (positer i = tails.begin(); i != tails.end(); ++i) + destination.putpixel(i->first, i->second, tail); + for (positer i = wires.begin(); i != wires.end(); ++i) + destination.putpixel(i->first, i->second, wire); + destination.flush(); +} + +void wireworld::step() +{ + std::map new_heads; + for (positer i = heads.begin(); i != heads.end(); ++i) + for (int dx = -1; dx <= 1; ++dx) + for (int dy = -1; dy <= 1; ++dy) + { + position pos(i->first + dx, i->second + dy); + if (wires.count(pos)) + new_heads[pos]++; + } + wires.insert(tails.begin(), tails.end()); + tails.swap(heads); + heads.clear(); + for (std::map::iterator i = new_heads.begin(); + i != new_heads.end(); + ++i) + { +// std::cout << i->second; + if (i->second < 3) + { + wires.erase(i->first); + heads.insert(i->first); + } + } +} + +ggi_color colors[4] = + {{ 0x0000, 0x0000, 0x0000 }, // background: black + { 0x8000, 0x8000, 0x8000 }, // wire: white + { 0xffff, 0xffff, 0x0000 }, // electron head: yellow + { 0xffff, 0x0000, 0x0000 }}; // electron tail: red + +int main(int argc, char* argv[]) +{ + int display_x = 800; + int display_y = 600; + int pixel_x = 5; + int pixel_y = 5; + + if (argc < 2) + { + std::cerr << "No file name given!\n"; + return 1; + } + + // assume that the first argument is the name of a file to parse + std::ifstream f(argv[1]); + wireworld w; + std::string line; + int line_number = 0; + while (std::getline(f, line)) + { + for (int col = 0; col < line.size(); ++col) + { + switch (line[col]) + { + case 'h': case 'H': + w.set(col, line_number, head); + break; + case 't': case 'T': + w.set(col, line_number, tail); + break; + case 'w': case 'W': case '.': + w.set(col, line_number, wire); + break; + default: + std::cerr << "unrecognized character: " << line[col] << "\n"; + return 1; + case ' ': + ; // no need to explicitly set this, so do nothing + } + } + ++line_number; + } + + display d(display_x, display_y, pixel_x, pixel_y, colors); + + w.draw(d); + + while (!d.keypressed()) + { + usleep(100000); + w.step(); + w.draw(d); + } + std::cout << std::endl; +} diff --git a/Task/Wireworld/C/wireworld.c b/Task/Wireworld/C/wireworld.c new file mode 100644 index 0000000000..cd6e49ec63 --- /dev/null +++ b/Task/Wireworld/C/wireworld.c @@ -0,0 +1,63 @@ +/* 2009-09-27 */ +#define ANIMATE_VT100_POSIX +#include +#include +#ifdef ANIMATE_VT100_POSIX +#include +#endif + +char world_7x14[2][512] = { + { + "+-----------+\n" + "|tH.........|\n" + "|. . |\n" + "| ... |\n" + "|. . |\n" + "|Ht.. ......|\n" + "+-----------+\n" + } +}; + +void next_world(const char *in, char *out, int w, int h) +{ + int i; + + for (i = 0; i < w*h; i++) { + switch (in[i]) { + case ' ': out[i] = ' '; break; + case 't': out[i] = '.'; break; + case 'H': out[i] = 't'; break; + case '.': { + int hc = (in[i-w-1] == 'H') + (in[i-w] == 'H') + (in[i-w+1] == 'H') + + (in[i-1] == 'H') + (in[i+1] == 'H') + + (in[i+w-1] == 'H') + (in[i+w] == 'H') + (in[i+w+1] == 'H'); + out[i] = (hc == 1 || hc == 2) ? 'H' : '.'; + break; + } + default: + out[i] = in[i]; + } + } + out[i] = in[i]; +} + +int main() +{ + int f; + + for (f = 0; ; f = 1 - f) { +#ifdef ANIMATE_VT100_POSIX + puts("\x1b[H"); +#endif + puts(world_7x14[f]); + next_world(world_7x14[f], world_7x14[1-f], 14, 7); +#ifdef ANIMATE_VT100_POSIX + { + static const struct timespec ts = { 0, 100000000 }; + nanosleep(&ts, 0); + } +#endif + } + + return 0; +} diff --git a/Task/Wireworld/Common-Lisp/wireworld.lisp b/Task/Wireworld/Common-Lisp/wireworld.lisp new file mode 100644 index 0000000000..40309e03dd --- /dev/null +++ b/Task/Wireworld/Common-Lisp/wireworld.lisp @@ -0,0 +1,65 @@ +(defun electron-neighbors (wireworld row col) + (destructuring-bind (rows cols) (array-dimensions wireworld) + (loop for off-row from (max 0 (1- row)) to (min (1- rows) (1+ row)) sum + (loop for off-col from (max 0 (1- col)) to (min (1- cols) (1+ col)) count + (and (not (and (= off-row row) (= off-col col))) + (eq 'electron-head (aref wireworld off-row off-col))))))) + +(defun wireworld-next-generation (wireworld) + (destructuring-bind (rows cols) (array-dimensions wireworld) + (let ((backing (make-array (list rows cols)))) + (do ((c 0 (if (= c (1- cols)) 0 (1+ c))) + (r 0 (if (= c (1- cols)) (1+ r) r))) + ((= r rows)) + (setf (aref backing r c) (aref wireworld r c))) + (do ((c 0 (if (= c (1- cols)) 0 (1+ c))) + (r 0 (if (= c (1- cols)) (1+ r) r))) + ((= r rows)) + (setf (aref wireworld r c) + (case (aref backing r c) + (electron-head 'electron-tail) + (electron-tail 'conductor) + (conductor (case (electron-neighbors backing r c) + ((1 2) 'electron-head) + (otherwise 'conductor))) + (otherwise nil))))))) + +(defun print-wireworld (wireworld) + (destructuring-bind (rows cols) (array-dimensions wireworld) + (do ((r 0 (1+ r))) + ((= r rows)) + (do ((c 0 (1+ c))) + ((= c cols)) + (format t "~C" (case (aref wireworld r c) + (electron-head #\H) + (electron-tail #\t) + (conductor #\.) + (otherwise #\Space)))) + (format t "~&")))) + +(defun wireworld-show-gens (wireworld n) + (dotimes (m n) + (terpri) + (wireworld-next-generation wireworld) + (print-wireworld wireworld))) + +(defun ww-char-to-symbol (char) + (ecase char + (#\Space 'nil) + (#\. 'conductor) + (#\t 'electron-tail) + (#\H 'electron-head))) + +(defun make-wireworld (image) + "Make a wireworld grid from a list of strings (rows) of equal length +(columns), each character being ' ', '.', 'H', or 't'." + (make-array (list (length image) (length (first image))) + :initial-contents + (mapcar (lambda (s) (map 'list #'ww-char-to-symbol s)) image))) + +(defun make-rosetta-wireworld () + (make-wireworld '("tH........." + ". . " + " ... " + ". . " + "Ht.. ......"))) diff --git a/Task/Wireworld/D/wireworld.d b/Task/Wireworld/D/wireworld.d new file mode 100644 index 0000000000..a4b2eb0ebe --- /dev/null +++ b/Task/Wireworld/D/wireworld.d @@ -0,0 +1,38 @@ +import std.stdio, std.algorithm; + +void wireworldStep(char[][] W1, char[][] W2) pure nothrow { + foreach (r; 1 .. W1.length - 1) + foreach (c; 1 .. W1[0].length - 1) + switch (W1[r][c]) { + case 'H': W2[r][c] = 't'; break; + case 't': W2[r][c] = '.'; break; + case '.': + int nH = 0; + foreach (sr; -1 .. 2) + foreach (sc; -1 .. 2) + nH += W1[r + sr][c + sc] == 'H'; + W2[r][c] = (nH == 1 || nH == 2) ? 'H' : '.'; + break; + default: + } +} + +void main() { + auto world = [" ".dup, + " tH ".dup, + " . .... ".dup, + " .. ".dup, + " ".dup]; + + char[][] world2; + foreach (row; world) + world2 ~= row.dup; + + foreach (step; 0 .. 7) { + writefln("\nStep %d: ------------", step); + foreach (row; world[1 .. $-1]) + writeln(row[1 .. $-1]); + wireworldStep(world, world2); + swap(world, world2); + } +} diff --git a/Task/Wireworld/Forth/wireworld.fth b/Task/Wireworld/Forth/wireworld.fth new file mode 100644 index 0000000000..156f340e9d --- /dev/null +++ b/Task/Wireworld/Forth/wireworld.fth @@ -0,0 +1,81 @@ +16 constant w + 8 constant h + +: rows w * 2* ; +1 rows constant row +h rows constant size + +create world size allot +world value old +old w + value new + +: init world size erase ; +: age new old to new to old ; + +: foreachrow ( xt -- ) + size 0 do I over execute row +loop drop ; + +0 constant EMPTY +1 constant HEAD +2 constant TAIL +3 constant WIRE +create cstate bl c, char H c, char t c, char . c, + +: showrow ( i -- ) cr + old + w over + swap do I c@ cstate + c@ emit loop ; +: show ['] showrow foreachrow ; + + +: line ( row addr len -- ) + bounds do + i c@ + case + bl of EMPTY over c! endof + 'H of HEAD over c! endof + 't of TAIL over c! endof + '. of WIRE over c! endof + endcase + 1+ + loop drop ; + +: load ( filename -- ) + r/o open-file throw + init old row + 1+ ( file row ) + begin over pad 80 rot read-line throw + while over pad rot line + row + + repeat + 2drop close-file throw + show cr ; + + +: +head ( sum i -- sum ) + old + c@ HEAD = if 1+ then ; +: conductor ( i WIRE -- i HEAD|WIRE ) + drop 0 + over 1- row - +head + over row - +head + over 1+ row - +head + over 1- +head + over 1+ +head + over 1- row + +head + over row + +head + over 1+ row + +head + 1 3 within if HEAD else WIRE then ; + +\ before: empty head tail wire + +create transition ' noop , ' 1+ , ' 1+ , ' conductor , + +\ after: empty tail wire head|wire + +: new-state ( i -- ) + dup old + c@ + dup cells transition + @ execute + swap new + c! ; + +: newrow ( i -- ) + w over + swap do I new-state loop ; +: gen ['] newrow foreachrow age ; + +: wireworld begin gen 0 0 at-xy show key? until ; diff --git a/Task/Wireworld/Fortran/wireworld.f b/Task/Wireworld/Fortran/wireworld.f new file mode 100644 index 0000000000..74a15e44be --- /dev/null +++ b/Task/Wireworld/Fortran/wireworld.f @@ -0,0 +1,85 @@ +program Wireworld + implicit none + + integer, parameter :: max_generations = 12 + integer :: nrows = 0, ncols = 0, maxcols = 0 + integer :: gen, ierr = 0 + integer :: i, j + character(1), allocatable :: cells(:,:) + character(10) :: form, sub + character(80) :: buff + +! open input file + open(unit=8, file="wwinput.txt") + +! find numbers of rows and columns in data + do + read(8, "(a)", iostat=ierr) buff + if(ierr /= 0) exit + nrows = nrows + 1 + ncols = len_trim(buff) + if(ncols > maxcols) maxcols = ncols + end do + +! allcate enough space to hold the data + allocate(cells(0:nrows+1, 0:maxcols+1)) + cells = " " + +! load data + rewind(8) + do i = 1, nrows + read(8, "(a)", iostat=ierr) buff + if(ierr /= 0) exit + do j = 1, maxcols + cells(i, j) = buff(j:j) + end do + end do + close(8) + +! calculate format string for write statement + write(sub, "(i8)") maxcols + form = "(" // trim(adjustl(sub)) // "a1)" + + do gen = 0, max_generations + write(*, "(/a, i0)") "Generation ", gen + do i = 1, nrows + write(*, form) cells(i, 1:maxcols) + end do + call nextgen(cells) + end do + deallocate(cells) + + contains + + subroutine Nextgen(cells) + character, intent(in out) :: cells(0:,0:) + character :: buffer(0:size(cells, 1)-1, 0:size(cells, 2)-1) + integer :: i, j, h + + buffer = cells ! Store current status + do i = 1, size(cells, 1)-2 + do j = 1, size(cells, 2)-2 + select case (buffer(i, j)) + case(" ") + ! no Change + + case("H") + ! If a head change to tail + cells(i, j) = "t" + + case("t") + ! if a tail change to conductor + cells(i, j) = "." + + case (".") + ! Count number of electron heads in surrounding eight cells. + ! We can ignore that fact that we count the centre cell as + ! well because we already know it contains a conductor. + ! If surrounded by 1 or 2 heads change to a head + h = sum(count(buffer(i-1:i+1, j-1:j+1) == "H", 1)) + if(h == 1 .or. h == 2) cells(i, j) = "H" + end select + end do + end do + end subroutine Nextgen +end program Wireworld diff --git a/Task/Wireworld/Go/wireworld.go b/Task/Wireworld/Go/wireworld.go new file mode 100644 index 0000000000..eda61e0afa --- /dev/null +++ b/Task/Wireworld/Go/wireworld.go @@ -0,0 +1,90 @@ +package main + +import ( + "bytes" + "fmt" + "io/ioutil" + "strings" +) + +var rows, cols int // extent of input configuration +var rx, cx int // grid extent (includes border) +var mn []int // offsets of moore neighborhood + +func main() { + // read input configuration from file + src, err := ioutil.ReadFile("ww.config") + if err != nil { + fmt.Println(err) + return + } + srcRows := bytes.Split(src, []byte{'\n'}) + + // compute package variables + rows = len(srcRows) + for _, r := range srcRows { + if len(r) > cols { + cols = len(r) + } + } + rx, cx = rows+2, cols+2 + mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1} + + // allocate two grids and copy input into first grid + odd := make([]byte, rx*cx) + even := make([]byte, rx*cx) + for ri, r := range srcRows { + copy(odd[(ri+1)*cx+1:], r) + } + + // run + for { + print(odd) + step(even, odd) + fmt.Scanln() + + print(even) + step(odd, even) + fmt.Scanln() + } +} + +func print(grid []byte) { + fmt.Println(strings.Repeat("__", cols)) + fmt.Println() + for r := 1; r <= rows; r++ { + for c := 1; c <= cols; c++ { + if grid[r*cx+c] == 0 { + fmt.Print(" ") + } else { + fmt.Printf(" %c", grid[r*cx+c]) + } + } + fmt.Println() + } +} + +func step(dst, src []byte) { + for r := 1; r <= rows; r++ { + for c := 1; c <= cols; c++ { + x := r*cx + c + dst[x] = src[x] + switch dst[x] { + case 'H': + dst[x] = 't' + case 't': + dst[x] = '.' + case '.': + var nn int + for _, n := range mn { + if src[x+n] == 'H' { + nn++ + } + } + if nn == 1 || nn == 2 { + dst[x] = 'H' + } + } + } + } +} diff --git a/Task/Wireworld/Haskell/wireworld-1.hs b/Task/Wireworld/Haskell/wireworld-1.hs new file mode 100644 index 0000000000..36fc2fc11a --- /dev/null +++ b/Task/Wireworld/Haskell/wireworld-1.hs @@ -0,0 +1,21 @@ +import Data.List +import Control.Monad +import Control.Arrow +import Data.Maybe + +states=" Ht." +shiftS=" t.." + +borden bc xs = bs: (map (\x -> bc:(x++[bc])) xs) ++ [bs] + where r = length $ head xs + bs = replicate (r+2) bc + +take3x3 = ap ((.). taken. length) (taken. length. head) `ap` borden '*' + where taken n = transpose. map (take n.map (take 3)).map tails + +nwState xs | e =='.' && noH>0 && noH<3 = 'H' + | otherwise = shiftS !! (fromJust $ elemIndex e states) + where e = xs!!1!!1 + noH = length $ filter (=='H') $ concat xs + +runCircuit = iterate (map(map nwState).take3x3) diff --git a/Task/Wireworld/Haskell/wireworld-2.hs b/Task/Wireworld/Haskell/wireworld-2.hs new file mode 100644 index 0000000000..4287dcc0b2 --- /dev/null +++ b/Task/Wireworld/Haskell/wireworld-2.hs @@ -0,0 +1,6 @@ +oscillator= [" tH ", + ". ....", + " .. " + ] + +example = mapM_ (mapM_ putStrLn) .map (borden ' ').take 9 $ runCircuit oscillator diff --git a/Task/Wireworld/Icon/wireworld.icon b/Task/Wireworld/Icon/wireworld.icon new file mode 100644 index 0000000000..6321de8998 --- /dev/null +++ b/Task/Wireworld/Icon/wireworld.icon @@ -0,0 +1,92 @@ +link graphics + +$define EDGE -1 +$define EMPTY 0 +$define HEAD 1 +$define TAIL 2 +$define COND 3 + +global Colours,Width,Height,World,oldWorld + +procedure main() # wire world modified from forestfire + + Height := 400 # Window height + Width := 400 # Window width + Rounds := 500 # max Rounds + Delay := 5 # Runout Delay + + setup_world(read_world()) + every round := 1 to Rounds do { + show_world() + if \runout then + delay(Delay) + else + case Event() of { + "q" : break # q = quit + "r" : runout := 1 # r = run w/o stepping + "s" : WriteImage("Wireworld-"||round) # save + } + evolve_world() + } + WDone() +end + +procedure read_world() #: for demo in place of reading + return [ "tH.........", + ". .", + " ...", + ". .", + "Ht.. ......"] +end + +procedure setup_world(L) #: setup the world + + Colours := table() # define colours + Colours[EDGE] := "grey" + Colours[EMPTY] := "black" + Colours[HEAD] := "blue" + Colours[TAIL] := "red" + Colours[COND] := "yellow" + + States := table() + States["t"] := TAIL + States["H"] := HEAD + States[" "] := EMPTY + States["."] := COND + + WOpen("label=Wireworld", "bg=black", + "size=" || Width+2 || "," || Height+2) | # add for border + stop("Unable to open Window") + every !(World := list(Height)) := list(Width,EMPTY) # default + every ( World[1,1 to Width] | World[Height,1 to Width] | + World[1 to Height,1] | World[1 to Height,Width] ) := EDGE + + every r := 1 to *L & c := 1 to *L[r] do { # setup read in program + World[r+1, c+1] := States[L[r,c]] + } +end + +procedure show_world() #: show World - drawn changes only + every r := 2 to *World-1 & c := 2 to *World[r]-1 do + if /oldWorld | oldWorld[r,c] ~= World[r,c] then { + WAttrib("fg=" || Colours[tr := World[r,c]]) + DrawPoint(r,c) + } +end + +procedure evolve_world() #: evolve world + old := oldWorld := list(*World) # freeze copy + every old[i := 1 to *World] := copy(World[i]) # deep copy + + every r := 2 to *World-1 & c := 2 to *World[r]-1 do + World[r,c] := case old[r,c] of { # apply rules + # EMPTY : EMPTY + HEAD : TAIL + TAIL : COND + COND : { + i := 0 + every HEAD = ( old[r-1,c-1 to c+1] | old[r,c-1|c+1] | old[r+1,c-1 to c+1] ) do i +:= 1 + if i := 1 | 2 then HEAD + } + } +end diff --git a/Task/Wireworld/J/wireworld-1.j b/Task/Wireworld/J/wireworld-1.j new file mode 100644 index 0000000000..c51bc1ab85 --- /dev/null +++ b/Task/Wireworld/J/wireworld-1.j @@ -0,0 +1,7 @@ +circ0=:}: ] ;. _1 LF, 0 : 0 +tH........ +. . + ... +. . +Ht.. ..... +) diff --git a/Task/Wireworld/J/wireworld-2.j b/Task/Wireworld/J/wireworld-2.j new file mode 100644 index 0000000000..facb511328 --- /dev/null +++ b/Task/Wireworld/J/wireworld-2.j @@ -0,0 +1,7 @@ +board=: ' ' ,.~ ' ' ,. ' ' , ' ' ,~ ] + +nwS=: 3 : 0 + e=. (<1 1){y + if. ('.'=e)*. e.&1 2 +/'H'=,y do. 'H' return. end. + ' t..' {~ ' Ht.' i. e +) diff --git a/Task/Wireworld/J/wireworld-3.j b/Task/Wireworld/J/wireworld-3.j new file mode 100644 index 0000000000..736fccb3cb --- /dev/null +++ b/Task/Wireworld/J/wireworld-3.j @@ -0,0 +1,2 @@ + process=: (3 3 nwS;. _3 board)^: +(<10) process circuit diff --git a/Task/Wireworld/J/wireworld-4.j b/Task/Wireworld/J/wireworld-4.j new file mode 100644 index 0000000000..8d2f514e99 --- /dev/null +++ b/Task/Wireworld/J/wireworld-4.j @@ -0,0 +1,2 @@ +require'viewmat' +viewmat"2 ' .tH'i. (<10) process circ0 diff --git a/Task/Wireworld/Liberty-BASIC/wireworld.liberty b/Task/Wireworld/Liberty-BASIC/wireworld.liberty new file mode 100644 index 0000000000..f891229541 --- /dev/null +++ b/Task/Wireworld/Liberty-BASIC/wireworld.liberty @@ -0,0 +1,129 @@ +WindowWidth = 840 +WindowHeight = 600 + +dim p$( 40, 25), q$( 40, 25) + +empty$ = " " ' white +tail$ = "t" ' yellow +head$ = "H" ' black +conductor$ = "." ' red + +jScr = 0 + +nomainwin + +menu #m, "File", "Load", [load], "Quit", [quit] + +open "wire world" for graphics_nf_nsb as #m + #m "trapclose [quit]" + 'timer 1000, [tmr] + wait + +end + +[quit] + close #m + end + +[load] + 'timer 0 + filedialog "Open WireWorld File", "*.ww", file$ + open file$ for input as #in + y =0 + while not( eof( #in)) + line input #in, lijn$ + ' print "|"; lijn$; "|" + for x =0 to len( lijn$) -1 + p$( x, y) =mid$( lijn$, x +1, 1) + + select case p$( x, y) + case " " + clr$ ="white" + case "t" + clr$ ="yellow" + case "H" + clr$ ="black" + case "." + clr$ ="red" + end select + + #m "goto " ; 4 +x *20; " "; 4 +y *20 + #m "backcolor "; clr$ + #m "down" + #m "boxfilled "; 4 +x *20 +19; " "; 4 +y *20 +19 + #m "up ; flush" + next x + y =y +1 + wend + close #in + 'notice "Ready to run." + timer 1000, [tmr] + wait + +[tmr] + timer 0 + scan + + for x =0 to 40 ' copy temp array /current array + for y =0 to 25 + q$( x, y) =p$( x, y) + next y + next x + + for y =0 to 25 + for x =0 to 40 + select case q$( x, y) + case head$ ' heads ( black) become tails ( yellow) + p$( x, y ) =tail$ + clr$ ="yellow" + + case tail$ ' tails ( yellow) become conductors ( red) + p$( x, y ) =conductor$ + clr$ ="red" + + case conductor$ ' + hCnt =0 + + xL =x -1: if xL < 0 then xL =40 ' wrap-round edges at all four sides + xR =x +1: if xR >40 then xR = 0 + yA =y -1: if yA < 0 then yA =25 + yB =y +1: if yB >40 then yB = 0 + + if q$( xL, y ) =head$ then hCnt =hCnt +1 ' Moore environment- 6 neighbours + if q$( xL, yA) =head$ then hCnt =hCnt +1 ' count all neighbours currently heads + if q$( xL, yB) =head$ then hCnt =hCnt +1 + + if q$( xR, y ) =head$ then hCnt =hCnt +1 + if q$( xR, yA) =head$ then hCnt =hCnt +1 + if q$( xR, yB) =head$ then hCnt =hCnt +1 + + if q$( x, yA) =head$ then hCnt =hCnt +1 + if q$( x, yB) =head$ then hCnt =hCnt +1 + + if ( hCnt =1) or ( hCnt =2) then ' conductor ( red) becomes head ( yellow) in this case only + p$( x, y ) =head$ ' otherwise stays conductor ( red). + clr$ ="black" + else + p$( x, y ) =conductor$ + clr$ ="red" + end if + + case else + clr$ ="white" + end select + + #m "goto " ; 4 +x *20; " "; 4 +y *20 + #m "backcolor "; clr$ + #m "down" + #m "boxfilled "; 4 +x *20 +19; " "; 4 +y *20 +19 + #m "up" + next x + next y + #m "flush" + #m "getbmp scr 0 0 400 300" + + 'bmpsave "scr", "R:\scrJHF" +right$( "000" +str$( jScr), 3) +".bmp" + jScr =jScr+1 + if jScr >20 then wait + timer 1000, [tmr] +wait diff --git a/Task/Wireworld/Logo/wireworld.logo b/Task/Wireworld/Logo/wireworld.logo new file mode 100644 index 0000000000..86eb6debe8 --- /dev/null +++ b/Task/Wireworld/Logo/wireworld.logo @@ -0,0 +1,69 @@ +to wireworld :filename :speed ;speed in n times per second, approximated +Make "speed 60/:speed +wireworldread :filename +Make "bufferfield (mdarray (list :height :width) 0) +for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :bufferfield mditem (list :i :j) :field]] +pu ht +Make "gen 0 +while ["true] [ ;The user will have to halt it :P + ;clean + seth 90 + setxy 0 20 + ;label :gen + sety 0 + for [i 0 :height-1] [for [j 0 :width-1] [mdsetitem (list :i :j) :field mditem (list :i :j) :bufferfield]] + for [i 0 :height-1] [ + for [j 0 :width-1] [ + if (mditem (list :i :j) :field)=[] [setpixel [255 255 255]] ;blank + if (mditem (list :i :j) :field)=1 [setpixel [0 0 0] if wn :j :i 2 [mdsetitem (list :i :j) :bufferfield 2]] ;wire + if (mditem (list :i :j) :field)=2 [setpixel [0 0 255] mdsetitem (list :i :j) :bufferfield 3] ;head + if (mditem (list :i :j) :field)=3 [setpixel [255 0 0] mdsetitem (list :i :j) :bufferfield 1] ;tail + setx xcor+1 + ] + setxy 0 ycor-1 + ] + Make "gen :gen+1 + wait :speed +] +end + +to wireworldread :filename +local [line] +openread :filename +setread :filename +Make "width 0 +Make "height 0 +; first pass, take dimensions +while [not eofp] [ + Make "line readword + if (count :line)>:width [Make "width count :line] + Make "height :height+1 +] +; second pass, load data +setreadpos 0 +Make "field (mdarray (list :height :width) 0) +for [i 0 :height-1] [ + Make "line readword + foreach :line [ + if ?=char 32 [mdsetitem (list :i #-1) :field []] + if ?=". [mdsetitem (list :i #-1) :field 1] + if ?="H [mdsetitem (list :i #-1) :field 2] + if ?="t [mdsetitem (list :i #-1) :field 3] + ] +] +setread [] +close :filename +end + +to wn :x :y :thing ;WireNeighbourhood +Make "neighbours 0 +if (mditem (list :y-1 :x) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y-1 :x+1) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y :x+1) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y+1 :x+1) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y+1 :x) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y+1 :x-1) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y :x-1) :field)=:thing [Make "neighbours :neighbours+1] +if (mditem (list :y-1 :x-1) :field)=:thing [Make "neighbours :neighbours+1] +ifelse OR :neighbours=1 :neighbours=2 [op "true] [op "false] +end diff --git a/Task/Wireworld/Mathematica/wireworld.math b/Task/Wireworld/Mathematica/wireworld.math new file mode 100644 index 0000000000..4b2970e8b3 --- /dev/null +++ b/Task/Wireworld/Mathematica/wireworld.math @@ -0,0 +1,14 @@ +DynamicModule[{data = + ArrayPad[PadRight[Characters /@ StringSplit["tH......... + . . + ... + . . + Ht.. ......", "\n"]] /. {" " -> 0, "t" -> 2, "H" -> 1, + "." -> 3}, 1]}, + Dynamic@ArrayPlot[ + data = CellularAutomaton[{{{_, _, _}, {_, 0, _}, {_, _, _}} -> + 0, {{_, _, _}, {_, 1, _}, {_, _, _}} -> + 2, {{_, _, _}, {_, 2, _}, {_, _, _}} -> + 3, {{a_, b_, c_}, {d_, 3, e_}, {f_, g_, h_}} :> + Switch[Count[{a, b, c, d, e, f, g, h}, 1], 1, 1, 2, 1, _, 3]}, + data], ColorRules -> {1 -> Yellow, 2 -> Red}]] diff --git a/Task/Wireworld/OCaml/wireworld.ocaml b/Task/Wireworld/OCaml/wireworld.ocaml new file mode 100644 index 0000000000..a04feea458 --- /dev/null +++ b/Task/Wireworld/OCaml/wireworld.ocaml @@ -0,0 +1,56 @@ +let w = [| + " ......tH "; + " . ...... "; + " ...Ht... . "; + " .... "; + " . ..... "; + " .... "; + " tH...... . "; + " . ...... "; + " ...Ht... "; + |] + +let is_head w x y = + try if w.(x).[y] = 'H' then 1 else 0 + with _ -> 0 + +let neighborhood_heads w x y = + let n = ref 0 in + for _x = pred x to succ x do + for _y = pred y to succ y do + n := !n + (is_head w _x _y) + done; + done; + (!n) + +let step w = + let n = Array.init (Array.length w) (fun i -> String.copy w.(i)) in + let width = Array.length w + and height = String.length w.(0) + in + for x = 0 to pred width do + for y = 0 to pred height do + n.(x).[y] <- ( + match w.(x).[y] with + | ' ' -> ' ' + | 'H' -> 't' + | 't' -> '.' + | '.' -> + (match neighborhood_heads w x y with + | 1 | 2 -> 'H' + | _ -> '.') + | _ -> assert false) + done; + done; + (n) + +let print = (Array.iter print_endline) + +let () = + let rec aux w = + Unix.sleep 1; + let n = step w in + print n; + aux n + in + aux w diff --git a/Task/Wireworld/Oz/wireworld.oz b/Task/Wireworld/Oz/wireworld.oz new file mode 100644 index 0000000000..3b764f6dc3 --- /dev/null +++ b/Task/Wireworld/Oz/wireworld.oz @@ -0,0 +1,92 @@ +declare + Rules = + [rule(& & ) + rule(&H &t) + rule(&t &.) + rule(&. &H when:fun {$ Neighbours} + fun {IsHead X} X == &H end + Hs = {Filter Neighbours IsHead} + Len = {Length Hs} + in + Len == 1 orelse Len == 2 + end) + rule(&. &.)] + + Init = ["tH........." + ". . " + " ... " + ". . " + "Ht.. ......"] + + MaxGen = 100 + + %% G(i) -> G(i+1) + fun {Evolve Gi} + fun {Get X#Y} + Row = {CondSelect Gi Y unit} + in + {CondSelect Row X & } %% cells beyond boundaries are empty + end + fun {GetNeighbors X Y} + {Map [X-1#Y-1 X#Y-1 X+1#Y-1 + X-1#Y X+1#Y + X-1#Y+1 X#Y+1 X+1#Y+1] + Get} + end + in + {Record.mapInd Gi + fun {$ Y Row} + {Record.mapInd Row + fun {$ X C} + for Rule in Rules return:Return do + if C == Rule.1 then + When = {CondSelect Rule when {Const true}} + in + if {When {GetNeighbors X Y}} then + {Return Rule.2} + end + end + end + end} + end} + end + + %% Create an arena from a list of strings. + fun {ReadArena LinesList} + {List.toTuple '#' + {Map LinesList + fun {$ Line} + {List.toTuple row Line} + end}} + end + + %% Converts an arena to a virtual string + fun {ShowArena G} + {Record.map G + fun {$ L} {Record.toList L}#"\n" end} + end + + %% helpers + fun lazy {Iterate F V} V|{Iterate F {F V}} end + fun {Const X} fun {$ _} X end end + + %% prepare GUI + [QTk]={Module.link ["x-oz://system/wp/QTk.ozf"]} + GenDisplay + Field + GUI = td(label(handle:GenDisplay) + label(handle:Field font:{QTk.newFont font(family:'Courier')}) + ) + {{QTk.build GUI} show} + + G0 = {ReadArena Init} + Gn = {Iterate Evolve G0} +in + for + Gi in Gn + I in 0..MaxGen + do + {GenDisplay set(text:"Gen. "#I)} + {Field set(text:{ShowArena Gi})} + {Delay 500} + end diff --git a/Task/Wireworld/PARI-GP/wireworld.pari b/Task/Wireworld/PARI-GP/wireworld.pari new file mode 100644 index 0000000000..67deca9125 --- /dev/null +++ b/Task/Wireworld/PARI-GP/wireworld.pari @@ -0,0 +1,31 @@ +\\ 0 = conductor, 1 = tail, 2 = head, 3 = empty +wireworldStep(M)={ + my(sz=matsize(M),t); + matrix(sz[1],sz[2],x,y, + t=M[x,y]; + if(t, + [0,1,3][t] + , + t=sum(i=max(x-1,1),min(x+1,sz[1]), + sum(j=max(y-1,1),min(y+1,sz[2]), + M[i,j]==2 + ) + ); + if(t==1|t==2,2,3) + ) + ) +}; +animate(M)={ + while(1,display(M=wireworldStep(M))) +}; +display(M)={ + my(sz=matsize(M),t); + for(i=1,sz[1], + for(j=1,sz[2], + t=M[i,j]; + print1([".","t","H"," "][t+1]) + ); + print + ) +}; +animate(read("wireworld.gp")) diff --git a/Task/Wireworld/PHP/wireworld.php b/Task/Wireworld/PHP/wireworld.php new file mode 100644 index 0000000000..c4a514f23a --- /dev/null +++ b/Task/Wireworld/PHP/wireworld.php @@ -0,0 +1,99 @@ +$desc = 'tH......... +. . + ........ +. . +Ht.. ...... + + .. +tH.... ....... + .. + + .. +tH..... ...... + ..'; + +$steps = 30; + +//fill in the world with the cells +$world = array(array()); +$row = 0; +$col = 0; +foreach(str_split($desc) as $i){ + switch($i){ + case "\n": + $row++; + //if($col > $width) $width = $col; + $col = 0; + $world[] = array(); + break; + case '.': + $world[$row][$col] = 1;//conductor + $col++; + break; + case 'H': + $world[$row][$col] = 2;//head + $col++; + break; + case 't': + $world[$row][$col] = 3;//tail + $col++; + break; + default: + $world[$row][$col] = 0;//insulator/air + $col++; + break; + }; +}; +function draw_world($world){ + foreach($world as $rowc){ + foreach($rowc as $cell){ + switch($cell){ + case 0: + echo ' '; + break; + case 1: + echo '.'; + break; + case 2: + echo 'H'; + break; + case 3: + echo 't'; + }; + }; + echo "\n"; + }; + //var_export($world); +}; +echo "Original world:\n"; +draw_world($world); +for($i = 0; $i < $steps; $i++){ + $old_world = $world; //backup to look up where was an electron head + foreach($world as $row => &$rowc){ + foreach($rowc as $col => &$cell){ + switch($cell){ + case 2: + $cell = 3; + break; + case 3: + $cell = 1; + break; + case 1: + $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; + $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; + $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; + $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; + $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; + $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; + $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; + if($neigh_heads == 1 || $neigh_heads == 2){ + $cell = 2; + }; + }; + }; + unset($cell); //just to be safe + }; + unset($rowc); //just to be safe + echo "\nStep " . ($i + 1) . ":\n"; + draw_world($world); +}; diff --git a/Task/Wireworld/Perl-6/wireworld.pl6 b/Task/Wireworld/Perl-6/wireworld.pl6 new file mode 100644 index 0000000000..8efe9cc159 --- /dev/null +++ b/Task/Wireworld/Perl-6/wireworld.pl6 @@ -0,0 +1,44 @@ +class Wireworld { + has @.line; + + multi method new(@line) { self.new: :@line } + multi method new($str ) { self.new: $str.split: "\n" } + + method gist { join "\n", @.line } + method postcircumfix:<[ ]>($i) { @.line[$i].comb } + + method neighbors($i where ^@.line, $j where ^$.line.pick.chars) + { + my @i = grep any(^@.line), $i «+« (-1, 0, 1); + my @j = grep any(^@.line.pick.chars), $j «+« (-1, 0, 1); + gather for @i X @j -> \i, \j { + next if [ i, j ] ~~ [ $i, $j ]; + take self[i][j]; + } + } + method succ { + my $succ = self.new: '' xx @.line; + for ^@.line X ^@.line.pick.chars -> $i, $j { + $succ.line[$i] ~= + do given self[$i][$j] { + when 'H' { 't' } + when 't' { '.' } + when '.' { + grep('H', self.neighbors($i, $j)) == 1|2 ?? 'H' !! '.' + } + default { ' ' } + } + } + return $succ; + } +} + +my $str = +"tH......... +. . + ... +. . +Ht.. ......"; + +my Wireworld $world .= new: $str; +say $world++ for ^3; diff --git a/Task/Wireworld/Perl/wireworld.pl b/Task/Wireworld/Perl/wireworld.pl new file mode 100644 index 0000000000..7d449aa65f --- /dev/null +++ b/Task/Wireworld/Perl/wireworld.pl @@ -0,0 +1,21 @@ +my @f = ([],(map {chomp;['',( split // ),'']} <>),[]); + +for (1 .. 10) { + print join "", map {"@$_\n"} @f; + my @a = ([]); + for my $y (1 .. $#f-1) { + my $r = $f[$y]; + my $rr = ['']; + for my $x (1 .. $#$r-1) { + my $c = $r->[$x]; + push @$rr, + $c eq 'H' ? 't' : + $c eq 't' ? '.' : + $c eq '.' ? (join('', map {"@{$f[$_]}[$x-1 .. $x+1]"=~/H/g} ($y-1 .. $y+1)) =~ /^H{1,2}$/ ? 'H' : '.') : + $c; + } + push @$rr, ''; + push @a, $rr; + } + @f = (@a,[]); +} diff --git a/Task/Wireworld/PicoLisp/wireworld.l b/Task/Wireworld/PicoLisp/wireworld.l new file mode 100644 index 0000000000..1417ab494b --- /dev/null +++ b/Task/Wireworld/PicoLisp/wireworld.l @@ -0,0 +1,36 @@ +(load "@lib/simul.l") + +(let + (Data (in "wire.data" (make (while (line) (link @)))) + Grid (grid (length (car Data)) (length Data)) ) + (mapc + '((G D) (mapc put G '(val .) D)) + Grid + (apply mapcar (flip Data) list) ) + (loop + (disp Grid T + '((This) (pack " " (: val) " ")) ) + (wait 1000) + (for Col Grid + (for This Col + (case (=: next (: val)) + ("H" (=: next "t")) + ("t" (=: next ".")) + ("." + (when + (>= + 2 + (cnt # Count neighbors + '((Dir) (= "H" (get (Dir This) 'val))) + (quote + west east south north + ((X) (south (west X))) + ((X) (north (west X))) + ((X) (south (east X))) + ((X) (north (east X))) ) ) + 1 ) + (=: next "H") ) ) ) ) ) + (for Col Grid # Update + (for This Col + (=: val (: next)) ) ) + (prinl) ) ) diff --git a/Task/Wireworld/PureBasic/wireworld-1.purebasic b/Task/Wireworld/PureBasic/wireworld-1.purebasic new file mode 100644 index 0000000000..c913357c3a --- /dev/null +++ b/Task/Wireworld/PureBasic/wireworld-1.purebasic @@ -0,0 +1,115 @@ +Enumeration + #Empty + #Electron_head + #Electron_tail + #Conductor +EndEnumeration + +#Delay=100 +#XSize=23 +#YSize=12 + +Procedure Limit(n, min, max) + If nmax + n=max + EndIf + ProcedureReturn n +EndProcedure + +Procedure Moore_neighborhood(Array World(2),x,y) + Protected cnt=0, i, j + For i=Limit(x-1, 0, #XSize) To Limit(x+1, 0, #XSize) + For j=Limit(y-1, 0, #YSize) To Limit(y+1, 0, #YSize) + If World(i,j)=#Electron_head + cnt+1 + EndIf + Next + Next + ProcedureReturn cnt +EndProcedure + +Procedure PresentWireWorld(Array World(2)) + Protected x,y + ;ClearConsole() + For y=0 To #YSize + For x=0 To #XSize + ConsoleLocate(x,y) + Select World(x,y) + Case #Electron_head + ConsoleColor(12,0): Print("#") + Case #Electron_tail + ConsoleColor(4,0): Print("#") + Case #Conductor + ConsoleColor(6,0): Print("#") + Default + ConsoleColor(15,0): Print(" ") + EndSelect + Next + PrintN("") + Next +EndProcedure + +Procedure UpdateWireWorld(Array World(2)) + Dim NewArray(#XSize,#YSize) + Protected i, j + For i=0 To #XSize + For j=0 To #YSize + Select World(i,j) + Case #Electron_head + NewArray(i,j)=#Electron_tail + Case #Electron_tail + NewArray(i,j)=#Conductor + Case #Conductor + Define m=Moore_neighborhood(World(),i,j) + If m=1 Or m=2 + NewArray(i,j)=#Electron_head + Else + NewArray(i,j)=#Conductor + EndIf + Default ; e.g. should be Empty + NewArray(i,j)=#Empty + EndSelect + Next + Next + CopyArray(NewArray(),World()) +EndProcedure + +If OpenConsole() + EnableGraphicalConsole(#True) + ConsoleTitle("XOR() WireWorld") + ;- Set up the WireWorld + Dim WW.i(#XSize,#YSize) + Define x, y + Restore StartWW + For y=0 To #YSize + For x=0 To #XSize + Read.i WW(x,y) + Next + Next + + ;- Start the WireWorld simulation + Repeat + PresentWireWorld(WW()) + UpdateWireWorld(WW()) + Delay(#Delay) + ForEver +EndIf + +DataSection + StartWW: + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + Data.i 0,0,0,3,3,3,3,2,1,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0 + Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0 + Data.i 0,0,0,2,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,3,3,3,3,3 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0 + Data.i 0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0 + Data.i 0,0,1,0,0,0,0,0,0,0,0,3,3,3,3,3,3,0,0,0,0,0,0,0 + Data.i 0,0,0,2,3,3,3,3,1,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + Data.i 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 +EndDataSection diff --git a/Task/Wireworld/PureBasic/wireworld-2.purebasic b/Task/Wireworld/PureBasic/wireworld-2.purebasic new file mode 100644 index 0000000000..5982bae07a --- /dev/null +++ b/Task/Wireworld/PureBasic/wireworld-2.purebasic @@ -0,0 +1,145 @@ +CompilerIf #PB_Compiler_Unicode + CompilerError "The file handling in this small program is only in ASCII." +CompilerEndIf + +Enumeration + #Empty + #Electron_head + #Electron_tail + #Conductor + #COL_Empty = $000000 + #COL_Electron_head = $5100FE + #COL_Electron_tail = $6A3595 + #COL_Conductor = $62C4FF + #WW_Window = 0 + #WW_IGadget = 0 + #WW_Timer = 0 + #WW_Image = 0 +EndEnumeration + +#Delay=100 +Global XSize, YSize + +Procedure Limit(n, min, max) + If nmax: n=max + EndIf + ProcedureReturn n +EndProcedure + +Procedure Moore_neighborhood(Array World(2),x,y) + Protected cnt=0, i, j + For i=Limit(x-1, 0, XSize) To Limit(x+1, 0, XSize) + For j=Limit(y-1, 0, YSize) To Limit(y+1, 0, YSize) + If World(i,j)=#Electron_head + cnt+1 + EndIf + Next + Next + ProcedureReturn cnt +EndProcedure + +Procedure PresentWireWorld(Array World(2)) + Protected x,y + StartDrawing(ImageOutput(#WW_Image)) + For y=0 To YSize-1 + For x=0 To XSize-1 + Select World(x,y) + Case #Electron_head + Plot(x,y,#COL_Electron_head) + Case #Electron_tail + Plot(x,y,#COL_Electron_tail) + Case #Conductor + Plot(x,y,#COL_Conductor) + Default + Plot(x,y,#COL_Empty) + EndSelect + Next + Next + StopDrawing() + ImageGadget(#WW_IGadget,0,0,XSize,YSize,ImageID(#WW_Image)) +EndProcedure + +Procedure UpdateWireWorld(Array World(2)) + Dim NewArray(XSize,YSize) + Protected i, j + For i=0 To XSize + For j=0 To YSize + Select World(i,j) + Case #Electron_head + NewArray(i,j)=#Electron_tail + Case #Electron_tail + NewArray(i,j)=#Conductor + Case #Conductor + Define m=Moore_neighborhood(World(),i,j) + If m=1 Or m=2 + NewArray(i,j)=#Electron_head + Else + NewArray(i,j)=#Conductor + EndIf + Default ; e.g. should be Empty + NewArray(i,j)=#Empty + EndSelect + Next + Next + CopyArray(NewArray(),World()) +EndProcedure + +Procedure LoadDataFromFile(File$,Array A(2)) + Define Line$, x, y, *c.Character + If OpenFile(0,File$) + ; + ; Count non-commented lines & length of the first line, e.g. get Array(x,y) + While Not Eof(0) + Line$=Trim(ReadString(0)) + *c=@Line$ + If Not PeekC(*c)=';' + y+1 + If Not x + While PeekC(*c)>='0' And PeekC(*c)<='3' + x+1: *c+1 + Wend + EndIf + EndIf + Wend + XSize=x: YSize=y + Dim A(XSize,YSize) + ; + ; Read in the Wire-World + y=0 + FileSeek(0,0) + While Not Eof(0) + Line$=Trim(ReadString(0)) + *c=@Line$ + If Not PeekC(*c)=';' + x=0 + While x initial world configuration''' + world = [row.rstrip('\r\n') for row in f] + height = len(world) + width = max(len(row) for row in world) + # fill right and frame in empty cells + nonrow = [ " %*s " % (-width, "") ] + world = nonrow + \ + [ " %*s " % (-width, row) for row in world ] + \ + nonrow + world = [list(row) for row in world] + return WW(world, width, height) + +def newcell(currentworld, x, y): + istate = currentworld[y][x] + assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate + if istate == head: + ostate = tail + elif istate == tail: + ostate = conductor + elif istate == empty: + ostate = empty + else: # istate == conductor + n = sum( currentworld[y+dy][x+dx] == head + for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), + (+0,-1), (+0,+1), + (+1,-1), (+1,+0), (+1,+1) ) ) + ostate = head if 1 <= n <= 2 else conductor + return ostate + +def nextgen(ww): + 'compute next generation of wireworld' + world, width, height = ww + newworld = copy.deepcopy(world) + for x in range(1, width+1): + for y in range(1, height+1): + newworld[y][x] = newcell(world, x, y) + return WW(newworld, width, height) + +def world2string(ww): + return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) + +ww = readfile(infile) +infile.close() + +for gen in range(10): + print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) + print ( world2string(ww) ) + ww = nextgen(ww) diff --git a/Task/Wireworld/Ursala/wireworld-1.ursala b/Task/Wireworld/Ursala/wireworld-1.ursala new file mode 100644 index 0000000000..094d37bf88 --- /dev/null +++ b/Task/Wireworld/Ursala/wireworld-1.ursala @@ -0,0 +1,7 @@ +#import std + +rule = case~&l\~&l {`H: `t!, `t: `.!,`.: @r ==`H*~; {'H','HH'}?*+ 0-* + +evolve "n" = @iNC ~&x+ rep"n" ^C\~& rule**+ neighborhoods@h diff --git a/Task/Wireworld/Ursala/wireworld-2.ursala b/Task/Wireworld/Ursala/wireworld-2.ursala new file mode 100644 index 0000000000..9dcfa6725f --- /dev/null +++ b/Task/Wireworld/Ursala/wireworld-2.ursala @@ -0,0 +1,10 @@ +diode = + +< + ' .. ', + 'tH....... .Ht', + ' .. '> + +#show+ + +example = mat0 evolve13 diode diff --git a/Task/Wireworld/XPL0/wireworld.xpl0 b/Task/Wireworld/XPL0/wireworld.xpl0 new file mode 100644 index 0000000000..497435ab38 --- /dev/null +++ b/Task/Wireworld/XPL0/wireworld.xpl0 @@ -0,0 +1,48 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations +char New(53,40), Old(53,40); + +proc Block(X0, Y0, C); \Display a colored block +int X0, Y0, C; \big (6x5) coordinates, char +int X, Y; +[case C of \convert char to color + ^H: C:= $9; \blue + ^t: C:= $C; \red + ^.: C:= $E \yellow +other C:= 0; \black +for Y:= Y0*5 to Y0*5+4 do \make square blocks by correcting aspect ratio + for X:= X0*6 to X0*6+5 do \ (6x5 = square) + Point(X,Y,C); +]; + +int X, Y, C; +[SetVid($13); \set 320x200 graphics display +for Y:= 0 to 40-1 do \initialize New with space (empty) characters + for X:= 0 to 53-1 do + New(X, Y):= ^ ; +X:= 1; Y:= 1; \read file from command line, skipping borders +loop [C:= ChIn(1); + case C of + $0D: X:= 1; \carriage return + $0A: Y:= Y+1; \line feed + $1A: quit \end of file + other [New(X,Y):= C; X:= X+1]; + ]; +repeat C:= Old; Old:= New; New:= C; \swap arrays, by swapping their pointers + for Y:= 1 to 39-1 do \generate New array from Old + for X:= 1 to 52-1 do \ (skipping borders) + [case Old(X,Y) of + ^ : New(X,Y):= ^ ; \copy empty to empty + ^H: New(X,Y):= ^t; \convert head to tail + ^t: New(X,Y):= ^. \convert tail to conductor + other [C:= (Old(X-1,Y-1)=^H) + (Old(X+0,Y-1)=^H) + \head count + (Old(X+1,Y-1)=^H) + (Old(X-1,Y+0)=^H) + \ in neigh- + (Old(X+1,Y+0)=^H) + (Old(X-1,Y+1)=^H) + \ boring + (Old(X+0,Y+1)=^H) + (Old(X+1,Y+1)=^H); \ cells + New(X,Y):= if C=-1 or C=-2 then ^H else ^.; \ (true=-1) + ]; + Block(X, Y, New(X,Y)); \display result + ]; + Sound(0, 6, 1); \delay about 1/3 second +until KeyHit; \keystroke terminates program +SetVid(3); \restore normal text mode +] diff --git a/Task/Word-wrap/0DESCRIPTION b/Task/Word-wrap/0DESCRIPTION new file mode 100644 index 0000000000..529a6619f2 --- /dev/null +++ b/Task/Word-wrap/0DESCRIPTION @@ -0,0 +1,7 @@ +Even today, with proportional fonts and complex layouts, there are still [[Template:Lines_too_long|cases]] where you need to wrap text at a specified column. The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the [http://en.wikipedia.org/wiki/Word_wrap#Minimum_length minimum length greedy algorithm from Wikipedia.] + +Show your routine working on a sample of text at two different wrap columns. + +'''Extra credit!''' Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you ''must reference documentation'' indicating that the algorithm is something better than a simple minimimum length algorithm. + +If you have both basic and extra credit solutions, show an example where the two algorithms give different results. diff --git a/Task/Word-wrap/1META.yaml b/Task/Word-wrap/1META.yaml new file mode 100644 index 0000000000..fce81aba31 --- /dev/null +++ b/Task/Word-wrap/1META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Text processing diff --git a/Task/Word-wrap/AWK/word-wrap.awk b/Task/Word-wrap/AWK/word-wrap.awk new file mode 100644 index 0000000000..92127addba --- /dev/null +++ b/Task/Word-wrap/AWK/word-wrap.awk @@ -0,0 +1,40 @@ +function wordwrap_paragraph(p) +{ + if ( length(p) < 1 ) return + + split(p, words) + spaceLeft = lineWidth + line = words[1] + delete words[1] + + for (i = 1; i <= length(words); i++) { + word = words[i] + if ( (length(word) + 1) > spaceLeft ) { + print line + line = word + spaceLeft = lineWidth - length(word) + } else { + spaceLeft -= length(word) + 1 + line = line " " word + } + } + print line +} + +BEGIN { + lineWidth = width + par = "" +} + +/^[ \t]*$/ { + wordwrap_paragraph(par) + par = "" +} + +!/^[ \t]*$/ { + par = par " " $0 +} + +END { + wordwrap_paragraph(par) +} diff --git a/Task/Word-wrap/Ada/word-wrap-1.ada b/Task/Word-wrap/Ada/word-wrap-1.ada new file mode 100644 index 0000000000..a716ee751b --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-1.ada @@ -0,0 +1,18 @@ +generic + with procedure Put_Line(Line: String); +package Word_Wrap is + + type Basic(Length_Of_Output_Line: Positive) is tagged private; + + procedure Push_Word(State: in out Basic; Word: String); + procedure New_Paragraph(State: in out Basic); + procedure Finish(State: in out Basic); + +private + type Basic(Length_Of_Output_Line: Positive) is tagged record + Line: String(1 .. Length_Of_Output_Line); + Size: Natural := 0; -- Line(1 .. Size) is relevant + Top_Of_Paragraph: Boolean := True; + end record; + +end Word_Wrap; diff --git a/Task/Word-wrap/Ada/word-wrap-2.ada b/Task/Word-wrap/Ada/word-wrap-2.ada new file mode 100644 index 0000000000..e1c6fb4675 --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-2.ada @@ -0,0 +1,36 @@ +package body Word_Wrap is + + procedure Push_Word(State: in out Basic; Word: String) is + begin + if Word'Length + State.Size >= State.Length_Of_Output_Line then + Put_Line(State.Line(1 .. State.Size)); + State.Line(1 .. Word'Length) := Word; -- may raise CE if Word too long + State.Size := Word'Length; + elsif State.Size > 0 then + State.Line(State.Size+1 .. State.Size+1+Word'Length) := ' ' & Word; + State.Size := State.Size + 1 + Word'Length; + else + State.Line(1 .. Word'Length) := Word; + State.Size := Word'Length; + end if; + State.Top_Of_Paragraph := False; + end Push_Word; + + procedure New_Paragraph(State: in out Basic) is + begin + Finish(State); + if not State.Top_Of_Paragraph then + Put_Line(""); + State.Top_Of_Paragraph := True; + end if; + end New_Paragraph; + + procedure Finish(State: in out Basic) is + begin + if State.Size > 0 then + Put_Line(State.Line(1 .. State.Size)); + State.Size := 0; + end if; + end Finish; + +end Word_Wrap; diff --git a/Task/Word-wrap/Ada/word-wrap-3.ada b/Task/Word-wrap/Ada/word-wrap-3.ada new file mode 100644 index 0000000000..f3e2fe48cb --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-3.ada @@ -0,0 +1,62 @@ +with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line; + +procedure Wrap is + + use Ada.Strings.Unbounded; + + Line: Unbounded_String; + Word: Unbounded_String; + + function "+"(S: String) return Unbounded_String renames To_Unbounded_String; + function "-"(U: Unbounded_String) return String renames To_String; + + package IO renames Ada.Text_IO; + + procedure Split(S: Unbounded_String; First, Rest: out Unbounded_String) is + + function Skip_Leading_Spaces(S: String) return String is + begin + if S="" then return ""; + elsif S(S'First) = ' ' then return S(S'First+1 .. S'Last); + else return S; + end if; + end Skip_Leading_Spaces; + + Str: String := Skip_Leading_Spaces(-S); + I: Positive := Str'First; + J: Natural; + begin + -- read nonspaces for First output param + J := I-1; + while J < Str'Last and then Str(J+1) /= ' ' loop + J := J + 1; + end loop; + First := + Str(I .. J); + + -- write output param Rest + Rest := + Skip_Leading_Spaces(Str(J+1 .. Str'Last)); + end Split; + + procedure Print(S: String) is + begin + IO.Put_Line(S); + end Print; + + package WW is new Word_Wrap(Print); + + Wrapper: WW.Basic(Integer'Value(Ada.Command_Line.Argument(1))); + +begin + while not IO.End_Of_File loop + Line := +IO.Get_Line; + if Line = +"" then + Wrapper.New_Paragraph; + Line := +IO.Get_Line; + end if; + while Line /= +"" loop + Split(Line, First => Word, Rest => Line); + Wrapper.Push_Word(-Word); + end loop; + end loop; + Wrapper.Finish; +end Wrap; diff --git a/Task/Word-wrap/C-sharp/word-wrap.cs b/Task/Word-wrap/C-sharp/word-wrap.cs new file mode 100644 index 0000000000..0692fb7c92 --- /dev/null +++ b/Task/Word-wrap/C-sharp/word-wrap.cs @@ -0,0 +1,64 @@ +namespace RosettaCode.WordWrap +{ + using System; + using System.Collections.Generic; + + internal static class Program + { + private const string LoremIpsum = @" +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien +vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu +pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus +consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque +penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt +purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel +felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta +tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, +condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed +venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu +nibh."; + + private static void Main() + { + foreach (var lineWidth in new[] { 72, 80 }) + { + Console.WriteLine(new string('-', lineWidth)); + Console.WriteLine(Wrap(LoremIpsum, lineWidth)); + } + } + + private static string Wrap(string text, int lineWidth) + { + return string.Join(string.Empty, + Wrap( + text.Split(new char[0], + StringSplitOptions + .RemoveEmptyEntries), + lineWidth)); + } + + private static IEnumerable Wrap(IEnumerable words, + int lineWidth) + { + var currentWidth = 0; + foreach (var word in words) + { + if (currentWidth != 0) + { + if (currentWidth + word.Length < lineWidth) + { + currentWidth++; + yield return " "; + } + else + { + currentWidth = 0; + yield return Environment.NewLine; + } + } + currentWidth += word.Length; + yield return word; + } + } + } +} diff --git a/Task/Word-wrap/C/word-wrap.c b/Task/Word-wrap/C/word-wrap.c new file mode 100644 index 0000000000..7e7b8e578b --- /dev/null +++ b/Task/Word-wrap/C/word-wrap.c @@ -0,0 +1,179 @@ +#include +#include +#include +#include + +/* nonsensical hyphens to make greedy wrapping method look bad */ +const char *string = "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."; + +/* Each but the last of wrapped lines comes with some penalty as the square + of the diff between line length and desired line length. If the line + is longer than desired length, the penalty is multiplied by 100. This + pretty much prohibits the wrapping routine from going over right margin. + If is ok to exceed the margin just a little, something like 20 or 40 will + do. + + Knuth uses a per-paragraph penalty for line-breaking in TeX, which is-- + unlike what I have here--probably bug-free. +*/ + +#define PENALTY_LONG 100 +#define PENALTY_SHORT 1 + +typedef struct word_t { + const char *s; + int len; +} *word; + +word make_word_list(const char *s, int *n) +{ + int max_n = 0; + word words = 0; + + *n = 0; + while (1) { + while (*s && isspace(*s)) s++; + if (!*s) break; + + if (*n >= max_n) { + if (!(max_n *= 2)) max_n = 2; + words = realloc(words, max_n * sizeof(*words)); + } + words[*n].s = s; + while (*s && !isspace(*s)) s++; + words[*n].len = s - words[*n].s; + (*n) ++; + } + + return words; +} + +int greedy_wrap(word words, int count, int cols, int *breaks) +{ + int score = 0, line, i, j, d; + + i = j = line = 0; + while (1) { + if (i == count) { + breaks[j++] = i; + break; + } + + if (!line) { + line = words[i++].len; + continue; + } + + if (line + words[i].len < cols) { + line += words[i++].len + 1; + continue; + } + + breaks[j++] = i; + if (i < count) { + d = cols - line; + if (d > 0) score += PENALTY_SHORT * d * d; + else if (d < 0) score += PENALTY_LONG * d * d; + } + + line = 0; + } + breaks[j++] = 0; + + return score; +} + +/* tries to make right margin more even; pretty sure there's an off-by-one bug + here somewhere */ +int balanced_wrap(word words, int count, int cols, int *breaks) +{ + int *best = malloc(sizeof(int) * (count + 1)); + + /* do a greedy wrap to have some baseline score to work with, else + we'll end up with O(2^N) behavior */ + int best_score = greedy_wrap(words, count, cols, breaks); + + void test_wrap(int line_no, int start, int score) { + int line = 0, current_score = -1, d; + + while (start <= count) { + if (line) line ++; + line += words[start++].len; + d = cols - line; + if (start < count || d < 0) { + if (d > 0) + current_score = score + PENALTY_SHORT * d * d; + else + current_score = score + PENALTY_LONG * d * d; + } else { + current_score = score; + } + + if (current_score >= best_score) { + if (d <= 0) return; + continue; + } + + best[line_no] = start; + test_wrap(line_no + 1, start, current_score); + } + if (current_score >= 0 && current_score < best_score) { + best_score = current_score; + memcpy(breaks, best, sizeof(int) * (line_no)); + } + } + test_wrap(0, 0, 0); + free(best); + + return best_score; +} + +void show_wrap(word list, int count, int *breaks) +{ + int i, j; + for (i = j = 0; i < count && breaks[i]; i++) { + while (j < breaks[i]) { + printf("%.*s", list[j].len, list[j].s); + if (j < breaks[i] - 1) + putchar(' '); + j++; + } + if (breaks[i]) putchar('\n'); + } +} + +int main(void) +{ + int len, score, cols; + word list = make_word_list(string, &len); + int *breaks = malloc(sizeof(int) * (len + 1)); + + cols = 80; + score = greedy_wrap(list, len, cols, breaks); + printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score); + show_wrap(list, len, breaks); + + score = balanced_wrap(list, len, cols, breaks); + printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score); + show_wrap(list, len, breaks); + + + cols = 32; + score = greedy_wrap(list, len, cols, breaks); + printf("\n== greedy wrap at %d (score %d) ==\n\n", cols, score); + show_wrap(list, len, breaks); + + score = balanced_wrap(list, len, cols, breaks); + printf("\n== balanced wrap at %d (score %d) ==\n\n", cols, score); + show_wrap(list, len, breaks); + + return 0; +} diff --git a/Task/Word-wrap/D/word-wrap.d b/Task/Word-wrap/D/word-wrap.d new file mode 100644 index 0000000000..7122375bc8 --- /dev/null +++ b/Task/Word-wrap/D/word-wrap.d @@ -0,0 +1,35 @@ +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/Forth/word-wrap.fth b/Task/Word-wrap/Forth/word-wrap.fth new file mode 100644 index 0000000000..478d1acb7c --- /dev/null +++ b/Task/Word-wrap/Forth/word-wrap.fth @@ -0,0 +1,26 @@ +\ wrap text +\ usage: gforth wrap.f in.txt 72 + +0. argc @ 1- arg >number 2drop drop constant maxLine + +: .wrapped ( buf len -- ) + begin + dup maxLine > + while + over maxLine + begin 1- 2dup + c@ bl = until + dup 1+ >r + begin 1- 2dup + c@ bl <> until + 1+ type cr + r> /string + repeat type cr ; + +: strip-nl ( buf len -- ) + bounds do + i c@ 10 = if bl i c! then + loop ; + +argc @ 2 - arg slurp-file +2dup strip-nl +.wrapped +bye diff --git a/Task/Word-wrap/Go/word-wrap.go b/Task/Word-wrap/Go/word-wrap.go new file mode 100644 index 0000000000..a682da6c84 --- /dev/null +++ b/Task/Word-wrap/Go/word-wrap.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "strings" +) + +func wrap(text string, lineWidth int) (wrapped string) { + words := strings.Fields(text) + if len(words) == 0 { + return + } + wrapped = words[0] + spaceLeft := lineWidth - len(wrapped) + for _, word := range words[1:] { + if len(word)+1 > spaceLeft { + wrapped += "\n" + word + spaceLeft = lineWidth - len(word) + } else { + wrapped += " " + word + spaceLeft -= 1 + len(word) + } + } + return +} + +var 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.` + +func main() { + fmt.Println("wrapped at 80:") + fmt.Println(wrap(frog, 80)) + fmt.Println("wrapped at 72:") + fmt.Println(wrap(frog, 72)) +} diff --git a/Task/Word-wrap/Haskell/word-wrap.hs b/Task/Word-wrap/Haskell/word-wrap.hs new file mode 100644 index 0000000000..a94bfdaa5c --- /dev/null +++ b/Task/Word-wrap/Haskell/word-wrap.hs @@ -0,0 +1,23 @@ +ss = "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." + +wordwrap maxlen = (wrap_ 0) . words where + wrap_ _ [] = "\n" + wrap_ pos (w:ws) + -- at line start: put down the word no matter what + | pos == 0 = w ++ wrap_ (pos + lw) ws + | pos + lw + 1 > maxlen = '\n':wrap_ 0 (w:ws) + | otherwise = " " ++ w ++ wrap_ (pos + lw + 1) ws + where lw = length w + +main = do + putStr $ wordwrap 72 ss + putStr "\n" + putStr $ wordwrap 32 ss diff --git a/Task/Word-wrap/J/word-wrap-1.j b/Task/Word-wrap/J/word-wrap-1.j new file mode 100644 index 0000000000..2eb2ef25e5 --- /dev/null +++ b/Task/Word-wrap/J/word-wrap-1.j @@ -0,0 +1,4 @@ +ww =: 75&$: : wrap + wrap =: (] turn edges) ,&' ' + turn =: LF"_`]`[} + edges =: (_1 + ] #~ 1 ,~ 2 >/\ |) [: +/\ #;.2 diff --git a/Task/Word-wrap/J/word-wrap-2.j b/Task/Word-wrap/J/word-wrap-2.j new file mode 100644 index 0000000000..90d837b185 --- /dev/null +++ b/Task/Word-wrap/J/word-wrap-2.j @@ -0,0 +1,16 @@ + GA =: 'Four score and seven years ago, our forefathers brought forth upon this continent a new nation, dedicated to the proposition that all men were created equal.' + + ww GA NB. Wrap at 75 chars by default +Four score and seven years ago, our forefathers brought forth upon this +continent a new nation, dedicated to the proposition that all men were +created equal. + + 20 ww GA NB. Specify different length +Four score and +seven years ago, our +forefathers brought +forth upon this +continent a new nation, +dedicated to the +proposition that all men +were created equal. diff --git a/Task/Word-wrap/OCaml/word-wrap.ocaml b/Task/Word-wrap/OCaml/word-wrap.ocaml new file mode 100644 index 0000000000..a3fe463719 --- /dev/null +++ b/Task/Word-wrap/OCaml/word-wrap.ocaml @@ -0,0 +1,33 @@ +#load "str.cma" + +let txt = "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." + +let () = + let line_width = int_of_string Sys.argv.(1) in + let words = Str.split (Str.regexp "[ \n]+") txt in + let buf = Buffer.create 10 in + let _ = + List.fold_left (fun (width, sep) word -> + let wlen = String.length word in + let len = width + wlen + 1 in + if len > line_width then + begin + Buffer.add_char buf '\n'; + Buffer.add_string buf word; + (wlen, " ") + end else begin + Buffer.add_string buf sep; + Buffer.add_string buf word; + (len, " ") + end + ) (0, "") words + in + print_endline (Buffer.contents buf) diff --git a/Task/Word-wrap/PARI-GP/word-wrap.pari b/Task/Word-wrap/PARI-GP/word-wrap.pari new file mode 100644 index 0000000000..cfe0000966 --- /dev/null +++ b/Task/Word-wrap/PARI-GP/word-wrap.pari @@ -0,0 +1,26 @@ +wrap(s,len)={ + my(t="",cur); + s=Vec(s); + for(i=1,#s, + if(s[i]==" ", + if(cur>#t, + print1(" "t); + cur-=#t+1 + , + print1("\n"t); + cur=len-#t + ); + t="" + , + t=concat(t,s[i]) + ) + ); + if(cur>#t, + print1(" "t) + , + print1("\n"t) + ) +}; +King="And so let freedom ring from the prodigious hilltops of New Hampshire; let freedom ring from the mighty mountains of New York; let freedom ring from the heightening Alleghenies of Pennsylvania; let freedom ring from the snow-capped Rockies of Colorado; let freedom ring from the curvaceous slopes of California. But not only that: let freedom ring from Stone Mountain of Georgia; let freedom ring from Lookout Mountain of Tennessee; let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring."; +wrap(King, 75) +wrap(King, 50) diff --git a/Task/Word-wrap/Perl-6/word-wrap.pl6 b/Task/Word-wrap/Perl-6/word-wrap.pl6 new file mode 100644 index 0000000000..ce78aa4c8c --- /dev/null +++ b/Task/Word-wrap/Perl-6/word-wrap.pl6 @@ -0,0 +1,15 @@ +my $s = "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."; + +$s ~~ s:g/»\s+/ /; +$s ~~ s/\s*$/\n\n/; + +say $s.subst(/ \s* (. ** 1..66) \s /, -> $/ { "$0\n" }, :g); +say $s.subst(/ \s* (. ** 1..25) \s /, -> $/ { "$0\n" }, :g); diff --git a/Task/Word-wrap/Perl/word-wrap.pl b/Task/Word-wrap/Perl/word-wrap.pl new file mode 100644 index 0000000000..2a48cc7b68 --- /dev/null +++ b/Task/Word-wrap/Perl/word-wrap.pl @@ -0,0 +1,18 @@ +my $s = "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."; + +$s =~ s/\b\s+/ /g; +$s =~ s/\s*$/\n\n/; + +my $_ = $s; +s/\s*(.{1,66})\s/$1\n/g, print; + +$_ = $s; +s/\s*(.{1,25})\s/$1\n/g, print; diff --git a/Task/Word-wrap/PicoLisp/word-wrap.l b/Task/Word-wrap/PicoLisp/word-wrap.l new file mode 100644 index 0000000000..9863eab38e --- /dev/null +++ b/Task/Word-wrap/PicoLisp/word-wrap.l @@ -0,0 +1,6 @@ +: (prinl (wrap 12 (chop "The quick brown fox jumps over the lazy dog"))) +The quick +brown fox +jumps over +the lazy dog +-> "The quick^Jbrown fox^Jjumps over^Jthe lazy dog" diff --git a/Task/Word-wrap/REXX/word-wrap.rexx b/Task/Word-wrap/REXX/word-wrap.rexx new file mode 100644 index 0000000000..bf58e97d45 --- /dev/null +++ b/Task/Word-wrap/REXX/word-wrap.rexx @@ -0,0 +1,37 @@ +/*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/Word-wrap/Ruby/word-wrap.rb b/Task/Word-wrap/Ruby/word-wrap.rb new file mode 100644 index 0000000000..feda615e00 --- /dev/null +++ b/Task/Word-wrap/Ruby/word-wrap.rb @@ -0,0 +1,31 @@ +class String + def wrap(width) + txt = gsub(/\s+/, " ") + para = [] + i = 0 + while i < txt.length + j = i + width + j -= 1 while txt[j] != " " + para << txt[i .. j-1] + i = j + 1 + end + para.join("\n") + end +end + +text = <" +html "" + doc$ + "" + doc$ + "" diff --git a/Task/Word-wrap/Run-BASIC/word-wrap-2.run b/Task/Word-wrap/Run-BASIC/word-wrap-2.run new file mode 100644 index 0000000000..ebdb9d717d --- /dev/null +++ b/Task/Word-wrap/Run-BASIC/word-wrap-2.run @@ -0,0 +1,23 @@ +doc$ = "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." + +input "Width"; width ' user specifies width + +while word$(doc$,i + 1," ") <> "" + i = i + 1 + thisWord$ = word$(doc$,i," ") + " " + if word$(thisWord$,2,chr$(13)) <> "" then thisWord$ = word$(thisWord$,2,chr$(13)) + " " ' strip the + if len(docOut$) + len(thisWord$) > width then + print docOut$ + docOut$ = "" + end if + docOut$ = docOut$ + thisWord$ +wend +print docOut$ diff --git a/Task/Word-wrap/TPP/word-wrap.tpp b/Task/Word-wrap/TPP/word-wrap.tpp new file mode 100644 index 0000000000..197892afdf --- /dev/null +++ b/Task/Word-wrap/TPP/word-wrap.tpp @@ -0,0 +1 @@ + The kings youngest daughter was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. diff --git a/Task/Word-wrap/TUSCRIPT/word-wrap.tuscript b/Task/Word-wrap/TUSCRIPT/word-wrap.tuscript new file mode 100644 index 0000000000..31e0a30f29 --- /dev/null +++ b/Task/Word-wrap/TUSCRIPT/word-wrap.tuscript @@ -0,0 +1,18 @@ +$$ MODE TUSCRIPT +text="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." + +ERROR/STOP CREATE ("text",seq-E,-std-) + +length=80 +line=REPEAT ("-",length) +FILE "text" = line +firstline=nextlines="" +wrappedtext=FORMAT(text,length,firstline,nextlines) +FILE "text" = wrappedtext + +length=72 +line=REPEAT ("-",length) +FILE "text" = line +firstline=CONCAT ("Length ",length,": ") +wrappedtext=FORMAT(text,length,firstline,nextlines) +FILE "text" = wrappedtext diff --git a/Task/Word-wrap/Tcl/word-wrap.tcl b/Task/Word-wrap/Tcl/word-wrap.tcl new file mode 100644 index 0000000000..06c91da03f --- /dev/null +++ b/Task/Word-wrap/Tcl/word-wrap.tcl @@ -0,0 +1,26 @@ +package require Tcl 8.5 + +proc wrapParagraph {n text} { + regsub -all {\s+} [string trim $text] " " text + set RE "^(.{1,$n})(?:\\s+(.*))?$" + for {set result ""} {[regexp $RE $text -> line text]} {} { + append result $line "\n" + } + return [string trimright $result "\n"] +} + +set txt \ +"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." + +puts "[string repeat - 80]" +puts [wrapParagraph 80 $txt] +puts "[string repeat - 72]" +puts [wrapParagraph 72 $txt] diff --git a/Task/Write-float-arrays-to-a-text-file/0DESCRIPTION b/Task/Write-float-arrays-to-a-text-file/0DESCRIPTION new file mode 100644 index 0000000000..7c9cb5bc2d --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/0DESCRIPTION @@ -0,0 +1,18 @@ +Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. + +The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. + +For example, considering: + x = {1, 2, 3, 1e11}; + y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; + /* sqrt(x) */ + xprecision = 3; + yprecision = 5; + +The file is: + 1 1 + 2 1.4142 + 3 1.7321 + 1e+011 3.1623e+005 + +This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]]. diff --git a/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg new file mode 100644 index 0000000000..032aee733d --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg @@ -0,0 +1,31 @@ +PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: ( + FILE f; + INT errno = open(f, filename, stand out channel); + IF errno NE 0 THEN stop FI; + FOR i TO UPB x DO + # FORMAT := IF the absolute exponent is small enough, THEN use fixed ELSE use float FI; # + FORMAT repr x := ( ABS log(x[i]) split("1 1.4142135623730951 1.7320508075688772 316227.76601683791",y); +> for(i in x)printf("%6g %.5g\n",x[i],y[i])}' +1e+11 3.1623e+05 + 1 1 + 2 1.4142 + 3 1.7321 diff --git a/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.ada b/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.ada new file mode 100644 index 0000000000..6202639d1d --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.ada @@ -0,0 +1,34 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; + +procedure Write_Float_Array is + type Float_Array is array (1..4) of Float; + procedure Write_Columns + ( File : File_Type; + X : Float_Array; + Y : Float_Array; + X_Pres : Natural := 3; + Y_Pres : Natural := 5 + ) is + begin + for I in Float_Array'range loop + Put (File => File, Item => X(I), Fore => 1, Aft => X_Pres - 1); + Put (File, " "); + Put (File => File, Item => Y(I), Fore => 1, Aft => Y_Pres - 1); + New_Line (File); + end loop; + end Write_Columns; + + File : File_Type; + X : Float_Array := (1.0, 2.0, 3.0, 1.0e11); + Y : Float_Array; +begin + Put ("Tell us the file name to write:"); + Create (File, Out_File, Get_Line); + for I in Float_Array'range loop + Y(I) := Sqrt (X (I)); + end loop; + Write_columns (File, X, Y); + Close (File); +end Write_Float_Array; diff --git a/Task/Write-float-arrays-to-a-text-file/BBC-BASIC/write-float-arrays-to-a-text-file.bbc b/Task/Write-float-arrays-to-a-text-file/BBC-BASIC/write-float-arrays-to-a-text-file.bbc new file mode 100644 index 0000000000..906d2b4b1e --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/BBC-BASIC/write-float-arrays-to-a-text-file.bbc @@ -0,0 +1,21 @@ + DIM x(3), y(3) + x() = 1, 2, 3, 1E11 + FOR i% = 0 TO 3 + y(i%) = SQR(x(i%)) + NEXT + + xprecision = 3 + yprecision = 5 + + outfile% = OPENOUT("filename.txt") + IF outfile%=0 ERROR 100, "Could not create file" + + FOR i% = 0 TO 3 + @% = &1000000 + (xprecision << 8) + a$ = STR$(x(i%)) + CHR$(9) + @% = &1000000 + (yprecision << 8) + a$ += STR$(y(i%)) + PRINT #outfile%, a$ : BPUT #outfile%, 10 + NEXT + + CLOSE #outfile% diff --git a/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-1.cpp b/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-1.cpp new file mode 100644 index 0000000000..a8275544ef --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-1.cpp @@ -0,0 +1,13 @@ +template +void writedat(const char* filename, + InputIterator xbegin, InputIterator xend, + InputIterator2 ybegin, InputIterator2 yend, + int xprecision=3, int yprecision=5) +{ + std::ofstream f; + f.exceptions(std::ofstream::failbit | std::ofstream::badbit); + f.open(filename); + for ( ; xbegin != xend and ybegin != yend; ++xbegin, ++ybegin) + f << std::setprecision(xprecision) << *xbegin << '\t' + << std::setprecision(yprecision) << *ybegin << '\n'; +} diff --git a/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-2.cpp b/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-2.cpp new file mode 100644 index 0000000000..5fc1331bc2 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/C++/write-float-arrays-to-a-text-file-2.cpp @@ -0,0 +1,31 @@ +#include +#include // ::sqrt() +#include +#include // setprecision() +#include +#include +#include + +int main() +{ + try { + // prepare test data + double x[] = {1, 2, 3, 1e11}; + const size_t xsize = sizeof(x) / sizeof(*x); + std::vector y(xsize); + std::transform(&x[0], &x[xsize], y.begin(), ::sqrt); + + // write file using default precisions + writedat("sqrt.dat", &x[0], &x[xsize], y.begin(), y.end()); + + // print the result file + std::ifstream f("sqrt.dat"); + for (std::string line; std::getline(f, line); ) + std::cout << line << std::endl; + } + catch(std::exception& e) { + std::cerr << "writedat: exception: '" << e.what() << "'\n"; + return 1; + } + return 0; +} diff --git a/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-1.c b/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-1.c new file mode 100644 index 0000000000..f0edf1ac65 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-1.c @@ -0,0 +1,18 @@ +#include +#include + +int main(int argc, char **argv) { + + float x[4] = {1,2,3,1e11}, y[4]; + int i = 0; + FILE *filePtr; + + filePtr = fopen("floatArray","w"); + + for (i = 0; i < 4; i++) { + y[i] = sqrt(x[i]); + fprintf(filePtr, "%.3g\t%.5g\n", x[i], y[i]); + } + + return 0; +} diff --git a/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-2.c b/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-2.c new file mode 100644 index 0000000000..836824f548 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/C/write-float-arrays-to-a-text-file-2.c @@ -0,0 +1,4 @@ +1 1 +2 1.4142 +3 1.7321 +1e+11 3.1623e+05 diff --git a/Task/Write-float-arrays-to-a-text-file/Common-Lisp/write-float-arrays-to-a-text-file.lisp b/Task/Write-float-arrays-to-a-text-file/Common-Lisp/write-float-arrays-to-a-text-file.lisp new file mode 100644 index 0000000000..c599017f68 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Common-Lisp/write-float-arrays-to-a-text-file.lisp @@ -0,0 +1,8 @@ +(with-open-file (stream (make-pathname :name "filename") :direction :output) + (let* ((x (make-array 4 :initial-contents '(1 2 3 1e11))) + (y (map 'vector 'sqrt x)) + (xprecision 3) + (yprecision 5) + (fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision))) + (map nil (lambda (a b) + (format stream fmt a b)) x y))) diff --git a/Task/Write-float-arrays-to-a-text-file/D/write-float-arrays-to-a-text-file.d b/Task/Write-float-arrays-to-a-text-file/D/write-float-arrays-to-a-text-file.d new file mode 100644 index 0000000000..1f69f53dbc --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/D/write-float-arrays-to-a-text-file.d @@ -0,0 +1,16 @@ +import std.file, std.conv, std.string; + +void main() { + auto x = [1.0, 2, 3, 1e11]; + auto y = [1.0, 1.4142135623730951, + 1.7320508075688772, 316227.76601683791]; + int xPrecision = 3, + yPrecision = 5; + + string tmp; + foreach (i, fx; x) + tmp ~= format("%." ~ text(xPrecision) ~ "g %." ~ + text(yPrecision) ~ "g\r\n", fx, y[i]); + + write("float_array.txt", tmp); +} diff --git a/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria new file mode 100644 index 0000000000..3533c25c7a --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria @@ -0,0 +1,10 @@ +constant x = {1, 2, 3, 1e11}, + y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} + +integer fn + +fn = open("filename","w") +for n = 1 to length(x) do + printf(fn,"%.3g\t%.5g\n",{x[n],y[n]}) +end for +close(fn) diff --git a/Task/Write-float-arrays-to-a-text-file/Forth/write-float-arrays-to-a-text-file.fth b/Task/Write-float-arrays-to-a-text-file/Forth/write-float-arrays-to-a-text-file.fth new file mode 100644 index 0000000000..6957a8dcfd --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Forth/write-float-arrays-to-a-text-file.fth @@ -0,0 +1,15 @@ +create x 1e f, 2e f, 3e f, 1e11 f, +create y 1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f, + +: main + s" sqrt.txt" w/o open-file throw to outfile-id + + 4 0 do + 4 set-precision + x i floats + f@ f. + 6 set-precision + y i floats + f@ f. cr + loop + + outfile-id stdout to outfile-id + close-file throw ; diff --git a/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-1.f b/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-1.f new file mode 100644 index 0000000000..778e3f3baa --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-1.f @@ -0,0 +1,10 @@ + real x(4), y(4) + data x / 1.0, 2.0, 4.0, 1.0e11 / + + do 10 i = 1, 4 + y = sqrt(x) +10 continue + + open(unit=15, file='two_cols.txt', status='new') + write(15,'(f20.3,f21.4)') (x(I), y(I), I = 1, 4) + end diff --git a/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-2.f b/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-2.f new file mode 100644 index 0000000000..268c2b3b63 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Fortran/write-float-arrays-to-a-text-file-2.f @@ -0,0 +1,26 @@ +program writefloats + implicit none + + real, dimension(10) :: a, sqrta + integer :: i + integer, parameter :: unit = 40 + + a = (/ (i, i=1,10) /) + sqrta = sqrt(a) + + open(unit, file="xydata.txt", status="new", action="write") + call writexy(unit, a, sqrta) + close(unit) + +contains + + subroutine writexy(u, x, y) + real, dimension(:), intent(in) :: x, y + integer, intent(in) :: u + + integer :: i + + write(u, "(2F10.4)") (x(i), y(i), i=lbound(x,1), ubound(x,1)) + end subroutine writexy + +end program writefloats diff --git a/Task/Write-float-arrays-to-a-text-file/Go/write-float-arrays-to-a-text-file.go b/Task/Write-float-arrays-to-a-text-file/Go/write-float-arrays-to-a-text-file.go new file mode 100644 index 0000000000..314cc3f356 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Go/write-float-arrays-to-a-text-file.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "os" +) + +var ( + x = []float64{1, 2, 3, 1e11} + y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} + + xprecision = 3 + yprecision = 5 +) + +func main() { + if len(x) != len(y) { + fmt.Println("x, y different length") + return + } + f, err := os.Create("filename") + if err != nil { + fmt.Println(err) + return + } + for i := range x { + fmt.Fprintf(f, "%.*e, %.*e\n", xprecision-1, x[i], yprecision-1, y[i]) + } + f.Close() +} diff --git a/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-1.hs b/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-1.hs new file mode 100644 index 0000000000..cf122673d4 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-1.hs @@ -0,0 +1,9 @@ +import System.IO +import Text.Printf +import Control.Monad + +writeDat filename x y xprec yprec = + withFile filename WriteMode $ \h -> + -- Haskell's printf doesn't support a precision given as an argument for some reason, so we insert it into the format manually: + let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in + zipWithM_ writeLine x y diff --git a/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-2.hs b/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-2.hs new file mode 100644 index 0000000000..2ae8680fd2 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Haskell/write-float-arrays-to-a-text-file-2.hs @@ -0,0 +1,8 @@ +import System.IO +import Control.Monad +import Numeric + +writeDat filename x y xprec yprec = + withFile filename WriteMode $ \h -> + let writeLine a b = hPutStrLn h $ showGFloat (Just xprec) a "" ++ "\t" ++ showGFloat (Just yprec) b "" in + zipWithM_ writeLine x y diff --git a/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-1.hicest b/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-1.hicest new file mode 100644 index 0000000000..60a377f7bf --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-1.hicest @@ -0,0 +1,9 @@ +REAL :: n=4, x(n), y(n) +CHARACTER :: outP = "Test.txt" + +OPEN(FIle = outP) +x = (1, 2, 3, 1E11) +y = x ^ 0.5 +DO i = 1, n + WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i) +ENDDO diff --git a/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-2.hicest b/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-2.hicest new file mode 100644 index 0000000000..bf4d9eeb90 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/HicEst/write-float-arrays-to-a-text-file-2.hicest @@ -0,0 +1 @@ +DLG(Text=x, Format='i12', Edit=y, Format='F10.2', Y=0) diff --git a/Task/Write-float-arrays-to-a-text-file/IDL/write-float-arrays-to-a-text-file.idl b/Task/Write-float-arrays-to-a-text-file/IDL/write-float-arrays-to-a-text-file.idl new file mode 100644 index 0000000000..b8f27cf3e8 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/IDL/write-float-arrays-to-a-text-file.idl @@ -0,0 +1,4 @@ +1 1 +2 1.4142 +3 1.7321 +1E+011 3.1623E+005 diff --git a/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-1.j b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-1.j new file mode 100644 index 0000000000..3f4be4cef5 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-1.j @@ -0,0 +1,13 @@ +require 'files' NB. for fwrites + +x =. 1 2 3 1e11 +y =. %: x NB. y is sqrt(x) + +xprecision =. 3 +yprecision =. 5 + +filename =. 'whatever.txt' + +data =. (0 j. xprecision,yprecision) ": x,.y + +data fwrites filename diff --git a/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-2.j b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-2.j new file mode 100644 index 0000000000..d899b091f1 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-2.j @@ -0,0 +1 @@ +((0 j. 3 5) ": (,.%:) 1 2 3 1e11) fwrites 'whatever.txt' [ require 'fwrites' diff --git a/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-3.j b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-3.j new file mode 100644 index 0000000000..09486f11ca --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/J/write-float-arrays-to-a-text-file-3.j @@ -0,0 +1,5 @@ + (0 j. 3 5) ": (,.%:) 1 2 3 1e11 + 1.000 1.00000 + 2.000 1.41421 + 3.000 1.73205 +100000000000.000 316227.76602 diff --git a/Task/Write-float-arrays-to-a-text-file/Java/write-float-arrays-to-a-text-file.java b/Task/Write-float-arrays-to-a-text-file/Java/write-float-arrays-to-a-text-file.java new file mode 100644 index 0000000000..2da272c7aa --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Java/write-float-arrays-to-a-text-file.java @@ -0,0 +1,33 @@ +import java.io.*; + +public class FloatArray { + public static void writeDat(String filename, double[] x, double[] y, + int xprecision, int yprecision) + throws IOException { + assert x.length == y.length; + PrintWriter out = new PrintWriter(filename); + for (int i = 0; i < x.length; i++) + out.printf("%."+xprecision+"g\t%."+yprecision+"g\n", x[i], y[i]); + out.close(); + } + + public static void main(String[] args) { + double[] x = {1, 2, 3, 1e11}; + double[] y = new double[x.length]; + for (int i = 0; i < x.length; i++) + y[i] = Math.sqrt(x[i]); + + try { + writeDat("sqrt.dat", x, y, 3, 5); + } catch (IOException e) { + System.err.println("writeDat: exception: "+e); + } + + try { + BufferedReader br = new BufferedReader(new FileReader("sqrt.dat")); + String line; + while ((line = br.readLine()) != null) + System.out.println(line); + } catch (IOException e) { } + } +} diff --git a/Task/Write-float-arrays-to-a-text-file/Joy/write-float-arrays-to-a-text-file.joy b/Task/Write-float-arrays-to-a-text-file/Joy/write-float-arrays-to-a-text-file.joy new file mode 100644 index 0000000000..bef4168a61 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Joy/write-float-arrays-to-a-text-file.joy @@ -0,0 +1,6 @@ +DEFINE write-floats == +['g 0] [formatf] enconcat map rollup +['g 0] [formatf] enconcat map swap zip +"filename" "w" fopen swap +[[fputchars] 9 fputch] step 10 fputch] step +fclose. diff --git a/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia new file mode 100644 index 0000000000..00650d1c62 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia @@ -0,0 +1,9 @@ +xprecision = 3 +yprecision = 5 +x = round([1, 2, 3, 1e11],xprecision) +y = round([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision) +file = open("filename","w") do f + for (a, b) in zip(x,y) + writedlm(f,[a b],'\t') + end +end diff --git a/Task/Write-float-arrays-to-a-text-file/Lua/write-float-arrays-to-a-text-file.lua b/Task/Write-float-arrays-to-a-text-file/Lua/write-float-arrays-to-a-text-file.lua new file mode 100644 index 0000000000..dea1702515 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Lua/write-float-arrays-to-a-text-file.lua @@ -0,0 +1,16 @@ +filename = "file.txt" + +x = { 1, 2, 3, 1e11 } +y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 }; +xprecision = 3; +yprecision = 5; + +fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n" + +fp = io.open( filename, "w+" ) + +for i = 1, #x do + fp:write( string.format( fstr, x[i], y[i] ) ) +end + +io.close( fp ) diff --git a/Task/Write-float-arrays-to-a-text-file/MATLAB/write-float-arrays-to-a-text-file.m b/Task/Write-float-arrays-to-a-text-file/MATLAB/write-float-arrays-to-a-text-file.m new file mode 100644 index 0000000000..a9327c7216 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/MATLAB/write-float-arrays-to-a-text-file.m @@ -0,0 +1,6 @@ + x = [1, 2, 3, 1e11]; + y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]; + + fid = fopen('filename','w') + fprintf(fid,'%.3g\t%.5g\n',[x;y]); + fclose(fid); diff --git a/Task/Write-float-arrays-to-a-text-file/Mathematica/write-float-arrays-to-a-text-file.math b/Task/Write-float-arrays-to-a-text-file/Mathematica/write-float-arrays-to-a-text-file.math new file mode 100644 index 0000000000..c423ce2400 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Mathematica/write-float-arrays-to-a-text-file.math @@ -0,0 +1 @@ +exportPrec[path_, data1_, data2_, prec1_, prec2_]:=Export[path,Transpose[{Map[ToString[NumberForm[#, prec2]] &, data2],Map[ToString[NumberForm[#, prec1]] &, data1]}], "Table"] diff --git a/Task/Write-float-arrays-to-a-text-file/NetRexx/write-float-arrays-to-a-text-file.netrexx b/Task/Write-float-arrays-to-a-text-file/NetRexx/write-float-arrays-to-a-text-file.netrexx new file mode 100644 index 0000000000..0d4a435ec7 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/NetRexx/write-float-arrays-to-a-text-file.netrexx @@ -0,0 +1,35 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols nobinary + +-- Invent a target text file name based on this program's source file name +parse source . . pgmName '.nrx' . +outFile = pgmName || '.txt' + +do + formatArrays(outFile, [1, 2, 3, 1e+11], [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]) +catch ex = Exception + ex.printStackTrace +end + +return + +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- This function formats the input arrays. +-- It has defaults for the x & y precision values of 3 & 5 +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +method formatArrays(outFile, xf = Rexx[], yf = Rexx[], xprecision = 3, yprecision = 5) - + public static signals IllegalArgumentException, FileNotFoundException, IOException + + if xf.length > yf.length then signal IllegalArgumentException('Y array must be at least as long as X array') + + fw = BufferedWriter(OutputStreamWriter(FileOutputStream(outFile))) + + loop i_ = 0 to xf.length - 1 + row = xf[i_].format(null, xprecision, null, xprecision).left(15) yf[i_].format(null, yprecision, null, yprecision) + (Writer fw).write(String row) + fw.newLine + end i_ + fw.close + + return diff --git a/Task/Write-float-arrays-to-a-text-file/NewLISP/write-float-arrays-to-a-text-file.newlisp b/Task/Write-float-arrays-to-a-text-file/NewLISP/write-float-arrays-to-a-text-file.newlisp new file mode 100644 index 0000000000..d1f6ac6c8f --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/NewLISP/write-float-arrays-to-a-text-file.newlisp @@ -0,0 +1,26 @@ +; file: write-float-array.lsp +; url: http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file +; author: oofoe 2012-01-30 + +; The "transpose" function is used to flip the joined lists around so +; that it's easier to iterate through them together. + +(define (write-float-array x xp y yp filename) + (let ((f (format "%%-10.%dg %%-10.%dg" xp yp)) + (o (open filename "write"))) + (dolist (v (transpose (list x y))) + (write-line o (format f (v 0) (v 1)))) + (close o) + )) + +; Test + +(write-float-array + '(1 2 3 1e11) 3 + '(1 1.4142135623730951 1.7320508075688772 316227.76601683791) 5 + "filename.chan") + +(println "File contents:") +(print (read-file "filename.chan")) + +(exit) diff --git a/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml b/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml new file mode 100644 index 0000000000..0552194a3e --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml @@ -0,0 +1,5 @@ +let write_dat filename x y ?(xprec=3) ?(yprec=5) () = + let oc = open_out filename in + let write_line a b = Printf.fprintf oc "%.*g\t%.*g\n" xprec a yprec b in + List.iter2 write_line x y; + close_out oc diff --git a/Task/Write-float-arrays-to-a-text-file/PARI-GP/write-float-arrays-to-a-text-file.pari b/Task/Write-float-arrays-to-a-text-file/PARI-GP/write-float-arrays-to-a-text-file.pari new file mode 100644 index 0000000000..85bf0fecb4 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/PARI-GP/write-float-arrays-to-a-text-file.pari @@ -0,0 +1,12 @@ +f(x,pr)={ + Strprintf(if(x>=10^pr, + Str("%.",pr-1,"e") + , + Str("%.",pr-#Str(x\1),"f") + ),x) +}; +wr(x,y,xprec,yprec)={ + for(i=1,#x, + write("filename",f(x[i],xprec),"\t",f(y[i],yprec)) + ) +}; diff --git a/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli b/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli new file mode 100644 index 0000000000..2c2644b7db --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli @@ -0,0 +1,9 @@ +declare X(5) float (9) initial (1, 2, 3, 4, 5), + Y(5) float (18) initial (9, 8, 7, 6, 1e9); +declare (x_precision, y_precision) fixed binary; +open file (out) title ('/OUT.TXT,type(text),recsize(100)'); +x_precision = 9; +y_precision = 16; +put file (out) edit ((X(i), Y(i) do i = 1 to 5)) + (skip, e(16, x_precision), + x(2), e(20, y_precision) ); diff --git a/Task/Write-float-arrays-to-a-text-file/Pascal/write-float-arrays-to-a-text-file.pascal b/Task/Write-float-arrays-to-a-text-file/Pascal/write-float-arrays-to-a-text-file.pascal new file mode 100644 index 0000000000..5140143518 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Pascal/write-float-arrays-to-a-text-file.pascal @@ -0,0 +1,19 @@ +Program WriteNumbers; + +const + x: array [1..4] of double = (1, 2, 3, 1e11); + xprecision = 3; + yprecision = 5; + baseDigits = 7; + +var + i: integer; + filename: text; + +begin + assign (filename, 'filename'); + rewrite (filename); + for i := 1 to 4 do + writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseDigits+yprecision); + close (filename); +end. diff --git a/Task/Write-float-arrays-to-a-text-file/Perl-6/write-float-arrays-to-a-text-file.pl6 b/Task/Write-float-arrays-to-a-text-file/Perl-6/write-float-arrays-to-a-text-file.pl6 new file mode 100644 index 0000000000..06368ca5e7 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Perl-6/write-float-arrays-to-a-text-file.pl6 @@ -0,0 +1,14 @@ +sub writedat ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) { + my $fh = open $filename, :w; + + for @x Z @y -> $x, $y { + $fh.printf: "%.*g\t%.*g\n", $x_precision, $x, $y_precision, $y; + } + + $fh.close; +} + +my @x = 1, 2, 3, 1e11; +my @y = @x.map({.sqrt}); + +writedat( 'sqrt.dat', @x, @y ); diff --git a/Task/Write-float-arrays-to-a-text-file/Perl/write-float-arrays-to-a-text-file.pl b/Task/Write-float-arrays-to-a-text-file/Perl/write-float-arrays-to-a-text-file.pl new file mode 100644 index 0000000000..f4b69b3152 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Perl/write-float-arrays-to-a-text-file.pl @@ -0,0 +1,11 @@ +sub writedat { + my ($filename, $x, $y, $xprecision, $yprecision) = @_; + open FH, ">", $filename or die "Can't open file: $!"; + printf FH "%.*g\t%.*g\n", $xprecision||3, $x->[$_], $yprecision||5, $y->[$_] for 0 .. $#$x; + close FH; +} + +my @x = (1, 2, 3, 1e11); +my @y = map sqrt, @x; + +writedat("sqrt.dat", \@x, \@y); diff --git a/Task/Write-float-arrays-to-a-text-file/PicoLisp/write-float-arrays-to-a-text-file.l b/Task/Write-float-arrays-to-a-text-file/PicoLisp/write-float-arrays-to-a-text-file.l new file mode 100644 index 0000000000..88675bcb17 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/PicoLisp/write-float-arrays-to-a-text-file.l @@ -0,0 +1,11 @@ +(setq *Xprecision 3 *Yprecision 5) + +(scl 7) +(mapc + '((X Y) + (prinl + (round X *Xprecision) + " " + (round Y *Yprecision) ) ) + (1.0 2.0 3.0) + (1.0 1.414213562 1.732050807) ) diff --git a/Task/Write-float-arrays-to-a-text-file/PureBasic/write-float-arrays-to-a-text-file.purebasic b/Task/Write-float-arrays-to-a-text-file/PureBasic/write-float-arrays-to-a-text-file.purebasic new file mode 100644 index 0000000000..3253437683 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/PureBasic/write-float-arrays-to-a-text-file.purebasic @@ -0,0 +1,28 @@ +#Size = 4 + +DataSection + Data.f 1, 2, 3, 1e11 ;x values, how many values needed is determined by #Size +EndDataSection + +Dim x.f(#Size - 1) +Dim y.f(#Size - 1) + +Define i +For i = 0 To #Size - 1 + Read.f x(i) + y(i) = Sqr(x(i)) +Next + +Define file$, fileID, xprecision = 3, yprecision = 5, output$ + +file$ = SaveFileRequester("Text file for float data", "xydata.txt","Text file | *.txt", 0) +If file$ + fileID = OpenFile(#PB_Any, file$) + If fileID + For i = 0 To #Size - 1 + output$ = StrF(x(i), xprecision) + Chr(9) + StrF(y(i), yprecision) + WriteStringN(fileID, output$) + Next + CloseFile(fileID) + EndIf +EndIf diff --git a/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-1.py b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-1.py new file mode 100644 index 0000000000..3e51ac6ad1 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-1.py @@ -0,0 +1,5 @@ +import itertools +def writedat(filename, x, y, xprecision=3, yprecision=5): + with open(filename,'w') as f: + for a, b in itertools.izip(x, y): + print >> f, "%.*g\t%.*g" % (xprecision, a, yprecision, b) diff --git a/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-2.py b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-2.py new file mode 100644 index 0000000000..5aebdffc0a --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-2.py @@ -0,0 +1,15 @@ +>>> import math +>>> x = [1, 2, 3, 1e11] +>>> y = map(math.sqrt, x) +>>> y +[1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791] +>>> writedat("sqrt.dat", x, y) +>>> # check +... +>>> for line in open('sqrt.dat'): +... print line, +... +1 1 +2 1.4142 +3 1.7321 +1e+011 3.1623e+005 diff --git a/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-3.py b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-3.py new file mode 100644 index 0000000000..7ecd1f5651 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Python/write-float-arrays-to-a-text-file-3.py @@ -0,0 +1,6 @@ +def writedat(filename, x, y, xprecision=3, yprecision=5): + with open(filename,'w') as f: + for a, b in zip(x, y): + print("%.*g\t%.*g" % (xprecision, a, yprecision, b), file=f) + #or, using the new-style formatting: + #print("{1:.{0}g}\t{3:.{2}g}".format(xprecision, a, yprecision, b), file=f) diff --git a/Task/Write-float-arrays-to-a-text-file/R/write-float-arrays-to-a-text-file.r b/Task/Write-float-arrays-to-a-text-file/R/write-float-arrays-to-a-text-file.r new file mode 100644 index 0000000000..9ab56cadb6 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/R/write-float-arrays-to-a-text-file.r @@ -0,0 +1,17 @@ +writexy <- function(file, x, y, xprecision=3, yprecision=3) +{ + #Format inputs as required, and join together + fx <- formatC(x, digits=xprecision, format="g", flag="-") + fy <- formatC(y, digits=yprecision, format="g", flag="-") + dfr <- data.frame(fx, fy) + #Write to file. Note that this encloses the formatted number in quotes, + write.table(dfr, file=file, sep="\t", row.names=FALSE) + #... so we have to process the output + str <- readLines(file) + writeLines(gsub('"', '', str), file) +} + + +x <- c(1, 2, 3, 1e11) +y <- sqrt(x) +writexy('test.txt', x, y, yp=5) diff --git a/Task/Write-float-arrays-to-a-text-file/REXX/write-float-arrays-to-a-text-file.rexx b/Task/Write-float-arrays-to-a-text-file/REXX/write-float-arrays-to-a-text-file.rexx new file mode 100644 index 0000000000..8ec329c80b --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/REXX/write-float-arrays-to-a-text-file.rexx @@ -0,0 +1,29 @@ +/*REXX program writes two arrays to a file with limited precision. */ +outfid='OUTPUT.TXT' /*this is operating system dependent.*/ +x.='' ; y.='' +x.1=1 ; y.1=1 +x.2=2 ; y.2=1.4142135623730951 +x.3=3 ; y.3=1.7320508075688772 +x.4=1e11 ; y.4=316227.76601683791 + +xprecision = 3 +yprecision = 5 +padding=left('',4) /*number of blanks between cols. */ + do j=1 while x.j\=='' + x.j=funnyway(x.j,xprecision) + y.j=funnyway(y.j,yprecision) + aLine=translate(x.j || padding || y.j,'e',"E") + say aLine + call lineout outfid,aLine + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────FUNNYWAY subroutine─────────────────*/ +funnyway: procedure; parse arg a,p; numeric digits p; a=format(a,,p) +parse var a i 'E' e /*format # according to the rules*/ +parse var i i '.' f +f=strip(f,'Trailing',0) +if f\=='' then f='.'f +if e\=='' then e='E'e +a=i || f || e +if datatype(a,'W') then return format(arg(1)/1,,0) /*whole number? */ + return format(arg(1)/1,,,3,0) /*use 3 dec digs*/ diff --git a/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-1.rlab b/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-1.rlab new file mode 100644 index 0000000000..d827be451a --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-1.rlab @@ -0,0 +1,2 @@ +>> x = rand(10,1); y = rand(10,1); +>> writem("mytextfile.txt", [x,y]); diff --git a/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-2.rlab b/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-2.rlab new file mode 100644 index 0000000000..567edcf4c1 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/RLaB/write-float-arrays-to-a-text-file-2.rlab @@ -0,0 +1,3 @@ +>> x = rand(10,1); y = rand(10,1); +>> s = text( [x,y], "%10.8f" ); +>> writem("mytextfile.txt", s); diff --git a/Task/Write-float-arrays-to-a-text-file/Ruby/write-float-arrays-to-a-text-file.rb b/Task/Write-float-arrays-to-a-text-file/Ruby/write-float-arrays-to-a-text-file.rb new file mode 100644 index 0000000000..5624cf31ef --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Ruby/write-float-arrays-to-a-text-file.rb @@ -0,0 +1,13 @@ +# prepare test data +x = [1, 2, 3, 1e11] +y = x.collect { |xx| Math.sqrt xx } +xprecision = 3 +yprecision = 5 + +# write the arrays +open('sqrt.dat', 'w') do |f| + x.zip(y) { |xx, yy| f.printf("%.*g\t%.*g\n", xprecision, xx, yprecision, yy) } +end + +# print the result file +open('sqrt.dat', 'r') { |f| puts f.read } diff --git a/Task/Write-float-arrays-to-a-text-file/Run-BASIC/write-float-arrays-to-a-text-file.run b/Task/Write-float-arrays-to-a-text-file/Run-BASIC/write-float-arrays-to-a-text-file.run new file mode 100644 index 0000000000..63b0923375 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Run-BASIC/write-float-arrays-to-a-text-file.run @@ -0,0 +1,8 @@ +x$ = "1, 2, 3, 1e11" +y$ = "1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791" + +open "filename" for output as #f ' Output to "filename" +for i = 1 to 4 + print #f, using("##############.###",val(word$(x$,i,",")));"|";using("#######.#####",val(word$(y$,i,","))) +next i +close #f diff --git a/Task/Write-float-arrays-to-a-text-file/SAS/write-float-arrays-to-a-text-file.sas b/Task/Write-float-arrays-to-a-text-file/SAS/write-float-arrays-to-a-text-file.sas new file mode 100644 index 0000000000..a55bc99880 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/SAS/write-float-arrays-to-a-text-file.sas @@ -0,0 +1,11 @@ +data _null_; +input x y; +file "output.txt"; +put x 12.3 " " y 12.5; +cards; +1 1 +2 1.4142135623730951 +3 1.7320508075688772 +1e11 316227.76601683791 +; +run; diff --git a/Task/Write-float-arrays-to-a-text-file/Seed7/write-float-arrays-to-a-text-file.seed7 b/Task/Write-float-arrays-to-a-text-file/Seed7/write-float-arrays-to-a-text-file.seed7 new file mode 100644 index 0000000000..5910da1391 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Seed7/write-float-arrays-to-a-text-file.seed7 @@ -0,0 +1,16 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + +const proc: main is func + local + const array float: numbers is [] (1.0, 2.0, 3.0, 1.0e11); + var float: aFloat is 0.0; + var file: aFile is STD_NULL; + begin + aFile := open("filename", "w"); + for aFloat range numbers do + writeln(aFile, aFloat sci 3 exp 2 <& " " <& sqrt(aFloat) sci 5 exp 2); + end for; + close(aFile); + end func; diff --git a/Task/Write-float-arrays-to-a-text-file/Standard-ML/write-float-arrays-to-a-text-file.ml b/Task/Write-float-arrays-to-a-text-file/Standard-ML/write-float-arrays-to-a-text-file.ml new file mode 100644 index 0000000000..ee8ad692ec --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Standard-ML/write-float-arrays-to-a-text-file.ml @@ -0,0 +1,9 @@ +fun writeDat (filename, x, y, xprec, yprec) = let + val os = TextIO.openOut filename + fun write_line (a, b) = + TextIO.output (os, Real.fmt (StringCvt.GEN (SOME xprec)) a ^ "\t" ^ + Real.fmt (StringCvt.GEN (SOME yprec)) b ^ "\n") +in + ListPair.appEq write_line (x, y); + TextIO.closeOut os +end; diff --git a/Task/Write-float-arrays-to-a-text-file/Tcl/write-float-arrays-to-a-text-file.tcl b/Task/Write-float-arrays-to-a-text-file/Tcl/write-float-arrays-to-a-text-file.tcl new file mode 100644 index 0000000000..f4004edbcc --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Tcl/write-float-arrays-to-a-text-file.tcl @@ -0,0 +1,11 @@ +set x {1 2 3 1e11} +foreach a $x {lappend y [expr {sqrt($a)}]} +set fh [open sqrt.dat w] +foreach a $x b $y { + puts $fh [format "%.*g\t%.*g" $xprecision $a $yprecision $b] +} +close $fh + +set fh [open sqrt.dat] +puts [read $fh [file size sqrt.dat]] +close $fh diff --git a/Task/Write-float-arrays-to-a-text-file/ZX-Spectrum-Basic/write-float-arrays-to-a-text-file.zx b/Task/Write-float-arrays-to-a-text-file/ZX-Spectrum-Basic/write-float-arrays-to-a-text-file.zx new file mode 100644 index 0000000000..c058789e07 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/ZX-Spectrum-Basic/write-float-arrays-to-a-text-file.zx @@ -0,0 +1 @@ +SAVE "myarray" DATA g() diff --git a/Task/Write-language-name-in-3D-ASCII/0DESCRIPTION b/Task/Write-language-name-in-3D-ASCII/0DESCRIPTION new file mode 100644 index 0000000000..faadf0f053 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/0DESCRIPTION @@ -0,0 +1 @@ +The task is to write the language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) diff --git a/Task/Write-language-name-in-3D-ASCII/Ada/write-language-name-in-3d-ascii.ada b/Task/Write-language-name-in-3D-ASCII/Ada/write-language-name-in-3d-ascii.ada new file mode 100644 index 0000000000..fb0039417c --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Ada/write-language-name-in-3d-ascii.ada @@ -0,0 +1,17 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +procedure AsciiArt is + art : constant array(1..27) of String(1..14) := + (1=>" /\\\\\\ ", 2=>" /\\\", + 3|6|9=>" ", 4|12=>" /\\\\\\\\\\ ", + 5|8|11=>" \/\\\", 7|17|21=>" /\\\//////\\\", + 10|19|20|22=>"\/\\\ \/\\\", 13|23|24=>"\/\\\\\\\\\\\\", + 14|18=>" /\\\\\\\\\\\", 15=>" \/////////\\\", + 16=>"\/\\\//////\\\", 25=>"\/// \/// ", + 26|27=>"\//////////// "); +begin + for i in art'Range loop + Put(art(i)&' '); + if i mod 3 = 0 then New_Line; Put(i/3*' '); end if; + end loop; +end AsciiArt; diff --git a/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc b/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc new file mode 100644 index 0000000000..9c416d07cd --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BBC-BASIC/write-language-name-in-3d-ascii.bbc @@ -0,0 +1,22 @@ + PROC3dname("BBC BASIC") + END + + DEF PROC3dname(name$) + LOCAL A%, X%, Y%, char%, row%, patt%, bit% + DIM X% 8 : A% = 10 : Y% = X% DIV 256 + FOR row% = 1 TO 8 + FOR char% = 1 TO LEN(name$) + ?X% = ASCMID$(name$,char%) + CALL &FFF1 + patt% = X%?row% + FOR bit% = 7 TO 0 STEP -1 + CASE TRUE OF + WHEN (patt% AND 2^bit%) <> 0 : PRINT "#"; + WHEN GET$(POS-1,VPOS-1) = "#": PRINT "\"; + OTHERWISE: PRINT " "; + ENDCASE + NEXT + NEXT char% + PRINT + NEXT row% + ENDPROC diff --git a/Task/Write-language-name-in-3D-ASCII/Batch-File/write-language-name-in-3d-ascii.bat b/Task/Write-language-name-in-3D-ASCII/Batch-File/write-language-name-in-3d-ascii.bat new file mode 100644 index 0000000000..deb0b8da7d --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Batch-File/write-language-name-in-3d-ascii.bat @@ -0,0 +1,9 @@ +@echo off +echo ****** ** ** +echo /*////** /** /** +echo /* /** ****** ****** ***** /** +echo /****** //////** ///**/ **///**/****** +echo /*//// ** ******* /** /** // /**///** +echo /* /** **////** /** /** **/** /** +echo /******* //******** //** //***** /** /** +echo /////// //////// // ///// // // diff --git a/Task/Write-language-name-in-3D-ASCII/C/write-language-name-in-3d-ascii.c b/Task/Write-language-name-in-3D-ASCII/C/write-language-name-in-3d-ascii.c new file mode 100644 index 0000000000..c4e00ea8db --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/C/write-language-name-in-3d-ascii.c @@ -0,0 +1,3 @@ +#include +const char*s = " _____\n /____/\\\n/ ___\\/\n\\ \\/__/\n \\____/"; +int main(){ puts(s); return 0; } diff --git a/Task/Write-language-name-in-3D-ASCII/D/write-language-name-in-3d-ascii.d b/Task/Write-language-name-in-3D-ASCII/D/write-language-name-in-3d-ascii.d new file mode 100644 index 0000000000..492244f0bc --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/D/write-language-name-in-3d-ascii.d @@ -0,0 +1,59 @@ +// Derived from AA3D - ASCII art stereogram generator +// by Jan Hubicka and Thomas Marsh +// (GNU General Public License) +// http://aa-project.sourceforge.net/aa3d/ +// http://en.wikipedia.org/wiki/ASCII_stereogram + +import std.stdio, std.string, std.random; + +immutable image = " + 111111111111111 + 1111111111111111 + 11111 1111 + 11111 1111 + 11111 1111 + 11111 1111 + 11111 1111 + 11111 1111 + 1111111111111111 + 111111111111111 + +"; + +void main() { + enum int width = 50; + immutable text = "DLanguage"; + enum int skip = 12; + + char[65536 / 2] data; + + foreach (y, row; image.splitLines()) { + immutable int shift = uniform(0, int.max); + bool l = false; + + foreach (x; 0 .. width) { + int s; + if (!l && x > skip) { + s = (x < row.length) ? row[x] : '\n'; + if (s == ' ') { + s = 0; + } else if (s == '\n') { + s = 0; + l = true; + } else if (s >= '0' && s <= '9') { + s = '0' - s; + } else + s = -2; + } else + s = 0; + + s += skip; + s = x - s; + s = (s < 0) ? text[(x + shift) % text.length] : data[s]; + data[x] = cast(char)s; + write(data[x]); + } + + writeln(); + } +} diff --git a/Task/Write-language-name-in-3D-ASCII/Go/write-language-name-in-3d-ascii.go b/Task/Write-language-name-in-3D-ASCII/Go/write-language-name-in-3d-ascii.go new file mode 100644 index 0000000000..a69ebda12e --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Go/write-language-name-in-3d-ascii.go @@ -0,0 +1,93 @@ +package main + +import ( + "fmt" + "strings" +) + +var lean = font{ + height: 5, + slant: 1, + spacing: 2, + m: map[rune][]string{ + 'G': []string{ + ` _/_/_/`, + `_/ `, + `_/ _/_/`, + `_/ _/`, + ` _/_/_/`, + }, + 'o': []string{ + ` `, + ` _/_/ `, + `_/ _/`, + `_/ _/`, + ` _/_/ `, + }, + }} + +var smallKeyboard = font{ + height: 4, + slant: 0, + spacing: -1, + m: map[rune][]string{ + 'G': []string{ + ` ____ `, + `||G ||`, + `||__||`, + `|/__\|`, + }, + 'o': []string{ + ` ____ `, + `||o ||`, + `||__||`, + `|/__\|`, + }, + }} + +type font struct { + height int + slant int + spacing int + m map[rune][]string +} + +func render(s string, f font) string { + rows := make([]string, f.height) + if f.slant != 0 { + start := 0 + if f.slant > 0 { + start = f.height + } + for i := range rows { + rows[i] = strings.Repeat(" ", (start-i)*f.slant) + } + } + if f.spacing >= 0 { + spacing := strings.Repeat(" ", f.spacing) + for j, c := range s { + for i, r := range f.m[c] { + if j > 0 { + r = spacing + r + } + rows[i] += r + } + } + } else { + overlap := -f.spacing + for j, c := range s { + for i, r := range f.m[c] { + if j > 0 { + r = r[overlap:] + } + rows[i] += r + } + } + } + return strings.Join(rows, "\n") +} + +func main() { + fmt.Println(render("Go", lean)) + fmt.Println(render("Go", smallKeyboard)) +} diff --git a/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs b/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs new file mode 100644 index 0000000000..73a56cf18f --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Haskell/write-language-name-in-3d-ascii.hs @@ -0,0 +1,22 @@ +module Main where +{- + __ __ __ ___ ___ +/\ \/\ \ /\ \ /\_ \ /\_ \ +\ \ \_\ \ __ ____\ \ \/'\ __\//\ \ \//\ \ + \ \ _ \ /'__`\ /',__\\ \ , < /'__`\\ \ \ \ \ \ + \ \ \ \ \/\ \L\.\_/\__, `\\ \ \\`\ /\ __/ \_\ \_ \_\ \_ + \ \_\ \_\ \__/.\_\/\____/ \ \_\ \_\ \____\/\____\/\____\ + \/_/\/_/\/__/\/_/\/___/ \/_/\/_/\/____/\/____/\/____/ +-} + +ascii3d :: String +ascii3d = " __ __ __ ___ ___ \n" ++ + "/\\ \\/\\ \\ /\\ \\ /\\_ \\ /\\_ \\ \n" ++ + "\\ \\ \\_\\ \\ __ ____\\ \\ \\/'\\ __\\//\\ \\ \\//\\ \\ \n" ++ + " \\ \\ _ \\ /'__`\\ /',__\\\\ \\ , < /'__`\\\\ \\ \\ \\ \\ \\ \n" ++ + " \\ \\ \\ \\ \\/\\ \\L\\.\\_/\\__, `\\\\ \\ \\\\`\\ /\\ __/ \\_\\ \\_ \\_\\ \\_ \n" ++ + " \\ \\_\\ \\_\\ \\__/.\\_\\/\\____/ \\ \\_\\ \\_\\ \\____\\/\\____\\/\\____\\\n" ++ + " \\/_/\\/_/\\/__/\\/_/\\/___/ \\/_/\\/_/\\/____/\\/____/\\/____/" + +main = do + putStrLn ascii3d diff --git a/Task/Write-language-name-in-3D-ASCII/Icon/write-language-name-in-3d-ascii.icon b/Task/Write-language-name-in-3D-ASCII/Icon/write-language-name-in-3d-ascii.icon new file mode 100644 index 0000000000..62e9d49538 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Icon/write-language-name-in-3d-ascii.icon @@ -0,0 +1,34 @@ +procedure main(arglist) +write(ExpandText( + if !arglist == "icon" then + "14/\\\n14\\/\n12/\\\n11/1/\n10/1/1/\\\n10\\/1/2\\\n12/1/\\1\\\n_ + 12\\1\\1\\/\n10/\\1\\1\\2/\\\n9/2\\1\\/1/2\\\n_ + 8/1/\\1\\2/1/\\1\\2/\\\n8\\1\\/1/2\\1\\/1/2\\1\\\n_ + 6/\\1\\2/4\\2/1/\\1\\1\\\n5/1/2\\/6\\/1/2\\1\\/\n_ + /\\2/1/1/\\10/1/\\1\\2/\\\n\\/2\\1\\/1/10\\/1/1/2\\/\n_ + 2/\\1\\2/1/\\6/\\2/1/\n2\\1\\1\\/1/2\\4/2\\1\\/\n_ + 3\\1\\2/1/\\1\\2/1/\\1\\\n4\\/2\\1\\/1/2\\1\\/1/\n_ + 9\\2/1/\\1\\2/\n10\\/2\\1\\1\\/\n12/\\1\\1\\\n12\\1\\/1/\n_ + 13\\2/1/\\\n14\\/1/1/\n16/1/\n16\\/\n14/\\\n14\\/\n" + else + "13/\\\n12/1/\n11/1/1/\\\n11\\1\\/1/\n12\\2/1/\\\n13\\/1/2\\\n_ + 15/1/\\1\\2/\\\n15\\/1/1/2\\/\n17/1/1/\\18/\\\n17\\/1/1/17/2\\\n_ + 19/1/1/\\14/1/\\1\\\n19\\/1/2\\13\\1\\1\\/\n21/1/\\1\\10/\\1\\1\\\n_ + 21\\1\\1\\/10\\1\\1\\/\n19/\\1\\1\\2/\\6/\\1\\1\\\n_ + 18/2\\1\\/1/2\\5\\1\\/1/\n17/1/\\1\\2/1/\\1\\2/\\1\\2/\n_ + 17\\1\\/1/2\\1\\/1/2\\1\\1\\/\n15/\\1\\2/4\\2/1/\\1\\1\\\n_ + 14/1/2\\/6\\/1/2\\1\\/\n9/\\2/1/1/\\10/1/\\1\\2/\\\n_ + 9\\/2\\1\\/1/10\\/1/1/2\\/\n11/\\1\\2/1/\\6/\\2/1/\n_ + 11\\1\\1\\/1/2\\4/2\\1\\/\n9/\\1\\1\\2/1/\\1\\2/1/\\1\\\n_ + 8/2\\1\\/2\\1\\/1/2\\1\\/1/\n7/1/\\1\\5\\2/1/\\1\\2/\n_ + 7\\1\\1\\/6\\/2\\1\\1\\/\n5/\\1\\1\\10/\\1\\1\\\n_ + 5\\1\\1\\/10\\1\\/1/\n3/\\1\\1\\13\\2/1/\\\n3\\1\\/1/14\\/1/1/\n_ + 4\\2/17/1/1/\\\n5\\/18\\/1/1/\n23/\\2/1/1/\\\n23\\/2\\1\\/1/\n_ + 28\\2/1/\\\n29\\/1/2\\\n31/1/\\1\\\n31\\/1/1/\n33/1/\n33\\/\n" + )) +end + +procedure ExpandText(s) +s ? until pos(0) do + writes(repl(" ",tab(many(&digits)))|tab(upto(&digits)|0)) +end diff --git a/Task/Write-language-name-in-3D-ASCII/J/write-language-name-in-3d-ascii.j b/Task/Write-language-name-in-3D-ASCII/J/write-language-name-in-3d-ascii.j new file mode 100644 index 0000000000..fe9096e389 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/J/write-language-name-in-3d-ascii.j @@ -0,0 +1,22 @@ + require 'vrml.ijs' NB. Due to Andrew Nikitin + view 5#.^:_1]21-~a.i.'j*ez`C3\toy.G)' NB. Due to Oleg Kobchenko + ________________________ + |\ \ \ \ \ + | \_____\_____\_____\_____\ + | | | | |\ \ + |\| | | | \_____\ + | \_____|_____|_____| | | + | | | | | |\| | + \| | |\| | \_____| + \_____| | \_____| + | | | + |\| | + | \_____| + ______ | | | +|\ \ |\| | +| \_____\_________|_\_____| +| |\ \ \ \ | + \| \_____\_____\_____\ | + | | | | |___| + \| | | | + \_____|_____|_____| diff --git a/Task/Write-language-name-in-3D-ASCII/NetRexx/write-language-name-in-3d-ascii.netrexx b/Task/Write-language-name-in-3D-ASCII/NetRexx/write-language-name-in-3d-ascii.netrexx new file mode 100644 index 0000000000..f0dfcbcbc8 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/NetRexx/write-language-name-in-3d-ascii.netrexx @@ -0,0 +1,65 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +txt = ''; +x = 0 +x = x + 1; txt[0] = x; txt[x] = ' * * *****' +x = x + 1; txt[0] = x; txt[x] = ' ** * * * *' +x = x + 1; txt[0] = x; txt[x] = ' * * * *** *** * * *** * * * *' +x = x + 1; txt[0] = x; txt[x] = ' * * * * * * ***** * * * * * *' +x = x + 1; txt[0] = x; txt[x] = ' * ** ***** * * * ***** * *' +x = x + 1; txt[0] = x; txt[x] = ' * * * * * * * * * * *' +x = x + 1; txt[0] = x; txt[x] = ' * * *** ** * * *** * * * *' +x = x + 1; txt[0] = x; txt[x] = '' + +_top = '_TOP' +_bot = '_BOT' +txt = Banner3D(txt, isTrue()) +loop ll = 1 to txt[0] + say txt[ll, _top] + say txt[ll, _bot] + end ll + +return + +method Banner3D(txt, slope = '') public static + + select + when slope = isTrue() then nop + when slope = isFalse() then nop + otherwise do + if slope = '' then slope = isFalse() + else slope = isTrue() + end + end + + _top = '_TOP' + _bot = '_BOT' + loop ll = 1 to txt[0] + txt[ll, _top] = txt[ll] + txt[ll, _bot] = txt[ll] + txt[ll, _top] = txt[ll, _top].changestr(' ', ' ') + txt[ll, _bot] = txt[ll, _bot].changestr(' ', ' ') + txt[ll, _top] = txt[ll, _top].changestr('*', '///') + txt[ll, _bot] = txt[ll, _bot].changestr('*', '\\\\\\') + txt[ll, _top] = txt[ll, _top] || ' ' + txt[ll, _bot] = txt[ll, _bot] || ' ' + txt[ll, _top] = txt[ll, _top].changestr('/ ', '/\\') + txt[ll, _bot] = txt[ll, _bot].changestr('\\ ', '\\/') + end ll + + if slope then do + loop li = txt[0] to 1 by -1 + ll = txt[0] - li + 1 + txt[ll, _top] = txt[ll, _top].insert('', 1, li - 1, ' ') + txt[ll, _bot] = txt[ll, _bot].insert('', 1, li - 1, ' ') + end li + end + + return txt + +method isTrue public constant binary returns boolean + return 1 == 1 + +method isFalse public constant binary returns boolean + return \isTrue() diff --git a/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 b/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 new file mode 100644 index 0000000000..f6f86b18d4 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 @@ -0,0 +1,3 @@ +print >>.ords>>.comb.map({(" |/\\\n_".comb)[$_-4]}); diff --git a/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii.py b/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii.py new file mode 100644 index 0000000000..e048065e9c --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii.py @@ -0,0 +1,12 @@ +py = '''\ + ##### # # ##### # # #### # # + # # # # # # # # # ## # + # # # # ###### # # # # # + ##### # # # # # # # # # + # # # # # # # # ## + # # # # # #### # # +''' + +lines = py.replace('#', '<<<').replace(' ','X').replace('X', ' ').replace('\n', ' Y').replace('< ', '<>').split('Y') +for i, l in enumerate(lines): + print( ' ' * (len(lines) - i) + l) diff --git a/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-1.rexx b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-1.rexx new file mode 100644 index 0000000000..6c14e05884 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-1.rexx @@ -0,0 +1,27 @@ +/*REXX program that displays a "REXX" 3D "ASCII art" as a logo. */ +signal . /* Uses left-hand shadows, slightly raised view. +0=5~2?A?2?A? +@)E)3@)B)1)2)8()2)1)2)8()2) +@]~")2@]0`)0@)%)6{)%)0@)%)6{)%) +#E)1#A@0}2)4;2(1}2)4;2( +#3??3@0#2??@1}2)2;2(3}2)2;2( +#2@5@)@2@0#2@A}2)0;2(5}2)0;2( +#2@?"@)@2@0#2@?7}2){2(7}2){2( +#2@6)@2@0#2@3)7}2)(2(9}2)(2( +#2@??@2@0#2@?_)7}5(B}5( +#F@0#8@8}3(D}3( +#3%3?(1#3?_@7;3)C;3) +#2@0}2)5#2@C;5)A;5) +#2@1}2)4#2@B;2()2)8;2()2) +#2@2}2)3#2@?"4;2(}2)6;2(}2) +#2@3}2)2#2@5)2;2(1}2)4;2(1}2) +#2@4}2)1#2@?%)0;2(3}2)2;2(3}2) +0]@2@5}2)1]@A@0)[2(5}2)1)[2(5}2) +1)@%@6}%)1)@`@1V%(7}%)1V%(7}%) +*/;.:a=sigL+1;signal ..;..:u='_';do j=a to sigl-1 +_=sourceline(j);_=_('(',"/");_=_('[',"//");_=_('{',"///") +_=_(';',"////");_=_(')',"\");_=_(']',"\\");_=_('}',"\\\");_=_('"',"__") +_=_('%',"___");_=_('?',left('',4,u));_=_('`',left('',11,u));_=_('~',left('', +,13,u));_=_('=',left('',16,u));_=_('#','|\\|');_=translate(_,"|"u,'@"') +do k=0 for 16;x=d2x(k,1);_=_(x,left('',k+1));end;say ' '_;end;exit;_:return, +changestr(arg(1),_,arg(2)) diff --git a/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-2.rexx b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-2.rexx new file mode 100644 index 0000000000..7f1cb290ca --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-2.rexx @@ -0,0 +1,67 @@ +/* Rexx */ + +drop !top !bot +x = 0 +x = x + 1; txt.0 = x; txt.x = ' *****' +x = x + 1; txt.0 = x; txt.x = ' * *' +x = x + 1; txt.0 = x; txt.x = ' * * ***** * * * *' +x = x + 1; txt.0 = x; txt.x = ' ***** * * * * *' +x = x + 1; txt.0 = x; txt.x = ' * * *** * *' +x = x + 1; txt.0 = x; txt.x = ' * * * * * * *' +x = x + 1; txt.0 = x; txt.x = ' * * ***** * * * *' +x = x + 1; txt.0 = x; txt.x = '' + +call Banner3D isTrue() +do ll = 1 to txt.0 + say txt.ll.!top + say txt.ll.!bot + end ll + +return +exit + +Banner3D: +procedure expose txt. + drop !top !bot + parse arg slope . + + select + when slope = isTrue() then nop + when slope = isFalse() then nop + otherwise do + if slope = '' then slope = isFalse() + else slope = isTrue() + end + end + + do ll = 1 to txt.0 + txt.ll.!top = txt.ll + txt.ll.!bot = txt.ll + txt.ll.!top = changestr(' ', txt.ll.!top, ' ') + txt.ll.!bot = changestr(' ', txt.ll.!bot, ' ') + txt.ll.!top = changestr('*', txt.ll.!top, '///') + txt.ll.!bot = changestr('*', txt.ll.!bot, '\\\') + txt.ll.!top = txt.ll.!top || ' ' + txt.ll.!bot = txt.ll.!bot || ' ' + txt.ll.!top = changestr('/ ', txt.ll.!top, '/\') + txt.ll.!bot = changestr('\ ', txt.ll.!bot, '\/') + end ll + + if slope then do + do li = txt.0 to 1 by -1 + ll = txt.0 - li + 1 + txt.ll.!top = insert('', txt.ll.!top, 1, li - 1, ' ') + txt.ll.!bot = insert('', txt.ll.!bot, 1, li - 1, ' ') + end li + end + + return +exit + +isTrue: +procedure + return 1 == 1 + +isFalse: +procedure + return \isTrue() diff --git a/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-3.rexx b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-3.rexx new file mode 100644 index 0000000000..cea24c7704 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/REXX/write-language-name-in-3d-ascii-3.rexx @@ -0,0 +1,18 @@ +/*REXX pgm draws a "3D" image of text representation (* MUST be used).*/ +m.1 = '**** ' +m.2 = '* * ' +m.3 = '* * *** * * * * ' +m.4 = '**** * * * * * ' +m.5 = '* * ** * * ' +m.6 = '* * * * * * * ' +m.7 = '* * *** * * * * ' +lines=7 /*number of lines of text for 3D.*/ + do j=1 for lines /*build the artwork for the text.*/ + A.j.1 = changestr( " " , m.j, ' ' ) ; A.j.2 = A.j.1 + A.j.1 = changestr( "*" , A.j.1, '///' )" " + A.j.2 = changestr( "*" , A.j.2, '\\\' )" " + A.j.1 = changestr( "/ ", A.j.1, '/\' ) + A.j.2 = changestr( "\ ", A.j.2, '\/' ) + do k=1 for 2; say strip(left('',lines-j) || A.j.k,'T'); end + end /*j*/ /* [↑] show a line and its shadow*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala new file mode 100644 index 0000000000..81ea8be9a8 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Scala/write-language-name-in-3d-ascii.scala @@ -0,0 +1,76 @@ +def ASCII3D = { + + val name = """ + * + ** ** * * * + * * * * * * * + * * * * * * * + * * *** * *** + * * * * * * * + * * * * * * * + ** ** * * *** * * + * + * + """ + + + // + // Create Array + // + + def getMaxSize( s:String ) : (Int,Int) = { + + var width = 0 + var height = 0 + + val nameArray = s.split("\n") + + height = nameArray.size + nameArray foreach {i => width = (i.size max width)} + + (width,height) + } + + val size = getMaxSize( name ) + + var arr = Array.fill( size._2+1, (size._1*3)+(size._2+1) )( ' ' ) + + + // + // Map astrisk to 3D cube + // + val cubeTop = """///\""" + val cubeBottom = """\\\/""" + + val nameArray = name.split("\n") + + for( j <- (0 until nameArray.size) ) { + + for( i <- (0 until nameArray(j).size) ) { + + if( nameArray(j)(i) == '*' ) + { + val indent = nameArray.size - j + + arr(j ) = arr(j ) patch ((i*3 + indent), cubeTop, cubeTop.size) + arr(j+1) = arr(j+1) patch ((i*3 + indent), cubeBottom, cubeBottom.size) + } + } + } + + // + // Map Array to String + // + var name3D = "" + + for( j <- (0 until arr.size) ) { + + for( i <- (0 until arr(j).size) ) { name3D += arr(j)(i) } + + name3D += "\n" + } + + name3D +} + +println(ASCII3D) diff --git a/Task/Write-language-name-in-3D-ASCII/Tcl/write-language-name-in-3d-ascii.tcl b/Task/Write-language-name-in-3D-ASCII/Tcl/write-language-name-in-3d-ascii.tcl new file mode 100644 index 0000000000..48e6cca6ee --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Tcl/write-language-name-in-3d-ascii.tcl @@ -0,0 +1,36 @@ +package require Tcl 8.5 + +proc mergeLine {upper lower} { + foreach u [split $upper ""] l [split $lower ""] { + lappend result [expr {$l in {" " ""} ? $u : $l}] + } + return [join $result ""] +} +proc printLines lines { + set n [llength $lines] + foreach line $lines { + set indent [string repeat " " $n] + lappend upper $indent[string map {"/ " "/\\"} [ + string map {" " " " "*" "///"} "$line "]] + lappend lower $indent[string map {"\\ " "\\/"} [ + string map {" " " " "*" "\\\\\\"} "$line "]] + incr n -1 + } + # Now do some line merging to strengthen the visual effect + set p [string repeat " " [string length [lindex $upper 0]]] + foreach u $upper l $lower { + puts [mergeLine $p $u] + set p $l + } + puts $p +} + +set lines { + {***** *} + { * *} + { * *** *} + { * * *} + { * * *} + { * *** *} +} +printLines $lines diff --git a/Task/Write-language-name-in-3D-ASCII/XPL0/write-language-name-in-3d-ascii.xpl0 b/Task/Write-language-name-in-3D-ASCII/XPL0/write-language-name-in-3d-ascii.xpl0 new file mode 100644 index 0000000000..819e840c84 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/XPL0/write-language-name-in-3d-ascii.xpl0 @@ -0,0 +1,27 @@ +include c:\cxpl\codes; + +proc DrawBlock(X, Y); +int X, Y; +[Cursor(X+1, Y); Text(0, "///\"); + Cursor(X, Y+1); Text(0,"/// \"); + Cursor(X, Y+2); Text(0,"\\\ /"); + Cursor(X+1, Y+3); Text(0, "\\\/"); +]; + +int Data, D, X, Y; +[ChOut(0, $C); \form feed, clears screen +Data:= [%1000100011110000100000001110, + %1000100010001000100000010001, + %0101000010001000100000010011, + %0010000011110000100000010101, + %0101000010000000100000011001, + %1000100010000000100000010001, + %1000100010000000111110001110]; +for Y:= 0 to 6 do + [D:= Data(Y); + for X:= 0 to 27 do + [if D&1<<27 then DrawBlock(X*2+(6-Y)*2, Y*2); + D:= D<<1; + ]; + ]; +] diff --git a/Task/Write-language-name-in-3D-ASCII/ZX-Spectrum-Basic/write-language-name-in-3d-ascii.zx b/Task/Write-language-name-in-3D-ASCII/ZX-Spectrum-Basic/write-language-name-in-3d-ascii.zx new file mode 100644 index 0000000000..ec0c10912b --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/ZX-Spectrum-Basic/write-language-name-in-3d-ascii.zx @@ -0,0 +1,48 @@ +10 LET s$="BASIC": REM our language name +20 DIM b(5,5):REM our bigmap characters +30 FOR l = 1 TO 5: REM 5 characters +40 FOR m = 1 TO 5: REM 5 rows +50 READ b(l,m) +60 NEXT m +70 NEXT l + +100 PAPER 0: REM black background +110 INK 2: REM our shadow will be red +120 CLS +130 LET r=9: REM shadow will start on row 5 +140 LET c=2: REM shadow will start at column 2 +150 GO SUB 2000: REM draw shadow +160 INK 6: REM our forground will be yellow +170 LET r=10: REM foreground will start on row 6 +180 LET c=3: REM foreground will start on column 3 +190 GO SUB 2000: REM display the language name + +999 STOP + +1000 REM convert to binary bigmap +1010 LET t=n: REM temporary variable +1020 LET g$="": REM this will contain our 5 character binary bigmap +1040 FOR z=5 TO 0 STEP -1 +1050 LET d$=" ": REM assume next digit is zero (draw a space) +1060 IF t>=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block +1070 LET g$=g$+d$ +1080 NEXT z +1090 RETURN + +2000 REM display the big letters +2010 FOR l=1 TO 5: REM our 5 rows +2020 PRINT AT r+l-1,c; +2030 FOR m=1 TO 5: REM bigmap for each character +2040 LET n=b(l,m) +2050 GO SUB 1000 +2060 PRINT g$;: REM 5 character bigmap +2070 PRINT " ";: REM space between each letter +2080 NEXT m +2090 NEXT l +2100 RETURN + +9000 DATA 30,17,30,17,30: REM B +9010 DATA 14,17,31,17,17: REM A +9020 DATA 15,16,14,1,30: REM S +9030 DATA 31,4,4,4,31: REM I +9040 DATA 14,17,16,17,14: REM C diff --git a/Task/Write-to-Windows-event-log/0DESCRIPTION b/Task/Write-to-Windows-event-log/0DESCRIPTION new file mode 100644 index 0000000000..1a5b271da1 --- /dev/null +++ b/Task/Write-to-Windows-event-log/0DESCRIPTION @@ -0,0 +1 @@ +Write script status to the Windows Event Log diff --git a/Task/Write-to-Windows-event-log/BBC-BASIC/write-to-windows-event-log.bbc b/Task/Write-to-Windows-event-log/BBC-BASIC/write-to-windows-event-log.bbc new file mode 100644 index 0000000000..a9224ca1a5 --- /dev/null +++ b/Task/Write-to-Windows-event-log/BBC-BASIC/write-to-windows-event-log.bbc @@ -0,0 +1,8 @@ + INSTALL @lib$+"COMLIB" + PROC_cominitlcid(1033) + + WshShell% = FN_createobject("WScript.Shell") + PROC_callmethod(WshShell%, "LogEvent(0, ""Test from BBC BASIC"")") + + PROC_releaseobject(WshShell%) + PROC_comexit diff --git a/Task/Write-to-Windows-event-log/C-sharp/write-to-windows-event-log.cs b/Task/Write-to-Windows-event-log/C-sharp/write-to-windows-event-log.cs new file mode 100644 index 0000000000..827faf87a0 --- /dev/null +++ b/Task/Write-to-Windows-event-log/C-sharp/write-to-windows-event-log.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; + +namespace RC +{ + internal class Program + { + public static void Main() + { + string sSource = "Sample App"; + string sLog = "Application"; + string sEvent = "Hello from RC!"; + + if (!EventLog.SourceExists(sSource)) + EventLog.CreateEventSource(sSource, sLog); + + EventLog.WriteEntry(sSource, sEvent); + EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information); + } + } +} diff --git a/Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.delphi b/Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.delphi new file mode 100644 index 0000000000..181a056563 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.delphi @@ -0,0 +1,26 @@ +program WriteToEventLog; + +{$APPTYPE CONSOLE} + +uses Windows; + +procedure WriteLog(aMsg: string); +var + lHandle: THandle; + lMessagePtr: Pointer; +begin + lMessagePtr := PChar(aMsg); + lHandle := RegisterEventSource(nil, 'Logger'); + if lHandle > 0 then + begin + try + ReportEvent(lHandle, 4 {Information}, 0, 0, nil, 1, 0, @lMessagePtr, nil); + finally + DeregisterEventSource(lHandle); + end; + end; +end; + +begin + WriteLog('Message to log.'); +end. diff --git a/Task/Write-to-Windows-event-log/PicoLisp/write-to-windows-event-log.l b/Task/Write-to-Windows-event-log/PicoLisp/write-to-windows-event-log.l new file mode 100644 index 0000000000..e0fa33c575 --- /dev/null +++ b/Task/Write-to-Windows-event-log/PicoLisp/write-to-windows-event-log.l @@ -0,0 +1,5 @@ +: (call 'logger "This is a test") +-> T + +: (call 'logger "This" 'is "another" 'test) +-> T diff --git a/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log.psh b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log.psh new file mode 100644 index 0000000000..b1247aadaf --- /dev/null +++ b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log.psh @@ -0,0 +1,13 @@ +# Create Event Log object +$EventLog=new-object System.Diagnostics.EventLog("Application") +#Declare Event Source; must be 'registered' with Windows +$EventLog.Source="Application" # It is possible to register a new source (see Note2) +# Setup the Event Types; you don't have to use them all, but I'm including all the possibilities for reference +$infoEvent=[System.Diagnostics.EventLogEntryType]::Information +$errorEvent=[System.Diagnostics.EventLogEntryType]::Error +$warningEvent=[System.Diagnostics.EventLogEntryType]::Warning +$successAuditEvent=[System.Diagnostics.EventLogEntryType]::SuccessAudit +$failureAuditEvent=[System.Diagnostics.EventLogEntryType]::FailureAudit + +# Write the event in the format "Event test",EventType,EventID +$EventLog.WriteEntry("My Test Event",$infoevent,70) diff --git a/Task/Write-to-Windows-event-log/PureBasic/write-to-windows-event-log.purebasic b/Task/Write-to-Windows-event-log/PureBasic/write-to-windows-event-log.purebasic new file mode 100644 index 0000000000..e607a7fc2a --- /dev/null +++ b/Task/Write-to-Windows-event-log/PureBasic/write-to-windows-event-log.purebasic @@ -0,0 +1,14 @@ +Procedure WriteToLog(Event_App$,EventMessage$,EvenetType,Computer$) + + Protected wNumStrings.w, lpString=@EventMessage$, lReturnX, CMessageTyp, lparray + Protected lprawdata=@EventMessage$, rawdata=Len(EventMessage$), Result + Protected lLogAPIRetVal.l = RegisterEventSource_(Computer$, Event_App$) + + If lLogAPIRetVal + lReturnX = ReportEvent_(lLogAPIRetVal,EvenetType,0,CMessageTyp,0,wNumStrings,rawdata,lparray,lprawdata + DeregisterEventSource_(lLogAPIRetVal) + Result=#True + EndIf + + ProcedureReturn Result +EndProcedure diff --git a/Task/Write-to-Windows-event-log/Python/write-to-windows-event-log.py b/Task/Write-to-Windows-event-log/Python/write-to-windows-event-log.py new file mode 100644 index 0000000000..57ae341dce --- /dev/null +++ b/Task/Write-to-Windows-event-log/Python/write-to-windows-event-log.py @@ -0,0 +1,19 @@ +import win32api +import win32con +import win32evtlog +import win32security +import win32evtlogutil + +ph = win32api.GetCurrentProcess() +th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ) +my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0] + +applicationName = "My Application" +eventID = 1 +category = 5 # Shell +myType = win32evtlog.EVENTLOG_WARNING_TYPE +descr = ["A warning", "An even more dire warning"] +data = "Application\0Data".encode("ascii") + +win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category, + eventType=myType, strings=descr, data=data, sid=my_sid) diff --git a/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx new file mode 100644 index 0000000000..76701de5b2 --- /dev/null +++ b/Task/Write-to-Windows-event-log/REXX/write-to-windows-event-log.rexx @@ -0,0 +1,13 @@ +/*REXX program writes a "record" (event) to the (MS) Windows event log.*/ + + eCMD = 'EVENTCREATE' + type = 'INFORMATION' /*one of: ERROR WARNING INFORMATION */ + id = 234 /*in range: 1 ───► 1000 (inclusive).*/ + logName = 'APPLICATION' + source = 'REXX' + desc = 'attempting to add an entry for Rosetta Code demonstration.' + desc = '"' || desc '"' /*enclose DESCription in double quotes.*/ + +eCMD '/T' type "/ID" id '/L' logName "/SO" source '/D' desc + + /*stick a fork in it honey, we're done.*/ diff --git a/Task/Write-to-Windows-event-log/Ruby/write-to-windows-event-log.rb b/Task/Write-to-Windows-event-log/Ruby/write-to-windows-event-log.rb new file mode 100644 index 0000000000..bbb9e15a04 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Ruby/write-to-windows-event-log.rb @@ -0,0 +1,3 @@ +require 'win32/eventlog' +logger = Win32::EventLog.new +logger.report_event(:event_type => Win32::EventLog::INFO, :data => "a test event log entry") diff --git a/Task/Write-to-Windows-event-log/Tcl/write-to-windows-event-log.tcl b/Task/Write-to-Windows-event-log/Tcl/write-to-windows-event-log.tcl new file mode 100644 index 0000000000..360ed159f2 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Tcl/write-to-windows-event-log.tcl @@ -0,0 +1,4 @@ +package require twapi + +# This command handles everything; use “-type error” to write an error message +twapi::eventlog_log "My Test Event" -type info diff --git a/Task/XML-DOM-serialization/0DESCRIPTION b/Task/XML-DOM-serialization/0DESCRIPTION new file mode 100644 index 0000000000..ef6639a56f --- /dev/null +++ b/Task/XML-DOM-serialization/0DESCRIPTION @@ -0,0 +1,8 @@ +Create a simple DOM and having it serialize to: + + + + + Some text here + + diff --git a/Task/XML-DOM-serialization/1META.yaml b/Task/XML-DOM-serialization/1META.yaml new file mode 100644 index 0000000000..d7f654b55d --- /dev/null +++ b/Task/XML-DOM-serialization/1META.yaml @@ -0,0 +1,2 @@ +--- +note: XML diff --git a/Task/XML-DOM-serialization/Ada/xml-dom-serialization.ada b/Task/XML-DOM-serialization/Ada/xml-dom-serialization.ada new file mode 100644 index 0000000000..784bec9825 --- /dev/null +++ b/Task/XML-DOM-serialization/Ada/xml-dom-serialization.ada @@ -0,0 +1,24 @@ +with Ada.Text_IO.Text_Streams; +with DOM.Core.Documents; +with DOM.Core.Nodes; + +procedure Serialization is + My_Implementation : DOM.Core.DOM_Implementation; + My_Document : DOM.Core.Document; + My_Root_Node : DOM.Core.Element; + My_Element_Node : DOM.Core.Element; + My_Text_Node : DOM.Core.Text; +begin + My_Document := DOM.Core.Create_Document (My_Implementation); + My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, "root"); + My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node); + My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, "element"); + My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node); + My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, "Some text here"); + My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node); + DOM.Core.Nodes.Write + (Stream => Ada.Text_IO.Text_Streams.Stream + (Ada.Text_IO.Standard_Output), + N => My_Document, + Pretty_Print => True); +end Serialization; diff --git a/Task/XML-DOM-serialization/AutoHotkey/xml-dom-serialization.ahk b/Task/XML-DOM-serialization/AutoHotkey/xml-dom-serialization.ahk new file mode 100644 index 0000000000..c72f45baa1 --- /dev/null +++ b/Task/XML-DOM-serialization/AutoHotkey/xml-dom-serialization.ahk @@ -0,0 +1,36 @@ +version = "1.0" +xmlheader := "" . "<" . root . ">" + +element("root", "child") +element("root", "element", "more text here") +element("root_child", "kid", "yak yak") +MsgBox % xmlheader . serialize("root") +Return + +element(parent, name, text="") +{ + Global + %parent%_children .= name . "`n" + %parent%_%name% = %parent%_%name% + %parent%_%name%_name := name + %parent%_%name%_text := text +} + +serialize(root){ + StringSplit, root, root, _ + xml .= "<" . root%root0% . ">" + StringTrimRight, %root%_children, %root%_children, 1 + Loop, Parse, %root%_children, `n + { + If %root%_%A_LoopField%_children + xml .= serialize(%root%_%A_LoopField%) + Else + { + element := "<" . %root%_%A_LoopField%_name . ">" + element .= %root%_%A_LoopField%_text + element .= "" + xml .= element + } + } + Return xml .= "" +} diff --git a/Task/XML-DOM-serialization/C-sharp/xml-dom-serialization.cs b/Task/XML-DOM-serialization/C-sharp/xml-dom-serialization.cs new file mode 100644 index 0000000000..35b21ce302 --- /dev/null +++ b/Task/XML-DOM-serialization/C-sharp/xml-dom-serialization.cs @@ -0,0 +1,16 @@ +using System.Xml; +using System.Xml.Serialization; +[XmlRoot("root")] +public class ExampleXML +{ + [XmlElement("element")] + public string element = "Some text here"; + static void Main(string[] args) + { + var xmlnamespace = new XmlSerializerNamespaces(); + xmlnamespace.Add("", ""); //used to stop default namespaces from printing + var writer = XmlWriter.Create("output.xml"); + new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace); + } + //Output: Some text here +} diff --git a/Task/XML-DOM-serialization/C/xml-dom-serialization.c b/Task/XML-DOM-serialization/C/xml-dom-serialization.c new file mode 100644 index 0000000000..1decaac5ee --- /dev/null +++ b/Task/XML-DOM-serialization/C/xml-dom-serialization.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include + +int main() +{ + const char **next; + int a; + FILE *outFile; + + xmlDoc *doc = xmlNewDoc("1.0"); + xmlNode *root = xmlNewNode(NULL, "root"); + xmlDocSetRootElement(doc, root); + + xmlNode *node = xmlNewNode(NULL, "element"); + xmlAddChild(node, xmlNewText("some text here")); + xmlAddChild(root, node); + + outFile = fopen("myfile.xml", "w"); + xmlElemDump(outFile, doc, root); + fclose(outFile); + + xmlFreeDoc(doc); + xmlCleanupParser(); + + return EXIT_SUCCESS; +} diff --git a/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-1.lisp b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-1.lisp new file mode 100644 index 0000000000..ab57632846 --- /dev/null +++ b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-1.lisp @@ -0,0 +1,8 @@ +(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil)) + (root (dom:create-element doc "root")) + (element (dom:create-element doc "element")) + (text (dom:create-text-node doc "Some text here"))) + (dom:append-child element text) + (dom:append-child root element) + (dom:append-child doc root) + (dom:map-document (cxml:make-rod-sink) doc)) diff --git a/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-2.lisp b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-2.lisp new file mode 100644 index 0000000000..3b42552aa0 --- /dev/null +++ b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-2.lisp @@ -0,0 +1,7 @@ +(let ((doc (dom:create-document 'rune-dom:implementation nil nil nil))) + (dom:append-child + (dom:append-child + (dom:append-child doc (dom:create-element doc "root")) + (dom:create-element doc "element")) + (dom:create-text-node doc "Some text here")) + (write-string (dom:map-document (cxml:make-rod-sink) doc))) diff --git a/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-3.lisp b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-3.lisp new file mode 100644 index 0000000000..fc2747cd46 --- /dev/null +++ b/Task/XML-DOM-serialization/Common-Lisp/xml-dom-serialization-3.lisp @@ -0,0 +1,9 @@ +(defun append-child* (parent &rest children) + (reduce 'dom:append-child children :initial-value parent)) + +(let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))) + (append-child* doc + (dom:create-element doc "root") + (dom:create-element doc "element") + (dom:create-text-node doc "Some text here")) + (write-string (dom:map-document (cxml:make-rod-sink) doc))) diff --git a/Task/XML-DOM-serialization/D/xml-dom-serialization.d b/Task/XML-DOM-serialization/D/xml-dom-serialization.d new file mode 100644 index 0000000000..407f12a64e --- /dev/null +++ b/Task/XML-DOM-serialization/D/xml-dom-serialization.d @@ -0,0 +1,12 @@ +module xmltest ; + +import std.stdio ; +import std.xml ; + +void main() { + auto doc = new Document("root") ; +//doc.prolog = q"//" ; // default + doc ~= new Element("element", "Some text here") ; + writefln(doc) ; +// output: Some text here +} diff --git a/Task/XML-DOM-serialization/E/xml-dom-serialization.e b/Task/XML-DOM-serialization/E/xml-dom-serialization.e new file mode 100644 index 0000000000..a2d57cfd06 --- /dev/null +++ b/Task/XML-DOM-serialization/E/xml-dom-serialization.e @@ -0,0 +1,11 @@ +def document := \ + .newInstance() \ + .newDocumentBuilder() \ + .getDOMImplementation() \ + .createDocument(null, "root", null) +def root := document.getDocumentElement() +root.appendChild( + def element := document.createElement("element")) +element.appendChild( + document.createTextNode("Some text here")) +println(document.saveXML(root)) diff --git a/Task/XML-DOM-serialization/Fantom/xml-dom-serialization.fantom b/Task/XML-DOM-serialization/Fantom/xml-dom-serialization.fantom new file mode 100644 index 0000000000..0d00d820fc --- /dev/null +++ b/Task/XML-DOM-serialization/Fantom/xml-dom-serialization.fantom @@ -0,0 +1,17 @@ +using xml + +class XmlDom +{ + public static Void main () + { + doc := XDoc() + root := XElem("root") + doc.add (root) + + child := XElem("element") + child.add(XText("Some text here")) + root.add (child) + + doc.write(Env.cur.out) + } +} diff --git a/Task/XML-DOM-serialization/Forth/xml-dom-serialization.fth b/Task/XML-DOM-serialization/Forth/xml-dom-serialization.fth new file mode 100644 index 0000000000..4fe73c8816 --- /dev/null +++ b/Task/XML-DOM-serialization/Forth/xml-dom-serialization.fth @@ -0,0 +1,29 @@ +include ffl/dom.fs + +\ Create a dom variable 'doc' in the dictionary + +dom-create doc + +\ Add the document root with its version attribute + +dom.document doc dom-append-node + +s" version" s" 1.0" dom.attribute doc dom-append-node + +\ Add root and element + +doc dom-parent 2drop + +s" root" dom.element doc dom-append-node + +s" element" dom.element doc dom-append-node + +\ Add the text + +s" Some text here" dom.text doc dom-append-node + +\ Convert the document to a string and print + +doc dom-write-string [IF] + type cr +[THEN] diff --git a/Task/XML-DOM-serialization/Go/xml-dom-serialization-1.go b/Task/XML-DOM-serialization/Go/xml-dom-serialization-1.go new file mode 100644 index 0000000000..a59bc203fa --- /dev/null +++ b/Task/XML-DOM-serialization/Go/xml-dom-serialization-1.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + dom "bitbucket.org/rj/xmldom-go" +) + +func main() { + d, err := dom.ParseStringXml(` + + + + Some text here + +`) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(d.ToXml())) +} diff --git a/Task/XML-DOM-serialization/Go/xml-dom-serialization-2.go b/Task/XML-DOM-serialization/Go/xml-dom-serialization-2.go new file mode 100644 index 0000000000..0179b75be3 --- /dev/null +++ b/Task/XML-DOM-serialization/Go/xml-dom-serialization-2.go @@ -0,0 +1,5 @@ + + + Some text here + + diff --git a/Task/XML-DOM-serialization/Groovy/xml-dom-serialization.groovy b/Task/XML-DOM-serialization/Groovy/xml-dom-serialization.groovy new file mode 100644 index 0000000000..c44fa2bbc6 --- /dev/null +++ b/Task/XML-DOM-serialization/Groovy/xml-dom-serialization.groovy @@ -0,0 +1,7 @@ +import groovy.xml.MarkupBuilder +def writer = new StringWriter() << '\n' +def xml = new MarkupBuilder(writer) +xml.root() { + element('Some text here' ) +} +println writer diff --git a/Task/XML-DOM-serialization/Haskell/xml-dom-serialization.hs b/Task/XML-DOM-serialization/Haskell/xml-dom-serialization.hs new file mode 100644 index 0000000000..ea2d865084 --- /dev/null +++ b/Task/XML-DOM-serialization/Haskell/xml-dom-serialization.hs @@ -0,0 +1,14 @@ +import Data.List +import Text.XML.Light + +xmlDOM :: String -> String +xmlDOM txt = showTopElement $ Element + (unqual "root") + [] + [ Elem $ Element + (unqual "element") + [] + [Text $ CData CDataText txt Nothing] + Nothing + ] + Nothing diff --git a/Task/XML-DOM-serialization/J/xml-dom-serialization-1.j b/Task/XML-DOM-serialization/J/xml-dom-serialization-1.j new file mode 100644 index 0000000000..98fea2a597 --- /dev/null +++ b/Task/XML-DOM-serialization/J/xml-dom-serialization-1.j @@ -0,0 +1,11 @@ +serialize=: ('',LF),;@serialize1&'' +serialize1=:4 :0 + if.L.x do. + start=. y,'<',(0{::x),'>',LF + middle=. ;;(}.x) serialize1&.> <' ',y + end=. y,'',LF + + + + some text here + + diff --git a/Task/XML-DOM-serialization/Java/xml-dom-serialization-1.java b/Task/XML-DOM-serialization/Java/xml-dom-serialization-1.java new file mode 100644 index 0000000000..8486f791c0 --- /dev/null +++ b/Task/XML-DOM-serialization/Java/xml-dom-serialization-1.java @@ -0,0 +1,105 @@ +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class RDOMSerialization { + + private Document domDoc; + + public RDOMSerialization() { + return; + } + + protected void buildDOMDocument() { + + DocumentBuilderFactory factory; + DocumentBuilder builder; + DOMImplementation impl; + Element elmt1; + Element elmt2; + + try { + factory = DocumentBuilderFactory.newInstance(); + builder = factory.newDocumentBuilder(); + impl = builder.getDOMImplementation(); + domDoc = impl.createDocument(null, null, null); + elmt1 = domDoc.createElement("root"); + elmt2 = domDoc.createElement("element"); + elmt2.setTextContent("Some text here"); + + domDoc.appendChild(elmt1); + elmt1.appendChild(elmt2); + } + catch (ParserConfigurationException ex) { + ex.printStackTrace(); + } + + return; + } + + protected void serializeXML() { + + DOMSource domSrc; + Transformer txformer; + StringWriter sw; + StreamResult sr; + + try { + domSrc = new DOMSource(domDoc); + + txformer = TransformerFactory.newInstance().newTransformer(); + txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + txformer.setOutputProperty(OutputKeys.METHOD, "xml"); + txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + txformer.setOutputProperty(OutputKeys.INDENT, "yes"); + txformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); + txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + + sw = new StringWriter(); + sr = new StreamResult(sw); + + txformer.transform(domSrc, sr); + + System.out.println(sw.toString()); + } + catch (TransformerConfigurationException ex) { + ex.printStackTrace(); + } + catch (TransformerFactoryConfigurationError ex) { + ex.printStackTrace(); + } + catch (TransformerException ex) { + ex.printStackTrace(); + } + + return; + } + + public static void serializationDriver(String[] args) { + + RDOMSerialization lcl = new RDOMSerialization(); + lcl.buildDOMDocument(); + lcl.serializeXML(); + + return; + } + + public static void main(String[] args) { + serializationDriver(args); + return; + } +} diff --git a/Task/XML-DOM-serialization/Java/xml-dom-serialization-2.java b/Task/XML-DOM-serialization/Java/xml-dom-serialization-2.java new file mode 100644 index 0000000000..3329e7d2f7 --- /dev/null +++ b/Task/XML-DOM-serialization/Java/xml-dom-serialization-2.java @@ -0,0 +1,4 @@ + + + Some text here + diff --git a/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-1.js b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-1.js new file mode 100644 index 0000000000..fab27d5a1e --- /dev/null +++ b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-1.js @@ -0,0 +1,6 @@ +var doc = document.implementation.createDocument( null, 'root', null ); +var root = doc.documentElement; +var element = doc.createElement( 'element' ); +root.appendChild( element ); +element.appendChild( document.createTextNode('Some text here') ); +var xmlString = new XMLSerializer().serializeToString( doc ); diff --git a/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-2.js b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-2.js new file mode 100644 index 0000000000..5a9a834b25 --- /dev/null +++ b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-2.js @@ -0,0 +1,4 @@ +var xml = + Some text here +; +var xmlString = xml.toXMLString(); diff --git a/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-3.js b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-3.js new file mode 100644 index 0000000000..d0a59422e3 --- /dev/null +++ b/Task/XML-DOM-serialization/JavaScript/xml-dom-serialization-3.js @@ -0,0 +1,6 @@ +XML.ignoreProcessingInstructions = false; +var xml = + + Some text here +; +var xmlString = xml.toXMLString(); diff --git a/Task/XML-DOM-serialization/Mathematica/xml-dom-serialization.math b/Task/XML-DOM-serialization/Mathematica/xml-dom-serialization.math new file mode 100644 index 0000000000..d8a560b84a --- /dev/null +++ b/Task/XML-DOM-serialization/Mathematica/xml-dom-serialization.math @@ -0,0 +1,4 @@ +DOM = XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0","Encoding" -> "utf-8"]}, +XMLElement["root", {}, {XMLElement["element", {}, {"Some text here"}]}], {}]; + +ExportString[DOM, "XML", "AttributeQuoting" -> "\""] diff --git a/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-1.netrexx b/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-1.netrexx new file mode 100644 index 0000000000..14ef43e1ed --- /dev/null +++ b/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-1.netrexx @@ -0,0 +1,68 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +import java.io.StringWriter +import javax.xml. +import org.w3c.dom. + +class RDOMSerialization public + +properties private + domDoc = Document + +method main(args = String[]) public static + + lcl = RDOMSerialization() + lcl.buildDOMDocument() + lcl.serializeXML() + + return + +method buildDOMDocument() inheritable + + do + factory = DocumentBuilderFactory.newInstance() + builder = factory.newDocumentBuilder() + impl = builder.getDOMImplementation() + domDoc = impl.createDocument(null, null, null) + elmt1 = domDoc.createElement("root") + elmt2 = domDoc.createElement("element") + elmt2.setTextContent("Some text here") + + domDoc.appendChild(elmt1) + elmt1.appendChild(elmt2) + + catch exPC = ParserConfigurationException + exPC.printStackTrace + end + + return + +method serializeXML() inheritable + + do + domSrc = DOMSource(domDoc) + txformer = TransformerFactory.newInstance().newTransformer() + txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no") + txformer.setOutputProperty(OutputKeys.METHOD, "xml") + txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") + txformer.setOutputProperty(OutputKeys.INDENT, "yes") + txformer.setOutputProperty(OutputKeys.STANDALONE, "yes") + txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") + + sw = StringWriter() + sr = StreamResult(sw) + + txformer.transform(domSrc, sr) + + say sw.toString + + catch exTC = TransformerConfigurationException + exTC.printStackTrace + catch exTF = TransformerFactoryConfigurationError + exTF.printStackTrace + catch exTE = TransformerException + exTE.printStackTrace + end + + return diff --git a/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-2.netrexx b/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-2.netrexx new file mode 100644 index 0000000000..79c2a605f1 --- /dev/null +++ b/Task/XML-DOM-serialization/NetRexx/xml-dom-serialization-2.netrexx @@ -0,0 +1,4 @@ + + + Some text here + diff --git a/Task/XML-DOM-serialization/Objeck/xml-dom-serialization.objeck b/Task/XML-DOM-serialization/Objeck/xml-dom-serialization.objeck new file mode 100644 index 0000000000..20c8586c84 --- /dev/null +++ b/Task/XML-DOM-serialization/Objeck/xml-dom-serialization.objeck @@ -0,0 +1,13 @@ +use XML; + +bundle Default { + class Test { + function : Main(args : String[]) ~ Nil { + builder := XMLBuilder->New("root", "1.0"); + root := builder->GetRoot(); + element := XMLElement->New(XMLElementType->ELEMENT, "element", "Some text here"); + root->AddChild(element); + builder->ToString()->PrintLine(); + } + } +} diff --git a/Task/XML-DOM-serialization/OpenEdge-Progress/xml-dom-serialization.openedge b/Task/XML-DOM-serialization/OpenEdge-Progress/xml-dom-serialization.openedge new file mode 100644 index 0000000000..b9a972ee9f --- /dev/null +++ b/Task/XML-DOM-serialization/OpenEdge-Progress/xml-dom-serialization.openedge @@ -0,0 +1,23 @@ +DEFINE VARIABLE hxdoc AS HANDLE NO-UNDO. +DEFINE VARIABLE hxroot AS HANDLE NO-UNDO. +DEFINE VARIABLE hxelement AS HANDLE NO-UNDO. +DEFINE VARIABLE hxtext AS HANDLE NO-UNDO. +DEFINE VARIABLE lcc AS LONGCHAR NO-UNDO. + +CREATE X-DOCUMENT hxdoc. + +CREATE X-NODEREF hxroot. +hxdoc:CREATE-NODE( hxroot, 'root', 'ELEMENT' ). +hxdoc:APPEND-CHILD( hxroot ). + +CREATE X-NODEREF hxelement. +hxdoc:CREATE-NODE( hxelement, 'element', 'ELEMENT' ). +hxroot:APPEND-CHILD( hxelement ). + +CREATE X-NODEREF hxtext. +hxdoc:CREATE-NODE( hxtext, 'element', 'TEXT' ). +hxelement:APPEND-CHILD( hxtext ). +hxtext:NODE-VALUE = 'Some text here'. + +hxdoc:SAVE( 'LONGCHAR', lcc ). +MESSAGE STRING( lcc ) VIEW-AS ALERT-BOX. diff --git a/Task/XML-DOM-serialization/Oz/xml-dom-serialization-1.oz b/Task/XML-DOM-serialization/Oz/xml-dom-serialization-1.oz new file mode 100644 index 0000000000..59c0f649a4 --- /dev/null +++ b/Task/XML-DOM-serialization/Oz/xml-dom-serialization-1.oz @@ -0,0 +1,7 @@ +declare + proc {Main} + DOM = root(element("Some text here")) + in + {System.showInfo {Serialize DOM}} + end + ... diff --git a/Task/XML-DOM-serialization/Oz/xml-dom-serialization-2.oz b/Task/XML-DOM-serialization/Oz/xml-dom-serialization-2.oz new file mode 100644 index 0000000000..77d90f5b20 --- /dev/null +++ b/Task/XML-DOM-serialization/Oz/xml-dom-serialization-2.oz @@ -0,0 +1,4 @@ + + + Some text here + diff --git a/Task/XML-DOM-serialization/PHP/xml-dom-serialization.php b/Task/XML-DOM-serialization/PHP/xml-dom-serialization.php new file mode 100644 index 0000000000..4ab59d4ac7 --- /dev/null +++ b/Task/XML-DOM-serialization/PHP/xml-dom-serialization.php @@ -0,0 +1,9 @@ +formatOutput = true;//format the outputted xml +$root = $dom->createElement('root'); +$element = $dom->createElement('element'); +$element->appendChild($dom->createTextNode('Some text here')); +$root->appendChild($element); +$dom->appendChild($root); +$xmlstring = $dom->saveXML(); diff --git a/Task/XML-DOM-serialization/Pascal/xml-dom-serialization.pascal b/Task/XML-DOM-serialization/Pascal/xml-dom-serialization.pascal new file mode 100644 index 0000000000..66e3207483 --- /dev/null +++ b/Task/XML-DOM-serialization/Pascal/xml-dom-serialization.pascal @@ -0,0 +1,23 @@ +program CrearXML; + +{$mode objfpc}{$H+} + +uses + Classes, XMLWrite, DOM; + +var + xdoc: TXMLDocument; // variable objeto documento XML + NodoRaiz, NodoPadre, NodoHijo: TDOMNode; // variables a los nodos +begin + //crear el documento + xdoc := TXMLDocument.create; + + NodoRaiz := xdoc.CreateElement('root'); // crear el nodo raíz + Xdoc.Appendchild(NodoRaiz); // guardar nodo raíz + NodoPadre := xdoc.CreateElement('element'); // crear el nodo hijo + NodoHijo := xdoc.CreateTextNode('Some text here'); // insertar el valor del nodo + NodoPadre.Appendchild(NodoHijo); // guardar nodo + NodoRaiz.AppendChild(NodoPadre); // insertar el nodo hijo en el correspondiente nodo padre + writeXMLFile(xDoc,'prueba.xml'); // escribir el XML + Xdoc.free; +end. diff --git a/Task/XML-DOM-serialization/Perl/xml-dom-serialization-1.pl b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-1.pl new file mode 100644 index 0000000000..b271964b6a --- /dev/null +++ b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-1.pl @@ -0,0 +1,2 @@ +use XML::Simple; +print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" ); diff --git a/Task/XML-DOM-serialization/Perl/xml-dom-serialization-2.pl b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-2.pl new file mode 100644 index 0000000000..d7b8ce3bb9 --- /dev/null +++ b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-2.pl @@ -0,0 +1,7 @@ +use XML::DOM::BagOfTricks qw(createDocument createTextElement); + +my ($doc, $root) = createDocument('root'); +$root->appendChild( + createTextElement($doc, 'element', 'Some text here') +); +print $doc->toString; diff --git a/Task/XML-DOM-serialization/Perl/xml-dom-serialization-3.pl b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-3.pl new file mode 100644 index 0000000000..b5944f269e --- /dev/null +++ b/Task/XML-DOM-serialization/Perl/xml-dom-serialization-3.pl @@ -0,0 +1,12 @@ +use XML::LibXML; + +$xml = XML::LibXML::Document->new('1.0'); +$node = $xml->createElement('root'); +$xml->setDocumentElement($node); +$node2 = $xml->createElement('element'); +$text = $xml->createTextNode('Some text here'); +$node2->addChild($text); +$node->appendWellBalancedChunk('text'); +$node->addChild($node2); + +print $xml->toString; diff --git a/Task/XML-DOM-serialization/PicoLisp/xml-dom-serialization.l b/Task/XML-DOM-serialization/PicoLisp/xml-dom-serialization.l new file mode 100644 index 0000000000..7288655d12 --- /dev/null +++ b/Task/XML-DOM-serialization/PicoLisp/xml-dom-serialization.l @@ -0,0 +1,4 @@ +(load "@lib/xm.l") + +(xml? T) +(xml '(root NIL (element NIL "Some text here"))) diff --git a/Task/XML-DOM-serialization/Pike/xml-dom-serialization-1.pike b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-1.pike new file mode 100644 index 0000000000..70de8005f3 --- /dev/null +++ b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-1.pike @@ -0,0 +1,14 @@ +object dom = Parser.XML.Tree.SimpleRootNode(); +dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), "")); +object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "root", ([]), ""); +dom->add_child(node); + +object subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "element", ([]), ""); +node->add_child(subnode); + +node = subnode; +subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "Some text here"); +node->add_child(subnode); + +dom->render_xml(); +Result: "Some text here" diff --git a/Task/XML-DOM-serialization/Pike/xml-dom-serialization-2.pike b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-2.pike new file mode 100644 index 0000000000..c5edede76f --- /dev/null +++ b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-2.pike @@ -0,0 +1,27 @@ +object make_xml_node(array|string in, void|int level) +{ + level++; + if (stringp(in)) + return Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), in); + else + { + object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, in[0], in[1], ""); + foreach(in[2..];; array|string child) + { + node->add_child(make_xml_node(child, level)); + } + return node; + } +} + +object make_xml_tree(array input) +{ + object dom = Parser.XML.Tree.SimpleRootNode(); + dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), "")); + dom->add_child(make_xml_node(input)); + return dom; +} + +array input = ({ "root", ([]), ({ "element", ([]), "Some text here" }) }); +make_xml_tree(input)->render_xml(); +Result: "Some text here" diff --git a/Task/XML-DOM-serialization/Pike/xml-dom-serialization-3.pike b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-3.pike new file mode 100644 index 0000000000..745f3e81bf --- /dev/null +++ b/Task/XML-DOM-serialization/Pike/xml-dom-serialization-3.pike @@ -0,0 +1,32 @@ +object indent_xml(object parent, void|int indent_text, void|int level) +{ + int subnodes = false; + foreach(parent->get_children();; object child) + { + if (child->get_node_type() == Parser.XML.Tree.XML_ELEMENT || + (child->get_node_type() == Parser.XML.Tree.XML_TEXT && indent_text)) + { + subnodes = true; + parent->add_child_before(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+" "*level), child); + indent_xml(child, indent_text, level+1); + } + } + if (subnodes && level) + parent->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "\r\n"+" "*(level-1))); + return parent; +} + + +indent_xml(make_xml_tree(input))->render_xml(); +Result: "\r\n" + "\r\n" + " Some text here\r\n" + "" + +indent_xml(make_xml_tree(input), 1)->render_xml(); +Result: "\r\n" + "\r\n" + " \r\n" + " Some text here\r\n" + " \r\n" + "" diff --git a/Task/XML-DOM-serialization/Python/xml-dom-serialization-1.py b/Task/XML-DOM-serialization/Python/xml-dom-serialization-1.py new file mode 100644 index 0000000000..53471c5fa2 --- /dev/null +++ b/Task/XML-DOM-serialization/Python/xml-dom-serialization-1.py @@ -0,0 +1,12 @@ +from xml.dom.minidom import getDOMImplementation + +dom = getDOMImplementation() +document = dom.createDocument(None, "root", None) + +topElement = document.documentElement +firstElement = document.createElement("element") +topElement.appendChild(firstElement) +textNode = document.createTextNode("Some text here") +firstElement.appendChild(textNode) + +xmlString = document.toprettyxml(" " * 4) diff --git a/Task/XML-DOM-serialization/Python/xml-dom-serialization-2.py b/Task/XML-DOM-serialization/Python/xml-dom-serialization-2.py new file mode 100644 index 0000000000..c7150c8225 --- /dev/null +++ b/Task/XML-DOM-serialization/Python/xml-dom-serialization-2.py @@ -0,0 +1,5 @@ +from xml.etree import ElementTree as et + +root = et.Element("root") +et.SubElement(root, "element").text = "Some text here" +xmlString = et.tostring(root) diff --git a/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-1.rascal b/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-1.rascal new file mode 100644 index 0000000000..67f6c61b8b --- /dev/null +++ b/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-1.rascal @@ -0,0 +1,6 @@ +import lang::xml::DOM; + +public void main(){ + x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])])); + return println(xmlPretty(x)); +} diff --git a/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-2.rascal b/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-2.rascal new file mode 100644 index 0000000000..bb18c6993d --- /dev/null +++ b/Task/XML-DOM-serialization/Rascal/xml-dom-serialization-2.rascal @@ -0,0 +1,5 @@ +rascal>main() + + + Some text here + diff --git a/Task/XML-DOM-serialization/Ruby/xml-dom-serialization.rb b/Task/XML-DOM-serialization/Ruby/xml-dom-serialization.rb new file mode 100644 index 0000000000..2f6c546bf3 --- /dev/null +++ b/Task/XML-DOM-serialization/Ruby/xml-dom-serialization.rb @@ -0,0 +1,12 @@ +require("rexml/document") +include REXML +(doc = Document.new) << XMLDecl.new +root = doc.add_element('root') +element = root.add_element('element') +element.add_text('Some text here') + +# save to a string +# (the first argument to write() needs an object that understands "<<") +serialized = String.new +doc.write(serialized, 4) +puts serialized diff --git a/Task/XML-DOM-serialization/Scala/xml-dom-serialization.scala b/Task/XML-DOM-serialization/Scala/xml-dom-serialization.scala new file mode 100644 index 0000000000..fd82189d02 --- /dev/null +++ b/Task/XML-DOM-serialization/Scala/xml-dom-serialization.scala @@ -0,0 +1,2 @@ +val xml = Some text here +scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null) diff --git a/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-1.tcl b/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-1.tcl new file mode 100644 index 0000000000..ac82e85f0c --- /dev/null +++ b/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-1.tcl @@ -0,0 +1,6 @@ +package require tdom +set d [dom createDocument root] +set root [$d documentElement] +$root appendChild [$d createElement element] +[$root firstChild] appendChild [$d createTextNode "Some text here"] +$d asXML diff --git a/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-2.tcl b/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-2.tcl new file mode 100644 index 0000000000..527ca08025 --- /dev/null +++ b/Task/XML-DOM-serialization/Tcl/xml-dom-serialization-2.tcl @@ -0,0 +1,6 @@ +package require dom +set doc [dom::DOMImplementation create] +set root [dom::document createElement $doc root] +set elem [dom::document createElement $root element] +set text [dom::document createTextNode $elem "Some text here"] +dom::DOMImplementation serialize $doc -newline {element} diff --git a/Task/XML-DOM-serialization/XProc/xml-dom-serialization.xproc b/Task/XML-DOM-serialization/XProc/xml-dom-serialization.xproc new file mode 100644 index 0000000000..da00c00b60 --- /dev/null +++ b/Task/XML-DOM-serialization/XProc/xml-dom-serialization.xproc @@ -0,0 +1,13 @@ + + + + + + + Some text here + + + + + + diff --git a/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-1.xquery b/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-1.xquery new file mode 100644 index 0000000000..34445e1045 --- /dev/null +++ b/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-1.xquery @@ -0,0 +1,5 @@ + + + Some text here + + diff --git a/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-2.xquery b/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-2.xquery new file mode 100644 index 0000000000..2e0e045a88 --- /dev/null +++ b/Task/XML-DOM-serialization/XQuery/xml-dom-serialization-2.xquery @@ -0,0 +1,10 @@ +let $rootTagname := 'root' +let $elementTagname := 'element' +let $elementContent := 'Some text here' + +return + element {$rootTagname} + { + element{$elementTagname} + {$elementContent} + } diff --git a/Task/XML-DOM-serialization/XSLT/xml-dom-serialization.xslt b/Task/XML-DOM-serialization/XSLT/xml-dom-serialization.xslt new file mode 100644 index 0000000000..9eadeef570 --- /dev/null +++ b/Task/XML-DOM-serialization/XSLT/xml-dom-serialization.xslt @@ -0,0 +1,10 @@ + + + + + + Some text here + + + + diff --git a/Task/XML-Input/0DESCRIPTION b/Task/XML-Input/0DESCRIPTION new file mode 100644 index 0000000000..0d349de9d8 --- /dev/null +++ b/Task/XML-Input/0DESCRIPTION @@ -0,0 +1,19 @@ +Given the following XML fragment, extract the list of ''student names'' using whatever means desired. If the only viable method is to use XPath, refer the reader to the task [[XML and XPath]]. + + + + + + + + + + + +Expected Output + + April + Bob + Chad + Dave + Émily diff --git a/Task/XML-Input/1META.yaml b/Task/XML-Input/1META.yaml new file mode 100644 index 0000000000..d7f654b55d --- /dev/null +++ b/Task/XML-Input/1META.yaml @@ -0,0 +1,2 @@ +--- +note: XML diff --git a/Task/XML-Input/AWK/xml-input-1.awk b/Task/XML-Input/AWK/xml-input-1.awk new file mode 100644 index 0000000000..d1601617d2 --- /dev/null +++ b/Task/XML-Input/AWK/xml-input-1.awk @@ -0,0 +1,56 @@ +function parse_buf() +{ + if ( match(buffer, /]*Name[ \t]*=[ \t]*"([^"]*)"/, mt) != 0 ) { + students[mt[1]] = 1 + } + buffer = "" +} + +BEGIN { + FS="" + mode = 0 + buffer = "" + li = 1 +} + +mode==1 { + for(i=1; i <= NF; i++) { + buffer = buffer $i + if ( $i == ">" ) { + mode = 0; + break; + } + } + if ( mode == 0 ) { + li = i + } else { + li = 1 + } + # let us process the buffer if "complete" + if ( mode == 0 ) { + parse_buf() + } +} + +mode==0 { + for(i=li; i <= NF; i++) { + if ( $i == "<" ) { + mode = 1 + break; + } + } + for(j=i; i <= NF; i++) { + buffer = buffer $i + if ( $i == ">" ) { + mode = 0 + parse_buf() + } + } + li = 1 +} + +END { + for(k in students) { + print k + } +} diff --git a/Task/XML-Input/AWK/xml-input-2.awk b/Task/XML-Input/AWK/xml-input-2.awk new file mode 100644 index 0000000000..f996630d65 --- /dev/null +++ b/Task/XML-Input/AWK/xml-input-2.awk @@ -0,0 +1,4 @@ +awk -f getXML.awk sample.xml | awk ' + $1 == "TAG" {tag = $2} + tag == "Student" && /Name=/ {print substr($0, index($0, "=") + 1)} +' diff --git a/Task/XML-Input/AWK/xml-input-3.awk b/Task/XML-Input/AWK/xml-input-3.awk new file mode 100644 index 0000000000..7d4da7bbd7 --- /dev/null +++ b/Task/XML-Input/AWK/xml-input-3.awk @@ -0,0 +1,5 @@ +gawk -f xmlparser.awk sample.xml | awk ' + $1 == "begin" {tag = $2} + $1 == "attrib" {attrib = $2} + $1 == "value" && tag == "STUDENT" && attrib == "name" {print $2} +' diff --git a/Task/XML-Input/ActionScript/xml-input.as b/Task/XML-Input/ActionScript/xml-input.as new file mode 100644 index 0000000000..8197364096 --- /dev/null +++ b/Task/XML-Input/ActionScript/xml-input.as @@ -0,0 +1,22 @@ +package +{ + import flash.display.Sprite; + + public class XMLReading extends Sprite + { + public function XMLReading() + { + var xml:XML = + + + + + + ; + for each(var node:XML in xml..Student) + { + trace(node.@Name); + } + } + } +} diff --git a/Task/XML-Input/Ada/xml-input-1.ada b/Task/XML-Input/Ada/xml-input-1.ada new file mode 100644 index 0000000000..9783752627 --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-1.ada @@ -0,0 +1,23 @@ +with Sax.Readers; +with Input_Sources.Strings; +with Unicode.CES.Utf8; +with My_Reader; + +procedure Extract_Students is + Sample_String : String := +"" & + "" & + "" & + "" & + "" & + "" & + "" & + "" & +""; + Reader : My_Reader.Reader; + Input : Input_Sources.Strings.String_Input; +begin + Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input); + My_Reader.Parse (Reader, Input); + Input_Sources.Strings.Close (Input); +end Extract_Students; diff --git a/Task/XML-Input/Ada/xml-input-2.ada b/Task/XML-Input/Ada/xml-input-2.ada new file mode 100644 index 0000000000..5c1dba6b2e --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-2.ada @@ -0,0 +1,12 @@ +with Sax.Attributes; +with Sax.Readers; +with Unicode.CES; +package My_Reader is + type Reader is new Sax.Readers.Reader with null record; + procedure Start_Element + (Handler : in out Reader; + Namespace_URI : Unicode.CES.Byte_Sequence := ""; + Local_Name : Unicode.CES.Byte_Sequence := ""; + Qname : Unicode.CES.Byte_Sequence := ""; + Atts : Sax.Attributes.Attributes'Class); +end My_Reader; diff --git a/Task/XML-Input/Ada/xml-input-3.ada b/Task/XML-Input/Ada/xml-input-3.ada new file mode 100644 index 0000000000..0a08e65253 --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-3.ada @@ -0,0 +1,14 @@ +with Ada.Text_IO; +package body My_Reader is + procedure Start_Element + (Handler : in out Reader; + Namespace_URI : Unicode.CES.Byte_Sequence := ""; + Local_Name : Unicode.CES.Byte_Sequence := ""; + Qname : Unicode.CES.Byte_Sequence := ""; + Atts : Sax.Attributes.Attributes'Class) is + begin + if Local_Name = "Student" then + Ada.Text_IO.Put_Line (Sax.Attributes.Get_Value (Atts, "Name")); + end if; + end Start_Element; +end My_Reader; diff --git a/Task/XML-Input/Ada/xml-input-4.ada b/Task/XML-Input/Ada/xml-input-4.ada new file mode 100644 index 0000000000..1668df0c2e --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-4.ada @@ -0,0 +1,41 @@ +with Ada.Text_IO; +with Sax.Readers; +with Input_Sources.Strings; +with Unicode.CES.Utf8; +with DOM.Readers; +with DOM.Core.Documents; +with DOM.Core.Nodes; +with DOM.Core.Attrs; + +procedure Extract_Students is + Sample_String : String := +"" & + "" & + "" & + "" & + "" & + "" & + "" & + "" & +""; + Input : Input_Sources.Strings.String_Input; + Reader : DOM.Readers.Tree_Reader; + Document : DOM.Core.Document; + List : DOM.Core.Node_List; +begin + Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input); + DOM.Readers.Parse (Reader, Input); + Input_Sources.Strings.Close (Input); + Document := DOM.Readers.Get_Tree (Reader); + List := DOM.Core.Documents.Get_Elements_By_Tag_Name (Document, "Student"); + for I in 0 .. DOM.Core.Nodes.Length (List) - 1 loop + Ada.Text_IO.Put_Line + (DOM.Core.Attrs.Value + (DOM.Core.Nodes.Get_Named_Item + (DOM.Core.Nodes.Attributes + (DOM.Core.Nodes.Item (List, I)), "Name") + ) + ); + end loop; + DOM.Readers.Free (Reader); +end Extract_Students; diff --git a/Task/XML-Input/Ada/xml-input-5.ada b/Task/XML-Input/Ada/xml-input-5.ada new file mode 100644 index 0000000000..49c528d4f7 --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-5.ada @@ -0,0 +1,16 @@ +with League.Application; +with XML.SAX.Input_Sources.Streams.Files; +with XML.SAX.Simple_Readers; + +with Handlers; + +procedure Main is + Handler : aliased Handlers.Handler; + Input : aliased XML.SAX.Input_Sources.Streams.Files.File_Input_Source; + Reader : aliased XML.SAX.Simple_Readers.SAX_Simple_Reader; + +begin + Input.Open_By_File_Name (League.Application.Arguments.Element (1)); + Reader.Set_Content_Handler (Handler'Unchecked_Access); + Reader.Parse (Input'Unchecked_Access); +end Main; diff --git a/Task/XML-Input/Ada/xml-input-6.ada b/Task/XML-Input/Ada/xml-input-6.ada new file mode 100644 index 0000000000..37c045f80c --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-6.ada @@ -0,0 +1,21 @@ +with League.Strings; +with XML.SAX.Attributes; +with XML.SAX.Content_Handlers; + +package Handlers is + + type Handler is + limited new XML.SAX.Content_Handlers.SAX_Content_Handler with null record; + + overriding procedure Start_Element + (Self : in out Handler; + Namespace_URI : League.Strings.Universal_String; + Local_Name : League.Strings.Universal_String; + Qualified_Name : League.Strings.Universal_String; + Attributes : XML.SAX.Attributes.SAX_Attributes; + Success : in out Boolean); + + overriding function Error_String + (Self : Handler) return League.Strings.Universal_String; + +end Handlers; diff --git a/Task/XML-Input/Ada/xml-input-7.ada b/Task/XML-Input/Ada/xml-input-7.ada new file mode 100644 index 0000000000..5bce21020a --- /dev/null +++ b/Task/XML-Input/Ada/xml-input-7.ada @@ -0,0 +1,39 @@ +with Ada.Wide_Wide_Text_IO; + +package body Handlers is + + use type League.Strings.Universal_String; + + function "+" + (Item : Wide_Wide_String) return League.Strings.Universal_String + renames League.Strings.To_Universal_String; + + ------------------ + -- Error_String -- + ------------------ + + overriding function Error_String + (Self : Handler) return League.Strings.Universal_String is + begin + return League.Strings.Empty_Universal_String; + end Error_String; + + ------------------- + -- Start_Element -- + ------------------- + + overriding procedure Start_Element + (Self : in out Handler; + Namespace_URI : League.Strings.Universal_String; + Local_Name : League.Strings.Universal_String; + Qualified_Name : League.Strings.Universal_String; + Attributes : XML.SAX.Attributes.SAX_Attributes; + Success : in out Boolean) is + begin + if Qualified_Name = +"Student" then + Ada.Wide_Wide_Text_IO.Put_Line + (Attributes.Value (+"Name").To_Wide_Wide_String); + end if; + end Start_Element; + +end Handlers; diff --git a/Task/XML-Input/Aikido/xml-input.aikido b/Task/XML-Input/Aikido/xml-input.aikido new file mode 100644 index 0000000000..dfc1ff683d --- /dev/null +++ b/Task/XML-Input/Aikido/xml-input.aikido @@ -0,0 +1,14 @@ +import xml + +var s = openin ("t.xml") +var tree = XML.parseStream (s) + +foreach node tree { + if (node.name == "Students") { + foreach studentnode node { + if (studentnode.name == "Student") { + println (studentnode.getAttribute ("Name")) + } + } + } +} diff --git a/Task/XML-Input/AutoHotkey/xml-input.ahk b/Task/XML-Input/AutoHotkey/xml-input.ahk new file mode 100644 index 0000000000..9473cbfbaa --- /dev/null +++ b/Task/XML-Input/AutoHotkey/xml-input.ahk @@ -0,0 +1,20 @@ +students = +( + + + + + + + + + +) + +quote = " ; " +pos = 1 +while, pos := RegExMatch(students, "Name=.(\w+)" . quote . "\sGender" +, name, pos + 1) +names .= name1 . "`n" + +msgbox % names diff --git a/Task/XML-Input/BBC-BASIC/xml-input.bbc b/Task/XML-Input/BBC-BASIC/xml-input.bbc new file mode 100644 index 0000000000..d8aa40cea0 --- /dev/null +++ b/Task/XML-Input/BBC-BASIC/xml-input.bbc @@ -0,0 +1,20 @@ + INSTALL @lib$+"XMLLIB" + xmlfile$ = "C:\students.xml" + PROC_initXML(xmlobj{}, xmlfile$) + + level% = FN_skipTo(xmlobj{}, "Students", 0) + IF level%=0 ERROR 100, "Students not found" + + REPEAT + IF FN_isTag(xmlobj{}) THEN + tag$ = FN_nextToken(xmlobj{}) + IF LEFT$(tag$, 8) = " + +#include +#include + +int main() { + QDomDocument doc; + + doc.setContent( + QObject::tr( + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "")); + + QDomElement n = doc.documentElement().firstChildElement("Student"); + while(!n.isNull()) { + std::cout << qPrintable(n.attribute("Name")) << std::endl; + n = n.nextSiblingElement(); + } + return 0; +} diff --git a/Task/XML-Input/C-sharp/xml-input.cs b/Task/XML-Input/C-sharp/xml-input.cs new file mode 100644 index 0000000000..67dca0d9ac --- /dev/null +++ b/Task/XML-Input/C-sharp/xml-input.cs @@ -0,0 +1,15 @@ +class Program +{ + static void Main(string[] args) + { + XDocument xmlDoc = XDocument.Load("XMLFile1.xml"); + var query = from p in xmlDoc.Descendants("Student") + select p.Attribute("Name"); + + foreach (var item in query) + { + Console.WriteLine(item.Value); + } + Console.ReadLine(); + } +} diff --git a/Task/XML-Input/C/xml-input.c b/Task/XML-Input/C/xml-input.c new file mode 100644 index 0000000000..f03f1c20e0 --- /dev/null +++ b/Task/XML-Input/C/xml-input.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +static void print_names(xmlNode *node) +{ + xmlNode *cur_node = NULL; + for (cur_node = node; cur_node; cur_node = cur_node->next) { + if (cur_node->type == XML_ELEMENT_NODE) { + if ( strcmp(cur_node->name, "Student") == 0 ) { + xmlAttr *prop = NULL; + if ( (prop = xmlHasProp(cur_node, "Name")) != NULL ) { + printf("%s\n", prop->children->content); + + } + } + } + print_names(cur_node->children); + } +} + +const char *buffer = + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; + +int main() +{ + xmlDoc *doc = NULL; + xmlNode *root = NULL; + + doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0); + if ( doc != NULL ) { + root = xmlDocGetRootElement(doc); + print_names(root); + xmlFreeDoc(doc); + } + xmlCleanupParser(); + return 0; +} diff --git a/Task/XML-Input/Clojure/xml-input-1.clj b/Task/XML-Input/Clojure/xml-input-1.clj new file mode 100644 index 0000000000..4704971962 --- /dev/null +++ b/Task/XML-Input/Clojure/xml-input-1.clj @@ -0,0 +1,14 @@ +(import '(java.io ByteArrayInputStream)) +(use 'clojure.xml) ; defines 'parse + +(def xml-text " + + + + + + + +") + +(def students (parse (-> xml-text .getBytes ByteArrayInputStream.))) diff --git a/Task/XML-Input/Clojure/xml-input-2.clj b/Task/XML-Input/Clojure/xml-input-2.clj new file mode 100644 index 0000000000..6736e5b115 --- /dev/null +++ b/Task/XML-Input/Clojure/xml-input-2.clj @@ -0,0 +1,3 @@ +(doseq [{:keys [tag attrs]} (xml-seq students)] + (if (= :Student tag) + (println (:Name attrs)))) diff --git a/Task/XML-Input/Common-Lisp/xml-input-1.lisp b/Task/XML-Input/Common-Lisp/xml-input-1.lisp new file mode 100644 index 0000000000..297fe518b2 --- /dev/null +++ b/Task/XML-Input/Common-Lisp/xml-input-1.lisp @@ -0,0 +1,17 @@ +(defparameter *xml-blob* +" + + + + + + + +") + +(let* ((document (cxml:parse *xml-blob* (cxml-dom:make-dom-builder))) + (students (dom:item (dom:get-elements-by-tag-name document "Students") 0)) + (student-names '())) + (dom:do-node-list (child (dom:child-nodes students) (nreverse student-names)) + (when (dom:element-p child) + (push (dom:get-attribute child "Name") student-names)))) diff --git a/Task/XML-Input/Common-Lisp/xml-input-2.lisp b/Task/XML-Input/Common-Lisp/xml-input-2.lisp new file mode 100644 index 0000000000..ea1f0d0739 --- /dev/null +++ b/Task/XML-Input/Common-Lisp/xml-input-2.lisp @@ -0,0 +1 @@ +("April" "Bob" "Chad" "Dave" "Émily") diff --git a/Task/XML-Input/D/xml-input.d b/Task/XML-Input/D/xml-input.d new file mode 100644 index 0000000000..92d076a459 --- /dev/null +++ b/Task/XML-Input/D/xml-input.d @@ -0,0 +1,24 @@ +import kxml.xml; +char[]xmlinput = +" + + + + + + + +"; + +void main() { + auto root = readDocument(xmlinput); + foreach(students;root.getChildren) if (!students.isCData && students.getName == "Students") { + // now look for student subnodes + foreach(student;students.getChildren) if (!student.isCData && student.getName == "Student") { + // we found a student! + std.stdio.writefln("%s",student.getAttribute("Name")); + } + // we only want one, so break out of the loop once we find a match + break; + } +} diff --git a/Task/XML-Input/Delphi/xml-input.delphi b/Task/XML-Input/Delphi/xml-input.delphi new file mode 100644 index 0000000000..d4369fc6a3 --- /dev/null +++ b/Task/XML-Input/Delphi/xml-input.delphi @@ -0,0 +1,46 @@ +//You need to use these units +uses + SysUtils, + Dialogs, + XMLIntf, + XMLDoc; + +//.............................................. + +//This function process the XML +function GetStudents(aXMLInput: string): string; +var + XMLDoc: IXMLDocument; + i: Integer; +begin + //Creating the TXMLDocument instance + XMLDoc:= TXMLDocument.Create(nil); + + //Loading the XML string + XMLDoc.LoadFromXML(aXMLInput); + + //Parsing the xml document + for i:=0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do + Result:= Result + XMLDoc.DocumentElement.ChildNodes.Get(i).GetAttributeNS('Name', '') + #13#10; + + //Removing the trailing #13#10 characters + Result:= Trim(Result); +end; + +//.............................................. + +//Consuming code example (fragment) +var + XMLInput: string; +begin + XMLInput:= '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''+ + ''; + Showmessage(GetStudents(XMLInput)); +end; diff --git a/Task/XML-Input/Factor/xml-input.factor b/Task/XML-Input/Factor/xml-input.factor new file mode 100644 index 0000000000..7410711aaa --- /dev/null +++ b/Task/XML-Input/Factor/xml-input.factor @@ -0,0 +1,14 @@ +USING: io sequences xml xml.data xml.traversal ; + +: print-student-names ( string -- ) + string>xml "Student" tags-named [ "Name" attr print ] each ; + +""" + + + + + + + +""" print-student-names diff --git a/Task/XML-Input/Fantom/xml-input.fantom b/Task/XML-Input/Fantom/xml-input.fantom new file mode 100644 index 0000000000..8ed3519c93 --- /dev/null +++ b/Task/XML-Input/Fantom/xml-input.fantom @@ -0,0 +1,18 @@ +using xml + +class XmlInput +{ + public static Void main () + { + // create the XML parser + parser := XParser(File("sample-xml.xml".toUri).in) + // parse the document, creating an XML document + XDoc doc := parser.parseDoc + // walk through each child element from the root of the document + doc.root.elems.each |elem| + { + // printing the Name attribute of all Students + if (elem.name == "Student") { echo (elem.get("Name")) } + } + } +} diff --git a/Task/XML-Input/Forth/xml-input.fth b/Task/XML-Input/Forth/xml-input.fth new file mode 100644 index 0000000000..2e07510c56 --- /dev/null +++ b/Task/XML-Input/Forth/xml-input.fth @@ -0,0 +1,48 @@ +include ffl/est.fs +include ffl/str.fs +include ffl/xis.fs + +\ Build input string +str-create xmlstr +: x+ xmlstr str-append-string ; + +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ +s\" \n" x+ + +\ Setup xml parser +xis-create xmlparser +xmlstr str-get xmlparser xis-set-string + +\ Parse the xml +: xmlparse + BEGIN + xmlparser xis-read dup xis.error <> over xis.done <> AND + WHILE + dup xis.start-tag = over xis.empty-element = OR IF + drop + s" Student" compare 0= IF + 0 ?DO + 2swap s" Name" compare 0= IF + type cr + ELSE + 2drop + THEN + LOOP + ELSE + xis+remove-attribute-parameters + THEN + ELSE + xis+remove-read-parameters + THEN + REPEAT + drop +; + +xmlparse diff --git a/Task/XML-Input/Go/xml-input.go b/Task/XML-Input/Go/xml-input.go new file mode 100644 index 0000000000..5990c04657 --- /dev/null +++ b/Task/XML-Input/Go/xml-input.go @@ -0,0 +1,50 @@ +package main + +import ( + "encoding/xml" + "fmt" +) + +const XML_DATA = ` + + + + + + + + + +` + +type Students struct { + Student []Student +} + +type Student struct { + Name string `xml:",attr"` + // Gender string `xml:",attr"` + // DateOfBirth string `xml:",attr"` + // Pets []Pet `xml:"Pet"` +} + +type Pet struct { + Type string `xml:",attr"` + Name string `xml:",attr"` +} + +// xml.Unmarshal quietly skips well formed input with no corresponding +// member in the output data structure. With Gender, DateOfBirth, and +// Pets commented out of the Student struct, as above, Student contains +// only Name, and this is the only value extracted from the input XML_DATA. +func main() { + data := new(Students) + err := xml.Unmarshal([]byte(XML_DATA), data) + if err != nil { + fmt.Println(err) + return + } + for _, s := range data.Student { + fmt.Println(s.Name) + } +} diff --git a/Task/XML-Input/Groovy/xml-input.groovy b/Task/XML-Input/Groovy/xml-input.groovy new file mode 100644 index 0000000000..408477328e --- /dev/null +++ b/Task/XML-Input/Groovy/xml-input.groovy @@ -0,0 +1,12 @@ +def input = """ + + + + + + + +""" + +def students = new XmlParser().parseText(input) +students.each { println it.'@Name' } diff --git a/Task/XML-Input/Haskell/xml-input-1.hs b/Task/XML-Input/Haskell/xml-input-1.hs new file mode 100644 index 0000000000..44c6ce97cc --- /dev/null +++ b/Task/XML-Input/Haskell/xml-input-1.hs @@ -0,0 +1,15 @@ +import Data.Maybe +import Text.XML.Light + +students=""++ + " "++ + " "++ + " "++ + " "++ + " "++ + " "++ + "" + +xmlRead elm name = mapM_ putStrLn + . concatMap (map (fromJust.findAttr (unqual name)).filterElementsName (== unqual elm)) + . onlyElems. parseXML diff --git a/Task/XML-Input/Haskell/xml-input-2.hs b/Task/XML-Input/Haskell/xml-input-2.hs new file mode 100644 index 0000000000..19d9de54c8 --- /dev/null +++ b/Task/XML-Input/Haskell/xml-input-2.hs @@ -0,0 +1,6 @@ +*Main> xmlRead "Student" "Name" students +April +Bob +Chad +Dave +Émily diff --git a/Task/XML-Input/HicEst/xml-input.hicest b/Task/XML-Input/HicEst/xml-input.hicest new file mode 100644 index 0000000000..b35596d746 --- /dev/null +++ b/Task/XML-Input/HicEst/xml-input.hicest @@ -0,0 +1,4 @@ +CHARACTER in*1000, out*100 + +READ(ClipBoard) in +EDIT(Text=in, SPR='"', Right=' + + + + + + + + +) diff --git a/Task/XML-Input/Java/xml-input.java b/Task/XML-Input/Java/xml-input.java new file mode 100644 index 0000000000..fe5e72e258 --- /dev/null +++ b/Task/XML-Input/Java/xml-input.java @@ -0,0 +1,51 @@ +import java.io.IOException; +import java.io.StringReader; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; +import org.xml.sax.helpers.XMLReaderFactory; + +public class StudentHandler extends DefaultHandler { + public static void main(String[] args)throws Exception{ + String xml = "\n"+ + "\n"+ + "\n"+ + "\n"+ + "\n"+ + " \n"+ + "\n"+ + "\n"+ + ""; + StudentHandler handler = new StudentHandler(); + handler.parse(new InputSource(new StringReader(xml))); + } + + public void parse(InputSource src) throws SAXException, IOException { + XMLReader parser = XMLReaderFactory.createXMLReader(); + parser.setContentHandler(this); + parser.parse(src); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + //if there were text as part of the elements, we would deal with it here + //by adding it to a StringBuffer, but we don't have to for this task + super.characters(ch, start, length); + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + //this is where we would get the info from the StringBuffer if we had to, + //but all we need is attributes + super.endElement(uri, localName, qName); + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if(qName.equals("Student")){ + System.out.println(attributes.getValue("Name")); + } + } +} diff --git a/Task/XML-Input/JavaScript/xml-input-1.js b/Task/XML-Input/JavaScript/xml-input-1.js new file mode 100644 index 0000000000..2d9fb3325b --- /dev/null +++ b/Task/XML-Input/JavaScript/xml-input-1.js @@ -0,0 +1,24 @@ +var xmlstr = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + +''; + +var list = xmlstr.match(//g); +var output = ''; +for (var i = 0; i < list.length; i++) { + if (i > 0) { + output += ', '; + } + var tmp = list[i].match(/Name="(.*?)"/); + output += tmp[1]; +} + +// Bounce it through a HTML element to handle Unicode for us +var l = document.createElement('p'); +l.innerHTML = output; +alert(l.innerHTML); diff --git a/Task/XML-Input/JavaScript/xml-input-2.js b/Task/XML-Input/JavaScript/xml-input-2.js new file mode 100644 index 0000000000..91edceb7c9 --- /dev/null +++ b/Task/XML-Input/JavaScript/xml-input-2.js @@ -0,0 +1,20 @@ +var xmlstr = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + +''; +var xml = XML(xmlstr); +var list = xml.Student.@Name; +var output = ''; +for (var i = 0; i < list.length(); i++) { + if (i > 0) { + output += ', '; + } + output += list[i]; +} + +alert(output); diff --git a/Task/XML-Input/Lua/xml-input.lua b/Task/XML-Input/Lua/xml-input.lua new file mode 100644 index 0000000000..e2f6d3097d --- /dev/null +++ b/Task/XML-Input/Lua/xml-input.lua @@ -0,0 +1,19 @@ +require 'lxp' +data = [[ + + + + + + + +]] + +p = lxp.new({StartElement = function (parser, name, attr) + if name == 'Student' and attr.Name then + print(attr.Name) + end +end}) + +p:parse(data) +p:close() diff --git a/Task/XML-Input/Mathematica/xml-input.math b/Task/XML-Input/Mathematica/xml-input.math new file mode 100644 index 0000000000..ae87cf250b --- /dev/null +++ b/Task/XML-Input/Mathematica/xml-input.math @@ -0,0 +1 @@ +Column[Cases[Import["test.xml","XML"],Rule["Name", n_ ] -> n,Infinity]] diff --git a/Task/XML-Input/OCaml/xml-input-1.ocaml b/Task/XML-Input/OCaml/xml-input-1.ocaml new file mode 100644 index 0000000000..c66e959a0d --- /dev/null +++ b/Task/XML-Input/OCaml/xml-input-1.ocaml @@ -0,0 +1,25 @@ +# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;; +# #load "xml-light.cma" ;; + +# let x = Xml.parse_string " + + + + + + + + + " + in + Xml.iter (function + Xml.Element ("Student", attrs, _) -> + List.iter (function ("Name", name) -> print_endline name | _ -> ()) attrs + | _ -> ()) x + ;; +April +Bob +Chad +Dave +Émily +- : unit = () diff --git a/Task/XML-Input/OCaml/xml-input-2.ocaml b/Task/XML-Input/OCaml/xml-input-2.ocaml new file mode 100644 index 0000000000..ab8ec4304f --- /dev/null +++ b/Task/XML-Input/OCaml/xml-input-2.ocaml @@ -0,0 +1,25 @@ +#directory "+xmlm" +#load "xmlm.cmo" +open Xmlm + +let str = " + + + + + + + + + " + + +let xi = make_input(`String(0, str)) + +let () = + while not(eoi xi) do + match Xmlm.input xi with + | `El_start ((_, "Student"), attrs) -> + List.iter (function ((_, "Name"), name) -> print_endline name | _ -> ()) attrs + | _ -> () + done diff --git a/Task/XML-Input/OCaml/xml-input-3.ocaml b/Task/XML-Input/OCaml/xml-input-3.ocaml new file mode 100644 index 0000000000..c9ee63e06a --- /dev/null +++ b/Task/XML-Input/OCaml/xml-input-3.ocaml @@ -0,0 +1,22 @@ +open Expat + +let xml_str = " + + + + + + + + + " + +let () = + let p = parser_create None in + set_start_element_handler p + (fun tag attrs -> + if tag = "Student" then + List.iter (function ("Name", name) -> print_endline name | _ -> ()) attrs + ); + parse p xml_str; + final p; diff --git a/Task/XML-Input/Objeck/xml-input.objeck b/Task/XML-Input/Objeck/xml-input.objeck new file mode 100644 index 0000000000..f00639fcdc --- /dev/null +++ b/Task/XML-Input/Objeck/xml-input.objeck @@ -0,0 +1,27 @@ +use XML; + +bundle Default { + class Test { + function : Main(args : String[]) ~ Nil { + in := String->New(); + in->Append(""); + in->Append(""); + in->Append(""); + in->Append(""); + in->Append(""); + in->Append(""); + in->Append(""); + in->Append(""); + + parser := XmlParser->New(in); + if(parser->Parse()) { + root := parser->GetRoot(); + children := root->GetChildren("Student"); + each(i : children) { + child : XMLElement := children->Get(i)->As(XMLElement); + XMLElement->DecodeString(child->GetAttribute("Name"))->PrintLine(); + }; + }; + } + } +} diff --git a/Task/XML-Input/OpenEdge-Progress/xml-input.openedge b/Task/XML-Input/OpenEdge-Progress/xml-input.openedge new file mode 100644 index 0000000000..e8c1bf3624 --- /dev/null +++ b/Task/XML-Input/OpenEdge-Progress/xml-input.openedge @@ -0,0 +1,36 @@ +DEF VAR lcc AS LONGCHAR. +DEF VAR hxdoc AS HANDLE. +DEF VAR hxstudents AS HANDLE. +DEF VAR hxstudent AS HANDLE. +DEF VAR hxname AS HANDLE. +DEF VAR ii AS INTEGER EXTENT 2. +DEF VAR cstudents AS CHARACTER. + +lcc = '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''. + +CREATE X-DOCUMENT hxdoc. +hxdoc:LOAD( 'LONGCHAR', lcc, FALSE ). + +DO ii[1] = 1 TO hxdoc:NUM-CHILDREN: + CREATE X-NODEREF hxstudents. + hxdoc:GET-CHILD( hxstudents, ii[1] ). + IF hxstudents:NAME = 'Students' THEN DO ii[2] = 1 TO hxstudents:NUM-CHILDREN: + CREATE X-NODEREF hxstudent. + hxstudents:GET-CHILD( hxstudent, ii[2] ). + IF hxstudent:NAME = 'Student' THEN + cstudents = cstudents + hxstudent:GET-ATTRIBUTE( 'Name' ) + '~n'. + DELETE OBJECT hxstudent. + END. + DELETE OBJECT hxstudents. +END. +DELETE OBJECT hxdoc. + +MESSAGE cstudents VIEW-AS ALERT-BOX. diff --git a/Task/XML-Input/Oz/xml-input.oz b/Task/XML-Input/Oz/xml-input.oz new file mode 100644 index 0000000000..b99ad360af --- /dev/null +++ b/Task/XML-Input/Oz/xml-input.oz @@ -0,0 +1,32 @@ +declare + [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} + Parser = {New XMLParser.parser init} + + Data = + "" + #" " + #" " + #" " + #" " + #" " + #" " + #" " + #"" + + fun {IsStudentElement X} + case X of element(name:'Student' ...) then true + else false + end + end + + fun {GetStudentName element(attributes:As ...)} + [NameAttr] = {Filter As fun {$ attribute(name:N ...)} N == 'Name' end} + in + NameAttr.value + end + + [StudentsDoc] = {Parser parseVS(Data $)} + Students = {Filter StudentsDoc.children IsStudentElement} + StudentNames = {Map Students GetStudentName} +in + {ForAll StudentNames System.showInfo} diff --git a/Task/XML-Input/PHP/xml-input.php b/Task/XML-Input/PHP/xml-input.php new file mode 100644 index 0000000000..b2545d8a17 --- /dev/null +++ b/Task/XML-Input/PHP/xml-input.php @@ -0,0 +1,16 @@ + + + + + + + + +'; +$xml = new XMLReader(); +$xml->xml( $data ); +while ( $xml->read() ) + if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' ) + echo $xml->getAttribute('Name') . "\n"; +?> diff --git a/Task/XML-Input/Perl/xml-input.pl b/Task/XML-Input/Perl/xml-input.pl new file mode 100644 index 0000000000..77cba64227 --- /dev/null +++ b/Task/XML-Input/Perl/xml-input.pl @@ -0,0 +1,13 @@ +use XML::Simple; + +my $ref = XMLin(' + + + + + + + +'); + +print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}}); diff --git a/Task/XML-Input/PicoLisp/xml-input.l b/Task/XML-Input/PicoLisp/xml-input.l new file mode 100644 index 0000000000..552c8b48e6 --- /dev/null +++ b/Task/XML-Input/PicoLisp/xml-input.l @@ -0,0 +1,5 @@ +(load "@lib/xm.l") + +(mapcar + '((L) (attr L 'Name)) + (body (in "file.xml" (xml))) ) diff --git a/Task/XML-Input/Pike/xml-input.pike b/Task/XML-Input/Pike/xml-input.pike new file mode 100644 index 0000000000..a9cd153b51 --- /dev/null +++ b/Task/XML-Input/Pike/xml-input.pike @@ -0,0 +1,19 @@ +string in = "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"; + +object s = Parser.XML.Tree.simple_parse_input(in); + +array collect = ({}); +s->walk_inorder(lambda(object node) + { + if (node->get_tag_name() == "Student") + collect += ({ node->get_attributes()->Name }); + }); +write("%{%s\n%}", collect); diff --git a/Task/XML-Input/PowerShell/xml-input.psh b/Task/XML-Input/PowerShell/xml-input.psh new file mode 100644 index 0000000000..c2a46e7871 --- /dev/null +++ b/Task/XML-Input/PowerShell/xml-input.psh @@ -0,0 +1,13 @@ +[xml]$xml = @' + + + + + + + + + +'@ + +foreach ($node in $xml.DocumentElement.ChildNodes) {$node.Name} diff --git a/Task/XML-Input/PureBasic/xml-input.purebasic b/Task/XML-Input/PureBasic/xml-input.purebasic new file mode 100644 index 0000000000..547cdd564d --- /dev/null +++ b/Task/XML-Input/PureBasic/xml-input.purebasic @@ -0,0 +1,50 @@ +Define studentNames.String, src$ + +src$ = "" +src$ + "" +src$ + "" +src$ + "" +src$ + "" +src$ + "" +src$ + "" +src$ + "" +src$ + "" + +;This procedure is generalized to match any attribute of any normal element's node name +;i.e. get_values(MainXMLNode(0),"Pet","Type",@petName.String) and displaying petName\s +;would display "dog". +Procedure get_values(*cur_node, nodeName$, attribute$, *valueResults.String) + ;If nodeName$ and attribute$ are matched then the value + ;will be added to the string structure pointed to by *valueResults . + Protected result$ + + While *cur_node + If XMLNodeType(*cur_node) = #PB_XML_Normal + + result$ = GetXMLNodeName(*cur_node) + If result$ = nodeName$ + If ExamineXMLAttributes(*cur_node) + While NextXMLAttribute(*cur_node) + If XMLAttributeName(*cur_node) = attribute$ + If *valueResults <> #Null + *valueResults\s + XMLAttributeValue(*cur_node) + Chr(13) ;value + carriage-return + EndIf + EndIf + Wend + EndIf + EndIf + + EndIf + + get_values(ChildXMLNode(*cur_node), nodeName$, attribute$, *valueResults) + *cur_node = NextXMLNode(*cur_node) + Wend +EndProcedure + +CatchXML(0,@src$,Len(src$)) + +If IsXML(0) + get_values(MainXMLNode(0), "Student", "Name",@studentNames) + MessageRequester("Student Names", studentNames\s) + FreeXML(0) +EndIf diff --git a/Task/XML-Input/Python/xml-input.py b/Task/XML-Input/Python/xml-input.py new file mode 100644 index 0000000000..99c6e2dc1c --- /dev/null +++ b/Task/XML-Input/Python/xml-input.py @@ -0,0 +1,16 @@ +import xml.dom.minidom + +doc = """ + + + + + + + +""" + +doc = xml.dom.minidom.parseString(doc) + +for i in doc.getElementsByTagName("Student"): + print i.getAttribute("Name") diff --git a/Task/XML-Input/R/xml-input-1.r b/Task/XML-Input/R/xml-input-1.r new file mode 100644 index 0000000000..9e7e5da219 --- /dev/null +++ b/Task/XML-Input/R/xml-input-1.r @@ -0,0 +1,13 @@ +library(XML) +#Read in XML string +str <- readLines(tc <- textConnection(' + + + + + + + +')) +close(tc) +str diff --git a/Task/XML-Input/R/xml-input-2.r b/Task/XML-Input/R/xml-input-2.r new file mode 100644 index 0000000000..fa85ba8fde --- /dev/null +++ b/Task/XML-Input/R/xml-input-2.r @@ -0,0 +1,18 @@ +#Convert to an XML tree +xmltree <- xmlTreeParse(str) + +#Retrieve the students, and how many there are +students <- xmltree$doc$children$Students +nstudents <- length(students) + +#Get each of their names +studentsnames <- character(nstudents) +for(i in 1:nstudents) +{ + this.student <- students$children[i]$Student + studentsnames[i] <- this.student$attributes["Name"] +} + +#Change the encoding so that Emily displays correctly +Encoding(studentsnames) <- "UTF-8" +studentsnames diff --git a/Task/XML-Input/REBOL/xml-input.rebol b/Task/XML-Input/REBOL/xml-input.rebol new file mode 100644 index 0000000000..8654d39dae --- /dev/null +++ b/Task/XML-Input/REBOL/xml-input.rebol @@ -0,0 +1,37 @@ +REBOL [ + Title: "XML Reading" + Author: oofoe + Date: 2009-12-08 + URL: http://rosettacode.org/wiki/XML_Reading +] + +xml: { + + + + + + + + + +} + +; REBOL has a simple built-in XML parser. It's not terribly fancy, but +; it's easy to use. It converts the XML into a nested list of blocks +; which can be accessed using standard REBOL path operators. The only +; annoying part (in this case) is that it does try to preserve +; whitespace, so some of the parsed elements are just things like line +; endings and whatnot, which I need to ignore. + +; Once I have drilled down to the individual student records, I can +; just use the standard REBOL 'select' to locate the requested +; property. + +data: parse-xml xml +students: data/3/1/3 ; Drill down to student records. +foreach student students [ + if block! = type? student [ ; Ignore whitespace elements. + print select student/2 "Name" + ] +] diff --git a/Task/XML-Input/REXX/xml-input-1.rexx b/Task/XML-Input/REXX/xml-input-1.rexx new file mode 100644 index 0000000000..30c279f5a1 --- /dev/null +++ b/Task/XML-Input/REXX/xml-input-1.rexx @@ -0,0 +1,18 @@ +/*REXX program to extract student names from an XML string(s). */ +g.= +g.1=' ' +g.2=' ' +g.3=' ' +g.4=' ' +g.5=' ' +g.6=' ' +g.7=' ' +g.8=' ' +g.9=' ' + + do j=1 while g.j\=='' + g.j=space(g.j) + parse var g.j 'Name="' studname '"' + if studname\=='' then say studname + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/XML-Input/REXX/xml-input-2.rexx b/Task/XML-Input/REXX/xml-input-2.rexx new file mode 100644 index 0000000000..41e3652830 --- /dev/null +++ b/Task/XML-Input/REXX/xml-input-2.rexx @@ -0,0 +1,6 @@ +April +Bob +Chad +Dave +Rover +Émily diff --git a/Task/XML-Input/REXX/xml-input-3.rexx b/Task/XML-Input/REXX/xml-input-3.rexx new file mode 100644 index 0000000000..fe08e878ac --- /dev/null +++ b/Task/XML-Input/REXX/xml-input-3.rexx @@ -0,0 +1,85 @@ +/*REXX program to extract student names from an XML string(s). */ +g.= +g.1=' ' +g.2=' ' +g.3=' ' +g.4=' ' +g.5=' ' +g.6=' ' +g.7=' ' +g.8=' ' +g.9=' ' + + do j=1 while g.j\=='' + g.j=space(g.j) + parse var g.j 'Name="' studname '"' + if studname=='' then iterate + if pos('&',studname)\==0 then studname=xmlTranE(studname) + say studname + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────XML_ subroutine─────────────────────*/ +xml_: parse arg ,_ /*tran an XML entity (&xxxx;) */ +xmlEntity! = '&'_";" +if pos(xmlEntity!,x)\==0 then x=changestr(xmlEntity!,x,arg(1)) +if left(_,2)=='#x' then do + xmlEntity!='&'left(_,3)translate(substr(_,4))";" + x=changestr(xmlEntity!,x,arg(1)) + end +return x +/*──────────────────────────────────XMLTRANE subroutine─────────────────*/ +xmlTranE: procedure; parse arg x /*Following are most of the chars in*/ + /*the DOS (under Windows) codepage. */ +x=XML_('♥',"hearts") ; x=XML_('â',"ETH") ; x=XML_('ƒ',"fnof") ; x=XML_('═',"boxH") +x=XML_('♦',"diams") ; x=XML_('â','#x00e2') ; x=XML_('á',"aacute"); x=XML_('╬',"boxVH") +x=XML_('♣',"clubs") ; x=XML_('â','#x00e9') ; x=XML_('á','#x00e1'); x=XML_('╧',"boxHu") +x=XML_('♠',"spades") ; x=XML_('ä',"auml") ; x=XML_('í',"iacute"); x=XML_('╨',"boxhU") +x=XML_('♂',"male") ; x=XML_('ä','#x00e4') ; x=XML_('í','#x00ed'); x=XML_('╤',"boxHd") +x=XML_('♀',"female") ; x=XML_('à',"agrave") ; x=XML_('ó',"oacute"); x=XML_('╥',"boxhD") +x=XML_('☼',"#x263c") ; x=XML_('à','#x00e0') ; x=XML_('ó','#x00f3'); x=XML_('╙',"boxUr") +x=XML_('↕',"UpDownArrow") ; x=XML_('å',"aring") ; x=XML_('ú',"uacute"); x=XML_('╘',"boxuR") +x=XML_('¶',"para") ; x=XML_('å','#x00e5') ; x=XML_('ú','#x00fa'); x=XML_('╒',"boxdR") +x=XML_('§',"sect") ; x=XML_('ç',"ccedil") ; x=XML_('ñ',"ntilde"); x=XML_('╓',"boxDr") +x=XML_('↑',"uarr") ; x=XML_('ç','#x00e7') ; x=XML_('ñ','#x00f1'); x=XML_('╫',"boxVh") +x=XML_('↑',"uparrow") ; x=XML_('ê',"ecirc") ; x=XML_('Ñ',"Ntilde"); x=XML_('╪',"boxvH") +x=XML_('↑',"ShortUpArrow") ; x=XML_('ê','#x00ea') ; x=XML_('Ñ','#x00d1'); x=XML_('┘',"boxul") +x=XML_('↓',"darr") ; x=XML_('ë',"euml") ; x=XML_('¿',"iquest"); x=XML_('┌',"boxdr") +x=XML_('↓',"downarrow") ; x=XML_('ë','#x00eb') ; x=XML_('⌐',"bnot") ; x=XML_('█',"block") +x=XML_('↓',"ShortDownArrow") ; x=XML_('è',"egrave") ; x=XML_('¬',"not") ; x=XML_('▄',"lhblk") +x=XML_('←',"larr") ; x=XML_('è','#x00e8') ; x=XML_('½',"frac12"); x=XML_('▀',"uhblk") +x=XML_('←',"leftarrow") ; x=XML_('ï',"iuml") ; x=XML_('½',"half") ; x=XML_('α',"alpha") +x=XML_('←',"ShortLeftArrow") ; x=XML_('ï','#x00ef') ; x=XML_('¼',"frac14"); x=XML_('ß',"beta") +x=XML_('1c'x,"rarr") ; x=XML_('î',"icirc") ; x=XML_('¡',"iexcl") ; x=XML_('ß',"szlig") +x=XML_('1c'x,"rightarrow") ; x=XML_('î','#x00ee') ; x=XML_('«',"laqru") ; x=XML_('ß','#x00df') +x=XML_('1c'x,"ShortRightArrow"); x=XML_('ì',"igrave") ; x=XML_('»',"raqru") ; x=XML_('Γ',"Gamma") +x=XML_('!',"excl") ; x=XML_('ì','#x00ec') ; x=XML_('░',"blk12") ; x=XML_('π',"pi") +x=XML_('"',"apos") ; x=XML_('Ä',"Auml") ; x=XML_('▒',"blk14") ; x=XML_('Σ',"Sigma") +x=XML_('$',"dollar") ; x=XML_('Ä','#x00c4') ; x=XML_('▓',"blk34") ; x=XML_('σ',"sigma") +x=XML_("'","quot") ; x=XML_('Å',"Aring") ; x=XML_('│',"boxv") ; x=XML_('µ',"mu") +x=XML_('*',"ast") ; x=XML_('Å','#x00c5') ; x=XML_('┤',"boxvl") ; x=XML_('τ',"tau") +x=XML_('/',"sol") ; x=XML_('É',"Eacute") ; x=XML_('╡',"boxvL") ; x=XML_('Φ',"phi") +x=XML_(':',"colon") ; x=XML_('É','#x00c9') ; x=XML_('╢',"boxVl") ; x=XML_('Θ',"Theta") +x=XML_('<',"lt") ; x=XML_('æ',"aelig") ; x=XML_('╖',"boxDl") ; x=XML_('δ',"delta") +x=XML_('=',"equals") ; x=XML_('æ','#x00e6') ; x=XML_('╕',"boxdL") ; x=XML_('∞',"infin") +x=XML_('>',"gt") ; x=XML_('Æ',"AElig") ; x=XML_('╣',"boxVL") ; x=XML_('φ',"Phi") +x=XML_('?',"quest") ; x=XML_('Æ','#x00c6') ; x=XML_('║',"boxV") ; x=XML_('ε',"epsilon") +x=XML_('@',"commat") ; x=XML_('ô',"ocirc") ; x=XML_('╗',"boxDL") ; x=XML_('∩',"cap") +x=XML_('[',"lbrack") ; x=XML_('ô','#x00f4') ; x=XML_('╝',"boxUL") ; x=XML_('≡',"equiv") +x=XML_('\',"bsol") ; x=XML_('ö',"ouml") ; x=XML_('╜',"boxUl") ; x=XML_('±',"plusmn") +x=XML_(']',"rbrack") ; x=XML_('ö','#x00f6') ; x=XML_('╛',"boxuL") ; x=XML_('±',"pm") +x=XML_('^',"Hat") ; x=XML_('ò',"ograve") ; x=XML_('┐',"boxdl") ; x=XML_('±',"PlusMinus") +x=XML_('`',"grave") ; x=XML_('ò','#x00f2') ; x=XML_('└',"boxur") ; x=XML_('≥',"ge") +x=XML_('{',"lbrace") ; x=XML_('û',"ucirc") ; x=XML_('┴',"bottom"); x=XML_('≤',"le") +x=XML_('{',"lcub") ; x=XML_('û','#x00fb') ; x=XML_('┴',"boxhu") ; x=XML_('÷',"div") +x=XML_('|',"vert") ; x=XML_('ù',"ugrave") ; x=XML_('┬',"boxhd") ; x=XML_('÷',"divide") +x=XML_('|',"verbar") ; x=XML_('ù','#x00f9') ; x=XML_('├',"boxvr") ; x=XML_('≈',"approx") +x=XML_('}',"rbrace") ; x=XML_('ÿ',"yuml") ; x=XML_('─',"boxh") ; x=XML_('∙',"bull") +x=XML_('}',"rcub") ; x=XML_('ÿ','#x00ff') ; x=XML_('┼',"boxvh") ; x=XML_('°',"deg") +x=XML_('Ç',"Ccedil") ; x=XML_('Ö',"Ouml") ; x=XML_('╞',"boxvR") ; x=XML_('·',"middot") +x=XML_('Ç','#x00c7') ; x=XML_('Ö','#x00d6') ; x=XML_('╟',"boxVr") ; x=XML_('·',"middledot") +x=XML_('ü',"uuml") ; x=XML_('Ü',"Uuml") ; x=XML_('╚',"boxUR") ; x=XML_('·',"centerdot") +x=XML_('ü','#x00fc') ; x=XML_('Ü','#x00dc') ; x=XML_('╔',"boxDR") ; x=XML_('·',"CenterDot") +x=XML_('é',"eacute") ; x=XML_('¢',"cent") ; x=XML_('╩',"boxHU") ; x=XML_('√',"radic") +x=XML_('é','#x00e9') ; x=XML_('£',"pound") ; x=XML_('╦',"boxHD") ; x=XML_('²',"sup2") +x=XML_('â',"acirc") ; x=XML_('¥',"yen") ; x=XML_('╠',"boxVR") ; x=XML_('■',"squart ") +return x diff --git a/Task/XML-Input/Racket/xml-input.rkt b/Task/XML-Input/Racket/xml-input.rkt new file mode 100644 index 0000000000..f99b27fecc --- /dev/null +++ b/Task/XML-Input/Racket/xml-input.rkt @@ -0,0 +1,23 @@ +#lang racket +(require xml xml/path) + +(define input +#< + + + + + + + + +END + ) + +(define students + (xml->xexpr + (document-element + (read-xml (open-input-string input))))) + +(se-path*/list '(Student #:Name) students) diff --git a/Task/XML-Input/Rascal/xml-input-1.rascal b/Task/XML-Input/Rascal/xml-input-1.rascal new file mode 100644 index 0000000000..d8ba650a96 --- /dev/null +++ b/Task/XML-Input/Rascal/xml-input-1.rascal @@ -0,0 +1,8 @@ +import lang::xml::DOM; + +public void getNames(loc a){ + D = parseXMLDOM(readFile(a)); + visit(D){ + case element(_,"Student",[_*,attribute(_,"Name", x),_*]): println(x); + }; +} diff --git a/Task/XML-Input/Rascal/xml-input-2.rascal b/Task/XML-Input/Rascal/xml-input-2.rascal new file mode 100644 index 0000000000..4bfe9ba437 --- /dev/null +++ b/Task/XML-Input/Rascal/xml-input-2.rascal @@ -0,0 +1,7 @@ +rascal>getNames(|file:///Users/.../Desktop/xmlinput.xml|) +April +Bob +Chad +Dave +Émily +ok diff --git a/Task/XML-Input/Ruby/xml-input.rb b/Task/XML-Input/Ruby/xml-input.rb new file mode 100644 index 0000000000..fb78c64d7c --- /dev/null +++ b/Task/XML-Input/Ruby/xml-input.rb @@ -0,0 +1,14 @@ +require 'rexml/document' +include REXML + +doc = Document.new(File.new("sample.xml")) +# or +# doc = Document.new(xml_string) + +# without using xpath +doc.each_recursive do |node| + puts node.attributes["Name"] if node.name == "Student" +end + +# using xpath +doc.each_element("*/Student") {|node| puts node.attributes["Name"]} diff --git a/Task/XML-Input/Run-BASIC/xml-input.run b/Task/XML-Input/Run-BASIC/xml-input.run new file mode 100644 index 0000000000..fae025c923 --- /dev/null +++ b/Task/XML-Input/Run-BASIC/xml-input.run @@ -0,0 +1,44 @@ +' ------------------------------------------------------------------------ +'XMLPARSER methods + +'#handle ELEMENTCOUNT() - Return the number of child XML elements +'#handle KEY$() - Return the key as a string from an XML expression like value +'#handle VALUE$() - Return the value as a string from an XML expression like value +'#handle VALUEFORKEY$(keyExpr$) - Return the value for the specified tag key in keyExpr$ +'#handle #ELEMENT(n) - Return the nth child-element XML element +'#handle #ELEMENT(nameExpr$) - Return the child-element XML element named by nameExpr$ +'#handle ATTRIBCOUNT() - Return a count of attribute pairs; has two pairs +'#handle ATTRIBKEY$(n) - Return the key string of the nth attribute +'#handle ATTRIBVALUE$(n) - Return the value string of the nth attribute +'#handle ATTRIBVALUE$(n$) - Return the value string of the attribute with the key n$, or an empty string if it doesn't exist. +'#handle ISNULL() - Returns zero (or false) +'#handle DEBUG$() - Returns the string "Xmlparser" +' ------------------------------------------------------------------------ + +' The xml string +xml$ = " + + + + + + + + +" + + +' Creates the xml handler, using the string +xmlparser #spies, xml$ + +' Uses elementCount() to know how many elements are in betweeb ... +for count = 1 to #spies elementCount() + + ' Uses "count" to work through the elements, and assigns the element to the + ' handle "#spy" + #spy = #spies #element(count) + + ' Prints the value, or inner text, of "#spy": Sam, Clover, & Alex + print count;" ";#spy value$();" ->";#spy ATTRIBVALUE$(1) + +next count diff --git a/Task/XML-Input/Scala/xml-input.scala b/Task/XML-Input/Scala/xml-input.scala new file mode 100644 index 0000000000..6e41153da1 --- /dev/null +++ b/Task/XML-Input/Scala/xml-input.scala @@ -0,0 +1,12 @@ +val students = + + + + + + + + + + +students \ "Student" \\ "@Name" foreach println diff --git a/Task/XML-Input/Slate/xml-input.slate b/Task/XML-Input/Slate/xml-input.slate new file mode 100644 index 0000000000..b201a3de5e --- /dev/null +++ b/Task/XML-Input/Slate/xml-input.slate @@ -0,0 +1,21 @@ +slate[1]> [ |tree| + + tree: (Xml SimpleParser newOn: ' + + + + + + + + ') parse. + tree name = 'Students' ifTrue: [(tree children select: #is: `er <- Xml Element) + do: [|:child| child name = 'Student' ifTrue: [inform: (child attributes at: 'Name' ifAbsent: ['Noname'])]]]. + +] do. +April +Bob +Chad +Dave +Émily +Nil diff --git a/Task/XML-Input/TUSCRIPT/xml-input.tuscript b/Task/XML-Input/TUSCRIPT/xml-input.tuscript new file mode 100644 index 0000000000..3131508188 --- /dev/null +++ b/Task/XML-Input/TUSCRIPT/xml-input.tuscript @@ -0,0 +1,22 @@ +$$ MODE TUSCRIPT +MODE DATA +$$ SET xmldata =* + + + + + + + + + +$$ MODE TUSCRIPT +COMPILE +LOOP x = xmldata +SET name=GET_TAG_NAME (x) +IF (name=="student") THEN +SET studentname=GET_ATTRIBUTE (x,"Name") +IF (studentname!="") PRINT studentname +ENDIF +ENDLOOP +ENDCOMPILE diff --git a/Task/XML-Input/TXR/xml-input-1.txr b/Task/XML-Input/TXR/xml-input-1.txr new file mode 100644 index 0000000000..8cf437cb73 --- /dev/null +++ b/Task/XML-Input/TXR/xml-input-1.txr @@ -0,0 +1,19 @@ + +@(collect :vars (NAME GENDER YEAR MONTH DAY (PET_TYPE "none") (PET_NAME ""))) +@ (cases) + +@ (end) +@(until) + +@(end) +@(output :filter :from_html) +NAME G DOB PET +@ (repeat) +@{NAME 12} @GENDER @YEAR-@MONTH-@DAY @PET_TYPE @PET_NAME +@ (end) +@(end) diff --git a/Task/XML-Input/TXR/xml-input-2.txr b/Task/XML-Input/TXR/xml-input-2.txr new file mode 100644 index 0000000000..d450d08e54 --- /dev/null +++ b/Task/XML-Input/TXR/xml-input-2.txr @@ -0,0 +1,3 @@ +@(output :filter :from_html) +@NAME +@(end) diff --git a/Task/XML-Input/Tcl/xml-input-1.tcl b/Task/XML-Input/Tcl/xml-input-1.tcl new file mode 100644 index 0000000000..93f5918b43 --- /dev/null +++ b/Task/XML-Input/Tcl/xml-input-1.tcl @@ -0,0 +1,7 @@ +package require tdom +set tree [dom parse $xml] +set studentNodes [$tree getElementsByTagName Student] ;# or: set studentNodes [[$tree documentElement] childNodes] + +foreach node $studentNodes { + puts [$node getAttribute Name] +} diff --git a/Task/XML-Input/Tcl/xml-input-2.tcl b/Task/XML-Input/Tcl/xml-input-2.tcl new file mode 100644 index 0000000000..90a4c890ca --- /dev/null +++ b/Task/XML-Input/Tcl/xml-input-2.tcl @@ -0,0 +1,8 @@ +package require xml +set parser [xml::parser -elementstartcommand elem] +proc elem {name attlist args} { + if {$name eq "Student"} { + puts [dict get $attlist Name] + } +} +$parser parse $xml diff --git a/Task/XML-Input/Tcl/xml-input-3.tcl b/Task/XML-Input/Tcl/xml-input-3.tcl new file mode 100644 index 0000000000..41061c5147 --- /dev/null +++ b/Task/XML-Input/Tcl/xml-input-3.tcl @@ -0,0 +1,51 @@ +proc xml2list xml { + regsub -all {>\s*<} [string trim $xml " \n\t<>"] "\} \{" xml + set xml [string map {> "\} \{#text \{" < "\}\} \{"} $xml] + set res "" ;# string to collect the result + set stack {} ;# track open tags + set rest {} + foreach item "{$xml}" { + switch -regexp -- $item { + ^# {append res "{[lrange $item 0 end]} " ; #text item} + ^/ { + regexp {/(.+)} $item -> tagname ;# end tag + set expected [lindex $stack end] + set stack [lrange $stack 0 end-1] + append res "\}\} " + } + /$ { # singleton - start and end in one <> group + regexp {([^ ]+)( (.+))?/$} $item -> tagname - rest + set rest [lrange [string map {= " "} $rest] 0 end] + append res "{$tagname [list $rest] {}} " + } + default { + set tagname [lindex $item 0] ;# start tag + set rest [lrange [string map {= " "} $item] 1 end] + lappend stack $tagname + append res "\{$tagname [list $rest] \{" + } + } + } + string map {"\} \}" "\}\}"} [lindex $res 0] ;#" +} +proc deent str { + regsub -all {&\#x(.+?);} $str {\\u\1} str + subst -nocommands -novar $str +} +#----------------------- Testing the whole thing: +set xml { + + + + + + + +} +foreach i [lindex [xml2list $xml] 2] { + if {[lindex $i 0] eq "Student"} { + foreach {att val} [lindex $i 1] { + if {$att eq "Name"} {puts [deent $val]} + } + } +} diff --git a/Task/XML-Input/Vedit-macro-language/xml-input.vedit b/Task/XML-Input/Vedit-macro-language/xml-input.vedit new file mode 100644 index 0000000000..99a0dc2613 --- /dev/null +++ b/Task/XML-Input/Vedit-macro-language/xml-input.vedit @@ -0,0 +1,10 @@ +Repeat(ALL) { + Search(" + + + + + + + +Dim names = (From node In xml... Select node.@Name).ToArray + +For Each name In names + Console.WriteLine(name) +Next diff --git a/Task/XML-Input/XPL0/xml-input.xpl0 b/Task/XML-Input/XPL0/xml-input.xpl0 new file mode 100644 index 0000000000..1eed3ebd0e --- /dev/null +++ b/Task/XML-Input/XPL0/xml-input.xpl0 @@ -0,0 +1,45 @@ +code ChOut=8, CrLf=9; \intrinsic routines +string 0; \use zero-terminated strings + +func StrLen(A); \Return number of characters in an ASCIIZ string +char A; +int I; +for I:= 0 to -1>>1-1 do + if A(I) = 0 then return I; + +func StrFind(A, B); \Search for ASCIIZ string A in string B +\Returns address of first occurrence of string A in B, or zero if A is not found +char A, B; \strings to be compared +int LA, LB, I, J; +[LA:= StrLen(A); +LB:= StrLen(B); +for I:= 0 to LB-LA do + [for J:= 0 to LA-1 do + if A(J) # B(J+I) then J:= LA+1; + if J = LA then return B+I; \found + ]; +return 0; +]; + +char XML, P; +[XML:= " + + + + + + + + "; +P:= XML; +loop [P:= StrFind(" elements each with a name attributes and each enclosing its remarks. All elements are to be enclosed in turn, in an outer element. + +As an example, calling the function with the three names of: +
+April
+Tam O'Shanter
+Emily
+And three remarks of: +
+Bubbly: I'm > Tam and <= Emily
+Burns: "When chapman billies leave the street ..."
+Short & shrift
+Should produce the XML (but not necessarily with the indentation): + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + + +The document may include an declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation ''must'' include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. + +Note: the example is chosen to show correct escaping of XML strings. +Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. + +'''Note to editors:''' Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See [[Talk:XML_Creation#Escaping_Escapes|this]]). Alternately, output can be placed in tags without any special treatment. diff --git a/Task/XML-Output/1META.yaml b/Task/XML-Output/1META.yaml new file mode 100644 index 0000000000..d7f654b55d --- /dev/null +++ b/Task/XML-Output/1META.yaml @@ -0,0 +1,2 @@ +--- +note: XML diff --git a/Task/XML-Output/Ada/xml-output-1.ada b/Task/XML-Output/Ada/xml-output-1.ada new file mode 100644 index 0000000000..2224c6c472 --- /dev/null +++ b/Task/XML-Output/Ada/xml-output-1.ada @@ -0,0 +1,40 @@ +with Ada.Strings.Unbounded; +with Ada.Text_IO.Text_Streams; +with DOM.Core.Documents; +with DOM.Core.Elements; +with DOM.Core.Nodes; + +procedure Character_Remarks is + package DC renames DOM.Core; + package IO renames Ada.Text_IO; + package US renames Ada.Strings.Unbounded; + type Remarks is record + Name : US.Unbounded_String; + Text : US.Unbounded_String; + end record; + type Remark_List is array (Positive range <>) of Remarks; + My_Remarks : Remark_List := + ((US.To_Unbounded_String ("April"), + US.To_Unbounded_String ("Bubbly: I'm > Tam and <= Emily")), + (US.To_Unbounded_String ("Tam O'Shanter"), + US.To_Unbounded_String ("Burns: ""When chapman billies leave the street ...""")), + (US.To_Unbounded_String ("Emily"), + US.To_Unbounded_String ("Short & shrift"))); + My_Implementation : DC.DOM_Implementation; + My_Document : DC.Document := DC.Create_Document (My_Implementation); + My_Root_Node : DC.Element := DC.Nodes.Append_Child (My_Document, + DC.Documents.Create_Element (My_Document, "CharacterRemarks")); + My_Element_Node : DC.Element; + My_Text_Node : DC.Text; +begin + for I in My_Remarks'Range loop + My_Element_Node := DC.Nodes.Append_Child (My_Root_Node, + DC.Documents.Create_Element (My_Document, "Character")); + DC.Elements.Set_Attribute (My_Element_Node, "Name", US.To_String (My_Remarks (I).Name)); + My_Text_Node := DC.Nodes.Append_Child (My_Element_Node, + DC.Documents.Create_Text_Node (My_Document, US.To_String (My_Remarks (I).Text))); + end loop; + DC.Nodes.Write (IO.Text_Streams.Stream (IO.Standard_Output), + N => My_Document, + Pretty_Print => True); +end Character_Remarks; diff --git a/Task/XML-Output/Ada/xml-output-2.ada b/Task/XML-Output/Ada/xml-output-2.ada new file mode 100644 index 0000000000..7f08a739de --- /dev/null +++ b/Task/XML-Output/Ada/xml-output-2.ada @@ -0,0 +1,53 @@ +with Ada.Wide_Wide_Text_IO; + +with League.Strings; +with XML.SAX.Attributes; +with XML.SAX.Pretty_Writers; + +procedure Main is + + function "+" + (Item : Wide_Wide_String) return League.Strings.Universal_String + renames League.Strings.To_Universal_String; + + type Remarks is record + Name : League.Strings.Universal_String; + Remark : League.Strings.Universal_String; + end record; + + type Remarks_Array is array (Positive range <>) of Remarks; + + ------------ + -- Output -- + ------------ + + procedure Output (Remarks : Remarks_Array) is + Writer : XML.SAX.Pretty_Writers.SAX_Pretty_Writer; + Attributes : XML.SAX.Attributes.SAX_Attributes; + + begin + Writer.Set_Offset (2); + Writer.Start_Document; + Writer.Start_Element (Qualified_Name => +"CharacterRemarks"); + + for J in Remarks'Range loop + Attributes.Clear; + Attributes.Set_Value (+"name", Remarks (J).Name); + Writer.Start_Element + (Qualified_Name => +"Character", Attributes => Attributes); + Writer.Characters (Remarks (J).Remark); + Writer.End_Element (Qualified_Name => +"Character"); + end loop; + + Writer.End_Element (Qualified_Name => +"CharacterRemarks"); + Writer.End_Document; + + Ada.Wide_Wide_Text_IO.Put_Line (Writer.Text.To_Wide_Wide_String); + end Output; + +begin + Output + (((+"April", +"Bubbly: I'm > Tam and <= Emily"), + (+"Tam O'Shanter", +"Burns: ""When chapman billies leave the street ..."""), + (+"Emily", +"Short & shrift"))); +end Main; diff --git a/Task/XML-Output/AutoHotkey/xml-output.ahk b/Task/XML-Output/AutoHotkey/xml-output.ahk new file mode 100644 index 0000000000..7f6c8fc0c2 --- /dev/null +++ b/Task/XML-Output/AutoHotkey/xml-output.ahk @@ -0,0 +1,50 @@ +gosub constants +names := xmlescape(names) +remarks := xmlescape(remarks) + +stringsplit, remarks, remarks, `n +xml = "" + +loop, parse, names, `n + xml .= "" . remarks%A_Index% + . "`n" + +xml .= "" + +msgbox % xml +return + +xmlescape(string) +{ + static + punc = ",>,<,<=,>=,',& ; " + xmlpunc = ",>,<,<=,>=,',& + if !punc1 + { + StringSplit, punc, punc, `, + StringSplit, xmlpunc, xmlpunc, `, + } + escaped := string + loop, parse, punc, `, + { + StringReplace, escaped, escaped, % A_LoopField, % xmlpunc%A_Index%, All + } + Return escaped +} + +constants: +#LTrim +names = +( + April + Tam O'Shanter + Emily +) + +remarks = +( + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift +) +return diff --git a/Task/XML-Output/BASIC/xml-output.basic b/Task/XML-Output/BASIC/xml-output.basic new file mode 100644 index 0000000000..0ebbcb64bd --- /dev/null +++ b/Task/XML-Output/BASIC/xml-output.basic @@ -0,0 +1,40 @@ +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/XML-Output/C++/xml-output.cpp b/Task/XML-Output/C++/xml-output.cpp new file mode 100644 index 0000000000..44b813ebed --- /dev/null +++ b/Task/XML-Output/C++/xml-output.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +std::string create_xml( std::vector & ,std::vector & ) ; + +int main( ) { + std::vector names , remarks ; + names.push_back( "April" ) ; + names.push_back( "Tam O'Shantor" ) ; + names.push_back ( "Emily" ) ; + remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ; + remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ; + remarks.push_back( "Short & shrift" ) ; + std::cout << "This is in XML:\n" ; + std::cout << create_xml( names , remarks ) << std::endl ; + return 0 ; +} + +std::string create_xml( std::vector & names , + std::vector & remarks ) { + std::vector > entities ; + entities.push_back( std::make_pair( "&" , "&" ) ) ; + entities.push_back( std::make_pair( "<" , "<" ) ) ; + entities.push_back( std::make_pair( ">" , ">" ) ) ; + std::string xmlstring ( "\n" ) ; + std::vector::iterator vsi = names.begin( ) ; + typedef std::vector >::iterator Vpss ; + for ( ; vsi != names.end( ) ; vsi++ ) { + for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { + boost::replace_all ( *vsi , vs->first , vs->second ) ; + } + } + for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) { + for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { + boost::replace_all ( *vsi , vs->first , vs->second ) ; + } + } + for ( int i = 0 ; i < names.size( ) ; i++ ) { + xmlstring.append( "\t") + .append( remarks[ i ] ).append( "\n" ) ; + } + xmlstring.append( "" ) ; + return xmlstring ; +} diff --git a/Task/XML-Output/C-sharp/xml-output.cs b/Task/XML-Output/C-sharp/xml-output.cs new file mode 100644 index 0000000000..36ab8e470c --- /dev/null +++ b/Task/XML-Output/C-sharp/xml-output.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; + +class Program +{ + static string CreateXML(Dictionary characterRemarks) + { + var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); + var xml = new XElement("CharacterRemarks", remarks); + return xml.ToString(); + } + + static void Main(string[] args) + { + var characterRemarks = new Dictionary + { + { "April", "Bubbly: I'm > Tam and <= Emily" }, + { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, + { "Emily", "Short & shrift" } + }; + + string xml = CreateXML(characterRemarks); + Console.WriteLine(xml); + } +} diff --git a/Task/XML-Output/C/xml-output.c b/Task/XML-Output/C/xml-output.c new file mode 100644 index 0000000000..c2d3a6454f --- /dev/null +++ b/Task/XML-Output/C/xml-output.c @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include + +const char *names[] = { + "April", "Tam O'Shanter", "Emily", NULL +}; +const char *remarks[] = { + "Bubbly: I'm > Tam and <= Emily", + "Burns: \"When chapman billies leave the street ...\"", + "Short & shrift", NULL +}; + +int main() +{ + xmlDoc *doc = NULL; + xmlNode *root = NULL, *node; + const char **next; + int a; + + doc = xmlNewDoc("1.0"); + root = xmlNewNode(NULL, "CharacterRemarks"); + xmlDocSetRootElement(doc, root); + + for(next = names, a = 0; *next != NULL; next++, a++) { + node = xmlNewNode(NULL, "Character"); + (void)xmlNewProp(node, "name", *next); + xmlAddChild(node, xmlNewText(remarks[a])); + xmlAddChild(root, node); + } + + xmlElemDump(stdout, doc, root); + + xmlFreeDoc(doc); + xmlCleanupParser(); + + return EXIT_SUCCESS; +} diff --git a/Task/XML-Output/Clojure/xml-output.clj b/Task/XML-Output/Clojure/xml-output.clj new file mode 100644 index 0000000000..cabeb05e1d --- /dev/null +++ b/Task/XML-Output/Clojure/xml-output.clj @@ -0,0 +1,9 @@ +(use 'clojure.xml) +(defn character-remarks-xml [characters remarks] + (with-out-str (emit-element + {:tag :CharacterRemarks, + :attrs nil, + :content (vec (for [item (map vector characters remarks)] + {:tag :Character, + :attrs {:name (item 0)}, + :content [(item 1)]}) )}))) diff --git a/Task/XML-Output/Common-Lisp/xml-output-1.lisp b/Task/XML-Output/Common-Lisp/xml-output-1.lisp new file mode 100644 index 0000000000..20a484adf6 --- /dev/null +++ b/Task/XML-Output/Common-Lisp/xml-output-1.lisp @@ -0,0 +1,10 @@ +(defun write-xml (characters lines &optional (out *standard-output*)) + (let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil)) + (chars (dom:append-child doc (dom:create-element doc "Characters")))) + (map nil (lambda (character line) + (let ((c (dom:create-element doc "Character"))) + (dom:set-attribute c "name" character) + (dom:append-child c (dom:create-text-node doc line)) + (dom:append-child chars c))) + characters lines) + (write-string (dom:map-document (cxml:make-rod-sink) doc) out))) diff --git a/Task/XML-Output/Common-Lisp/xml-output-2.lisp b/Task/XML-Output/Common-Lisp/xml-output-2.lisp new file mode 100644 index 0000000000..2779d0ce03 --- /dev/null +++ b/Task/XML-Output/Common-Lisp/xml-output-2.lisp @@ -0,0 +1,4 @@ +(write-xml '("April" "Tam O'Shanter" "Emily") + '("Bubbly: I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ...\"" + "Short & shrift")) diff --git a/Task/XML-Output/D/xml-output.d b/Task/XML-Output/D/xml-output.d new file mode 100644 index 0000000000..c25f0c0724 --- /dev/null +++ b/Task/XML-Output/D/xml-output.d @@ -0,0 +1,18 @@ +import kxml.xml; +char[][][]characters = + [["April","Bubbly: I'm > Tam and <= Emily"], + ["Tam O'Shanter","Burns: \"When chapman billies leave the street ...\""], + ["Emily","Short & shrift"]]; +void addChars(XmlNode root,char[][][]info) { + auto remarks = new XmlNode("CharacterRemarks"); + root.addChild(remarks); + foreach(set;info) { + remarks.addChild((new XmlNode("Character")).setAttribute("name",set[0]).addCData(set[1])); + } +} +void main() { + auto root = new XmlNode(""); + root.addChild(new XmlPI("xml")); + addChars(root,characters); + std.stdio.writefln("%s",root.write); +} diff --git a/Task/XML-Output/Delphi/xml-output.delphi b/Task/XML-Output/Delphi/xml-output.delphi new file mode 100644 index 0000000000..9137e443bc --- /dev/null +++ b/Task/XML-Output/Delphi/xml-output.delphi @@ -0,0 +1,75 @@ +//You need to use these units +uses + Classes, + Dialogs, + XMLIntf, + XMLDoc; + +//.............................................. + +//This function creates the XML +function CreateXML(aNames, aRemarks: TStringList): string; +var + XMLDoc: IXMLDocument; + Root: IXMLNode; + i: Integer; +begin + //Input check + if (aNames = nil) or + (aRemarks = nil) then + begin + Result:= ''; + Exit; + end; + + //Creating the TXMLDocument instance + XMLDoc:= TXMLDocument.Create(nil); + + //Activating the document + XMLDoc.Active:= True; + + //Creating the Root element + Root:= XMLDoc.AddChild('CharacterRemarks'); + + //Creating the inner nodes + for i:=0 to Min(aNames.Count, aRemarks.Count) - 1 do + with Root.AddChild('Character') do + begin + Attributes['name']:= aNames[i]; + Text:= aRemarks[i]; + end; + + //Outputting the XML as a string + Result:= XMLDoc.XML.Text; +end; + +//.............................................. + +//Consuming code example (fragment) +var + Names, + Remarks: TStringList; +begin + //Creating the lists objects + Names:= TStringList.Create; + Remarks:= TStringList.Create; + try + //Filling the list with names + Names.Add('April'); + Names.Add('Tam O''Shanter'); + Names.Add('Emily'); + + //Filling the list with remarks + Remarks.Add('Bubbly: I''m > Tam and <= Emily'); + Remarks.Add('Burns: "When chapman billies leave the street ..."'); + Remarks.Add('Short & shrift'); + + //Constructing and showing the XML + Showmessage(CreateXML(Names, Remarks)); + + finally + //Freeing the list objects + Names.Free; + Remarks.Free; + end; +end; diff --git a/Task/XML-Output/Euphoria/xml-output-1.euphoria b/Task/XML-Output/Euphoria/xml-output-1.euphoria new file mode 100644 index 0000000000..6e3674c064 --- /dev/null +++ b/Task/XML-Output/Euphoria/xml-output-1.euphoria @@ -0,0 +1,34 @@ +function xmlquote(sequence s) + sequence r + r = "" + for i = 1 to length(s) do + if s[i] = '<' then + r &= "<" + elsif s[i] = '>' then + r &= ">" + elsif s[i] = '&' then + r &= "&" + elsif s[i] = '"' then + r &= """ + elsif s[i] = '\'' then + r &= "'" + else + r &= s[i] + end if + end for + return r +end function + +constant CharacterRemarks = { + {"April", "Bubbly: I'm > Tam and <= Emily"}, + {"Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""}, + {"Emily", "Short & shrift"} +} + +puts(1,"\n") +for i = 1 to length(CharacterRemarks) do + printf(1," ",{xmlquote(CharacterRemarks[i][1])}) + puts(1,xmlquote(CharacterRemarks[i][2])) + puts(1,"
\n") +end for +puts(1,"\n") diff --git a/Task/XML-Output/Euphoria/xml-output-2.euphoria b/Task/XML-Output/Euphoria/xml-output-2.euphoria new file mode 100644 index 0000000000..d9384feb46 --- /dev/null +++ b/Task/XML-Output/Euphoria/xml-output-2.euphoria @@ -0,0 +1,5 @@ + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + diff --git a/Task/XML-Output/Factor/xml-output-1.factor b/Task/XML-Output/Factor/xml-output-1.factor new file mode 100644 index 0000000000..0f2fd006b6 --- /dev/null +++ b/Task/XML-Output/Factor/xml-output-1.factor @@ -0,0 +1,5 @@ +USING: sequences xml.syntax xml.writer ; + +: print-character-remarks ( names remarks -- ) + [ [XML ><-> XML] ] 2map + [XML <-> XML] pprint-xml ; diff --git a/Task/XML-Output/Factor/xml-output-2.factor b/Task/XML-Output/Factor/xml-output-2.factor new file mode 100644 index 0000000000..aa24cb6d89 --- /dev/null +++ b/Task/XML-Output/Factor/xml-output-2.factor @@ -0,0 +1,5 @@ +{ "April" "Tam O'Shanter" "Emily" } { + "Bubbly: I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ...\"" + "Short & shrift" +} print-remarks diff --git a/Task/XML-Output/Fantom/xml-output.fantom b/Task/XML-Output/Fantom/xml-output.fantom new file mode 100644 index 0000000000..026a541661 --- /dev/null +++ b/Task/XML-Output/Fantom/xml-output.fantom @@ -0,0 +1,26 @@ +using xml + +class XmlOutput +{ + public static Void main () + { + Str[] names := ["April", "Tam O'Shanter", "Emily"] + Str[] remarks := ["Bubbly: I'm > Tam and <= Emily", + "Burns: \"When chapman billies leave the street ...\"", + "Short & shrift"] + + doc := XDoc() + root := XElem("CharacterRemarks") + doc.add (root) + + names.each |Str name, Int i| + { + child := XElem("Character") + child.addAttr("Name", name) + child.add(XText(remarks[i])) + root.add (child) + } + + doc.write(Env.cur.out) + } +} diff --git a/Task/XML-Output/Forth/xml-output.fth b/Task/XML-Output/Forth/xml-output.fth new file mode 100644 index 0000000000..4a2498f1cf --- /dev/null +++ b/Task/XML-Output/Forth/xml-output.fth @@ -0,0 +1,41 @@ +include ffl/est.fs +include ffl/xos.fs + +\ Input lists +0 value names +here ," Emily" +here ," Tam O'Shanter" +here ," April" +here to names +, , , + +0 value remarks +here ," Short & shrift" +here ,\" Burns: \"When chapman billies leave the street ...\"" +here ," Bubbly: I'm > Tam and <= Emily" +here to remarks +, , , + +: s++ ( c-addr1 -- c-addr2 c-addr3 u3 ) + dup cell+ swap @ count +; + +\ Create xml writer +tos-create xml + +: create-xml ( c-addr1 c-addr2 -- ) + 0 s" CharacterRemarks" xml xos-write-start-tag + 3 0 DO + swap s++ s" name" 2swap 1 + s" Character" xml xos-write-start-tag + swap s++ xml xos-write-text + s" Character" xml xos-write-end-tag + LOOP + drop drop + s" CharacterRemarks" xml xos-write-end-tag +; + +names remarks create-xml + +\ Output xml string +xml str-get type cr diff --git a/Task/XML-Output/Go/xml-output-1.go b/Task/XML-Output/Go/xml-output-1.go new file mode 100644 index 0000000000..9b1b798fdb --- /dev/null +++ b/Task/XML-Output/Go/xml-output-1.go @@ -0,0 +1,35 @@ +package main + +import ( + "encoding/xml" + "fmt" +) + +// Function required by task description. +func xRemarks(r CharacterRemarks) (string, error) { + b, err := xml.MarshalIndent(r, "", " ") + return string(b), err +} + +// Task description allows the function to take "a single mapping..." +// This data structure represents a mapping. +type CharacterRemarks struct { + Character []crm +} + +type crm struct { + Name string `xml:"name,attr"` + Remark string `xml:",chardata"` +} + +func main() { + x, err := xRemarks(CharacterRemarks{[]crm{ + {`April`, `Bubbly: I'm > Tam and <= Emily`}, + {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`}, + {`Emily`, `Short & shrift`}, + }}) + if err != nil { + x = err.Error() + } + fmt.Println(x) +} diff --git a/Task/XML-Output/Go/xml-output-2.go b/Task/XML-Output/Go/xml-output-2.go new file mode 100644 index 0000000000..dbc43a3d26 --- /dev/null +++ b/Task/XML-Output/Go/xml-output-2.go @@ -0,0 +1,5 @@ + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + diff --git a/Task/XML-Output/Go/xml-output-3.go b/Task/XML-Output/Go/xml-output-3.go new file mode 100644 index 0000000000..30a6a49bc3 --- /dev/null +++ b/Task/XML-Output/Go/xml-output-3.go @@ -0,0 +1,46 @@ +package main + +import ( + "bytes" + "encoding/xml" + "fmt" + "text/template" +) + +type crm struct { + Char, Rem string +} + +var tmpl = ` +{{range .}} {{xml .Rem}} +{{end}} +` + +func xmlEscapeString(s string) string { + var b bytes.Buffer + xml.Escape(&b, []byte(s)) + return b.String() +} + +func main() { + xt := template.New("").Funcs(template.FuncMap{"xml": xmlEscapeString}) + template.Must(xt.Parse(tmpl)) + + // Define function required by task description. + xRemarks := func(crms []crm) (string, error) { + var b bytes.Buffer + err := xt.Execute(&b, crms) + return b.String(), err + } + + // Call the function with example data. The data is represented as + // a "single mapping" as allowed by the task, rather than two lists. + x, err := xRemarks([]crm{ + {`April`, `Bubbly: I'm > Tam and <= Emily`}, + {`Tam O'Shanter`, `Burns: "When chapman billies leave the street ..."`}, + {`Emily`, `Short & shrift`}}) + if err != nil { + x = err.Error() + } + fmt.Println(x) +} diff --git a/Task/XML-Output/Groovy/xml-output.groovy b/Task/XML-Output/Groovy/xml-output.groovy new file mode 100644 index 0000000000..de12d6882c --- /dev/null +++ b/Task/XML-Output/Groovy/xml-output.groovy @@ -0,0 +1,10 @@ +def writer = new StringWriter() +def builder = new groovy.xml.MarkupBuilder(writer) +def names = ["April", "Tam O'Shanter", "Emily"] +def remarks = ["Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift"] + +builder.CharacterRemarks() { + names.eachWithIndex() { n, i -> Character(name:n, remarks[i]) }; +} + +println writer.toString() diff --git a/Task/XML-Output/Haskell/xml-output.hs b/Task/XML-Output/Haskell/xml-output.hs new file mode 100644 index 0000000000..58992abbc6 --- /dev/null +++ b/Task/XML-Output/Haskell/xml-output.hs @@ -0,0 +1,13 @@ +import Text.XML.Light + +characterRemarks :: [String] -> [String] -> String +characterRemarks names remarks = showElement $ Element + (unqual "CharacterRemarks") + [] + (zipWith character names remarks) + Nothing + where character name remark = Elem $ Element + (unqual "Character") + [Attr (unqual "name") name] + [Text $ CData CDataText remark Nothing] + Nothing diff --git a/Task/XML-Output/HicEst/xml-output.hicest b/Task/XML-Output/HicEst/xml-output.hicest new file mode 100644 index 0000000000..6f89e04fb7 --- /dev/null +++ b/Task/XML-Output/HicEst/xml-output.hicest @@ -0,0 +1,15 @@ +CHARACTER names="April~Tam O'Shanter~Emily~" +CHARACTER remarks*200/%Bubbly: I'm > Tam and <= Emily~Burns: "When chapman billies leave the street ..."~Short & shrift~%/ +CHARACTER XML*1000 + +EDIT(Text=remarks, Right='&', RePLaceby='&', DO) +EDIT(Text=remarks, Right='>', RePLaceby='>', DO) +EDIT(Text=remarks, Right='<', RePLaceby='<', DO) + +XML = "" // $CRLF +DO i = 1, 3 + EDIT(Text=names, SePaRators='~', ITeM=i, Parse=name) + EDIT(Text=remarks, SePaRators='~', ITeM=i, Parse=remark) + XML = TRIM(XML) // '' // remark // '' // $CRLF +ENDDO +XML = TRIM(XML) // "" diff --git a/Task/XML-Output/J/xml-output-1.j b/Task/XML-Output/J/xml-output-1.j new file mode 100644 index 0000000000..32ae4329e5 --- /dev/null +++ b/Task/XML-Output/J/xml-output-1.j @@ -0,0 +1,2 @@ +tbl=: ('"e;'; '&'; '<'; '>') (a.i.'"&<>')} <"0 a. +esc=: [:; {&tbl@:i.~&a. diff --git a/Task/XML-Output/J/xml-output-2.j b/Task/XML-Output/J/xml-output-2.j new file mode 100644 index 0000000000..1cfe83a7f3 --- /dev/null +++ b/Task/XML-Output/J/xml-output-2.j @@ -0,0 +1,3 @@ +cmb=: [:; dyad define &.> + '', (esc y), '', LF +) diff --git a/Task/XML-Output/J/xml-output-3.j b/Task/XML-Output/J/xml-output-3.j new file mode 100644 index 0000000000..4863d2f86a --- /dev/null +++ b/Task/XML-Output/J/xml-output-3.j @@ -0,0 +1 @@ +xmlify=: '', LF, cmb, ''"_ diff --git a/Task/XML-Output/J/xml-output-4.j b/Task/XML-Output/J/xml-output-4.j new file mode 100644 index 0000000000..03d6192ec1 --- /dev/null +++ b/Task/XML-Output/J/xml-output-4.j @@ -0,0 +1,7 @@ +names=: 'April'; 'Tam O''Shanter'; 'Emily' + +remarks=: <;._2]0 :0 + I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift +) diff --git a/Task/XML-Output/J/xml-output-5.j b/Task/XML-Output/J/xml-output-5.j new file mode 100644 index 0000000000..25adab91d4 --- /dev/null +++ b/Task/XML-Output/J/xml-output-5.j @@ -0,0 +1,6 @@ + names xmlify remarks + + I'm > Tam and <= Emily + Burns: "e;When chapman billies leave the street ..."e; + Short & shrift + diff --git a/Task/XML-Output/Java/xml-output-1.java b/Task/XML-Output/Java/xml-output-1.java new file mode 100644 index 0000000000..b7af776053 --- /dev/null +++ b/Task/XML-Output/Java/xml-output-1.java @@ -0,0 +1,61 @@ +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class XmlCreation { + + private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; + private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", + "Burns: \"When chapman billies leave the street ...\"", + "Short & shrift"}; + + public static void main(String[] args) { + try { + // Create a new XML document + final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + + // Append the root element + final Element root = doc.createElement("CharacterRemarks"); + doc.appendChild(root); + + // Read input data and create a new element for each name. + for(int i = 0; i < names.length; i++) { + final Element character = doc.createElement("Character"); + root.appendChild(character); + character.setAttribute("name", names[i]); + character.appendChild(doc.createTextNode(remarks[i])); + } + + // Serializing XML in Java is unnecessary complicated + // Create a Source from the document. + final Source source = new DOMSource(doc); + + // This StringWriter acts as a buffer + final StringWriter buffer = new StringWriter(); + + // Create a Result as a transformer target. + final Result result = new StreamResult(buffer); + + // The Transformer is used to copy the Source to the Result object. + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty("indent", "yes"); + transformer.transform(source, result); + + // Now the buffer is filled with the serialized XML and we can print it + // to the console. + System.out.println(buffer.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/Task/XML-Output/Java/xml-output-2.java b/Task/XML-Output/Java/xml-output-2.java new file mode 100644 index 0000000000..de5393b78a --- /dev/null +++ b/Task/XML-Output/Java/xml-output-2.java @@ -0,0 +1,5 @@ + + +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift diff --git a/Task/XML-Output/Java/xml-output-3.java b/Task/XML-Output/Java/xml-output-3.java new file mode 100644 index 0000000000..045c9c981a --- /dev/null +++ b/Task/XML-Output/Java/xml-output-3.java @@ -0,0 +1,38 @@ +import java.io.StringWriter; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; + +public class XmlCreationStax { + + private static final String[] names = {"April", "Tam O'Shanter", "Emily"}; + private static final String[] remarks = {"Bubbly: I'm > Tam and <= Emily", + "Burns: \"When chapman billies leave the street ...\"", + "Short & shrift"}; + + public static void main(String[] args) { + try { + final StringWriter buffer = new StringWriter(); + + final XMLStreamWriter out = XMLOutputFactory.newInstance() + .createXMLStreamWriter(buffer); + + out.writeStartDocument("UTF-8", "1.0"); + out.writeStartElement("CharacterRemarks"); + + for(int i = 0; i < names.length; i++) { + out.writeStartElement("Character"); + out.writeAttribute("name", names[i]); + out.writeCharacters(remarks[i]); + out.writeEndElement(); + } + + out.writeEndElement(); + out.writeEndDocument(); + + System.out.println(buffer); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/Task/XML-Output/Java/xml-output-4.java b/Task/XML-Output/Java/xml-output-4.java new file mode 100644 index 0000000000..74e3c06cbc --- /dev/null +++ b/Task/XML-Output/Java/xml-output-4.java @@ -0,0 +1 @@ +Bubbly: I'm > Tam and <= EmilyBurns: "When chapman billies leave the street ..."Short & shrift diff --git a/Task/XML-Output/Joy/xml-output.joy b/Task/XML-Output/Joy/xml-output.joy new file mode 100644 index 0000000000..d2fc9f2ac0 --- /dev/null +++ b/Task/XML-Output/Joy/xml-output.joy @@ -0,0 +1,15 @@ +DEFINE subst == +[[['< "<" putchars] + ['> ">" putchars] + ['& "&" putchars] + [putch]] case] step; + +XMLOutput == +"\n" putchars +[ "" putchars first subst "\n" putchars] step +"\n" putchars. + +[ [ "April" "Bubbly: I'm > Tam and <= Emily" ] + [ "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" ] + [ "Emily" "Short & shrift" ] +] XMLOutput. diff --git a/Task/XML-Output/Mathematica/xml-output.math b/Task/XML-Output/Mathematica/xml-output.math new file mode 100644 index 0000000000..da915b6aef --- /dev/null +++ b/Task/XML-Output/Mathematica/xml-output.math @@ -0,0 +1,9 @@ +c = {"April", "Tam O'Shanter","Emily"}; +r = {"Bubbly:I'm > Tam and <= Emily" , +StringReplace["Burns:\"When chapman billies leave the street ...\"", "\"" -> ""], "Short & shrift"}; + +ExportString[ XMLElement[ "CharacterRemarks", {}, +{XMLElement["Character", {"name" -> c[[1]]}, {r[[1]]}], + XMLElement["Character", {"name" -> c[[2]]}, {r[[2]]}], + XMLElement["Character", {"name" -> c[[3]]}, {r[[3]]}] +}], "XML", "AttributeQuoting" -> "\""] diff --git a/Task/XML-Output/NetRexx/xml-output-1.netrexx b/Task/XML-Output/NetRexx/xml-output-1.netrexx new file mode 100644 index 0000000000..caa566bcc4 --- /dev/null +++ b/Task/XML-Output/NetRexx/xml-output-1.netrexx @@ -0,0 +1,65 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols nobinary + +import java.io.StringWriter + +import javax.xml.parsers.DocumentBuilderFactory +import javax.xml.transform.Result +import javax.xml.transform.Source +import javax.xml.transform.Transformer +import javax.xml.transform.TransformerFactory +import javax.xml.transform.dom.DOMSource +import javax.xml.transform.stream.StreamResult + +import org.w3c.dom.Document +import org.w3c.dom.Element + +names = [String - + "April", "Tam O'Shanter", "Emily" - +] + +remarks = [ String - + "Bubbly: I'm > Tam and <= Emily" - + , 'Burns: "When chapman billies leave the street ..."' - + , 'Short & shrift' - +] + +do + -- Create a new XML document + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() + + -- Append the root element + root = doc.createElement("CharacterRemarks") + doc.appendChild(root) + + -- Read input data and create a new element for each name. + loop i_ = 0 to names.length - 1 + character = doc.createElement("Character") + root.appendChild(character) + character.setAttribute("name", names[i_]) + character.appendChild(doc.createTextNode(remarks[i_])) + end i_ + + -- Serializing XML in Java is unnecessary complicated + -- Create a Source from the document. + source = DOMSource(doc) + + -- This StringWriter acts as a buffer + buffer = StringWriter() + + -- Create a Result as a transformer target. + result = StreamResult(buffer) + + -- The Transformer is used to copy the Source to the Result object. + transformer = TransformerFactory.newInstance().newTransformer() + transformer.setOutputProperty("indent", "yes") + transformer.transform(source, result) + + -- Now the buffer is filled with the serialized XML and we can print it to the console. + say buffer.toString +catch ex = Exception + ex.printStackTrace +end + +return diff --git a/Task/XML-Output/NetRexx/xml-output-2.netrexx b/Task/XML-Output/NetRexx/xml-output-2.netrexx new file mode 100644 index 0000000000..209577cf0e --- /dev/null +++ b/Task/XML-Output/NetRexx/xml-output-2.netrexx @@ -0,0 +1,6 @@ + + +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift + diff --git a/Task/XML-Output/NetRexx/xml-output-3.netrexx b/Task/XML-Output/NetRexx/xml-output-3.netrexx new file mode 100644 index 0000000000..8adffcdac4 --- /dev/null +++ b/Task/XML-Output/NetRexx/xml-output-3.netrexx @@ -0,0 +1,48 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols nobinary + +import java.io.StringWriter + +import javax.xml.stream.XMLOutputFactory +import javax.xml.stream.XMLStreamWriter + +names = [String - + "April", "Tam O'Shanter", "Emily" - +] + +remarks = [ String - + "Bubbly: I'm > Tam and <= Emily" - + , 'Burns: "When chapman billies leave the street ..."' - + , 'Short & shrift' - +] + +do + buffer = StringWriter() + + out = XMLOutputFactory.newInstance().createXMLStreamWriter(buffer) + + out.writeStartDocument("UTF-8", "1.0") + out.writeCharacters('\n') + + out.writeStartElement("CharacterRemarks") + out.writeCharacters('\n') + + loop i_ = 0 to names.length - 1 + out.writeStartElement("Character") + out.writeAttribute("name", names[i_]) + out.writeCharacters(remarks[i_]) + out.writeEndElement() + out.writeCharacters('\n') + end i_ + + out.writeEndElement() + out.writeEndDocument() + out.writeCharacters('\n') + + say buffer.toString +catch ex = Exception + ex.printStackTrace +end + +return diff --git a/Task/XML-Output/NetRexx/xml-output-4.netrexx b/Task/XML-Output/NetRexx/xml-output-4.netrexx new file mode 100644 index 0000000000..1cd7b6c22d --- /dev/null +++ b/Task/XML-Output/NetRexx/xml-output-4.netrexx @@ -0,0 +1,6 @@ + + +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift + diff --git a/Task/XML-Output/OCaml/xml-output-1.ocaml b/Task/XML-Output/OCaml/xml-output-1.ocaml new file mode 100644 index 0000000000..b8505966d7 --- /dev/null +++ b/Task/XML-Output/OCaml/xml-output-1.ocaml @@ -0,0 +1,23 @@ +# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;; + +# #load "xml-light.cma" ;; + +# let data = [ + ("April", "Bubbly: I'm > Tam and <= Emily"); + ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""); + ("Emily", "Short & shrift"); + ] in + let tags = + List.map (fun (name, comment) -> + Xml.Element ("Character", [("name", name)], [(Xml.PCData comment)]) + ) data + in + print_endline ( + Xml.to_string_fmt (Xml.Element ("CharacterRemarks", [], tags))) + ;; + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + +- : unit = () diff --git a/Task/XML-Output/OCaml/xml-output-2.ocaml b/Task/XML-Output/OCaml/xml-output-2.ocaml new file mode 100644 index 0000000000..74ce3f74e0 --- /dev/null +++ b/Task/XML-Output/OCaml/xml-output-2.ocaml @@ -0,0 +1,22 @@ +#directory "+xmlm" +#load "xmlm.cmo" +open Xmlm + +let datas = [ + ("April", "Bubbly: I'm > Tam and <= Emily"); + ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""); + ("Emily", "Short & shrift"); + ] + +let xo = make_output (`Channel stdout) + +let () = + output xo (`Dtd None); + output xo (`El_start (("", "CharacterRemarks"), [])); + List.iter (fun (name, content) -> + output xo (`El_start (("", "Character"), [(("", "name"), name)])); + output xo (`Data content); + output xo (`El_end); + ) datas; + output xo (`El_end); + print_newline() diff --git a/Task/XML-Output/Objeck/xml-output.objeck b/Task/XML-Output/Objeck/xml-output.objeck new file mode 100644 index 0000000000..83e5c8dcc4 --- /dev/null +++ b/Task/XML-Output/Objeck/xml-output.objeck @@ -0,0 +1,31 @@ +use XML; +use Structure; + +bundle Default { + class Test { + function : Main(args : String[]) ~ Nil { + # list of name + names := Vector->New(); + names->AddBack("April"->As(Base)); + names->AddBack("Tam O'Shanter"->As(Base)); + names->AddBack("Emily"->As(Base)); + # list of comments + comments := Vector->New(); + comments->AddBack("Bubbly: I'm > Tam and <= Emily"->As(Base)); + comments->AddBack("Burns: \"When chapman billies leave the street ...\""->As(Base)); + comments->AddBack("Short & shrift"->As(Base)); + # build XML document + builder := XMLBuilder->New("CharacterRemarks"); + root := builder->GetRoot(); + if(names->Size() = comments->Size()) { + each(i : names) { + element := XMLElement->New(XMLElementType->ELEMENT, + names->Get(i)->As(String), + comments->Get(i)->As(String)); + root->AddChild(element); + }; + }; + XMLElement->DecodeString(builder->ToString())->PrintLine(); + } + } +} diff --git a/Task/XML-Output/Oz/xml-output-1.oz b/Task/XML-Output/Oz/xml-output-1.oz new file mode 100644 index 0000000000..0b9fafc970 --- /dev/null +++ b/Task/XML-Output/Oz/xml-output-1.oz @@ -0,0 +1,89 @@ +declare + proc {Main} + Names = ["April" + "Tam O'Shanter" + "Emily"] + + Remarks = ["Bubbly: I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ...\"" + "Short & shrift"] + + Characters = {List.zip Names Remarks + fun {$ N R} + 'Character'(name:N R) + end} + + DOM = {List.toTuple 'CharacterRemarks' Characters} + in + {System.showInfo {Serialize DOM}} + end + + fun {Serialize DOM} + "\n"# + {SerializeElement DOM 0} + end + + fun {SerializeElement El Indent} + Name = {Label El} + Attributes ChildElements Contents + {DestructureElement El ?Attributes ?ChildElements ?Contents} + EscContents = {Map Contents Escape} + Spaces = {List.make Indent} for S in Spaces do S = & end + in + Spaces#"<"#Name# + {VSConcatMap Attributes SerializeAttribute}#">"# + {VSConcat EscContents}#{When ChildElements\=nil "\n"}# + {VSConcatMap ChildElements fun {$ E} {SerializeElement E Indent+4} end}# + {When ChildElements\=nil Spaces}#"\n" + end + + proc {DestructureElement El ?Attrs ?ChildElements ?Contents} + SubelementRec AttributeRec + {Record.partitionInd El fun {$ I _} {Int.is I} end + ?SubelementRec ?AttributeRec} + Subelements = {Record.toList SubelementRec} + in + {List.partition Subelements VirtualString.is ?Contents ?ChildElements} + Attrs = {Record.toListInd AttributeRec} + end + + fun {SerializeAttribute Name#Value} + " "#Name#"=\""#{EscapeAttribute Value}#"\"" + end + + fun {Escape VS} + {Flatten {Map {VirtualString.toString VS} EscapeChar}} + end + + fun {EscapeAttribute VS} + {Flatten {Map {VirtualString.toString VS} EscapeAttributeChar}} + end + + fun {EscapeChar X} + case X of 60 then "<" + [] 62 then ">" + [] 38 then "&" + else X + end + end + + fun {EscapeAttributeChar X} + case X of 34 then """ + else {EscapeChar X} + end + end + + %% concatenates a list to a virtual string + fun {VSConcat Xs} + {List.toTuple '#' Xs} + end + + fun {VSConcatMap Xs F} + {VSConcat {Map Xs F}} + end + + fun {When Cond X} + if Cond then X else nil end + end +in + {Main} diff --git a/Task/XML-Output/Oz/xml-output-2.oz b/Task/XML-Output/Oz/xml-output-2.oz new file mode 100644 index 0000000000..b3367d8d86 --- /dev/null +++ b/Task/XML-Output/Oz/xml-output-2.oz @@ -0,0 +1,6 @@ + + + Bubbly: I'm > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + diff --git a/Task/XML-Output/Perl/xml-output.pl b/Task/XML-Output/Perl/xml-output.pl new file mode 100644 index 0000000000..1753e80e7a --- /dev/null +++ b/Task/XML-Output/Perl/xml-output.pl @@ -0,0 +1,19 @@ +#! /usr/bin/perl +use strict; +use XML::Mini::Document; + +my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ], + [ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ], + [ "Emily", "Short & shrift" ] + ); + +my $doc = XML::Mini::Document->new(); +my $root = $doc->getRoot(); +my $studs = $root->createChild("CharacterRemarks"); +foreach my $s (@students) +{ + my $stud = $studs->createChild("Character"); + $stud->attribute("name", $s->[0]); + $stud->text($s->[1]); +} +print $doc->toString(); diff --git a/Task/XML-Output/PicoLisp/xml-output.l b/Task/XML-Output/PicoLisp/xml-output.l new file mode 100644 index 0000000000..3f2d6f68ed --- /dev/null +++ b/Task/XML-Output/PicoLisp/xml-output.l @@ -0,0 +1,19 @@ +(load "@lib/xm.l") + +(de characterRemarks (Names Remarks) + (xml + (cons + 'CharacterRemarks + NIL + (mapcar + '((Name Remark) + (list 'Character (list (cons 'name Name)) Remark) ) + Names + Remarks ) ) ) ) + +(characterRemarks + '("April" "Tam O'Shanter" "Emily") + (quote + "I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ..." + "Short & shrift" ) ) diff --git a/Task/XML-Output/PureBasic/xml-output.purebasic b/Task/XML-Output/PureBasic/xml-output.purebasic new file mode 100644 index 0000000000..6feafa3b0a --- /dev/null +++ b/Task/XML-Output/PureBasic/xml-output.purebasic @@ -0,0 +1,34 @@ +Structure characteristic + name.s + remark.s +EndStructure +NewList didel.characteristic() +If ReadFile(0, GetCurrentDirectory()+"names.txt") + While Eof(0) = 0 + AddElement(didel()) + didel()\name = ReadString(0) + Wend + CloseFile(0) +EndIf +ResetList(didel()) +FirstElement(didel()) +If ReadFile(0, GetCurrentDirectory()+"remarks.txt") + While Eof(0) = 0 + didel()\remark = ReadString(0) + NextElement(didel()) + Wend + CloseFile(0) +EndIf +ResetList(didel()) +FirstElement(didel()) + xml = CreateXML(#PB_Any) + mainNode = CreateXMLNode(RootXMLNode(xml)) + SetXMLNodeName(mainNode, "CharacterRemarks") + ForEach didel() + item = CreateXMLNode(mainNode) + SetXMLNodeName(item, "Character") + SetXMLAttribute(item, "name", didel()\name) + SetXMLNodeText(item, didel()\remark) + Next + FormatXML(xml, #PB_XML_ReFormat | #PB_XML_WindowsNewline | #PB_XML_ReIndent) + SaveXML(xml, "demo.xml") diff --git a/Task/XML-Output/Python/xml-output-1.py b/Task/XML-Output/Python/xml-output-1.py new file mode 100644 index 0000000000..fdf1a574c8 --- /dev/null +++ b/Task/XML-Output/Python/xml-output-1.py @@ -0,0 +1,14 @@ +>>> from xml.etree import ElementTree as ET +>>> from itertools import izip +>>> def characterstoxml(names, remarks): + root = ET.Element("CharacterRemarks") + for name, remark in izip(names, remarks): + c = ET.SubElement(root, "Character", {'name': name}) + c.text = remark + return ET.tostring(root) + +>>> print characterstoxml( + names = ["April", "Tam O'Shanter", "Emily"], + remarks = [ "Bubbly: I'm > Tam and <= Emily", + 'Burns: "When chapman billies leave the street ..."', + 'Short & shrift' ] ).replace('><','>\n<') diff --git a/Task/XML-Output/Python/xml-output-2.py b/Task/XML-Output/Python/xml-output-2.py new file mode 100644 index 0000000000..8ee4694cf1 --- /dev/null +++ b/Task/XML-Output/Python/xml-output-2.py @@ -0,0 +1,5 @@ + +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift + diff --git a/Task/XML-Output/R/xml-output.r b/Task/XML-Output/R/xml-output.r new file mode 100644 index 0000000000..64f920b604 --- /dev/null +++ b/Task/XML-Output/R/xml-output.r @@ -0,0 +1,13 @@ +library(XML) +char2xml <- function(names, remarks){ + tt <- xmlHashTree() + head <- addNode(xmlNode("CharacterRemarks"), character(), tt) + node <- list() + for (i in 1:length(names)){ + node[[i]] <- addNode(xmlNode("Character", attrs=c(name=names[i])), head, tt) + addNode(xmlTextNode(remarks[i]), node[[i]], tt) + } + return(tt) +} +output <- char2xml( names=c("April","Tam O'Shanter","Emily"), +remarks=c("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift") ) diff --git a/Task/XML-Output/REXX/xml-output.rexx b/Task/XML-Output/REXX/xml-output.rexx new file mode 100644 index 0000000000..fe8dd3128b --- /dev/null +++ b/Task/XML-Output/REXX/xml-output.rexx @@ -0,0 +1,118 @@ +/*REXX program to create a list of character names & remarks. */ +charname.= +charname.1="April" +charname.2="Tam O'Shanter" +charname.3="Emily" + do i=1 while charname.i\=='' + say 'charname' i '=' charname.i + end /*i*/; say +remark.= +remark.1="I'm > Tam and <= Emily" +remark.2="When chapman billies leave the street ..." +remark.3="Short & shift" + do k=1 while remark.k\=='' + say ' remark' k '=' remark.k + end /*k*/; say +items=0 +header='CharacterRemarks' +header=header'>' + + do j=1 while charname.j\=='' + _=charname.j + if j==1 then call create '<'header + call create ' "' ||, + char2xml(remark.j)'"' + end /*j*/ + +if create.0\==0 then call create '',"gt") ; x=XML_('Æ',"AElig") ; x=XML_('╣',"boxVL") ; x=XML_('φ',"Phi") +x=XML_('?',"quest") ; x=XML_('Æ','#x00c6') ; x=XML_('║',"boxV") ; x=XML_('ε',"epsilon") +x=XML_('@',"commat") ; x=XML_('ô',"ocirc") ; x=XML_('╗',"boxDL") ; x=XML_('∩',"cap") +x=XML_('[',"lbrack") ; x=XML_('ô','#x00f4') ; x=XML_('╝',"boxUL") ; x=XML_('≡',"equiv") +x=XML_('\',"bsol") ; x=XML_('ö',"ouml") ; x=XML_('╜',"boxUl") ; x=XML_('±',"plusmn") +x=XML_(']',"rbrack") ; x=XML_('ö','#x00f6') ; x=XML_('╛',"boxuL") ; x=XML_('±',"pm") +x=XML_('^',"Hat") ; x=XML_('ò',"ograve") ; x=XML_('┐',"boxdl") ; x=XML_('±',"PlusMinus") +x=XML_('`',"grave") ; x=XML_('ò','#x00f2') ; x=XML_('└',"boxur") ; x=XML_('≥',"ge") +x=XML_('{',"lbrace") ; x=XML_('û',"ucirc") ; x=XML_('┴',"bottom"); x=XML_('≤',"le") +x=XML_('{',"lcub") ; x=XML_('û','#x00fb') ; x=XML_('┴',"boxhu") ; x=XML_('÷',"div") +x=XML_('|',"vert") ; x=XML_('ù',"ugrave") ; x=XML_('┬',"boxhd") ; x=XML_('÷',"divide") +x=XML_('|',"verbar") ; x=XML_('ù','#x00f9') ; x=XML_('├',"boxvr") ; x=XML_('≈',"approx") +x=XML_('}',"rbrace") ; x=XML_('ÿ',"yuml") ; x=XML_('─',"boxh") ; x=XML_('∙',"bull") +x=XML_('}',"rcub") ; x=XML_('ÿ','#x00ff') ; x=XML_('┼',"boxvh") ; x=XML_('°',"deg") +x=XML_('Ç',"Ccedil") ; x=XML_('Ö',"Ouml") ; x=XML_('╞',"boxvR") ; x=XML_('·',"middot") +x=XML_('Ç','#x00c7') ; x=XML_('Ö','#x00d6') ; x=XML_('╟',"boxVr") ; x=XML_('·',"middledot") +x=XML_('ü',"uuml") ; x=XML_('Ü',"Uuml") ; x=XML_('╚',"boxUR") ; x=XML_('·',"centerdot") +x=XML_('ü','#x00fc') ; x=XML_('Ü','#x00dc') ; x=XML_('╔',"boxDR") ; x=XML_('·',"CenterDot") +x=XML_('é',"eacute") ; x=XML_('¢',"cent") ; x=XML_('╩',"boxHU") ; x=XML_('√',"radic") +x=XML_('é','#x00e9') ; x=XML_('£',"pound") ; x=XML_('╦',"boxHD") ; x=XML_('²',"sup2") +x=XML_('â',"acirc") ; x=XML_('¥',"yen") ; x=XML_('╠',"boxVR") ; x=XML_('■',"squart ") + +if a then x=xml_(?,"amp") /*if we had an ampersand, translate it now.*/ +if b then x=xml_(??,"semi") /*if we had a semicolon, translate it now.*/ +return x diff --git a/Task/XML-Output/Racket/xml-output-1.rkt b/Task/XML-Output/Racket/xml-output-1.rkt new file mode 100644 index 0000000000..9c5f4659a3 --- /dev/null +++ b/Task/XML-Output/Racket/xml-output-1.rkt @@ -0,0 +1,16 @@ +#lang racket +(require xml) + +(define (make-character-xexpr characters remarks) + `(CharacterRemarks + ,@(for/list ([character characters] + [remark remarks]) + `(Character ((name ,character)) ,remark)))) + +(display-xml/content + (xexpr->xml + (make-character-xexpr + '("April" "Tam O'Shanter" "Emily") + '("Bubbly: I'm > Tam and <= Emily" + "Burns: \"When chapman billies leave the street ...\"" + "Short & shrift")))) diff --git a/Task/XML-Output/Racket/xml-output-2.rkt b/Task/XML-Output/Racket/xml-output-2.rkt new file mode 100644 index 0000000000..bce920d4c4 --- /dev/null +++ b/Task/XML-Output/Racket/xml-output-2.rkt @@ -0,0 +1,11 @@ + + + Bubbly: I'm > Tam and <= Emily + + + Burns: "When chapman billies leave the street ..." + + + Short & shrift + + diff --git a/Task/XML-Output/Rascal/xml-output-1.rascal b/Task/XML-Output/Rascal/xml-output-1.rascal new file mode 100644 index 0000000000..d7330c15f2 --- /dev/null +++ b/Task/XML-Output/Rascal/xml-output-1.rascal @@ -0,0 +1,16 @@ +import Prelude; +import lang::xml::DOM; + +list[str] charnames = ["April", "Tam O\'Shanter", "Emily"]; +list[str] remarks = ["Bubbly: I\'m \> Tam and \<= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"]; + +public void xmloutput(list[str] n,list[str] r){ + if(size(n) != size(r)){ + throw "n and r should be of the same size"; + } + else{ + characters = [element(none(),"Character",[attribute(none(),"name",n[i]), charData(r[i])]),charData("\n")| i <- [0..size(n)-1]]; + x = document(element(none(),"CharacterRemarks",characters)); + return println(xmlPretty(x)); + } +} diff --git a/Task/XML-Output/Rascal/xml-output-2.rascal b/Task/XML-Output/Rascal/xml-output-2.rascal new file mode 100644 index 0000000000..bef2b6b13a --- /dev/null +++ b/Task/XML-Output/Rascal/xml-output-2.rascal @@ -0,0 +1,10 @@ +rascal>xmloutput(charnames, remarks) + + + Bubbly: I'\m > Tam and <= Emily + Burns: "When chapman billies leave the street ..." + Short & shrift + + + +ok diff --git a/Task/XML-Output/Ruby/xml-output.rb b/Task/XML-Output/Ruby/xml-output.rb new file mode 100644 index 0000000000..71434687eb --- /dev/null +++ b/Task/XML-Output/Ruby/xml-output.rb @@ -0,0 +1,18 @@ +require 'rexml/document' +include REXML + +remarks = { + %q(April) => %q(Bubbly: I'm > Tam and <= Emily), + %q(Tam O'Shanter) => %q(Burns: "When chapman billies leave the street ..."), + %q(Emily) => %q(Short & shrift), +} + +doc = Document.new +root = doc.add_element("CharacterRemarks") + +remarks.each do |name, remark| + root.add_element("Character", {'Name' => name}).add_text(remark) +end + +# output with indentation +doc.write($stdout, 2) diff --git a/Task/XML-Output/Scala/xml-output-1.scala b/Task/XML-Output/Scala/xml-output-1.scala new file mode 100644 index 0000000000..a745a90fdd --- /dev/null +++ b/Task/XML-Output/Scala/xml-output-1.scala @@ -0,0 +1,10 @@ +val names = List("April", "Tam O'Shanter", "Emily") + +val remarks = List("Bubbly: I'm > Tam and <= Emily", """Burns: "When chapman billies leave the street ..."""", "Short & shrift") + +def characterRemarks(names: List[String], remarks: List[String]) = + { names zip remarks map { case (name, remark) => {remark} } } + + + +characterRemarks(names, remarks) diff --git a/Task/XML-Output/Scala/xml-output-2.scala b/Task/XML-Output/Scala/xml-output-2.scala new file mode 100644 index 0000000000..87f36299ac --- /dev/null +++ b/Task/XML-Output/Scala/xml-output-2.scala @@ -0,0 +1,4 @@ + + Bubbly: I'm > Tam and <= EmilyBurns: +"When chapman billies leave the street ..."Short & shrift + diff --git a/Task/XML-Output/Slate/xml-output.slate b/Task/XML-Output/Slate/xml-output.slate new file mode 100644 index 0000000000..f05bb4f52f --- /dev/null +++ b/Task/XML-Output/Slate/xml-output.slate @@ -0,0 +1,14 @@ +lobby define: #remarks -> ( +{'April' -> 'Bubbly: I\'m > Tam and <= Emily'. +'Tam O\'Shanter' -> 'Burns: "When chapman billies leave the street ..."'. +'Emily' -> 'Short & shrift'. +} as: Dictionary). + +define: #writer -> (Xml Writer newOn: '' new writer). +writer inTag: 'CharacterRemarks' do: + [| :w | + lobby remarks keysAndValuesDo: + [| :name :remark | w inTag: 'Character' do: [| :w | w ; remark] &attributes: {'name' -> name}]. + ]. + +inform: writer contents diff --git a/Task/XML-Output/TUSCRIPT/xml-output.tuscript b/Task/XML-Output/TUSCRIPT/xml-output.tuscript new file mode 100644 index 0000000000..5b84bb585b --- /dev/null +++ b/Task/XML-Output/TUSCRIPT/xml-output.tuscript @@ -0,0 +1,21 @@ +$$ MODE TUSCRIPT +STRUCTURE xmloutput +DATA '' +DATA * ' ' remarks +'' +DATA = '' +ENDSTRUCTURE +BUILD X_TABLE entitysubst=" >> > << < & & " +ERROR/STOP CREATE ("dest",seq-o,-std-) +ACCESS d: WRITE/ERASE/STRUCTURE "dest" num,str +str="xmloutput" + names=* + DATA April + DATA Tam O'Shanter + DATA Emily + remarks=* + DATA Bubbly: I'm > Tam and <= Emily + DATA Burns: "When chapman billies leave the street ..." + DATA Short & shrift + remarks=EXCHANGE(remarks,entitysubst) +WRITE/NEXT d +ENDACCESS d diff --git a/Task/XML-Output/Tcl/xml-output-1.tcl b/Task/XML-Output/Tcl/xml-output-1.tcl new file mode 100644 index 0000000000..65853e4a77 --- /dev/null +++ b/Task/XML-Output/Tcl/xml-output-1.tcl @@ -0,0 +1,28 @@ +proc xquote string { + list [string map "' ' \\\" " < > > < & &" $string] +} +proc < {name attl args} { + set res <$name + foreach {att val} $attl { + append res " $att='$val'" + } + if {[llength $args]} { + append res > + set sep "" + foreach a $args { + append res $sep $a + set sep \n + } + append res + } else {append res />} + return $res +} +set cmd {< CharacterRemarks {}} +foreach {name comment} { + April "Bubbly: I'm > Tam and <= Emily" + "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" + Emily "Short & shrift" +} { + append cmd " \[< Character {Name [xquote $name]} [xquote $comment]\]" +} +puts [eval $cmd] diff --git a/Task/XML-Output/Tcl/xml-output-2.tcl b/Task/XML-Output/Tcl/xml-output-2.tcl new file mode 100644 index 0000000000..0bfd3053a9 --- /dev/null +++ b/Task/XML-Output/Tcl/xml-output-2.tcl @@ -0,0 +1,13 @@ +package require tdom +set xml [dom createDocument CharacterRemarks] +foreach {name comment} { + April "Bubbly: I'm > Tam and <= Emily" + "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" + Emily "Short & shrift" +} { + set elem [$xml createElement Character] + $elem setAttribute name $name + $elem appendChild [$xml createTextNode $comment] + [$xml documentElement] appendChild $elem +} +$xml asXML diff --git a/Task/XML-Output/Tcl/xml-output-3.tcl b/Task/XML-Output/Tcl/xml-output-3.tcl new file mode 100644 index 0000000000..973c0eb4c7 --- /dev/null +++ b/Task/XML-Output/Tcl/xml-output-3.tcl @@ -0,0 +1,13 @@ +package require dom +set xml [dom::DOMImplementation create] +set root [dom::document createElement $xml CharacterRemarks] +foreach {name comment} { + April "Bubbly: I'm > Tam and <= Emily" + "Tam O'Shanter" "Burns: \"When chapman billies leave the street ...\"" + Emily "Short & shrift" +} { + set element [dom::document createElement $root Character] + dom::element setAttribute $element name $name + dom::document createTextNode $element $comment +} +dom::DOMImplementation serialize $xml -indent 1 diff --git a/Task/XML-Output/Vedit-macro-language/xml-output.vedit b/Task/XML-Output/Vedit-macro-language/xml-output.vedit new file mode 100644 index 0000000000..e80c7b8c64 --- /dev/null +++ b/Task/XML-Output/Vedit-macro-language/xml-output.vedit @@ -0,0 +1,18 @@ +// Replace special characters with entities: +Replace("&", "&", BEGIN+ALL+NOERR) // this must be the first replace! +Replace("<", "<", BEGIN+ALL+NOERR) +Replace(">", ">", BEGIN+ALL+NOERR) +Replace("'", "'", BEGIN+ALL+NOERR) +Replace('"', """, BEGIN+ALL+NOERR) + +// Insert XML marking +BOF +IT("") IN +Repeat(ALL) { + Search("^.", REGEXP+ERRBREAK) + IT(' ') + EOL IT('') +} +EOF +IT("") IN diff --git a/Task/XML-Output/Visual-Basic-.NET/xml-output.visual b/Task/XML-Output/Visual-Basic-.NET/xml-output.visual new file mode 100644 index 0000000000..f3186c5b30 --- /dev/null +++ b/Task/XML-Output/Visual-Basic-.NET/xml-output.visual @@ -0,0 +1,14 @@ +Module XMLOutput + Sub Main() + Dim charRemarks As New Dictionary(Of String, String) + charRemarks.Add("April", "Bubbly: I'm > Tam and <= Emily") + charRemarks.Add("Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""") + charRemarks.Add("Emily", "Short & shrift") + + Dim xml = + <%= From cr In charRemarks Select ><%= cr.Value %> %> + + + Console.WriteLine(xml) + End Sub +End Module diff --git a/Task/XML-Output/XPL0/xml-output.xpl0 b/Task/XML-Output/XPL0/xml-output.xpl0 new file mode 100644 index 0000000000..e004b88c94 --- /dev/null +++ b/Task/XML-Output/XPL0/xml-output.xpl0 @@ -0,0 +1,30 @@ +code ChOut=8, CrLf=9, Text=12; +string 0; \use zero-terminated strings + +proc XmlOut(S); \Output string in XML format +char S; +repeat case S(0) of \character entity substitutions + ^<: Text(0, "<"); + ^>: Text(0, ">"); + ^&: Text(0, "&"); + ^": Text(0, """); + ^': Text(0, "'") + other ChOut(0, S(0)); + S:= S+1; +until S(0) = 0; + +int Name, Remark, I; +[Name:= ["April", "Tam O'Shanter", "Emily"]; +Remark:= ["Bubbly: I'm > Tam and <= Emily", + "Burns: ^"When chapman billies leave the street ...^"", + "Short & shrift"]; +Text(0, ""); CrLf(0); +for I:= 0 to 3-1 do + [Text(0, " "); + XmlOut(Remark(I)); + Text(0, ""); CrLf(0); + ]; +Text(0, ""); CrLf(0); +] diff --git a/Task/XML-XPath/0DESCRIPTION b/Task/XML-XPath/0DESCRIPTION new file mode 100644 index 0000000000..eb0c177e4b --- /dev/null +++ b/Task/XML-XPath/0DESCRIPTION @@ -0,0 +1,32 @@ +Perform the following three XPath queries on the XML Document below: +* Retrieve the first "item" element +* Perform an action on each "price" element (print it out) +* Get an array of all the "name" elements + +XML Document: + +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
diff --git a/Task/XML-XPath/1META.yaml b/Task/XML-XPath/1META.yaml new file mode 100644 index 0000000000..d7f654b55d --- /dev/null +++ b/Task/XML-XPath/1META.yaml @@ -0,0 +1,2 @@ +--- +note: XML diff --git a/Task/XML-XPath/AppleScript/xml-xpath-1.applescript b/Task/XML-XPath/AppleScript/xml-xpath-1.applescript new file mode 100644 index 0000000000..3edd77d446 --- /dev/null +++ b/Task/XML-XPath/AppleScript/xml-xpath-1.applescript @@ -0,0 +1,61 @@ +set theXMLdata to " +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
" + +on getElementValuesByName(theXML, theNameToFind) + set R to {} + tell application "System Events" + repeat with i in theXML + set {theName, theElements} to {i's name, i's XML elements} + if (count of theElements) > 0 then set R to R & my getElementValuesByName(theElements, theNameToFind) + if theName = theNameToFind then set R to R & i's value + end repeat + end tell + return R +end getElementValuesByName + +on getBlock(theXML, theItem, theInstance) + set text item delimiters to "" + repeat with i from 1 to theInstance + set {R, blockStart, blockEnd} to {{}, "<" & theItem & space, ""} + set x to offset of blockStart in theXML + if x = 0 then exit repeat + set y to offset of blockEnd in (characters x thru -1 of theXML as string) + if y = 0 then exit repeat + set R to characters x thru (x + y + (length of blockEnd) - 2) of theXML as string + set theXML to characters (y + (length of blockEnd)) thru -1 of theXML as string + end repeat + return R +end getBlock + +tell application "System Events" + set xmlData to make new XML data with properties {name:"xmldata", text:theXMLdata} + + return my getBlock(xmlData's text, "item", 1) -- Solution to part 1 of problem. + return my getElementValuesByName(xmlData's contents, "name") -- Solution to part 2 of problem. + return my getElementValuesByName(xmlData's contents, "price") -- Solution to part 3 of problem. + +end tell diff --git a/Task/XML-XPath/AppleScript/xml-xpath-2.applescript b/Task/XML-XPath/AppleScript/xml-xpath-2.applescript new file mode 100644 index 0000000000..2fbf5bad18 --- /dev/null +++ b/Task/XML-XPath/AppleScript/xml-xpath-2.applescript @@ -0,0 +1,9 @@ +" + Invisibility Cream + 14.50 + Makes you invisible + " + +{"Invisibility Cream", "Levitation Salve", "Blork and Freen Instameal", "Grob winglets"} + +{"14.50", "23.99", "4.95", "3.56"} diff --git a/Task/XML-XPath/AutoHotkey/xml-xpath-1.ahk b/Task/XML-XPath/AutoHotkey/xml-xpath-1.ahk new file mode 100644 index 0000000000..ea68207910 --- /dev/null +++ b/Task/XML-XPath/AutoHotkey/xml-xpath-1.ahk @@ -0,0 +1,12 @@ +FileRead, inventory, xmlfile.xml + +RegExMatch(inventory, "", item1) +MsgBox % item1 + +pos = 1 +While, pos := RegExMatch(inventory, "(.*?)", price, pos + 1) + MsgBox % price1 + +While, pos := RegExMatch(inventory, ".*?", name, pos + 1) + names .= name . "`n" +MsgBox % names diff --git a/Task/XML-XPath/AutoHotkey/xml-xpath-2.ahk b/Task/XML-XPath/AutoHotkey/xml-xpath-2.ahk new file mode 100644 index 0000000000..2f15b462b4 --- /dev/null +++ b/Task/XML-XPath/AutoHotkey/xml-xpath-2.ahk @@ -0,0 +1,15 @@ +#Include xpath.ahk + +xpath_load(doc, "xmlfile.xml") + +; Retrieve the first "item" element +MsgBox % xpath(doc, "/inventory/section[1]/item[1]/text()") + +; Perform an action on each "price" element (print it out) +prices := xpath(doc, "/inventory/section/item/price/text()") +Loop, Parse, prices,`, + reordered .= A_LoopField "`n" +MsgBox % reordered + +; Get an array of all the "name" elements +MsgBox % xpath(doc, "/inventory/section/item/name") diff --git a/Task/XML-XPath/C++/xml-xpath.cpp b/Task/XML-XPath/C++/xml-xpath.cpp new file mode 100644 index 0000000000..e09c844b1b --- /dev/null +++ b/Task/XML-XPath/C++/xml-xpath.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include + +int main( ) { + const std::string xmltext( + "" + "
" + "" + "Invisibility Cream" + "14.50" + "Makes you invisible" + "" + "" + "Levitation Salve" + "23.99" + "Levitate yourself for up to 3 hours per application" + "" + "
" + "
" + "" + "Blork and Freen Instameal" + "4.95" + "A tasty meal in a tablet; just add water" + "" + "" + "Grob winglets" + "3.56" + "Tender winglets of Grob. Just add water" + "" + "
" + "
" ) ; + std::string::size_type found = xmltext.find( "" , found + 5 ) ; //and its end + std::cout << "The first item is\n" << xmltext.substr( found + 5 , foundnext - ( found + 5 ) ) << '\n' ; + std::string::const_iterator start , end ; + start = xmltext.begin( ) ; + end = xmltext.end( ) ; + boost::match_results what ; + boost::regex pricefind( "(\\d+\\.?\\d+)" ) ;//this regex finds the prices + start = xmltext.begin( ) ; + std::cout << "The prices are:\n" ; + while ( boost::regex_search( start , end , what , pricefind ) ) { + std::string price( what[ 1 ].first , what[ 1 ].second ) ;//find the first price + std::cout << price << std::endl ; + start = what[ 1 ].second ; //continue search after first price found + } + start = xmltext.begin( ) ; + std::vector names ; + boost::regex namefind( "(.+?)" ) ; //find characters, be greedy! + while ( boost::regex_search ( start , end , what , namefind ) ) { + std::string name ( what[ 1 ].first , what[ 1 ].second ) ; + names.push_back( name ) ; + start = what[ 1 ].second ; + } + std::cout << "The following name elements were found in the xml string:\n" ; + std::copy( names.begin( ) , names.end( ) , std::ostream_iterator( std::cout , "\n" )) ; + return 0 ; +} diff --git a/Task/XML-XPath/C-sharp/xml-xpath.cs b/Task/XML-XPath/C-sharp/xml-xpath.cs new file mode 100644 index 0000000000..418ac8bb2a --- /dev/null +++ b/Task/XML-XPath/C-sharp/xml-xpath.cs @@ -0,0 +1,42 @@ +XmlReader XReader; + +// Either read the xml from a string ... +XReader = XmlReader.Create(new StringReader("")); + +// ... or read it from the file system. +XReader = XmlReader.Create("xmlfile.xml"); + +// Create a XPathDocument object (which implements the IXPathNavigable interface) +// which is optimized for XPath operation. (very fast). +IXPathNavigable XDocument = new XPathDocument(XReader); + +// Create a Navigator to navigate through the document. +XPathNavigator Nav = XDocument.CreateNavigator(); +Nav = Nav.SelectSingleNode("//item"); + +// Move to the first element of the selection. (if available). +if(Nav.MoveToFirst()) +{ + Console.WriteLine(Nav.OuterXml); // The outer xml of the first item element. +} + +// Get an iterator to loop over multiple selected nodes. +XPathNodeIterator Iterator = XDocument.CreateNavigator().Select("//price"); + +while (Iterator.MoveNext()) +{ + Console.WriteLine(Iterator.Current.Value); +} + +Iterator = XDocument.CreateNavigator().Select("//name"); + +// Use a generic list. +List NodesValues = new List(); + +while (Iterator.MoveNext()) +{ + NodesValues.Add(Iterator.Current.Value); +} + +// Convert the generic list to an array and output the count of items. +Console.WriteLine(NodesValues.ToArray().Length); diff --git a/Task/XML-XPath/ColdFusion/xml-xpath.cfm b/Task/XML-XPath/ColdFusion/xml-xpath.cfm new file mode 100644 index 0000000000..b12d9e10b3 --- /dev/null +++ b/Task/XML-XPath/ColdFusion/xml-xpath.cfm @@ -0,0 +1,21 @@ + + + + + + + + + + + + + #priceSearch[i].xmlText#
+
+ + + + + diff --git a/Task/XML-XPath/Common-Lisp/xml-xpath.lisp b/Task/XML-XPath/Common-Lisp/xml-xpath.lisp new file mode 100644 index 0000000000..8232e53419 --- /dev/null +++ b/Task/XML-XPath/Common-Lisp/xml-xpath.lisp @@ -0,0 +1,15 @@ +(dolist (system '(:xpath :cxml-stp :cxml)) + (asdf:oos 'asdf:load-op system)) + +(defparameter *doc* (cxml:parse-file "xml" (stp:make-builder))) + +(xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*)) + +(xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*)) + (format t "~A~%" (stp:data node))) + +(defun node-array (node-set) + (coerce (xpath:all-nodes node-set) 'vector)) + +(node-array + (xpath:evaluate "/inventory/section/item/name" *doc*)) diff --git a/Task/XML-XPath/D/xml-xpath.d b/Task/XML-XPath/D/xml-xpath.d new file mode 100644 index 0000000000..e87e51e4b4 --- /dev/null +++ b/Task/XML-XPath/D/xml-xpath.d @@ -0,0 +1,37 @@ +import kxml.xml; +char[]xmlinput = +" +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
+"; +void main() { + auto root = readDocument(xmlinput); + auto firstitem = root.parseXPath("inventory/section/item")[0]; + foreach(price;root.parseXPath("inventory/section/item/price")) { + std.stdio.writefln("%s",price.getCData); + } + auto namearray = root.parseXPath("inventory/section/item/name"); +} diff --git a/Task/XML-XPath/Delphi/xml-xpath-1.delphi b/Task/XML-XPath/Delphi/xml-xpath-1.delphi new file mode 100644 index 0000000000..39057b74a1 --- /dev/null +++ b/Task/XML-XPath/Delphi/xml-xpath-1.delphi @@ -0,0 +1,65 @@ +program XMLXPath; + +{$APPTYPE CONSOLE} + +uses ActiveX, MSXML; + +const + XML = + '' + + '
' + + ' ' + + ' Invisibility Cream' + + ' 14.50' + + ' Makes you invisible' + + ' ' + + ' ' + + ' Levitation Salve' + + ' 23.99' + + ' Levitate yourself for up to 3 hours per application' + + ' ' + + '
' + + '
' + + ' ' + + ' Blork and Freen Instameal' + + ' 4.95' + + ' A tasty meal in a tablet; just add water' + + ' ' + + ' ' + + ' Grob winglets' + + ' 3.56' + + ' Tender winglets of Grob. Just add water' + + ' ' + + '
' + + '
'; + +var + i: Integer; + s: string; + lXMLDoc: IXMLDOMDocument2; + lNodeList: IXMLDOMNodeList; + lNode: IXMLDOMNode; + lItemNames: array of string; +begin + CoInitialize(nil); + lXMLDoc := CoDOMDocument.Create; + lXMLDoc.setProperty('SelectionLanguage', 'XPath'); + lXMLDoc.loadXML(XML); + + Writeln('First item node:'); + lNode := lXMLDoc.selectNodes('//item')[0]; + Writeln(lNode.xml); + Writeln(''); + + lNodeList := lXMLDoc.selectNodes('//price'); + for i := 0 to lNodeList.length - 1 do + Writeln('Price = ' + lNodeList[i].text); + Writeln(''); + + lNodeList := lXMLDoc.selectNodes('//item/name'); + SetLength(lItemNames, lNodeList.length); + for i := 0 to lNodeList.length - 1 do + lItemNames[i] := lNodeList[i].text; + for s in lItemNames do + Writeln('Item name = ' + s); +end. diff --git a/Task/XML-XPath/Delphi/xml-xpath-2.delphi b/Task/XML-XPath/Delphi/xml-xpath-2.delphi new file mode 100644 index 0000000000..d946a88994 --- /dev/null +++ b/Task/XML-XPath/Delphi/xml-xpath-2.delphi @@ -0,0 +1,16 @@ +First item node: + + Invisibility Cream + 14.50 + Makes you invisible + + +Price = 14.50 +Price = 23.99 +Price = 4.95 +Price = 3.56 + +Item name = Invisibility Cream +Item name = Levitation Salve +Item name = Blork and Freen Instameal +Item name = Grob winglets diff --git a/Task/XML-XPath/E/xml-xpath.e b/Task/XML-XPath/E/xml-xpath.e new file mode 100644 index 0000000000..3a9cc6fdb6 --- /dev/null +++ b/Task/XML-XPath/E/xml-xpath.e @@ -0,0 +1,50 @@ +? def xml__quasiParser := () +> def xpath__quasiParser := xml__quasiParser.xPathQuasiParser() +> null + +? def doc := xml` +>
+> +> Invisibility Cream +> 14.50 +> Makes you invisible +> +> +> Levitation Salve +> 23.99 +> Levitate yourself for up to 3 hours per applicationn> +> +>
+>
+> +> Blork and Freen Instameal +> 4.95 +> A tasty meal in a tablet; just add water +> +> +> Grob winglets +> 3.56 +> Tender winglets of Grob. Just add water +> +>
+>
` +# value: xml`...` + +? doc[xpath`inventory/section/item`][0] +# value: xml` +# Invisibility Cream +# 14.50 +# Makes you invisible +# ` + +? for price in doc[xpath`inventory/section/item/price/text()`] { println(price :String) } +14.50 +23.99 +4.95 +3.56 + +? doc[xpath`inventory/section/item/name`] +# value: [xml`Invisibility Cream`, +# xml`Levitation Salve`, +# xml`Blork and Freen Instameal`, +# xml`Grob winglets`] diff --git a/Task/XML-XPath/Groovy/xml-xpath.groovy b/Task/XML-XPath/Groovy/xml-xpath.groovy new file mode 100644 index 0000000000..434d70239e --- /dev/null +++ b/Task/XML-XPath/Groovy/xml-xpath.groovy @@ -0,0 +1,4 @@ +def inventory = new XmlSlurper().parseText(" Bool) -> [a] -> [a] +takeWhileIncl _ [] = [] +takeWhileIncl p (x:xs) + | p x = x : takeWhileIncl p xs + | otherwise = [x] + +getmultiLineItem n = takeWhileIncl(not.isInfixOf ("')). filter (isInfixOf ('<': n)) + +main = do + xml <- readFile "./Rosetta/xmlpath.xml" + let xmlText = lines xml + + putStrLn "\n== First item ==\n" + mapM_ putStrLn $ head $ unfoldr (Just. liftM2 (id &&&) (\\) (getmultiLineItem "item")) xmlText + + putStrLn "\n== Prices ==\n" + mapM_ putStrLn $ getsingleLineItems "price" xmlText + + putStrLn "\n== Names ==\n" + print $ getsingleLineItems "name" xmlText diff --git a/Task/XML-XPath/Haskell/xml-xpath-2.hs b/Task/XML-XPath/Haskell/xml-xpath-2.hs new file mode 100644 index 0000000000..e60db68196 --- /dev/null +++ b/Task/XML-XPath/Haskell/xml-xpath-2.hs @@ -0,0 +1,18 @@ +{-# LANGUAGE Arrows #-} +import Text.XML.HXT.Arrow +{- For HXT version >= 9.0, use instead: +import Text.XML.HXT.Core +-} + +deepElem name = deep (isElem >>> hasName name) + +process = proc doc -> do + item <- single (deepElem "item") -< doc + _ <- listA (arrIO print <<< deepElem "price") -< doc + names <- listA (deepElem "name") -< doc + returnA -< (item, names) + +main = do + [(item, names)] <- runX (readDocument [] "xmlpath.xml" >>> process) + print item + print names diff --git a/Task/XML-XPath/HicEst/xml-xpath-1.hicest b/Task/XML-XPath/HicEst/xml-xpath-1.hicest new file mode 100644 index 0000000000..e76dbf2550 --- /dev/null +++ b/Task/XML-XPath/HicEst/xml-xpath-1.hicest @@ -0,0 +1,15 @@ +CHARACTER xml*1000, output*1000 + READ(ClipBoard) xml + + EDIT(Text=xml, Right=' 0) THEN + WRITE(Text=output, APPend) 'Price element = ', price, $CRLF + GOTO 1 ! HicEst does not have a "WHILE" + ENDIF + + EDIT(Text=xml, SPR='<>', R='', W=1, WordEnd=$CR, APpendTo=output, DO=999) + WRITE(ClipBoard) TRIM(output) diff --git a/Task/XML-XPath/HicEst/xml-xpath-2.hicest b/Task/XML-XPath/HicEst/xml-xpath-2.hicest new file mode 100644 index 0000000000..d14f5b7783 --- /dev/null +++ b/Task/XML-XPath/HicEst/xml-xpath-2.hicest @@ -0,0 +1,13 @@ + upc="123456789" stock="12"> + Invisibility Cream + 14.50 + Makes you invisible + +Price element = 14.50 +Price element = 23.99 +Price element = 4.95 +Price element = 3.56 +Invisibility Cream + Levitation Salve + Blork and Freen Instameal + Grob winglets diff --git a/Task/XML-XPath/Java/xml-xpath.java b/Task/XML-XPath/Java/xml-xpath.java new file mode 100644 index 0000000000..07de11dcec --- /dev/null +++ b/Task/XML-XPath/Java/xml-xpath.java @@ -0,0 +1,60 @@ +import java.io.StringReader; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +public class XMLParser { + final static String xmlStr = + "" + + "
" + + " " + + " Invisibility Cream" + + " 14.50" + + " Makes you invisible" + + " " + + " " + + " Levitation Salve" + + " 23.99" + + " Levitate yourself for up to 3 hours per application" + + " " + + "
" + + "
" + + " " + + " Blork and Freen Instameal" + + " 4.95" + + " A tasty meal in a tablet; just add water" + + " " + + " " + + " Grob winglets" + + " 3.56" + + " Tender winglets of Grob. Just add priwater" + + " " + + "
" + + "
"; + + public static void main(String[] args) { + try { + Document doc = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(new InputSource(new StringReader(xmlStr))); + XPath xpath = XPathFactory.newInstance().newXPath(); + // 1 + System.out.println(((Node) xpath.evaluate( + "/inventory/section/item[1]", doc, XPathConstants.NODE)) + .getAttributes().getNamedItem("upc")); + // 2, 3 + NodeList nodes = (NodeList) xpath.evaluate( + "/inventory/section/item/price", doc, + XPathConstants.NODESET); + for (int i = 0; i < nodes.getLength(); i++) + System.out.println(nodes.item(i).getTextContent()); + } catch (Exception e) { + System.out.println("Error ocurred while parsing XML."); + } + } +} diff --git a/Task/XML-XPath/JavaScript/xml-xpath-1.js b/Task/XML-XPath/JavaScript/xml-xpath-1.js new file mode 100644 index 0000000000..99be975d19 --- /dev/null +++ b/Task/XML-XPath/JavaScript/xml-xpath-1.js @@ -0,0 +1,23 @@ +//create XMLDocument object from file +var xhr = new XMLHttpRequest(); +xhr.open('GET', 'file.xml', false); +xhr.send(null); +var doc = xhr.responseXML; + +//get first element +var firstItem = doc.evaluate( '//item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue; +alert( firstItem.textContent ); + +//output contents of elements +var prices = doc.evaluate( '//price', doc, null, XPathResult.ANY_TYPE, null ); +for( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) { + alert( price.textContent ); +} + +//add elements to array +var names = doc.evaluate( '//name', doc, null, XPathResult.ANY_TYPE, null); +var namesArray = []; +for( var name = names.iterateNext(); name != null; name = names.iterateNext() ) { + namesArray.push( name ); +} +alert( namesArray ); diff --git a/Task/XML-XPath/JavaScript/xml-xpath-2.js b/Task/XML-XPath/JavaScript/xml-xpath-2.js new file mode 100644 index 0000000000..4f2967affd --- /dev/null +++ b/Task/XML-XPath/JavaScript/xml-xpath-2.js @@ -0,0 +1,21 @@ +//create XML object from file +var xhr = new XMLHttpRequest(); +xhr.open('GET', 'file.xml', false); +xhr.send(null); +var doc = new XML(xhr.responseText); + +//get first element +var firstItem = doc..item[0]; +alert( firstItem ); + +//output contents of elements +for each( var price in doc..price ) { + alert( price ); +} + +//add elements to array +var names = []; +for each( var name in doc..name ) { + names.push( name ); +} +alert( names ); diff --git a/Task/XML-XPath/Lua/xml-xpath.lua b/Task/XML-XPath/Lua/xml-xpath.lua new file mode 100644 index 0000000000..f80ac500f8 --- /dev/null +++ b/Task/XML-XPath/Lua/xml-xpath.lua @@ -0,0 +1,44 @@ +require 'lxp' +data = [[ +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
]] +local first = true +local names, prices = {}, {} +p = lxp.new({StartElement = function (parser, name) + local a, b, c = parser:pos() --line, offset, pos + if name == 'item' and first then + print(data:match('.-
', c - b + 1)) + first = false + end + if name == 'name' then names[#names+1] = data:match('>(.-)<', c) end + if name == 'price' then prices[#prices+1] = data:match('>(.-)<', c) end +end}) + +p:parse(data) +p:close() + +print('Name: ', table.concat(names, ', ')) +print('Price: ', table.concat(prices, ', ')) diff --git a/Task/XML-XPath/Mathematica/xml-xpath.math b/Task/XML-XPath/Mathematica/xml-xpath.math new file mode 100644 index 0000000000..c04bddb0a3 --- /dev/null +++ b/Task/XML-XPath/Mathematica/xml-xpath.math @@ -0,0 +1,4 @@ +example = Import["test.txt", "XML"]; +Cases[example, XMLElement["item", _ , _] , Infinity] // First +Cases[example, XMLElement["price", _, List[n_]] -> n, Infinity] // Column +Cases[example, XMLElement["name", _, List[n_]] -> n, Infinity] // Column diff --git a/Task/XML-XPath/NetRexx/xml-xpath.netrexx b/Task/XML-XPath/NetRexx/xml-xpath.netrexx new file mode 100644 index 0000000000..81ca52e31c --- /dev/null +++ b/Task/XML-XPath/NetRexx/xml-xpath.netrexx @@ -0,0 +1,78 @@ +/* NetRexx */ +options replace format comments java crossref symbols binary + +import javax.xml.parsers. +import javax.xml.xpath. +import org.w3c.dom. +import org.xml.sax. + +xmlStr = '' - + || '' - + || '
' - + || ' ' - + || ' Invisibility Cream' - + || ' 14.50' - + || ' Makes you invisible' - + || ' ' - + || ' ' - + || ' Levitation Salve' - + || ' 23.99' - + || ' Levitate yourself for up to 3 hours per application' - + || ' ' - + || '
' - + || '
' - + || ' ' - + || ' Blork and Freen Instameal' - + || ' 4.95' - + || ' A tasty meal in a tablet; just add water' - + || ' ' - + || ' ' - + || ' Grob winglets' - + || ' 3.56' - + || ' Tender winglets of Grob. Just add priwater' - + || ' ' - + || '
' - + || '
' + +expr1 = '/inventory/section/item[1]' +expr2 = '/inventory/section/item/price' +expr3 = '/inventory/section/item/name' +attr1 = 'upc' + +do + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(xmlStr))) + xpath = XPathFactory.newInstance().newXPath() + + -- Extract attribute from 1st item element + say expr1 + say " "(Node xpath.evaluate(expr1, doc, XPathConstants.NODE)).getAttributes().getNamedItem(attr1) + say + + -- Extract and display all price elments + nodes = NodeList xpath.evaluate(expr2, doc, XPathConstants.NODESET) + say expr2 + loop i_ = 0 to nodes.getLength() - 1 + say Rexx(nodes.item(i_).getTextContent()).format(10, 2) + end i_ + say + + -- Extract elements and store in an ArrayList + nameList = java.util.List + nameList = ArrayList() + nodes = NodeList xpath.evaluate(expr3, doc, XPathConstants.NODESET) + loop i_ = 0 to nodes.getLength() - 1 + nameList.add(nodes.item(i_).getTextContent()) + end i_ + + -- display contents of ArrayList + say expr3 + loop n_ = 0 to nameList.size() - 1 + say " "nameList.get(n_) + end n_ + say + +catch ex = Exception + ex.printStackTrace() +end + +return diff --git a/Task/XML-XPath/Objeck/xml-xpath.objeck b/Task/XML-XPath/Objeck/xml-xpath.objeck new file mode 100644 index 0000000000..a92ef2a3da --- /dev/null +++ b/Task/XML-XPath/Objeck/xml-xpath.objeck @@ -0,0 +1,57 @@ +use XML; + +bundle Default { + class Test { + function : Main(args : String[]) ~ Nil { + in := String->New(); + in->Append(""); + in->Append("
"); + in->Append(""); + in->Append("Invisibility Cream"); + in->Append("14.50"); + in->Append("Makes you invisible"); + in->Append(""); + in->Append(""); + in->Append("Levitation Salve"); + in->Append("23.99"); + in->Append("Levitate yourself for up to 3 hours per application"); + in->Append(""); + in->Append("
"); + in->Append("
"); + in->Append(""); + in->Append("Blork and Freen Instameal"); + in->Append("4.95"); + in->Append("A tasty meal in a tablet; just add water"); + in->Append(""); + in->Append(""); + in->Append("Grob winglets"); + in->Append("3.56"); + in->Append("Tender winglets of Grob. Just add water"); + in->Append(""); + in->Append("
"); + in->Append("
"); + + parser := XmlParser->New(in); + if(parser->Parse()) { + # get first item + results := parser->FindElements("//inventory/section[1]/item[1]"); + if(results <> Nil) { + IO.Console->Instance()->Print("items: ")->PrintLine(results->Size()); + }; + # get all prices + results := parser->FindElements("//inventory/section/item/price"); + if(results <> Nil) { + each(i : results) { + element := results->Get(i)->As(XMLElement); + element->GetContent()->PrintLine(); + }; + }; + # get names + results := parser->FindElements("//inventory/section/item/name"); + if(results <> Nil) { + IO.Console->Instance()->Print("names: ")->PrintLine(results->Size()); + }; + }; + } + } +} diff --git a/Task/XML-XPath/Oz/xml-xpath.oz b/Task/XML-XPath/Oz/xml-xpath.oz new file mode 100644 index 0000000000..27705027d4 --- /dev/null +++ b/Task/XML-XPath/Oz/xml-xpath.oz @@ -0,0 +1,87 @@ +declare + [XMLParser] = {Module.link ['x-oz://system/xml/Parser.ozf']} + + proc {Main Data} + Parser = {New XMLParser.parser init} + [Doc] = {Parser parseVS(Data $)} + + FirstItem = {XPath Doc [inventory section item]}.1 + + Prices = {XPath Doc [inventory section item price Text]} + + Names = {XPath Doc [inventory section item name]} + in + {ForAll Prices System.showInfo} + end + + %% + %% Emulation of some XPath functionality: + %% + + fun {XPath Doc Path} + P|Pr = Path + in + Doc.name = P %% assert + {FoldL Pr XPathStep [Doc]} + end + + fun {XPathStep Elements P} + if {IsProcedure P} then + {Map Elements P} + else + {FilteredChildren Elements P} + end + end + + %% A flat list of all Type-children of all Elements. + fun {FilteredChildren Elements Type} + {Flatten + {Map Elements + fun {$ E} + {Filter E.children + fun {$ X} + case X of element(name:!Type ...) then true + else false + end + end} + end}} + end + + %% PCDATA of an element as a ByteString + fun {Text Element} + Texts = for Child in Element.children collect:C do + case Child of text(data:BS ...) then {C BS} end + end + in + {FoldR Texts ByteString.append {ByteString.make nil}} + end + + Data = + "" + #"
" + #" " + #" Invisibility Cream" + #" 14.50" + #" Makes you invisible" + #" " + #" " + #" Levitation Salve" + #" 23.99" + #" Levitate yourself for up to 3 hours per application" + #" " + #"
" + #"
" + #" " + #" Blork and Freen Instameal" + #" 4.95" + #" A tasty meal in a tablet; just add water" + #" " + #" " + #" Grob winglets" + #" 3.56" + #" Tender winglets of Grob. Just add water" + #" " + #"
" + #"
" +in + {Main Data} diff --git a/Task/XML-XPath/PHP/xml-xpath.php b/Task/XML-XPath/PHP/xml-xpath.php new file mode 100644 index 0000000000..328a5b697b --- /dev/null +++ b/Task/XML-XPath/PHP/xml-xpath.php @@ -0,0 +1,30 @@ +...
'); +//Load from file instead with $doc = DOMDocument::load('filename'); +$xpath = new DOMXPath($doc); +/* + 1st Task: Retrieve the first "item" element +*/ +$nodelist = $xpath->query('//item'); +$result = $nodelist->item(0); +/* + 2nd task: Perform an action on each "price" element (print it out) +*/ +$nodelist = $xpath->query('//price'); +for($i = 0; $i < $nodelist->length; $i++) +{ + //print each price element in the DOMNodeList instance, $nodelist, as text/xml followed by a newline + print $doc->saveXML($nodelist->item($i))."\n"; +} +/* + 3rd Task: Get an array of all the "name" elements +*/ +$nodelist = $xpath->query('//name'); +//our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList +$result = array(); +//a different way of iterating through the DOMNodeList +foreach($nodelist as $node) +{ + $result[] = $node; +} diff --git a/Task/XML-XPath/Perl/xml-xpath.pl b/Task/XML-XPath/Perl/xml-xpath.pl new file mode 100644 index 0000000000..4855589908 --- /dev/null +++ b/Task/XML-XPath/Perl/xml-xpath.pl @@ -0,0 +1,7 @@ +use XML::XPath qw(); + +my $x = XML::XPath->new(''); + +[$x->findnodes('//item[1]')->get_nodelist]->[0]; +print $x->findnodes_as_string('//price'); +$x->findnodes('//name')->get_nodelist; diff --git a/Task/XML-XPath/PicoLisp/xml-xpath.l b/Task/XML-XPath/PicoLisp/xml-xpath.l new file mode 100644 index 0000000000..6d2f21390e --- /dev/null +++ b/Task/XML-XPath/PicoLisp/xml-xpath.l @@ -0,0 +1,12 @@ +(load "@lib/xm.l") + +(let Sections (body (in "file.xml" (xml))) + (pretty (car (body (car Sections)))) + (prinl) + (for S Sections + (for L (body S) + (prinl (car (body L 'price))) ) ) + (make + (for S Sections + (for L (body S) + (link (car (body L 'name))) ) ) ) ) diff --git a/Task/XML-XPath/Python/xml-xpath.py b/Task/XML-XPath/Python/xml-xpath.py new file mode 100644 index 0000000000..bc3f6a71e1 --- /dev/null +++ b/Task/XML-XPath/Python/xml-xpath.py @@ -0,0 +1,18 @@ +# Python has basic xml parsing built in + +from xml.dom import minidom + +xmlfile = file("test3.xml") # load xml document from file +xmldoc = minidom.parse(xmlfile).documentElement # parse from file stream or... +xmldoc = minidom.parseString("...").documentElement # alternatively, parse a string + +# 1st Task: Retrieve the first "item" element +i = xmldoc.getElementsByTagName("item") # get a list of all "item" tags +firstItemElement = i[0] # get the first element + +# 2nd task: Perform an action on each "price" element (print it out) +for j in xmldoc.getElementsByTagName("price"): # get a list of all "price" tags + print j.childNodes[0].data # XML Element . TextNode . data of textnode + +# 3rd Task: Get an array of all the "name" elements +namesArray = xmldoc.getElementsByTagName("name") diff --git a/Task/XML-XPath/R/xml-xpath.r b/Task/XML-XPath/R/xml-xpath.r new file mode 100644 index 0000000000..2fd83af08e --- /dev/null +++ b/Task/XML-XPath/R/xml-xpath.r @@ -0,0 +1,10 @@ +## Require the XML package you can download from http://www.omegahat.org/RSXML/ +library("XML") +doc <- xmlInternalTreeParse("test3.xml") +# 1st Task: Retrieve the first "item" element +(firstItemElement <- getNodeSet(doc, "//item")[[1]]) +# 2nd task: Perform an action on each "price" element (print it out) +prices <- sapply(getNodeSet(doc, "//price"), xmlValue) +for(i in 1:length(prices)) print(prices[i]) +# 3rd Task: Get an array of all the "name" elements +(namesArray <- sapply(getNodeSet(doc, "//name"), xmlValue)) diff --git a/Task/XML-XPath/Rascal/xml-xpath-1.rascal b/Task/XML-XPath/Rascal/xml-xpath-1.rascal new file mode 100644 index 0000000000..72fb62abc4 --- /dev/null +++ b/Task/XML-XPath/Rascal/xml-xpath-1.rascal @@ -0,0 +1,23 @@ +import lang::xml::DOM; +import Prelude; + +public void get_first_item(loc a){ + D = parseXMLDOM(readFile(a)); + top-down-break visit(D){ + case E:element(_,"item",_): return println(xmlPretty(E)); + }; +} + +public void print_prices(loc a){ + D = parseXMLDOM(readFile(a)); + for(/element(_,"price",[charData(/str p)]) := D) + println(p); +} + +public list[str] get_names(loc a){ + D = parseXMLDOM(readFile(a)); + L = []; + for(/element(_,"name",[charData(/str n)]) := D) + L += n; + return L; +} diff --git a/Task/XML-XPath/Rascal/xml-xpath-2.rascal b/Task/XML-XPath/Rascal/xml-xpath-2.rascal new file mode 100644 index 0000000000..acde243828 --- /dev/null +++ b/Task/XML-XPath/Rascal/xml-xpath-2.rascal @@ -0,0 +1,20 @@ +rascal>get_first_item(|file:///Users/.../Desktop/xmlpath.xml|) + + + Invisibility Cream + 14.50 + Makes you invisible + + + +ok + +rascal>print_prices(|file:///Users/.../Desktop/xmlpath.xml|) +14.50 +23.99 +4.95 +3.56 +ok + +rascal>get_names(|file:///Users/.../Desktop/xmlpath.xml|) +list[str]: ["Invisibility Cream","Levitation Salve","Blork and Freen Instameal","Grob winglets"] diff --git a/Task/XML-XPath/Ruby/xml-xpath.rb b/Task/XML-XPath/Ruby/xml-xpath.rb new file mode 100644 index 0000000000..95d4951216 --- /dev/null +++ b/Task/XML-XPath/Ruby/xml-xpath.rb @@ -0,0 +1,16 @@ +#Example taken from the REXML tutorial (http://www.germane-software.com/software/rexml/docs/tutorial.html) +require "rexml/document" +include REXML +#create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string) +doc = Document.new( + %q@ + ... + + @ + ) +# The invisibility cream is the first +invisibility = XPath.first( doc, "//item" ) +# Prints out all of the prices +XPath.each( doc, "//price") { |element| puts element.text } +# Gets an array of all of the "name" elements in the document. +names = XPath.match( doc, "//name" ) diff --git a/Task/XML-XPath/Scala/xml-xpath.scala b/Task/XML-XPath/Scala/xml-xpath.scala new file mode 100644 index 0000000000..338ab34978 --- /dev/null +++ b/Task/XML-XPath/Scala/xml-xpath.scala @@ -0,0 +1,80 @@ +scala> val xml = + |
+ | + | Invisibility Cream + | 14.50 + | Makes you invisible + | + | + | Levitation Salve + | 23.99 + | Levitate yourself for up to 3 hours per application + | + |
+ |
+ | + | Blork and Freen Instameal + | 4.95 + | A tasty meal in a tablet; just add water + | + | + | Grob winglets + | 3.56 + | Tender winglets of Grob. Just add water + | + |
+ |
+xml: scala.xml.Elem = + +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
+ +scala> val firstItem = xml \\ "item" head +firstItem: scala.xml.Node = + + Invisibility Cream + 14.50 + Makes you invisible + + +scala> xml \\ "price" foreach println +14.50 +23.99 +4.95 +3.56 + +scala> xml \\ "price" map (_ text) foreach println +14.50 +23.99 +4.95 +3.56 + +scala> val elements = xml \\ "name" toArray +elements: Array[scala.xml.Node] = Array(Invisibility Cream, Levitation Salve, Blork and +Freen Instameal, Grob winglets) + +scala> val values = xml \\ "name" map (_ text) toArray +values: Array[String] = Array(Invisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets) diff --git a/Task/XML-XPath/TUSCRIPT/xml-xpath.tuscript b/Task/XML-XPath/TUSCRIPT/xml-xpath.tuscript new file mode 100644 index 0000000000..f6dc5ad20d --- /dev/null +++ b/Task/XML-XPath/TUSCRIPT/xml-xpath.tuscript @@ -0,0 +1,62 @@ +$$ MODE TUSCRIPT,{} +MODE DATA +$$ XML=* + +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
+$$ MODE TUSCRIPT + +FILE = "test.xml" +ERROR/STOP CREATE (file,fdf-o,-std-) +FILE/ERASE/UTF8 $FILE = xml + +BUILD S_TABLE beg="::::" +BUILD S_TABLE end=":
:::" +BUILD S_TABLE modifiedbeg=":::" +BUILD S_TABLE modifiedend=":::" +firstitem=names="",countitem=0 +ACCESS q: READ/STREAM/UTF8 $FILE s,a/beg+t+e/end +LOOP +READ/EXIT q +IF (a=="") names=APPEND(names,t) +IF (a=="") PRINT t +IF (a.sw."") THEN + COUNTITEM=0 + MODIFY ACCESS q s_TABLE modifiedbeg,-,modifiedend + ENDIF +ENDIF +ENDLOOP +ENDACCESS q +ERROR/STOP CLOSE (file) +firstitem=EXCHANGE (firstitem,":{2-00} ::") +firstitem=INDENT_TAGS (firstitem,-," ") +names=SPLIT(names) +TRACE *firstitem,names diff --git a/Task/XML-XPath/Tcl/xml-xpath.tcl b/Task/XML-XPath/Tcl/xml-xpath.tcl new file mode 100644 index 0000000000..1871b3fb6b --- /dev/null +++ b/Task/XML-XPath/Tcl/xml-xpath.tcl @@ -0,0 +1,14 @@ +# assume $xml holds the XML data +package require tdom +set doc [dom parse $xml] +set root [$doc documentElement] + +set allNames [$root selectNodes //name] +puts [llength $allNames] ;# ==> 4 + +set firstItem [lindex [$root selectNodes //item] 0] +puts [$firstItem @upc] ;# ==> 123456789 + +foreach node [$root selectNodes //price] { + puts [$node text] +} diff --git a/Task/XML-XPath/Visual-Basic-.NET/xml-xpath.visual b/Task/XML-XPath/Visual-Basic-.NET/xml-xpath.visual new file mode 100644 index 0000000000..e1002962a9 --- /dev/null +++ b/Task/XML-XPath/Visual-Basic-.NET/xml-xpath.visual @@ -0,0 +1,8 @@ +Dim first_item = xml.XPathSelectElement("//item") +Console.WriteLine(first_item) + +For Each price In xml.XPathSelectElements("//price") + Console.WriteLine(price.Value) +Next + +Dim names = (From item In xml.XPathSelectElements("//name") Select item.Value).ToArray diff --git a/Task/XML-XPath/XProc/xml-xpath.xproc b/Task/XML-XPath/XProc/xml-xpath.xproc new file mode 100644 index 0000000000..edc35cffed --- /dev/null +++ b/Task/XML-XPath/XProc/xml-xpath.xproc @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/XML-XPath/XQuery/xml-xpath-1.xquery b/Task/XML-XPath/XQuery/xml-xpath-1.xquery new file mode 100644 index 0000000000..1675b2182e --- /dev/null +++ b/Task/XML-XPath/XQuery/xml-xpath-1.xquery @@ -0,0 +1,19 @@ +(: + 1. Retrieve the first "item" element + Notice the braces around //item. This evaluates first all item elements and then retrieving the first one. + Whithout the braces you get the first item for every section. +:) +let $firstItem := (//item)[1] + +(: 2. Perform an action on each "price" element (print it out) :) +let $price := //price/data(.) + +(: 3. Get an array of all the "name" elements :) +let $names := //name + +return + + {$firstItem} + {$price} + {$names} + diff --git a/Task/XML-XPath/XQuery/xml-xpath-2.xquery b/Task/XML-XPath/XQuery/xml-xpath-2.xquery new file mode 100644 index 0000000000..74bf4bd5c2 --- /dev/null +++ b/Task/XML-XPath/XQuery/xml-xpath-2.xquery @@ -0,0 +1,17 @@ + + + + + Invisibility Cream + 14.50 + Makes you invisible + + + 14.50 23.99 4.95 3.56 + + Invisibility Cream + Levitation Salve + Blork and Freen Instameal + Grob winglets + + diff --git a/Task/XML-XPath/XSLT/xml-xpath.xslt b/Task/XML-XPath/XSLT/xml-xpath.xslt new file mode 100644 index 0000000000..93e4bbdc96 --- /dev/null +++ b/Task/XML-XPath/XSLT/xml-xpath.xslt @@ -0,0 +1,24 @@ + + + + + + +The first item element is + + + + +The prices are: + + + + + + + + +The names are: + + + diff --git a/Task/Xiaolin-Wus-line-algorithm/0DESCRIPTION b/Task/Xiaolin-Wus-line-algorithm/0DESCRIPTION new file mode 100644 index 0000000000..def095b152 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/0DESCRIPTION @@ -0,0 +1 @@ +Implement the [[wp:Xiaolin Wu's line algorithm|Xiaolin Wu's line algorithm]] as described in Wikipedia. This algorithm draw antialiased lines. See [[Bresenham's line algorithm]] for ''aliased'' lines. diff --git a/Task/Xiaolin-Wus-line-algorithm/1META.yaml b/Task/Xiaolin-Wus-line-algorithm/1META.yaml new file mode 100644 index 0000000000..c4801aa5b2 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Graphics algorithms +note: Raster graphics operations diff --git a/Task/Xiaolin-Wus-line-algorithm/BBC-BASIC/xiaolin-wus-line-algorithm.bbc b/Task/Xiaolin-Wus-line-algorithm/BBC-BASIC/xiaolin-wus-line-algorithm.bbc new file mode 100644 index 0000000000..6e526f5900 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/BBC-BASIC/xiaolin-wus-line-algorithm.bbc @@ -0,0 +1,54 @@ + PROCdrawAntiAliasedLine(100, 100, 600, 400, 0, 0, 0) + END + + DEF PROCdrawAntiAliasedLine(x1, y1, x2, y2, r%, g%, b%) + LOCAL dx, dy, xend, yend, grad, yf, xgap, ix1%, iy1%, ix2%, iy2%, x% + + dx = x2 - x1 + dy = y2 - y1 + IF ABS(dx) < ABS(dy) THEN + SWAP x1, y1 + SWAP x2, y2 + SWAP dx, dy + ENDIF + + IF x2 < x1 THEN + SWAP x1, x2 + SWAP y1, y2 + ENDIF + + grad = dy / dx + + xend = INT(x1 + 0.5) + yend = y1 + grad * (xend - x1) + xgap = xend + 0.5 - x1 + ix1% = xend + iy1% = INT(yend) + PROCplot(ix1%, iy1%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap) + PROCplot(ix1%, iy1% + 1, r%, b%, g%, (yend - INT(yend)) * xgap) + yf = yend + grad + + xend = INT(x2 + 0.5) + yend = y2 + grad * (xend - x2) + xgap = x2 + 0.5 - xend + ix2% = xend + iy2% = INT(yend) + PROCplot(ix2%, iy2%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap) + PROCplot(ix2%, iy2% + 1, r%, b%, g%, (yend - INT(yend)) * xgap) + + FOR x% = ix1% + 1 TO ix2% - 1 + PROCplot(x%, INT(yf), r%, b%, g%, INT(yf) + 1 - yf) + PROCplot(x%, INT(yf) + 1, r%, b%, g%, yf - INT(yf)) + yf += grad + NEXT + ENDPROC + + DEF PROCplot(X%, Y%, R%, G%, B%, a) + LOCAL C% + C% = TINT(X%*2,Y%*2) + COLOUR 1, R%*a + (C% AND 255)*(1-a), \ + \ G%*a + (C% >> 8 AND 255)*(1-a), \ + \ B%*a + (C% >> 16 AND 255)*(1-a) + GCOL 1 + LINE X%*2, Y%*2, X%*2, Y%*2 + ENDPROC diff --git a/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-1.c b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-1.c new file mode 100644 index 0000000000..d272711123 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-1.c @@ -0,0 +1,7 @@ +void draw_line_antialias( + image img, + unsigned int x0, unsigned int y0, + unsigned int x1, unsigned int y1, + color_component r, + color_component g, + color_component b ); diff --git a/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c new file mode 100644 index 0000000000..b62b6488be --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c @@ -0,0 +1,103 @@ +inline void _dla_changebrightness(rgb_color_p from, + rgb_color_p to, float br) +{ + if ( br > 1.0 ) br = 1.0; + /* linear... Maybe something more complex could give better look */ + to->red = br * (float)from->red; + to->green = br * (float)from->green; + to->blue = br * (float)from->blue; +} + +#define plot_(X,Y,D) do{ rgb_color f_; \ + f_.red = r; f_.green = g; f_.blue = b; \ + _dla_plot(img, (X), (Y), &f_, (D)) ; }while(0) + +inline void _dla_plot(image img, int x, int y, rgb_color_p col, float br) +{ + rgb_color oc; + _dla_changebrightness(col, &oc, br); + put_pixel_clip(img, x, y, oc.red, oc.green, oc.blue); +} + +#define ipart_(X) ((int)(X)) +#define round_(X) ((int)(((double)(X))+0.5)) +#define fpart_(X) (((double)(X))-(double)ipart_(X)) +#define rfpart_(X) (1.0-fpart_(X)) + +#define swap_(a, b) do{ __typeof__(a) tmp; tmp = a; a = b; b = tmp; }while(0) +void draw_line_antialias( + image img, + unsigned int x1, unsigned int y1, + unsigned int x2, unsigned int y2, + color_component r, + color_component g, + color_component b ) +{ + double dx = (double)x2 - (double)x1; + double dy = (double)y2 - (double)y1; + if ( fabs(dx) > fabs(dy) ) { + if ( x2 < x1 ) { + swap_(x1, x2); + swap_(y1, y2); + } + double gradient = dy / dx; + double xend = round_(x1); + double yend = y1 + gradient*(xend - x1); + double xgap = rfpart_(x1 + 0.5); + int xpxl1 = xend; + int ypxl1 = ipart_(yend); + plot_(xpxl1, ypxl1, rfpart_(yend)*xgap); + plot_(xpxl1, ypxl1+1, fpart_(yend)*xgap); + double intery = yend + gradient; + + xend = round_(x2); + yend = y2 + gradient*(xend - x2); + xgap = fpart_(x2+0.5); + int xpxl2 = xend; + int ypxl2 = ipart_(yend); + plot_(xpxl2, ypxl2, rfpart_(yend) * xgap); + plot_(xpxl2, ypxl2 + 1, fpart_(yend) * xgap); + + int x; + for(x=xpxl1+1; x <= (xpxl2-1); x++) { + plot_(x, ipart_(intery), rfpart_(intery)); + plot_(x, ipart_(intery) + 1, fpart_(intery)); + intery += gradient; + } + } else { + if ( y2 < y1 ) { + swap_(x1, x2); + swap_(y1, y2); + } + double gradient = dx / dy; + double yend = round_(y1); + double xend = x1 + gradient*(yend - y1); + double ygap = rfpart_(y1 + 0.5); + int ypxl1 = yend; + int xpxl1 = ipart_(xend); + plot_(xpxl1, ypxl1, rfpart_(xend)*ygap); + plot_(xpxl1, ypxl1+1, fpart_(xend)*ygap); + double interx = xend + gradient; + + yend = round_(y2); + xend = x2 + gradient*(yend - y2); + ygap = fpart_(y2+0.5); + int ypxl2 = yend; + int xpxl2 = ipart_(xend); + plot_(xpxl2, ypxl2, rfpart_(xend) * ygap); + plot_(xpxl2, ypxl2 + 1, fpart_(xend) * ygap); + + int y; + for(y=ypxl1+1; y <= (ypxl2-1); y++) { + plot_(ipart_(interx), y, rfpart_(interx)); + plot_(ipart_(interx) + 1, y, fpart_(interx)); + interx += gradient; + } + } +} +#undef swap_ +#undef plot_ +#undef ipart_ +#undef fpart_ +#undef round_ +#undef rfpart_ diff --git a/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d b/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d new file mode 100644 index 0000000000..9e540abf68 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/D/xiaolin-wus-line-algorithm.d @@ -0,0 +1,103 @@ +import std.math, std.algorithm, grayscale_image; + +/// Plots anti-aliased line by Xiaolin Wu's line algorithm. +void aaLine(Color)(ref Image!Color img, double x1, double y1, + double x2, double y2, + in Color color) +/*pure*/ nothrow { + // Straight translation of Wikipedia pseudocode. + static double round(in double x) /*pure*/ nothrow { + return floor(x + 0.5); // Not pure. + } + + static double fpart(in double x) /*pure*/ nothrow { + return x - floor(x); + } + + static double rfpart(in double x) /*pure*/ nothrow { + return 1 - fpart(x); + } + + auto dx = x2 - x1; + auto dy = y2 - y1; + immutable ax = abs(dx); + immutable ay = abs(dy); + + static Color mixColors(in Color c1, in Color c2, in double p) + pure nothrow { + static if (is(Color == RGB)) + return Color(cast(ubyte)(c1.r * p + c2.r * (1 - p)), + cast(ubyte)(c1.g * p + c2.g * (1 - p)), + cast(ubyte)(c1.b * p + c2.b * (1 - p))); + else + // This doesn't work for every kind of Color. + return Color(cast(ubyte)(c1 * p + c2 * (1 - p))); + } + + // Plot function set here to handle the two cases of slope. + void delegate(in int, in int, in double) nothrow plot; + if (ax < ay) { + swap(x1, y1); + swap(x2, y2); + swap(dx, dy); + plot = (x, y, p) { + assert(p >= 0.0 && p <= 1.0); + img[y, x] = mixColors(color, img[y, x], p); + }; + } else { + plot = (x, y, p) { + assert(p >= 0.0 && p <= 1.0); + img[x, y] = mixColors(color, img[x, y], p); + }; + } + + if (x2 < x1) { + swap(x1, x2); + swap(y1, y2); + } + immutable gradient = dy / dx; + + // Handle first endpoint. + auto xEnd = round(x1); + auto yEnd = y1 + gradient * (xEnd - x1); + auto xGap = rfpart(x1 + 0.5); + // This will be used in the main loop. + immutable xpxl1 = cast(int)xEnd; + immutable ypxl1 = cast(int)floor(yEnd); + plot(xpxl1, ypxl1, rfpart(yEnd) * xGap); + plot(xpxl1, ypxl1 + 1, fpart(yEnd) * xGap); + // First y-intersection for the main loop. + auto yInter = yEnd + gradient; + + // Handle second endpoint. + xEnd = round(x2); + yEnd = y2 + gradient * (xEnd - x2); + xGap = fpart(x2 + 0.5); + // This will be used in the main loop. + immutable xpxl2 = cast(int)xEnd; + immutable ypxl2 = cast(int)floor(yEnd); + plot(xpxl2, ypxl2, rfpart(yEnd) * xGap); + plot(xpxl2, ypxl2 + 1, fpart(yEnd) * xGap); + + // Main loop. + foreach (immutable x; xpxl1 + 1 .. xpxl2) { + plot(x, cast(int)floor(yInter), rfpart(yInter)); + plot(x, cast(int)floor(yInter) + 1, fpart(yInter)); + yInter += gradient; + } +} + +void main() { + auto im1 = new Image!Gray(400, 300); + im1.clear(Gray.white); + im1.aaLine(7.4, 12.3, 307, 122.5, Gray.black); + im1.aaLine(177.4, 12.3, 127, 222.5, Gray.black); + im1.savePGM("xiaolin_lines1.pgm"); + + auto im2 = new Image!RGB(400, 300); + im2.clear(RGB(0, 255, 0)); + immutable red = RGB(255, 0, 0); + im2.aaLine(7.4, 12.3, 307, 122.5, red); + im2.aaLine(177.4, 12.3, 127, 222.5, red); + im2.savePPM6("xiaolin_lines2.ppm"); +} diff --git a/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-1.go b/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-1.go new file mode 100644 index 0000000000..f73a5288c7 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-1.go @@ -0,0 +1,79 @@ +package raster + +import "math" + +func ipart(x float64) float64 { + return math.Floor(x) +} + +func round(x float64) float64 { + return ipart(x + .5) +} + +func fpart(x float64) float64 { + return x - ipart(x) +} + +func rfpart(x float64) float64 { + return 1 - fpart(x) +} + +// AaLine plots anti-aliased line by Xiaolin Wu's line algorithm. +func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { + // straight translation of WP pseudocode + dx := x2 - x1 + dy := y2 - y1 + ax := dx + if ax < 0 { + ax = -ax + } + ay := dy + if ay < 0 { + ay = -ay + } + // plot function set here to handle the two cases of slope + var plot func(int, int, float64) + if ax < ay { + x1, y1 = y1, x1 + x2, y2 = y2, x2 + dx, dy = dy, dx + plot = func(x, y int, c float64) { + g.SetPx(y, x, uint16(c*math.MaxUint16)) + } + } else { + plot = func(x, y int, c float64) { + g.SetPx(x, y, uint16(c*math.MaxUint16)) + } + } + if x2 < x1 { + x1, x2 = x2, x1 + y1, y2 = y2, y1 + } + gradient := dy / dx + + // handle first endpoint + xend := round(x1) + yend := y1 + gradient*(xend-x1) + xgap := rfpart(x1 + .5) + xpxl1 := int(xend) // this will be used in the main loop + ypxl1 := int(ipart(yend)) + plot(xpxl1, ypxl1, rfpart(yend)*xgap) + plot(xpxl1, ypxl1+1, fpart(yend)*xgap) + intery := yend + gradient // first y-intersection for the main loop + + // handle second endpoint + xend = round(x2) + yend = y2 + gradient*(xend-x2) + xgap = fpart(x2 + 0.5) + xpxl2 := int(xend) // this will be used in the main loop + ypxl2 := int(ipart(yend)) + plot(xpxl2, ypxl2, rfpart(yend)*xgap) + plot(xpxl2, ypxl2+1, fpart(yend)*xgap) + + // main loop + for x := xpxl1 + 1; x <= xpxl2-1; x++ { + plot(x, int(ipart(intery)), rfpart(intery)) + plot(x, int(ipart(intery))+1, fpart(intery)) + intery = intery + gradient + } +} diff --git a/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-2.go b/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-2.go new file mode 100644 index 0000000000..9d27a20428 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Go/xiaolin-wus-line-algorithm-2.go @@ -0,0 +1,16 @@ +package main + +// Files required to build supporting package raster are found in: +// * This task (immediately above) +// * Bitmap +// * Grayscale image +// * Write a PPM file + +import "raster" + +func main() { + g := raster.NewGrmap(400, 300) + g.AaLine(7.4, 12.3, 307, 122.5) + g.AaLine(177.4, 12.3, 127, 222.5) + g.Bitmap().WritePpmFile("wu.ppm") +} diff --git a/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-1.j b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-1.j new file mode 100644 index 0000000000..485e097a6b --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-1.j @@ -0,0 +1,25 @@ +load'gl2' +coinsert'jgl2' + +drawpt=:4 :0"0 1 + glrgb <.(-.x)*255 255 255 + glpixel y +) + +drawLine=:3 :0 NB. drawline x1,y1,x2,y2 + pts=. 2 2$y + isreversed=. : -~/ xend + 'xlist ylist'=. (n*/~1,gradient) + ({.xend),({.yend) + weights=. ((2&}.,~ xgap*2&{.)&.(_1&|.) (,.~-.) 1|ylist) + weights (drawpt r)"1 2 (,:+&0 1)"1 xlist,.<.ylist +) diff --git a/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j new file mode 100644 index 0000000000..91d3f6cf86 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/J/xiaolin-wus-line-algorithm-2.j @@ -0,0 +1,2 @@ + wd'pc win closeok; xywh 0 0 300 200;cc g isigraph; pas 0 0; pshow;' + glpaint drawLine 10 10 590 390 diff --git a/Task/Xiaolin-Wus-line-algorithm/Liberty-BASIC/xiaolin-wus-line-algorithm.liberty b/Task/Xiaolin-Wus-line-algorithm/Liberty-BASIC/xiaolin-wus-line-algorithm.liberty new file mode 100644 index 0000000000..8c9ec884e7 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Liberty-BASIC/xiaolin-wus-line-algorithm.liberty @@ -0,0 +1,155 @@ +NoMainWin +WindowWidth = 270 +WindowHeight = 290 +UpperLeftX=int((DisplayWidth-WindowWidth)/2) +UpperLeftY=int((DisplayHeight-WindowHeight)/2) + +Global variablesInitialized : variablesInitialized = 0 +Global BackColor$ : BackColor$ = "0 0 0" +' BackColor$ = "255 255 255" + 'now, right click randomizes BG +Global size : size = 1'4 +global mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1 + +'StyleBits #main.gbox, 0, _WS_BORDER, 0, 0 +GraphicBox #main.gbox, 0, 0, 253, 252 + +Open "Click Twice to Form Line" For Window As #main +Print #main, "TrapClose quit" +Print #main.gbox, "Down; Color Black" +Print #main.gbox, "Down; fill ";BackColor$ +Print #main.gbox, "When leftButtonUp gBoxClick" +Print #main.gbox, "When rightButtonUp RandomBG" +Print #main.gbox, "Size "; size + +result = drawAntiAliasedLine(126.5, 0, 126.5, 252, "255 0 0") +result = drawAntiAliasedLine(0, 126, 253, 126, "255 0 0") +result = drawAntiAliasedLine(0, 0, 253, 252, "255 0 0") +result = drawAntiAliasedLine(253, 0, 0, 252, "255 0 0") +Wait + + + Sub quit handle$ + Close #main + End + End Sub + +sub RandomBG handle$, MouseX, MouseY + BackColor$ = int(rnd(1)*256);" ";int(rnd(1)*256);" ";int(rnd(1)*256) + Print #main.gbox, "CLS; fill ";BackColor$ + variablesInitialized = 0 +end sub + + Sub gBoxClick handle$, MouseX, MouseY + 'We will use the mousepoints "struct" to hold the values + 'that way they are retained between subroutine calls + If variablesInitialized = 0 Then + Print #main.gbox, "CLS; fill ";BackColor$ + mousepoints.mouseX0 = MouseX + mousepoints.mouseY0 = MouseY + variablesInitialized = 1 + Else + If variablesInitialized = 1 Then + mousepoints.mouseX1 = MouseX + mousepoints.mouseY1 = MouseY + variablesInitialized = 0 + result = drawAntiAliasedLine(mousepoints.mouseX0, mousepoints.mouseY0, mousepoints.mouseX1, mousepoints.mouseY1, "255 0 0") + End If + End If + End Sub + + Function Swap(Byref a,Byref b) + aTemp = b + b = a + a = aTemp + End Function + + Function RoundtoInt(val) + RoundtoInt = Int(val + 0.5) + End Function + + Function PlotAntiAliased(x, y, RGB$, b, steep) + + RGB$ = Int(Val(Word$(BackColor$, 1))*(1-b) + Val(Word$(RGB$, 1)) * b) ; " " ; _ + Int(Val(Word$(BackColor$, 2))*(1-b) + Val(Word$(RGB$, 3)) * b) ; " " ; _ + Int(Val(Word$(BackColor$, 3))*(1-b) + Val(Word$(RGB$, 2)) * b) + + if steep then 'x and y reversed + Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(y) + " " + str$(x) + else + Print #main.gbox, "Down; Color " + RGB$ + "; Set " + str$(x) + " " + str$(y) + end if + End Function + + Function fracPart(x) + fracPart = (x Mod 1) + End function + + Function invFracPart(x) + invFracPart = (1 - fracPart(x)) + End Function + + Function drawAntiAliasedLine(x1, y1, x2, y2, RGB$) + If (x2 - x1)=0 Or (y2 - y1)=0 Then + Print #main.gbox, "Down; Color " + RGB$ + result = BresenhamLine(x1, y1, x2, y2) + Exit Function + End If + steep = abs(x2 - x1) < abs(y2 - y1) + if steep then 'x and y should be reversed + result = Swap(x1, y1) + result = Swap(x2, y2) + end if + + If (x2 < x1) Then + result = Swap(x1, x2) + result = Swap(y1, y2) + End If + dx = (x2 - x1) + dy = (y2 - y1) + grad = (dy/ dx) + 'Handle the First EndPoint + xend = RoundtoInt(x1) + yend = y1 + grad * (xend - x1) + xgap = invFracPart(x1 + 0.5) + ix1 = xend + iy1 = Int(yend) + result = PlotAntiAliased(ix1, iy1, RGB$, invFracPart(yend) * xgap, steep ) + result = PlotAntiAliased(ix1, (iy1 + size), RGB$, fracPart(yend) * xgap, steep ) + yf = (yend + grad) + 'Handle the Second EndPoint + xend = RoundtoInt(x2) + yend = y2 + grad * (xend - x2) + xgap = fracPart(x2 + 0.5) + ix2 = xend + iy2 = Int(yend) + result = PlotAntiAliased(ix2, iy2, RGB$, invFracPart(yend) * xgap, steep ) + result = PlotAntiAliased(ix2, (iy2 + size), RGB$, fracPart(yend) * xgap, steep ) + For x = ix1 + 1 To ix2 - 1 + result = PlotAntiAliased(x, Int(yf), RGB$, invFracPart(yf), steep ) + result = PlotAntiAliased(x, (Int(yf) + size), RGB$, fracPart(yf), steep ) + yf = (yf + grad) + Next x + End Function + + + Function BresenhamLine(x0, y0, x1, y1) + dx = Abs(x1 - x0) + dy = Abs(y1 - y0) + sx = ((x1 > x0) + Not(x0 < x1)) + sy = ((y1 > y0) + Not(y0 < y1)) + errornum = (dx - dy) + Do While 1 + Print #main.gbox, "Set " + str$(x0) + " " + str$(y0) + If (x0 = x1) And (y0 = y1) Then Exit Do + errornum2 = (2 * errornum) + If errornum2 > (-1 * dy) Then + errornum = (errornum - dy) + x0 = (x0 + sx) + End If + If errornum2 < dx Then + errornum = (errornum + dx) + y0 = (y0 + sy) + End If + Loop + End Function diff --git a/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 b/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 new file mode 100644 index 0000000000..fe44f497e8 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Perl-6/xiaolin-wus-line-algorithm.pl6 @@ -0,0 +1,60 @@ +sub plot(\x, \y, \c) { say "plot {x} {y} {c}" } + +sub fpart(\x) { x - floor(x) } + +sub draw-line(@a is copy, @b is copy) { + my Bool \steep = abs(@b[1] - @a[1]) > abs(@b[0] - @a[0]); + my $plot = &OUTER::plot; + + if steep { + $plot = -> $y, $x, $c { plot($x, $y, $c) } + @a.=reverse; + @b.=reverse; + } + if @a[0] > @b[0] { my @t = @a; @a = @b; @b = @t } + + my (\x0,\y0) = @a; + my (\x1,\y1) = @b; + + my \dx = x1 - x0; + my \dy = y1 - y0; + my \gradient = dy / dx; + + # handle first endpoint + my \x-end1 = round(x0); + my \y-end1 = y0 + gradient * (x-end1 - x0); + my \x-gap1 = 1 - round(x0 + 0.5); + + my \x-pxl1 = x-end1; # this will be used in the main loop + my \y-pxl1 = floor(y-end1); + my \c1 = fpart(y-end1) * x-gap1; + + $plot(x-pxl1, y-pxl1 , 1 - c1) unless c1 == 1; + $plot(x-pxl1, y-pxl1 + 1, c1 ) unless c1 == 0; + + # handle second endpoint + my \x-end2 = round(x1); + my \y-end2 = y1 + gradient * (x-end2 - x1); + my \x-gap2 = fpart(x1 + 0.5); + + my \x-pxl2 = x-end2; # this will be used in the main loop + my \y-pxl2 = floor(y-end2); + my \c2 = fpart(y-end2) * x-gap2; + + my \intery = y-end1 + gradient; + + # main loop + for (x-pxl1 + 1 .. x-pxl2 - 1) + Z + (intery, intery + gradient ... *) + -> \x,\y { + my \c = fpart(y); + $plot(x, floor(y) , 1 - c) unless c == 1; + $plot(x, floor(y) + 1, c ) unless c == 0; + } + + $plot(x-pxl2, y-pxl2 , 1 - c2) unless c2 == 1; + $plot(x-pxl2, y-pxl2 + 1, c2 ) unless c2 == 0; +} + +draw-line [0,1], [10,2]; diff --git a/Task/Xiaolin-Wus-line-algorithm/PicoLisp/xiaolin-wus-line-algorithm.l b/Task/Xiaolin-Wus-line-algorithm/PicoLisp/xiaolin-wus-line-algorithm.l new file mode 100644 index 0000000000..69d144c8bd --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/PicoLisp/xiaolin-wus-line-algorithm.l @@ -0,0 +1,57 @@ +(scl 2) + +(de plot (Img X Y C) + (set (nth Img (*/ Y 1.0) (*/ X 1.0)) (- 100 C)) ) + +(de ipart (X) + (* 1.0 (/ X 1.0)) ) + +(de iround (X) + (ipart (+ X 0.5)) ) + +(de fpart (X) + (% X 1.0) ) + +(de rfpart (X) + (- 1.0 (fpart X)) ) + +(de xiaolin (Img X1 Y1 X2 Y2) + (let (DX (- X2 X1) DY (- Y2 Y1)) + (use (Grad Xend Yend Xgap Xpxl1 Ypxl1 Xpxl2 Ypxl2 Intery) + (when (> (abs DY) (abs DX)) + (xchg 'X1 'Y1 'X2 'Y2) ) + (when (> X1 X2) + (xchg 'X1 'X2 'Y1 'Y2) ) + (setq + Grad (*/ DY 1.0 DX) + Xend (iround X1) + Yend (+ Y1 (*/ Grad (- Xend X1) 1.0)) + Xgap (rfpart (+ X1 0.5)) + Xpxl1 Xend + Ypxl1 (ipart Yend) ) + (plot Img Xpxl1 Ypxl1 (*/ (rfpart Yend) Xgap 1.0)) + (plot Img Xpxl1 (+ 1.0 Ypxl1) (*/ (fpart Yend) Xgap 1.0)) + (setq + Intery (+ Yend Grad) + Xend (iround X2) + Yend (+ Y2 (*/ Grad (- Xend X2) 1.0)) + Xgap (fpart (+ X2 0.5)) + Xpxl2 Xend + Ypxl2 (ipart Yend) ) + (plot Img Xpxl2 Ypxl2 (*/ (rfpart Yend) Xgap 1.0)) + (plot Img Xpxl2 (+ 1.0 Ypxl2) (*/ (fpart Yend) Xgap 1.0)) + (for (X (+ Xpxl1 1.0) (>= (- Xpxl2 1.0) X) (+ X 1.0)) + (plot Img X (ipart Intery) (rfpart Intery)) + (plot Img X (+ 1.0 (ipart Intery)) (fpart Intery)) + (inc 'Intery Grad) ) ) ) ) + +(let Img (make (do 90 (link (need 120 99)))) # Create image 120 x 90 + (xiaolin Img 10.0 10.0 110.0 80.0) # Draw lines + (xiaolin Img 10.0 10.0 110.0 45.0) + (xiaolin Img 10.0 80.0 110.0 45.0) + (xiaolin Img 10.0 80.0 110.0 10.0) + (out "img.pgm" # Write to bitmap file + (prinl "P2") + (prinl 120 " " 90) + (prinl 100) + (for Y Img (apply printsp Y)) ) ) diff --git a/Task/Xiaolin-Wus-line-algorithm/PureBasic/xiaolin-wus-line-algorithm.purebasic b/Task/Xiaolin-Wus-line-algorithm/PureBasic/xiaolin-wus-line-algorithm.purebasic new file mode 100644 index 0000000000..893a189645 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/PureBasic/xiaolin-wus-line-algorithm.purebasic @@ -0,0 +1,72 @@ +Macro PlotB(x, y, Color, b) + Plot(x, y, RGB(Red(Color) * (b), Green(Color) * (b), Blue(Color) * (b))) +EndMacro + +Procedure.f fracPart(x.f) + ProcedureReturn x - Int(x) +EndProcedure + +Procedure.f invFracPart(x.f) + ProcedureReturn 1.0 - fracPart(x) +EndProcedure + +Procedure drawAntiAliasedLine(x1.f, y1.f, x2.f, y2.f, color) + Protected.f dx, dy, xend, yend, grad, yf, xgap, ix1, iy1, ix2, iy2 + Protected x + + dx = x2 - x1 + dy = y2 - y1 + If Abs(dx) < Abs(dy) + Swap x1, y1 + Swap x2, y2 + Swap dx, dy + EndIf + + If x2 < x1 + Swap x1, x2 + Swap y1, y2 + EndIf + + grad = dy / dx + + ;handle first endpoint + xend = Round(x1, #pb_round_nearest) + yend = y1 + grad * (xend - x1) + xgap = invFracPart(x1 + 0.5) + ix1 = xend ;this will be used in the MAIN loop + iy1 = Int(yend) + PlotB(ix1, iy1, color, invFracPart(yend) * xgap) + PlotB(ix1, iy1 + 1, color, fracPart(yend) * xgap) + yf = yend + grad ;first y-intersection for the MAIN loop + + ;handle second endpoint + xend = Round(x2, #pb_round_nearest) + yend = y2 + grad * (xend - x2) + xgap = fracPart(x2 + 0.5) + ix2 = xend ;this will be used in the MAIN loop + iy2 = Int(yend) + PlotB(ix2, iy2, color, invFracPart(yend) * xgap) + PlotB(ix2, iy2 + 1, color, fracPart(yend) * xgap) + ;MAIN loop + For x = ix1 + 1 To ix2 - 1 + PlotB(x, Int(yf), color, invFracPart(yf)) + PlotB(x, Int(yf) + 1, color, fracPart(yf)) + yf + grad + Next +EndProcedure + +Define w = 200, h = 200, img = 1 +CreateImage(img, w, h) ;img is internal id of the image + +OpenWindow(0, 0, 0, w, h,"Xiaolin Wu's line algorithm", #PB_Window_SystemMenu) + +StartDrawing(ImageOutput(img)) + drawAntiAliasedLine(80,20, 130,80, RGB(255, 0, 0)) +StopDrawing() + +ImageGadget(0, 0, 0, w, h, ImageID(img)) + +Define event +Repeat + event = WaitWindowEvent() +Until event = #PB_Event_CloseWindow diff --git a/Task/Xiaolin-Wus-line-algorithm/Python/xiaolin-wus-line-algorithm.py b/Task/Xiaolin-Wus-line-algorithm/Python/xiaolin-wus-line-algorithm.py new file mode 100644 index 0000000000..0913b8eb8a --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Python/xiaolin-wus-line-algorithm.py @@ -0,0 +1,77 @@ +"""Script demonstrating drawing of anti-aliased lines using Xiaolin Wu's line +algorithm + +usage: python xiaolinwu.py [output-file] + +""" +from __future__ import division +import sys + +from PIL import Image + + +def _fpart(x): + return x - int(x) + +def _rfpart(x): + return 1 - _fpart(x) + +def putpixel(img, xy, color, alpha=1): + """Paints color over the background at the point xy in img. + + Use alpha for blending. alpha=1 means a completely opaque foreground. + + """ + c = tuple(map(lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg)), + img.getpixel(xy), color)) + img.putpixel(xy, c) + +def draw_line(img, p1, p2, color): + """Draws an anti-aliased line in img from p1 to p2 with the given color.""" + x1, y1, x2, y2 = p1 + p2 + dx, dy = x2-x1, y2-y1 + steep = abs(dx) < abs(dy) + p = lambda px, py: ((px,py), (py,px))[steep] + + if steep: + x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx + if x2 < x1: + x1, x2, y1, y2 = x2, x1, y2, y1 + + grad = dy/dx + intery = y1 + _rfpart(x1) * grad + def draw_endpoint(pt): + x, y = pt + xend = round(x) + yend = y + grad * (xend - x) + xgap = _rfpart(x + 0.5) + px, py = int(xend), int(yend) + putpixel(img, (px, py), color, _rfpart(yend) * xgap) + putpixel(img, (px, py+1), color, _fpart(yend) * xgap) + return px + + xstart = draw_endpoint(p(*p1)) + 1 + xend = draw_endpoint(p(*p2)) + + for x in range(xstart, xend): + y = int(intery) + putpixel(img, p(x, y), color, _rfpart(intery)) + putpixel(img, p(x, y+1), color, _fpart(intery)) + intery += grad + + +if __name__ == '__main__': + if len(sys.argv) != 2: + print 'usage: python xiaolinwu.py [output-file]' + sys.exit(-1) + + blue = (0, 0, 255) + yellow = (255, 255, 0) + img = Image.new("RGB", (500,500), blue) + for a in range(10, 431, 60): + draw_line(img, (10, 10), (490, a), yellow) + draw_line(img, (10, 10), (a, 490), yellow) + draw_line(img, (10, 10), (490, 490), yellow) + filename = sys.argv[1] + img.save(filename) + print 'image saved to', filename diff --git a/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx new file mode 100644 index 0000000000..150289e5e9 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx @@ -0,0 +1,82 @@ +/*REXX program plots/draws a line using the Xiaolin Wu line algorithm.*/ +background = 'fa'x /*background char: middle-dot. */ + image. = background /*fill the array with middle-dots*/ + plotC = '░▒▓█' /*chars used for plotting points.*/ + EoE = 1000 /*EOE = End Of Earth, er... plot.*/ + do j=-EoE to +EoE /*draw grid from lowest──►highest*/ + image.j.0 = '─' /*draw the horizontal axis. */ + image.0.j = '│' /* " " verical " */ + end /*j*/ +image.0.0 = '┼' /*"draw" the axis origin (char). */ +parse arg xi yi xf yf . /*allow specifying line-end pts. */ +if xi=='' | xi==',' then xi = 1 /*if not specified, use default. */ +if yi=='' | yi==',' then yi = 2 /* " " " " " */ +if xf=='' | xf==',' then xf = 11 /* " " " " " */ +if yf=='' | yf==',' then yf = 12 /* " " " " " */ +minX=0; minY=0 /*used as limits for plotting. */ +maxX=0; maxY=0 /* " " " " " */ +call line_draw xi, yi, xf, yf /*call subroutine and draw line. */ +border = 2 /*allow additional space for plot*/ +minX=minX-border*2; maxX=maxX+border*2 +minY=minY-border ; maxY=maxY+border + do y=maxY by -1 to minY; _= /*build a row*/ + do x=minX to maxX + _=_ || image.x.y + end /*x*/ + say _ /*display row*/ + end /*y*/ +exit /*stick a fork in it, we're done.*/ +/*────────────────────────────────DRAW_LINE subroutine──────────────────*/ +line_draw: procedure expose background image. minX maxX minY maxY plotC +parse arg x1, y1, x2, y2; switchXY=0; dx=x2-x1 + dy=y2-y1 +if abs(dx) (x2 - x1).abs + if steep + x1, y1 = y1, x1 + x2, y2 = y2, x2 + end + if x1 > x2 + x1, x2 = x2, x1 + y1, y2 = y2, y1 + end + deltax = x2 - x1 + deltay = (y2 - y1).abs + gradient = 1.0 * deltay / deltax + + # handle the first endpoint + xend = x1.round + yend = y1 + gradient * (xend - x1) + xgap = rfpart(x1 + 0.5) + xpxl1 = xend + ypxl1 = ipart(yend) + put_colour(xpxl1, ypxl1, colour, steep, rfpart(yend)*xgap) + put_colour(xpxl1, ypxl1 + 1, colour, steep, fpart(yend)*xgap) + itery = yend + gradient + + # handle the second endpoint + xend = x2.round + yend = y2 + gradient * (xend - x2) + xgap = rfpart(x2 + 0.5) + xpxl2 = xend + ypxl2 = ipart(yend) + put_colour(xpxl2, ypxl2, colour, steep, rfpart(yend)*xgap) + put_colour(xpxl2, ypxl2 + 1, colour, steep, fpart(yend)*xgap) + + # in between + (xpxl1 + 1).upto(xpxl2 - 1).each do |x| + put_colour(x, ipart(itery), colour, steep, rfpart(itery)) + put_colour(x, ipart(itery) + 1, colour, steep, fpart(itery)) + itery = itery + gradient + end + end + + def put_colour(x, y, colour, steep, c) + x, y = y, x if steep + self[x, y] = anti_alias(colour, self[x, y], c) + end + + def anti_alias(new, old, ratio) + blended = new.values.zip(old.values).map {|n, o| (n*ratio + o*(1.0 - ratio)).round} + RGBColour.new(*blended) + end +end + +bitmap = Pixmap.new(500, 500) +bitmap.fill(RGBColour::BLUE) +10.step(430, 60) do |a| + bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,a], RGBColour::YELLOW) + bitmap.draw_line_antialised(Pixel[10, 10], Pixel[a,490], RGBColour::YELLOW) +end +bitmap.draw_line_antialised(Pixel[10, 10], Pixel[490,490], RGBColour::YELLOW) diff --git a/Task/Xiaolin-Wus-line-algorithm/Tcl/xiaolin-wus-line-algorithm.tcl b/Task/Xiaolin-Wus-line-algorithm/Tcl/xiaolin-wus-line-algorithm.tcl new file mode 100644 index 0000000000..20c6d8a534 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Tcl/xiaolin-wus-line-algorithm.tcl @@ -0,0 +1,88 @@ +package require Tcl 8.5 +package require Tk + +proc ::tcl::mathfunc::ipart x {expr {int($x)}} +proc ::tcl::mathfunc::fpart x {expr {$x - int($x)}} +proc ::tcl::mathfunc::rfpart x {expr {1.0 - fpart($x)}} + +proc drawAntialiasedLine {image colour p1 p2} { + lassign $p1 x1 y1 + lassign $p2 x2 y2 + + set steep [expr {abs($y2 - $y1) > abs($x2 - $x1)}] + if {$steep} { + lassign [list $x1 $y1] y1 x1 + lassign [list $x2 $y2] y2 x2 + } + if {$x1 > $x2} { + lassign [list $x1 $x2] x2 x1 + lassign [list $y1 $y2] y2 y1 + } + set deltax [expr {$x2 - $x1}] + set deltay [expr {abs($y2 - $y1)}] + set gradient [expr {1.0 * $deltay / $deltax}] + + # handle the first endpoint + set xend [expr {round($x1)}] + set yend [expr {$y1 + $gradient * ($xend - $x1)}] + set xgap [expr {rfpart($x1 + 0.5)}] + set xpxl1 $xend + set ypxl1 [expr {ipart($yend)}] + plot $image $colour $steep $xpxl1 $ypxl1 [expr {rfpart($yend)*$xgap}] + plot $image $colour $steep $xpxl1 [expr {$ypxl1+1}] [expr {fpart($yend)*$xgap}] + set itery [expr {$yend + $gradient}] + + # handle the second endpoint + set xend [expr {round($x2)}] + set yend [expr {$y2 + $gradient * ($xend - $x2)}] + set xgap [expr {rfpart($x2 + 0.5)}] + set xpxl2 $xend + set ypxl2 [expr {ipart($yend)}] + plot $image $colour $steep $xpxl2 $ypxl2 [expr {rfpart($yend)*$xgap}] + plot $image $colour $steep $xpxl2 [expr {$ypxl2+1}] [expr {fpart($yend)*$xgap}] + + for {set x [expr {$xpxl1 + 1}]} {$x < $xpxl2} {incr x} { + plot $image $colour $steep $x [expr {ipart($itery)}] [expr {rfpart($itery)}] + plot $image $colour $steep $x [expr {ipart($itery) + 1}] [expr {fpart($itery)}] + set itery [expr {$itery + $gradient}] + } +} + +proc plot {image colour steep x y c} { + set point [expr {$steep ? [list $y $x] : [list $x $y]}] + set newColour [antialias $colour [getPixel $image $point] $c] + setPixel $image $newColour $point +} + +proc antialias {newColour oldColour c} { + # get the new colour r,g,b + if {[scan $newColour "#%2x%2x%2x%c" nr ng gb -] != 3} { + scan [colour2rgb $newColour] "#%2x%2x%2x" nr ng nb + } + + # get the current colour r,g,b + scan $oldColour "#%2x%2x%2x" cr cg cb + + # blend the colours in the ratio defined by "c" + foreach new [list $nr $ng $nb] curr [list $cr $cg $cb] { + append blend [format {%02x} [expr {round($new*$c + $curr*(1.0-$c))}]] + } + return #$blend +} + +proc colour2rgb {color_name} { + foreach part [winfo rgb . $color_name] { + append colour [format %02x [expr {$part >> 8}]] + } + return #$colour +} + +set img [newImage 500 500] +fill $img blue +for {set a 10} {$a < 500} {incr a 60} { + drawAntialiasedLine $img yellow {10 10} [list 490 $a] + drawAntialiasedLine $img yellow {10 10} [list $a 490] +} +toplevel .wu +label .wu.l -image $img +pack .wu.l diff --git a/Task/Y-combinator/0DESCRIPTION b/Task/Y-combinator/0DESCRIPTION new file mode 100644 index 0000000000..e64c9e7967 --- /dev/null +++ b/Task/Y-combinator/0DESCRIPTION @@ -0,0 +1,8 @@ +In strict [[wp:Functional programming|functional programming]] and the [[wp:lambda calculus|lambda calculus]], functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. + +The [http://mvanier.livejournal.com/2897.html Y combinator] is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called [[wp:Fixed-point combinator|fixed-point combinators]]. + +The task is to define the stateless Y combinator and use it to compute [[wp:Factorial|factorials]] and [[wp:Fibonacci number|Fibonacci numbers]] from other stateless functions or lambda expressions. + +;Cf: +* [http://vimeo.com/45140590 Jim Weirich: Adventures in Functional Programming] diff --git a/Task/Y-combinator/1META.yaml b/Task/Y-combinator/1META.yaml new file mode 100644 index 0000000000..e1062d6f14 --- /dev/null +++ b/Task/Y-combinator/1META.yaml @@ -0,0 +1,6 @@ +--- +category: +- Recursion +note: Classic CS problems and programs +requires: +- First class functions diff --git a/Task/Y-combinator/ALGOL-68/y-combinator.alg b/Task/Y-combinator/ALGOL-68/y-combinator.alg new file mode 100644 index 0000000000..9edb64720a --- /dev/null +++ b/Task/Y-combinator/ALGOL-68/y-combinator.alg @@ -0,0 +1,11 @@ +BEGIN + MODE F = PROC(INT)INT; + MODE Y = PROC(Y)F; + +# compare python Y = lambda f: (lambda x: x(x)) (lambda y: f( lambda *args: y(y)(*args)))# + PROC y = (PROC(F)F f)F: ( (Y x)F: x(x)) ( (Y z)F: f((INT arg )INT: z(z)( arg ))); + + PROC fib = (F f)F: (INT n)INT: CASE n IN n,n OUT f(n-1) + f(n-2) ESAC; + + FOR i TO 10 DO print(y(fib)(i)) OD +END diff --git a/Task/Y-combinator/AppleScript/y-combinator.applescript b/Task/Y-combinator/AppleScript/y-combinator.applescript new file mode 100644 index 0000000000..e6a02c268b --- /dev/null +++ b/Task/Y-combinator/AppleScript/y-combinator.applescript @@ -0,0 +1,54 @@ +to |Y|(f) + script x + to funcall(y) + script + to funcall(arg) + y's funcall(y)'s funcall(arg) + end funcall + end script + f's funcall(result) + end funcall + end script + x's funcall(x) +end |Y| + +script + to funcall(f) + script + to funcall(n) + if n = 0 then return 1 + n * (f's funcall(n - 1)) + end funcall + end script + end funcall +end script +set fact to |Y|(result) + +script + to funcall(f) + script + to funcall(n) + if n = 0 then return 0 + if n = 1 then return 1 + (f's funcall(n - 2)) + (f's funcall(n - 1)) + end funcall + end script + end funcall +end script +set fib to |Y|(result) + +set facts to {} +repeat with i from 0 to 11 + set end of facts to fact's funcall(i) +end repeat + +set fibs to {} +repeat with i from 0 to 20 + set end of fibs to fib's funcall(i) +end repeat + +{facts:facts, fibs:fibs} +(* +{facts:{1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800}, + fibs:{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765}} +*) diff --git a/Task/Y-combinator/BlitzMax/y-combinator.blitz b/Task/Y-combinator/BlitzMax/y-combinator.blitz new file mode 100644 index 0000000000..c7719d8ed2 --- /dev/null +++ b/Task/Y-combinator/BlitzMax/y-combinator.blitz @@ -0,0 +1,156 @@ +SuperStrict + +'Boxed type so we can just use object arrays for argument lists +Type Integer + Field val:Int + Function Make:Integer(_val:Int) + Local i:Integer = New Integer + i.val = _val + Return i + End Function +End Type + + +'Higher-order function type - just a procedure attached to a scope +Type Func Abstract + Method apply:Object(args:Object[]) Abstract +End Type + +'Function definitions - extend with fields as locals and implement apply as body +Type Scope Extends Func Abstract + Field env:Scope + + 'Constructor - bind an environment to a procedure + Function lambda:Scope(env:Scope) Abstract + + Method _init:Scope(_env:Scope) 'Helper to keep constructors small + env = _env ; Return Self + End Method +End Type + + +'Based on the following definition: +'(define (Y f) +' (let ((_r (lambda (r) (f (lambda a (apply (r r) a)))))) +' (_r _r))) + +'Y (outer) +Type Y Extends Scope + Field f:Func 'Parameter - gets closed over + + Function lambda:Scope(env:Scope) 'Necessary due to highly limited constructor syntax + Return (New Y)._init(env) + End Function + + Method apply:Func(args:Object[]) + f = Func(args[0]) + Local _r:Func = YInner1.lambda(Self) + Return Func(_r.apply([_r])) + End Method +End Type + +'First lambda within Y +Type YInner1 Extends Scope + Field r:Func 'Parameter - gets closed over + + Function lambda:Scope(env:Scope) + Return (New YInner1)._init(env) + End Function + + Method apply:Func(args:Object[]) + r = Func(args[0]) + Return Func(Y(env).f.apply([YInner2.lambda(Self)])) + End Method +End Type + +'Second lambda within Y +Type YInner2 Extends Scope + Field a:Object[] 'Parameter - not really needed, but good for clarity + + Function lambda:Scope(env:Scope) + Return (New YInner2)._init(env) + End Function + + Method apply:Object(args:Object[]) + a = args + Local r:Func = YInner1(env).r + Return Func(r.apply([r])).apply(a) + End Method +End Type + + +'Based on the following definition: +'(define fac (Y (lambda (f) +' (lambda (x) +' (if (<= x 0) 1 (* x (f (- x 1))))))) + +Type FacL1 Extends Scope + Field f:Func 'Parameter - gets closed over + + Function lambda:Scope(env:Scope) + Return (New FacL1)._init(env) + End Function + + Method apply:Object(args:Object[]) + f = Func(args[0]) + Return FacL2.lambda(Self) + End Method +End Type + +Type FacL2 Extends Scope + Function lambda:Scope(env:Scope) + Return (New FacL2)._init(env) + End Function + + Method apply:Object(args:Object[]) + Local x:Int = Integer(args[0]).val + If x <= 0 Then Return Integer.Make(1) ; Else Return Integer.Make(x * Integer(FacL1(env).f.apply([Integer.Make(x - 1)])).val) + End Method +End Type + + +'Based on the following definition: +'(define fib (Y (lambda (f) +' (lambda (x) +' (if (< x 2) x (+ (f (- x 1)) (f (- x 2))))))) + +Type FibL1 Extends Scope + Field f:Func 'Parameter - gets closed over + + Function lambda:Scope(env:Scope) + Return (New FibL1)._init(env) + End Function + + Method apply:Object(args:Object[]) + f = Func(args[0]) + Return FibL2.lambda(Self) + End Method +End Type + +Type FibL2 Extends Scope + Function lambda:Scope(env:Scope) + Return (New FibL2)._init(env) + End Function + + Method apply:Object(args:Object[]) + Local x:Int = Integer(args[0]).val + If x < 2 + Return Integer.Make(x) + Else + Local f:Func = FibL1(env).f + Local x1:Int = Integer(f.apply([Integer.Make(x - 1)])).val + Local x2:Int = Integer(f.apply([Integer.Make(x - 2)])).val + Return Integer.Make(x1 + x2) + EndIf + End Method +End Type + + +'Now test +Local _Y:Func = Y.lambda(Null) + +Local fac:Func = Func(_Y.apply([FacL1.lambda(Null)])) +Print Integer(fac.apply([Integer.Make(10)])).val + +Local fib:Func = Func(_Y.apply([FibL1.lambda(Null)])) +Print Integer(fib.apply([Integer.Make(10)])).val diff --git a/Task/Y-combinator/Bracmat/y-combinator.bracmat b/Task/Y-combinator/Bracmat/y-combinator.bracmat new file mode 100644 index 0000000000..04121c96cb --- /dev/null +++ b/Task/Y-combinator/Bracmat/y-combinator.bracmat @@ -0,0 +1,44 @@ + ( ( Y + = /( + ' ( g + . /('(x.$g'($x'$x))) + $ /('(x.$g'($x'$x))) + ) + ) + ) + & ( g + = /( + ' ( r + . /( + ' ( n + . $n:~>0&1 + | $n*($r)$($n+-1) + ) + ) + ) + ) + ) + & ( h + = /( + ' ( r + . /( + ' ( n + . $n:(1|2)&1 + | ($r)$($n+-1)+($r)$($n+-2) + ) + ) + ) + ) + ) + & 0:?i + & whl + ' ( 1+!i:~>10:?i + & out$(str$(!i "!=" (!Y$!g)$!i)) + ) + & 0:?i + & whl + ' ( 1+!i:~>10:?i + & out$(str$("fib(" !i ")=" (!Y$!h)$!i)) + ) + & + ) diff --git a/Task/Y-combinator/C++/y-combinator.cpp b/Task/Y-combinator/C++/y-combinator.cpp new file mode 100644 index 0000000000..a8756e34ab --- /dev/null +++ b/Task/Y-combinator/C++/y-combinator.cpp @@ -0,0 +1,43 @@ +#include +#include + +template +struct RecursiveFunc { + std::function o; +}; + +template +std::function fix (std::function(std::function)> f) { + RecursiveFunc> r = { + std::function(RecursiveFunc>)>([f](RecursiveFunc> w) { + return f(std::function([w](A x) { + return w.o(w)(x); + })); + }) + }; + return r.o(r); +} + +typedef std::function Func; +typedef std::function FuncFunc; +FuncFunc almost_fac = [](Func f) { + return Func([f](int n) { + if (n <= 1) return 1; + return n * f(n - 1); + }); +}; + +FuncFunc almost_fib = [](Func f) { + return Func([f](int n) { + if (n <= 2) return 1; + return f(n - 1) + f(n - 2); + }); +}; + +int main() { + auto fib = fix(almost_fib); + auto fac = fix(almost_fac); + std::cout << "fib(10) = " << fib(10) << std::endl; + std::cout << "fac(10) = " << fac(10) << std::endl; + return 0; +} diff --git a/Task/Y-combinator/C/y-combinator.c b/Task/Y-combinator/C/y-combinator.c new file mode 100644 index 0000000000..4422a8fafd --- /dev/null +++ b/Task/Y-combinator/C/y-combinator.c @@ -0,0 +1,79 @@ +#include +#include + +/* func: our one and only data type; it holds either a pointer to + a function call, or an integer. Also carry a func pointer to + a potential parameter, to simulate closure */ +typedef struct func_t *func; +typedef struct func_t { + func (*func) (func, func), _; + int num; +} func_t; + +func new(func(*f)(func, func), func _) { + func x = malloc(sizeof(func_t)); + x->func = f; + x->_ = _; /* closure, sort of */ + x->num = 0; + return x; +} + +func call(func f, func g) { + return f->func(f, g); +} + +func Y(func(*f)(func, func)) { + func _(func x, func y) { return call(x->_, y); } + func_t __ = { _ }; + + func g = call(new(f, 0), &__); + g->_ = g; + return g; +} + +func num(int n) { + func x = new(0, 0); + x->num = n; + return x; +} + +func fac(func f, func _null) { + func _(func self, func n) { + int nn = n->num; + return nn > 1 ? num(nn * call(self->_, num(nn - 1))->num) + : num(1); + } + + return new(_, f); +} + +func fib(func f, func _null) { + func _(func self, func n) { + int nn = n->num; + return nn > 1 + ? num( call(self->_, num(nn - 1))->num + + call(self->_, num(nn - 2))->num ) + : num(1); + } + + return new(_, f); +} + +void show(func n) { printf(" %d", n->num); } + +int main() { + int i; + func f = Y(fac); + printf("fac: "); + for (i = 1; i < 10; i++) + show( call(f, num(i)) ); + printf("\n"); + + f = Y(fib); + printf("fib: "); + for (i = 1; i < 10; i++) + show( call(f, num(i)) ); + printf("\n"); + + return 0; +} diff --git a/Task/Y-combinator/Clojure/y-combinator-1.clj b/Task/Y-combinator/Clojure/y-combinator-1.clj new file mode 100644 index 0000000000..188fadfca1 --- /dev/null +++ b/Task/Y-combinator/Clojure/y-combinator-1.clj @@ -0,0 +1,19 @@ +(defn Y [f] + ((fn [x] (x x)) + (fn [x] + (f (fn [& args] + (apply (x x) args)))))) + +(def fac + (fn [f] + (fn [n] + (if (zero? n) 1 (* n (f (dec n))))))) + +(def fib + (fn [f] + (fn [n] + (condp = n + 0 0 + 1 1 + (+ (f (dec n)) + (f (dec (dec n)))))))) diff --git a/Task/Y-combinator/Clojure/y-combinator-2.clj b/Task/Y-combinator/Clojure/y-combinator-2.clj new file mode 100644 index 0000000000..90b7df61e9 --- /dev/null +++ b/Task/Y-combinator/Clojure/y-combinator-2.clj @@ -0,0 +1,2 @@ +(defn Y [f] + (#(% %) #(f (fn [& args] (apply (% %) args))))) diff --git a/Task/Y-combinator/Common-Lisp/y-combinator.lisp b/Task/Y-combinator/Common-Lisp/y-combinator.lisp new file mode 100644 index 0000000000..44a1f8ebc0 --- /dev/null +++ b/Task/Y-combinator/Common-Lisp/y-combinator.lisp @@ -0,0 +1,25 @@ +(defun Y (f) + ((lambda (x) (funcall x x)) + (lambda (y) + (funcall f (lambda (&rest args) + (apply (funcall y y) args)))))) + +(defun fac (f) + (lambda (n) + (if (zerop n) + 1 + (* n (funcall f (1- n)))))) + +(defun fib (f) + (lambda (n) + (case n + (0 0) + (1 1) + (otherwise (+ (funcall f (- n 1)) + (funcall f (- n 2))))))) + +? ((mapcar (y #'fac) '(1 2 3 4 5 6 7 8 9 10)) +(1 2 6 24 120 720 5040 40320 362880 3628800)) + +? (mapcar (y #'fib) '(1 2 3 4 5 6 7 8 9 10)) +(1 1 2 3 5 8 13 21 34 55) diff --git a/Task/Y-combinator/D/y-combinator.d b/Task/Y-combinator/D/y-combinator.d new file mode 100644 index 0000000000..0104df5fd0 --- /dev/null +++ b/Task/Y-combinator/D/y-combinator.d @@ -0,0 +1,31 @@ +import std.stdio, std.traits, std.algorithm, std.range; + +auto Y(F)(F f) { + alias D = void delegate(); + alias Ret = ReturnType!(ParameterTypeTuple!F); + alias Args = ParameterTypeTuple!(ParameterTypeTuple!F); + + return ((Ret delegate(Args) delegate(D) x) => + x(cast(D)x))( + (D y) => + f((Args args) => + (cast(Ret delegate(Args))(cast(D delegate(D))y)(y))(args) + ) + ); +} + +void main() { // Demo code -------------------- + auto factorial = Y((int delegate(int) self) => + (int n) => 0 == n ? 1 : n * self(n - 1) + ); + + auto ackermann = Y((ulong delegate(ulong, ulong) self) => + (ulong m, ulong n) { + if (m == 0) return n + 1; + if (n == 0) return self(m - 1, 1); + return self(m - 1, self(m, n - 1)); + }); + + writeln("factorial: ", map!factorial(iota(10))); + writeln("ackermann(3, 5): ", ackermann(3, 5)); +} diff --git a/Task/Y-combinator/Delphi/y-combinator.delphi b/Task/Y-combinator/Delphi/y-combinator.delphi new file mode 100644 index 0000000000..5a133a58da --- /dev/null +++ b/Task/Y-combinator/Delphi/y-combinator.delphi @@ -0,0 +1,67 @@ +program Y; + +{$APPTYPE CONSOLE} + +uses + SysUtils; + +type + YCombinator = class sealed + class function Fix (F: TFunc, TFunc>): TFunc; static; + end; + + TRecursiveFuncWrapper = record // workaround required because of QC #101272 (http://qc.embarcadero.com/wc/qcmain.aspx?d=101272) + type + TRecursiveFunc = reference to function (R: TRecursiveFuncWrapper): TFunc; + var + O: TRecursiveFunc; + end; + +class function YCombinator.Fix (F: TFunc, TFunc>): TFunc; +var + R: TRecursiveFuncWrapper; +begin + R.O := function (W: TRecursiveFuncWrapper): TFunc + begin + Result := F (function (I: T): T + begin + Result := W.O (W) (I); + end); + end; + Result := R.O (R); +end; + + +type + IntFunc = TFunc; + +function AlmostFac (F: IntFunc): IntFunc; +begin + Result := function (N: Integer): Integer + begin + if N <= 1 then + Result := 1 + else + Result := N * F (N - 1); + end; +end; + +function AlmostFib (F: TFunc): TFunc; +begin + Result := function (N: Integer): Integer + begin + if N <= 2 then + Result := 1 + else + Result := F (N - 1) + F (N - 2); + end; +end; + +var + Fib, Fac: IntFunc; +begin + Fib := YCombinator.Fix (AlmostFib); + Fac := YCombinator.Fix (AlmostFac); + Writeln ('Fib(10) = ', Fib (10)); + Writeln ('Fac(10) = ', Fac (10)); +end. diff --git a/Task/Y-combinator/E/y-combinator-1.e b/Task/Y-combinator/E/y-combinator-1.e new file mode 100644 index 0000000000..f22c419527 --- /dev/null +++ b/Task/Y-combinator/E/y-combinator-1.e @@ -0,0 +1,3 @@ +def y := fn f { fn x { x(x) }(fn y { f(fn a { y(y)(a) }) }) } +def fac := fn f { fn n { if (n<2) {1} else { n*f(n-1) } }} +def fib := fn f { fn n { if (n == 0) {0} else if (n == 1) {1} else { f(n-1) + f(n-2) } }} diff --git a/Task/Y-combinator/E/y-combinator-2.e b/Task/Y-combinator/E/y-combinator-2.e new file mode 100644 index 0000000000..2fe7ebb891 --- /dev/null +++ b/Task/Y-combinator/E/y-combinator-2.e @@ -0,0 +1,6 @@ +? pragma.enable("accumulator") +? accum [] for i in 0..!10 { _.with(y(fac)(i)) } +[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] + +? accum [] for i in 0..!10 { _.with(y(fib)(i)) } +[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/Ela/y-combinator.ela b/Task/Y-combinator/Ela/y-combinator.ela new file mode 100644 index 0000000000..59a3f9fe2d --- /dev/null +++ b/Task/Y-combinator/Ela/y-combinator.ela @@ -0,0 +1,10 @@ +fix = \f -> (\x -> & f (x x)) (\x -> & f (x x)) + +fac _ 0 = 1 +fac f n = n * f (n - 1) + +fib _ 0 = 0 +fib _ 1 = 1 +fib f n = f (n - 1) + f (n - 2) + +(fix fac 12, fix fib 12) diff --git a/Task/Y-combinator/Erlang/y-combinator.erl b/Task/Y-combinator/Erlang/y-combinator.erl new file mode 100644 index 0000000000..939dc0d4ae --- /dev/null +++ b/Task/Y-combinator/Erlang/y-combinator.erl @@ -0,0 +1,15 @@ +Y = fun(M) -> (fun(X) -> X(X) end)(fun (F) -> M(fun(A) -> (F(F))(A) end) end) end. + +Fac = fun (F) -> + fun (0) -> 1; + (N) -> N * F(N-1) + end + end. +Fib = fun(F) -> + fun(0) -> 0; + (1) -> 1; + (N) -> F(N-1) + F(N-2) + end + end. +(Y(Fac))(5). %% 120 +(Y(Fib))(8). %% 21 diff --git a/Task/Y-combinator/Factor/y-combinator-1.factor b/Task/Y-combinator/Factor/y-combinator-1.factor new file mode 100644 index 0000000000..9d318ad8a3 --- /dev/null +++ b/Task/Y-combinator/Factor/y-combinator-1.factor @@ -0,0 +1,10 @@ +USING: fry kernel math ; +IN: rosettacode.Y +: Y ( quot -- quot ) + '[ [ dup call call ] curry @ ] dup call ; inline + +: almost-fac ( quot -- quot ) + '[ dup zero? [ drop 1 ] [ dup 1 - @ * ] if ] ; + +: almost-fib ( quot -- quot ) + '[ dup 2 >= [ 1 2 [ - @ ] bi-curry@ bi + ] when ] ; diff --git a/Task/Y-combinator/Factor/y-combinator-2.factor b/Task/Y-combinator/Factor/y-combinator-2.factor new file mode 100644 index 0000000000..0caf8fd127 --- /dev/null +++ b/Task/Y-combinator/Factor/y-combinator-2.factor @@ -0,0 +1,5 @@ +USING: kernel tools.test rosettacode.Y ; +IN: rosettacode.Y.tests + +[ 120 ] [ 5 [ almost-fac ] Y call ] unit-test +[ 8 ] [ 6 [ almost-fib ] Y call ] unit-test diff --git a/Task/Y-combinator/Falcon/y-combinator.falcon b/Task/Y-combinator/Falcon/y-combinator.falcon new file mode 100644 index 0000000000..5c6f2bbea5 --- /dev/null +++ b/Task/Y-combinator/Falcon/y-combinator.falcon @@ -0,0 +1,9 @@ +Y = { f => {x=> {n => f(x(x))(n)}} ({x=> {n => f(x(x))(n)}}) } +facStep = { f => {x => x < 1 ? 1 : x*f(x-1) }} +fibStep = { f => {x => x == 0 ? 0 : (x == 1 ? 1 : f(x-1) + f(x-2))}} + +YFac = Y(facStep) +YFib = Y(fibStep) + +> "Factorial 10: ", YFac(10) +> "Fibonacci 10: ", YFib(10) diff --git a/Task/Y-combinator/GAP/y-combinator.gap b/Task/Y-combinator/GAP/y-combinator.gap new file mode 100644 index 0000000000..317faa88d1 --- /dev/null +++ b/Task/Y-combinator/GAP/y-combinator.gap @@ -0,0 +1,35 @@ +Y := function(f) + local u; + u := x -> x(x); + return u(y -> f(a -> y(y)(a))); +end; + +fib := function(f) + local u; + u := function(n) + if n < 2 then + return n; + else + return f(n-1) + f(n-2); + fi; + end; + return u; +end; + +Y(fib)(10); +# 55 + +fac := function(f) + local u; + u := function(n) + if n < 2 then + return 1; + else + return n*f(n-1); + fi; + end; + return u; +end; + +Y(fac)(8); +# 40320 diff --git a/Task/Y-combinator/Genyris/y-combinator.genyris b/Task/Y-combinator/Genyris/y-combinator.genyris new file mode 100644 index 0000000000..c1676a4ed1 --- /dev/null +++ b/Task/Y-combinator/Genyris/y-combinator.genyris @@ -0,0 +1,19 @@ +def fac (f) + function (n) + if (equal? n 0) 1 + * n (f (- n 1)) +def fib (f) + function (n) + cond + (equal? n 0) 0 + (equal? n 1) 1 + else (+ (f (- n 1)) (f (- n 2))) + +def Y (f) + (function (x) (x x)) + function (y) + f + function (&rest args) (apply (y y) args) + +assertEqual ((Y fac) 5) 120 +assertEqual ((Y fib) 8) 21 diff --git a/Task/Y-combinator/Go/y-combinator.go b/Task/Y-combinator/Go/y-combinator.go new file mode 100644 index 0000000000..d8ce185ebb --- /dev/null +++ b/Task/Y-combinator/Go/y-combinator.go @@ -0,0 +1,41 @@ +package main + +import "fmt" + +type Func func(int) int +type FuncFunc func(Func) Func +type RecursiveFunc func (RecursiveFunc) Func + +func main() { + fac := fix(almost_fac) + fib := fix(almost_fib) + fmt.Println("fac(10) = ", fac(10)) + fmt.Println("fib(10) = ", fib(10)) +} + +func fix(f FuncFunc) Func { + g := func(r RecursiveFunc) Func { + return f(func(x int) int { + return r(r)(x) + }) + } + return g(g) +} + +func almost_fac(f Func) Func { + return func(x int) int { + if x <= 1 { + return 1 + } + return x * f(x-1) + } +} + +func almost_fib(f Func) Func { + return func(x int) int { + if x <= 2 { + return 1 + } + return f(x-1)+f(x-2) + } +} diff --git a/Task/Y-combinator/Groovy/y-combinator-1.groovy b/Task/Y-combinator/Groovy/y-combinator-1.groovy new file mode 100644 index 0000000000..fd5f5b1d08 --- /dev/null +++ b/Task/Y-combinator/Groovy/y-combinator-1.groovy @@ -0,0 +1,13 @@ +def Y = { le -> ({ f -> f(f) })({ f -> le { x -> f(f)(x) } }) } + +def factorial = Y { fac -> + { n -> n <= 2 ? n : n * fac(n - 1) } +} + +assert 2432902008176640000 == factorial(20G) + +def fib = Y { fibStar -> + { n -> n <= 1 ? n : fibStar(n - 1) + fibStar(n - 2) } +} + +assert fib(10) == 55 diff --git a/Task/Y-combinator/Groovy/y-combinator-2.groovy b/Task/Y-combinator/Groovy/y-combinator-2.groovy new file mode 100644 index 0000000000..86c5f110f5 --- /dev/null +++ b/Task/Y-combinator/Groovy/y-combinator-2.groovy @@ -0,0 +1,7 @@ +def Y = { le -> ({ f -> f(f) })({ f -> le { Object[] args -> f(f)(*args) } }) } + +def mul = Y { mulStar -> { a, b -> a ? b + mulStar(a - 1, b) : 0 } } + +1.upto(10) { + assert mul(it, 10) == it * 10 +} diff --git a/Task/Y-combinator/Haskell/y-combinator-1.hs b/Task/Y-combinator/Haskell/y-combinator-1.hs new file mode 100644 index 0000000000..166f51aebb --- /dev/null +++ b/Task/Y-combinator/Haskell/y-combinator-1.hs @@ -0,0 +1,15 @@ +newtype Mu a = Roll { unroll :: Mu a -> a } + +fix :: (a -> a) -> a +fix = \f -> (\x -> f (unroll x x)) $ Roll (\x -> f (unroll x x)) + +fac :: Integer -> Integer +fac = fix $ \f n -> if (n <= 0) then 1 else n * f (n-1) + +fibs :: [Integer] +fibs = fix $ \fbs -> 0 : 1 : fix zipP fbs (tail fbs) + where zipP f (x:xs) (y:ys) = x+y : f xs ys + +main = do + print $ map fac [1 .. 20] + print $ take 20 fibs diff --git a/Task/Y-combinator/Haskell/y-combinator-2.hs b/Task/Y-combinator/Haskell/y-combinator-2.hs new file mode 100644 index 0000000000..fad39f6b54 --- /dev/null +++ b/Task/Y-combinator/Haskell/y-combinator-2.hs @@ -0,0 +1,28 @@ +fix :: (a -> a) -> a +fix f = f (fix f) + +fac :: Integer -> Integer +fac' f n | n <= 0 = 1 + | otherwise = n * f (n-1) +fac = fix fac' + +-- a simple but wasteful exponential time definition: +fib :: Integer -> Integer +fib' f 0 = 0 +fib' f 1 = 1 +fib' f n = f (n-1) + f (n-2) +fib = fix fib' + +-- Or for far more efficiency, compute a lazy infinite list. This is +-- a Y-combinator version of: fibs = 0:1:zipWith (+) fibs (tail fibs) +fibs :: [Integer] +fibs' a = 0:1:(fix zipP a (tail a)) + where + zipP f (x:xs) (y:ys) = x+y : f xs ys +fibs = fix fibs' + +-- This code shows how the functions can be used: +main = do + print $ map fac [1 .. 20] + print $ map fib [0 .. 19] + print $ take 20 fibs diff --git a/Task/Y-combinator/J/y-combinator-1.j b/Task/Y-combinator/J/y-combinator-1.j new file mode 100644 index 0000000000..757cded197 --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-1.j @@ -0,0 +1 @@ +Y=. ((((&>)/)(1 : '(5!:5)<''x'''))(&([ 128!:2 ,&<)))f. diff --git a/Task/Y-combinator/J/y-combinator-2.j b/Task/Y-combinator/J/y-combinator-2.j new file mode 100644 index 0000000000..fe0b2408ac --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-2.j @@ -0,0 +1,11 @@ + u=. [ NB. Function (left) + n=. ] NB. Argument (right) + sr=. [ 128!:2 ,&< NB. Self referring + + fac=. (1:`(n * u sr n - 1:)) @. (0: < n) + fac f. Y 10 +3628800 + + Fib=. ((u sr n - 2:) + u sr n - 1:) ^: (1: < n) + Fib f. Y 10 +55 diff --git a/Task/Y-combinator/J/y-combinator-3.j b/Task/Y-combinator/J/y-combinator-3.j new file mode 100644 index 0000000000..8690a20540 --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-3.j @@ -0,0 +1,9 @@ + fac f. Y NB. Showing the stateless recursive factorial function... +'1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0: < ])&>/'&([ 128!:2 ,&<) + fac f. NB. Showing the stateless factorial step... +1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0: < ]) + + Fib f. Y NB. Showing the stateless recursive Fibonacci function... +'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1: < ])&>/'&([ 128!:2 ,&<) + Fib f. NB. Showing the stateless Fibonacci step... +(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1: < ]) diff --git a/Task/Y-combinator/J/y-combinator-4.j b/Task/Y-combinator/J/y-combinator-4.j new file mode 100644 index 0000000000..f6d6b60d3d --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-4.j @@ -0,0 +1,4 @@ +sr=. [ 128!:2 ,&< NB. Self referring +lw=. '(5!:5)<''x''' (1 :) NB. Linear representation of a word +Y=. (&>)/lw(&sr) f. +Y=. 'Y'f. NB. Fixing it diff --git a/Task/Y-combinator/J/y-combinator-5.j b/Task/Y-combinator/J/y-combinator-5.j new file mode 100644 index 0000000000..73006241a6 --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-5.j @@ -0,0 +1,40 @@ +lambda=:3 :0 + if. 1=#;:y do. + 3 :(y,'=.y',LF,0 :0)`'' + else. + (,<#;:y) Defer (3 :('''',y,'''=.y',LF,0 :0))`'' + end. +) + +Defer=:2 :0 + if. (_1 {:: m) <: #m do. + v |. y;_1 }. m + else. + (y;m) Defer v`'' + end. +) + +recursivelY=: lambda 'g recur x' + (g`:6 recur`:6 recur)`:6 x +) + +sivelY=: lambda 'g recur' + (recursivelY`:6 g)`:6 recur +) + +Y=: lambda 'g' + recur=. sivelY`:6 g + recur`:6 recur +) + +almost_factorial=: lambda 'f n' + if. 0 >: n do. 1 + else. n * f`:6 n-1 end. +) + +almost_fibonacci=: lambda 'f n' + if. 2 > n do. n + else. (f`:6 n-1) + f`:6 n-2 end. +) + +Ev=: `:6 diff --git a/Task/Y-combinator/J/y-combinator-6.j b/Task/Y-combinator/J/y-combinator-6.j new file mode 100644 index 0000000000..63a39cdf14 --- /dev/null +++ b/Task/Y-combinator/J/y-combinator-6.j @@ -0,0 +1,6 @@ + (Y Ev almost_factorial)Ev 9 +362880 + (Y Ev almost_fibonacci)Ev 9 +34 + (Y Ev almost_fibonacci)Ev"0 i. 10 +0 1 1 2 3 5 8 13 21 34 diff --git a/Task/Y-combinator/Java/y-combinator-1.java b/Task/Y-combinator/Java/y-combinator-1.java new file mode 100644 index 0000000000..749a9a24b7 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-1.java @@ -0,0 +1,53 @@ +interface Function { + public B call(A x); +} + +public class YCombinator { + interface RecursiveFunc extends Function, F> { } + + public static Function fix(final Function, Function> f) { + RecursiveFunc> r = + new RecursiveFunc>() { + public Function call(final RecursiveFunc> w) { + return f.call(new Function() { + public B call(A x) { + return w.call(w).call(x); + } + }); + } + }; + return r.call(r); + } + + public static void main(String[] args) { + Function, Function> almost_fib = + new Function, Function>() { + public Function call(final Function f) { + return new Function() { + public Integer call(Integer n) { + if (n <= 2) return 1; + return f.call(n - 1) + f.call(n - 2); + } + }; + } + }; + + Function, Function> almost_fac = + new Function, Function>() { + public Function call(final Function f) { + return new Function() { + public Integer call(Integer n) { + if (n <= 1) return 1; + return n * f.call(n - 1); + } + }; + } + }; + + Function fib = fix(almost_fib); + Function fac = fix(almost_fac); + + System.out.println("fib(10) = " + fib.call(10)); + System.out.println("fac(10) = " + fac.call(10)); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-2.java b/Task/Y-combinator/Java/y-combinator-2.java new file mode 100644 index 0000000000..98d5efd886 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-2.java @@ -0,0 +1,23 @@ +import java.util.function.Function; + +public class YCombinator { + interface RecursiveFunc extends Function, F> { } + public static Function fix(Function, Function> f) { + RecursiveFunc> r = w -> f.apply(x -> w.apply(w).apply(x)); + return r.apply(r); + } + + public static void main(String[] args) { + Function fib = fix(f -> n -> { + if (n <= 2) return 1; + return f.apply(n - 1) + f.apply(n - 2); + }); + Function fac = fix(f -> n -> { + if (n <= 1) return 1; + return n * f.apply(n - 1); + }); + + System.out.println("fib(10) = " + fib.apply(10)); + System.out.println("fac(10) = " + fac.apply(10)); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-3.java b/Task/Y-combinator/Java/y-combinator-3.java new file mode 100644 index 0000000000..0e34a8230e --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-3.java @@ -0,0 +1,142 @@ +import java.math.BigInteger; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +interface Function { + public static final List NIL = Collections.emptyList(); + public OUTPUT call(List input); +} + +class Functions { + public static OUTPUT call( + Function f) { + return f.call(Function.NIL); + } + + public static OUTPUT call( + Function f, + INPUT input) { + return f.call(Collections.singletonList(input)); + } + + public static OUTPUT call( + Function f, + INPUT... input) { + return f.call(Arrays.asList(input)); + } + + public static OUTPUT call( + Function f, + Class type, + INPUT... input) { + List i = Collections.checkedList(new ArrayList(), type); + i.addAll(Arrays.asList(input)); + return f.call(i); + } + + public static T input( + List input, int index) { + return input.size() > index + ? input.get(index) + : null; + } + + public static Function compose( + final Function f + , final Function g) { + return new Function() { + @Override + public OUTPUT call(List input) { + return f.call(Collections.singletonList(g.call(input))); + } + }; + } + + public static Function y( + final Function, Function> f) { + return new Function() { + @Override + public OUTPUT call(List input) { + return Functions.call(f, new Function() { + @Override + public OUTPUT call(List input) { + return y(f).call(input); + } + }).call(input); + } + }; + } +} + +public class Y { + public static BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); + + public static void main(String[] args) { + Function fibonacci = Functions.y( + new Function, Function>() { + @Override + public Function call(List> input) { + final Function f = Functions.input(input, 0); + return new Function() { + @Override + public Number call(List input) { + BigInteger n = new BigInteger(Functions.input(input, 0).toString()); + if (n.compareTo(TWO) <= 0) return 1; + return new BigInteger(Functions.call(f, n.subtract(BigInteger.ONE)).toString()) + .add(new BigInteger(Functions.call(f, n.subtract(TWO)).toString())); + } + }; + } + } + ); + + Function factorial = Functions.y( + new Function, Function>() { + @Override + public Function call(List> input) { + final Function f = Functions.input(input, 0); + return new Function() { + @Override + public Number call(List input) { + BigInteger n = new BigInteger(Functions.input(input, 0).toString()); + if (n.compareTo(BigInteger.ONE) <= 0) return 1; + return n.multiply( + new BigInteger(Functions.call(f, n.subtract(BigInteger.ONE)).toString()) + ); + } + }; + } + } + ); + + Function ackermann = Functions.y( + new Function, Function>() { + @Override + public Function call(List> input) { + final Function f = Functions.input(input, 0); + return new Function() { + @Override + public Number call(List input) { + BigInteger m = new BigInteger(Functions.input(input, 0) + ""); + BigInteger n = new BigInteger(Functions.input(input, 1) + ""); + return m.equals(BigInteger.ZERO) + ? n.add(BigInteger.ONE) + : Functions.call(f, m.subtract(BigInteger.ONE), + n.equals(BigInteger.ZERO) + ? BigInteger.ONE + : Functions.call(f, m, n.subtract(BigInteger.ONE))); + } + }; + } + } + ); + + System.out.println("fibonacci(10) = " + Functions.call(fibonacci, 10)); + System.out.println("factorial(10) = " + Functions.call(factorial, 10)); + System.out.println("ackermann(3, 7) = " + Functions.call(ackermann, 3, 7)); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-4.java b/Task/Y-combinator/Java/y-combinator-4.java new file mode 100644 index 0000000000..f6d5b803e5 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-4.java @@ -0,0 +1,147 @@ +import java.math.BigInteger; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.BiFunction; +import java.util.stream.Collectors; + +@FunctionalInterface +interface VarargFunction { + public OUTPUT apply(List input); + + public default OUTPUT apply() { + return apply(Collections.emptyList()); + } + + public default OUTPUT apply(INPUT input) { + return apply(Collections.singletonList(input)); + } + + public default OUTPUT apply(INPUT input, INPUT input2) { + return apply(Arrays.asList(input, input2)); + } + + public default OUTPUT apply(INPUT input, INPUT input2, INPUT input3) { + return apply(Arrays.asList(input, input2, input3)); + } + + public default OUTPUT apply(Class type, Object... input) { + List i = Collections.checkedList(new ArrayList<>(), type); + for (Object object : input) { + i.add(type.cast(object)); + } + return apply(i); + } + + public default VarargFunction compose( + VarargFunction after) { + return input -> after.apply(apply(input)); + } + + public default Function toFunction() { + return input -> apply(input); + } + + public default BiFunction toBiFunction() { + return (input, input2) -> apply(input, input2); + } + + public default VarargFunction transformArguments(Function transformer) { + return input -> apply(input.parallelStream().map(transformer).collect(Collectors.toList())); + } +} + +@FunctionalInterface +interface SelfApplicable { + OUTPUT apply(SelfApplicable input); +} + +class Utils { + public static T input( List input, int index) { + return input.size() > index ? input.get(index) : null; + } + + /* Based on https://gist.github.com/aruld/3965968/#comment-604392 */ + + public static SelfApplicable, Function>, Function>> y(Class input, Class output) { + return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); + } + + public static Function, Function>, Function> fix(Class input, Class output) { + return y(input, output).apply(y(input, output)); + } + + public static SelfApplicable, VarargFunction>, VarargFunction>> yVararg(Class input, Class output) { + return y -> f -> x -> f.apply(y.apply(y).apply(f)).apply(x); + } + + public static Function, VarargFunction>, VarargFunction> fixVararg(Class input, Class output) { + return yVararg(input, output).apply(yVararg(input, output)); + } + + public static VarargFunction toVarargFunction(Function function) { + return input -> function.apply(Utils.input(input, 0)); + } + + public static VarargFunction toVarargFunction(BiFunction function) { + return input -> function.apply(Utils.input(input, 0), Utils.input(input, 1)); + } +} + +public class Y { + public static final BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); + + public static final Function toBigInteger = ((Function) Number::longValue).compose(BigInteger::valueOf); + + public static void main(String[] args) { + VarargFunction fibonacci = Utils.fixVararg(Number.class, Number.class).apply( + f -> Utils.toVarargFunction( + toBigInteger.compose( + n -> (n.compareTo(TWO) <= 0) ? 1 + : new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString()) + .add(new BigInteger(f.apply(n.subtract(TWO)).toString())) + ) + ) + ); + + VarargFunction factorial = Utils.fixVararg(Number.class, Number.class).apply( + f -> Utils.toVarargFunction( + toBigInteger.compose( + n -> (n.compareTo(BigInteger.ONE) <= 0) ? 1 + : n.multiply(new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString())) + ) + ) + ); + + VarargFunction ackermann = Utils.fixVararg(Number.class, Number.class).apply( + f -> Utils.toVarargFunction( + (BigInteger m, BigInteger n) -> m.equals(BigInteger.ZERO) ? n.add(BigInteger.ONE) + : f.apply(m.subtract(BigInteger.ONE), + n.equals(BigInteger.ZERO) + ? BigInteger.ONE + : f.apply(m, n.subtract(BigInteger.ONE))) + ).transformArguments(toBigInteger) + ); + + Map> functions = new HashMap<>(); + functions.put("fibonacci", fibonacci); + functions.put("factorial", factorial); + functions.put("ackermann", ackermann); + + Map, List> arguments = new HashMap<>(); + arguments.put(functions.get("fibonacci"), Arrays.asList(20)); + arguments.put(functions.get("factorial"), Arrays.asList(10)); + arguments.put(functions.get("ackermann"), Arrays.asList(3, 2)); + + functions.entrySet().parallelStream().map( + entry -> + entry.getKey() + arguments.get(entry.getValue()) + " = " + + entry.getValue().apply(arguments.get(entry.getValue())) + ).forEach(System.out::println); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-5.java b/Task/Y-combinator/Java/y-combinator-5.java new file mode 100644 index 0000000000..59f6175dd8 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-5.java @@ -0,0 +1,3 @@ +factorial[10] = 3628800 +ackermann[3, 2] = 29 +fibonacci[20] = 6765 diff --git a/Task/Y-combinator/JavaScript/y-combinator-1.js b/Task/Y-combinator/JavaScript/y-combinator-1.js new file mode 100644 index 0000000000..389c78bfa4 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-1.js @@ -0,0 +1,18 @@ +function Y(f) { + var g = f(function() { + return g.apply(this, arguments); + }); + return g; +} + +var fac = Y(function(f) { + return function(n) { + return n > 1 ? n * f(n - 1) : 1; + }; +}); + +var fib = Y(function(f) { + return function(n) { + return n > 1 ? f(n - 1) + f(n - 2) : n; + }; +}); diff --git a/Task/Y-combinator/JavaScript/y-combinator-2.js b/Task/Y-combinator/JavaScript/y-combinator-2.js new file mode 100644 index 0000000000..0341545078 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-2.js @@ -0,0 +1,14 @@ +function Y(f) { + var g = f((function(h) { + return function() { + var g = f(h(h)); + return g.apply(this, arguments); + } + })(function(h) { + return function() { + var g = f(h(h)); + return g.apply(this, arguments); + } + })); + return g; +} diff --git a/Task/Y-combinator/JavaScript/y-combinator-3.js b/Task/Y-combinator/JavaScript/y-combinator-3.js new file mode 100644 index 0000000000..411c9ccda0 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-3.js @@ -0,0 +1,9 @@ +function Y(f) { + return (function(h) { + return h(h); + })(function(h) { + return f(function() { + return h(h).apply(this, arguments); + }); + }); +} diff --git a/Task/Y-combinator/JavaScript/y-combinator-4.js b/Task/Y-combinator/JavaScript/y-combinator-4.js new file mode 100644 index 0000000000..20ffe77061 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-4.js @@ -0,0 +1,13 @@ +function pseudoY(f) { + return function g() { + return f.apply(g, arguments); + }; +} + +var fac = pseudoY(function(n) { + return n > 1 ? n * this(n - 1) : 1; +}); + +var fib = pseudoY(function(n) { + return n > 1 ? this(n - 1) + this(n - 2) : n; +}); diff --git a/Task/Y-combinator/Joy/y-combinator.joy b/Task/Y-combinator/Joy/y-combinator.joy new file mode 100644 index 0000000000..72bfcd22a6 --- /dev/null +++ b/Task/Y-combinator/Joy/y-combinator.joy @@ -0,0 +1,3 @@ +DEFINE y == [dup cons] swap concat dup cons i; + + fac == [ [pop null] [pop succ] [[dup pred] dip i *] ifte ] y. diff --git a/Task/Y-combinator/Lua/y-combinator-1.lua b/Task/Y-combinator/Lua/y-combinator-1.lua new file mode 100644 index 0000000000..d326573a76 --- /dev/null +++ b/Task/Y-combinator/Lua/y-combinator-1.lua @@ -0,0 +1,5 @@ +Y = function (f) + return function(...) + return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...) + end +end diff --git a/Task/Y-combinator/Lua/y-combinator-2.lua b/Task/Y-combinator/Lua/y-combinator-2.lua new file mode 100644 index 0000000000..764896deb6 --- /dev/null +++ b/Task/Y-combinator/Lua/y-combinator-2.lua @@ -0,0 +1,4 @@ +almostfactorial = function(f) return function(n) return n > 0 and n * f(n-1) or 1 end end +almostfibs = function(f) return function(n) return n < 2 and n or f(n-1) + f(n-2) end end +factorial, fibs = Y(almostfactorial), Y(almostfibs) +print(factorial(7)) diff --git a/Task/Y-combinator/Maple/y-combinator.maple b/Task/Y-combinator/Maple/y-combinator.maple new file mode 100644 index 0000000000..1aa366ccbf --- /dev/null +++ b/Task/Y-combinator/Maple/y-combinator.maple @@ -0,0 +1,7 @@ +> Y:=f->(x->x(x))(g->f((()->g(g)(args)))): +> Yfac:=Y(f->(x->`if`(x<2,1,x*f(x-1)))): +> seq( Yfac( i ), i = 1 .. 10 ); + 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800 +> Yfib:=Y(f->(x->`if`(x<2,x,f(x-1)+f(x-2)))): +> seq( Yfib( i ), i = 1 .. 10 ); + 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 diff --git a/Task/Y-combinator/Mathematica/y-combinator.math b/Task/Y-combinator/Mathematica/y-combinator.math new file mode 100644 index 0000000000..48011ecca0 --- /dev/null +++ b/Task/Y-combinator/Mathematica/y-combinator.math @@ -0,0 +1,3 @@ +Y = Function[f, #@# &@Function[x, f[x[x]@# &]]]; +factorial = Y@Function[f, If[# < 1, 1, # f[# - 1]] &]; +fibonacci = Y@Function[f, If[# < 2, #, f[# - 1] + f[# - 2]] &]; diff --git a/Task/Y-combinator/OCaml/y-combinator-1.ocaml b/Task/Y-combinator/OCaml/y-combinator-1.ocaml new file mode 100644 index 0000000000..799aad17b1 --- /dev/null +++ b/Task/Y-combinator/OCaml/y-combinator-1.ocaml @@ -0,0 +1 @@ +let fix f g = (fun x a -> f (x x) a) (fun x a -> f (x x) a) g diff --git a/Task/Y-combinator/OCaml/y-combinator-2.ocaml b/Task/Y-combinator/OCaml/y-combinator-2.ocaml new file mode 100644 index 0000000000..42006d4042 --- /dev/null +++ b/Task/Y-combinator/OCaml/y-combinator-2.ocaml @@ -0,0 +1 @@ +let fix f = (fun (`X x) -> f(x (`X x))) (`X(fun (`X x) y -> f(x (`X x)) y));; diff --git a/Task/Y-combinator/OCaml/y-combinator-3.ocaml b/Task/Y-combinator/OCaml/y-combinator-3.ocaml new file mode 100644 index 0000000000..86d6dcc106 --- /dev/null +++ b/Task/Y-combinator/OCaml/y-combinator-3.ocaml @@ -0,0 +1,27 @@ +type 'a mu = Roll of ('a mu -> 'a);; + +let unroll (Roll x) = x;; + +let fix f = (fun x a -> f (unroll x x) a) (Roll (fun x a -> f (unroll x x) a));; + +let fac f = function + 0 -> 1 + | n -> n * f (n-1) +;; + +let fib f = function + 0 -> 0 + | 1 -> 1 + | n -> f (n-1) + f (n-2) +;; + +(* val unroll : 'a mu -> 'a mu -> 'a = +val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = +val fac : (int -> int) -> int -> int = +val fib : (int -> int) -> int -> int = *) + +fix fac 5;; +(* - : int = 120 *) + +fix fib 8;; +(* - : int = 21 *) diff --git a/Task/Y-combinator/OCaml/y-combinator-4.ocaml b/Task/Y-combinator/OCaml/y-combinator-4.ocaml new file mode 100644 index 0000000000..fbd793c468 --- /dev/null +++ b/Task/Y-combinator/OCaml/y-combinator-4.ocaml @@ -0,0 +1 @@ +let rec fix f x = f (fix f) x;; diff --git a/Task/Y-combinator/Objective-C/y-combinator.m b/Task/Y-combinator/Objective-C/y-combinator.m new file mode 100644 index 0000000000..da491e0ed2 --- /dev/null +++ b/Task/Y-combinator/Objective-C/y-combinator.m @@ -0,0 +1,42 @@ +#import + +typedef int (^Func)(int); +typedef Func (^FuncFunc)(Func); +typedef Func (^RecursiveFunc)(id); // hide recursive typing behind dynamic typing + +Func fix (FuncFunc f) { + RecursiveFunc r = + ^(id y) { + RecursiveFunc w = y; // cast value back into desired type + return f(^(int x) { + return w(w)(x); + }); + }; + return r(r); +} + +int main (int argc, const char *argv[]) { + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + FuncFunc almost_fac = ^Func(Func f) { + return [[^(int n) { + if (n <= 1) return 1; + return n * f(n - 1); + } copy] autorelease]; + }; + + FuncFunc almost_fib = ^Func(Func f) { + return [[^(int n) { + if (n <= 2) return 1; + return f(n - 1) + f(n - 2); + } copy] autorelease]; + }; + + Func fib = fix(almost_fib); + Func fac = fix(almost_fac); + NSLog(@"fib(10) = %d", fib(10)); + NSLog(@"fac(10) = %d", fac(10)); + + [pool release]; + return 0; +} diff --git a/Task/Y-combinator/Order/y-combinator.order b/Task/Y-combinator/Order/y-combinator.order new file mode 100644 index 0000000000..dc1c021260 --- /dev/null +++ b/Task/Y-combinator/Order/y-combinator.order @@ -0,0 +1,19 @@ +#include + +#define ORDER_PP_DEF_8y \ +ORDER_PP_FN(8fn(8F, \ + 8let((8R, 8fn(8G, \ + 8ap(8F, 8fn(8A, 8ap(8ap(8G, 8G), 8A))))), \ + 8ap(8R, 8R)))) + +#define ORDER_PP_DEF_8fac \ +ORDER_PP_FN(8fn(8F, 8X, \ + 8if(8less_eq(8X, 0), 1, 8times(8X, 8ap(8F, 8minus(8X, 1)))))) + +#define ORDER_PP_DEF_8fib \ +ORDER_PP_FN(8fn(8F, 8X, \ + 8if(8less(8X, 2), 8X, 8plus(8ap(8F, 8minus(8X, 1)), \ + 8ap(8F, 8minus(8X, 2)))))) + +ORDER_PP(8to_lit(8ap(8y(8fac), 10))) // 3628800 +ORDER_PP(8ap(8y(8fib), 10)) // 55 diff --git a/Task/Y-combinator/Oz/y-combinator.oz b/Task/Y-combinator/Oz/y-combinator.oz new file mode 100644 index 0000000000..8dd5e954c1 --- /dev/null +++ b/Task/Y-combinator/Oz/y-combinator.oz @@ -0,0 +1,23 @@ +declare + Y = fun {$ F} + {fun {$ X} {X X} end + fun {$ X} {F fun {$ Z} {{X X} Z} end} end} + end + + Fac = {Y fun {$ F} + fun {$ N} + if N == 0 then 1 else N*{F N-1} end + end + end} + + Fib = {Y fun {$ F} + fun {$ N} + case N of 0 then 0 + [] 1 then 1 + else {F N-1} + {F N-2} + end + end + end} +in + {Show {Fac 5}} + {Show {Fib 8}} diff --git a/Task/Y-combinator/PHP/y-combinator-1.php b/Task/Y-combinator/PHP/y-combinator-1.php new file mode 100644 index 0000000000..bb4167f2bc --- /dev/null +++ b/Task/Y-combinator/PHP/y-combinator-1.php @@ -0,0 +1,22 @@ + diff --git a/Task/Y-combinator/PHP/y-combinator-2.php b/Task/Y-combinator/PHP/y-combinator-2.php new file mode 100644 index 0000000000..8e15134bd5 --- /dev/null +++ b/Task/Y-combinator/PHP/y-combinator-2.php @@ -0,0 +1,26 @@ + diff --git a/Task/Y-combinator/Perl-6/y-combinator-1.pl6 b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 new file mode 100644 index 0000000000..d3e1c43a4d --- /dev/null +++ b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 @@ -0,0 +1,5 @@ +sub Y ($f) { { .($_) }( -> $y { $f({ $y($y)($^arg) }) } ) } +sub fac ($f) { sub ($n) { $n < 2 ?? 1 !! $n * $f($n - 1) } } +say map(Y(&fac), ^10).perl; +sub fib ($f) { sub ($n) { $n < 2 ?? $n !! $f($n - 1) + $f($n - 2) } } +say map(Y(&fib), ^10).perl; diff --git a/Task/Y-combinator/Perl-6/y-combinator-2.pl6 b/Task/Y-combinator/Perl-6/y-combinator-2.pl6 new file mode 100644 index 0000000000..b841ab44e1 --- /dev/null +++ b/Task/Y-combinator/Perl-6/y-combinator-2.pl6 @@ -0,0 +1 @@ +say .(10) given sub (Int $x) { $x < 2 ?? 1 !! $x * &?ROUTINE($x - 1); } diff --git a/Task/Y-combinator/Perl/y-combinator.pl b/Task/Y-combinator/Perl/y-combinator.pl new file mode 100644 index 0000000000..0069d1615c --- /dev/null +++ b/Task/Y-combinator/Perl/y-combinator.pl @@ -0,0 +1,5 @@ +my $Y = sub { my ($f) = @_; sub {my ($x) = @_; $x->($x)}->(sub {my ($y) = @_; $f->(sub {$y->($y)->(@_)})})}; +my $fac = sub {my ($f) = @_; sub {my ($n) = @_; $n < 2 ? 1 : $n * $f->($n-1)}}; +print join(' ', map {$Y->($fac)->($_)} 0..9), "\n"; +my $fib = sub {my ($f) = @_; sub {my ($n) = @_; $n == 0 ? 0 : $n == 1 ? 1 : $f->($n-1) + $f->($n-2)}}; +print join(' ', map {$Y->($fib)->($_)} 0..9), "\n"; diff --git a/Task/Y-combinator/PicoLisp/y-combinator-1.l b/Task/Y-combinator/PicoLisp/y-combinator-1.l new file mode 100644 index 0000000000..70a531a15b --- /dev/null +++ b/Task/Y-combinator/PicoLisp/y-combinator-1.l @@ -0,0 +1,3 @@ +(de Y (F) + (let X (curry (F) (Y) (F (curry (Y) @ (pass (Y Y))))) + (X X) ) ) diff --git a/Task/Y-combinator/PicoLisp/y-combinator-2.l b/Task/Y-combinator/PicoLisp/y-combinator-2.l new file mode 100644 index 0000000000..e28830f282 --- /dev/null +++ b/Task/Y-combinator/PicoLisp/y-combinator-2.l @@ -0,0 +1,9 @@ +# Factorial +(de fact (F) + (curry (F) (N) + (if (=0 N) + 1 + (* N (F (dec N))) ) ) ) + +: ((Y fact) 6) +-> 720 diff --git a/Task/Y-combinator/PicoLisp/y-combinator-3.l b/Task/Y-combinator/PicoLisp/y-combinator-3.l new file mode 100644 index 0000000000..6fa9c8e54c --- /dev/null +++ b/Task/Y-combinator/PicoLisp/y-combinator-3.l @@ -0,0 +1,9 @@ +# Fibonacci +(de fibo (F) + (curry (F) (N) + (if (> 2 N) + 1 + (+ (F (dec N)) (F (- N 2))) ) ) ) + +: ((Y fibo) 22) +-> 28657 diff --git a/Task/Y-combinator/PicoLisp/y-combinator-4.l b/Task/Y-combinator/PicoLisp/y-combinator-4.l new file mode 100644 index 0000000000..ac023bf975 --- /dev/null +++ b/Task/Y-combinator/PicoLisp/y-combinator-4.l @@ -0,0 +1,10 @@ +# Ackermann +(de ack (F) + (curry (F) (X Y) + (cond + ((=0 X) (inc Y)) + ((=0 Y) (F (dec X) 1)) + (T (F (dec X) (F X (dec Y)))) ) ) ) + +: ((Y ack) 3 4) +-> 125 diff --git a/Task/Y-combinator/Pop11/y-combinator.pop11 b/Task/Y-combinator/Pop11/y-combinator.pop11 new file mode 100644 index 0000000000..887e61b51e --- /dev/null +++ b/Task/Y-combinator/Pop11/y-combinator.pop11 @@ -0,0 +1,22 @@ +define Y(f); + procedure (x); x(x) endprocedure( + procedure (y); + f(procedure(z); (y(y))(z) endprocedure) + endprocedure + ) +enddefine; + +define fac(h); + procedure (n); + if n = 0 then 1 else n * h(n - 1) endif + endprocedure +enddefine; + +define fib(h); + procedure (n); + if n < 2 then 1 else h(n - 1) + h(n - 2) endif + endprocedure +enddefine; + +Y(fac)(5) => +Y(fib)(5) => diff --git a/Task/Y-combinator/PostScript/y-combinator.ps b/Task/Y-combinator/PostScript/y-combinator.ps new file mode 100644 index 0000000000..d7b7f83b2a --- /dev/null +++ b/Task/Y-combinator/PostScript/y-combinator.ps @@ -0,0 +1,8 @@ +y { + {dup cons} exch concat dup cons i +}. + +/fac { + { {pop zero?} {pop succ} {{dup pred} dip i *} ifte } + y +}. diff --git a/Task/Y-combinator/PowerShell/y-combinator.psh b/Task/Y-combinator/PowerShell/y-combinator.psh new file mode 100644 index 0000000000..3ae2f5dd4c --- /dev/null +++ b/Task/Y-combinator/PowerShell/y-combinator.psh @@ -0,0 +1,51 @@ +$fac = { + param([ScriptBlock] $f) + invoke-expression @" + { + param([int] `$n) + if (`$n -le 0) {1} + else {`$n * {$f}.InvokeReturnAsIs(`$n - 1)} + } +"@ + } + +$fib = { + param([ScriptBlock] $f) + invoke-expression @" + { + param([int] `$n) + switch (`$n) + { + 0 {1} + 1 {1} + default {{$f}.InvokeReturnAsIs(`$n-1)+{$f}.InvokeReturnAsIs(`$n-2)} + } + } +"@ +} + +$Z = { + param([ScriptBlock] $f) + invoke-expression @" + { + param([ScriptBlock] `$x) + {$f}.InvokeReturnAsIs(`$(invoke-expression @`" + { + param(```$y) + {`$x}.InvokeReturnAsIs({`$x}).InvokeReturnAsIs(```$y) + } +`"@)) + }.InvokeReturnAsIs({ + param([ScriptBlock] `$x) + {$f}.InvokeReturnAsIs(`$(invoke-expression @`" + { + param(```$y) + {`$x}.InvokeReturnAsIs({`$x}).InvokeReturnAsIs(```$y) + } +`"@)) + }) +"@ +} + +$Z.InvokeReturnAsIs($fac).InvokeReturnAsIs(5) +$Z.InvokeReturnAsIs($fib).InvokeReturnAsIs(5) diff --git a/Task/Y-combinator/Prolog/y-combinator.pro b/Task/Y-combinator/Prolog/y-combinator.pro new file mode 100644 index 0000000000..9477a7667c --- /dev/null +++ b/Task/Y-combinator/Prolog/y-combinator.pro @@ -0,0 +1,32 @@ +:- use_module(lambda). + +% The Y combinator +y(P, Arg, R) :- + Pred = P +\Nb2^F2^call(P,Nb2,F2,P), + call(Pred, Arg, R). + + +test_y_combinator :- + % code for Fibonacci function + Fib = \NFib^RFib^RFibr1^(NFib < 2 -> + RFib = NFib + ; + NFib1 is NFib - 1, + NFib2 is NFib - 2, + call(RFibr1,NFib1,RFib1,RFibr1), + call(RFibr1,NFib2,RFib2,RFibr1), + RFib is RFib1 + RFib2 + ), + + y(Fib, 10, FR), format('Fib(~w) = ~w~n', [10, FR]), + + % code for Factorial function + Fact = \NFact^RFact^RFactr1^(NFact = 1 -> + RFact = NFact + ; + NFact1 is NFact - 1, + call(RFactr1,NFact1,RFact1,RFactr1), + RFact is NFact * RFact1 + ), + + y(Fact, 10, FF), format('Fact(~w) = ~w~n', [10, FF]). diff --git a/Task/Y-combinator/Python/y-combinator.py b/Task/Y-combinator/Python/y-combinator.py new file mode 100644 index 0000000000..72a0a6c144 --- /dev/null +++ b/Task/Y-combinator/Python/y-combinator.py @@ -0,0 +1,7 @@ +>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) +>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) +>>> [ Y(fac)(i) for i in range(10) ] +[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] +>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) +>>> [ Y(fib)(i) for i in range(10) ] +[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/R/y-combinator-1.r b/Task/Y-combinator/R/y-combinator-1.r new file mode 100644 index 0000000000..d355b170fd --- /dev/null +++ b/Task/Y-combinator/R/y-combinator-1.r @@ -0,0 +1,3 @@ +Y <- function(f) { + (function(x) { (x)(x) })( function(y) { f( (function(a) {y(y)})(a) ) } ) +} diff --git a/Task/Y-combinator/R/y-combinator-2.r b/Task/Y-combinator/R/y-combinator-2.r new file mode 100644 index 0000000000..875df436bb --- /dev/null +++ b/Task/Y-combinator/R/y-combinator-2.r @@ -0,0 +1,17 @@ +fac <- function(f) { + function(n) { + if (n<2) + 1 + else + n*f(n-1) + } +} + +fib <- function(f) { + function(n) { + if (n <= 1) + n + else + f(n-1) + f(n-2) + } +} diff --git a/Task/Y-combinator/R/y-combinator-3.r b/Task/Y-combinator/R/y-combinator-3.r new file mode 100644 index 0000000000..5ea7ce779c --- /dev/null +++ b/Task/Y-combinator/R/y-combinator-3.r @@ -0,0 +1,2 @@ +for(i in 1:9) print(Y(fac)(i)) +for(i in 1:9) print(Y(fib)(i)) diff --git a/Task/Y-combinator/REBOL/y-combinator-1.rebol b/Task/Y-combinator/REBOL/y-combinator-1.rebol new file mode 100644 index 0000000000..28581775a8 --- /dev/null +++ b/Task/Y-combinator/REBOL/y-combinator-1.rebol @@ -0,0 +1 @@ +Y: closure [g] [do func [f] [f :f] closure [f] [g func [x] [do f :f :x]]] diff --git a/Task/Y-combinator/REBOL/y-combinator-2.rebol b/Task/Y-combinator/REBOL/y-combinator-2.rebol new file mode 100644 index 0000000000..8f8061e657 --- /dev/null +++ b/Task/Y-combinator/REBOL/y-combinator-2.rebol @@ -0,0 +1,2 @@ +fact*: closure [h] [func [n] [either n <= 1 [1] [n * h n - 1]]] +fact: Y :fact* diff --git a/Task/Y-combinator/REXX/y-combinator.rexx b/Task/Y-combinator/REXX/y-combinator.rexx new file mode 100644 index 0000000000..5e68608882 --- /dev/null +++ b/Task/Y-combinator/REXX/y-combinator.rexx @@ -0,0 +1,24 @@ +/*REXX program to implement a stateless Y combinator. */ +numeric digits 1000 /*allow big 'uns. */ + +say ' fib' Y(fib (50)) /*Fibonacci series*/ +say ' fib' Y(fib (12 11 10 9 8 7 6 5 4 3 2 1 0)) /*Fibonacci series*/ +say ' fact' Y(fact (60)) /*single fact. */ +say ' fact' Y(fact (0 1 2 3 4 5 6 7 8 9 10 11)) /*single fact. */ +say ' Dfact' Y(dfact (4 5 6 7 8 9 10 11 12 13)) /*double fact. */ +say ' Tfact' Y(tfact (4 5 6 7 8 9 10 11 12 13)) /*triple fact. */ +say ' Qfact' Y(qfact (4 5 6 7 8 40)) /*quadruple fact. */ +say ' length' Y(length (when for to where whenceforth)) /*lengths of words*/ +say 'reverse' Y(reverse (23 678 1007 45 MAS I MA)) /*reverses strings*/ +say ' trunc' Y(trunc (-7.0005 12 3.14159 6.4 78.999)) /*truncates numbs.*/ +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────subroutines─────────────────────────*/ + Y: lambda=; parse arg Y _; do j=1 for words(_); interpret , + 'lambda=lambda' Y'('word(_,j)')'; end; return lambda + fib: procedure; parse arg x; if x<2 then return x; s=0; a=0; b=1 + do j=2 to x; s=a+b; a=b; b=s; end; return s + dfact: procedure; arg x; !=1; do j=x to 2 by -2;!=!*j; end; return ! + tfact: procedure; arg x; !=1; do j=x to 2 by -3;!=!*j; end; return ! + qfact: procedure; arg x; !=1; do j=x to 2 by -4;!=!*j; end; return ! + fact: procedure; arg x; !=1; do j=2 to x ;!=!*j; end; return ! diff --git a/Task/Y-combinator/Ruby/y-combinator-1.rb b/Task/Y-combinator/Ruby/y-combinator-1.rb new file mode 100644 index 0000000000..bb5b22e3e1 --- /dev/null +++ b/Task/Y-combinator/Ruby/y-combinator-1.rb @@ -0,0 +1,14 @@ +irb(main):001:0> Y = lambda do |f| +irb(main):002:1* lambda {|g| g[g]}[lambda do |g| +irb(main):003:3* f[lambda {|*args| g[g][*args]}] +irb(main):004:3> end] +irb(main):005:1> end +=> # +irb(main):006:0> Fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} +=> # +irb(main):007:0> Array.new(10) {|i| Y[Fac][i]} +=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] +irb(main):008:0> Fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} +=> # +irb(main):009:0> Array.new(10) {|i| Y[Fib][i]} +=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/Ruby/y-combinator-2.rb b/Task/Y-combinator/Ruby/y-combinator-2.rb new file mode 100644 index 0000000000..13cc62fcfd --- /dev/null +++ b/Task/Y-combinator/Ruby/y-combinator-2.rb @@ -0,0 +1,13 @@ +def y(&f) + lambda do |g| + f.call {|*args| g[g][*args]} + end.tap {|g| break g[g]} +end + +Fac = y {|&f| lambda {|n| n < 2 ? 1 : n * f[n - 1]}} +Fib = y {|&f| lambda {|n| n < 2 ? n : f[n - 1] + f[n - 2]}} + +p Array.new(10) {|i| Fac[i]} +# => [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] +p Array.new(10) {|i| Fib[i]} +# => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/Scala/y-combinator-1.scala b/Task/Y-combinator/Scala/y-combinator-1.scala new file mode 100644 index 0000000000..949f954381 --- /dev/null +++ b/Task/Y-combinator/Scala/y-combinator-1.scala @@ -0,0 +1,7 @@ +def Y[A,B](f: (A=>B)=>(A=>B)) = { + case class W(wf: W=>A=>B) { + def apply(w: W) = wf(w) + } + val g: W=>A=>B = w => f(w(w))(_) + g(W(g)) +} diff --git a/Task/Y-combinator/Scala/y-combinator-2.scala b/Task/Y-combinator/Scala/y-combinator-2.scala new file mode 100644 index 0000000000..0fd2cd0255 --- /dev/null +++ b/Task/Y-combinator/Scala/y-combinator-2.scala @@ -0,0 +1,5 @@ +val fac = Y[Int, Int](f => i => if (i <= 0) 1 else f(i - 1) * i) +fac(6) //> res0: Int = 720 + +val fib = Y[Int, Int](f => i => if (i < 2) i else f(i - 1) + f(i - 2)) +fib(6) //> res1: Int = 8 diff --git a/Task/Y-combinator/Scheme/y-combinator.ss b/Task/Y-combinator/Scheme/y-combinator.ss new file mode 100644 index 0000000000..d8f1b529b5 --- /dev/null +++ b/Task/Y-combinator/Scheme/y-combinator.ss @@ -0,0 +1,27 @@ +(define Y + (lambda (f) + ((lambda (x) (x x)) + (lambda (g) + (f (lambda args (apply (g g) args))))))) + +(define fac + (Y + (lambda (f) + (lambda (x) + (if (< x 2) + 1 + (* x (f (- x 1)))))))) + +(define fib + (Y + (lambda (f) + (lambda (x) + (if (< x 2) + x + (+ (f (- x 1)) (f (- x 2)))))))) + +(display (fac 6)) +(newline) + +(display (fib 6)) +(newline) diff --git a/Task/Y-combinator/Slate/y-combinator.slate b/Task/Y-combinator/Slate/y-combinator.slate new file mode 100644 index 0000000000..939a70610e --- /dev/null +++ b/Task/Y-combinator/Slate/y-combinator.slate @@ -0,0 +1,3 @@ +Method traits define: #Y &builder: + [[| :f | [| :x | f applyWith: (x applyWith: x)] + applyWith: [| :x | f applyWith: (x applyWith: x)]]]. diff --git a/Task/Y-combinator/Smalltalk/y-combinator.st b/Task/Y-combinator/Smalltalk/y-combinator.st new file mode 100644 index 0000000000..58a26084b8 --- /dev/null +++ b/Task/Y-combinator/Smalltalk/y-combinator.st @@ -0,0 +1,9 @@ +Y := [:f| [:x| x value: x] value: [:g| f value: [:x| (g value: g) value: x] ] ]. + +fib := Y value: [:f| [:i| i <= 1 ifTrue: [i] ifFalse: [(f value: i-1) + (f value: i-2)] ] ]. + +(fib value: 10) displayNl. + +fact := Y value: [:f| [:i| i = 0 ifTrue: [1] ifFalse: [(f value: i-1) * i] ] ]. + +(fact value: 10) displayNl. diff --git a/Task/Y-combinator/Standard-ML/y-combinator.ml b/Task/Y-combinator/Standard-ML/y-combinator.ml new file mode 100644 index 0000000000..a394b04b07 --- /dev/null +++ b/Task/Y-combinator/Standard-ML/y-combinator.ml @@ -0,0 +1,21 @@ +- datatype 'a mu = Roll of ('a mu -> 'a) + fun unroll (Roll x) = x + + fun fix f = (fn x => fn a => f (unroll x x) a) (Roll (fn x => fn a => f (unroll x x) a)) + + fun fac f 0 = 1 + | fac f n = n * f (n-1) + + fun fib f 0 = 0 + | fib f 1 = 1 + | fib f n = f (n-1) + f (n-2) +; +datatype 'a mu = Roll of 'a mu -> 'a +val unroll = fn : 'a mu -> 'a mu -> 'a +val fix = fn : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b +val fac = fn : (int -> int) -> int -> int +val fib = fn : (int -> int) -> int -> int +- List.tabulate (10, fix fac); +val it = [1,1,2,6,24,120,720,5040,40320,362880] : int list +- List.tabulate (10, fix fib); +val it = [0,1,1,2,3,5,8,13,21,34] : int list diff --git a/Task/Y-combinator/Ursala/y-combinator-1.ursala b/Task/Y-combinator/Ursala/y-combinator-1.ursala new file mode 100644 index 0000000000..c0de78ec16 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-1.ursala @@ -0,0 +1,2 @@ +(r "f") "x" = "f"("f","x") +my_fix "h" = r ("f","x"). ("h" r "f") "x" diff --git a/Task/Y-combinator/Ursala/y-combinator-2.ursala b/Task/Y-combinator/Ursala/y-combinator-2.ursala new file mode 100644 index 0000000000..74ea23cb19 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-2.ursala @@ -0,0 +1 @@ +my_fix = //~&R+ ^|H\~&+ ; //~&R diff --git a/Task/Y-combinator/Ursala/y-combinator-3.ursala b/Task/Y-combinator/Ursala/y-combinator-3.ursala new file mode 100644 index 0000000000..d38d509579 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-3.ursala @@ -0,0 +1,3 @@ +#import nat + +fact = my_fix "f". ~&?\1! product^/~& "f"+ predecessor diff --git a/Task/Y-combinator/Ursala/y-combinator-4.ursala b/Task/Y-combinator/Ursala/y-combinator-4.ursala new file mode 100644 index 0000000000..5bca9cab01 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-4.ursala @@ -0,0 +1 @@ +#fix my_fix diff --git a/Task/Y-combinator/Ursala/y-combinator-5.ursala b/Task/Y-combinator/Ursala/y-combinator-5.ursala new file mode 100644 index 0000000000..7194ac81a5 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-5.ursala @@ -0,0 +1 @@ +fib = {0,1}?,fib* <1,2,3,4,5,6,7,8>) diff --git a/Task/Y-combinator/Ursala/y-combinator-7.ursala b/Task/Y-combinator/Ursala/y-combinator-7.ursala new file mode 100644 index 0000000000..af772da3f3 --- /dev/null +++ b/Task/Y-combinator/Ursala/y-combinator-7.ursala @@ -0,0 +1,5 @@ +#import sol + +#fix general_function_fixer 1 + +my_fix "h" = "h" my_fix "h" diff --git a/Task/Yahoo--search-interface/0DESCRIPTION b/Task/Yahoo--search-interface/0DESCRIPTION new file mode 100644 index 0000000000..0a46298f91 --- /dev/null +++ b/Task/Yahoo--search-interface/0DESCRIPTION @@ -0,0 +1,2 @@ +Create a class for searching Yahoo! results. +It must implement a '''Next Page''' method, and read URL, Title and Content from results. diff --git a/Task/Yahoo--search-interface/1META.yaml b/Task/Yahoo--search-interface/1META.yaml new file mode 100644 index 0000000000..7948000013 --- /dev/null +++ b/Task/Yahoo--search-interface/1META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Networking and Web Interaction +note: Programming environment operations diff --git a/Task/Yahoo--search-interface/AutoHotkey/yahoo--search-interface.ahk b/Task/Yahoo--search-interface/AutoHotkey/yahoo--search-interface.ahk new file mode 100644 index 0000000000..2f591c29be --- /dev/null +++ b/Task/Yahoo--search-interface/AutoHotkey/yahoo--search-interface.ahk @@ -0,0 +1,31 @@ +test: +yahooSearch("test", 1) +yahooSearch("test", 2) +return + +yahooSearch(query, page) +{ + global + start := ((page - 1) * 10) + 1 + filedelete, search.txt + urldownloadtofile, % "http://search.yahoo.com/search?p=" . query + . "&b=" . start, search.txt + fileread, content, search.txt + reg =
(.+?)
(.+?)
(.+?) + + index := found := 1 + while (found := regexmatch(content, reg, self, found + 1)) + { + msgbox % title%A_Index% := fix(self1) + content%A_Index% := fix(self2) + url%A_Index% := fix(self3) + } +} + +fix(url) +{ +if pos := instr(url, "") +StringLeft, url, url, pos - 1 +url := regexreplace(url, "<.*?>") +return url +} diff --git a/Task/Yahoo--search-interface/C-sharp/yahoo--search-interface.cs b/Task/Yahoo--search-interface/C-sharp/yahoo--search-interface.cs new file mode 100644 index 0000000000..f81faec8f0 --- /dev/null +++ b/Task/Yahoo--search-interface/C-sharp/yahoo--search-interface.cs @@ -0,0 +1,113 @@ +using System; +using System.Net; +using System.Text.RegularExpressions; +using System.Collections.Generic; + +class YahooSearch { + private string query; + private string content; + private int page; + + const string yahoo = "http://search.yahoo.com/search?"; + + public YahooSearch(string query) : this(query, 0) { } + + public YahooSearch(string query, int page) { + this.query = query; + this.page = page; + this.content = new WebClient() + .DownloadString( + string.Format(yahoo + "p={0}&b={1}", query, this.page * 10 + 1) + ); + } + + public YahooResult[] Results { + get { + List results = new List(); + + Func substringBefore = (str, before) => + { + int iHref = str.IndexOf(before); + return iHref < 0 ? "" : str.Substring(0, iHref); + }; + Func substringAfter = (str, after) => + { + int iHref = str.IndexOf(after); + return iHref < 0 ? "" : str.Substring(iHref + after.Length); + }; + Converter getText = p => + Regex.Replace(p, "<[^>]*>", x => ""); + + Regex rx = new Regex(@" +
  • +
    + +
    + (?'Abstract' .*?) + (?>
    ) + .*? + (?>
    ) +
  • ", + RegexOptions.IgnorePatternWhitespace + | RegexOptions.ExplicitCapture + ); + foreach (Match e in rx.Matches(this.content)) { + string rurl = getText(substringBefore(substringAfter( + e.Groups["LinkAttributes"].Value, @"href="""), @"""")); + string rtitle = getText(e.Groups["LinkText"].Value); + string rcontent = getText(e.Groups["Abstract"].Value); + + results.Add(new YahooResult(rurl, rtitle, rcontent)); + } + return results.ToArray(); + } + } + + public YahooSearch NextPage() { + return new YahooSearch(this.query, this.page + 1); + } + + public YahooSearch GetPage(int page) { + return new YahooSearch(this.query, page); + } +} + +class YahooResult { + public string URL { get; set; } + public string Title { get; set; } + public string Content { get; set; } + + public YahooResult(string url, string title, string content) { + this.URL = url; + this.Title = title; + this.Content = content; + } + + public override string ToString() + { + return string.Format("\nTitle: {0}\nLink: {1}\nText: {2}", + Title, URL, Content); + } +} + +// Usage: + +class Prog { + static void Main() { + foreach (int page in new[] { 0, 1 }) + { + YahooSearch x = new YahooSearch("test", page); + + foreach (YahooResult result in x.Results) + { + Console.WriteLine(result); + } + } + } +} diff --git a/Task/Yahoo--search-interface/GUISS/yahoo--search-interface.guiss b/Task/Yahoo--search-interface/GUISS/yahoo--search-interface.guiss new file mode 100644 index 0000000000..00517d2909 --- /dev/null +++ b/Task/Yahoo--search-interface/GUISS/yahoo--search-interface.guiss @@ -0,0 +1,2 @@ +Start,Programs,Applications,Mozilla Firefox,Inputbox:address bar>www.yahoo.co.uk, +Button:Go,Area:browser window,Inputbox:searchbox>elephants,Button:Search diff --git a/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-1.hs b/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-1.hs new file mode 100644 index 0000000000..d5521913e2 --- /dev/null +++ b/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-1.hs @@ -0,0 +1,105 @@ +import Network.HTTP +import Text.Parsec + +data YahooSearchItem = YahooSearchItem { + itemUrl, itemTitle, itemContent :: String } + +data YahooSearch = YahooSearch { + searchQuery :: String, + searchPage :: Int, + searchItems :: [YahooSearchItem] } + +-- URL for Yahoo! searches, without giving a page number +yahooUrl = "http://search.yahoo.com/search?p=" + +-- make an HTTP request and return a YahooSearch +yahoo :: String -> IO YahooSearch +yahoo q = simpleHTTP (getRequest $ yahooUrl ++ q) >>= + getResponseBody >>= return . YahooSearch q 1 . items + +-- get some results and return the next page of results +next :: YahooSearch -> IO YahooSearch +next (YahooSearch q p _) = + simpleHTTP (getRequest $ + -- add the page number to the search + yahooUrl ++ q ++ "&b=" ++ show (p + 1)) >>= + getResponseBody >>= return . YahooSearch q (p + 1) . items + +printResults :: YahooSearch -> IO () +printResults (YahooSearch q p items) = do + putStrLn $ "Showing Yahoo! search results for query: " ++ q + putStrLn $ "Page: " ++ show p + putChar '\n' + mapM_ printOne items + where + printOne (YahooSearchItem itemUrl itemTitle itemContent) = do + putStrLn $ "URL : " ++ itemUrl + putStrLn $ "Title : " ++ itemTitle + putStrLn $ "Abstr : " ++ itemContent + putChar '\n' + +urlTag, titleTag, contentTag1, contentTag2, ignoreTag, + ignoreText :: Parsec String () String + +-- parse a tag containing the URL of a search result +urlTag = do { string "'); + return url } + +-- the title comes after the URL tag, so parse it first, discard it +-- and get the title text +titleTag = do { urlTag; manyTill anyChar (try (string "")) } + +-- parse a tag containing the description of the search result +-- the tag can be named "sm-abs" or "abstr" +contentTag1 = do { string "
    "; + manyTill anyChar (try (string "
    ")) } + +contentTag2 = do { string "
    "; + manyTill anyChar (try (string "
    ")) } + +-- parse a tag and discard it +ignoreTag = do { char ('<'); manyTill anyChar (char '>'); + return "" } + +-- parse some text and discard it +ignoreText = do { many1 (noneOf "<"); return "" } + +-- return only non-empty strings +nonempty :: [String] -> Parsec String () [String] +nonempty xs = return [ x | x <- xs, not (null x) ] + +-- a template to parse a whole source file looking for items of the +-- same class +parseCategory x = do + res <- many x + eof + nonempty res + +urls, titles, contents :: Parsec String () [String] + +-- parse HTML source looking for URL tags of the search results +urls = parseCategory url where + url = (try urlTag) <|> ignoreTag <|> ignoreText + +-- parse HTML source looking for titles of the search results +titles = parseCategory title where + title = (try titleTag) <|> ignoreTag <|> ignoreText + +-- parse HTML source looking for descriptions of the search results +contents = parseCategory content where + content = (try contentTag1) <|> (try contentTag2) <|> + ignoreTag <|> ignoreText + +-- parse the HTML source three times looking for URL, title and +-- description of all search results and return them as a list of +-- YahooSearchItem +items :: String -> [YahooSearchItem] +items q = + let ignoreOrKeep = either (const []) id + us = ignoreOrKeep $ parse urls "" q + ts = ignoreOrKeep $ parse titles "" q + cs = ignoreOrKeep $ parse contents "" q + in [ YahooSearchItem { itemUrl = u, itemTitle = t, itemContent = c } | + (u, t, c) <- zip3 us ts cs ] diff --git a/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-2.hs b/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-2.hs new file mode 100644 index 0000000000..4ee201b181 --- /dev/null +++ b/Task/Yahoo--search-interface/Haskell/yahoo--search-interface-2.hs @@ -0,0 +1,43 @@ +link printf,strings + +procedure main() +YS := YahooSearch("rosettacode") +every 1 to 2 do { # 2 pages + YS.readnext() + YS.showinfo() + } +end + +class YahooSearch(urlpat,page,response) #: class for Yahoo Search + + method readnext() #: read the next page of search results + self.page +:= 1 # can't find as w|w/o self + readurl() + end + + method readurl() #: read the url + url := sprintf(self.urlpat,(self.page-1)*10+1) + m := open(url,"m") | stop("Unable to open : ",url) + every (self.response := "") ||:= |read(m) + close(m) + self.response := deletec(self.response,"\x00") # kill stray NULs + end + + method showinfo() #: show the info of interest + self.response ? repeat { + (tab(find("<")) & ="")+1) + title := tab(find("<")) & ="" + tab(find("<")) & =("
    " | "
    ") + abstr := tab(find("<")) & ="
    " + + printf("\nTitle : %i\n",title) + printf("URL : %i\n",url) + printf("Abstr : %i\n",abstr) + } + end + +initially(searchtext) #: initialize each instance + urlpat := sprintf("http://search.yahoo.com/search?p=%s&b=%%d",searchtext) + page := 0 +end diff --git a/Task/Yahoo--search-interface/Java/yahoo--search-interface.java b/Task/Yahoo--search-interface/Java/yahoo--search-interface.java new file mode 100644 index 0000000000..413d4c9449 --- /dev/null +++ b/Task/Yahoo--search-interface/Java/yahoo--search-interface.java @@ -0,0 +1,157 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +class YahooSearch { + private String query; + // Page number + private int page = 1; + // Regexp to look for the individual results in the returned page + private static final Pattern pattern = Pattern.compile( + "(.+?).*?
    (.+?)
    "); + + public YahooSearch(String query) { + this.query = query; + } + + public List search() throws MalformedURLException, URISyntaxException, IOException { + // Build the search string, starting with the Yahoo search URL, + // then appending the query and optionally the page number (if > 1) + StringBuilder searchUrl = new StringBuilder("http://search.yahoo.com/search?"); + searchUrl.append("p=").append(URLEncoder.encode(query, "UTF-8")); + if (page > 1) {searchUrl.append("&b=").append((page - 1) * 10 + 1);} + // Query the Yahoo search engine + URL url = new URL(searchUrl.toString()); + List result = new ArrayList(); + StringBuilder sb = new StringBuilder(); + // Get the search results using a buffered reader + BufferedReader in = null; + try { + in = new BufferedReader(new InputStreamReader(url.openStream())); + // Read the results line by line + String line = in.readLine(); + while (line != null) { + sb.append(line); + line = in.readLine(); + } + } + catch (IOException ioe) { + ioe.printStackTrace(); + } + finally { + try {in.close();} catch (Exception ignoreMe) {} + } + String searchResult = sb.toString(); + // Look for the individual results by matching the regexp pattern + Matcher matcher = pattern.matcher(searchResult); + while (matcher.find()) { + // Extract the result URL, title and excerpt + String resultUrl = URLDecoder.decode(matcher.group(1), "UTF-8"); + String resultTitle = matcher.group(2).replaceAll("", "").replaceAll("", ""); + String resultContent = matcher.group(3).replaceAll("", "").replaceAll("", ""); + // Create a new YahooResult and add to the list + result.add(new YahooResult(resultUrl, resultTitle, resultContent)); + } + return result; + } + + public List search(int page) throws MalformedURLException, URISyntaxException, IOException { + // Set the page number and search + this.page = page; + return search(); + } + + public List nextPage() throws MalformedURLException, URISyntaxException, IOException { + // Increment the page number and search + page++; + return search(); + } + + public List previousPage() throws MalformedURLException, URISyntaxException, IOException { + // Decrement the page number and search; if the page number is 1 return an empty list + if (page > 1) { + page--; + return search(); + } else return new ArrayList(); + } +} + +class YahooResult { + private URL url; + private String title; + private String content; + + public URL getUrl() { + return url; + } + + public void setUrl(URL url) { + this.url = url; + } + + public void setUrl(String url) throws MalformedURLException { + this.url = new URL(url); + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public YahooResult(URL url, String title, String content) { + setUrl(url); + setTitle(title); + setContent(content); + } + + public YahooResult(String url, String title, String content) throws MalformedURLException { + setUrl(url); + setTitle(title); + setContent(content); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (title != null) { + sb.append(",title=").append(title); + } + if (url != null) { + sb.append(",url=").append(url); + } + return sb.charAt(0) == ',' ? sb.substring(1) : sb.toString(); + } +} + +public class TestYahooSearch { + public static void main(String[] args) throws MalformedURLException, URISyntaxException, IOException { + // Create a new search + YahooSearch search = new YahooSearch("Rosetta code"); + // Get the search results + List results = search.search(); + // Show the search results + for (YahooResult result : results) { + System.out.println(result.toString()); + } + } +} diff --git a/Task/Yahoo--search-interface/Mathematica/yahoo--search-interface.math b/Task/Yahoo--search-interface/Mathematica/yahoo--search-interface.math new file mode 100644 index 0000000000..6edf32c9d8 --- /dev/null +++ b/Task/Yahoo--search-interface/Mathematica/yahoo--search-interface.math @@ -0,0 +1,25 @@ +Manipulate[ + Column[Flatten[ + StringCases[ + StringCases[ + URLFetch[ + "http://search.yahoo.com/search?p=" <> query <> "&b=" <> + ToString@page], ""], + "" ~~ + Shortest[title__] ~~ + "
    " | "
    " ~~ + Shortest[abstr__] ~~ "
    " :> + Column[{Hyperlink[Style[#[[1]], Larger], #[[2]]], #[[3]], + Style[#[[2]], Smaller]} &@ + StringReplace[{title, url, + abstr}, {"<" ~~ Shortest[__] ~~ ">" -> "", + "&#" ~~ n : DigitCharacter ... ~~ ";" :> + FromCharacterCode[FromDigits@n], "&" -> "&", + """ -> "\"", "<" -> "<", ">" -> ">"}]]], 1], + Spacings -> 2], {{input, "", "Yahoo!"}, + InputField[Dynamic@input, String] &}, {{query, ""}, + ControlType -> None}, {{page, 1}, ControlType -> None}, + Row[{Button["Search", page = 1; query = input], + Button["Prev", page -= 10, Enabled -> Dynamic[page >= 10]], + Button["Next", page += 10]}]] diff --git a/Task/Yahoo--search-interface/Oz/yahoo--search-interface.oz b/Task/Yahoo--search-interface/Oz/yahoo--search-interface.oz new file mode 100644 index 0000000000..42e28a5b2e --- /dev/null +++ b/Task/Yahoo--search-interface/Oz/yahoo--search-interface.oz @@ -0,0 +1,147 @@ +declare + [HTTPClient] = {Module.link ['x-ozlib://mesaros/net/HTTPClient.ozf']} + [StringX] = {Module.link ['x-oz://system/String.ozf']} + [Regex] = {Module.link ['x-oz://contrib/regex']} + + %% Displays page 1 and 3 of the search results. + %% The user can request and display more with context menu->Actions->Make Needed. + proc {ExampleUsage} + Pages = {YahooSearch "Rosetta code"} + in + {Inspector.configure widgetShowStrings true} + {ForAll {Nth Pages 1} Value.makeNeeded} + {ForAll {Nth Pages 3} Value.makeNeeded} + %% Display the infinite list of search result pages. + {Inspect Pages} + end + + %% Returns a lazy list of pages. + %% A page is a lazy list of entries like this: result(url:U title:T content:C). + fun {YahooSearch Query} + FetchURL = {CreateURLFetcher} + + fun {Page Nr} + StartResult = (Nr-1)*10+1 + %% only retrieve it when really needed + Doc = {Value.byNeed fun {$} + {FetchURL "http://search.yahoo.com/search" + ["p"#Query "b"#{Int.toString StartResult}]} + end} + RE = "" R1 R2} + Title = {Fix {Until "" R2 R3}} + {Const "
    " R3 R4} + choice + %% "enchanted" result? + {Const "
    " R4 R5} + {Until "
    " R5 R6 _} + [] %% result with links into document + {Const "
    " R4 R5} + {Until "
    " R5 R6 _} + [] %% PDF file + {Const "
    " R4 R5} + {Until "
    " R5 R6 _} + [] %% With Review + {Const "
    " R4 R5} + R6 = nil %% no nice abstract when a review is there + [] %% normal result + R6 = R4 + end + Abstract = + choice + {Const "
    " R6 R7} + {Fix {Until "
    " R7 _}} + [] {Const "
    " R6 R7} + {Fix {Until "
    " R7 _}} + [] "" + end + in + Root = result(url:Url title:Title content:Abstract) + end + in + {CondSelect {SearchOne Parse} 1 parseError} + end + + %% Result: contents of Xs until M is found. + %% Xs = {Append M Yr} + fun {Until M Xs ?Yr} + L R + in + {List.takeDrop Xs {Length M} L R} + if L == M then Yr = R nil + elsecase Xs of X|Xr then X|{Until M Xr Yr} + [] nil then Yr = nil nil + end + end + + %% Asserts that Xs starts with C. Returns the remainder in Ys. + proc {Const C Xs ?Ys} + {List.takeDrop Xs {Length C} C Ys} + end + + %% Assert that a quoted string follows. + %% Returns the unquoted string and binds Ys to the remainder of Xs. + fun {QuotedString &"|Xs ?Ys} + fun {Loop Xs Ys} + case Xs of &\\|&"|Xr then &\\|&"|{Loop Xr Ys} + [] &"|Xr then Ys = Xr nil + [] X|Xr then X|{Loop Xr Ys} + end + end + in + {Loop Xs Ys} + end + + %% Remove formatting tags. + fun {Fix Xs} + {Until "" + {FoldL ["" "" "" "" "..."] + fun {$ Ys Z} + {StringX.replace Ys Z ""} + end + Xs} + _} + end +in + {ExampleUsage} diff --git a/Task/Yahoo--search-interface/Perl/yahoo--search-interface.pl b/Task/Yahoo--search-interface/Perl/yahoo--search-interface.pl new file mode 100644 index 0000000000..aae62b8450 --- /dev/null +++ b/Task/Yahoo--search-interface/Perl/yahoo--search-interface.pl @@ -0,0 +1,68 @@ +package YahooSearch; + +use Encode; +use HTTP::Cookies; +use WWW::Mechanize; + +# --- Internals ------------------------------------------------- + +sub apply (&$) + {my $f = shift; local $_ = shift; $f->(); return $_;} + +# We construct a cookie to get 100 results per page and prevent +# "enhanced results". +my $search_prefs = 'v=1&n=100&sm=' . + apply {s/([^a-zA-Z0-9])/sprintf '%%%02X', ord $1/ge} + join '|', + map {'!' . $_} + qw(hsb Zq0 XbM sss dDO VFM RQh uZ0 Fxe yCl GP4 FZK yNC mEG niH); +my $cookies = HTTP::Cookies->new; +$cookies->set_cookie(0, 'sB', $search_prefs, '/', 'search.yahoo.com'); + +my $mech = new WWW::Mechanize + (cookie_jar => $cookies, + stack_depth => 0); + +sub read_page + {my ($next, $page, @results) = + ($mech->find_link(text => 'Next >')->url, + decode 'iso-8859-1', $mech->content); + while ($page =~ m + {

    #" + (.+?) + .+? +
    + (.+?)
    }xg) + {push @results, {url => $1, title => $2, content => $3}; + foreach ( @{$results[-1]}{qw(title content)} ) + {s/<.+?>//g; + $_ = encode 'utf8', $_;}} + return $next, \@results;} + +# --- Methods --------------------------------------------------- + +sub new + {my $invocant = shift; + my $class = ref($invocant) || $invocant; + $mech->get('http://search.yahoo.com/search?p=' . apply + {s/([^a-zA-Z0-9 ])/sprintf '%%%02X', ord $1/ge; + s/ /+/g;} + shift); + my ($next, $results) = read_page(); + return bless {link_to_next => $next, results => $results}, $class;} + +sub results + {@{shift()->{results}};} + +sub next_page + {my $invocant = shift; + my $next = $invocant->{link_to_next}; + unless ($next) + {$invocant->{results} = []; + return undef;} + $mech->get($next); + ($next, my $results) = read_page(); + $invocant->{link_to_next} = $next; + $invocant->{results} = $results; + return 1;} diff --git a/Task/Yahoo--search-interface/PicoLisp/yahoo--search-interface.l b/Task/Yahoo--search-interface/PicoLisp/yahoo--search-interface.l new file mode 100644 index 0000000000..39da06983f --- /dev/null +++ b/Task/Yahoo--search-interface/PicoLisp/yahoo--search-interface.l @@ -0,0 +1,25 @@ +(load "@lib/http.l") + +(de yahoo (Query Page) + (default Page 1) + (client "search.yahoo.com" 80 + (pack + "search?p=" (ht:Fmt Query) + "&b=" (inc (* 10 (dec Page))) ) + (make + (while (from "") + (link (till "<" T)) # Title + (from "class=\"abstr\"") + (from ">") + (link # Content + (pack + (make + (loop + (link (till "<" T)) + (T (eof)) + (T (= "" T))) + (char) ) ) ) ) ) ) ) ) ) ) diff --git a/Task/Yahoo--search-interface/Python/yahoo--search-interface.py b/Task/Yahoo--search-interface/Python/yahoo--search-interface.py new file mode 100644 index 0000000000..b96766e863 --- /dev/null +++ b/Task/Yahoo--search-interface/Python/yahoo--search-interface.py @@ -0,0 +1,45 @@ +import urllib +import re + +def fix(x): + p = re.compile(r'<[^<]*?>') + return p.sub('', x).replace('&', '&') + +class YahooSearch: + def __init__(self, query, page=1): + self.query = query + self.page = page + self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.page - 1) * 10 + 1)) + self.content = urllib.urlopen(self.url).read() + + def getresults(self): + self.results = [] + + for i in re.findall('(.+?)

    (.+?)
    .*?(.+?)', self.content): + + title = fix(i[0]) + content = fix(i[1]) + url = fix(i[2]) + + self.results.append(YahooResult(title, content, url)) + + return self.results + + def getnextpage(self): + return YahooSearch(self.query, self.page+1) + + search_results = property(fget=getresults) + nextpage = property(fget=getnextpage) + +class YahooResult: + def __init__(self,title,content,url): + self.title = title + self.content = content + self.url = url + +# Usage: + +x = YahooSearch("test") + +for result in x.search_results: + print result.title diff --git a/Task/Yahoo--search-interface/R/yahoo--search-interface.r b/Task/Yahoo--search-interface/R/yahoo--search-interface.r new file mode 100644 index 0000000000..3306946a27 --- /dev/null +++ b/Task/Yahoo--search-interface/R/yahoo--search-interface.r @@ -0,0 +1,90 @@ +YahooSearch <- function(query, page=1, .opts=list(), ignoreMarkUpErrors=TRUE) +{ + if(!require(RCurl) || !require(XML)) + { + stop("Could not load required packages") + } + + # Replace " " with "%20", etc + query <- curlEscape(query) + + # Retrieve page + b <- 10*(page-1)+1 + theurl <- paste("http://uk.search.yahoo.com/search?p=", + query, "&b=", b, sep="") + webpage <- getURL(theurl, .opts=.opts) + + # Save search for nextpage function + .Search <- list(query=query, page=page, .opts=.opts, + ignoreMarkUpErrors=ignoreMarkUpErrors) + assign(".Search", .Search, envir=globalenv()) + + # Parse HTML; retrieve results block + webpage <- readLines(tc <- textConnection(webpage)); close(tc) + if(ignoreMarkUpErrors) + { + pagetree <- htmlTreeParse(webpage, error=function(...){}) + } else + { + pagetree <- htmlTreeParse(webpage) + } + + + findbyattr <- function(x, id, type="id") + { + ids <- sapply(x, function(x) x$attributes[type]) + x[ids==id] + } + + body <- pagetree$children$html$children$body + bd <- findbyattr(body$children$div$children, "bd") + left <- findbyattr(bd$div$children$div$children, "left") + web <- findbyattr(left$div$children$div$children, "web") + resol <- web$div$children$ol + + #Get url, title, content from results + gettextfromnode <- function(x) + { + un <- unlist(x$children) + paste(un[grep("value", names(un))], collapse=" ") + } + + n <- length(resol) + results <- list() + length(results) <- n + for(i in 1:n) + { + mainlink <- resol[[i]]$children$div$children[1]$div$children$h3$children$a + url <- mainlink$attributes["href"] + title <- gettextfromnode(mainlink) + + contenttext <- findbyattr(resol[[i]]$children$div$children[2], "abstr", type="class") + if(length(contenttext)==0) + { + contenttext <- findbyattr(resol[[i]]$children$div$children[2]$div$children$div$children, + "sm-abs", type="class") + } + + content <- gettextfromnode(contenttext$div) + results[[i]] <- list(url=url, title=title, content=content) + } + names(results) <- as.character(seq(b, b+n-1)) + results +} + +nextpage <- function() +{ + if(exists(".Search", envir=globalenv())) + { + .Search <- get(".Search", envir=globalenv()) + .Search$page <- .Search$page + 1L + do.call(YahooSearch, .Search) + } else + { + message("No search has been performed yet") + } +} + +#Usage +YahooSearch("rosetta code") +nextpage() diff --git a/Task/Yahoo--search-interface/Ruby/yahoo--search-interface.rb b/Task/Yahoo--search-interface/Ruby/yahoo--search-interface.rb new file mode 100644 index 0000000000..12f2f3d759 --- /dev/null +++ b/Task/Yahoo--search-interface/Ruby/yahoo--search-interface.rb @@ -0,0 +1,63 @@ +require 'open-uri' +require 'hpricot' + +SearchResult = Struct.new(:url, :title, :content) + +class SearchYahoo + @@urlinfo = [nil, 'ca.search.yahoo.com', 80, '/search', nil, nil] + + def initialize(term) + @term = term + @page = 1 + @results = nil + @url = URI::HTTP.build(@@urlinfo) + end + + def next_result + if not @results + @results = [] + fetch_results + elsif @results.empty? + next_page + end + @results.shift + end + + def fetch_results + @url.query = URI.escape("p=%s&b=%d" % [@term, @page]) + doc = open(@url) { |f| Hpricot(f) } + parse_html(doc) + end + + def next_page + @page += 10 + fetch_results + end + + def parse_html(doc) + doc.search("div#main").search("div").each do |div| + next unless div.has_attribute?("class") and div.get_attribute("class").index("res") == 0 + result = SearchResult.new + div.search("a").each do |link| + next unless link.has_attribute?("class") and link.get_attribute("class") == "yschttl spt" + result.url = link.get_attribute("href") + result.title = link.inner_text + end + div.search("div").each do |abstract| + next unless abstract.has_attribute?("class") and abstract.get_attribute("class").index("abstr") + result.content = abstract.inner_text + end + @results << result + end + end +end + +s = SearchYahoo.new("test") +15.times do |i| + result = s.next_result + puts i+1 + puts result.title + puts result.url + puts result.content + puts +end diff --git a/Task/Yahoo--search-interface/Run-BASIC/yahoo--search-interface.run b/Task/Yahoo--search-interface/Run-BASIC/yahoo--search-interface.run new file mode 100644 index 0000000000..4ed24f5a02 --- /dev/null +++ b/Task/Yahoo--search-interface/Run-BASIC/yahoo--search-interface.run @@ -0,0 +1,38 @@ +'-------------------------------------------------------------------------- +' send this from the server to the clients browser +'-------------------------------------------------------------------------- +html "" +html "" +html "
    Yahoo Search
    Find" + textbox #find,findThis$,30 + +html "
    Page" + textbox #page,findPage$,2 + +html "
    " + button #s, "Search", [search] +html " " + button #ex, "Exit", [exit] + +html "
    " +wait + +'-------------------------------------------------------------------------- +' get search stuff from the clients browser +'-------------------------------------------------------------------------- +[search] +findThis$ = trim$(#find contents$()) +findPage$ = trim$(#page contents$()) +findPage = max(val(findPage$),1) ' must be at least 1 + +'-------------------------------------------------------------------------- +' sho page but keep user interface at the top by not clearing the page (cls) +' so they can change the search or page +' ------------------------------------------------------------------------- +url$ = "http://search.yahoo.com/search?p=";findThis$;"&b=";((findPage - 1) * 10) + 1 +html httpget$(url$) +wait + +[exit] +cls ' clear browser screen and get outta here +wait diff --git a/Task/Yahoo--search-interface/TXR/yahoo--search-interface.txr b/Task/Yahoo--search-interface/TXR/yahoo--search-interface.txr new file mode 100644 index 0000000000..aa0a7fde29 --- /dev/null +++ b/Task/Yahoo--search-interface/TXR/yahoo--search-interface.txr @@ -0,0 +1,22 @@ +#!/usr/bin/txr -f +@(next :args) +@(cases) +@ QUERY +@ PAGE +@(or) +@ (throw error "specify query and page# (from zero)") +@(end) +@(next `!wget -O - http://search.yahoo.com/search?p=@QUERY\&b=@{PAGE}1 2> /dev/null`) +@(all) +@ (coll)]+/>@TITLE@(end) +@(and) +@ (coll)
    @ABSTR
    @(end) +@(end) +@(output) +@ (repeat) +TITLE: @TITLE +URL: @URL +TEXT: @ABSTR +--- +@ (end) +@(end) diff --git a/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-1.tcl b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-1.tcl new file mode 100644 index 0000000000..de76dc0944 --- /dev/null +++ b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-1.tcl @@ -0,0 +1,38 @@ +package require http + +proc fix s { + string map {... "" "" "" "" "" ""} \ + [regsub ".*" $s ""] +} +proc YahooSearch {term {page 1}} { + # Build the (ugly) scraper URL + append re {(.+?)} + append re {
    (.+?)} + append re {
    (.+?)} + + # Perform the query; note that this handles special characters + # in the query term correctly + set q [http::formatQuery p $term b [expr {$page*10-9}]] + set token [http::geturl http://search.yahoo.com/search?$q] + set data [http::data $token] + http::cleanup $token + + # Assemble the results into a nice list + set results {} + foreach {- title content url} [regexp -all -inline $re $data] { + lappend results [fix $title] [fix $content] [fix $url] + } + + # set up the call for the next page + interp alias {} Nextpage {} YahooSearch $term [incr page] + + return $results +} + +# Usage: get the first two pages of results +foreach {title content url} [YahooSearch "test"] { + puts $title +} +foreach {title content url} [Nextpage] { + puts $title +} diff --git a/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-2.tcl b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-2.tcl new file mode 100644 index 0000000000..8aaf6948a1 --- /dev/null +++ b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-2.tcl @@ -0,0 +1,34 @@ +package require Tcl 8.6 + +oo::class create WebSearcher { + variable page term results + constructor searchTerm { + set page 0 + set term $searchTerm + my nextPage + } + # This next method *is* a very Tcl-ish way of doing iteration. + method for {titleVar contentsVar urlVar body} { + upvar 1 $titleVar t $contentsVar c $urlVar v + foreach {t c v} $results { + uplevel 1 $body + } + } + # Reuse the previous code for simplicity rather than writing it anew + # Of course, if we were serious about this, we'd put the code here properly + method nextPage {} { + set results [YahooSearch $term [incr page]] + return + } +} + +# How to use. Note the 'foreach' method use below; new "keywords" as methods! +set ytest [WebSearcher new "test"] +$ytest for title - url { + puts "\"$title\" : $url" +} +$ytest nextPage +$ytest for title - url { + puts "\"$title\" : $url" +} +$ytest delete ;# standard method that deletes the object diff --git a/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-3.tcl b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-3.tcl new file mode 100644 index 0000000000..b5dcad43bb --- /dev/null +++ b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-3.tcl @@ -0,0 +1,23 @@ +package require Tcl 8.6 + +proc yahoo! term { + coroutine yahoo![incr ::yahoo] apply {term { + yield [info coroutine] + while 1 { + set results [YahooSearch $term [incr step]] + if {[llength $results] == 0} { + return -code break + } + foreach {t c u} $results { + yield [dict create title $t content $c url $u] + } + } + }} $term +} + +# test by getting first fifty titles... +set it [yahoo! "test"] +for {set i 50} {$i>0} {incr i -1} { + puts [dict get [$it] title] + after 300 ;# Slow the code down... :-) +} diff --git a/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-4.tcl b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-4.tcl new file mode 100644 index 0000000000..efa1599d93 --- /dev/null +++ b/Task/Yahoo--search-interface/Tcl/yahoo--search-interface-4.tcl @@ -0,0 +1,114 @@ +package require Tcl 8.6 +package require http +package require htmlparse +package require textutil::adjust + +oo::class create yahoosearch { + + method search {s} { + my variable searchterm page baseurl + set searchterm $s + set page 1 + set baseurl {http://ca.search.yahoo.com/search} + } + + method getresults {} { + my variable state results current_data + set results [list] + set current_data [dict create] + set state looking_for_results + htmlparse::parse -cmd [list [self] html_parser_callback] [my gethtml] + } + + method nextpage {} { + my variable page + incr page 10 + my getresults + } + + method nextresult {} { + my variable results page + if { ! [info exists results]} { + my getresults + } elseif {[llength $results] == 0} { + my nextpage + } + set results [lassign $results result] + return $result + } + + method gethtml {} { + my variable searchterm page baseurl + set url [format {%s?%s} $baseurl [::http::formatQuery p $searchterm b $page]] + set response [http::geturl $url] + set html [http::data $response] + http::cleanup $response + return $html + } + + method html_parser_callback {tag slash param textBehindTheTag} { + my variable state results current_data + switch -exact -- $state { + looking_for_results { + if {$tag eq "div" && [string first {id="main"} $param] != -1} { + set state ready + } + } + ready { + if {($tag eq "div" && [string first {class="res} $param] != -1) || + ($tag eq "html" && $slash eq "/") + } { #" -- unbalanced quote disturbs syntax highlighting + if {[dict size $current_data] > 0} {lappend results $current_data} + set current_data [dict create] + set state getting_url + } + } + getting_url { + if {$tag eq "a" && [string match "*yschttl spt*" $param]} { + if {[regexp {href="(.+?)"} $param - url]} { + dict set current_data url $url + } else { + dict set current_data url "no href in tag params: '$param'" + } + dict set current_data title $textBehindTheTag + set state getting_title + } + } + getting_title { + if {$tag eq "a" && $slash eq "/"} { + set state looking_for_abstract + } else { + dict append current_data title $textBehindTheTag + } + } + looking_for_abstract { + if {$tag eq "span" && [string first {class="url} $param] != -1} { + set state ready + } elseif {$tag eq "div" && [string first {class="abstr} $param] != -1} { + dict set current_data abstract $textBehindTheTag + set state getting_abstract + } + } + getting_abstract { + if {$tag eq "div" && $slash eq "/"} { + set state ready + } else { + dict append current_data abstract $textBehindTheTag + } + } + } + } +} + +yahoosearch create searcher +searcher search "search text here" + +for {set x 1} {$x <= 15} {incr x} { + set result [searcher nextresult] + dict with result { + puts $title + puts $url + puts [textutil::adjust::indent [textutil::adjust::adjust $abstract] " "] + puts "" + } +} diff --git a/Task/Yin-and-yang/0DESCRIPTION b/Task/Yin-and-yang/0DESCRIPTION new file mode 100644 index 0000000000..24dcba4133 --- /dev/null +++ b/Task/Yin-and-yang/0DESCRIPTION @@ -0,0 +1,3 @@ +Create a function that given a variable representing size, generates a [[wp:File:Yin_and_Yang.svg|Yin and yang]] also known as a [[wp:Taijitu|Taijitu]] symbol scaled to that size. + +Generate and display the symbol generated for two different (small) sizes. diff --git a/Task/Yin-and-yang/ALGOL-68/yin-and-yang.alg b/Task/Yin-and-yang/ALGOL-68/yin-and-yang.alg new file mode 100644 index 0000000000..6fc67e30ee --- /dev/null +++ b/Task/Yin-and-yang/ALGOL-68/yin-and-yang.alg @@ -0,0 +1,38 @@ +INT scale x=2, scale y=1; +CHAR black="#", white=".", clear=" "; + +PROC print yin yang = (REAL radius)VOID:( + + PROC in circle = (REAL centre x, centre y, radius, x, y)BOOL: + (x-centre x)**2+(y-centre y)**2 <= radius**2; + + PROC (REAL, REAL)BOOL + in big circle = in circle(0, 0, radius, , ), + in white semi circle = in circle(0, +radius/2, radius/2, , ), + in small black circle = in circle(0, +radius/2, radius/6, , ), + in black semi circle = in circle(0, -radius/2, radius/2, , ), + in small white circle = in circle(0, -radius/2, radius/6, , ); + + FOR sy FROM +ROUND(radius * scale y) BY -1 TO -ROUND(radius * scale y) DO + FOR sx FROM -ROUND(radius * scale x) TO +ROUND(radius * scale x) DO + REAL x=sx/scale x, y=sy/scale y; + print( + IF in big circle(x, y) THEN + IF in white semi circle(x, y) THEN + IF in small black circle(x, y) THEN black ELSE white FI + ELIF in black semi circle(x, y) THEN + IF in small white circle(x, y) THEN white ELSE black FI + ELIF x < 0 THEN white ELSE black FI + ELSE + clear + FI + ) + OD; + print(new line) + OD +); + +main:( + print yin yang(17); + print yin yang(8) +) diff --git a/Task/Yin-and-yang/Ada/yin-and-yang.ada b/Task/Yin-and-yang/Ada/yin-and-yang.ada new file mode 100644 index 0000000000..530af37b4f --- /dev/null +++ b/Task/Yin-and-yang/Ada/yin-and-yang.ada @@ -0,0 +1,32 @@ +with Glib; use Glib; +with Cairo; use Cairo; +with Cairo.Png; use Cairo.Png; +with Cairo.Image_Surface; use Cairo.Image_Surface; + +procedure YinYang is + subtype Dub is Glib.Gdouble; + + procedure Draw (C : Cairo_Context; x : Dub; y : Dub; r : Dub) is begin + Arc (C, x, y, r + 1.0, 1.571, 7.854); + Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C); + Arc_Negative (C, x, y - r / 2.0, r / 2.0, 1.571, 4.712); + Arc (C, x, y + r / 2.0, r / 2.0, 1.571, 4.712); + Arc_Negative (C, x, y, r, 4.712, 1.571); + Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C); + Arc (C, x, y - r / 2.0, r / 5.0, 1.571, 7.854); + Set_Source_Rgb (C, 0.0, 0.0, 0.0); Fill (C); + Arc (C, x, y + r / 2.0, r / 5.0, 1.571, 7.854); + Set_Source_Rgb (C, 1.0, 1.0, 1.0); Fill (C); + end Draw; + + Surface : Cairo_Surface; + Context : Cairo_Context; + Status : Cairo_Status; +begin + Surface := Create (Cairo_Format_ARGB32, 200, 200); + Context := Create (Surface); + Draw (Context, 120.0, 120.0, 75.0); + Draw (Context, 35.0, 35.0, 30.0); + Status := Write_To_Png (Surface, "YinYangAda.png"); + pragma Assert (Status = Cairo_Status_Success); +end YinYang; diff --git a/Task/Yin-and-yang/Asymptote/yin-and-yang.asymptote b/Task/Yin-and-yang/Asymptote/yin-and-yang.asymptote new file mode 100644 index 0000000000..c1b4233490 --- /dev/null +++ b/Task/Yin-and-yang/Asymptote/yin-and-yang.asymptote @@ -0,0 +1,18 @@ +unitsize(1 inch); + +fill(scale(6)*unitsquare, invisible); + +picture yinyang(pair center, real radius) { + picture p; + fill(p, unitcircle, white); + fill(p, arc(0, S, N) -- cycle, black); + fill(p, circle(N/2, 1/2), white); + fill(p, circle(S/2, 1/2), black); + fill(p, circle(N/2, 1/5), black); + fill(p, circle(S/2, 1/5), white); + draw(p, unitcircle, linewidth((1/32) * inch) + gray(0.5)); + return shift(center) * scale(radius) * p; +} + +add(yinyang((1 + 1/4, 4 + 3/4), 1)); +add(yinyang((3 + 3/4, 2 + 1/4), 2)); diff --git a/Task/Yin-and-yang/AutoHotkey/yin-and-yang.ahk b/Task/Yin-and-yang/AutoHotkey/yin-and-yang.ahk new file mode 100644 index 0000000000..a99528e1d2 --- /dev/null +++ b/Task/Yin-and-yang/AutoHotkey/yin-and-yang.ahk @@ -0,0 +1,37 @@ +Yin_and_Yang(50, 50, A_ScriptDir "\YinYang1.png") +Yin_and_Yang(300, 300,A_ScriptDir "\YinYang2.png") + +Yin_and_Yang(width, height, fileName + , color1=0xFFFFFFFF, color2=0xFF000000, outlineWidth=1){ + + pToken := gdip_Startup() + pBitmap := gdip_CreateBitmap(w := width, h := height) + w-=1, h-=1 + pGraphics:= gdip_GraphicsFromImage(pBitmap) + pBrushW := gdip_BrushCreateSolid(color1) + pBrushB := gdip_BrushCreateSolid(color2) + + gdip_SetSmoothingMode(pGraphics, 4) ; Antialiasing + + If (outlineWidth){ + pPen := gdip_CreatePen(0xFF000000, outlineWidth) + gdip_DrawEllipse(pGraphics, pPen, 0, 0, w, h) + gdip_DeletePen(pPen) + } + + gdip_FillPie(pGraphics, pBrushB, 0, 0, w, h, -90, 180) + gdip_FillPie(pGraphics, pBrushW, 0, 0, w, h, 90, 180) + gdip_FillEllipse(pGraphics, pBrushB, w//4, h//2, w//2, h//2) + gdip_FillEllipse(pGraphics, pBrushW, w//4, 0 , w//2, h//2) + gdip_FillEllipse(pGraphics, pBrushB, 5*w//12, h//6, w//6, h//6) + gdip_FillEllipse(pGraphics, pBrushW, 5*w//12, 4*h//6,w//6,h//6) + + r := gdip_SaveBitmapToFile(pBitmap, filename) + + ; cleanup: + gdip_DeleteBrush(pBrushW), gdip_deleteBrush(pBrushB) + gdip_DisposeImage(pBitmap) + gdip_DeleteGraphics(pGraphics) + gdip_Shutdown(pToken) + return r +} diff --git a/Task/Yin-and-yang/BBC-BASIC/yin-and-yang.bbc b/Task/Yin-and-yang/BBC-BASIC/yin-and-yang.bbc new file mode 100644 index 0000000000..1fa5264aa3 --- /dev/null +++ b/Task/Yin-and-yang/BBC-BASIC/yin-and-yang.bbc @@ -0,0 +1,16 @@ + PROCyinyang(200, 200, 100) + PROCyinyang(700, 400, 300) + END + + DEF PROCyinyang(xpos%, ypos%, size%) + CIRCLE xpos%, ypos%, size% + LINE xpos%, ypos%+size%, xpos%, ypos%-size% + FILL xpos%+size%/2, ypos% + CIRCLE FILL xpos%, ypos%-size%/2, size%/2+2 + GCOL 15 + CIRCLE FILL xpos%, ypos%+size%/2, size%/2+2 + CIRCLE FILL xpos%, ypos%-size%/2, size%/6+2 + GCOL 0 + CIRCLE FILL xpos%, ypos%+size%/2, size%/6+2 + CIRCLE xpos%, ypos%, size% + ENDPROC diff --git a/Task/Yin-and-yang/C/yin-and-yang.c b/Task/Yin-and-yang/C/yin-and-yang.c new file mode 100644 index 0000000000..c2dbc9c240 --- /dev/null +++ b/Task/Yin-and-yang/C/yin-and-yang.c @@ -0,0 +1,30 @@ +#include + +void draw_yinyang(int trans, double scale) +{ + printf("", + trans, trans, scale); +} + +int main() +{ printf( + "\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n"); + draw_yinyang(20, .05); + draw_yinyang(8, .02); + printf(""); + return 0; +} diff --git a/Task/Yin-and-yang/D/yin-and-yang.d b/Task/Yin-and-yang/D/yin-and-yang.d new file mode 100644 index 0000000000..05ec4e0b04 --- /dev/null +++ b/Task/Yin-and-yang/D/yin-and-yang.d @@ -0,0 +1,47 @@ +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/Yin-and-yang/DWScript/yin-and-yang.dwscript b/Task/Yin-and-yang/DWScript/yin-and-yang.dwscript new file mode 100644 index 0000000000..4880c254a6 --- /dev/null +++ b/Task/Yin-and-yang/DWScript/yin-and-yang.dwscript @@ -0,0 +1,77 @@ +type + TColorFuncX = function (x : Integer) : Integer; + +type + TSquareBoard = class + Scale : Integer; + Pix : array of array of Integer; + + constructor Create(aScale : Integer); + begin + Scale := aScale; + Pix := new Integer[aScale*12+1, aScale*12+1]; + end; + + method Print; + begin + var i, j : Integer; + for i:=0 to Pix.High do begin + for j:=0 to Pix.High do begin + case Pix[j, i] of + 1 : Print('.'); + 2 : Print('#'); + else + Print(' '); + end; + end; + PrintLn(''); + end; + end; + + method DrawCircle(cx, cy, cr : Integer; color : TColorFuncX); + begin + var rr := Sqr(cr*Scale); + var x, y : Integer; + for x := 0 to Pix.High do begin + for y := 0 to Pix.High do begin + if Sqr(x-cx*Scale)+Sqr(y-cy*Scale)<=rr then + Pix[x, y] := color(x); + end; + end; + end; + + method ColorHalf(x : Integer) : Integer; + begin + if (x<6*Scale) then + Result:=1 + else Result:=2; + end; + + method ColorYin(x : Integer) : Integer; + begin + Result:=2; + end; + + method ColorYang(x : Integer) : Integer; + begin + Result:=1; + end; + + method YinYang; + begin + DrawCircle(6, 6, 6, ColorHalf); + DrawCircle(6, 3, 3, ColorYang); + DrawCircle(6, 9, 3, ColorYin); + DrawCircle(6, 9, 1, ColorYang); + DrawCircle(6, 3, 1, ColorYin); + end; + + end; + +var sq := new TSquareBoard(2); +sq.YinYang; +sq.Print; + +sq := new TSquareBoard(1); +sq.YinYang; +sq.Print; diff --git a/Task/Yin-and-yang/Delphi/yin-and-yang.delphi b/Task/Yin-and-yang/Delphi/yin-and-yang.delphi new file mode 100644 index 0000000000..9d98e1d260 --- /dev/null +++ b/Task/Yin-and-yang/Delphi/yin-and-yang.delphi @@ -0,0 +1,28 @@ +procedure TForm1.ButtonCreateClick(Sender: TObject); +begin + DrawYinAndYang(StrToInt(EditSize.Text), Canvas, GetClientRect); +end; + +procedure DrawYinandYang(size: Word; DrawArea: TCanvas; R: TRect); +begin + DrawArea.Brush.Color := clGray; + DrawArea.FillRect(R); + DrawArea.Brush.Color := clwhite; + DrawArea.Pen.Color := clwhite; + DrawArea.Pie(10, 10, 10 + size, 10 + size, 10 + (size div 2), 10, 10 + (size div 2), 10 + size); + DrawArea.Brush.Color := clblack; + DrawArea.Pen.Color := clblack; + DrawArea.Pie(10, 10, 10 + size, 10 + size, 10 + (size div 2), 10 + size, 10 + (size div 2), 10); + DrawArea.Brush.Color := clwhite; + DrawArea.Pen.Color := clwhite; + DrawArea.Ellipse(10 + (size div 4), 10, 10 + 3 * (size div 4),10 + (size div 2)); + DrawArea.Brush.Color := clblack; + DrawArea.Pen.Color := clblack; + DrawArea.Ellipse(10 + (size div 4), 10 + (size div 2), 10 + 3 * (size div 4), 10 + size); + DrawArea.Brush.Color := clwhite; + DrawArea.Pen.Color := clwhite; + DrawArea.Ellipse(10 + 7 * (size div 16), 10 + 11 * (size div 16), 10 + 9 * (size div 16),10 + 13 * (size div 16)); + DrawArea.Brush.Color := clblack; + DrawArea.Pen.Color := clblack; + DrawArea.Ellipse(10 + 7 * (size div 16), 10 + 3 * (size div 16), 10 + 9 * (size div 16),10 + 5 * (size div 16)); +end; diff --git a/Task/Yin-and-yang/Go/yin-and-yang.go b/Task/Yin-and-yang/Go/yin-and-yang.go new file mode 100644 index 0000000000..47f7a38a20 --- /dev/null +++ b/Task/Yin-and-yang/Go/yin-and-yang.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "os" + "text/template" +) + +var tmpl = ` + + + + + + + +{{range .}} +{{end}} +` + +// structure specifies position and size to draw symbol +type xysz struct { + X, Y, Sz int +} + +// example data to specify drawing the symbol twice, +// with different position and size. +var yys = []xysz{ + {20, 20, 100}, + {140, 30, 60}, +} + +func main() { + xt := template.New("") + template.Must(xt.Parse(tmpl)) + f, err := os.Create("yy.svg") + if err != nil { + fmt.Println(err) + return + } + if err := xt.Execute(f, yys); err != nil { + fmt.Println(err) + } + f.Close() +} diff --git a/Task/Yin-and-yang/Haskell/yin-and-yang.hs b/Task/Yin-and-yang/Haskell/yin-and-yang.hs new file mode 100644 index 0000000000..5285924c43 --- /dev/null +++ b/Task/Yin-and-yang/Haskell/yin-and-yang.hs @@ -0,0 +1,18 @@ +{-# LANGUAGE NoMonomorphismRestriction #-} + +import Diagrams.Prelude +import Diagrams.Backend.Cairo.CmdLine + +yinyang = lw 0 $ + perim # lw 0.003 <> + torus white black # xform id <> + torus black white # xform negate <> + clipBy perim base + where perim = arc 0 (360 :: Deg) # scale (1/2) + torus c c' = circle (1/3) # fc c' <> circle 1 # fc c + xform f = translateY (f (1/4)) . scale (1/4) + base = rect (1/2) 1 # fc white ||| rect (1/2) 1 # fc black + +main = defaultMain $ + pad 1.1 $ + beside (2,-1) yinyang (yinyang # scale (1/4)) diff --git a/Task/Yin-and-yang/Icon/yin-and-yang.icon b/Task/Yin-and-yang/Icon/yin-and-yang.icon new file mode 100644 index 0000000000..6bcd647b85 --- /dev/null +++ b/Task/Yin-and-yang/Icon/yin-and-yang.icon @@ -0,0 +1,23 @@ +link graphics + +procedure main() +YinYang(100) +YinYang(40,"blue","yellow","white") +WDone() # quit on Q/q +end + +procedure YinYang(R,lhs,rhs,bg) # draw YinYang with radius of R pixels and ... +/lhs := "white" # left hand side +/rhs := "black" # right hand side +/bg := "grey" # background + +wsize := 2*(C := R + (margin := R/5)) + +W := WOpen("size="||wsize||","||wsize,"bg="||bg) | stop("Unable to open Window") +WAttrib(W,"fg="||lhs) & FillCircle(W,C,C,R,+dtor(90),dtor(180)) # main halves +WAttrib(W,"fg="||rhs) & FillCircle(W,C,C,R,-dtor(90),dtor(180)) +WAttrib(W,"fg="||lhs) & FillCircle(W,C,C+R/2,R/2,-dtor(90),dtor(180)) # sub halves +WAttrib(W,"fg="||rhs) & FillCircle(W,C,C-R/2,R/2,dtor(90),dtor(180)) +WAttrib(W,"fg="||lhs) & FillCircle(W,C,C-R/2,R/8) # dots +WAttrib(W,"fg="||rhs) & FillCircle(W,C,C+R/2,R/8) +end diff --git a/Task/Yin-and-yang/J/yin-and-yang-1.j b/Task/Yin-and-yang/J/yin-and-yang-1.j new file mode 100644 index 0000000000..ca420d26b3 --- /dev/null +++ b/Task/Yin-and-yang/J/yin-and-yang-1.j @@ -0,0 +1,14 @@ +yinyang=:3 :0 + radii=. y*1 3 6 + ranges=. i:each radii + squares=. ,"0/~each ranges + circles=. radii ([ >: +/"1&.:*:@])each squares + cInds=. ({:radii) +each circles #&(,/)each squares + + M=. ' *.' {~ circles (* 1 + 0 >: {:"1)&(_1&{::) squares + offset=. 3*y,0 + M=. '*' ((_2 {:: cInds) <@:+"1 offset)} M + M=. '.' ((_2 {:: cInds) <@:-"1 offset)} M + M=. '.' ((_3 {:: cInds) <@:+"1 offset)} M + M=. '*' ((_3 {:: cInds) <@:-"1 offset)} M +) diff --git a/Task/Yin-and-yang/J/yin-and-yang-2.j b/Task/Yin-and-yang/J/yin-and-yang-2.j new file mode 100644 index 0000000000..1edacbb75c --- /dev/null +++ b/Task/Yin-and-yang/J/yin-and-yang-2.j @@ -0,0 +1,40 @@ + yinyang 1 + . + ......* + ....*..** + ....***..** + .....*..*** + ........*** +.......****** + ...******** + ...**.***** + ..**...**** + ..**.**** + .****** + * + yinyang 2 + . + ........* + ...........** + .............** + ........*.....*** + ........***....**** + ........*****....**** + .........***....***** + ...........*.....****** + .................****** + ................******* + ...............******** +.............************ + ........*************** + .......**************** + ......***************** + ......*****.*********** + .....****...********* + ....****.....******** + ....****...******** + ...*****.******** + ..************* + ..*********** + .******** + * diff --git a/Task/Yin-and-yang/Java/yin-and-yang.java b/Task/Yin-and-yang/Java/yin-and-yang.java new file mode 100644 index 0000000000..a25f1008b0 --- /dev/null +++ b/Task/Yin-and-yang/Java/yin-and-yang.java @@ -0,0 +1,81 @@ +package org.rosettacode.yinandyang; + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.image.BufferedImage; +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JLabel; + +public class YinYangGenerator +{ + private final int size; + + public YinYangGenerator(final int size) + { + this.size = size; + } + + /** + * Draw a yin yang symbol on the given graphics context. + */ + public void drawYinYang(final Graphics graphics) + { + // Preserve the color for the caller + final Color colorSave = graphics.getColor(); + + graphics.setColor(Color.WHITE); + // Use fillOval to draw a filled in circle + graphics.fillOval(0, 0, size-1, size-1); + + graphics.setColor(Color.BLACK); + // Use fillArc to draw part of a filled in circle + graphics.fillArc(0, 0, size-1, size-1, 270, 180); + graphics.fillOval(size/4, size/2, size/2, size/2); + + graphics.setColor(Color.WHITE); + graphics.fillOval(size/4, 0, size/2, size/2); + graphics.fillOval(7*size/16, 11*size/16, size/8, size/8); + + graphics.setColor(Color.BLACK); + graphics.fillOval(7*size/16, 3*size/16, size/8, size/8); + // Use drawOval to draw an empty circle for the outside border + graphics.drawOval(0, 0, size-1, size-1); + + // Restore the color for the caller + graphics.setColor(colorSave); + } + + /** + * Create an image containing a yin yang symbol. + */ + public Image createImage(final Color bg) + { + // A BufferedImage creates the image in memory + final BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); + // Get the graphics object for the image; note in many + // applications you actually use Graphics2D for the + // additional API calls + final Graphics graphics = image.getGraphics(); + // Color in the background of the image + graphics.setColor(bg); + graphics.fillRect(0,0,size,size); + drawYinYang(graphics); + return image; + } + + public static void main(final String args[]) + { + final int size = Integer.parseInt(args[0]); + final YinYangGenerator generator = new YinYangGenerator(size); + + final JFrame frame = new JFrame("Yin Yang Generator"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + final Image yinYang = generator.createImage(frame.getBackground()); + // Use JLabel to display an image + frame.add(new JLabel(new ImageIcon(yinYang))); + frame.pack(); + frame.setVisible(true); + } +} diff --git a/Task/Yin-and-yang/Liberty-BASIC/yin-and-yang.liberty b/Task/Yin-and-yang/Liberty-BASIC/yin-and-yang.liberty new file mode 100644 index 0000000000..c023c7409b --- /dev/null +++ b/Task/Yin-and-yang/Liberty-BASIC/yin-and-yang.liberty @@ -0,0 +1,46 @@ + WindowWidth =410 + WindowHeight =440 + + open "Yin & Yang" for graphics_nf_nsb as #w + + #w "trapclose [quit]" + + call YinYang 200, 200, 200 + call YinYang 120, 50, 50 + + wait + + sub YinYang x, y, size + + #w "up ; goto "; x; " "; y + #w "backcolor black ; color black" + #w "down ; circlefilled "; size /2 + + #w "color 255 255 255 ; backcolor 255 255 255" + #w "up ; goto "; x -size /2; " "; y -size /2 + #w "down ; boxfilled "; x; " "; y +size /2 + + #w "up ; goto "; x; " "; y -size /4 + #w "down ; backcolor black ; color black ; circlefilled "; size /4 + #w "up ; goto "; x; " "; y -size /4 + #w "down ; backcolor white ; color white ; circlefilled "; size /12 + + #w "up ; goto "; x; " "; y +size /4 + #w "down ; backcolor white ; color white ; circlefilled "; size /4 + #w "up ; goto "; x; " "; y +size /4 + #w "down ; backcolor black ; color black ; circlefilled "; size /12 + + #w "up ; goto "; x; " "; y + #w "down ; color black ; circle "; size /2 + + #w "flush" + + end sub + + scan + + wait + + [quit] + close #w + end diff --git a/Task/Yin-and-yang/Logo/yin-and-yang.logo b/Task/Yin-and-yang/Logo/yin-and-yang.logo new file mode 100644 index 0000000000..7bd971c9ed --- /dev/null +++ b/Task/Yin-and-yang/Logo/yin-and-yang.logo @@ -0,0 +1,60 @@ +to taijitu :r + ; Draw a classic Taoist taijitu of the given radius centered on the current + ; turtle position. The "eyes" are placed along the turtle's heading, the + ; filled one in front, the open one behind. + + ; don't bother doing anything if the pen is not down + if not pendown? [stop] + + ; useful derivative values + localmake "r2 (ashift :r -1) + localmake "r4 (ashift :r2 -1) + localmake "r8 (ashift :r4 -1) + + ; remember where we started + localmake "start pos + + ; draw outer circle + pendown + arc 360 :r + + ; draw upper half of S + penup + forward :r2 + pendown + arc 180 :r2 + + ; and filled inner eye + arc 360 :r8 + fill + + ; draw lower half of S + penup + back :r + pendown + arc -180 :r2 + + ; other inner eye + arc 360 :r8 + + ; fill this half of the symbol + penup + forward :r4 + fill + + ; put the turtle back where it started + setpos :start + pendown +end + +; demo code to produce image at right +clearscreen +pendown +hideturtle +taijitu 100 +penup +forward 150 +left 90 +forward 150 +pendown +taijitu 75 diff --git a/Task/Yin-and-yang/Mathematica/yin-and-yang.math b/Task/Yin-and-yang/Mathematica/yin-and-yang.math new file mode 100644 index 0000000000..8f27a65802 --- /dev/null +++ b/Task/Yin-and-yang/Mathematica/yin-and-yang.math @@ -0,0 +1,5 @@ +YinYang[size_] := + Graphics[{{Circle[{0, 0}, 2]}, {Disk[{0, 0}, + 2, {90 Degree, -90 Degree}]}, {White, Disk[{0, 1}, 1]}, {Black, + Disk[{0, -1}, 1]}, {Black, Disk[{0, 1}, 1/4]}, {White, + Disk[{0, -1}, 1/4]}}, ImageSize -> 40 size] diff --git a/Task/Yin-and-yang/Metapost/yin-and-yang.metapost b/Task/Yin-and-yang/Metapost/yin-and-yang.metapost new file mode 100644 index 0000000000..f3625f8bf0 --- /dev/null +++ b/Task/Yin-and-yang/Metapost/yin-and-yang.metapost @@ -0,0 +1,24 @@ +vardef yinyang(expr u) = + picture pic_; + path p_; + p_ := halfcircle scaled 2u rotated -90 -- + halfcircle scaled u rotated 90 shifted (0, 1/2u) reflectedabout ((0,1), (0,-1)) -- + halfcircle scaled u rotated -270 shifted (0, -1/2u) -- cycle; + + pic_ := nullpicture; + addto pic_ contour fullcircle scaled 2u withcolor black; + addto pic_ contour p_ withcolor white; + addto pic_ doublepath p_ withcolor black withpen pencircle scaled 0.5mm; + addto pic_ contour fullcircle scaled 1/3u shifted (0, 1/2u) withcolor white; + addto pic_ contour fullcircle scaled 1/3u shifted (0, -1/2u) withcolor black; + pic_ +enddef; + +beginfig(1) + % let's create a Yin Yang symbol with a radius of 5cm + draw yinyang(5cm) shifted (5cm, 5cm); + % and another one, radius 2.5cm, rotated 180 degrees and translated + draw yinyang(2.5cm) rotated 180 shifted (11cm, 11cm); +endfig; + +end. diff --git a/Task/Yin-and-yang/NetRexx/yin-and-yang.netrexx b/Task/Yin-and-yang/NetRexx/yin-and-yang.netrexx new file mode 100644 index 0000000000..7be840a33a --- /dev/null +++ b/Task/Yin-and-yang/NetRexx/yin-and-yang.netrexx @@ -0,0 +1,31 @@ +/* NetRexx */ + +options replace format comments java crossref savelog symbols binary + +say "" +say "" +say "" +say " " +say " " +say " " +say " " +say " " +say " " + +say draw_yinyang(20, 0.05) +say draw_yinyang(8, 0.02) + +say "" + +return + +method draw_yinyang(trans = int, scale = double) inheritable static returns String + yy = String.format(" ", - + [Object Integer(trans), Integer(trans), Double(scale)]) + return yy diff --git a/Task/Yin-and-yang/OCaml/yin-and-yang.ocaml b/Task/Yin-and-yang/OCaml/yin-and-yang.ocaml new file mode 100644 index 0000000000..6be1a842a0 --- /dev/null +++ b/Task/Yin-and-yang/OCaml/yin-and-yang.ocaml @@ -0,0 +1,32 @@ +open Graphics + +let draw_yinyang x y radius black white = + let hr = radius / 2 in + let sr = radius / 6 in + set_color black; + set_line_width 6; + draw_circle x y radius; + set_line_width 0; + set_color black; + fill_arc x y radius radius 270 450; + set_color white; + fill_arc x y radius radius 90 270; + fill_arc x (y + hr) hr hr 270 450; + set_color black; + fill_arc x (y - hr) hr hr 90 270; + fill_circle x (y + hr) sr; + set_color white; + fill_circle x (y - hr) sr + +let () = + open_graph ""; + let width = size_x() + and height = size_y() in + set_color (rgb 200 200 200); + fill_rect 0 0 width height; + let w = width / 3 + and h = height / 3 in + let r = (min w h) / 3 in + draw_yinyang w (h*2) (r*2) black white; + draw_yinyang (w*2) h r blue magenta; + ignore(read_key()) diff --git a/Task/Yin-and-yang/POV-Ray/yin-and-yang.pov-ray b/Task/Yin-and-yang/POV-Ray/yin-and-yang.pov-ray new file mode 100644 index 0000000000..9ecad2af2e --- /dev/null +++ b/Task/Yin-and-yang/POV-Ray/yin-and-yang.pov-ray @@ -0,0 +1,69 @@ +// ====== General Scene setup ====== +#version 3.7; +global_settings { assumed_gamma 2.2 } + +camera{ location <0,2.7,4> look_at <0,.1,0> right x*1.6 + aperture .2 focal_point <1,0,0> blur_samples 200 variance 1/10000 } +light_source{<2,4,8>, 1 spotlight point_at 0 radius 10} +sky_sphere {pigment {granite scale <1,.1,1> color_map {[0 rgb 1][1 rgb <0,.4,.6>]}}} +#default {finish {diffuse .9 reflection {.1 metallic} ambient .3} + normal {granite scale .2}} +plane { y, -1 pigment {hexagon color rgb .7 color rgb .75 color rgb .65} + normal {hexagon scale 5}} + +// ====== Declare one side of the symbol as a sum and difference of discs ====== + +#declare yang = +difference { + merge { + difference { + cylinder {0 <0,.1,0> 1} // flat disk + box {-1 <1,1,0>} // cut in half + cylinder {<.5,-.1,0> <.5,.2,0> .5} // remove half-cicle on one side + } + cylinder {<-.5,0,0> <-.5,.1,0> .5} // add on the other side + cylinder {<.5,0,0> <.5,.1,0> .15} // also add a little dot + } + cylinder {<-.5,-.1,0> <-.5,.2,0> .15} // and carve out a hole + pigment{color rgb 0.1} +} + +// ====== The other side is white and 180-degree turned ====== + +#declare yin = +object { + yang + rotate <0,180,0> + pigment{color rgb 1} +} + +// ====== Here we put the two together: ====== + +#macro yinyang( ysize ) + union { + object {yin} + object {yang} + scale ysize + } +#end + +// ====== Here we put one into a scene: ====== + +object { yinyang(1) + translate -y*1.08 } + +// ====== And a bunch more just for fun: ====== + +#declare scl=1.1; +#while (scl > 0.01) + + object { yinyang(scl) + rotate <0,180,0> translate <-scl*4,scl*2-1,0> + rotate <0,scl*360,0> translate <-.5,0,0>} + + object { yinyang(scl) + translate <-scl*4,scl*2-1,0> + rotate <0,scl*360+180,0> translate <.5,0,0>} + + #declare scl = scl*0.85; +#end diff --git a/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 b/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 new file mode 100644 index 0000000000..533ed1e968 --- /dev/null +++ b/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 @@ -0,0 +1,24 @@ +sub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){ + say ""; +} + +sub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) { + my ($c, $w) = (1, 0); + say "" if $angle; + circle($rad, $cx, $cy, $fill, $stroke); + say ""; + circle($rad/5, $cx, $cy + $rad/2, $fill, $stroke); + circle($rad/5, $cx, $cy - $rad/2, $stroke, $fill); + say "" if $angle; +} + +say ' + +'; + +yin_yang(40, 50, 50); +yin_yang(20, 120, 120); + +say ''; diff --git a/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 b/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 new file mode 100644 index 0000000000..98f6eeeb99 --- /dev/null +++ b/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 @@ -0,0 +1,5 @@ +sub cheat_harder ($scale) { + ""; +} + +say '


    ', cheat_harder(700), cheat_harder(350), '
    '; diff --git a/Task/Yin-and-yang/Perl/yin-and-yang.pl b/Task/Yin-and-yang/Perl/yin-and-yang.pl new file mode 100644 index 0000000000..2447c2cdeb --- /dev/null +++ b/Task/Yin-and-yang/Perl/yin-and-yang.pl @@ -0,0 +1,54 @@ +sub circle { + my ($radius, $cx, $cy, $fill, $stroke) = @_; + print "\n"; +} + +sub yin_yang { + my ($rad, $cx, $cy, %opt) = @_; + my ($c, $w) = (1, 0); + $opt{fill} //= 'white'; + $opt{stroke} //= 'black'; + $opt{recurangle} //= 0; + + print "" + if $opt{angle}; + + if ($opt{flip}) { ($c, $w) = ($w, $c) }; + + circle($rad, $cx, $cy, $opt{fill}, $opt{stroke}); + + print ""; + + if ($opt{recur} and $rad > 1) { + # recursive "eyes" are slightly larger + yin_yang($rad/4, $cx, $cy + $rad/2, %opt, + angle => $opt{recurangle}, + fill => $opt{stroke}, + stroke => $opt{fill} ); + yin_yang($rad/4, $cx, $cy - $rad/2, %opt, + angle => 180 + $opt{recurangle}); + } else { + circle($rad/5, $cx, $cy + $rad/2, $opt{fill}, $opt{stroke}); + circle($rad/5, $cx, $cy - $rad/2, $opt{stroke}, $opt{fill}); + } + print "" if $opt{angle}; +} + +print <<'HEAD'; + + + +HEAD + +yin_yang(200, 250, 250, recur=>1, + angle=>0, recurangle=>90, fill=>'white', stroke=>'black'); +yin_yang(100, 500, 500); + +print "" diff --git a/Task/Yin-and-yang/PicoLisp/yin-and-yang.l b/Task/Yin-and-yang/PicoLisp/yin-and-yang.l new file mode 100644 index 0000000000..078dd76533 --- /dev/null +++ b/Task/Yin-and-yang/PicoLisp/yin-and-yang.l @@ -0,0 +1,24 @@ +(de circle (X Y C R) + (>= + (* R R) + (+ + (* (setq X (/ X 2)) X) + (* (dec 'Y C) Y) ) ) ) + +(de yinYang (R) + (for Y (range (- R) R) + (for X (range (- 0 R R) (+ R R)) + (prin + (cond + ((circle X Y (- (/ R 2)) (/ R 6)) + "#" ) + ((circle X Y (/ R 2) (/ R 6)) + "." ) + ((circle X Y (- (/ R 2)) (/ R 2)) + "." ) + ((circle X Y (/ R 2) (/ R 2)) + "#" ) + ((circle X Y 0 R) + (if (lt0 X) "." "#") ) + (T " ") ) ) ) + (prinl) ) ) diff --git a/Task/Yin-and-yang/PostScript/yin-and-yang.ps b/Task/Yin-and-yang/PostScript/yin-and-yang.ps new file mode 100644 index 0000000000..39ac61c63f --- /dev/null +++ b/Task/Yin-and-yang/PostScript/yin-and-yang.ps @@ -0,0 +1,40 @@ +%!PS-Adobe-3.0 +%%BoundingBox: 0 0 400 400 + +/fs 10 def +/ed { exch def } def +/dist { 3 -1 roll sub dup mul 3 1 roll sub dup mul add sqrt } def +/circ { + /r exch def + [r neg 1 r { + /y exch def + [ r 2 mul neg 1 r 2 mul { + /x ed x 2 div y 0 0 dist r .05 add gt {( )}{ + x 2 div y 0 r 2 div dist dup + r 5 div le { pop (.) } { + r 2 div le { (@) }{ + x 2 div y 0 r 2 div neg dist dup + r 5 div le { pop (@)} { + r 2 div le {(.)}{ + x 0 le {(.)}{(@)}ifelse + } ifelse + } ifelse + } ifelse + } ifelse + } ifelse + } for] + } for] +} def + +/dis { moveto gsave + { grestore 0 fs 1.15 mul neg rmoveto gsave + {show} forall + } forall grestore +} def + +/Courier findfont fs scalefont setfont + +11 circ 10 390 dis +6 circ 220 180 dis +showpage +%%EOF diff --git a/Task/Yin-and-yang/Prolog/yin-and-yang.pro b/Task/Yin-and-yang/Prolog/yin-and-yang.pro new file mode 100644 index 0000000000..a7dd23be4d --- /dev/null +++ b/Task/Yin-and-yang/Prolog/yin-and-yang.pro @@ -0,0 +1,56 @@ +ying_yang(N) :- + R is N * 100, + sformat(Title, 'Yin Yang ~w', [N]), + new(W, window(Title)), + new(Wh, colour(@default, 255*255, 255*255, 255*255)), + new(Bl, colour(@default, 0, 0, 0)), + CX is R + 50, + CY is R + 50, + R1 is R / 2, + R2 is R / 8, + CY1 is R1 + 50, + CY2 is 3 * R1 + 50, + + new(E, semi_disk(point(CX, CY), R, w, Bl)), + new(F, semi_disk(point(CX, CY), R, e, Wh)), + new(D1, disk(point(CX, CY1), R, Bl)), + new(D2, disk(point(CX, CY2), R, Wh)), + new(D3, disk(point(CX, CY1), R2, Wh)), + new(D4, disk(point(CX, CY2), R2, Bl)), + + send_list(W, display, [E, F, D1, D2, D3, D4]), + + WD is 2 * R + 100, + send(W, size, size(WD, WD )), + send(W, open). + +:- pce_begin_class(semi_disk, path, "Semi disk with color "). + +initialise(P, C, R, O, Col) :-> + send(P, send_super, initialise), + get(C, x, CX), + get(C, y, CY), + choose(O, Deb, End), + forall(between(Deb, End, I), + ( X is R * cos(I * pi/180) + CX, + Y is R * sin(I * pi/180) + CY, + send(P, append, point(X,Y)))), + send(P, closed, @on), + send(P, fill_pattern, Col). + +:- pce_end_class. + +choose(s, 0, 180). +choose(n, 180, 360). +choose(w, 90, 270). +choose(e, -90, 90). + +:- pce_begin_class(disk, ellipse, "disk with color "). + +initialise(P, C, R, Col) :-> + send(P, send_super, initialise, R, R), + send(P, center, C), + send(P, pen, 0), + send(P, fill_pattern, Col). + +:- pce_end_class. diff --git a/Task/Yin-and-yang/PureBasic/yin-and-yang.purebasic b/Task/Yin-and-yang/PureBasic/yin-and-yang.purebasic new file mode 100644 index 0000000000..94663a6cc0 --- /dev/null +++ b/Task/Yin-and-yang/PureBasic/yin-and-yang.purebasic @@ -0,0 +1,22 @@ +Procedure Yin_And_Yang(x, y, radius) + DrawingMode(#PB_2DDrawing_Outlined) + Circle(x, y, 2 * radius, #Black) ;outer circle + DrawingMode(#PB_2DDrawing_Default) + LineXY(x, y - 2 * radius, x, y + 2 * radius, #Black) + FillArea(x + 1, y, #Black, #Black) + Circle(x, y - radius, radius - 1, #White) + Circle(x, y + radius, radius - 1, #Black) + Circle(x, y - radius, radius / 3, #Black) ;small contrasting inner circles + Circle(x, y + radius, radius / 3, #White) +EndProcedure + +If CreateImage(0, 700, 700) And StartDrawing(ImageOutput(0)) + FillArea(1, 1, -1, #White) + Yin_And_Yang(105, 105, 50) + Yin_And_Yang(400, 400, 148) + StopDrawing() + ; + UsePNGImageEncoder() + path$ = SaveFileRequester("Save image", "Yin And yang.png", "*.png", 0) + If path$ <> "": SaveImage(0, path$, #PB_ImagePlugin_PNG, 0, 2): EndIf +EndIf diff --git a/Task/Yin-and-yang/Python/yin-and-yang-1.py b/Task/Yin-and-yang/Python/yin-and-yang-1.py new file mode 100644 index 0000000000..530e2996cf --- /dev/null +++ b/Task/Yin-and-yang/Python/yin-and-yang-1.py @@ -0,0 +1,21 @@ +import math +def yinyang(n=3): + radii = [i * n for i in (1, 3, 6)] + ranges = [list(range(-r, r+1)) for r in radii] + squares = [[ (x,y) for x in rnge for y in rnge] + for rnge in ranges] + circles = [[ (x,y) for x,y in sqrpoints + if math.hypot(x,y) <= radius ] + for sqrpoints, radius in zip(squares, radii)] + m = {(x,y):' ' for x,y in squares[-1]} + for x,y in circles[-1]: + m[x,y] = '*' + for x,y in circles[-1]: + if x>0: m[(x,y)] = '·' + for x,y in circles[-2]: + m[(x,y+3*n)] = '*' + m[(x,y-3*n)] = '·' + for x,y in circles[-3]: + m[(x,y+3*n)] = '·' + m[(x,y-3*n)] = '*' + return '\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1]) diff --git a/Task/Yin-and-yang/Python/yin-and-yang-2.py b/Task/Yin-and-yang/Python/yin-and-yang-2.py new file mode 100644 index 0000000000..13f50bb955 --- /dev/null +++ b/Task/Yin-and-yang/Python/yin-and-yang-2.py @@ -0,0 +1,53 @@ +from turtle import * + +mode('logo') + +def taijitu(r): + '''\ + Draw a classic Taoist taijitu of the given radius centered on the current + turtle position. The "eyes" are placed along the turtle's heading, the + filled one in front, the open one behind. + ''' + + # useful derivative values + r2, r4, r8 = (r >> s for s in (1, 2, 3)) + + # remember where we started + x0, y0 = start = pos() + startcolour = color() + startheading = heading() + color('black', 'black') + + # draw outer circle + pendown() + circle(r) + + # draw two 'fishes' + begin_fill(); circle(r, 180); circle(r2, 180); circle(-r2, 180); end_fill() + + # black 'eye' + setheading(0); penup(); goto(-(r4 + r8) + x0, y0); pendown() + begin_fill(); circle(r8); end_fill() + + # white 'eye' + color('white', 'white'); setheading(0); penup(); goto(-(r+r4+r8) + x0, y0); pendown() + begin_fill(); circle(r8); end_fill() + + # put the turtle back where it started + penup() + setpos(start) + setheading(startheading) + color(*startcolour) + + +if __name__ == '__main__': + # demo code to produce image at right + reset() + #hideturtle() + penup() + goto(300, 200) + taijitu(200) + penup() + goto(-150, -150) + taijitu(100) + hideturtle() diff --git a/Task/Yin-and-yang/R/yin-and-yang.r b/Task/Yin-and-yang/R/yin-and-yang.r new file mode 100644 index 0000000000..a6fd949797 --- /dev/null +++ b/Task/Yin-and-yang/R/yin-and-yang.r @@ -0,0 +1,15 @@ +plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){ + suppressMessages(require("plotrix")) + if(!add) plot(1:10, type="n", xlim=c(0,s), ylim=c(0,s), xlab="", ylab="", xaxt="n", yaxt="n", bty="n", asp=1) + draw.circle(x, y, r, border="white", col= "black") + draw.ellipse(x, y, r, r, col="white", angle=0, segment=c(90,270), arc.only=F) + draw.ellipse(x, y - r * 0.5, r * 0.5, r * 0.5, col="black", border="black", angle=0, segment=c(90,270), arc.only=F) + draw.circle(x, y - r * 0.5, r * 0.125, border="white", col= "white") + draw.circle(x, y + r * 0.5, r * 0.5, col="white", border="white") + draw.circle(x, y + r * 0.5, r * 0.125, border="black", lty=1, col= "black") + draw.circle(x, y, r, border="black") +} +png("yin_yang.png") +plot.yin.yang() +plot.yin.yang(1,7,1, add=T) +dev.off() diff --git a/Task/Yin-and-yang/Racket/yin-and-yang.rkt b/Task/Yin-and-yang/Racket/yin-and-yang.rkt new file mode 100644 index 0000000000..322bfb6e48 --- /dev/null +++ b/Task/Yin-and-yang/Racket/yin-and-yang.rkt @@ -0,0 +1,20 @@ +#lang racket +(require slideshow/pict) + +(define (yin-yang d) + (define base + (hc-append (inset/clip (circle d) 0 0 (- (/ d 2)) 0) + (inset/clip (disk d) (- (/ d 2)) 0 0 0))) + (define with-top + (ct-superimpose + base + (cc-superimpose (colorize (disk (/ d 2)) "white") + (disk (/ d 8))))) + (define with-bottom + (cb-superimpose + with-top + (cc-superimpose (disk (/ d 2)) + (colorize (disk (/ d 8)) "white")))) + (cc-superimpose with-bottom (circle d))) + +(yin-yang 200) diff --git a/Task/Yin-and-yang/Rascal/yin-and-yang.rascal b/Task/Yin-and-yang/Rascal/yin-and-yang.rascal new file mode 100644 index 0000000000..6e8a9457e7 --- /dev/null +++ b/Task/Yin-and-yang/Rascal/yin-and-yang.rascal @@ -0,0 +1,19 @@ +import util::Math; +import vis::Render; +import vis::Figure; + +public void yinyang(){ + template = ellipse(fillColor("white")); + + smallWhite = ellipse(fillColor("white"), shrink(0.1), valign(0.75)); + smallBlack = ellipse(fillColor("black"), shrink(0.1), valign(0.25)); + + dots= [ellipse(fillColor("white"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/4, 0.25 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]]; + dots2 = [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/-4, 0.75 + cos(0.0031415*n)/-4)) | n <- [1 .. 1000]]; + dots3= [ellipse(fillColor("black"), shrink(0.000001), align(0.5 + sin(0.0031415*n)/2, 0.5-cos(0.0031415*n)/-2)) | n <- [1 .. 1000]]; + + black= overlay([*dots, *dots2, *dots3], shapeConnected(true), shapeClosed(true), shapeCurved(true), fillColor("black")); + + render(hcat([vcat([overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0)), space(), space()]), + overlay([template, black, smallWhite, smallBlack], aspectRatio (1.0))])); +} diff --git a/Task/Yin-and-yang/Ruby/yin-and-yang.rb b/Task/Yin-and-yang/Ruby/yin-and-yang.rb new file mode 100644 index 0000000000..8473df1709 --- /dev/null +++ b/Task/Yin-and-yang/Ruby/yin-and-yang.rb @@ -0,0 +1,28 @@ +Shoes.app(:width => 470, :height => 380) do + PI = Shoes::TWO_PI/2 + + strokewidth 1 + + def yin_yang(x, y, radius) + fill black; stroke black + arc x, y, radius, radius, -PI/2, PI/2 + + fill white; stroke white + arc x, y, radius, radius, PI/2, -PI/2 + oval x-radius/4, y-radius/2, radius/2-1 + + fill black; stroke black + oval x-radius/4, y, radius/2-1 + oval x-radius/12, y-radius/4-radius/12, radius/6-1 + + fill white; stroke white + oval x-radius/12, y+radius/4-radius/12, radius/6-1 + + nofill + stroke black + oval x-radius/2, y-radius/2, radius + end + + yin_yang 190, 190, 360 + yin_yang 410, 90, 90 +end diff --git a/Task/Yin-and-yang/Seed7/yin-and-yang.seed7 b/Task/Yin-and-yang/Seed7/yin-and-yang.seed7 new file mode 100644 index 0000000000..3164eb555e --- /dev/null +++ b/Task/Yin-and-yang/Seed7/yin-and-yang.seed7 @@ -0,0 +1,26 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + include "math.s7i"; + include "draw.s7i"; + include "keybd.s7i"; + +const proc: yinYang (in integer: xPos, in integer: yPos, in integer: size) is func + begin + pieslice(xPos, yPos, size, 3.0 * PI / 2.0, PI, black); + pieslice(xPos, yPos, size, PI / 2.0, PI, white); + fcircle(xPos, yPos - size div 2, size div 2, white); + fcircle(xPos, yPos + size div 2, size div 2, black); + fcircle(xPos, yPos - size div 2, size div 6, black); + fcircle(xPos, yPos + size div 2, size div 6, white); + circle(xPos, yPos, size, black); + end func; + +const proc: main is func + begin + screen(640, 480); + clear(white); + KEYBOARD := GRAPH_KEYBOARD; + yinYang(100, 100, 80); + yinYang(400, 250, 200); + readln(KEYBOARD); + end func; diff --git a/Task/Yin-and-yang/Tcl/yin-and-yang.tcl b/Task/Yin-and-yang/Tcl/yin-and-yang.tcl new file mode 100644 index 0000000000..8037af30d1 --- /dev/null +++ b/Task/Yin-and-yang/Tcl/yin-and-yang.tcl @@ -0,0 +1,27 @@ +package require Tcl 8.5 +package require Tk + +namespace import tcl::mathop::\[-+\] ;# Shorter coordinate math +proc yinyang {c x y r {colors {white black}}} { + lassign $colors a b + set tt [expr {$r * 2 / 3.0}] + set h [expr {$r / 2.0}] + set t [expr {$r / 3.0}] + set s [expr {$r / 6.0}] + $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \ + -fill $a -outline {} -extent 180 -start 90 + $c create arc [- $x $r] [- $y $r] [+ $x $r] [+ $y $r] \ + -fill $b -outline {} -extent 180 -start 270 + $c create oval [- $x $h] [- $y $r] [+ $x $h] $y \ + -fill $a -outline {} + $c create oval [- $x $h] [+ $y $r] [+ $x $h] $y \ + -fill $b -outline {} + $c create oval [- $x $s] [- $y $tt] [+ $x $s] [- $y $t] \ + -fill $b -outline {} + $c create oval [- $x $s] [+ $y $tt] [+ $x $s] [+ $y $t] \ + -fill $a -outline {} +} + +pack [canvas .c -width 300 -height 300 -background gray50] +yinyang .c 110 110 90 +yinyang .c 240 240 40 diff --git a/Task/Yin-and-yang/Visual-Basic-.NET/yin-and-yang.visual b/Task/Yin-and-yang/Visual-Basic-.NET/yin-and-yang.visual new file mode 100644 index 0000000000..74d3597464 --- /dev/null +++ b/Task/Yin-and-yang/Visual-Basic-.NET/yin-and-yang.visual @@ -0,0 +1,21 @@ +Public Class Form1 + + Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint + Dim g As Graphics = e.Graphics + g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias + + DrawTaijitu(g, New Point(50, 50), 200, True) + DrawTaijitu(g, New Point(10, 10), 60, True) + End Sub + + Private Sub DrawTaijitu(ByVal g As Graphics, ByVal pt As Point, ByVal width As Integer, ByVal hasOutline As Boolean) + g.FillPie(Brushes.Black, pt.X, pt.Y, width, width, 90, 180) + g.FillPie(Brushes.White, pt.X, pt.Y, width, width, 270, 180) + g.FillEllipse(Brushes.Black, CSng(pt.X + (width * 0.25)), CSng(pt.Y), CSng(width * 0.5), CSng(width * 0.5)) + g.FillEllipse(Brushes.White, CSng(pt.X + (width * 0.25)), CSng(pt.Y + (width * 0.5)), CSng(width * 0.5), CSng(width * 0.5)) + g.FillEllipse(Brushes.White, CSng(pt.X + (width * 0.4375)), CSng(pt.Y + (width * 0.1875)), CSng(width * 0.125), CSng(width * 0.125)) + g.FillEllipse(Brushes.Black, CSng(pt.X + (width * 0.4375)), CSng(pt.Y + (width * 0.6875)), CSng(width * 0.125), CSng(width * 0.125)) + If hasOutline Then g.DrawEllipse(Pens.Black, pt.X, pt.Y, width, width) + End Sub + +End Class diff --git a/Task/Yin-and-yang/XPL0/yin-and-yang.xpl0 b/Task/Yin-and-yang/XPL0/yin-and-yang.xpl0 new file mode 100644 index 0000000000..917dad78b9 --- /dev/null +++ b/Task/Yin-and-yang/XPL0/yin-and-yang.xpl0 @@ -0,0 +1,29 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +def Black=0, Red=4, White=$F; + +proc Circle(X0, Y0, R, CL, CR); \Show a filled circle +int X0, Y0, R, CL, CR; \left and right half colors +int X, Y; +[for Y:= -R to R do + for X:= -R to R do + if X*X + Y*Y <= R*R then + Point(X+X0, Y+Y0, if X<0 then CL else CR); +]; \Circle + +proc YinYang(X0, Y0, R); +int X0, Y0, R; +[Circle(X0, Y0, R, White, Black); + Circle(X0, Y0-R/2, R/2, White, White); + Circle(X0, Y0-R/2, R/6, Black, Black); + Circle(X0, Y0+R/2, R/2, Black, Black); + Circle(X0, Y0+R/2, R/6, White, White); +]; \YinYang + +[SetVid($101); \640x480 graphics +Circle(320, 240, 400, Red, Red);\fill screen with background color +YinYang(80, 80, 70); +YinYang(240, 240, 150); +if ChIn(1) then []; \wait for keystroke +SetVid(3); \restore normal text mode +] diff --git a/Task/Zebra-puzzle/0DESCRIPTION b/Task/Zebra-puzzle/0DESCRIPTION new file mode 100644 index 0000000000..9dadf17f4c --- /dev/null +++ b/Task/Zebra-puzzle/0DESCRIPTION @@ -0,0 +1,24 @@ +The [[wp:Zebra puzzle|Zebra puzzle]], a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this: + +#There are five houses. +#The English man lives in the red house. +#The Swede has a dog. +#The Dane drinks tea. +#The green house is immediately to the left of the white house. +#They drink coffee in the green house. +#The man who smokes Pall Mall has birds. +#In the yellow house they smoke Dunhill. +#In the middle house they drink milk. +#The Norwegian lives in the first house. +#The man who smokes Blend lives in the house next to the house with cats. +#In a house next to the house where they have a horse, they smoke Dunhill. +#The man who smokes Blue Master drinks beer. +#The German smokes Prince. +#The Norwegian lives next to the blue house. +#They drink water in a house next to the house where they smoke Blend. + +The question is, who owns the zebra? + +Additionally, list the solution for all the houses. Optionally, show the solution is unique. + +cf. [[Dinesman's multiple-dwelling problem]] diff --git a/Task/Zebra-puzzle/1META.yaml b/Task/Zebra-puzzle/1META.yaml new file mode 100644 index 0000000000..c666ee12ce --- /dev/null +++ b/Task/Zebra-puzzle/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Logic puzzles diff --git a/Task/Zebra-puzzle/Ada/zebra-puzzle.ada b/Task/Zebra-puzzle/Ada/zebra-puzzle.ada new file mode 100644 index 0000000000..b5eda367de --- /dev/null +++ b/Task/Zebra-puzzle/Ada/zebra-puzzle.ada @@ -0,0 +1,106 @@ +with Ada.Text_IO; use Ada.Text_IO; +procedure Zebra is + type Content is (Beer, Coffee, Milk, Tea, Water, + Danish, English, German, Norwegian, Swedish, + Blue, Green, Red, White, Yellow, + Blend, BlueMaster, Dunhill, PallMall, Prince, + Bird, Cat, Dog, Horse, Zebra); + type Test is (Drink, Person, Color, Smoke, Pet); + type House is (One, Two, Three, Four, Five); + type Street is array (Test'Range, House'Range) of Content; + type Alley is access all Street; + + procedure Print (mat : Alley) is begin + for H in House'Range loop + Put(H'Img&": "); + for T in Test'Range loop + Put(T'Img&"="&mat(T,H)'Img&" "); + end loop; New_Line; end loop; + end Print; + + function FinalChecks (mat : Alley) return Boolean is + function Diff (A, B : Content; CA , CB : Test) return Integer is begin + for H1 in House'Range loop for H2 in House'Range loop + if mat(CA,H1) = A and mat(CB,H2) = B then + return House'Pos(H1) - House'Pos(H2); + end if; + end loop; end loop; + end Diff; + begin + if abs(Diff(Norwegian, Blue, Person, Color)) = 1 + and Diff(Green, White, Color, Color) = -1 + and abs(Diff(Horse, Dunhill, Pet, Smoke)) = 1 + and abs(Diff(Water, Blend, Drink, Smoke)) = 1 + and abs(Diff(Blend, Cat, Smoke, Pet)) = 1 + then return True; + end if; + return False; + end FinalChecks; + + function Constrained (mat : Alley; atest : Natural) return Boolean is begin + -- Tests seperated into levels for speed, not strictly necessary + -- As such, the program finishes in around ~0.02s + case Test'Val (atest) is + when Drink => -- Drink + if mat (Drink, Three) /= Milk then return False; end if; + return True; + when Person => -- Drink+Person + for H in House'Range loop + if (mat(Person,H) = Norwegian and H /= One) + or (mat(Person,H) = Danish and mat(Drink,H) /= Tea) + then return False; end if; + end loop; + return True; + when Color => -- Drink+People+Color + for H in House'Range loop + if (mat(Person,H) = English and mat(Color,H) /= Red) + or (mat(Drink,H) = Coffee and mat(Color,H) /= Green) + then return False; end if; + end loop; + return True; + when Smoke => -- Drink+People+Color+Smoke + for H in House'Range loop + if (mat(Color,H) = Yellow and mat(Smoke,H) /= Dunhill) + or (mat(Smoke,H) = BlueMaster and mat(Drink,H) /= Beer) + or (mat(Person,H) = German and mat(Smoke,H) /= Prince) + then return False; end if; + end loop; + return True; + when Pet => -- Drink+People+Color+Smoke+Pet + for H in House'Range loop + if (mat(Person,H) = Swedish and mat(Pet,H) /= Dog) + or (mat(Smoke,H) = PallMall and mat(Pet,H) /= Bird) + then return False; end if; + end loop; + return FinalChecks(mat); -- Do the next-to checks + end case; + end Constrained; + + procedure Solve (mat : Alley; t, n : Natural) is + procedure Swap (I, J : Natural) is + temp : constant Content := mat (Test'Val (t), House'Val (J)); + begin + mat (Test'Val (t), House'Val (J)) := mat (Test'Val (t), House'Val (I)); + mat (Test'Val (t), House'Val (I)) := temp; + end Swap; + begin + if n = 1 and Constrained (mat, t) then -- test t passed + if t < 4 then Solve (mat, t + 1, 5); -- Onto next test + else Print (mat); return; -- Passed and t=4 means a solution + end if; + end if; + for i in 0 .. n - 1 loop -- The permutations part + Solve (mat, t, n - 1); + if n mod 2 = 1 then Swap (0, n - 1); + else Swap (i, n - 1); end if; + end loop; + end Solve; + + myStreet : aliased Street; + myAlley : constant Alley := myStreet'Access; +begin + for i in Test'Range loop for j in House'Range loop -- Init Matrix + myStreet (i,j) := Content'Val(Test'Pos(i)*5 + House'Pos(j)); + end loop; end loop; + Solve (myAlley, 0, 5); -- start at test 0 with 5 options +end Zebra; diff --git a/Task/Zebra-puzzle/BBC-BASIC/zebra-puzzle.bbc b/Task/Zebra-puzzle/BBC-BASIC/zebra-puzzle.bbc new file mode 100644 index 0000000000..78c41d1f37 --- /dev/null +++ b/Task/Zebra-puzzle/BBC-BASIC/zebra-puzzle.bbc @@ -0,0 +1,101 @@ + REM The names (only used for printing the results): + DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4) + Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water" + Nation$() = "Denmark", "England", "Germany", "Norway", "Sweden" + Colr$() = "Blue", "Green", "Red", "White", "Yellow" + Smoke$() = "Blend", "BlueMaster", "Dunhill", "PallMall", "Prince" + Animal$() = "Birds", "Cats", "Dog", "Horse", "Zebra" + + REM Some single-character tags: + a$ = "A" : b$ = "B" : c$ = "C" : d$ = "D" : e$ = "E" + + REM BBC BASIC Doesn't have enumerations! + Beer$=a$ : Coffee$=b$ : Milk$=c$ : Tea$=d$ : Water$=e$ + Denmark$=a$ : England$=b$ : Germany$=c$ : Norway$=d$ : Sweden$=e$ + Blue$=a$ : Green$=b$ : Red$=c$ : White$=d$ : Yellow$=e$ + Blend$=a$ : BlueMaster$=b$ : Dunhill$=c$ : PallMall$=d$ : Prince$=e$ + Birds$=a$ : Cats$=b$ : Dog$=c$ : Horse$=d$ : Zebra$=e$ + + REM Create the 120 permutations of 5 objects: + DIM perm$(120), x$(4) : x$() = a$, b$, c$, d$, e$ + REPEAT + p% += 1 + perm$(p%) = x$(0)+x$(1)+x$(2)+x$(3)+x$(4) + UNTIL NOT FNperm(x$()) + + REM Express the statements as conditional expressions: + ex2$ = "INSTR(Nation$,England$) = INSTR(Colr$,Red$)" + ex3$ = "INSTR(Nation$,Sweden$) = INSTR(Animal$,Dog$)" + ex4$ = "INSTR(Nation$,Denmark$) = INSTR(Drink$,Tea$)" + ex5$ = "INSTR(Colr$,Green$+White$) <> 0" + ex6$ = "INSTR(Drink$,Coffee$) = INSTR(Colr$,Green$)" + ex7$ = "INSTR(Smoke$,PallMall$) = INSTR(Animal$,Birds$)" + ex8$ = "INSTR(Smoke$,Dunhill$) = INSTR(Colr$,Yellow$)" + ex9$ = "MID$(Drink$,3,1) = Milk$" + ex10$ = "LEFT$(Nation$,1) = Norway$" + ex11$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Animal$,Cats$)) = 1" + ex12$ = "ABS(INSTR(Smoke$,Dunhill$)-INSTR(Animal$,Horse$)) = 1" + ex13$ = "INSTR(Smoke$,BlueMaster$) = INSTR(Drink$,Beer$)" + ex14$ = "INSTR(Nation$,Germany$) = INSTR(Smoke$,Prince$)" + ex15$ = "ABS(INSTR(Nation$,Norway$)-INSTR(Colr$,Blue$)) = 1" + ex16$ = "ABS(INSTR(Smoke$,Blend$)-INSTR(Drink$,Water$)) = 1" + + REM Solve: + solutions% = 0 + TIME = 0 + FOR nation% = 1 TO 120 + Nation$ = perm$(nation%) + IF EVAL(ex10$) THEN + FOR colr% = 1 TO 120 + Colr$ = perm$(colr%) + IF EVAL(ex5$) IF EVAL(ex2$) IF EVAL(ex15$) THEN + FOR drink% = 1 TO 120 + Drink$ = perm$(drink%) + IF EVAL(ex9$) IF EVAL(ex4$) IF EVAL(ex6$) THEN + FOR smoke% = 1 TO 120 + Smoke$ = perm$(smoke%) + IF EVAL(ex14$) IF EVAL(ex13$) IF EVAL(ex16$) IF EVAL(ex8$) THEN + FOR animal% = 1 TO 120 + Animal$ = perm$(animal%) + IF EVAL(ex3$) IF EVAL(ex7$) IF EVAL(ex11$) IF EVAL(ex12$) THEN + PRINT "House Drink Nation Colour Smoke Animal" + FOR house% = 1 TO 5 + PRINT ; house% ,; + PRINT Drink$(ASCMID$(Drink$,house%)-65),; + PRINT Nation$(ASCMID$(Nation$,house%)-65),; + PRINT Colr$(ASCMID$(Colr$,house%)-65),; + PRINT Smoke$(ASCMID$(Smoke$,house%)-65),; + PRINT Animal$(ASCMID$(Animal$,house%)-65) + NEXT + solutions% += 1 + ENDIF + NEXT animal% + ENDIF + NEXT smoke% + ENDIF + NEXT drink% + ENDIF + NEXT colr% + ENDIF + NEXT nation% + PRINT '"Number of solutions = "; solutions% + PRINT "Solved in " ; TIME/100 " seconds" + END + + DEF FNperm(x$()) + LOCAL i%, j% + FOR i% = DIM(x$(),1)-1 TO 0 STEP -1 + IF x$(i%) < x$(i%+1) EXIT FOR + NEXT + IF i% < 0 THEN = FALSE + j% = DIM(x$(),1) + WHILE x$(j%) <= x$(i%) j% -= 1 : ENDWHILE + SWAP x$(i%), x$(j%) + i% += 1 + j% = DIM(x$(),1) + WHILE i% < j% + SWAP x$(i%), x$(j%) + i% += 1 + j% -= 1 + ENDWHILE + = TRUE diff --git a/Task/Zebra-puzzle/C/zebra-puzzle-1.c b/Task/Zebra-puzzle/C/zebra-puzzle-1.c new file mode 100644 index 0000000000..b7267aa169 --- /dev/null +++ b/Task/Zebra-puzzle/C/zebra-puzzle-1.c @@ -0,0 +1,228 @@ +#include +#include + +enum HouseStatus {Invalid, Underfull, Valid}; + +enum Attrib {C, M, D, A, S}; +// Unfilled attributes are represented by -1 +enum Colors {Red, Green, White, Yellow, Blue}; +enum Mans {English, Swede, Dane, German, Norwegian}; +enum Drinks {Tea, Coffee, Milk, Beer, Water}; +enum Animals {Dog, Birds, Cats, Horse, Zebra}; +enum Smokes {PallMall, Dunhill, Blend, BlueMaster, Prince}; + +void printHouses(int ha[5][5]) +{ + const char *Color [] = {"Red", "Green", "White", "Yellow", "Blue"}; + const char *Man [] = {"English", "Swede", "Dane", "German", "Norwegian"}; + const char *Drink [] = {"Tea", "Coffee", "Milk", "Beer", "Water"}; + const char *Animal[] = {"Dog", "Birds", "Cats", "Horse", "Zebra"}; + const char *Smoke [] = {"PallMall", "Dunhill", "Blend", "BlueMaster", "Prince"}; + printf("%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s%-10.10s\n", + "House", "Color", "Man", "Drink", "Animal", "Smoke"); + for(int i=0; i<5; i++) { + printf("%-10d", i); + if (ha[i][C]>=0) + printf("%-10.10s", Color[ha[i][C]]); + else + printf("%-10.10s", "-"); + if (ha[i][M]>=0) + printf("%-10.10s", Man[ha[i][M]]); + else + printf("%-10.10s", "-"); + if (ha[i][D]>=0) + printf("%-10.10s", Drink[ha[i][D]]); + else + printf("%-10.10s", "-"); + if (ha[i][A]>=0) + printf("%-10.10s", Animal[ha[i][A]]); + else + printf("%-10.10s", "-"); + if (ha[i][S]>=0) + printf("%-10.10s\n", Smoke[ha[i][S]]); + else + printf("-\n"); + } +} + +int checkHouses(int ha[5][5]) +{ + int c_add=0, c_or=0; + int m_add=0, m_or=0; + int d_add=0, d_or=0; + int a_add=0, a_or=0; + int s_add=0, s_or=0; + + // Cond 9: In the middle house they drink milk + if ( ha[2][D] >= 0 && ha[2][D] != Milk ) + return Invalid; + + // Cond 10: The Norwegian lives in the first house + if ( ha[0][M] >= 0 && ha[0][M] != Norwegian ) + return Invalid; + + for (int i=0; i<5; i++) { + // Uniqueness tests + if (ha[i][C] >= 0) { + c_add += (1<= 0) { + m_add += (1<= 0) { + d_add += (1<= 0) { + a_add += (1<= 0) { + s_add += (1<= 0 && ha[i][C] >= 0 ) && + ( (ha[i][M] == English && ha[i][C] != Red ) || // checking both + (ha[i][M] != English && ha[i][C] == Red ) ) ) // to make things quicker + return Invalid; + + // Cond 3: The Swede has a dog + if ( ( ha[i][M] >= 0 && ha[i][A] >= 0 ) && + ((ha[i][M] == Swede && ha[i][A] != Dog )|| + (ha[i][M] != Swede && ha[i][A] == Dog ) ) ) + return Invalid; + + // Cond 4: The Dane drinks tea + if ( ( ha[i][M] >= 0 && ha[i][D] >= 0 ) && + ((ha[i][M] == Dane && ha[i][D] != Tea )|| + (ha[i][M] != Dane && ha[i][D] == Tea ) ) ) + return Invalid; + + // Cond 5: The green house is immediately to the left of the white house + if ( ( i>0 && ha[i][C] >= 0 /*&& ha[i-1][C] >= 0 */) && + ((ha[i-1][C] == Green && ha[i][C] != White )|| + (ha[i-1][C] != Green && ha[i][C] == White ) ) ) + return Invalid; + + // Cond 6: drink coffee in the green house + if ( ( ha[i][C] >= 0 && ha[i][D] >= 0 ) && + ((ha[i][C] == Green && ha[i][D] != Coffee )|| + (ha[i][C] != Green && ha[i][D] == Coffee ) ) ) + return Invalid; + + // Cond 7: The man who smokes Pall Mall has birds + if ( ( ha[i][S] >= 0 && ha[i][A] >= 0 ) && + ((ha[i][S] == PallMall && ha[i][A] != Birds )|| + (ha[i][S] != PallMall && ha[i][A] == Birds ) ) ) + return Invalid; + + // Cond 8: In the yellow house they smoke Dunhill + if ( ( ha[i][S] >= 0 && ha[i][C] >= 0 ) && + ((ha[i][S] == Dunhill && ha[i][C] != Yellow )|| + (ha[i][S] != Dunhill && ha[i][C] == Yellow ) ) ) + return Invalid; + + // Cond 11: The man who smokes Blend lives in the house next to the house with cats + if (ha[i][S] == Blend) { + if (i==0 && ha[i+1][A]>=0&&ha[i+1][A]!=Cats) + return Invalid; + else if (i==4 && ha[i-1][A]!=Cats) + return Invalid; + else if (ha[i+1][A]>=0&&ha[i+1][A]!=Cats&&ha[i-1][A]!=Cats) + return Invalid; + } + + // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill + if (ha[i][S] == Dunhill) { + if (i==0 && ha[i+1][A]>=0&&ha[i+1][A]!=Horse) + return Invalid; + else if (i==4 && ha[i-1][A]!=Horse) + return Invalid; + else if (ha[i+1][A]>=0&&ha[i+1][A]!=Horse&&ha[i-1][A]!=Horse) + return Invalid; + } + + // Cond 13: The man who smokes Blue Master drinks beer + if ( ( ha[i][S] >= 0 && ha[i][D] >= 0 ) && + ((ha[i][S] == BlueMaster && ha[i][D] != Beer )|| + (ha[i][S] != BlueMaster && ha[i][D] == Beer ) ) ) + return Invalid; + + // Cond 14: The German smokes Prince + if ( ( ha[i][M] >= 0 && ha[i][S] >= 0 ) && + ((ha[i][M] == German && ha[i][S] != Prince )|| + (ha[i][M] != German && ha[i][S] == Prince ) ) ) + return Invalid; + + // Cond 15: The Norwegian lives next to the blue house + if ( ha[i][M] == Norwegian && + ((i<4&&ha[i+1][C]>=0&&ha[i+1][C]!=Blue) || + (i>0&&ha[i-1][C]!=Blue))) + return Invalid; + + // Cond 16: They drink water in a house next to the house where they smoke Blend. + if (ha[i][S] == Blend) { + if (i==0 && ha[i+1][D]>=0&&ha[i+1][D]!=Water) + return Invalid; + else if (i==4 && ha[i-1][D]!=Water) + return Invalid; + else if (ha[i+1][D]>=0&&ha[i+1][D]!=Water&&ha[i-1][D]!=Water) + return Invalid; + } + + } + if ((c_add != c_or)||(m_add != m_or)||(d_add != d_or) + ||(a_add != a_or)||(s_add != s_or)) { + return Invalid; + } + if ((c_add != 0b11111)||(m_add != 0b11111)||(d_add != 0b11111) + ||(a_add != 0b11111)||(s_add != 0b11111)) { + return Underfull; + } + return Valid; +} + +int bruteFill(int ha[5][5], int hno, int attr) +{ + int stat = checkHouses(ha); + if (( stat == Valid)||(stat == Invalid)) + return stat; + + int hb[5][5]; + memcpy(hb, ha, sizeof(int)*5*5); + for (int i=0; i<5; i++) { + hb[hno][attr] = i; + stat = checkHouses(hb); + if (stat != Invalid) { + int nexthno, nextattr; + if (attr<4) { + nextattr = attr+1; + nexthno = hno; + } else { + nextattr = 0; + nexthno = hno+1; + } + + stat = bruteFill(hb, nexthno, nextattr); + if (stat != Invalid) { + memcpy(ha, hb, sizeof(int)*5*5); + return stat; + } + } + } + // we only come here if none of the attr values assigned were valid + return Invalid; +} + +int main(void) +{ + int ha[5][5]={{-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1}, + {-1,-1,-1,-1,-1},{-1,-1,-1,-1,-1}}; + bruteFill(ha, 0, 0); + printHouses(ha); + return 0; +} diff --git a/Task/Zebra-puzzle/C/zebra-puzzle-2.c b/Task/Zebra-puzzle/C/zebra-puzzle-2.c new file mode 100644 index 0000000000..82269d1158 --- /dev/null +++ b/Task/Zebra-puzzle/C/zebra-puzzle-2.c @@ -0,0 +1,176 @@ +#!/usr/bin/perl + +use utf8; +no strict; + +my (%props, %name, @pre, @conds, @works, $find_all_solutions); + +sub do_consts { + local $"; + for my $p (keys %props) { + my @s = @{ $props{$p} }; + + $" = ", "; + print "enum { ${p}_none = 0, @s };\n"; + + $" = '", "'; + print "const char *string_$p [] = { \"###\", \"@s\" };\n\n"; + } + print "#define FIND_BY(p) \\ +int find_by_##p(int v) { \\ +int i; \\ +for (i = 0; i < N_ITEMS; i++) \\ + if (house[i].p == v) return i; \\ +return -1; }\n"; + + print "FIND_BY($_)" for (keys %props); + + local $" = ", "; + my @k = keys %props; + + my $sl = 0; + for (keys %name) { + if (length > $sl) { $sl = length } + } + + my $fmt = ("%".($sl + 1)."s ") x @k; + my @arg = map { "string_$_"."[house[i].$_]" } @k; + print << "SNIPPET"; +int work0(void) { + int i; + for (i = 0; i < N_ITEMS; i++) + printf("%d $fmt\\n", i, @arg); + puts(\"\"); + return 1; +} +SNIPPET + +} + +sub setprops { + %props = @_; + my $l = 0; + my @k = keys %props; + for my $p (@k) { + my @s = @{ $props{$p} }; + + if ($l && $l != @s) { + die "bad length @s"; + } + $l = @s; + $name{$_} = $p for @s; + } + local $" = ", "; + print "#include +#define N_ITEMS $l +struct item_t { int @k; } house[N_ITEMS] = {{0}};\n"; +} + +sub pair {NB. h =.~.&> compose&.>~/y,= 0 && b < N_ITEMS) { \\ + if (!house[b].p) { \\ + house[b].p = c; \\ + if (n()) $return1; \\ + house[b].p = 0; \\ + }} +"; + + while (@conds) { + my ($c1, $c2, $diff) = @{ pop @conds }; + my $p2 = $name{$c2} or die "bad prop $c2"; + + if ($c1 =~ /^\d+$/) { + push @pre, "house[$c1].$p2 = $c2;"; + next; + } + + my $p1 = $name{$c1} or die "bad prop $c1"; + my $next = "work$idx"; + my $this = "work".++$idx; + + print " +/* condition pair($c1, $c2, [@$diff]) */ +int $this(void) { +int a = find_by_$p1($c1); +int b = find_by_$p2($c2); +if (a != -1 && b != -1) { +switch(b - a) { +"; + print "case $_: " for @$diff; + print "return $next(); default: return 0; }\n } if (a != -1) {"; + print "TRY(a, b, $c2, +($_), $p2, $next);" for @$diff; + print " return 0; } if (b != -1) {"; + print "TRY(b, a, $c1, -($_), $p1, $next);" for @$diff; + print " +return 0; } +/* neither condition is set; try all possibles */ +for (a = 0; a < N_ITEMS; a++) { +if (house[a].$p1) continue; +house[a].$p1 = $c1; +"; + + print "TRY(a, b, $c2, +($_), $p2, $next);" for @$diff; + print " house[a].$p1 = 0; } return 0; }"; + } + + print "int main() { @pre return !work$idx(); }"; +} + +sub make_c { + do_consts; + make_conditions; +} + +# ---- above should be generic for all similar puzzles ---- # + +# ---- below: per puzzle setup ---- # +# property names and values +setprops ( + 'nationality' # Svensk n. a Swede, not a swede (kålrot). + # AEnglisk (from middle Viking "Æŋløsåksen") n. a Brit. + => [ qw(Deutsch Svensk Norske Danske AEnglisk) ], + 'pet' => [ qw(birds dog horse zebra cats) ], + 'drink' => [ qw(water tea milk beer coffee) ], + 'smoke' => [ qw(dunhill blue_master prince blend pall_mall) ], + 'color' => [ qw(red green yellow white blue) ] +); + +# constraints +pair(AEnglisk, red); +pair(Svensk, dog); +pair(Danske, tea); +pair(green, white, 1); # "to the left of" can mean either 1 or -1: ambiguous +pair(coffee, green); +pair(pall_mall, birds); +pair(yellow, dunhill); +pair(2, milk); +pair(0, Norske); +pair(blend, cats, [-1, 1]); +pair(horse, dunhill, [-1, 1]); +pair(blue_master, beer); # Nicht das Deutsche Bier trinken? Huh. +pair(Deutsch, prince); +pair(Norske, blue, [-1, 1]); +pair(water, blend, [-1, 1]); + +# "zebra lives *somewhere* relative to the Brit". It has no effect on +# the logic. It's here just to make sure the code will insert a zebra +# somewhere in the table (after all other conditions are met) so the +# final print-out shows it. (the C code can be better structured, but +# meh, I ain't reading it, so who cares). +pair(zebra, AEnglisk, [ -4 .. 4 ]); + +# write C code. If it's ugly to you: I didn't write; Perl did. +make_c; diff --git a/Task/Zebra-puzzle/D/zebra-puzzle-1.d b/Task/Zebra-puzzle/D/zebra-puzzle-1.d new file mode 100644 index 0000000000..b56bc4ad6f --- /dev/null +++ b/Task/Zebra-puzzle/D/zebra-puzzle-1.d @@ -0,0 +1,96 @@ +import std.stdio, std.traits, std.algorithm, std.math; + +enum Content { Beer, Coffee, Milk, Tea, Water, + Danish, English, German, Norwegian, Swedish, + Blue, Green, Red, White, Yellow, + Blend, BlueMaster, Dunhill, PallMall, Prince, + Bird, Cat, Dog, Horse, Zebra } +enum Test { Drink, Person, Color, Smoke, Pet } +enum House { One, Two, Three, Four, Five } + +alias Content[EnumMembers!Test.length][EnumMembers!House.length] TM; + +bool finalChecks(in ref TM M) pure nothrow { + int diff(in Content a, in Content b, in Test ca, in Test cb) + nothrow { + foreach (immutable h1; EnumMembers!House) + foreach (immutable h2; EnumMembers!House) + if (M[ca][h1] == a && M[cb][h2] == b) + return h1 - h2; + assert(0); // Useless but required. + } + + with (Content) with (Test) { // Braces required (8414). + return abs(diff(Norwegian, Blue, Person, Color)) == 1 && + diff(Green, White, Color, Color) == -1 && + abs(diff(Horse, Dunhill, Pet, Smoke)) == 1 && + abs(diff(Water, Blend, Drink, Smoke)) == 1 && + abs(diff(Blend, Cat, Smoke, Pet)) == 1; + } +} + +bool constrained(in ref TM M, in Test atest) pure nothrow { + with (Content) with (Test) with (House) + final switch (atest) { + case Drink: + return M[Drink][Three] == Milk; + case Person: + foreach (immutable h; EnumMembers!House) + if ((M[Person][h] == Norwegian && h != One) || + (M[Person][h] == Danish && M[Drink][h] != Tea)) + return false; + return true; + case Color: + foreach (immutable h; EnumMembers!House) + if ((M[Person][h] == English && M[Color][h] != Red) || + (M[Drink][h] == Coffee && M[Color][h] != Green)) + return false; + return true; + case Smoke: + foreach (immutable h; EnumMembers!House) + if ((M[Color][h] == Yellow && M[Smoke][h] != Dunhill) || + (M[Smoke][h] == BlueMaster && M[Drink][h] != Beer) || + (M[Person][h] == German && M[Smoke][h] != Prince)) + return false; + return true; + case Pet: + foreach (immutable h; EnumMembers!House) + if ((M[Person][h] == Swedish && M[Pet][h] != Dog) || + (M[Smoke][h] == PallMall && M[Pet][h] != Bird)) + return false; + return finalChecks(M); + } +} + +void show(in ref TM M) { + foreach (h; EnumMembers!House) { + writef("%5s: ", h); + foreach (immutable t; EnumMembers!Test) + writef("%10s ", M[t][h]); + writeln(); + } +} + +void solve(ref TM M, in Test t, in size_t n) { + if (n == 1 && constrained(M, t)) { + if (t < 4) { + solve(M, [EnumMembers!Test][t + 1], 5); + } else { + show(M); + return; + } + } + foreach (immutable i; 0 .. n) { + solve(M, t, n - 1); + swap(M[t][n % 2 ? 0 : i], M[t][n - 1]); + } +} + +void main() { + TM M; + foreach (immutable t; EnumMembers!Test) + foreach (immutable h; EnumMembers!House) + M[t][h] = EnumMembers!Content[t * 5 + h]; + + solve(M, Test.Drink, 5); +} diff --git a/Task/Zebra-puzzle/D/zebra-puzzle-2.d b/Task/Zebra-puzzle/D/zebra-puzzle-2.d new file mode 100644 index 0000000000..bd2c29cf96 --- /dev/null +++ b/Task/Zebra-puzzle/D/zebra-puzzle-2.d @@ -0,0 +1,101 @@ +import std.stdio, std.math, std.traits, std.typetuple; + +const(T[N][]) permutationsFixed(T, size_t N)(in T[N] items) +pure nothrow { + const(T[N])[] result; + T[N] row; + + void perms(in T[] s, in T[] prefix=null) nothrow { + if (s.length) + foreach (immutable i, immutable c; s) + perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c); + else { + row[] = prefix[]; + result ~= row; + } + } + + perms(items); + return result; +} + +enum Number : uint { One, Two, Three, Four, Five } +enum Color : uint { Red, Green, Blue, White, Yellow } +enum Drink : uint { Milk, Coffee, Water, Beer, Tea } +enum Smoke : uint { PallMall, Dunhill, Blend, BlueMaster, Prince } +enum Pet : uint { Dog, Cat, Zebra, Horse, Bird } +enum Nation : uint { British, Swedish, Danish, Norvegian, German } + +bool isPossible(immutable(Number[5])* number, + immutable(Color[5])* color=null, + immutable(Drink[5])* drink=null, + immutable(Smoke[5])* smoke=null, + immutable(Pet[5])* pet=null + ) pure nothrow { + if ((number && (*number)[Nation.Norvegian] != Number.One) || + (color && (*color)[Nation.British] != Color.Red) || + (drink && (*drink)[Nation.Danish] != Drink.Tea) || + (smoke && (*smoke)[Nation.German] != Smoke.Prince) || + (pet && (*pet)[Nation.Swedish] != Pet.Dog)) + return false; + + if (!number || !color || !drink || !smoke || !pet) + return true; + + foreach (immutable i; 0 .. 5) { + if (((*color)[i] == Color.Green && (*drink)[i] != Drink.Coffee) || + ((*smoke)[i] == Smoke.PallMall && (*pet)[i] != Pet.Bird) || + ((*color)[i] == Color.Yellow && (*smoke)[i] != Smoke.Dunhill) || + ((*number)[i] == Number.Three && (*drink)[i] != Drink.Milk) || + ((*smoke)[i] == Smoke.BlueMaster && (*drink)[i] != Drink.Beer)|| + ((*color)[i] == Color.Blue && (*number)[i] != Number.Two)) + return false; + + foreach (immutable j; 0 .. 5) { + if ((*color)[i] == Color.Green && (*color)[j] == Color.White && + (*number)[j] - (*number)[i] != 1) + return false; + + immutable int diff = abs((*number)[i] - (*number)[j]); + if (((*smoke)[i] == Smoke.Blend && + (*pet)[j] == Pet.Cat && diff != 1) || + ((*pet)[i] == Pet.Horse && + (*smoke)[j] == Smoke.Dunhill && diff != 1) || + ((*smoke)[i] == Smoke.Blend && + (*drink)[j] == Drink.Water && diff != 1)) + return false; + } + } + + return true; +} + +void main() { + static immutable perms = permutationsFixed!(uint, 5)([0,1,2,3,4]); + // Not nice casts. + static permsNumber = cast(immutable(Number[5][]))perms; + static permsColor = cast(immutable(Color[5][]))perms; + static permsDrink = cast(immutable(Drink[5][]))perms; + static permsSmoke = cast(immutable(Smoke[5][]))perms; + static permsPet = cast(immutable(Pet[5][]))perms; + immutable nation = [EnumMembers!Nation]; + + foreach (immutable ref number; permsNumber) + if (isPossible(&number)) + foreach (immutable ref color; permsColor) + if (isPossible(&number, &color)) + foreach (immutable ref drink; permsDrink) + if (isPossible(&number, &color, &drink)) + foreach (immutable ref smoke; permsSmoke) + if (isPossible(&number, &color, &drink, &smoke)) + foreach (immutable ref pet; permsPet) + if (isPossible(&number,&color,&drink,&smoke,&pet)) { + writeln("Found a solution:"); + foreach (x; TypeTuple!(nation, number, color, + drink, smoke, pet)) + writefln("%6s: %12s%12s%12s%12s%12s", + (Unqual!(typeof(x[0]))).stringof, + x[0], x[1], x[2], x[3], x[4]); + writeln(); + } +} diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-1.j b/Task/Zebra-puzzle/J/zebra-puzzle-1.j new file mode 100644 index 0000000000..3a97c1da26 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-1.j @@ -0,0 +1,13 @@ +ehs=: 5$a: + +cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs +cr=: cr, (('German';'Prince') 0 4}ehs);<('Swede';'dog') 0 1 }ehs + +cs=: <('PallMall';'birds') 4 1}ehs +cs=: cs, (('yellow';'Dunhill') 3 4}ehs);<('BlueMaster';'beer') 4 2}ehs + +lof=: (('coffee';'green')2 3}ehs);<(<'white')3}ehs + +next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs +next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs +next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-10.j b/Task/Zebra-puzzle/J/zebra-puzzle-10.j new file mode 100644 index 0000000000..eea43ac714 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-10.j @@ -0,0 +1,12 @@ + houses solve3 constraints, next diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-4.j b/Task/Zebra-puzzle/J/zebra-puzzle-4.j new file mode 100644 index 0000000000..55bcd68d29 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-4.j @@ -0,0 +1 @@ +houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs;#S:0)"1 +compose=: [: filter f. [: ,/ select f. L:0"1"1 _ + +solve=: 4 :0 +h=. ,:x +whilst. 0=# z do. + for_e. y do. h=. h compose > e end. + z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h +end. +) diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-8.j b/Task/Zebra-puzzle/J/zebra-puzzle-8.j new file mode 100644 index 0000000000..6117d6a177 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-8.j @@ -0,0 +1,12 @@ + >"0 houses solve constraints +┌─────────┬─────┬──────┬──────┬──────────┐ +│Norwegian│cats │water │yellow│Dunhill │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Dane │horse│tea │blue │Blend │ +├─────────┼─────┼──────┼──────┼──────────┤ +│English │birds│milk │red │PallMall │ +├─────────┼─────┼──────┼──────┼──────────┤ +│German │ │coffee│green │Prince │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Swede │dog │beer │white │BlueMaster│ +└─────────┴─────┴──────┴──────┴──────────┘ diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-9.j b/Task/Zebra-puzzle/J/zebra-puzzle-9.j new file mode 100644 index 0000000000..4ca962c4d5 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-9.j @@ -0,0 +1,8 @@ +zebra=: (-i.5)|."0 1 (<(<'zebra') 1}ehs),4$ [: compose&.>~/y&, f. +z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x +>"0 (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z +) diff --git a/Task/Zebra-puzzle/Perl/zebra-puzzle-1.pl b/Task/Zebra-puzzle/Perl/zebra-puzzle-1.pl new file mode 100644 index 0000000000..8e9660e5ec --- /dev/null +++ b/Task/Zebra-puzzle/Perl/zebra-puzzle-1.pl @@ -0,0 +1,104 @@ +#!/usr/bin/perl + +use utf8; +use strict; +binmode STDOUT, ":utf8"; + +my (@tgt, %names); +sub setprops { + my %h = @_; + my @p = keys %h; + for my $p (@p) { + my @v = @{ $h{$p} }; + @tgt = map(+{idx=>$_-1, map{ ($_, undef) } @p}, 1 .. @v) + unless @tgt; + $names{$_} = $p for @v; + } +} + +my $solve = sub { + for my $i (@tgt) { + printf("%12s", ucfirst($i->{$_} // "¿Qué?")) + for reverse sort keys %$i; + print "\n"; + } + "there is only one" # <--- change this to a false value to find all solutions (if any) +}; + +sub pair { + my ($a, $b, @v) = @_; + if ($a =~ /^(\d+)$/) { + $tgt[$1]{ $names{$b} } = $b; + return; + } + + @v = (0) unless @v; + my %allowed; + $allowed{$_} = 1 for @v; + + my ($p1, $p2) = ($names{$a}, $names{$b}); + + my $e = $solve; + $solve = sub { # <--- sorta like how TeX \let...\def macro + my ($x, $y); + + ($x) = grep { $_->{$p1} eq $a } @tgt; + ($y) = grep { $_->{$p2} eq $b } @tgt; + + $x and $y and + return $allowed{ $x->{idx} - $y->{idx} } && $e->(); + + my $try_stuff = sub { + my ($this, $p, $v, $sign) = @_; + for (@v) { + my $i = $this->{idx} + $sign * $_; + next unless $i >= 0 && $i < @tgt && !$tgt[$i]{$p}; + local $tgt[$i]{$p} = $v; + $e->() and return 1; + } + return + }; + + $x and return $try_stuff->($x, $p2, $b, 1); + $y and return $try_stuff->($y, $p1, $a, -1); + + for $x (@tgt) { + next if $x->{$p1}; + local $x->{$p1} = $a; + $try_stuff->($x, $p2, $b, 1) and return 1; + } + }; +} + +# ---- above should be generic for all similar puzzles ---- # + +# ---- below: per puzzle setup ---- # +# property names and values +setprops ( + # Svensk n. a Swede, not a swede (kålrot). + # AEnglisk (from middle Viking "Æŋløsåksen") n. a Brit. + 'Who' => [ qw(Deutsch Svensk Norske Danske AEnglisk) ], + 'Pet' => [ qw(birds dog horse zebra cats) ], + 'Drink' => [ qw(water tea milk beer coffee) ], + 'Smoke' => [ qw(dunhill blue_master prince blend pall_mall) ], + 'Color' => [ qw(red green yellow white blue) ] +); + +# constraints +pair qw( AEnglisk red ); +pair qw( Svensk dog ); +pair qw( Danske tea ); +pair qw( green white 1 ); # "to the left of" can mean either 1 or -1: ambiguous +pair qw( coffee green ); +pair qw( pall_mall birds ); +pair qw( yellow dunhill ); +pair qw( 2 milk ); +pair qw( 0 Norske ); +pair qw( blend cats -1 1 ); +pair qw( horse dunhill -1 1 ); +pair qw( blue_master beer ); # Nicht das Deutsche Bier trinken? Huh. +pair qw( Deutsch prince ); +pair qw( Norske blue -1 1 ); +pair qw( water blend -1 1 ); + +$solve->(); diff --git a/Task/Zebra-puzzle/Perl/zebra-puzzle-2.pl b/Task/Zebra-puzzle/Perl/zebra-puzzle-2.pl new file mode 100644 index 0000000000..f3cd752516 --- /dev/null +++ b/Task/Zebra-puzzle/Perl/zebra-puzzle-2.pl @@ -0,0 +1,21 @@ +... +# property names and values +setprops + 'Who' => [ qw(baker cooper fletcher miller smith) ], + 'Level' => [ qw(one two three four five) ]; + +# constraints +pair qw(0 one); +pair qw(1 two); +pair qw(2 three); +pair qw(3 four); +pair qw(4 five); +pair qw(baker five -4 -3 -2 -1 1 2 3 4); +pair qw(cooper one -4 -3 -2 -1 1 2 3 4); +pair qw(fletcher one -4 -3 -2 -1 1 2 3 4); +pair qw(fletcher five -4 -3 -2 -1 1 2 3 4); +pair qw(miller cooper -1 -2 -3 -4); +pair qw(smith fletcher 4 3 2 -2 -3 -4); +pair qw(cooper fletcher 4 3 2 -2 -3 -4); + +$solve->(); diff --git a/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-1.l b/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-1.l new file mode 100644 index 0000000000..96ebb0d19b --- /dev/null +++ b/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-1.l @@ -0,0 +1,41 @@ +(be match (@House @Person @Drink @Pet @Cigarettes) + (permute (red blue green yellow white) @House) + (left-of @House white @House green) + + (permute (Norwegian English Swede German Dane) @Person) + (has @Person English @House red) + (equal @Person (Norwegian . @)) + (next-to @Person Norwegian @House blue) + + (permute (tea coffee milk beer water) @Drink) + (has @Drink tea @Person Dane) + (has @Drink coffee @House green) + (equal @Drink (@ @ milk . @)) + + (permute (dog birds cats horse zebra) @Pet) + (has @Pet dog @Person Swede) + + (permute (Pall-Mall Dunhill Blend Blue-Master Prince) @Cigarettes) + (has @Cigarettes Pall-Mall @Pet birds) + (has @Cigarettes Dunhill @House yellow) + (next-to @Cigarettes Blend @Pet cats) + (next-to @Cigarettes Dunhill @Pet horse) + (has @Cigarettes Blue-Master @Drink beer) + (has @Cigarettes Prince @Person German) + + (next-to @Drink water @Cigarettes Blend) ) + +(be has ((@A . @X) @A (@B . @Y) @B)) +(be has ((@ . @X) @A (@ . @Y) @B) + (has @X @A @Y @B) ) + +(be right-of ((@A . @X) @A (@ @B . @Y) @B)) +(be right-of ((@ . @X) @A (@ . @Y) @B) + (right-of @X @A @Y @B) ) + +(be left-of ((@ @A . @X) @A (@B . @Y) @B)) +(be left-of ((@ . @X) @A (@ . @Y) @B) + (left-of @X @A @Y @B) ) + +(be next-to (@X @A @Y @B) (right-of @X @A @Y @B)) +(be next-to (@X @A @Y @B) (left-of @X @A @Y @B)) diff --git a/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-2.l b/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-2.l new file mode 100644 index 0000000000..20b4d88e89 --- /dev/null +++ b/Task/Zebra-puzzle/PicoLisp/zebra-puzzle-2.l @@ -0,0 +1,5 @@ +(pilog '((match @House @Person @Drink @Pet @Cigarettes)) + (let Fmt (-8 -11 -8 -7 -11) + (tab Fmt "HOUSE" "PERSON" "DRINKS" "HAS" "SMOKES") + (mapc '(@ (pass tab Fmt)) + @House @Person @Drink @Pet @Cigarettes ) ) ) diff --git a/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro b/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro new file mode 100644 index 0000000000..d593d97eaa --- /dev/null +++ b/Task/Zebra-puzzle/Prolog/zebra-puzzle.pro @@ -0,0 +1,22 @@ +select([A|As],S):- select(A,S,S1),select(As,S1). +select([],_). + +next_to(A,B,C):- left_of(A,B,C) ; left_of(B,A,C). +left_of(A,B,C):- append(_,[A,B|_],C). + +zebra(Owns, HS):- % color,nation,pet,drink,smokes + HS = [h(_,norwegian,_,_,_),_,h(_,_,_,milk,_),_,_], + select( [h(red,englishman,_,_,_),h(_,swede,dog,_,_),h(_,dane,_,tea,_), + h(_,german,_,_,prince)], HS), + select( [h(_,_,birds,_,pallmall),h(yellow,_,_,_,dunhill), + h(_,_,_,beer,bluemaster)], HS), + left_of( h(green,_,_,coffee,_),h(white,_,_,_,_), HS), + next_to( h(_,_,_,_,dunhill), h(_,_,horse,_,_), HS), + next_to( h(_,_,_,_,blend), h(_,_,cats, _,_), HS), + next_to( h(_,_,_,_,blend), h(_,_,_,water,_), HS), + next_to( h(_,norwegian,_,_,_), h(blue,_,_,_,_), HS), + member( h(_,Owns,zebra,_,_), HS). + +:- zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail + ; + write('No more solutions.'). diff --git a/Task/Zebra-puzzle/Python/zebra-puzzle-1.py b/Task/Zebra-puzzle/Python/zebra-puzzle-1.py new file mode 100644 index 0000000000..84cb78bf95 --- /dev/null +++ b/Task/Zebra-puzzle/Python/zebra-puzzle-1.py @@ -0,0 +1,101 @@ +import psyco; psyco.full() + +class Content: elems= """Beer Coffee Milk Tea Water + Danish English German Norwegian Swedish + Blue Green Red White Yellow + Blend BlueMaster Dunhill PallMall Prince + Bird Cat Dog Horse Zebra""".split() +class Test: elems= "Drink Person Color Smoke Pet".split() +class House: elems= "One Two Three Four Five".split() + +for c in (Content, Test, House): + c.values = range(len(c.elems)) + for i, e in enumerate(c.elems): + exec "%s.%s = %d" % (c.__name__, e, i) + +def finalChecks(M): + def diff(a, b, ca, cb): + for h1 in House.values: + for h2 in House.values: + if M[ca][h1] == a and M[cb][h2] == b: + return h1 - h2 + assert False + + return abs(diff(Content.Norwegian, Content.Blue, + Test.Person, Test.Color)) == 1 and \ + diff(Content.Green, Content.White, + Test.Color, Test.Color) == -1 and \ + abs(diff(Content.Horse, Content.Dunhill, + Test.Pet, Test.Smoke)) == 1 and \ + abs(diff(Content.Water, Content.Blend, + Test.Drink, Test.Smoke)) == 1 and \ + abs(diff(Content.Blend, Content.Cat, + Test.Smoke, Test.Pet)) == 1 + +def constrained(M, atest): + if atest == Test.Drink: + return M[Test.Drink][House.Three] == Content.Milk + elif atest == Test.Person: + for h in House.values: + if ((M[Test.Person][h] == Content.Norwegian and + h != House.One) or + (M[Test.Person][h] == Content.Danish and + M[Test.Drink][h] != Content.Tea)): + return False + return True + elif atest == Test.Color: + for h in House.values: + if ((M[Test.Person][h] == Content.English and + M[Test.Color][h] != Content.Red) or + (M[Test.Drink][h] == Content.Coffee and + M[Test.Color][h] != Content.Green)): + return False + return True + elif atest == Test.Smoke: + for h in House.values: + if ((M[Test.Color][h] == Content.Yellow and + M[Test.Smoke][h] != Content.Dunhill) or + (M[Test.Smoke][h] == Content.BlueMaster and + M[Test.Drink][h] != Content.Beer) or + (M[Test.Person][h] == Content.German and + M[Test.Smoke][h] != Content.Prince)): + return False + return True + elif atest == Test.Pet: + for h in House.values: + if ((M[Test.Person][h] == Content.Swedish and + M[Test.Pet][h] != Content.Dog) or + (M[Test.Smoke][h] == Content.PallMall and + M[Test.Pet][h] != Content.Bird)): + return False + return finalChecks(M) + +def show(M): + for h in House.values: + print "%5s:" % House.elems[h], + for t in Test.values: + print "%10s" % Content.elems[M[t][h]], + print + +def solve(M, t, n): + if n == 1 and constrained(M, t): + if t < 4: + solve(M, Test.values[t + 1], 5) + else: + show(M) + return + + for i in xrange(n): + solve(M, t, n - 1) + M[t][0 if n % 2 else i], M[t][n - 1] = \ + M[t][n - 1], M[t][0 if n % 2 else i] + +def main(): + M = [[None] * len(Test.elems) for _ in xrange(len(House.elems))] + for t in Test.values: + for h in House.values: + M[t][h] = Content.values[t * 5 + h] + + solve(M, Test.Drink, 5) + +main() diff --git a/Task/Zebra-puzzle/Python/zebra-puzzle-2.py b/Task/Zebra-puzzle/Python/zebra-puzzle-2.py new file mode 100644 index 0000000000..ee8e55bc04 --- /dev/null +++ b/Task/Zebra-puzzle/Python/zebra-puzzle-2.py @@ -0,0 +1,89 @@ +from itertools import permutations +import psyco +psyco.full() + +class Number:elems= "One Two Three Four Five".split() +class Color: elems= "Red Green Blue White Yellow".split() +class Drink: elems= "Milk Coffee Water Beer Tea".split() +class Smoke: elems= "PallMall Dunhill Blend BlueMaster Prince".split() +class Pet: elems= "Dog Cat Zebra Horse Bird".split() +class Nation:elems= "British Swedish Danish Norvegian German".split() + +for c in (Number, Color, Drink, Smoke, Pet, Nation): + for i, e in enumerate(c.elems): + exec "%s.%s = %d" % (c.__name__, e, i) + +def is_possible(number, color, drink, smoke, pet): + if number and number[Nation.Norvegian] != Number.One: + return False + if color and color[Nation.British] != Color.Red: + return False + if drink and drink[Nation.Danish] != Drink.Tea: + return False + if smoke and smoke[Nation.German] != Smoke.Prince: + return False + if pet and pet[Nation.Swedish] != Pet.Dog: + return False + + if not number or not color or not drink or not smoke or not pet: + return True + + for i in xrange(5): + if color[i] == Color.Green and drink[i] != Drink.Coffee: + return False + if smoke[i] == Smoke.PallMall and pet[i] != Pet.Bird: + return False + if color[i] == Color.Yellow and smoke[i] != Smoke.Dunhill: + return False + if number[i] == Number.Three and drink[i] != Drink.Milk: + return False + if smoke[i] == Smoke.BlueMaster and drink[i] != Drink.Beer: + return False + if color[i] == Color.Blue and number[i] != Number.Two: + return False + + for j in xrange(5): + if (color[i] == Color.Green and + color[j] == Color.White and + number[j] - number[i] != 1): + return False + + diff = abs(number[i] - number[j]) + if smoke[i] == Smoke.Blend and pet[j] == Pet.Cat and diff != 1: + return False + if pet[i]==Pet.Horse and smoke[j]==Smoke.Dunhill and diff != 1: + return False + if smoke[i]==Smoke.Blend and drink[j]==Drink.Water and diff!=1: + return False + + return True + +def show_row(t, data): + print "%6s: %12s%12s%12s%12s%12s" % ( + t.__name__, t.elems[data[0]], + t.elems[data[1]], t.elems[data[2]], + t.elems[data[3]], t.elems[data[4]]) + +def main(): + perms = list(permutations(range(5))) + + for number in perms: + if is_possible(number, None, None, None, None): + for color in perms: + if is_possible(number, color, None, None, None): + for drink in perms: + if is_possible(number, color, drink, None, None): + for smoke in perms: + if is_possible(number, color, drink, smoke, None): + for pet in perms: + if is_possible(number, color, drink, smoke, pet): + print "Found a solution:" + show_row(Nation, range(5)) + show_row(Number, number) + show_row(Color, color) + show_row(Drink, drink) + show_row(Smoke, smoke) + show_row(Pet, pet) + print + +main() diff --git a/Task/Zebra-puzzle/Racket/zebra-puzzle.rkt b/Task/Zebra-puzzle/Racket/zebra-puzzle.rkt new file mode 100644 index 0000000000..0a21e107ea --- /dev/null +++ b/Task/Zebra-puzzle/Racket/zebra-puzzle.rkt @@ -0,0 +1,57 @@ +#lang racket + +(require racklog) + +(define %select + (%rel (x xs S S1) + [(x (cons x xs) xs)] + [(x (cons S xs) (cons S S1)) (%select x xs S1)] + [((cons x xs) S) + (%select x S S1) + (%select xs S1)] + [('() (_))])) + +(define %next-to + (%rel (A B C) + [(A B C) + (%or (%left-of A B C) + (%left-of B A C))])) + +(define %left-of + (%rel (A B C) + [(A B C) (%append (_) (cons A (cons B (_))) C)])) + +(define %zebra + (%rel (Owns HS) + [(Owns HS) + (%is HS (list (list (_) 'norwegian (_) (_) (_)) + (_) + (list (_) (_) (_) 'milk (_)) + (_) (_))) + (%select (list (list 'red 'englishman (_) (_) (_)) + (list (_) 'swede 'dog (_) (_)) + (list (_) 'dane (_) 'tea (_)) + (list (_) 'german (_) (_) 'prince)) + HS) + (%select (list (list (_) (_) 'birds (_) 'pallmall) + (list 'yellow (_) (_) (_) 'dunhill) + (list (_) (_) (_) 'beer 'bluemaster)) + HS) + (%left-of (list 'green (_) (_) 'coffee (_)) + (list 'white (_) (_) (_) (_)) + HS) + (%next-to (list (_) (_) (_) (_) 'dunhill) + (list (_) (_) 'horse (_) (_)) + HS) + (%next-to (list (_) (_) (_) (_) 'blend) + (list (_) (_) 'cats (_) (_)) + HS) + (%next-to (list (_) (_) (_) (_) 'blend) + (list (_) (_) (_) 'water (_)) + HS) + (%next-to (list (_) 'norwegian (_) (_) (_)) + (list 'blue (_) (_) (_) (_)) + HS) + (%member (list (_) Owns 'zebra (_) (_)) HS)])) + +(%which (Who HS) (%zebra Who HS)) diff --git a/Task/Zebra-puzzle/Tcl/zebra-puzzle.tcl b/Task/Zebra-puzzle/Tcl/zebra-puzzle.tcl new file mode 100644 index 0000000000..cdea00a245 --- /dev/null +++ b/Task/Zebra-puzzle/Tcl/zebra-puzzle.tcl @@ -0,0 +1,116 @@ +package require struct::list + +# Implements the constants by binding them directly into the named procedures. +# This is much faster than the alternatives! +proc initConstants {args} { + global {} + set remap {} + foreach {class elems} { + Number {One Two Three Four Five} + Color {Red Green Blue White Yellow} + Drink {Milk Coffee Water Beer Tea} + Smoke {PallMall Dunhill Blend BlueMaster Prince} + Pet {Dog Cat Horse Bird Zebra} + Nation {British Swedish Danish Norwegian German} + } { + set i -1 + foreach e $elems {lappend remap "\$${class}($e)" [incr i]} + set ($class) $elems + } + foreach procedure $args { + proc $procedure [info args $procedure] \ + [string map $remap [info body $procedure]] + } +} + +proc isPossible {number color drink smoke pet} { + if {[llength $number] && [lindex $number $Nation(Norwegian)] != $Number(One)} { + return false + } elseif {[llength $color] && [lindex $color $Nation(British)] != $Color(Red)} { + return false + } elseif {[llength $drink] && [lindex $drink $Nation(Danish)] != $Drink(Tea)} { + return false + } elseif {[llength $smoke] && [lindex $smoke $Nation(German)] != $Smoke(Prince)} { + return false + } elseif {[llength $pet] && [lindex $pet $Nation(Swedish)] != $Pet(Dog)} { + return false + } + + if {!([llength $number] && [llength $color] && [llength $drink] && [llength $smoke] && [llength $pet])} { + return true + } + + for {set i 0} {$i < 5} {incr i} { + if {[lindex $color $i] == $Color(Green) && [lindex $drink $i] != $Drink(Coffee)} { + return false + } elseif {[lindex $smoke $i] == $Smoke(PallMall) && [lindex $pet $i] != $Pet(Bird)} { + return false + } elseif {[lindex $color $i] == $Color(Yellow) && [lindex $smoke $i] != $Smoke(Dunhill)} { + return false + } elseif {[lindex $number $i] == $Number(Three) && [lindex $drink $i] != $Drink(Milk)} { + return false + } elseif {[lindex $smoke $i] == $Smoke(BlueMaster) && [lindex $drink $i] != $Drink(Beer)} { + return false + } elseif {[lindex $color $i] == $Color(Blue) && [lindex $number $i] != $Number(Two)} { + return false + } + + for {set j 0} {$j < 5} {incr j} { + if {[lindex $color $i] == $Color(Green) && [lindex $color $j] == $Color(White) && [lindex $number $j] - [lindex $number $i] != 1} { + return false + } + + set diff [expr {abs([lindex $number $i] - [lindex $number $j])}] + if {[lindex $smoke $i] == $Smoke(Blend) && [lindex $pet $j] == $Pet(Cat) && $diff != 1} { + return false + } elseif {[lindex $pet $i] == $Pet(Horse) && [lindex $smoke $j] == $Smoke(Dunhill) && $diff != 1} { + return false + } elseif {[lindex $smoke $i] == $Smoke(Blend) && [lindex $drink $j] == $Drink(Water) && $diff != 1} { + return false + } + } + } + + return true +} + +proc showRow {t data} { + upvar #0 ($t) elems + puts [format "%6s: %12s%12s%12s%12s%12s" $t \ + [lindex $elems [lindex $data 0]] \ + [lindex $elems [lindex $data 1]] \ + [lindex $elems [lindex $data 2]] \ + [lindex $elems [lindex $data 3]] \ + [lindex $elems [lindex $data 4]]] +} + +proc main {} { + set perms [struct::list permutations {0 1 2 3 4}] + foreach number $perms { + if {![isPossible $number {} {} {} {}]} continue + foreach color $perms { + if {![isPossible $number $color {} {} {}]} continue + foreach drink $perms { + if {![isPossible $number $color $drink {} {}]} continue + foreach smoke $perms { + if {![isPossible $number $color $drink $smoke {}]} continue + foreach pet $perms { + if {[isPossible $number $color $drink $smoke $pet]} { + puts "Found a solution:" + showRow Nation {0 1 2 3 4} + showRow Number $number + showRow Color $color + showRow Drink $drink + showRow Smoke $smoke + showRow Pet $pet + puts "" + } + } + } + } + } + } +} + +initConstants isPossible +main diff --git a/Task/Zeckendorf-arithmetic/0DESCRIPTION b/Task/Zeckendorf-arithmetic/0DESCRIPTION new file mode 100644 index 0000000000..98282268cb --- /dev/null +++ b/Task/Zeckendorf-arithmetic/0DESCRIPTION @@ -0,0 +1,67 @@ +This task is a total immersion zeckendorf task, using decimal numbers will attract serious disapprobation. + +The task is to implement addition, subtraction, multiplication, and division using [[Zeckendorf number representation]]. [[Zeckendorf number representation#Using_a_C.2B.2B11_User_Defined_Literal|Optionally]] provide decrement, increment and comparitive operation functions. + +;Addition +Like binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case. + +Occurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100; + +;Subtraction +10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg: +
    +  abcde
    +  10100 -
    +   1000
    +  _____
    +    100  borrow 1 from a leaves 100
    +  + 100  add the carry
    +  _____
    +   1001
    +
    +A larger example: +
    +  abcdef
    +  100100 -
    +    1000
    +  ______
    +  1*0100 borrow 1 from b
    +   + 100 add the carry
    +  ______
    +  1*1001
    +
    +Sadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:
    +
    +    1001
    +  + 1000 add the carry
    +    ____
    +   10100
    +
    + +;Multiplication +Here you teach your computer its zeckendorf tables. eg. 101 * 1001: +
    +  a = 1 * 101 = 101
    +  b = 10 * 101 = a + a = 10000
    +  c = 100 * 101 = b + a = 10101
    +  d = 1000 * 101 = c + b = 101010
    +
    +  1001 = d + a therefore 101 * 1001 =
    +
    +  101010
    +   + 101
    +  ______
    + 1000100
    +
    + +;Division +Lets try 1000101 divided by 101, so we can use the same table used for addition. +
    +  1000101 -
    +   101010 subtract d (1000 * 101)
    +  _______
    +     1000 -
    +      101 b and c are too large to subtract, so subtract a
    +     ____
    +        1 so 1000101 divided by 101 is d + a (1001) remainder 1
    +
    diff --git a/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-1.cpp b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-1.cpp new file mode 100644 index 0000000000..85a7de4868 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-1.cpp @@ -0,0 +1,72 @@ +// For a class N which implements Zeckendorf numbers: +// I define an increment operation ++() +// I define a comparison operation <=(other N) +// I define an addition operation +=(other N) +// I define a subtraction operation -=(other N) +// Nigel Galloway October 28th., 2012 +#include +enum class zd {N00,N01,N10,N11}; +class N { +private: + int dVal = 0, dLen; + void _a(int i) { + for (;; i++) { + if (dLen < i) dLen = i; + switch ((zd)((dVal >> (i*2)) & 3)) { + case zd::N00: case zd::N01: return; + case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return; + dVal += (1 << (i*2+1)); return; + case zd::N11: dVal &= ~(3 << (i*2)); _b((i+1)*2); + }}} + void _b(int pos) { + if (pos == 0) {++*this; return;} + if (((dVal >> pos) & 1) == 0) { + dVal += 1 << pos; + _a(pos/2); + if (pos > 1) _a((pos/2)-1); + } else { + dVal &= ~(1 << pos); + _b(pos + 1); + _b(pos - ((pos > 1)? 2:1)); + }} + void _c(int pos) { + if (((dVal >> pos) & 1) == 1) {dVal &= ~(1 << pos); return;} + _c(pos + 1); + if (pos > 0) _b(pos - 1); else ++*this; + return; + } +public: + N(char const* x = "0") { + int i = 0, q = 1; + for (; x[i] > 0; i++); + for (dLen = --i/2; i >= 0; i--) {dVal+=(x[i]-48)*q; q*=2; + }} + const N& operator++() {dVal += 1; _a(0); return *this;} + const N& operator+=(const N& other) { + for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _b(GN); + return *this; + } + const N& operator-=(const N& other) { + for (int GN = 0; GN < (other.dLen + 1) * 2; GN++) if ((other.dVal >> GN) & 1 == 1) _c(GN); + for (;((dVal >> dLen*2) & 3) == 0 or dLen == 0; dLen--); + return *this; + } + const N& operator*=(const N& other) { + N Na = other, Nb = other, Nt, Nr; + for (int i = 0; i <= (dLen + 1) * 2; i++) { + if (((dVal >> i) & 1) > 0) Nr += Nb; + Nt = Nb; Nb += Na; Na = Nt; + } + return *this = Nr; + } + const bool operator<=(const N& other) const {return dVal <= other.dVal;} + friend std::ostream& operator<<(std::ostream&, const N&); +}; +N operator "" N(char const* x) {return N(x);} +std::ostream &operator<<(std::ostream &os, const N &G) { + const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; + if (G.dVal == 0) return os << "0"; + os << dig1[(G.dVal >> (G.dLen*2)) & 3]; + for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; + return os; +} diff --git a/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-2.cpp b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-2.cpp new file mode 100644 index 0000000000..3435789933 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-2.cpp @@ -0,0 +1,15 @@ +int main(void) { + N G; + G = 10N; + G += 10N; + std::cout << G << std::endl; + G += 10N; + std::cout << G << std::endl; + G += 1001N; + std::cout << G << std::endl; + G += 1000N; + std::cout << G << std::endl; + G += 10101N; + std::cout << G << std::endl; + return 0; +} diff --git a/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-3.cpp b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-3.cpp new file mode 100644 index 0000000000..36ed1c2999 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-3.cpp @@ -0,0 +1,10 @@ +int main(void) { + N G; + G = 1000N; + G -= 101N; + std::cout << G << std::endl; + G = 10101010N; + G -= 1010101N; + std::cout << G << std::endl; + return 0; +} diff --git a/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-4.cpp b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-4.cpp new file mode 100644 index 0000000000..f126f7bd2e --- /dev/null +++ b/Task/Zeckendorf-arithmetic/C++/zeckendorf-arithmetic-4.cpp @@ -0,0 +1,10 @@ +int main(void) { + N G = 1001N; + G *= 101N; + std::cout << G << std::endl; + + G = 101010N; + G += 101N; + std::cout << G << std::endl; + return 0; +} diff --git a/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 new file mode 100644 index 0000000000..fd65430771 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 @@ -0,0 +1,100 @@ +my $z1 = '1'; # glyph to use for a '1' +my $z0 = '0'; # glyph to use for a '0' + +# helper sub to translate constants into the particular glyphs you used +sub z($a) { $a.trans([<1 0>] => [$z1, $z0]) }; + +######## Zeckendorf comparison operators ######### + +# less than +sub infix:($a, $b) { ($z0 lt $z1) ?? ($a lt $b) !! + ($a.trans([$z1, $z0] => [<1 0>]) lt $b.trans([$z1, $z0] => [<1 0>])) +}; + +# greater than +sub infix:($a, $b) { ($z0 lt $z1) ?? ($a gt $b) !! + ($a.trans([$z1, $z0] => [<1 0>]) gt $b.trans([$z1, $z0] => [<1 0>])) +}; + +# equal +sub infix:($a, $b) { $a eq $b }; + +# not equal +sub infix:($a, $b) { $a ne $b }; + + +######## Operators for Zeckendorf arithmetic ######## + +# post increment +sub postfix:<++z>($a is rw) { + $a = ("$z0$z0"~$a).subst(/("$z0$z0")($z1+ %% $z0)?$/, -> $/ { "$z0$z1" ~ $z0 x $1.chars }); + $a ~~ s/^$z0+//; + $a +} + +# post decrement +sub postfix:<--z>($a is rw) { + $a.=subst(/$z1($z0*)$/, -> $/ {$z0 ~ "$z1$z0" x $0.chars div 2 ~ $z1 x $0.chars mod 2}); + $a ~~ s/^$z0+(.+)$/$0/; + $a +} + +# addition +sub infix:<+z>($a is copy, $b is copy) { $a++z while $b--z nez $z0; $a }; + +# subtraction +sub infix:<-z>($a is copy, $b is copy) { $a--z while $b--z nez $z0; $a }; + +# multiplication +sub infix:<*z>($a, $b) { + return $z0 if $a eq $z0 or $b eq $z0; + return $a if $b eq $z1; + return $b if $a eq $z1; + my $c = $a; + my $d = $z1; + repeat { + my $e = $z0; + repeat { $c++z; $e++z } until $e eqz $a; + $d++z; + } until $d eqz $b; + $c +}; + +# division (really more of a div mod) +sub infix:($a is copy, $b is copy) { + fail "Divide by zero" if $b eqz $z0; + return $a if $a eqz $z0 or $b eqz $z1; + my $c = $z0; + repeat { + my $d = $b +z ($z1 ~ $z0); + $c++z; + $a--z while $d--z nez $z0 + } until $a ltz $b; + $c ~= " remainder $a" if $a nez $z0; + $c +}; + + +###################### Testing ###################### + +say "Using the glyph '$z1' for 1 and '$z0' for 0\n"; + +my $fmt = "%-22s = %15s %s\n"; + +my $zeck = $z1; + +printf( $fmt, "$zeck++z", $zeck++z, '# increment' ) for 1 .. 10; + +printf $fmt, "$zeck +z {z('1010')}", $zeck +z= z('1010'), '# addition'; + +printf $fmt, "$zeck -z {z('100')}", $zeck -z= z('100'), '# subtraction'; + +printf $fmt, "$zeck *z {z('100101')}", $zeck *z= z('100101'), '# multiplication'; + +printf $fmt, "$zeck /z {z('100')}", $zeck /z= z('100'), '# division'; + +printf( $fmt, "$zeck--z", $zeck--z, '# decrement' ) for 1 .. 5; + +printf $fmt, "$zeck *z {z('101001')}", $zeck *z= z('101001'), '# multiplication'; + +printf $fmt, "$zeck /z {z('100')}", $zeck /z= z('100'), '# division'; diff --git a/Task/Zeckendorf-number-representation/0DESCRIPTION b/Task/Zeckendorf-number-representation/0DESCRIPTION new file mode 100644 index 0000000000..3d3b72d4f3 --- /dev/null +++ b/Task/Zeckendorf-number-representation/0DESCRIPTION @@ -0,0 +1,11 @@ +Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. + +Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. + +10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. + +The task is to generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. See +[http://oeis.org/A014417 OEIS A014417] for the the sequence of required results. +Cf: +* [[Fibonacci sequence]] +* [http://www.youtube.com/watch?v=kQZmZRE0cQY&list=UUoxcjq-8xIDTYp3uz647V5A&index=3&feature=plcp Brown's Criterion - Numberphile] diff --git a/Task/Zeckendorf-number-representation/AutoIt/zeckendorf-number-representation.autoit b/Task/Zeckendorf-number-representation/AutoIt/zeckendorf-number-representation.autoit new file mode 100644 index 0000000000..715635b464 --- /dev/null +++ b/Task/Zeckendorf-number-representation/AutoIt/zeckendorf-number-representation.autoit @@ -0,0 +1,42 @@ +For $i = 0 To 20 + ConsoleWrite($i &": "& Zeckendorf($i)&@CRLF) +Next + +Func Zeckendorf($int, $Fibarray = "") + If Not IsArray($Fibarray) Then $Fibarray = Fibonacci($int) + Local $ret = "" + For $i = UBound($Fibarray) - 1 To 1 Step -1 + If $Fibarray[$i] > $int And $ret = "" Then ContinueLoop ; dont use Leading Zeros + If $Fibarray[$i] > $int Then + $ret &= "0" + Else + If StringRight($ret, 1) <> "1" Then + $ret &= "1" + $int -= $Fibarray[$i] + Else + $ret &= "0" + EndIf + EndIf + Next + If $ret = "" Then $ret = "0" + Return $ret +EndFunc ;==>Zeckendorf + +Func Fibonacci($max) + $AList = ObjCreate("System.Collections.ArrayList") + $AList.add("0") + $current = 0 + While True + If $current > 1 Then + $count = $AList.Count + $current = $AList.Item($count - 1) + $current = $current + $AList.Item($count - 2) + Else + $current += 1 + EndIf + $AList.add($current) + If $current > $max Then ExitLoop + WEnd + $Array = $AList.ToArray + Return $Array +EndFunc ;==>Fibonacci diff --git a/Task/Zeckendorf-number-representation/BBC-BASIC/zeckendorf-number-representation.bbc b/Task/Zeckendorf-number-representation/BBC-BASIC/zeckendorf-number-representation.bbc new file mode 100644 index 0000000000..fada42f70e --- /dev/null +++ b/Task/Zeckendorf-number-representation/BBC-BASIC/zeckendorf-number-representation.bbc @@ -0,0 +1,27 @@ + FOR n% = 0 TO 20 + PRINT n% RIGHT$(" " + FNzeckendorf(n%), 8) + NEXT + PRINT '"Checking numbers up to 10000..." + FOR n% = 21 TO 10000 + IF INSTR(FNzeckendorf(n%), "11") STOP + NEXT + PRINT "No Zeckendorf numbers contain consecutive 1's" + END + + DEF FNzeckendorf(n%) + LOCAL i%, o$, fib%() : DIM fib%(45) + fib%(0) = 1 : fib%(1) = 1 : i% = 1 + REPEAT + i% += 1 + fib%(i%) = fib%(i%-1) + fib%(i%-2) + UNTIL fib%(i%) > n% + REPEAT + i% -= 1 + IF n% >= fib%(i%) THEN + o$ += "1" + n% -= fib%(i%) + ELSE + o$ += "0" + ENDIF + UNTIL i% = 1 + = o$ diff --git a/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-1.cpp b/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-1.cpp new file mode 100644 index 0000000000..4221d95f7f --- /dev/null +++ b/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-1.cpp @@ -0,0 +1,35 @@ +// For a class N which implements Zeckendorf numbers: +// I define an increment operation ++() +// I define a comparison operation <=(other N) +// Nigel Galloway October 22nd., 2012 +#include +class N { +private: + int dVal = 0, dLen; +public: + N(char const* x = "0"){ + int i = 0, q = 1; + for (; x[i] > 0; i++); + for (dLen = --i/2; i >= 0; i--) { + dVal+=(x[i]-48)*q; + q*=2; + }} + const N& operator++() { + for (int i = 0;;i++) { + if (dLen < i) dLen = i; + switch ((dVal >> (i*2)) & 3) { + case 0: dVal += (1 << (i*2)); return *this; + case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this; + case 2: dVal &= ~(3 << (i*2)); + }}} + const bool operator<=(const N& other) const {return dVal <= other.dVal;} + friend std::ostream& operator<<(std::ostream&, const N&); +}; +N operator "" N(char const* x) {return N(x);} +std::ostream &operator<<(std::ostream &os, const N &G) { + const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; + if (G.dVal == 0) return os << "0"; + os << dig1[(G.dVal >> (G.dLen*2)) & 3]; + for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; + return os; +} diff --git a/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-2.cpp b/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-2.cpp new file mode 100644 index 0000000000..f645f304bb --- /dev/null +++ b/Task/Zeckendorf-number-representation/C++/zeckendorf-number-representation-2.cpp @@ -0,0 +1,5 @@ +int main(void) { +//for (N G; G <= 101010N; ++G) std::cout << G << std::endl; // from zero to 101010M + for (N G(101N); G <= 101010N; ++G) std::cout << G << std::endl; // from 101N to 101010N + return 0; +} diff --git a/Task/Zeckendorf-number-representation/C/zeckendorf-number-representation.c b/Task/Zeckendorf-number-representation/C/zeckendorf-number-representation.c new file mode 100644 index 0000000000..d6ecafba61 --- /dev/null +++ b/Task/Zeckendorf-number-representation/C/zeckendorf-number-representation.c @@ -0,0 +1,58 @@ +#include + +typedef unsigned long long u64; + +#define FIB_INVALID (~(u64)0) + +u64 fib[] = { + 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, + 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, + 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, + 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, + 267914296, 433494437, 701408733, 1134903170, 1836311903, + 2971215073ULL, 4807526976ULL, 7778742049ULL, 12586269025ULL, + 20365011074ULL, 32951280099ULL, 53316291173ULL, 86267571272ULL, + 139583862445ULL, 225851433717ULL, 365435296162ULL, 591286729879ULL, + 956722026041ULL, 1548008755920ULL, 2504730781961ULL, 4052739537881ULL, + 6557470319842ULL, 10610209857723ULL, 17167680177565ULL, + + 27777890035288ULL // this 65-th one is for range check +}; + +u64 fibbinary(u64 n) +{ + if (n >= fib[64]) return FIB_INVALID; + + u64 ret = 0; + int i; + for (i = 64; i--; ) + if (n >= fib[i]) { + ret |= 1ULL << i; + n -= fib[i]; + } + + return ret; +} + +void bprint(u64 n, int width) +{ + if (width > 64) width = 64; + + u64 b; + for (b = 1ULL << (width - 1); b; b >>= 1) + putchar(b == 1 && !n + ? '0' + : b > n ? ' ' + : b & n ? '1' : '0'); + putchar('\n'); +} + +int main(void) +{ + int i; + + for (i = 0; i <= 20; i++) + printf("%2d:", i), bprint(fibbinary(i), 8); + + return 0; +} diff --git a/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-1.lisp b/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-1.lisp new file mode 100644 index 0000000000..d2a1da26ac --- /dev/null +++ b/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-1.lisp @@ -0,0 +1,15 @@ +(defun zeckendorf (n) + "returns zeckendorf integer of n (see OEIS A003714)" + (let ((fib '(2 1))) + ;; extend Fibonacci sequence long enough + (loop while (<= (car fib) n) do + (push (+ (car fib) (cadr fib)) fib)) + (loop with r = 0 for f in fib do + (setf r (* 2 r)) + (when (>= n f) (setf n (- n f)) + (incf r)) + finally (return r)))) + +;;; task requirement +(loop for i from 0 to 20 do + (format t "~2D: ~2R~%" i (zeckendorf i))) diff --git a/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-2.lisp b/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-2.lisp new file mode 100644 index 0000000000..5fd74126ca --- /dev/null +++ b/Task/Zeckendorf-number-representation/Common-Lisp/zeckendorf-number-representation-2.lisp @@ -0,0 +1,10 @@ +;; Print Zeckendorf numbers upto 20. +;; I have implemented this as a state machine. +;; Nigel Galloway - October 13th., 2012 +;; +(let ((fibz '(13 8 5 3 2 1))) (dotimes (G 21) (progn (format t "~S is " G) + (let ((z 0) (ng G)) (dolist (N fibz) + (if (> z 1) (progn (setq z 1) (format t "~S" 0)) + (if (>= ng N) (progn (setq z 2) (setq ng (- ng N)) (format t "~S" 1)) + (if (= z 1) (format t "~S" 0))))) + (if (= z 0) (format t "~S~%" 0) (format t "~%")))))) diff --git a/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d new file mode 100644 index 0000000000..36d782c197 --- /dev/null +++ b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-1.d @@ -0,0 +1,7 @@ +import std.stdio, std.range, std.algorithm; + +void main() { + writefln("%(%b\n%)", iota(size_t.max) + .filter!q{ !(a & (a >> 1)) } + .take(21)); +} diff --git a/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-2.d b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-2.d new file mode 100644 index 0000000000..487d7c1b1b --- /dev/null +++ b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-2.d @@ -0,0 +1,22 @@ +import std.stdio, std.typecons; + +int zeckendorf(in int n) pure nothrow { + Tuple!(int,"remaining", int,"set") + zr(in int fib0, in int fib1, in int n, in uint bit) pure nothrow { + if (fib1 > n) + return typeof(return)(n, 0); + auto rs = zr(fib1, fib0 + fib1, n, bit + 1); + if (fib1 <= rs.remaining) { + rs.set |= 1 << bit; + rs.remaining -= fib1; + } + return rs; + } + + return zr(1, 1, n, 0)[1]; +} + +void main() { + foreach (i; 0 .. 21) + writefln("%2d: %6b", i, zeckendorf(i)); +} diff --git a/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-3.d b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-3.d new file mode 100644 index 0000000000..ebcd5adb5a --- /dev/null +++ b/Task/Zeckendorf-number-representation/D/zeckendorf-number-representation-3.d @@ -0,0 +1,21 @@ +import std.stdio, std.algorithm, std.range; + +string zeckendorf(size_t n) { + if (n == 0) + return "0"; + auto fibs = recurrence!q{a[n - 1] + a[n - 2]}(1, 2); + + string result; + foreach_reverse (immutable f; fibs.until!(x => x > n).array) { + result ~= (f <= n) ? '1' : '0'; + if (f <= n) + n -= f; + } + + return result; +} + +void main() { + foreach (immutable i; 0 .. 21) + writefln("%2d: %6s", i, i.zeckendorf); +} diff --git a/Task/Zeckendorf-number-representation/Go/zeckendorf-number-representation.go b/Task/Zeckendorf-number-representation/Go/zeckendorf-number-representation.go new file mode 100644 index 0000000000..2d1b7f864a --- /dev/null +++ b/Task/Zeckendorf-number-representation/Go/zeckendorf-number-representation.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +func main() { + for i := 0; i <= 20; i++ { + fmt.Printf("%2d %7b\n", i, zeckendorf(i)) + } +} + +func zeckendorf(n int) int { + // initial arguments of fib0 = 1 and fib1 = 1 will produce + // the Fibonacci sequence {1, 2, 3,..} on the stack as successive + // values of fib1. + _, set := zr(1, 1, n, 0) + return set +} + +func zr(fib0, fib1, n int, bit uint) (remaining, set int) { + if fib1 > n { + return n, 0 + } + // recurse. + // construct sequence on the way in, construct ZR on the way out. + remaining, set = zr(fib1, fib0+fib1, n, bit+1) + if fib1 <= remaining { + set |= 1 << bit + remaining -= fib1 + } + return +} diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs new file mode 100644 index 0000000000..09cd42189a --- /dev/null +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-1.hs @@ -0,0 +1,9 @@ +import Data.Bits +import Numeric + +zeckendorf = map b $ filter ones [0..] where + ones :: Int -> Bool + ones x = 0 == x .&. (x `shiftR` 1) + b x = showIntAtBase 2 ("01"!!) x "" + +main = mapM putStrLn $ take 21 zeckendorf diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-2.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-2.hs new file mode 100644 index 0000000000..21d5eb7d63 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-2.hs @@ -0,0 +1,4 @@ +zeckendorf = "0":"1":[s++[d] | s <- tail zeckendorf, d <- "01", + last s /= '1' || d /= '1'] + +main = mapM putStrLn $ take 21 zeckendorf diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs new file mode 100644 index 0000000000..69144ce1c4 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-3.hs @@ -0,0 +1,11 @@ +import Numeric + +fib = 1 : 1 : zipWith (+) fib (tail fib) +pow2 = iterate (2*) 1 + +zeckendorf = map b z where + z = 0:concat (zipWith f fib pow2) + f x y = map (y+) (take x z) + b x = showIntAtBase 2 ("01"!!) x "" + +main = mapM putStrLn $ take 21 zeckendorf diff --git a/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs new file mode 100644 index 0000000000..b9b9de38a1 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Haskell/zeckendorf-number-representation-4.hs @@ -0,0 +1,10 @@ +fib = 1 : 2 : zipWith (+) fib (tail fib) + +zeckendorf 0 = "0" +zeckendorf n = f n (reverse $ takeWhile (<=n) fib) where + f _ [] = "" + f n (x:xs) + | n < x = '0' : f n xs + | True = '1' : f (n - x) xs + +main = mapM (putStrLn . zeckendorf) [0..20] diff --git a/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j b/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j new file mode 100644 index 0000000000..f7b7e68d1b --- /dev/null +++ b/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j @@ -0,0 +1,27 @@ +fib=: 3 : 0 " 0 + mp=. +/ .* + {.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x +) + +phi=: -:1+%:5 +fi =: 3 : 'n - y.(1=y)-~>.(phi^.%:5)+phi^.y' +fsum=: 3 : 0 + z=. 0$r=. y + while. 3i.3 7 +┌──────┬──────┬──────┬──────┬──────┬──────┬──────┐ +│0 │1 │10 │100 │101 │1000 │1001 │ +├──────┼──────┼──────┼──────┼──────┼──────┼──────┤ +│1010 │10000 │10001 │10010 │10100 │10101 │100000│ +├──────┼──────┼──────┼──────┼──────┼──────┼──────┤ +│100001│100010│100100│100101│101000│101001│101010│ +└──────┴──────┴──────┴──────┴──────┴──────┴──────┘ diff --git a/Task/Zeckendorf-number-representation/Java/zeckendorf-number-representation.java b/Task/Zeckendorf-number-representation/Java/zeckendorf-number-representation.java new file mode 100644 index 0000000000..32c6c432e9 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Java/zeckendorf-number-representation.java @@ -0,0 +1,33 @@ +import java.util.*; + +class Zeckendorf +{ + public static String getZeckendorf(int n) + { + if (n == 0) + return "0"; + List fibNumbers = new ArrayList(); + fibNumbers.add(1); + int nextFib = 2; + while (nextFib <= n) + { + fibNumbers.add(nextFib); + nextFib += fibNumbers.get(fibNumbers.size() - 2); + } + StringBuilder sb = new StringBuilder(); + for (int i = fibNumbers.size() - 1; i >= 0; i--) + { + int fibNumber = fibNumbers.get(i); + sb.append((fibNumber <= n) ? "1" : "0"); + if (fibNumber <= n) + n -= fibNumber; + } + return sb.toString(); + } + + public static void main(String[] args) + { + for (int i = 0; i <= 20; i++) + System.out.println("Z(" + i + ")=" + getZeckendorf(i)); + } +} diff --git a/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia b/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia new file mode 100644 index 0000000000..2ae46cc18c --- /dev/null +++ b/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia @@ -0,0 +1,6 @@ +function zeck(n) + n <= 0 && return 0 + fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end + dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end + return dig[1] == 0 ? dig[2:end] : dig +end diff --git a/Task/Zeckendorf-number-representation/Mathematica/zeckendorf-number-representation.math b/Task/Zeckendorf-number-representation/Mathematica/zeckendorf-number-representation.math new file mode 100644 index 0000000000..c2b6a7e315 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Mathematica/zeckendorf-number-representation.math @@ -0,0 +1,7 @@ +zeckendorf[0] = 0; +zeckendorf[n_Integer] := + 10^(# - 1) + zeckendorf[n - Fibonacci[# + 1]] &@ + LengthWhile[ + Fibonacci /@ + Range[2, Ceiling@Log[GoldenRatio, n Sqrt@5]], # <= n &]; +zeckendorf /@ Range[0, 20] diff --git a/Task/Zeckendorf-number-representation/PARI-GP/zeckendorf-number-representation.pari b/Task/Zeckendorf-number-representation/PARI-GP/zeckendorf-number-representation.pari new file mode 100644 index 0000000000..5f4fd9fc31 --- /dev/null +++ b/Task/Zeckendorf-number-representation/PARI-GP/zeckendorf-number-representation.pari @@ -0,0 +1,2 @@ +Z(n)=if(!n,print1(0));my(k=2);while(fibonacci(k)<=n,k++); forstep(i=k-1,2,-1,print1(if(fibonacci(i)<=n,n-=fibonacci(i);1,0)));print +for(n=0,20,Z(n)) diff --git a/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 b/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 new file mode 100644 index 0000000000..90f0b62d67 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Perl-6/zeckendorf-number-representation.pl6 @@ -0,0 +1,10 @@ +printf "%2d: %8s\n", $_, zeckendorf($_) for 0 .. 20; + +multi zeckendorf(0) { '0' } +multi zeckendorf($n is copy) { + constant FIBS = 1,2, *+* ... *; + join '', map { + $n -= $_ if my $digit = $n >= $_; + +$digit; + }, reverse FIBS ...^ * > $n; +} diff --git a/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-1.py b/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-1.py new file mode 100644 index 0000000000..5c232f5efd --- /dev/null +++ b/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-1.py @@ -0,0 +1,34 @@ +def fib(): + memo = [1, 2] + while True: + memo.append(sum(memo)) + yield memo.pop(0) + +def sequence_down_from_n(n, seq_generator): + seq = [] + for s in seq_generator(): + seq.append(s) + if s >= n: break + return seq[::-1] + +def zeckendorf(n): + if n == 0: return [0] + seq = sequence_down_from_n(n, fib) + digits, nleft = [], n + for s in seq: + if s <= nleft: + digits.append(1) + nleft -= s + else: + digits.append(0) + assert nleft == 0, 'Check all of n is accounted for' + assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct' + while digits[0] == 0: + # Remove any zeroes padding L.H.S. + digits.pop(0) + return digits + +n = 20 +print('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib)) +for i in range(n + 1): + print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i)))) diff --git a/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-2.py b/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-2.py new file mode 100644 index 0000000000..b13a8f2311 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Python/zeckendorf-number-representation-2.py @@ -0,0 +1,15 @@ +n = 20 +def z(n): + if n == 0 : return [0] + fib = [2,1] + while fib[0] < n: fib[0:0] = [sum(fib[:2])] + dig = [] + for f in fib: + if f <= n: + dig, n = dig + [1], n - f + else: + dig += [0] + return dig if dig[0] else dig[1:] + +for i in range(n + 1): + print('%3i: %8s' % (i, ''.join(str(d) for d in z(i)))) diff --git a/Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r b/Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r new file mode 100644 index 0000000000..bee9d99ecb --- /dev/null +++ b/Task/Zeckendorf-number-representation/R/zeckendorf-number-representation.r @@ -0,0 +1,44 @@ +zeckendorf <- function(number) { + + # Get an upper limit on Fibonacci numbers needed to cover number + indexOfFibonacciNumber <- function(n) { + if (n < 1) { + 2 + } else { + Phi <- (1 + sqrt(5)) / 2 + invertClosedFormula <- log(n * sqrt(5)) / log(Phi) + ceiling(invertClosedFormula) + } + } + + upperLimit <- indexOfFibonacciNumber(number) + + # Return the sequence as digits, sorted descending + fibonacciSequenceDigits <- function(n) { + fibGenerator <- function(f, ...) { c(f[2], sum(f)) } + fibSeq <- Reduce(fibGenerator, 1:n, c(0,1), accumulate=TRUE) + + fibNums <- unlist(lapply(fibSeq, head, n=1)) + + # drop last F0 and F1 and reverse sequence + rev(fibNums[-2:-1]) + } + + digits <- fibonacciSequenceDigits(upperLimit) + + isInNumber <- function(digit) { + if (number >= digit) { + number <<- number - digit + 1 + } else { + 0 + } + } + + zeckSeq <- Map(isInNumber, digits) + + # drop leading 0 and convert to String + gsub("^0+1", "1", paste(zeckSeq, collapse="")) +} + +print(unlist(lapply(0:20, zeckendorf))) diff --git a/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-1.rexx b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-1.rexx new file mode 100644 index 0000000000..d5c6b01d15 --- /dev/null +++ b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-1.rexx @@ -0,0 +1,22 @@ +/* REXX *************************************************************** +* 11.10.2012 Walter Pachl +**********************************************************************/ +fib='13 8 5 3 2 1' +Do i=6 To 1 By -1 /* Prepare Fibonacci Numbers */ + Parse Var fib f.i fib /* f.1 ... f.7 */ + End +Do n=0 To 20 /* for all numbers in the task */ + m=n /* copy of number */ + r='' /* result for n */ + Do i=6 To 1 By -1 /* loop through numbers */ + If m>=f.i Then Do /* f.i must be used */ + r=r||1 /* 1 into result */ + m=m-f.i /* subtract */ + End + Else /* f.i is larger than the rest */ + r=r||0 /* 0 into result */ + End + r=strip(r,'L','0') /* strip leading zeros */ + If r='' Then r='0' /* take care of 0 */ + Say right(n,2)': 'right(r,6) /* show result */ + End diff --git a/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-2.rexx b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-2.rexx new file mode 100644 index 0000000000..7b790e3109 --- /dev/null +++ b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-2.rexx @@ -0,0 +1,19 @@ +/*REXX pgm to calculate and display the first N Zeckendorf numbers.*/ +numeric digits 1000 /*just in case user gets ka-razy.*/ +parse arg n .; if n=='' then n=20 /*let user specify upper limit. */ +#=1 2; do until word(#,words(#))>n /*build a list of Fib numbers. */ + w=words(#) /*number of words in list of Fib#*/ + #=# (word(#,w-1)+word(#,w)) /*sum the last two Fib numbers. */ + end /*until word(#, ... */ + + do j=0 to n; parse var j x z /*task: process zero ──► N. */ + do k=w by -1 for w; _=word(#,k) /*process all the Fib numbers. */ + if x>=_ then do /*is X>than the next Fib number? */ + z=z'1' /* ... then append unity (1). */ + x=x-_ /*subtract this fib# from index. */ + end + else z=z'0' /* append zero (0). */ + end /*k*/ + say ' Zeckendorf' right(j,length(n)) '= ' right(0+z,30) /*show #*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx new file mode 100644 index 0000000000..b79297f2da --- /dev/null +++ b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx @@ -0,0 +1,10 @@ +/*REXX pgm to calculate and display the first N Zeckendorf numbers.*/ +numeric digits 1000 /*just in case user gets ka-razy.*/ +parse arg n .; if n=='' then n=20 /*let user specify upper limit. */ +z=0 /*index of a Zeckendorf number. */ + do j=0 until z>n; _=x2b(d2x(j))+0 /*task: process zero ──► N. */ + if pos(11,_)\==0 then iterate /*two consecutive ones (1s) ? */ + say ' Zeckendorf' right(z,length(n)) '= ' right(_,30) /*show #.*/ + z=z+1 + end /*m*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Zeckendorf-number-representation/Scala/zeckendorf-number-representation.scala b/Task/Zeckendorf-number-representation/Scala/zeckendorf-number-representation.scala new file mode 100644 index 0000000000..c561271718 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Scala/zeckendorf-number-representation.scala @@ -0,0 +1,29 @@ +def zNum( n:BigInt ) : String = { + + if( n == 0 ) return "0" // Short-circuit this and return zero if we were given zero + + + val v = n.abs + + val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail.tail } + + + def z( v:BigInt ) : List[BigInt] = if(v == 0) List() else {val m = fibs(fibs.indexWhere(_>v) - 1); m :: z(v-m)} + + val zv = z(v) + + // Walk the list of fibonacci numbers from the number that matches the most significant down to 1, + // if the zeckendorf matchs then yield '1' otherwise '0' + val s = (for( i <- (fibs.indexWhere(_==zv(0)) to 0 by -1) ) yield { + + if( zv.contains(fibs(i))) "1" else "0" + + }).mkString + + if( n < 0 ) "-" + s // Using a negative-sign instead of twos-complement + else s +} + + +// A little test... +(0 to 20) foreach( i => print( zNum(i) + "\n" ) ) diff --git a/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-1.tcl b/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-1.tcl new file mode 100644 index 0000000000..5d63ed7d9e --- /dev/null +++ b/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-1.tcl @@ -0,0 +1,29 @@ +package require Tcl 8.5 + +# Generates the Fibonacci sequence (starting at 1) up to the largest item that +# is no larger than the target value. Could use tricks to precompute, but this +# is actually a pretty cheap linear operation. +proc fibseq target { + set seq {}; set prev 1; set fib 1 + for {set n 1;set i 1} {$fib <= $target} {incr n} { + for {} {$i < $n} {incr i} { + lassign [list $fib [incr fib $prev]] prev fib + } + if {$fib <= $target} { + lappend seq $fib + } + } + return $seq +} + +# Produce the given Zeckendorf number. +proc zeckendorf n { + # Special case: only value that begins with 0 + if {$n == 0} {return 0} + set zs {} + foreach f [lreverse [fibseq $n]] { + lappend zs [set z [expr {$f <= $n}]] + if {$z} {incr n [expr {-$f}]} + } + return [join $zs ""] +} diff --git a/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-2.tcl b/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-2.tcl new file mode 100644 index 0000000000..4d19dd61af --- /dev/null +++ b/Task/Zeckendorf-number-representation/Tcl/zeckendorf-number-representation-2.tcl @@ -0,0 +1,3 @@ +for {set i 0} {$i <= 20} {incr i} { + puts [format "%2d:%9s" $i [zeckendorf $i]] +} diff --git a/Task/Zeckendorf-number-representation/XPL0/zeckendorf-number-representation.xpl0 b/Task/Zeckendorf-number-representation/XPL0/zeckendorf-number-representation.xpl0 new file mode 100644 index 0000000000..55468bffe1 --- /dev/null +++ b/Task/Zeckendorf-number-representation/XPL0/zeckendorf-number-representation.xpl0 @@ -0,0 +1,20 @@ +include c:\cxpl\codes; \intrinsic 'code' declarations + +proc Zeckendorf(N); \Display Zeckendorf number (N <= 20) +int N; +int Fib, LZ, I; +[Fib:= [1, 2, 3, 5, 8, 13]; \Fibonacci sequence +LZ:= true; \suppress leading zeros +for I:= 5 downto 1 do + [if N >= Fib(I) then [N:= N-Fib(I); ChOut(0, ^1); LZ:= false] + else ChOut(0, if LZ then ^ else ^0); + ]; +ChOut(0, N+^0); \output final digit, which can be 0 +]; + +int N; +[for N:= 0 to 20 do + [if N<10 then ChOut(0,^ ); IntOut(0, N); Text(0, ": "); + Zeckendorf(N); CrLf(0); + ]; +] diff --git a/Task/Zig-zag-matrix/0DESCRIPTION b/Task/Zig-zag-matrix/0DESCRIPTION new file mode 100644 index 0000000000..359765bb69 --- /dev/null +++ b/Task/Zig-zag-matrix/0DESCRIPTION @@ -0,0 +1,10 @@ +Produce a zig-zag array. A zig-zag array is a square arrangement of the first N2 integers, where the numbers increase sequentially as you zig-zag along the anti-diagonals of the array. For a graphical representation, see [[wp:Image:JPEG_ZigZag.svg|JPG zigzag]] (JPG uses such arrays to encode images). + +For example, given 5, produce this array: +
    + 0  1  5  6 14
    + 2  4  7 13 15
    + 3  8 12 16 21
    + 9 11 17 20 22
    +10 18 19 23 24
    +
    diff --git a/Task/Zig-zag-matrix/1META.yaml b/Task/Zig-zag-matrix/1META.yaml new file mode 100644 index 0000000000..1e81690bbc --- /dev/null +++ b/Task/Zig-zag-matrix/1META.yaml @@ -0,0 +1,2 @@ +--- +note: Matrices diff --git a/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg b/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg new file mode 100644 index 0000000000..96c4e91353 --- /dev/null +++ b/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg @@ -0,0 +1,37 @@ +PROC zig zag = (INT n)[,]INT: ( + PROC move = (REF INT i, j)VOID: ( + IF j < n THEN + i := ( i <= 1 | 1 | i-1 ); + j +:= 1 + ELSE + i +:= 1 + FI + ); + + [n, n]INT a; + INT x:=LWB a, y:=LWB a; + + FOR v FROM 0 TO n**2-1 DO + a[y, x] := v; + IF ODD (x + y) THEN + move(x, y) + ELSE + move(y, x) + FI + OD; + a +); + +INT dim = 5; +#IF formatted transput possible THEN + FORMAT d = $z-d$; + FORMAT row = $"("n(dim-1)(f(d)",")f(d)")"$; + FORMAT block = $"("n(dim-1)(f(row)","lx)f(row)")"l$; + + printf((block, zig zag(dim))) +ELSE# + [,]INT result = zig zag(dim); + FOR i TO dim DO + print((result[i,], new line)) + OD +#FI# diff --git a/Task/Zig-zag-matrix/APL/zig-zag-matrix.apl b/Task/Zig-zag-matrix/APL/zig-zag-matrix.apl new file mode 100644 index 0000000000..18c34faace --- /dev/null +++ b/Task/Zig-zag-matrix/APL/zig-zag-matrix.apl @@ -0,0 +1,8 @@ + zz ← {⍵⍴⎕IO-⍨⍋⊃,/{(2|⍴⍵):⌽⍵⋄⍵}¨(⊂w)/¨⍨w{↓⍵∘.=⍨∪⍵}+/[1]⍵⊤w←⎕IO-⍨⍳×/⍵} ⍝ General zigzag (any rectangle) + zzSq ← {zz,⍨⍵} ⍝ Square zigzag + zzSq 5 + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 +10 18 19 23 24 diff --git a/Task/Zig-zag-matrix/AWK/zig-zag-matrix.awk b/Task/Zig-zag-matrix/AWK/zig-zag-matrix.awk new file mode 100644 index 0000000000..e2c3523889 --- /dev/null +++ b/Task/Zig-zag-matrix/AWK/zig-zag-matrix.awk @@ -0,0 +1,28 @@ +# syntax: GAWK -f ZIG-ZAG_MATRIX.AWK [-v offset={0|1}] [size] +BEGIN { +# offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2 + offset = (offset == "") ? 0 : offset + size = (ARGV[1] == "") ? 5 : ARGV[1] + if (offset !~ /^[01]$/) { exit(1) } + if (size !~ /^[0-9]+$/) { exit(1) } + width = length(size ^ 2 - 1 + offset) + 1 + i = j = 1 + for (n=0; n<=size^2-1; n++) { # build array + arr[i-1,j-1] = n + offset + if ((i+j) % 2 == 0) { + if (j < size) { j++ } else { i+=2 } + if (i > 1) { i-- } + } + else { + if (i < size) { i++ } else { j+=2 } + if (j > 1) { j-- } + } + } + for (row=0; row 1) i --; + } else { + // Odd stripes + if (i < size) i ++; + else j += 2; + if (j > 1) j --; + } + } + } + } +} diff --git a/Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada b/Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada new file mode 100644 index 0000000000..5af67ec17f --- /dev/null +++ b/Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada @@ -0,0 +1,50 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Zig_Zag is + + type Matrix is array (Positive range <>, Positive range <>) of Natural; + function Zig_Zag (Size : Positive) return Matrix is + Data : Matrix (1..Size, 1..Size); + I, J : Integer := 1; + begin + Data (1, 1) := 0; + for Element in 1..Size**2 - 1 loop + if (I + J) mod 2 = 0 then + -- Even stripes + if J < Size then + J := J + 1; + else + I := I + 2; + end if; + if I > 1 then + I := I - 1; + end if; + else + -- Odd stripes + if I < Size then + I := I + 1; + else + J := J + 2; + end if; + if J > 1 then + J := J - 1; + end if; + end if; + Data (I, J) := Element; + end loop; + return Data; + end Zig_Zag; + + procedure Put (Data : Matrix) is + begin + for I in Data'Range (1) loop + for J in Data'Range (2) loop + Put (Integer'Image (Data (I, J))); + end loop; + New_Line; + end loop; + end Put; + +begin + Put (Zig_Zag (5)); +end Test_Zig_Zag; diff --git a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-1.applescript b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-1.applescript new file mode 100644 index 0000000000..54aebc6c44 --- /dev/null +++ b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-1.applescript @@ -0,0 +1,37 @@ +set n to 5 -- Size of zig-zag matrix (n^2 cells). + +-- Create an empty matrix. +set m to {} +repeat with i from 1 to n + set R to {} + repeat with j from 1 to n + set end of R to 0 + end repeat + set end of m to R +end repeat + +-- Populate the matrix in a zig-zag manner. +set {x, y, v, d} to {1, 1, 0, 1} +repeat while v < (n ^ 2) + if 1 ≤ x and x ≤ n and 1 ≤ y and y ≤ n then + set {m's item y's item x, x, y, v} to {v, x + d, y - d, v + 1} + else if x > n then + set {x, y, d} to {n, y + 2, -d} + else if y > n then + set {x, y, d} to {x + 2, n, -d} + else if x < 1 then + set {x, y, d} to {1, y, -d} + else if y < 1 then + set {x, y, d} to {x, 1, -d} + end if +end repeat +--> R = {{0, 1, 5, 6, 14}, {2, 4, 7, 13, 15}, {3, 8, 12, 16, 21}, {9, 11, 17, 20, 22}, {10, 18, 19, 23, 24}} + +-- Reformat the matrix into a table for viewing. +repeat with i in m + repeat with j in i + set j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (" " & j)) as string + end repeat + set end of i to return +end repeat +return return & m as string diff --git a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript new file mode 100644 index 0000000000..e565bed953 --- /dev/null +++ b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript @@ -0,0 +1,34 @@ +set n to 5 + +set m to {} +repeat with i from 1 to n + set end of m to {} -- Built a foundation for the matrix out of n empty lists. +end repeat + +set {v, d, i} to {0, -1, 1} +repeat while v < n ^ 2 + if length of m's item i < n then + set {end of m's item i, i, v} to {f(v, n), i + d, v + 1} + if i < 1 then + set {i, d} to {1, -d} + else if i > n then + set {i, d} to {n, -d} + else if i > 1 and (count of m's item (i - 1)) = 1 then + set d to -d + end if + else + set {i, d} to {i + 1, 1} + end if +end repeat + +-- Handler/function to format the cells on the fly. +on f(v, n) + return (characters -(length of (n ^ 2 as string)) thru -1 of (" " & v)) as string +end f + +-- Reformat the matrix into a table for viewing. +set text item delimiters to "" +repeat with i in m + set i's contents to (i as string) & return +end repeat +return return & m as string diff --git a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript new file mode 100644 index 0000000000..1c22824cc4 --- /dev/null +++ b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-3.applescript @@ -0,0 +1,7 @@ +" + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 + 10 18 19 23 24 +" diff --git a/Task/Zig-zag-matrix/AutoHotkey/zig-zag-matrix.ahk b/Task/Zig-zag-matrix/AutoHotkey/zig-zag-matrix.ahk new file mode 100644 index 0000000000..2d362f2740 --- /dev/null +++ b/Task/Zig-zag-matrix/AutoHotkey/zig-zag-matrix.ahk @@ -0,0 +1,21 @@ +n = 5 ; size +v := x := y := 1 ; initial values +Loop % n*n { ; for every array element + a_%x%_%y% := v++ ; assign the next index + If ((x+y)&1) ; odd diagonal + If (x < n) ; while inside the square + y -= y<2 ? 0 : 1, x++ ; move right-up + Else y++ ; on the edge increment y, but not x: to even diagonal + Else ; even diagonal + If (y < n) ; while inside the square + x -= x<2 ? 0 : 1, y++ ; move left-down + Else x++ ; on the edge increment x, but not y: to odd diagonal +} + +Loop %n% { ; generate printout + x := A_Index ; for each row + Loop %n% ; and for each column + t .= a_%x%_%A_Index% "`t" ; attach stored index + t .= "`n" ; row is complete +} +MsgBox %t% ; show output diff --git a/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit b/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit new file mode 100644 index 0000000000..0fe354b261 --- /dev/null +++ b/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit @@ -0,0 +1,27 @@ +#include +$Array = ZigZag(5) +_ArrayDisplay($Array) + +Func ZigZag($int) + Local $av_array[$int][$int] + Local $x = 1, $y = 1 + For $I = 0 To $int ^ 2 -1 + $av_array[$x-1][$y-1] = $I + If Mod(($x + $y), 2) = 0 Then ;Even + if ($y < $int) Then + $y += 1 + Else + $x += 2 + EndIf + if ($x > 1) Then $x -= 1 + Else ; ODD + if ($x < $int) Then + $x += 1 + Else + $y += 2 + EndIf + If $y > 1 Then $y -= 1 + EndIf + Next + Return $av_array +EndFunc ;==>ZigZag diff --git a/Task/Zig-zag-matrix/BBC-BASIC/zig-zag-matrix.bbc b/Task/Zig-zag-matrix/BBC-BASIC/zig-zag-matrix.bbc new file mode 100644 index 0000000000..55293101b3 --- /dev/null +++ b/Task/Zig-zag-matrix/BBC-BASIC/zig-zag-matrix.bbc @@ -0,0 +1,23 @@ + Size% = 5 + DIM array%(Size%-1,Size%-1) + + i% = 1 + j% = 1 + FOR e% = 0 TO Size%^2-1 + array%(i%-1,j%-1) = e% + IF ((i% + j%) AND 1) = 0 THEN + IF j% < Size% j% += 1 ELSE i% += 2 + IF i% > 1 i% -= 1 + ELSE + IF i% < Size% i% += 1 ELSE j% += 2 + IF j% > 1 j% -= 1 + ENDIF + NEXT + + @% = &904 + FOR row% = 0 TO Size%-1 + FOR col% = 0 TO Size%-1 + PRINT array%(row%,col%); + NEXT + PRINT + NEXT row% diff --git a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp new file mode 100644 index 0000000000..dafee601f6 --- /dev/null +++ b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp @@ -0,0 +1,81 @@ +#include +#include // for auto_ptr +#include // for the log10 and floor functions +#include +#include // for the setw function + +using namespace std; + +typedef vector< int > IntRow; +typedef vector< IntRow > IntTable; + +auto_ptr< IntTable > getZigZagArray( int dimension ) +{ + auto_ptr< IntTable > zigZagArrayPtr( new IntTable( + dimension, IntRow( dimension ) ) ); + + // fill along diagonal stripes (oriented as "/") + int lastValue = dimension * dimension - 1; + int currNum = 0; + int currDiag = 0; + int loopFrom; + int loopTo; + int i; + int row; + int col; + do + { + if ( currDiag < dimension ) // if doing the upper-left triangular half + { + loopFrom = 0; + loopTo = currDiag; + } + else // doing the bottom-right triangular half + { + loopFrom = currDiag - dimension + 1; + loopTo = dimension - 1; + } + + for ( i = loopFrom; i <= loopTo; i++ ) + { + if ( currDiag % 2 == 0 ) // want to fill upwards + { + row = loopTo - i + loopFrom; + col = i; + } + else // want to fill downwards + { + row = i; + col = loopTo - i + loopFrom; + } + + ( *zigZagArrayPtr )[ row ][ col ] = currNum++; + } + + currDiag++; + } + while ( currNum <= lastValue ); + + return zigZagArrayPtr; +} + +void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr ) +{ + size_t dimension = zigZagArrayPtr->size(); + + int fieldWidth = static_cast< int >( floor( log10( + static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; + + size_t col; + for ( size_t row = 0; row < dimension; row++ ) + { + for ( col = 0; col < dimension; col++ ) + cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]; + cout << endl; + } +} + +int main() +{ + printZigZagArray( getZigZagArray( 5 ) ); +} diff --git a/Task/Zig-zag-matrix/C-sharp/zig-zag-matrix.cs b/Task/Zig-zag-matrix/C-sharp/zig-zag-matrix.cs new file mode 100644 index 0000000000..a88c9d13d3 --- /dev/null +++ b/Task/Zig-zag-matrix/C-sharp/zig-zag-matrix.cs @@ -0,0 +1,25 @@ +public static int[,] ZigZag(int n) +{ + int[,] result = new int[n, n]; + int i = 0, j = 0; + int d = -1; // -1 for top-right move, +1 for bottom-left move + int start = 0, end = n * n - 1; + do + { + result[i, j] = start++; + result[n - i - 1, n - j - 1] = end--; + + i += d; j -= d; + if (i < 0) + { + i++; d = -d; // top reached, reverse + } + else if (j < 0) + { + j++; d = -d; // left reached, reverse + } + } while (start < end); + if (start == end) + result[i, j] = start; + return result; +} diff --git a/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c b/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c new file mode 100644 index 0000000000..ebe9d6ef1d --- /dev/null +++ b/Task/Zig-zag-matrix/C/zig-zag-matrix-1.c @@ -0,0 +1,23 @@ +#include +#include + +int main(int c, char **v) +{ + int i, j, m, n, *s; + + /* default size: 5 */ + if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5; + + /* alloc array*/ + s = malloc(sizeof(int) * m * m); + + for (i = n = 0; i < m * 2; i++) + for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++) + s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++; + + for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n')) + printf("%3d", s[i]); + + /* free(s) */ + return 0; +} diff --git a/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c b/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c new file mode 100644 index 0000000000..44b1c1944a --- /dev/null +++ b/Task/Zig-zag-matrix/C/zig-zag-matrix-2.c @@ -0,0 +1,8 @@ +% ./a.out 7 + 0 1 5 6 14 15 27 + 2 4 7 13 16 26 28 + 3 8 12 17 25 29 38 + 9 11 18 24 30 37 39 + 10 19 23 31 36 40 45 + 20 22 32 35 41 44 46 + 21 33 34 42 43 47 48 diff --git a/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj b/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj new file mode 100644 index 0000000000..dbac76be7c --- /dev/null +++ b/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj @@ -0,0 +1,33 @@ +(defn partitions [sizes coll] + (lazy-seq + (when-let [n (first sizes)] + (when-let [s (seq coll)] + (cons (take n coll) + (partitions (next sizes) (drop n coll))))))) + +(defn take-from [n colls] + (lazy-seq + (when-let [s (seq colls)] + (let [[first-n rest-n] (split-at n s)] + (cons (map first first-n) + (take-from n (concat (filter seq (map rest first-n)) rest-n))))))) + +(defn zig-zag [n] + (->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n))) + (map #(%1 %2) (cycle [reverse identity]) ,) + (take-from n ,))) + +user> (zig-zag 5) +(( 0 1 5 6 14) + ( 2 4 7 13 15) + ( 3 8 12 16 21) + ( 9 11 17 20 22) + (10 18 19 23 24)) + +user> (zig-zag 6) +(( 0 1 5 6 14 15) + ( 2 4 7 13 16 25) + ( 3 8 12 17 24 26) + ( 9 11 18 23 27 32) + (10 19 22 28 31 33) + (20 21 29 30 34 35)) diff --git a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffeescript b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffeescript new file mode 100644 index 0000000000..8f7565fa58 --- /dev/null +++ b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-1.coffeescript @@ -0,0 +1,41 @@ +# Calculate a zig-zag pattern of numbers like so: +# 0 1 5 +# 2 4 6 +# 3 7 8 +# +# There are many interesting ways to solve this; we +# try for an algebraic approach, calculating triangle +# areas, so that me minimize space requirements. + +zig_zag_value = (x, y, n) -> + + upper_triangle_zig_zag = (x, y) -> + # calculate the area of the triangle from the prior + # diagonals + diag = x + y + triangle_area = diag * (diag+1) / 2 + # then add the offset along the diagonal + if diag % 2 == 0 + triangle_area + y + else + triangle_area + x + + if x + y < n + upper_triangle_zig_zag x, y + else + # For the bottom right part of the matrix, we essentially + # use reflection to count backward. + bottom_right_cell = n * n - 1 + n -= 1 + v = upper_triangle_zig_zag(n-x, n-y) + bottom_right_cell - v + +zig_zag_matrix = (n) -> + row = (i) -> (zig_zag_value i, j, n for j in [0...n]) + (row i for i in [0...n]) + +do -> + for n in [4..6] + console.log "---- n=#{n}" + console.log zig_zag_matrix(n) + console.log "\n" diff --git a/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffeescript b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffeescript new file mode 100644 index 0000000000..973d2c6d0e --- /dev/null +++ b/Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix-2.coffeescript @@ -0,0 +1,23 @@ +> coffee zigzag.coffee +---- n=4 +[ [ 0, 1, 5, 6 ], + [ 2, 4, 7, 12 ], + [ 3, 8, 11, 13 ], + [ 9, 10, 14, 15 ] ] + + +---- n=5 +[ [ 0, 1, 5, 6, 14 ], + [ 2, 4, 7, 13, 15 ], + [ 3, 8, 12, 16, 21 ], + [ 9, 11, 17, 20, 22 ], + [ 10, 18, 19, 23, 24 ] ] + + +---- n=6 +[ [ 0, 1, 5, 6, 14, 15 ], + [ 2, 4, 7, 13, 16, 25 ], + [ 3, 8, 12, 17, 24, 26 ], + [ 9, 11, 18, 23, 27, 32 ], + [ 10, 19, 22, 28, 31, 33 ], + [ 20, 21, 29, 30, 34, 35 ] ] diff --git a/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-1.lisp b/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-1.lisp new file mode 100644 index 0000000000..39ac588f91 --- /dev/null +++ b/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-1.lisp @@ -0,0 +1,14 @@ +(defun zigzag (n) + (flet ((move (i j) + (if (< j (1- n)) + (values (max 0 (1- i)) (1+ j)) + (values (1+ i) j)))) + (loop with a = (make-array (list n n) :element-type 'integer) + with x = 0 + with y = 0 + for v from 0 below (* n n) + do (setf (aref a x y) v) + (if (evenp (+ x y)) + (setf (values x y) (move x y)) + (setf (values y x) (move y x))) + finally (return a)))) diff --git a/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-2.lisp b/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-2.lisp new file mode 100644 index 0000000000..16ad4c355a --- /dev/null +++ b/Task/Zig-zag-matrix/Common-Lisp/zig-zag-matrix-2.lisp @@ -0,0 +1,17 @@ +; ZigZag +; +; Nigel Galloway. +; June 4th., 2012 +; +(defun ZigZag (COLS) + (let ((cs 2) (st '(1 2)) (dx '(-1 1))) + (defun new_cx (i) + (setq st (append st (list (setq cs (+ cs (* 2 i))) (setq cs (+ 1 cs)))) + dx (append dx '(-1 1)))) + (do ((i 2 (+ 2 i))) ((>= i COLS)) (new_cx i)) + (do ((i (- COLS 1 (mod COLS 2)) (+ -2 i))) ((<= i 0)) (new_cx i)) + (do ((i 0 (+ 1 i))) ((>= i COLS)) + (format t "~%") + (do ((j i (+ 1 j))) ((>= j (+ COLS i))) + (format t "~3d" (nth j st)) + (setf (nth j st) (+ (nth j st) (nth j dx))))))) diff --git a/Task/Zig-zag-matrix/D/zig-zag-matrix.d b/Task/Zig-zag-matrix/D/zig-zag-matrix.d new file mode 100644 index 0000000000..a4a14aef0a --- /dev/null +++ b/Task/Zig-zag-matrix/D/zig-zag-matrix.d @@ -0,0 +1,22 @@ +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)); +} diff --git a/Task/Zig-zag-matrix/E/zig-zag-matrix.e b/Task/Zig-zag-matrix/E/zig-zag-matrix.e new file mode 100644 index 0000000000..cba975c24a --- /dev/null +++ b/Task/Zig-zag-matrix/E/zig-zag-matrix.e @@ -0,0 +1,24 @@ +def zigZag(n) { + def move(&i, &j) { + if (j < (n - 1)) { + i := 0.max(i - 1) + j += 1 + } else { + i += 1 + } + } + + def array := makeFlex2DArray(n, n) + var x := 0 + var y := 0 + + for i in 1..n**2 { + array[y, x] := i + if ((x + y) % 2 == 0) { + move(&x, &y) + } else { + move(&y, &x) + } + } + return array +} diff --git a/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria b/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria new file mode 100644 index 0000000000..9a1253d23a --- /dev/null +++ b/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria @@ -0,0 +1,20 @@ +function zigzag(integer size) + sequence s + integer i, j, d, max + s = repeat(repeat(0,size),size) + i = 1 j = 1 d = -1 + max = size*size + for n = 1 to floor(max/2)+1 do + s[i][j] = n + s[size-i+1][size-j+1] = max-n+1 + i += d j-= d + if i < 1 then + i += 1 d = -d + elsif j < 1 then + j += 1 d = -d + end if + end for + return s +end function + +? zigzag(5) diff --git a/Task/Zig-zag-matrix/Fan/zig-zag-matrix.fan b/Task/Zig-zag-matrix/Fan/zig-zag-matrix.fan new file mode 100644 index 0000000000..347c0bb969 --- /dev/null +++ b/Task/Zig-zag-matrix/Fan/zig-zag-matrix.fan @@ -0,0 +1,91 @@ +using gfx // for Point; convenient x/y wrapper + +** +** A couple methods for generating a 'zigzag' array like +** +** 0 1 5 6 +** 2 4 7 12 +** 3 8 11 13 +** 9 10 14 15 +** +class ZigZag +{ + ** return an n x n array of uninitialized Int + static Int[][] makeSquareArray(Int n) + { + Int[][] grid := Int[][,] {it.size=n} + n.times |i| { grid[i] = Int[,] {it.size=n} } + return grid + } + + + Int[][] zig(Int n) + { + grid := makeSquareArray(n) + + move := |Int i, Int j->Point| + { return j < n - 1 ? Point(i <= 0 ? 0 : i-1, j+1) : Point(i+1, j) } + pt := Point(0,0) + (n*n).times |i| { + grid[pt.y][pt.x] = i + if ((pt.x+pt.y)%2 != 0) pt = move(pt.x,pt.y) + else {tmp:= move(pt.y,pt.x); pt = Point(tmp.y, tmp.x) } + } + return grid + } + + public static Int[][] zag(Int size) + { + data := makeSquareArray(size) + + Int i := 1 + Int j := 1 + for (element:=0; element < size * size; element++) + { + data[i - 1][j - 1] = element + if((i + j) % 2 == 0) { + // Even stripes + if (j < size) { + j++ + } else { + i += 2 + } + if (i > 1) { + i-- + } + } else { + // Odd stripes + if (i < size) { + i++; + } else { + j += 2 + } + if (j > 1) { + j-- + } + } + } + return data; + } + + Void print(Int[][] data) + { + data.each |row| + { + buf := StrBuf() + row.each |num| + { + buf.add(num.toStr.justr(3)) + } + echo(buf) + } + } + + Void main() + { + echo("zig method:") + print(zig(8)) + echo("\nzag method:") + print(zag(8)) + } +} diff --git a/Task/Zig-zag-matrix/Forth/zig-zag-matrix.fth b/Task/Zig-zag-matrix/Forth/zig-zag-matrix.fth new file mode 100644 index 0000000000..a3dff3693a --- /dev/null +++ b/Task/Zig-zag-matrix/Forth/zig-zag-matrix.fth @@ -0,0 +1,50 @@ +0 value diag + +: south diag abs + cell+ ; + +' cell+ value zig +' south value zag + +: init ( n -- ) + 1- cells negate to diag + ['] cell+ to zig + ['] south to zag ; + +: swap-diag zig zag to zig to zag ; + +: put ( n addr -- n+1 addr ) + 2dup ! swap 1+ swap ; + +: turn ( addr -- addr+E/S ) + zig execute swap-diag + diag negate to diag ; + +: zigzag ( matrix n -- ) + { n } n init + 0 swap + n 1 ?do + put turn + i 0 do put diag + loop + loop + swap-diag + n 1 ?do + put turn + n i 1+ ?do put diag + loop + loop + ! ; + +: .matrix ( n matrix -- ) + over 0 do + cr + over 0 do + dup @ 3 .r cell+ + loop + loop 2drop ; + +: test ( n -- ) here over zigzag here .matrix ; +5 test + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 + 10 18 19 23 24 ok diff --git a/Task/Zig-zag-matrix/Fortran/zig-zag-matrix.f b/Task/Zig-zag-matrix/Fortran/zig-zag-matrix.f new file mode 100644 index 0000000000..a4f4f1572d --- /dev/null +++ b/Task/Zig-zag-matrix/Fortran/zig-zag-matrix.f @@ -0,0 +1,38 @@ +PROGRAM ZIGZAG + + IMPLICIT NONE + INTEGER, PARAMETER :: size = 5 + INTEGER :: zzarray(size,size), x(size*size), y(size*size), i, j + + ! index arrays + x = (/ ((j, i = 1, size), j = 1, size) /) + y = (/ ((i, i = 1, size), j = 1, size) /) + + ! Sort indices + DO i = 2, size*size + j = i - 1 + DO WHILE (j>=1 .AND. (x(j)+y(j)) > (x(i)+y(i))) + j = j - 1 + END DO + x(j+1:i) = cshift(x(j+1:i),-1) + y(j+1:i) = cshift(y(j+1:i),-1) + END DO + + ! Create zig zag array + DO i = 1, size*size + IF (MOD(x(i)+y(i), 2) == 0) THEN + zzarray(x(i),y(i)) = i - 1 + ELSE + zzarray(y(i),x(i)) = i - 1 + END IF + END DO + + ! Print zig zag array + DO j = 1, size + DO i = 1, size + WRITE(*, "(I5)", ADVANCE="NO") zzarray(i,j) + END DO + WRITE(*,*) + END DO + + END PROGRAM ZIGZAG diff --git a/Task/Zig-zag-matrix/GAP/zig-zag-matrix.gap b/Task/Zig-zag-matrix/GAP/zig-zag-matrix.gap new file mode 100644 index 0000000000..17d58dd2e6 --- /dev/null +++ b/Task/Zig-zag-matrix/GAP/zig-zag-matrix.gap @@ -0,0 +1,36 @@ +ZigZag := function(n) + local a, i, j, k; + a := NullMat(n, n); + i := 1; + j := 1; + for k in [0 .. n*n - 1] do + a[i][j] := k; + if (i + j) mod 2 = 0 then + if j < n then + j := j + 1; + else + i := i + 2; + fi; + if i > 1 then + i := i - 1; + fi; + else + if i < n then + i := i + 1; + else + j := j + 2; + fi; + if j > 1 then + j := j - 1; + fi; + fi; + od; + return a; +end; + +PrintArray(ZigZag(5)); +# [ [ 0, 1, 5, 6, 14 ], +# [ 2, 4, 7, 13, 15 ], +# [ 3, 8, 12, 16, 21 ], +# [ 9, 11, 17, 20, 22 ], +# [ 10, 18, 19, 23, 24 ] ] diff --git a/Task/Zig-zag-matrix/Go/zig-zag-matrix.go b/Task/Zig-zag-matrix/Go/zig-zag-matrix.go new file mode 100644 index 0000000000..7a00478387 --- /dev/null +++ b/Task/Zig-zag-matrix/Go/zig-zag-matrix.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "strconv" +) + +func zz(n int) []int { + r := make([]int, n*n) + i := 0 + n2 := n * 2 + for d := 1; d <= n2; d++ { + x := d - n + if x < 0 { + x = 0 + } + y := d - 1 + if y > n-1 { + y = n - 1 + } + j := n2 - d + if j > d { + j = d + } + for k := 0; k < j; k++ { + if d&1 == 0 { + r[(x+k)*n+y-k] = i + } else { + r[(y-k)*n+x+k] = i + } + i++ + } + } + + return r +} + +func main() { + const n = 5 + w := len(strconv.Itoa(n*n - 1)) + for i, e := range zz(n) { + fmt.Printf("%*d ", w, e) + if i%n == n-1 { + fmt.Println("") + } + } +} diff --git a/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-1.groovy b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-1.groovy new file mode 100644 index 0000000000..b67ed874cd --- /dev/null +++ b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-1.groovy @@ -0,0 +1,11 @@ +def zz = { n -> + grid = new int[n][n] + i = 0 + for (d in 1..n*2) { + (x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)] + Math.min(d, n*2 - d).times { + grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++; + } + } + grid +} diff --git a/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-2.groovy b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-2.groovy new file mode 100644 index 0000000000..5e26a51fd2 --- /dev/null +++ b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-2.groovy @@ -0,0 +1,11 @@ +def zz = { n-> + move = { i, j -> j < n - 1 ? [i <= 0 ? 0 : i-1, j+1] : [i+1, j] } + grid = new int[n][n] + (x, y) = [0, 0] + (n**2).times { + grid[y][x] = it + if ((x+y)%2) (x,y) = move(x,y) + else (y,x) = move(y,x) + } + grid +} diff --git a/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-3.groovy b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-3.groovy new file mode 100644 index 0000000000..68f9a60fba --- /dev/null +++ b/Task/Zig-zag-matrix/Groovy/zig-zag-matrix-3.groovy @@ -0,0 +1,5 @@ +def zz = { n -> + (0.. + [c.x+c.y, (((c.x+c.y)%2) ? c.y : -c.y)] + }.with { l -> l.inject(new int[n][n]) { a, c -> a[c.y][c.x] = l.indexOf(c); a } } +} diff --git a/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-1.hs b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-1.hs new file mode 100644 index 0000000000..de00187f91 --- /dev/null +++ b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-1.hs @@ -0,0 +1,11 @@ +import Data.Array (array, bounds, range, (!)) +import Data.Monoid (mappend) +import Data.List (sortBy) + +compZig (x,y) (x',y') = compare (x+y) (x'+y') + `mappend` if even (x+y) then compare x x' + else compare y y' + +zigZag upper = array b $ zip (sortBy compZig (range b)) + [0..] + where b = ((0,0),upper) diff --git a/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-2.hs b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-2.hs new file mode 100644 index 0000000000..cfe72501ca --- /dev/null +++ b/Task/Zig-zag-matrix/Haskell/zig-zag-matrix-2.hs @@ -0,0 +1,8 @@ +import Text.Printf (printf) + +-- format a 2d array of integers neatly +show2d a = unlines [unwords [printf "%3d" (a ! (x,y) :: Integer) | x <- axis fst] | y <- axis snd] + where (l, h) = bounds a + axis f = [f l .. f h] + +main = mapM_ (putStr . show2d . zigZag) [(3,3), (4,4), (10,2)] diff --git a/Task/Zig-zag-matrix/Icon/zig-zag-matrix.icon b/Task/Zig-zag-matrix/Icon/zig-zag-matrix.icon new file mode 100644 index 0000000000..d53bf86f5c --- /dev/null +++ b/Task/Zig-zag-matrix/Icon/zig-zag-matrix.icon @@ -0,0 +1,25 @@ +procedure main(args) + n := integer(!args) | 5 + every !(A := list(n)) := list(n) + A := zigzag(A) + show(A) +end + +procedure show(A) + every writes(right(!A,5) | "\n") +end + +procedure zigzag(A) + x := [0,0] + every i := 0 to (*A^2 -1) do { + x := nextIndices(*A, x) + A[x[1]][x[2]] := i + } + return A +end + +procedure nextIndices(n, x) + return if (x[1]+x[2])%2 = 0 + then if x[2] = n then [x[1]+1, x[2]] else [max(1, x[1]-1), x[2]+1] + else if x[1] = n then [x[1], x[2]+1] else [x[1]+1, max(1, x[2]-1)] +end diff --git a/Task/Zig-zag-matrix/J/zig-zag-matrix-1.j b/Task/Zig-zag-matrix/J/zig-zag-matrix-1.j new file mode 100644 index 0000000000..c5d7c786d4 --- /dev/null +++ b/Task/Zig-zag-matrix/J/zig-zag-matrix-1.j @@ -0,0 +1,6 @@ + ($ [: /:@; <@|.` 1) + i--; + } + else + { + // Odd stripes + if (i < size) + i++; + else + j+= 2; + if (j > 1) + j--; + } + } + return data; +} diff --git a/Task/Zig-zag-matrix/JavaScript/zig-zag-matrix.js b/Task/Zig-zag-matrix/JavaScript/zig-zag-matrix.js new file mode 100644 index 0000000000..799e4f3036 --- /dev/null +++ b/Task/Zig-zag-matrix/JavaScript/zig-zag-matrix.js @@ -0,0 +1,32 @@ +function ZigZagMatrix(n) { + this.height = n; + this.width = n; + + this.mtx = []; + for (var i = 0; i < n; i++) + this.mtx[i] = []; + + var i=1, j=1; + for (var e = 0; e < n*n; e++) { + this.mtx[i-1][j-1] = e; + if ((i + j) % 2 == 0) { + // Even stripes + if (j < n) j ++; + else i += 2; + if (i > 1) i --; + } else { + // Odd stripes + if (i < n) i ++; + else j += 2; + if (j > 1) j --; + } + } +} +ZigZagMatrix.prototype = Matrix.prototype; + +var z = new ZigZagMatrix(5); +print(z); +print(); + +z = new ZigZagMatrix(4); +print(z); diff --git a/Task/Zig-zag-matrix/Joy/zig-zag-matrix.joy b/Task/Zig-zag-matrix/Joy/zig-zag-matrix.joy new file mode 100644 index 0000000000..3f251bdea4 --- /dev/null +++ b/Task/Zig-zag-matrix/Joy/zig-zag-matrix.joy @@ -0,0 +1,51 @@ +(* + From the library. +*) +DEFINE reverse == [] swap shunt; + shunt == [swons] step. + +(* + Split according to the parameter given. +*) +DEFINE take-drop == [dup] swap dup [[] cons [take swap] concat concat] dip [] + cons concat [drop] concat. + +(* + Take the first of a list of lists. +*) +DEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map + swap dup] concat swap concat [drop swap] concat swap + concat [take [rest] step []] concat swap concat [[cons] + times swap concat 1 drop] concat. + +DEFINE zigzag == + +(* + Use take-drop to generate a list of lists. +*) +4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat +swap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons] +while + +(* + The odd numbers must be modified with reverse. +*) +[dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map + +(* + Take the first of the first of n lists. +*) +swap dup take-first [i] cons times pop + +(* + Merge the n separate lists. +*) +[] [pop list] [cons] while + +(* + And print them. +*) +swap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars] +concat [step '\n putch] cons step. + +11 zigzag. diff --git a/Task/Zig-zag-matrix/Lua/zig-zag-matrix.lua b/Task/Zig-zag-matrix/Lua/zig-zag-matrix.lua new file mode 100644 index 0000000000..6af0654857 --- /dev/null +++ b/Task/Zig-zag-matrix/Lua/zig-zag-matrix.lua @@ -0,0 +1,76 @@ +local zigzag = {} + +function zigzag.new(n) + local a = {} + local i -- cols + local j -- rows + + a.n = n + a.val = {} + + for j = 1, n do + a.val[j] = {} + for i = 1, n do + a.val[j][i] = 0 + end + end + + i = 1 + j = 1 + + local di + local dj + local k = 0 + + while k < n * n do + a.val[j][i] = k + k = k + 1 + if i == n then + j = j + 1 + a.val[j][i] = k + k = k + 1 + di = -1 + dj = 1 + end + if j == 1 then + i = i + 1 + a.val[j][i] = k + k = k + 1 + di = -1 + dj = 1 + end + if j == n then + i = i + 1 + a.val[j][i] = k + k = k + 1 + di = 1 + dj = -1 + end + if i == 1 then + j = j + 1 + a.val[j][i] = k + k = k + 1 + di = 1 + dj = -1 + end + i = i + di + j = j + dj + end + + setmetatable(a, {__index = zigzag, __tostring = zigzag.__tostring}) + return a +end + +function zigzag:__tostring() + local s = {} + for j = 1, self.n do + local row = {} + for i = 1, self.n do + row[i] = string.format('%d', self.val[j][i]) + end + s[j] = table.concat(row, ' ') + end + return table.concat(s, '\n') +end + +print(zigzag.new(5)) diff --git a/Task/Zig-zag-matrix/M4/zig-zag-matrix.m4 b/Task/Zig-zag-matrix/M4/zig-zag-matrix.m4 new file mode 100644 index 0000000000..3a6819f034 --- /dev/null +++ b/Task/Zig-zag-matrix/M4/zig-zag-matrix.m4 @@ -0,0 +1,30 @@ +divert(-1) + +define(`set2d',`define(`$1[$2][$3]',`$4')') +define(`get2d',`defn(`$1[$2][$3]')') +define(`for', + `ifelse($#,0,``$0'', + `ifelse(eval($2<=$3),1, + `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') +define(`show2d', + `for(`x',0,decr($2), + `for(`y',0,decr($3),`format(`%2d',get2d($1,x,y)) ') +')') + +dnl , +define(`zigzag', + `define(`j',1)`'define(`k',1)`'for(`e',0,eval($2*$2-1), + `set2d($1,decr(j),decr(k),e)`'ifelse(eval((j+k)%2),0, + `ifelse(eval(k<$2),1, + `define(`k',incr(k))', + `define(`j',eval(j+2))')`'ifelse(eval(j>1),1, + `define(`j',decr(j))')', + `ifelse(eval(j<$2),1, + `define(`j',incr(j))', + `define(`k',eval(k+2))')`'ifelse(eval(k>1),1, + `define(`k',decr(k))')')')') + +divert + +zigzag(`a',5) +show2d(`a',5,5) diff --git a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m new file mode 100644 index 0000000000..7120658c08 --- /dev/null +++ b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-1.m @@ -0,0 +1,64 @@ +function matrix = zigZag(n) + + %This is very unintiutive. This algorithm parameterizes the + %zig-zagging movement along the matrix indicies. The easiest way to see + %what this algorithm does is to go through line-by-line and write out + %what the algorithm does on a peace of paper. + + matrix = zeros(n); + counter = 1; + flipCol = true; + flipRow = false; + + %This for loop does the top-diagonal of the matrix + for i = (2:n) + row = (1:i); + column = (1:i); + + %Causes the zig-zagging. Without these conditionals, you would end + %up with a diagonal matrix. To see what happens comment these conditionals out. + if flipCol + column = fliplr(column); + flipRow = true; + flipCol = false; + elseif flipRow + row = fliplr(row); + flipRow = false; + flipCol = true; + end + + %Selects a diagonal of the zig-zag matrix and places the correct + %integer value in each index along that diagonal + for j = (1:numel(row)) + matrix(row(j),column(j)) = counter; + counter = counter + 1; + end + end + + %This for loop does the bottom-diagonal of the matrix + for i = (2:n) + row = (i:n); + column = (i:n); + + %Causes the zig-zagging. Without these conditionals, you would end + %up with a diagonal matrix. To see what happens comment these conditionals out. + if flipCol + column = fliplr(column); + flipRow = true; + flipCol = false; + elseif flipRow + row = fliplr(row); + flipRow = false; + flipCol = true; + end + + %Selects a diagonal of the zig-zag matrix and places the correct + %integer value in each index along that diagonal + for j = (1:numel(row)) + matrix(row(j),column(j)) = counter; + counter = counter + 1; + end + end + + +end diff --git a/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m new file mode 100644 index 0000000000..50618a0307 --- /dev/null +++ b/Task/Zig-zag-matrix/MATLAB/zig-zag-matrix-2.m @@ -0,0 +1,9 @@ +>> zigZag(5) + +ans = + + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 + 10 18 19 23 24 diff --git a/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-1.math b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-1.math new file mode 100644 index 0000000000..9c2c601995 --- /dev/null +++ b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-1.math @@ -0,0 +1,4 @@ +ZigZag[size_Integer/;size>0]:=Module[{empty=ConstantArray[0,{size,size}]}, + empty=ReplacePart[empty,{i_,j_}:>1/2 (i+j)^2-(i+j)/2-i (1-Mod[i+j,2])-j Mod[i+j,2]]; + ReplacePart[empty,{i_,j_}/;i+j>size+1:> size^2-tmp[[size-i+1,size-j+1]]-1] +] diff --git a/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-2.math b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-2.math new file mode 100644 index 0000000000..8369c9c1d2 --- /dev/null +++ b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-2.math @@ -0,0 +1,15 @@ +ZigZag2[size_] := Module[{data, i, j, elem}, + data = ConstantArray[0, {size, size}]; + i = j = 1; + For[elem = 0, elem < size^2, elem++, + data[[i, j]] = elem; + If[Mod[i + j, 2] == 0, + If[j < size, j++, i += 2]; + If[i > 1, i--] + , + If[i < size, i++, j += 2]; + If[j > 1, j--]; + ]; + ]; + data + ] diff --git a/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-3.math b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-3.math new file mode 100644 index 0000000000..1a019e8541 --- /dev/null +++ b/Task/Zig-zag-matrix/Mathematica/zig-zag-matrix-3.math @@ -0,0 +1,2 @@ +ZigZag[5] // MatrixForm +ZigZag2[6] // MatrixForm diff --git a/Task/Zig-zag-matrix/Maxima/zig-zag-matrix.maxima b/Task/Zig-zag-matrix/Maxima/zig-zag-matrix.maxima new file mode 100644 index 0000000000..5b2c0f1b44 --- /dev/null +++ b/Task/Zig-zag-matrix/Maxima/zig-zag-matrix.maxima @@ -0,0 +1,22 @@ +zigzag(n) := block([a, i, j], +a: zeromatrix(n, n), +i: 1, +j: 1, +for k from 0 thru n*n - 1 do ( + a[i, j]: k, + if evenp(i + j) then ( + if j < n then j: j + 1 else i: i + 2, + if i > 1 then i: i - 1 + ) else ( + if i < n then i: i + 1 else j: j + 2, + if j > 1 then j: j - 1 + ) +), +a)$ + +zigzag(5); +/* matrix([ 0, 1, 5, 6, 14], + [ 2, 4, 7, 13, 15], + [ 3, 8, 12, 16, 21], + [ 9, 11, 17, 20, 22], + [10, 18, 19, 23, 24]) */ diff --git a/Task/Zig-zag-matrix/Modula-3/zig-zag-matrix.mod3 b/Task/Zig-zag-matrix/Modula-3/zig-zag-matrix.mod3 new file mode 100644 index 0000000000..7615590c7e --- /dev/null +++ b/Task/Zig-zag-matrix/Modula-3/zig-zag-matrix.mod3 @@ -0,0 +1,48 @@ +MODULE ZigZag EXPORTS Main; + +IMPORT IO, Fmt; + +TYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL; + +PROCEDURE Create(size: CARDINAL): Matrix = + PROCEDURE move(VAR i, j: INTEGER) = + BEGIN + IF j < (size - 1) THEN + IF (i - 1) < 0 THEN + i := 0; + ELSE + i := i - 1; + END; + INC(j); + ELSE + INC(i); + END; + END move; + + VAR data := NEW(Matrix, size, size); + x, y: INTEGER := 0; + BEGIN + FOR v := 0 TO size * size - 1 DO + data[y, x] := v; + IF (x + y) MOD 2 = 0 THEN + move(y, x); + ELSE + move(x, y); + END; + END; + RETURN data; + END Create; + +PROCEDURE Print(data: Matrix) = + BEGIN + FOR i := FIRST(data^) TO LAST(data^) DO + FOR j := FIRST(data[0]) TO LAST(data[0]) DO + IO.Put(Fmt.F("%3s", Fmt.Int(data[i, j]))); + END; + IO.Put("\n"); + END; + END Print; + +BEGIN + Print(Create(5)); +END ZigZag. diff --git a/Task/Zig-zag-matrix/NetRexx/zig-zag-matrix.netrexx b/Task/Zig-zag-matrix/NetRexx/zig-zag-matrix.netrexx new file mode 100644 index 0000000000..d3cbb47ec4 --- /dev/null +++ b/Task/Zig-zag-matrix/NetRexx/zig-zag-matrix.netrexx @@ -0,0 +1,41 @@ +/* NetRexx */ +options replace format comments java crossref savelog symbols binary + +zigzag(5) + +return + +method zigzag(msize) public static + + row = 1 + col = 1 + + ziggy = Rexx(0) + loop j_ = 0 for msize * msize + ziggy[row, col] = j_ + if (row + col) // 2 == 0 then do + if col < msize then - + col = col + 1 + else row = row + 2 + if row \== 1 then - + row = row - 1 + end + else do + if row < msize then - + row = row + 1 + else col = col + 2 + if col \== 1 then - + col = col - 1 + end + end j_ + + L = (msize * msize - 1).length /*for a constant element width. */ + loop row = 1 for msize /*show all the matrix's rows. */ + rowOut = '' + loop col = 1 for msize + rowOut = rowOut ziggy[row, col].right(L) + end col + say rowOut + end row + + return diff --git a/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml b/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml new file mode 100644 index 0000000000..c5717936f5 --- /dev/null +++ b/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml @@ -0,0 +1,19 @@ +let zigzag n = + (* move takes references and modifies them directly *) + let move i j = + if !j < n - 1 then begin + i := max 0 (!i - 1); + incr j + end else + incr i + in + let a = Array.make_matrix n n 0 + and x = ref 0 and y = ref 0 in + for v = 0 to n * n - 1 do + a.(!x).(!y) <- v; + if (!x + !y) mod 2 = 0 then + move x y + else + move y x + done; + a diff --git a/Task/Zig-zag-matrix/Objeck/zig-zag-matrix.objeck b/Task/Zig-zag-matrix/Objeck/zig-zag-matrix.objeck new file mode 100644 index 0000000000..11e8e7b83b --- /dev/null +++ b/Task/Zig-zag-matrix/Objeck/zig-zag-matrix.objeck @@ -0,0 +1,39 @@ +function : native : ZigZag(size : Int) ~ Int[,] { + data := Int->New[size, size]; + i := 1; + j := 1; + + max := size * size; + for(element := 0; element < max ; element += 1;) { + data[i - 1, j - 1] := element; + + if((i + j) % 2 = 0) { + # even stripes + if(j < size){ + j += 1; + } + else{ + i+= 2; + }; + + if(i > 1) { + i -= 1; + }; + } + else{ + # ddd stripes + if(i < size){ + i += 1; + } + else{ + j+= 2; + }; + + if(j > 1){ + j -= 1; + }; + }; + }; + + return data; +} diff --git a/Task/Zig-zag-matrix/Oz/zig-zag-matrix.oz b/Task/Zig-zag-matrix/Oz/zig-zag-matrix.oz new file mode 100644 index 0000000000..3f76ad42b6 --- /dev/null +++ b/Task/Zig-zag-matrix/Oz/zig-zag-matrix.oz @@ -0,0 +1,39 @@ +declare + %% state move success failure + States = unit(right: [ 1# 0 downLeft downInstead] + downInstead: [ 0# 1 downLeft terminate] + downLeft: [~1# 1 downLeft down] + down: [ 0# 1 topRight rightInstead] + rightInstead: [ 1# 0 topRight terminate] + topRight: [ 1#~1 topRight right]) + + fun {CreateZigZag N} + ZZ = {Create2DTuple N N} + + %% recursively walk through 2D tuple and set values + proc {Walk Pos=X#Y Count State} + [Dir Success Failure] = States.State + NextPos = {Record.zip Pos Dir Number.'+'} + Valid = {Record.all NextPos fun {$ C} C > 0 andthen C =< N end} + NewPos = if Valid then NextPos else Pos end + NewCount = if Valid then Count + 1 else Count end + NewState = if Valid then Success else Failure end + in + ZZ.Y.X = Count + if NewState \= terminate then + {Walk NewPos NewCount NewState} + end + end + in + {Walk 1#1 0 right} + ZZ + end + + fun {Create2DTuple W H} + T = {MakeTuple unit H} + in + {Record.forAll T fun {$} {MakeTuple unit W} end} + T + end +in + {Inspect {CreateZigZag 5}} diff --git a/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.pari b/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.pari new file mode 100644 index 0000000000..a93e31960c --- /dev/null +++ b/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.pari @@ -0,0 +1,21 @@ +zz(n)={ + my(M=matrix(n,n),i,j,d=-1,start,end=n^2-1); + while(ct--, + M[i+1,j+1]=start; + M[n-i,n-j]=end; + start++; + end--; + i+=d; + j-=d; + if(i<0, + i++; + d=-d + , + if(j<0, + j++; + d=-d + ) + ); + if(start>end,return(M)) + ) +}; diff --git a/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php b/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php new file mode 100644 index 0000000000..22568a7742 --- /dev/null +++ b/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php @@ -0,0 +1,32 @@ +function ZigZagMatrix($num) { + $matrix = array(); + for ($i = 0; $i < $num; $i++){ + $matrix[$i] = array(); + } + + $i=1; + $j=1; + for ($e = 0; $e < $num*$num; $e++) { + $matrix[$i-1][$j-1] = $e; + if (($i + $j) % 2 == 0) { + if ($j < $num){ + $j++; + }else{ + $i += 2; + } + if ($i > 1){ + $i --; + } + } else { + if ($i < $num){ + $i++; + }else{ + $j += 2; + } + if ($j > 1){ + $j --; + } + } + } + return $matrix; +} diff --git a/Task/Zig-zag-matrix/PL-I/zig-zag-matrix.pli b/Task/Zig-zag-matrix/PL-I/zig-zag-matrix.pli new file mode 100644 index 0000000000..8ea27585cd --- /dev/null +++ b/Task/Zig-zag-matrix/PL-I/zig-zag-matrix.pli @@ -0,0 +1,51 @@ +/* Fill a square matrix with the values 0 to N**2-1, */ +/* in a zig-zag fashion. */ +/* N is the length of one side of the square. */ +/* Written 22 February 2010. */ + + declare n fixed binary; + + put skip list ('Please type the size of the matrix:'); + get list (n); + +begin; + declare A(n,n) fixed binary; + declare (i, j, inc, q) fixed binary; + + on subrg snap begin; + declare i fixed binary; + do i = 1 to n; + put skip edit (a(i,*)) (f(4)); + end; + stop; + end; + + A = -1; + inc = -1; + i, j = 1; + +loop: + do q = 0 to n**2-1; + a(i,j) = q; + if q = n**2-1 then leave; + if i = 1 & j = n then + if iand(j,1) = 1 then /* odd-sided matrix */ + do; i = i + 1; inc = -inc; iterate loop; end; + else /* an even-sided matrix */ + do; i = i + inc; j = j - inc; iterate loop; end; + if inc = -1 then if i+inc < 1 then + do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; + if inc = 1 then if i+inc > n then + do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end; + if inc = 1 then if j-inc < 1 then + do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; + if inc = -1 then if j - inc > n then + do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end; + i = i + inc; j = j - inc; + end; + + /* Display the square. */ + do i = 1 to n; + put skip edit (a(i,*)) (f(4)); + end; +end; diff --git a/Task/Zig-zag-matrix/Pascal/zig-zag-matrix.pascal b/Task/Zig-zag-matrix/Pascal/zig-zag-matrix.pascal new file mode 100644 index 0000000000..9dc91cb677 --- /dev/null +++ b/Task/Zig-zag-matrix/Pascal/zig-zag-matrix.pascal @@ -0,0 +1,49 @@ +Program zigzag; + +const + size = 5; +var + zzarray: array [1..size, 1..size] of integer; + element, i, j: integer; + direction: integer; + +begin + i := 1; + j := 1; + direction := 1; + for element := 1 to size*size do + begin + zzarray[i,j] := element; + i := i + direction; + j := j - direction; + if (i = 0) then + begin + direction := -direction; + i := i + 1; + end; + if (i = size +1) then + begin + direction := -direction; + i := i - 1; + j := j + 2; + end; + if (j = 0) then + begin + direction := -direction; + j := j + 1; + end; + if (j = size + 1) then + begin + direction := -direction; + j := j - 1; + i := i + 2; + end; + end; + + for j := 1 to size do + begin + for i := 1 to size do + write(zzarray[i,j]:3); + writeln; + end; +end. diff --git a/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 new file mode 100644 index 0000000000..eba875b43b --- /dev/null +++ b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 @@ -0,0 +1,22 @@ +sub MAIN($size as Int) { + my $t = Turtle.new(dir => northeast); + my $counter = 0; + for 1 ..^ $size -> $run { + for ^$run { + $t.lay-egg($counter++); + $t.forward; + } + my $yaw = $run %% 2 ?? -1 !! 1; + $t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45); + } + for $size ... 1 -> $run { + for ^$run -> $ { + $t.lay-egg($counter++); + $t.forward; + } + $t.turn-left(180); $t.forward; + my $yaw = $run %% 2 ?? 1 !! -1; + $t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45); + } + $t.showmap; +} diff --git a/Task/Zig-zag-matrix/Perl/zig-zag-matrix.pl b/Task/Zig-zag-matrix/Perl/zig-zag-matrix.pl new file mode 100644 index 0000000000..e5f772667d --- /dev/null +++ b/Task/Zig-zag-matrix/Perl/zig-zag-matrix.pl @@ -0,0 +1,16 @@ +sub zig_zag { + my ($w, $h, @r, $n) = @_; + + $r[ $_->[1] ][ $_->[0] ] = $n++ for + sort { $a->[0] + $a->[1] <=> $b->[0] + $b->[1] or + ($a->[0] + $a->[1]) % 2 + ? $a->[1] <=> $b->[1] + : $a->[0] <=> $b->[0] + } + map { my $e = $_; + map{ [$e, $_] } 0 .. $w-1 + } 0 .. $h - 1; + @r +} + +print map{ "@$_\n" } zig_zag(3, 5); diff --git a/Task/Zig-zag-matrix/PicoLisp/zig-zag-matrix.l b/Task/Zig-zag-matrix/PicoLisp/zig-zag-matrix.l new file mode 100644 index 0000000000..ff61359067 --- /dev/null +++ b/Task/Zig-zag-matrix/PicoLisp/zig-zag-matrix.l @@ -0,0 +1,20 @@ +(load "@lib/simul.l") + +(de zigzag (N) + (prog1 (grid N N) + (let (D '(north west south east .) E '(north east .) This 'a1) + (for Val (* N N) + (=: val Val) + (setq This + (or + ((cadr D) ((car D) This)) + (prog + (setq D (cddr D)) + ((pop 'E) This) ) + ((pop 'E) This) ) ) ) ) ) ) + +(mapc + '((L) + (for This L (prin (align 3 (: val)))) + (prinl) ) + (zigzag 5) ) diff --git a/Task/Zig-zag-matrix/PostScript/zig-zag-matrix.ps b/Task/Zig-zag-matrix/PostScript/zig-zag-matrix.ps new file mode 100644 index 0000000000..10c185f989 --- /dev/null +++ b/Task/Zig-zag-matrix/PostScript/zig-zag-matrix.ps @@ -0,0 +1,55 @@ +%!PS +%%BoundingBox: 0 0 300 200 +/size 9 def % defines row * column (9*9 -> 81 numbers, + % from 0 to 80) +/itoa { 2 string cvs } bind def +% visual bounding box... +% 0 0 moveto 300 0 lineto 300 200 lineto 0 200 lineto +% closepath stroke +20 150 translate +% it can be easily enhanced to support more columns and +% rows. This limit is put here just to avoid more than 2 +% digits, mainly because of formatting +size size mul 99 le { + /Helvetica findfont 14 scalefont setfont + /ulimit size size mul def + /sizem1 size 1 sub def + % prepare the number list + 0 ulimit 1 sub { dup 1 add } repeat + ulimit array astore + /di -1 def /dj 1 def + /ri 1 def /rj 0 def /pus true def + 0 0 moveto + /i 0 def /j 0 def + { % can be rewritten a lot better :) + 0.8 setgray i 30 mul j 15 mul neg lineto stroke + 0 setgray i 30 mul j 15 mul neg moveto itoa show + i 30 mul j 15 mul neg moveto + pus { + i ri add size ge { + /ri 0 def /rj 1 def + } if + j rj add size ge { + /ri 1 def /rj 0 def + } if + /pus false def + /i i ri add def + /j j rj add def + /ri rj /rj ri def def + } { + i di add dup 0 le + exch sizem1 ge or + j dj add dup 0 le + exch sizem1 ge or + or { + /pus true def + /i i di add def /j j dj add def + /di di neg def /dj dj neg def + } { + /i i di add def /j j dj add def + } ifelse + } ifelse + } forall + stroke showpage +} if +%%EOF diff --git a/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix.psh b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix.psh new file mode 100644 index 0000000000..609cf4fbac --- /dev/null +++ b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix.psh @@ -0,0 +1,39 @@ +function zigzag( [int] $n ) { + $zigzag=New-Object 'Object[,]' $n,$n + $nodd = $n -band 1 + $nm1 = $n - 1 + $i=0; + $j=0; + foreach( $k in 0..( $n * $n - 1 ) ) { + $zigzag[$i,$j] = $k + $iodd = $i -band 1 + $jodd = $j -band 1 + if( ( $j -eq $nm1 ) -and ( $iodd -ne $nodd ) ) { + $i++ + } elseif( ( $i -eq $nm1 ) -and ( $jodd -eq $nodd ) ) { + $j++ + } elseif( ( $i -eq 0 ) -and ( -not $jodd ) ) { + $j++ + } elseif( ( $j -eq 0 ) -and $iodd ) { + $i++ + } elseif( $iodd -eq $jodd ) { + $i-- + $j++ + } else { + $i++ + $j-- + } + } + ,$zigzag +} + +function displayZigZag( [int] $n ) { + $a = zigzag $n + 0..$n | ForEach-Object { + $b=$_ + $pad=($n*$n-1).ToString().Length + "$(0..$n | ForEach-Object { + "{0,$pad}" -f $a[$b,$_] + } )" + } +} diff --git a/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro b/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro new file mode 100644 index 0000000000..2d7f6ad709 --- /dev/null +++ b/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro @@ -0,0 +1,79 @@ +zig_zag(N) :- + zig_zag(N, N). + +% compute zig_zag for a matrix of Lig lines of Col columns +zig_zag(Lig, Col) :- + length(M, Lig), + maplist(init(Col), M), + fill(M, 0, 0, 0, Lig, Col, up), + % display the matrix + maplist(print_line, M). + + +fill(M, Cur, L, C, NL, NC, _) :- + L is NL - 1, + C is NC - 1, + nth0(L, M, Line), + nth0(C, Line, Cur). + +fill(M, Cur, L, C, NL, NC, Sens) :- + nth0(L, M, Line), + nth0(C, Line, Cur), + Cur1 is Cur + 1, + compute_next(NL, NC, L, C, Sens, L1, C1, Sens1), + fill(M, Cur1, L1, C1, NL, NC, Sens1). + + +init(N, L) :- + length(L, N). + +% compute_next +% arg1 : Number of lnes of the matrix +% arg2 : number of columns of the matrix +% arg3 : current line +% arg4 : current column +% arg5 : current direction of movement +% arg6 : nect line +% arg7 : next column +% arg8 : next direction of movement +compute_next(_NL, NC, 0, Col, up, 0, Col1, down) :- + Col < NC - 1, + Col1 is Col+1. + +compute_next(_NL, NC, 0, Col, up, 1, Col, down) :- + Col is NC - 1. + +compute_next(NL, _NC, Lig, 0, down, Lig1, 0, up) :- + Lig < NL - 1, + Lig1 is Lig+1. + +compute_next(NL, _NC, Lig, 0, down, Lig, 1, up) :- + Lig is NL - 1. + +compute_next(NL, _NC, Lig, Col, down, Lig1, Col1, down) :- + Lig < NL - 1, + Lig1 is Lig + 1, + Col1 is Col-1. + +compute_next(NL, _NC, Lig, Col, down, Lig, Col1, up) :- + Lig is NL - 1, + Col1 is Col+1. + +compute_next(_NL, NC, Lig, Col, up, Lig1, Col1, up) :- + Col < NC - 1, + Lig1 is Lig - 1, + Col1 is Col+1. + +compute_next(_NL, NC, Lig, Col, up, Lig1, Col, down) :- + Col is NC - 1, + Lig1 is Lig + 1. + + + + +print_line(L) :- + maplist(print_val, L), + nl. + +print_val(V) :- + writef('%3r ', [V]). diff --git a/Task/Zig-zag-matrix/PureBasic/zig-zag-matrix.purebasic b/Task/Zig-zag-matrix/PureBasic/zig-zag-matrix.purebasic new file mode 100644 index 0000000000..88dd97bbe9 --- /dev/null +++ b/Task/Zig-zag-matrix/PureBasic/zig-zag-matrix.purebasic @@ -0,0 +1,53 @@ +Procedure zigZag(size) + Protected i, v, x, y + + Dim a(size - 1, size - 1) + + x = 1 + y = 1 + For i = 1 To size * size ;loop once for each element + a(x - 1, y - 1) = v ;assign the next index + + If (x + y) & 1 = 0 ;even diagonal (zero based count) + If x < size ;while inside the square + If y > 1 ;move right-up + y - 1 + EndIf + x + 1 + Else + y + 1 ;on the edge increment y, but not x until diagonal is odd + EndIf + Else ;odd diagonal (zero based count) + If y < size ;while inside the square + If x > 1 ;move left-down + x - 1 + EndIf + y + 1 + Else + x + 1 ;on the edge increment x, but not y until diagonal is even + EndIf + EndIf + v + 1 + Next + + + ;generate and show printout + PrintN("Zig-zag matrix of size " + Str(size) + #CRLF$) + maxDigitCount = Len(Str(size * size)) + 1 + For y = 0 To size - 1 + For x = 0 To size - 1 + Print(RSet(Str(a(x, y)), maxDigitCount, " ")) + Next + PrintN("") + Next + PrintN("") +EndProcedure + +If OpenConsole() + zigZag(5) + zigZag(6) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Zig-zag-matrix/Python/zig-zag-matrix-1.py b/Task/Zig-zag-matrix/Python/zig-zag-matrix-1.py new file mode 100644 index 0000000000..c0096fac3f --- /dev/null +++ b/Task/Zig-zag-matrix/Python/zig-zag-matrix-1.py @@ -0,0 +1,13 @@ +def zigzag(n): + indexorder = sorted(((x,y) for x in range(n) for y in range(n)), + key = lambda (x,y): (x+y, -y if (x+y) % 2 else y) ) + return {index: n for n,index in enumerate(indexorder)} + +def printzz(myarray): + n = int(len(myarray)** 0.5 +0.5) + for x in range(n): + for y in range(n): + print "%2i" % myarray[(x,y)], + print + +printzz(zigzag(6)) diff --git a/Task/Zig-zag-matrix/Python/zig-zag-matrix-2.py b/Task/Zig-zag-matrix/Python/zig-zag-matrix-2.py new file mode 100644 index 0000000000..d393f2f499 --- /dev/null +++ b/Task/Zig-zag-matrix/Python/zig-zag-matrix-2.py @@ -0,0 +1,18 @@ +def zigzag(n): + def move(i, j): + if j < (n - 1): + return max(0, i-1), j+1 + else: + return i+1, j + a = [[0] * n for _ in xrange(n)] + x, y = 0, 0 + for v in xrange(n * n): + a[y][x] = v + if (x + y) & 1: + x, y = move(x, y) + else: + y, x = move(y, x) + return a + +from pprint import pprint +pprint(zigzag(5)) diff --git a/Task/Zig-zag-matrix/Python/zig-zag-matrix-3.py b/Task/Zig-zag-matrix/Python/zig-zag-matrix-3.py new file mode 100644 index 0000000000..70d429068f --- /dev/null +++ b/Task/Zig-zag-matrix/Python/zig-zag-matrix-3.py @@ -0,0 +1,5 @@ +[[0, 1, 5, 6, 14], + [2, 4, 7, 13, 15], + [3, 8, 12, 16, 21], + [9, 11, 17, 20, 22], + [10, 18, 19, 23, 24]] diff --git a/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py b/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py new file mode 100644 index 0000000000..375dcf601c --- /dev/null +++ b/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py @@ -0,0 +1,20 @@ +#ZigZag +# +# Nigel Galloway: June 7th., 2012, +# +COLS = 9 +def CX(x, ran): + while True: + x += 2 * next(ran) + yield x + x += 1 + yield x +ran = [] +d = -1 +for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))): + ran.append(iter(range(V, V+COLS*d, d))) + d *= -1 +for x in range(0,COLS): + for y in range(x, x+COLS): + print(repr(next(ran[y])).rjust(3), end = ' ') + print() diff --git a/Task/Zig-zag-matrix/Qi/zig-zag-matrix.qi b/Task/Zig-zag-matrix/Qi/zig-zag-matrix.qi new file mode 100644 index 0000000000..723db8cef2 --- /dev/null +++ b/Task/Zig-zag-matrix/Qi/zig-zag-matrix.qi @@ -0,0 +1,25 @@ +(define odd? A -> (= 1 (MOD A 2))) +(define even? A -> (= 0 (MOD A 2))) + +(define zigzag-val + 0 0 N -> 0 + + X 0 N -> (1+ (zigzag-val (1- X) 0 N)) where (odd? X) + X 0 N -> (1+ (zigzag-val (1- X) 1 N)) + + 0 Y N -> (1+ (zigzag-val 1 (1- Y) N)) where (odd? Y) + 0 Y N -> (1+ (zigzag-val 0 (1- Y) N)) + + X Y N -> (1+ (zigzag-val (MAX 0 (1- X)) (MIN (1- N) (1+ Y)) N)) where (even? (+ X Y)) + X Y N -> (1+ (zigzag-val (MIN (1- N) (1+ X)) (MAX 0 (1- Y)) N))) + +(define range + E E -> [] + S E -> [S|(range (1+ S) E)]) + +(define zigzag + N -> (map (/. Y + (map (/. X + (zigzag-val X Y N)) + (range 0 N))) + (range 0 N))) diff --git a/Task/Zig-zag-matrix/R/zig-zag-matrix.r b/Task/Zig-zag-matrix/R/zig-zag-matrix.r new file mode 100644 index 0000000000..a16a69b253 --- /dev/null +++ b/Task/Zig-zag-matrix/R/zig-zag-matrix.r @@ -0,0 +1,25 @@ +zigzag <- function(size) +{ + digits <- seq_len(size^2) - 1 + mat <- matrix(0, nrow = size, ncol=size) + i <- 1 + j <- 1 + for(element in digits) + { + mat[i,j] <- element + if((i + j) %% 2 == 0) + { + # Even stripes + if(j < size) j <- j + 1 else i <- i + 2 + if(i > 1) i <- i - 1 + } else + { + # Odd stripes + if(i < size) i <- i + 1 else j <- j + 2 + if(j > 1) j <- j - 1 + } + } + mat +} + +zigzag(5) diff --git a/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx b/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx new file mode 100644 index 0000000000..f2accafc92 --- /dev/null +++ b/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx @@ -0,0 +1,28 @@ +/*REXX program to produce a zig-zag matrix (array) and display it. */ + +parse arg n start inc . /*get any and/or all arguments. */ +if n=='' then n=5 /*if not specified, use default. */ +if start=='' then start=0 /* " " " " " */ +if inc=='' then inc=1 /* " " " " " */ +row=1; col=1 /*start with 1st row, 1st column.*/ + + do j=start by inc for n*n; @.row.col=j + if (row+col)//2==0 then do + if col| x <- [0..n], y <- [0..n]], + bool (cd a, cd b){ + if (a[0]+a[1] > b[0]+b[1]) + return false; + elseif(a[0] < b[0]) + return false; + else + return true; + ; + }); + return { | z <- index(indexorder)}; +} + +public void printzz(rel[cd, int] myarray){ + n = floor(sqrt(size(myarray))); + for (x <- [0..n-1]){ + for (y <- [0..n-1]){ + print("]>\t");} + println();} +} diff --git a/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-4.rascal b/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-4.rascal new file mode 100644 index 0000000000..f43ebbc0c8 --- /dev/null +++ b/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-4.rascal @@ -0,0 +1,7 @@ +rascal>printzz(zz(4)) +{0} {1} {3} {6} {10} +{2} {4} {7} {11} {15} +{5} {8} {12} {16} {19} +{9} {13} {17} {20} {22} +{14} {18} {21} {23} {24} +ok diff --git a/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb b/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb new file mode 100644 index 0000000000..50635bd620 --- /dev/null +++ b/Task/Zig-zag-matrix/Ruby/zig-zag-matrix.rb @@ -0,0 +1,15 @@ +def zigzag(n) + indices = [] + n.times {|x| n.times {|y| indices << [x,y] }} + zigzag = Array.new(n) {Array.new(n)} # n x n array of nils + indices.sort_by {|x,y| [x+y, (x+y).even? ? y : -y]} \ + .each_with_index {|(x,y),i| zigzag[x][y] = i} + zigzag +end + +def print_matrix(m) + width = m.flatten.max.to_s.size + m.each {|row| row.each {|val| print "%#{width}d " % val}; puts} +end + +print_matrix zigzag(5) diff --git a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala new file mode 100644 index 0000000000..7e5d1c0c25 --- /dev/null +++ b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-1.scala @@ -0,0 +1,10 @@ +def zigzag(n:int) = { + var l = List[Tuple2[int,int]]() + (0 until n*n) foreach {i=>l = l + (i%n,i/n)} + l = l.sort{case ((x,y),(u,v)) => if (x+y == u+v) + if ((x+y) % 2 == 0) x a(y)(x) = i} + a +} diff --git a/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala new file mode 100644 index 0000000000..b087b071d6 --- /dev/null +++ b/Task/Zig-zag-matrix/Scala/zig-zag-matrix-2.scala @@ -0,0 +1,10 @@ +def zigzag(n:int) = { + var indices = List[Tuple2[Int,Int]]() + var array = new Array[Array[Int]](n,n) + + (0 until n*n).foldLeft(indices)((l,i) => l + (i%n,i/n)). + sort{case ((x,y),(u,v)) => if (x+y == u+v) + if ((x+y) % 2 == 0) x a(y)(x) = i; a} +} diff --git a/Task/Zig-zag-matrix/Seed7/zig-zag-matrix.seed7 b/Task/Zig-zag-matrix/Seed7/zig-zag-matrix.seed7 new file mode 100644 index 0000000000..826f89de29 --- /dev/null +++ b/Task/Zig-zag-matrix/Seed7/zig-zag-matrix.seed7 @@ -0,0 +1,45 @@ +$ include "seed7_05.s7i"; + +const type: matrix is array array integer; + +const func matrix: zigzag (in integer: size) is func + result + var matrix: s is matrix.value; + local + var integer: i is 1; + var integer: j is 1; + var integer: d is -1; + var integer: max is 0; + var integer: n is 0; + begin + s := size times size times 0; + max := size ** 2; + for n range 1 to max div 2 + 1 do + s[i][j] := n; + s[size - i + 1][size - j + 1] := max - n + 1; + i +:= d; + j -:= d; + if i < 1 then + incr(i); + d := -d; + elsif j < 1 then + incr(j); + d := -d; + end if; + end for; + end func; + +const proc: main is func + local + var matrix: s is matrix.value; + var integer: i is 0; + var integer: num is 0; + begin + s := zigzag(7); + for i range 1 to length(s) do + for num range s[i] do + write(num lpad 4); + end for; + writeln; + end for; + end func; diff --git a/Task/Zig-zag-matrix/Tcl/zig-zag-matrix.tcl b/Task/Zig-zag-matrix/Tcl/zig-zag-matrix.tcl new file mode 100644 index 0000000000..6e1b4eb789 --- /dev/null +++ b/Task/Zig-zag-matrix/Tcl/zig-zag-matrix.tcl @@ -0,0 +1,36 @@ +proc zigzag {size} { + set m [lrepeat $size [lrepeat $size .]] + set x 0; set dx -1 + set y 0; set dy 1 + + for {set i 0} {$i < $size ** 2} {incr i} { + if {$x >= $size} { + incr x -1 + incr y 2 + negate dx dy + } elseif {$y >= $size} { + incr x 2 + incr y -1 + negate dx dy + } elseif {$x < 0 && $y >= 0} { + incr x + negate dx dy + } elseif {$x >= 0 && $y < 0} { + incr y + negate dx dy + } + lset m $x $y $i + incr x $dx + incr y $dy + } + return $m +} + +proc negate {args} { + foreach varname $args { + upvar 1 $varname var + set var [expr {-1 * $var}] + } +} + +print_matrix [zigzag 5] diff --git a/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-1.ursala b/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-1.ursala new file mode 100644 index 0000000000..f28d8d399d --- /dev/null +++ b/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-1.ursala @@ -0,0 +1,4 @@ +#import std +#import nat + +zigzag = ~&mlPK2xnSS+ num+ ==+sum~~|=xK9xSL@iiK0+ iota diff --git a/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-2.ursala b/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-2.ursala new file mode 100644 index 0000000000..a3b56d188d --- /dev/null +++ b/Task/Zig-zag-matrix/Ursala/zig-zag-matrix-2.ursala @@ -0,0 +1,3 @@ +#cast %nLLL + +tests = zigzag* <4,5,6> diff --git a/Task/Zig-zag-matrix/VBA/zig-zag-matrix.vba b/Task/Zig-zag-matrix/VBA/zig-zag-matrix.vba new file mode 100644 index 0000000000..1e0852bd47 --- /dev/null +++ b/Task/Zig-zag-matrix/VBA/zig-zag-matrix.vba @@ -0,0 +1,59 @@ +Public Sub zigzag(n) +Dim a() As Integer +'populate a (1,1) to a(n,n) in zigzag pattern + +'check if n too small +If n < 1 Then + Debug.Print "zigzag: enter a number greater than 1" + Exit Sub +End If + +'initialize +ReDim a(1 To n, 1 To n) +i = 1 'i is the row +j = 1 'j is the column +P = 0 'P is the next number +a(i, j) = P 'fill in initial value + +'now zigzag through the matrix and fill it in +Do While (i <= n) And (j <= n) + 'move one position to the right or down the rightmost column, if possible + If j < n Then + j = j + 1 + ElseIf i < n Then + i = i + 1 + Else + Exit Do + End If + 'fill in + P = P + 1: a(i, j) = P + 'move down to the left + While (j > 1) And (i < n) + i = i + 1: j = j - 1 + P = P + 1: a(i, j) = P + Wend + 'move one position down or to the right in the bottom row, if possible + If i < n Then + i = i + 1 + ElseIf j < n Then + j = j + 1 + Else + Exit Do + End If + P = P + 1: a(i, j) = P + 'move back up to the right + While (i > 1) And (j < n) + i = i - 1: j = j + 1 + P = P + 1: a(i, j) = P + Wend +Loop + +'print result +Debug.Print "Result for n="; n; ":" +For i = 1 To n + For j = 1 To n + Debug.Print a(i, j), + Next + Debug.Print +Next +End Sub diff --git a/Task/Zig-zag-matrix/XPL0/zig-zag-matrix.xpl0 b/Task/Zig-zag-matrix/XPL0/zig-zag-matrix.xpl0 new file mode 100644 index 0000000000..b5a52062c5 --- /dev/null +++ b/Task/Zig-zag-matrix/XPL0/zig-zag-matrix.xpl0 @@ -0,0 +1,23 @@ +include c:\cxpl\codes; +def N=6; +int A(N,N), X, Y, I, D; +[I:=0; X:=0; Y:=0; D:=1; +repeat A(X,Y):=I; + case of + X+D>=N: [D:=-D; Y:=Y+1]; + Y-D>=N: [D:=-D; X:=X+1]; + X+D<0: [D:=-D; Y:=Y+1]; + Y-D<0: [D:=-D; X:=X+1] + other [X:=X+D; Y:=Y-D]; + I:=I+1; +until I>=N*N; +for Y:=0 to N-1 do + [for X:=0 to N-1 do + [I:=A(X,Y); + ChOut(0,^ ); + if I<10 then ChOut(0,^ ); + IntOut(0, I); + ]; + CrLf(0); + ]; +]